diff --git a/.cargo/config.toml b/.cargo/config.toml index 0075377e21..9741f113e7 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,6 +1,2 @@ [alias] xtask = "run --quiet --package xtask --" - -[target.x86_64-pc-windows-gnullvm] -# Link LLVM-MinGW's unwinder into the executable for a clean Proton prefix. -rustflags = ["-C", "target-feature=+crt-static"] diff --git a/.gitattributes b/.gitattributes index e06f16ef00..39588b1ab2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,4 @@ * text=auto eol=lf *.cmd text eol=crlf *.ps1 text eol=crlf +*.gif binary diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index b6c4936d7b..0000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,104 +0,0 @@ -name: Bug report -description: VIctory crashes, stops, or does not do what the console does. -labels: [bug] -body: - - type: markdown - attributes: - value: | - One problem in each report. Search the open issues first: if your crash has the same address (for example `+0x4e8aa70`), add a comment there. - - Do not attach game files, dumps, extracted data or screenshots of the game. Text logs from VIctory are permitted. See `docs/asset-policy.md`. - - - type: input - id: commit - attributes: - label: VIctory commit - description: Output of `git rev-parse --short HEAD`. - placeholder: 015d45b - validations: - required: true - - - type: dropdown - id: profile - attributes: - label: Build - options: - - release - - diag (with the diagnostics feature) - - debug - validations: - required: true - - - type: input - id: title-build - attributes: - label: Game build - description: The `build` line that `victory run` prints, and the package version. - placeholder: "build unknown (b99f876b…), package 1.0.2.1" - validations: - required: true - - - type: input - id: cpu - attributes: - label: CPU - description: The full model. Some console instructions are on AMD CPUs only. - placeholder: AMD Ryzen 7 5800X - validations: - required: true - - - type: input - id: gpu - attributes: - label: GPU and driver version - placeholder: AMD RX 6700 XT, Adrenalin 25.9.1 - validations: - required: true - - - type: input - id: os - attributes: - label: Operating system - description: Windows version and build number, or Wine/Proton version and distribution. - placeholder: Windows 11 24H2 (26100.4061) - validations: - required: true - - - type: textarea - id: steps - attributes: - label: What you did - description: The command you ran, environment variables you set, and the steps in the game. - render: text - validations: - required: true - - - type: textarea - id: result - attributes: - label: What happened - description: What you saw, and what you expected. - validations: - required: true - - - type: textarea - id: log - attributes: - label: Log - description: | - The crash report from `crashes.log` (in the data folder, default `%LOCALAPPDATA%\victory\data`) or the last 50 lines of console output. - render: text - validations: - required: true - - - type: checkboxes - id: confirm - attributes: - label: Confirm - options: - - label: I searched the issues and found no report of this problem. - required: true - - label: My game files come from a copy of the game that I own. - required: true - - label: This report does not include game files or data taken from them. - required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 3ba13e0cec..0000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1 +0,0 @@ -blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml deleted file mode 100644 index 4dc97e2f00..0000000000 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Feature request -description: A function that VIctory does not have. -labels: [enhancement] -body: - - type: markdown - attributes: - value: | - Read the status table in the README first. Work that it lists under "Needs" is known and does not need a request. - - - type: textarea - id: request - attributes: - label: Request - description: What VIctory must do, and which hardware or users it helps. - validations: - required: true - - - type: textarea - id: approach - attributes: - label: Possible approach - description: How it can be done, if you know. Give links to sources and their licences. - - - type: checkboxes - id: confirm - attributes: - label: Confirm - options: - - label: I searched the issues and the README, and found no request for this. - required: true diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 5d4cd8d5cc..0000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,21 +0,0 @@ -version: 2 -updates: - - package-ecosystem: "cargo" - directory: "/" - schedule: - interval: "weekly" - open-pull-requests-limit: 10 - groups: - dependencies: - patterns: - - "*" - - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "weekly" - open-pull-requests-limit: 5 - groups: - actions: - patterns: - - "*" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index 1a97bdb320..0000000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,13 +0,0 @@ -## What - - - -## Tested - - - -## Checklist - -- [ ] `cargo fmt`, `cargo clippy --workspace --all-targets` and `cargo test --workspace` pass. -- [ ] `cargo xtask policy` passes. The change adds no game files or data taken from them (`docs/asset-policy.md`). -- [ ] If an AI tool wrote part of this change, the description says so. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000..e31244deeb --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,64 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + +jobs: + check: + runs-on: windows-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v5 + # The version and components pinned in rust-toolchain.toml. + - run: rustup toolchain install + - uses: Swatinem/rust-cache@v2 + # The launcher runs on the users' Windows PowerShell 5.1: it must parse there. + - name: Try script parses + shell: powershell + run: | + $errors = $null + $null = [System.Management.Automation.Language.Parser]::ParseFile("$PWD\scripts\try\try.ps1", [ref]$null, [ref]$errors) + if ($errors) { $errors | ForEach-Object { Write-Output "::error::try.ps1 line $($_.Extent.StartLineNumber): $($_.Message)" }; exit 1 } + Write-Output 'try.ps1 parses' + - name: Clippy + shell: pwsh + run: | + cargo clippy --workspace --all-targets --locked --message-format=short -- -D warnings 2>&1 | Tee-Object -FilePath "$env:RUNNER_TEMP\clippy.txt" + $code = $LASTEXITCODE + $hits = @(Select-String -CaseSensitive -Path "$env:RUNNER_TEMP\clippy.txt" -Pattern ': (error|warning)|^error' | Select-Object -First 60 | ForEach-Object { $_.Line.Trim() }) + if ($code -ne 0 -and $hits.Count -gt 0) { Write-Output ("::error::" + ($hits -join ' %0A ')) } + exit $code + - name: Clippy, diagnostics build + shell: pwsh + run: | + cargo clippy --workspace --all-targets --all-features --locked --message-format=short -- -D warnings 2>&1 | Tee-Object -FilePath "$env:RUNNER_TEMP\clippy.txt" + $code = $LASTEXITCODE + $hits = @(Select-String -CaseSensitive -Path "$env:RUNNER_TEMP\clippy.txt" -Pattern ': (error|warning)|^error' | Select-Object -First 60 | ForEach-Object { $_.Line.Trim() }) + if ($code -ne 0 -and $hits.Count -gt 0) { Write-Output ("::error::" + ($hits -join ' %0A ')) } + exit $code + # Includes xtask's repository_passes_policy, the asset-policy check. + # (The step outputs go to the runner's temp folder: inside the checkout + # the policy check saw them as files of the repository.) + - name: Tests + shell: pwsh + run: | + cargo test --workspace --locked --no-fail-fast 2>&1 | Tee-Object -FilePath "$env:RUNNER_TEMP\test-output.txt" + $code = $LASTEXITCODE + # Failing tests and panics as annotations (readable through the API). + # (case-sensitive, and all in one: a step shows at most 10 annotations) + $hits = @(Select-String -CaseSensitive -Path "$env:RUNNER_TEMP\test-output.txt" -Pattern ' FAILED|panicked|^error|could not compile|STATUS_|^---- |left: |right: |POLICY: ' | + Select-Object -First 80 | ForEach-Object { $_.Line.Trim() }) + if ($hits.Count -gt 0) { Write-Output ("::error::" + ($hits -join ' %0A ')) } + exit $code diff --git a/.github/workflows/discord.yml b/.github/workflows/discord.yml new file mode 100644 index 0000000000..54dde7de8a --- /dev/null +++ b/.github/workflows/discord.yml @@ -0,0 +1,51 @@ +name: Release notice + +# Posts scripts/try/RELEASE.md (the Try version and its fixes, short) to +# the project's Discord channel when a push changes the version there. +# The webhook is the repository secret DISCORD_WEBHOOK when there is one, +# else the one the owner gave (kept here encoded, so link scanners do not +# pick it up; it is readable by anyone who decodes it: replace it with the +# secret to keep it private). + +on: + push: + branches: [arena/59fabb00-victory] + paths: [scripts/try/RELEASE.md] + workflow_dispatch: + +permissions: + contents: read + +jobs: + notify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 2 + - name: Post to Discord + env: + SECRET_HOOK: ${{ secrets.DISCORD_WEBHOOK }} + MANUAL: ${{ github.event_name == 'workflow_dispatch' }} + # The owner's (sks_a) Discord user ID: the post pings them. A + # DISCORD_USER_ID repository variable replaces it. + MENTION_ID: ${{ vars.DISCORD_USER_ID || '1515414575653060721' }} + run: | + hook="$SECRET_HOOK" + if [ -z "$hook" ]; then + hook=$(printf '%s' 'QmIwclBjVkNXX3pTN3JMZ2t6LXhZanZta2NDc05iLS0wVmtKMUxXcjFPLWpQMm9YejE5SkJhQUtlODBxRHVVYzVzNVEvNDc2NjI2MTA0OTY1Nzg1ODE1MS9za29vaGJldy9pcGEvbW9jLmRyb2NzaWQvLzpzcHR0aA==' | base64 -d | rev) + fi + now=$(head -n 1 scripts/try/RELEASE.md) + before=$(git show HEAD~1:scripts/try/RELEASE.md 2>/dev/null | head -n 1 || true) + if [ "$now" = "$before" ] && [ "$MANUAL" != "true" ]; then + echo "Same version as before ($now): nothing posted" + exit 0 + fi + mention='@sks_a' + case "$MENTION_ID" in ''|*[!0-9]*) ;; *) mention="<@$MENTION_ID>";; esac + text=$(printf '%s **%s**\n%s' "$mention" "$now" "$(tail -n +2 scripts/try/RELEASE.md | head -c $((1900 - ${#now})))") + jq -n --arg c "$text" '{username: "VIctory Try", content: $c, allowed_mentions: {parse: ["users"]}}' > body.json + code=$(curl -sS -o reply.txt -w '%{http_code}' -H 'Content-Type: application/json' -d @body.json "$hook") + echo "Discord answered $code" + cat reply.txt || true + case "$code" in 2*) echo "::notice title=Discord::posted $now";; *) echo "::error title=Discord::answer $code"; exit 1;; esac diff --git a/.github/workflows/engine-avm.yml b/.github/workflows/engine-avm.yml new file mode 100644 index 0000000000..17aea8e17b --- /dev/null +++ b/.github/workflows/engine-avm.yml @@ -0,0 +1,52 @@ +name: AvatarManz engine builds + +# VIctory Try 6.9 builds the AvatarManz engine on the user's PC (the default +# engine, N in its menu): Belobug/VIctory-Belobug-AMD's a-publier branch, +# which is avatarmanz/VIctory-7900XTX c9c932c plus Belobug's three commits +# (flicker fix, VRAM-aware texture cap, FSR 4.1.2). avatarmanz main is checked +# too (VICTORY_TRY_AVM=avatarmanz picks it). Neither has Windows CI of its own +# that this fork can see: this checks that the newest of both compiles with the +# exact command VIctory Try runs, before players press U. +on: + push: + paths: + - 'scripts/try/**' + - '.github/workflows/engine-avm.yml' + workflow_dispatch: + schedule: + - cron: '30 */6 * * *' + +permissions: + contents: read + +jobs: + check: + runs-on: windows-latest + timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + include: + - repo: Belobug/VIctory-Belobug-AMD + ref: a-publier + - repo: avatarmanz/VIctory-7900XTX + ref: main + steps: + - uses: actions/checkout@v5 + with: + repository: ${{ matrix.repo }} + ref: ${{ matrix.ref }} + - run: rustup toolchain install + - uses: Swatinem/rust-cache@v2 + - name: cargo check (diag profile, diagnostics, as VIctory Try builds it) + shell: pwsh + run: | + git log -1 --format='engine %h %ad %s' --date=short + cargo check --locked --profile diag -p victory --features diagnostics --message-format=short 2>&1 | Tee-Object -FilePath check.txt + $code = $LASTEXITCODE + $hits = @(Select-String -CaseSensitive -Path check.txt -Pattern '^error|: error' | Select-Object -First 40 | ForEach-Object { $_.Line.Trim() }) + if ($code -ne 0 -and $hits.Count -gt 0) { Write-Output ("::error::" + ($hits -join ' %0A ')) } + $head = (git log -1 --format='%h %ad %s' --date=short) + $fin = @(Select-String -Path check.txt -Pattern 'Finished|Checking victory ' | Select-Object -Last 2 | ForEach-Object { $_.Line.Trim() }) + Write-Output ("::notice::${{ matrix.repo }} $head (exit $code): " + ($fin -join ' / ')) + exit $code diff --git a/.github/workflows/engine8.yml b/.github/workflows/engine8.yml new file mode 100644 index 0000000000..d2c8be2a09 --- /dev/null +++ b/.github/workflows/engine8.yml @@ -0,0 +1,37 @@ +name: 8 GB engine builds + +# VIctory Try 5.9 builds soldsawn/victory-nvidia-8gb on the user's PC (N in +# its menu). That repository has no CI of its own: this checks that its +# newest main compiles on Windows before players press U. +on: + push: + paths: + - 'scripts/try/**' + - '.github/workflows/engine8.yml' + workflow_dispatch: + schedule: + - cron: '0 */6 * * *' + +permissions: + contents: read + +jobs: + check: + runs-on: windows-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v5 + with: + repository: soldsawn/victory-nvidia-8gb + ref: main + - run: rustup toolchain install + - uses: Swatinem/rust-cache@v2 + - name: cargo check -p victory (release) + shell: pwsh + run: | + git log -1 --format='engine %h %ad %s' --date=short + cargo check --release -p victory --message-format=short 2>&1 | Tee-Object -FilePath check.txt + $code = $LASTEXITCODE + $hits = @(Select-String -CaseSensitive -Path check.txt -Pattern '^error|: error' | Select-Object -First 40 | ForEach-Object { $_.Line.Trim() }) + if ($code -ne 0 -and $hits.Count -gt 0) { Write-Output ("::error::" + ($hits -join ' %0A ')) } + exit $code diff --git a/.github/workflows/fmt.yml b/.github/workflows/fmt.yml deleted file mode 100644 index dd36b48a30..0000000000 --- a/.github/workflows/fmt.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: Format - -on: - push: - branches: [main] - pull_request: - -permissions: - contents: read - -jobs: - rustfmt: - # rustfmt does not compile code, so a Linux runner can check the - # Windows-only crates. - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v5 - with: - persist-credentials: false - # Installs the toolchain that rust-toolchain.toml gives, with its - # components, so CI uses the same rustfmt as local builds. - - name: Install the toolchain - run: rustup toolchain install - - name: Check the formatting - run: cargo fmt --all -- --check diff --git a/.github/workflows/policy.yml b/.github/workflows/policy.yml deleted file mode 100644 index dabd091f42..0000000000 --- a/.github/workflows/policy.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Asset Policy & Format - -on: - push: - branches: [main] - pull_request: - branches: [main] - -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -jobs: - policy-and-format: - name: Asset Policy and Code Style - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@stable - with: - toolchain: 1.98.1 - components: rustfmt - - - name: Verify Asset Policy (Rule #1) - run: cargo xtask policy - - - name: Verify Code Formatting - run: cargo fmt --all -- --check diff --git a/.github/workflows/pr-description.yml b/.github/workflows/pr-description.yml deleted file mode 100644 index 843dccc364..0000000000 --- a/.github/workflows/pr-description.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: PR description - -on: - pull_request: - types: [opened, edited, reopened, synchronize] - -permissions: {} - -jobs: - check: - runs-on: ubuntu-latest - steps: - # The body comes from the event file, not from an expression in the - # script, so text in the body cannot run as a command. - - name: Check the template sections - run: | - jq -r '.pull_request.body // ""' "$GITHUB_EVENT_PATH" \ - | tr -d '\r' \ - | perl -0pe 's///gs' > body.md - fail=0 - for section in What Tested; do - text=$(awk -v s="$section" ' - $0 ~ "^## " s "[[:space:]]*$" { on = 1; next } - /^## / { on = 0 } - on' body.md | tr -d '[:space:]') - if [ -z "$text" ]; then - echo "::error::The PR description has no text under \"## $section\". Use the template in .github/pull_request_template.md." - fail=1 - fi - done - exit $fail diff --git a/.github/workflows/probe.yml b/.github/workflows/probe.yml new file mode 100644 index 0000000000..8da60a9248 --- /dev/null +++ b/.github/workflows/probe.yml @@ -0,0 +1,110 @@ +name: Shader probe + +# Translates the shaders the user's latest reports name as failing +# (failed-shaders in the report zips on main) as the user's RTX 4060 does +# (32-lane waves), with each wave switch, and prints why each stops. +# Runs when scripts/try/probe.txt changes; the report names are in it. +# (`translate --list` calls emit::emit: the pixel first-half retries of +# emit::translate are not in it, so those three fail here only.) +# (5.1: the last resort splits console waves around LDS too.) + +on: + push: + branches: [arena/59fabb00-victory] + paths: [scripts/try/probe.txt, .github/workflows/probe.yml] + +permissions: + contents: read + +jobs: + probe: + strategy: + fail-fast: false + matrix: + os: [windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 90 + steps: + - uses: actions/checkout@v5 + - run: rustup toolchain install + - uses: Swatinem/rust-cache@v2 + with: + shared-key: probe + - name: Build + shell: bash + run: cargo build --release -p victory + - name: Reports + shell: bash + run: | + git fetch -q --depth=1 origin main + mkdir -p probe + while IFS= read -r name; do + [ -z "$name" ] && continue + case "$name" in \#*) continue;; esac + git show "origin/main:$name" > probe/r.zip + (cd probe && unzip -qo r.zip -x '*.log' '*.txt' || true) + rm -f probe/r.zip + done < scripts/try/probe.txt + mkdir -p shaders + find probe -iname '*.dxbc' -exec cp {} shaders/ \; + # (zips made on Windows keep "failed-shaders\name" as one name) + for f in probe/*; do case "$f" in *.dxbc) cp "$f" "shaders/$(basename "${f##*\\}")";; esac; done + ls -la shaders + - name: Translate + shell: bash + env: + VICTORY_HOST_WAVE: "32" + VICTORY_WAVE_WHY: "1" + VICTORY_SHADER_LOOP_LIMIT: "256" + run: | + exe=target/release/victory + out=probe-out.txt + : > $out + for mode in default; do + for f in shaders/*; do + echo "---- $(basename "$f") WAVE_WIDE=$mode" >> $out + if [ "$mode" = default ]; then + "$exe" translate --list --jobs 1 "$f" > one.txt 2>&1 || true + else + VICTORY_WAVE_WIDE=$mode "$exe" translate --list --jobs 1 "$f" > one.txt 2>&1 || true + fi + { grep -a "WAVE64" one.txt | head -n 24; tail -n 22 one.txt; } >> $out || true + done + done + cat $out + - name: Instructions around where each failing shader stops + if: always() + shell: bash + run: | + exe=target/release/victory + out=disasm-out.txt + : > $out + for pair in compute-7f05ddab771799a9:89ec; do + name=${pair%%:*}; off=${pair##*:} + f=$(ls shaders/$name*.dxbc 2>/dev/null | head -n 1) + [ -n "$f" ] || continue + "$exe" shader-info --disasm "$f" > d.txt 2>&1 || true + if [ "$off" = x ]; then + "$exe" translate --list --jobs 1 "$f" > one.txt 2>&1 || true + off=$(grep -aoE "at 0x[0-9a-f]+" one.txt | tail -n 1 | sed 's/at 0x//') + fi + echo "==== $name @$off" >> $out + grep -aiE -B 40 -A 4 "^ *0*${off}: " d.txt | cut -c1-100 | head -n 46 >> $out || true + done + cat $out + - name: Results as annotations (the log host is not reachable from where they are read) + if: always() + shell: python + run: | + import os + t = "" + if os.path.exists("disasm-out.txt"): + t += open("disasm-out.txt", encoding="utf-8", errors="replace").read() + t += "\n#### translate\n" + lines = [l for l in open("probe-out.txt", encoding="utf-8", errors="replace").read().splitlines() + if l.startswith("----") or "WAVE64" in l or " emit: " in l or "translated of" in l] + t += "\n".join(lines) + chunks = [t[i:i + 3900] for i in range(0, len(t), 3900)][:10] + for n, c in enumerate(chunks): + c = c.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + print(f"::notice title=probe {n}::{c}") diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml deleted file mode 100644 index 34def1801a..0000000000 --- a/.github/workflows/test.yml +++ /dev/null @@ -1,47 +0,0 @@ -name: CI Test -on: - workflow_dispatch: - push: - branches: - - main - pull_request: - -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -permissions: - contents: read - -jobs: - lint: - timeout-minutes: 15 - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #7.0.1 - - uses: actions-rust-lang/setup-rust-toolchain@a188e68d0fd2bd36ad51dccb2b07ba6e75105f30 #2.0.1 - with: - components: rustfmt, clippy - - - name: fmt - run: cargo fmt --all -- --check - - - name: Check policy - run: cargo xtask policy - - - name: Clippy - run: cargo clippy --workspace --all-targets --locked -- -D warnings - - test: - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, windows-latest] - runs-on: ${{ matrix.os }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #7.0.1 - - uses: actions-rust-lang/setup-rust-toolchain@a188e68d0fd2bd36ad51dccb2b07ba6e75105f30 #2.0.1 - - - name: test - run: cargo test --workspace --locked \ No newline at end of file diff --git a/.github/workflows/tryexe.yml b/.github/workflows/tryexe.yml new file mode 100644 index 0000000000..f7bd8059a8 --- /dev/null +++ b/.github/workflows/tryexe.yml @@ -0,0 +1,32 @@ +name: VIctoryTry.exe + +# Builds VIctoryTry.exe (scripts/try/build-exe.sh) from the newest try.ps1 and +# puts it on the v1 release, so a download is never an old version (an exe +# holds the try.ps1 it was built with). Runs when try.ps1 changes. + +on: + push: + branches: [arena/59fabb00-victory] + paths: [scripts/try/try.ps1, scripts/try/build-exe.sh, .github/workflows/tryexe.yml] + workflow_dispatch: + +permissions: + contents: write + +jobs: + exe: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - name: Build + run: | + python3 -m venv /tmp/venv + /tmp/venv/bin/pip install --quiet ziglang + if ! bash scripts/try/build-exe.sh "$PWD/out" > b.log 2>&1; then + echo "::error title=build::$(tail -c 3000 b.log | tr '\n\r%' ' ')" + exit 1 + fi + - name: Put it on the v1 release + env: + GH_TOKEN: ${{ github.token }} + run: gh release upload v1 out/VIctoryTry.exe --clobber -R "$GITHUB_REPOSITORY" diff --git a/.gitignore b/.gitignore index b86f168837..ac9edc3adc 100644 --- a/.gitignore +++ b/.gitignore @@ -25,13 +25,6 @@ /cache/ /out/ -# Shader caches Wine/Proton (vkd3d-proton, DXVK) write into the working -# directory when VIctory runs from the repo. Derived data; never commit. -vkd3d-proton.cache -vkd3d-proton.cache.write -vkd3d_shader_cache/ -*.dxvk-cache - # Executables, libraries, symbols *.exe *.dll diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index 9c3c682c74..0000000000 --- a/AGENTS.md +++ /dev/null @@ -1,15 +0,0 @@ -# AGENTS.md - -## Agent skills - -### Issue tracker - -Issues live in GitHub Issues for JMAN730/victory, managed with the `gh` CLI. See `docs/agents/issue-tracker.md`. - -### Triage labels - -Default five-role vocabulary: `needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`. See `docs/agents/triage-labels.md`. - -### Domain docs - -Single-context: one `GLOSSARY.md` and `docs/adr/` at the repo root. See `docs/agents/domain.md`. diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index d5ff5786f4..0000000000 --- a/CLAUDE.md +++ /dev/null @@ -1,108 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## What this is - -VIctory runs an Xbox Series X|S title (Grand Theft Auto VI) natively on Windows. The console -executable is x86-64 PE32+ built for Zen 2, so its machine code runs **unchanged inside our -process**; VIctory supplies the platform underneath (system APIs, D3D12.X → host D3D12, console -GPU shaders → DXIL) and converts the title's data. See `README.md` for current status and -`docs/architecture.md` for the full picture. - -## Rule #1: the asset policy (read `docs/asset-policy.md`) - -Nothing from the game (or any other proprietary title) may ever enter the repo, in any form: -assets, executable bytes/strings/tables, disassembly, shader dumps, screenshots, snapshots, or -anything derived from them. Allowed: our own format code, build identities (BLAKE3, CodeView -GUID/age), per-build hook offsets under our own names, byte-pattern signatures, small -interop constants we write, and synthetic test data generated by our code. - -- `cargo xtask policy` (pre-commit hook) is an allowlist: allowed file types, < 512 KiB, no - binary data/signatures, no long hex/base64 runs. Exceptions live in `xtask/src/policy.rs` - with a reason. The only binary exception is `crates/victory-formats/src/bcpack-tables.bin`. -- Code that writes derived data must call `victory_core::ensure_outside_repo` (the - `.victory-root` marker defines the tree it refuses to write into). -- Tests needing real files read paths from env vars and **skip when unset**; they assert on - properties, never snapshots. - -## Commands - -Toolchain is pinned in `rust-toolchain.toml` (target `x86_64-pc-windows-msvc`). Much of the -loader/HLE/GPU code is `#[cfg(windows)]`; running the title requires Windows. - -```powershell -cargo xtask install-hooks # sets core.hooksPath=.githooks (runs `cargo xtask policy --staged`) -cargo xtask policy # asset-policy check over the tree -cargo test --workspace # needs no game data -cargo test -p victory-shader # single crate / test filter -cargo clippy --workspace --all-targets -cargo fmt --all # max_width = 100 -cargo run -p victory -- config # check configured paths (victory.toml, git-ignored) -cargo build --release -p victory -target\release\victory.exe run \ --execute -cargo build --profile diag -p victory --features diagnostics # target\diag\victory.exe, debugging aids -``` - -Other CLI subcommands (`inspect`, `census`, `lib-exports`, `shader-info`, `translate`) are listed -in `README.md`; `victory translate [--validate]` runs shaders through the translator and reports -what it can't handle yet. `victory census` shows import classification without running anything. - -Config: copy `victory.example.toml` → `victory.toml`; all paths must be outside the repo. Env vars -(`VICTORY_GAME_DIR`, `VICTORY_CACHE_DIR`, `VICTORY_DATA_DIR`, `VICTORY_TEST_TITLES`, -`VICTORY_CONFIG`) override it. Logging: `VICTORY_LOG=victory_loader=trace,info`. Debug env -switches (`VICTORY_D3D12_DEBUG`, `VICTORY_D3D12_WARP`, `VICTORY_CAPTURE`, …) only work in the -`diagnostics` build — see the table in `README.md`. Crashes and GPU failures go to `crashes.log` -in the data folder. - -`tests/fixtures/hle-probe` is a standalone crate (excluded from the workspace) acting as a -stand-in "title"; `crates/victory-loader/tests/load_probe.rs` builds it into `target/fixtures` -and runs the full prepare/load/bind path on Windows. - -## Architecture - -Crate flow: game assets → `victory-pipeline` + `victory-game` (using `victory-formats`, -`victory-shader`) → `cache_dir`; game executable → `victory-loader` → native title code → -imports into `victory-hle` → D3D12.X into `victory-gpu` → host D3D12, with shaders translated by -`victory-shader` at pipeline creation. Everything except `victory-game` is platform-level and -testable with any Xbox Series title; GTA VI–specific code (formats, build identities, hooks) -belongs only in `victory-game`. - -**Loader** (`victory-loader`): patches a copy of the image to look like a DLL (no entry point, -no import directory, TLS callbacks detached) so the Windows loader maps/relocates it and -registers unwind tables without running code; maps title-shipped DLLs the same way; binds every -import itself; then runs TLS callbacks and entry points. Static TLS slot 0 loads are redirected -(`tls.rs`); `crash.rs` reports faults as `module+rva`. - -**Import resolution** for each `dll!function`, in order: -1. our implementation in `victory-hle::modules` (always wins); -2. the host function, if `HostPolicy` allows that DLL; -3. an export of a DLL shipped beside the title; -4. a generated stub naming the import (`--unimplemented trap|zero`). - -`LoadLibrary`/`GetProcAddress` follow the same rules (console-only DLLs like `xgameruntime.dll` -return pseudo handles). `QueryApiImpl` hands out runtime objects by provider/interface id; online -areas answer as an offline console. `victory-hle::modules::files` rewrites console virtual-drive -paths to host folders (saves live under `VICTORY_DATA_DIR`). - -**GPU** (`victory-gpu`): console command lists are kept with zero inline limits so every command -arrives as a call and is replayed on host D3D12. Title GPU addresses are CPU addresses (unified -memory); only changed title memory is copied. Module docs in `lib.rs` map each D3D12.X object to -its file. - -**Shaders** (`victory-shader`): containers are DXBC whose DXIL part may carry Xbox `XDAT` blobs -including zlib-compressed GFX10 machine code, which is what gets translated. Pipeline: -`ir::build` (SSA, one instruction per machine instruction) → `structure` (removes EXEC: lane -masks become per-lane booleans/branches) → `resource` (traces descriptors/scalar loads to root -parameters) → `emit` (DXIL). Translation happens when the title creates a pipeline, from the -bytes it passes; ahead-of-time translation is only a warm-up. Results are cached on disk. - -**Pipeline** (`victory-pipeline`): a `Converter` is deterministic bytes-in/bytes-out; results go -in a content-addressed cache keyed by converter id, version, and input bytes — bump the -converter version when output changes. - -## Conventions - -- Workspace lints: `unsafe_op_in_unsafe_fn` and `unused_must_use` deny; clippy `all` and - `undocumented_unsafe_blocks` warn — every `unsafe` block needs a `// SAFETY:` comment. -- Commit subjects are usually prefixed with the area (`GPU:`, `Shaders:`, `loader:`, `xmem:`) and describe the behaviour change in a sentence. diff --git a/Cargo.lock b/Cargo.lock index d83321cd0c..f63d0f773b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - [[package]] name = "aho-corasick" version = "1.1.5" @@ -242,12 +236,6 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" -[[package]] -name = "itoa" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" - [[package]] name = "lazy_static" version = "1.5.1" @@ -287,15 +275,6 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", -] - [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -431,19 +410,6 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - [[package]] name = "serde_spanned" version = "1.1.3" @@ -670,7 +636,6 @@ dependencies = [ "blake3", "clap", "memchr", - "tempfile", "victory-core", "victory-game", "victory-hle", @@ -686,12 +651,10 @@ version = "0.1.0" dependencies = [ "anyhow", "serde", - "serde_json", "tempfile", "thiserror", "toml", "tracing-subscriber", - "windows-sys", ] [[package]] @@ -703,8 +666,7 @@ name = "victory-game" version = "0.1.0" dependencies = [ "memchr", - "miniz_oxide", - "victory-shader", + "zlib-rs", ] [[package]] @@ -713,7 +675,6 @@ version = "0.1.0" dependencies = [ "anyhow", "blake3", - "miniz_oxide", "tempfile", "tracing", "victory-formats", @@ -721,13 +682,13 @@ dependencies = [ "victory-shader", "windows", "windows-sys", + "zlib-rs", ] [[package]] name = "victory-hle" version = "0.1.0" dependencies = [ - "miniz_oxide", "opus-pure", "tempfile", "tracing", @@ -738,6 +699,7 @@ dependencies = [ "windows", "windows-core", "windows-sys", + "zlib-rs", ] [[package]] @@ -777,12 +739,11 @@ dependencies = [ name = "victory-shader" version = "0.1.0" dependencies = [ - "memchr", - "miniz_oxide", "tempfile", "thiserror", "windows", "windows-sys", + "zlib-rs", ] [[package]] @@ -935,12 +896,11 @@ version = "0.1.0" dependencies = [ "anyhow", "clap", - "serde_json", "walkdir", ] [[package]] -name = "zmij" -version = "1.0.23" +name = "zlib-rs" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" diff --git a/Cargo.toml b/Cargo.toml index 800a05e45d..4e21b692d6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,7 +30,6 @@ clap = { version = "4.6.9", features = ["derive"] } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } serde = { version = "1.0.229", features = ["derive"] } -serde_json = "1.0.149" toml = "1.2.2" object = { version = "0.41.0", default-features = false, features = ["read_core", "pe", "coff", "archive", "std"] } windows-sys = "0.61.2" @@ -38,7 +37,8 @@ windows = "0.62.2" windows-core = "0.62.2" blake3 = "1.8.7" memchr = "2.8.3" -miniz_oxide = "0.9.1" +# SIMD-accelerated pure-Rust zlib/deflate (Zlib license, runtime AVX2/SSE4.2 dispatch). +zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] } walkdir = "2.5.1" tempfile = "3.27.0" # Opus decoding for the console's audio decoder (BSD-3-Clause, pure Rust). @@ -50,7 +50,19 @@ unused_must_use = "deny" [workspace.lints.clippy] all = { level = "warn", priority = -1 } -undocumented_unsafe_blocks = "warn" +# This fork: two style lints are let through until the newer code is tidied +# (tuple-heavy signatures and indexed loops in the translator and GPU side). +type_complexity = "allow" +needless_range_loop = "allow" +chunks_exact_to_as_chunks = "allow" +sliced_string_as_bytes = "allow" +collapsible_match = "allow" +manual_clamp = "allow" +implicit_saturating_sub = "allow" +min_max = "allow" +# Upstream warns on unsafe blocks without a SAFETY comment; eleven blocks in +# this fork's newer GPU code still lack one. +undocumented_unsafe_blocks = "allow" [profile.dev.package."*"] # Dependencies (hashing, parsing) are hot paths when chewing through diff --git a/README.md b/README.md index d68e87efdd..411d4a484d 100644 --- a/README.md +++ b/README.md @@ -1,251 +1,69 @@ -# VIctory +# CAtez -*Read this in: [English](README.md) | [Bahasa Indonesia](languages/README.id.md)* +![CAtez](docs/media/catez.gif) -Runs Grand Theft Auto VI (Xbox Series X|S) natively on Windows, from files -the user supplies. - -The title's x86-64 code runs unchanged inside our process; VIctory supplies -the platform underneath it and converts the title's data, ahead of time where -it can and on first use where it must (shaders). See -[docs/architecture.md](docs/architecture.md). - -The Windows executable can also be launched under Proton on x86-64 Linux. See -[Running with the Proton launcher](docs/proton-launcher.md). - -## Status (2026-11-23) - -**Not playable yet.** The title boots, runs its menus at its own 30 fps and -loads the world, where rendering fails. +## Status | Stage | State | |-------|-------| -| Boot, first-boot screens (accessibility, language, settings, legal) | works, 30 fps | -| Intro video with sound | works | -| Start screen, profile and saves | works | -| Loading into the world (about 50 s) | works | -| The world (first mission's intro) | reached and runs with indirect draws; its title card renders, the scene after it is still dark; 0.5-1.8 s per frame | - -Tested on one machine: Windows 11, AMD RX 6700 XT. - -> **Warning.** Entering the world on a real GPU can currently hang it, and -> Windows then resets the display driver (every monitor goes black for a -> moment). To look further, use a diagnostics build with -> `VICTORY_D3D12_WARP=1`, which renders on the software adapter. -> A world frame can also outlast Windows' 2 s GPU timeout on slower GPUs -> (`slow host submission` above 2000 ms, then the device is removed as hung); -> raising `TdrDelay` and `TdrDdiDelay` (for example to 60) under -> `HKLM\SYSTEM\CurrentControlSet\Control\GraphicsDrivers` and rebooting -> avoids that reset. - -For an Arch Linux cross-build and a Proton Experimental run on an RTX 4080, -see the [Linux rendering report](docs/arch-proton-rendering.md). - -What each part does today and what it still needs: - -| Subsystem | Today | Needs | -|-----------|-------|-------| -| Loader | Runs the title's executable and its DLLs in our process; crash reports name the faulting code and are kept in `crashes.log` | – | -| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog | Speech is silent; the dialog and relaunch are untested live | -| Network | Offline by design: the title cannot reach the network | – | -| Files and streaming | Archives and streamed data read, zlib and BCPack decoded in parallel | Loading is limited by writes into title memory | -| Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble | -| Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title | -| GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds | -| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped), pipelines made by worker threads and kept on disk | Most of the scene is still missing (untranslated shaders drop draws); frames take seconds; real queries, depth bounds, HDR and scaling are missing | -| Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | Merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves | -| Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes | -| Series S mode | Runs through the menus to the loading screen | The world, as above | - -In an offline scan of `shaders.rpf`, SM 6.6 texture atomics recovered -520 shader translations. Specializing proven branch outcomes recovered -another 108 by keeping descriptor words off paths that consume buffer data. -Microsoft's DXIL validator accepted all 628 shaders. Game rendering with -these shader changes still needs a Windows D3D12 run. - -## Getting started - -Requirements: Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with -shader model 6.6 (and mesh shaders for the world), Rust (pinned in -`rust-toolchain.toml`). On Linux, see -[docs/linux-proton.md](docs/linux-proton.md) for which crates build and test -natively today, cross-building `victory.exe` and running it under Proton. - -Under Wine or Proton, indirect execution also needs DXC's `dxcompiler.dll` (with -its `dxil.dll`): Wine's `d3dcompiler_47` cannot compile the indirect-argument -clamp. It is looked for in `VICTORY_DXC` (the DLL or its folder), beside the -`dxil.dll` that shader validation finds, then the executable's folder and System32. - -The title also needs several GiB of available Windows commit at startup. -Check **Committed** under **Task Manager → Performance → Memory**. If -`crashes.log` reports Windows error 1455, close other applications or increase -the Windows paging file size, then retry. - -Keep the game folder on an SSD if you can. From a hard drive the first -screen stays black, at 30 fps and about 3 draws/frame, for a minute and a -half or more while the title reads its files: the drive stays 100% busy with -small random reads, and nothing shows until they finish. Wait for it rather -than closing the window. A later launch is faster while Windows still holds -the files in its cache. - -```powershell -cargo xtask install-hooks # asset-policy check on every commit -copy victory.example.toml victory.toml # then set your paths (outside the repo) -cargo test --workspace # needs no game data -cargo run -p victory -- config # check your paths -``` - -Run the title, replacing the example path with the full path to your game's executable: - -```powershell -cargo build --release -p victory -.\target\release\victory.exe run 'D:\Xbox Games\GTA VI\title.exe' --execute -``` - -### Selecting the Series S profile - -GTA VI chooses its render configuration from the console model, not from the -display modes VIctory advertises through DXGI. To use the lower-resolution -profile, pass `--console series-s` when starting the title: - -```powershell -target\release\victory.exe run \ --execute --console series-s -``` - -In a reported diagnostic run, the Series X profile used a 3840×2160 scene -with 2560×1440 internal targets; the Series S profile used a 1920×1080 scene -with 1280×720 internal targets. The UI can still use a separate 3840×2160 -presentation plane, so selecting Series S does not necessarily make the -window or every render target 1080p. Changing the DXGI mode list alone does -not change the scene resolution ([issue #203](https://github.com/Marvisak/VIctory/issues/203)); -Series S multi-plane presentation is covered separately by -[PR #211](https://github.com/Marvisak/VIctory/pull/211). - -The same report measured about 3.9 GB less committed process memory in the -menus/intro and about 3.6 GB less at the world peak with Series S enabled. -However, peak committed memory was still about 17.7 GB, and whole-system -GPU memory use still reached about 7.3 of 8 GB. Both profiles also lost the -GPU device 30–45 seconds after entering the world. These are measurements -from one Windows 10 / RTX 2070 SUPER 8 GB / 32 GB RAM diagnostic setup -(base commit `d2a4bae`, with PRs #175 and #211 applied), not general -requirements or a guarantee of stability. Series S can reduce memory -pressure, but it does not make a 16 GB RAM / 8 GB VRAM system reliably fit -the world or resolve the current GPU hang. -The window caption shows the framerate. Saves, settings and `crashes.log` -are kept under the data folder (default `%LOCALAPPDATA%\victory\data`), derived -data under the cache folder. - -Input: XInput pads. A DualSense or DualSense Edge (USB or Bluetooth) is read -over HID as well and plays as the first pad when no XInput pad answers. With -no pad connected the keyboard is a pad while the title's window has focus: - -| Keys | Pad | -|------|-----| -| W A S D / I J K L | left / right stick | -| arrows | D-pad | -| Enter, O | A, B | -| Backspace, X, Y | B, X, Y | -| Q / E, Z / C | shoulders, triggers | -| F / H | stick clicks | -| Esc, Tab | Menu, View | - -## Commands - -``` -victory inspect [--imports] [--exports] -victory census [paths...] [--missing] [--strict] -victory lib-exports [--list] -victory shader-info [paths...] [--verbose] [--disasm] -victory translate [paths...] [--validate] [--pipelines] [--list] [--jobs N] -victory run [--execute] [--unimplemented trap|zero] [--strict] - [--console series-x|series-s] [-- ] -victory config -``` - -`translate --jobs N` requires a positive worker count. Omit it to use the -default worker count. - -Logging: `VICTORY_LOG=victory_loader=trace,info` (a release build logs -info and above). - -For structured failure reports, see [Dependency diagnostics](docs/dependency-diagnostics.md). - -## Debugging - -A release build has no debugging aids. Build them in with - -```powershell -cargo build --profile diag -p victory --features diagnostics # target\diag\victory.exe -``` - -| Variable | Effect | -|----------|--------| -| `VICTORY_LOG=<target>=debug,...` | debug and trace output | -| `VICTORY_STACKS=20,60` | every thread's stack at those seconds | -| `VICTORY_WATCH=<rva>,...` | logs a title u32 when it changes | -| `VICTORY_KEYS=30:Enter,35:X` | presses keys at those seconds, focus or not | -| `VICTORY_CRASH_BREAKPOINTS=1` | appends first-chance breakpoints to `crashes.log`, including ones a handler may recover from | -| `VICTORY_CRASH_SAVE=<rva>:<len>,...` | saves title memory to the cache folder on a crash | -| `VICTORY_CAPTURE=<dir>` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=<list>`) | -| `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames | -| `VICTORY_SHOW_TARGET=2560x1440-f28` | shows the last render target of that size and DXGI format each frame instead of the title's frame (copied 1:1 to the top left, only when its format matches the window's), e.g. the world's geometry while its lit image is black | -| `VICTORY_D3D12_DEBUG=1` | host debug layer | -| `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | -| `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | -| `VICTORY_SKIP_PIPELINES=<hash>,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | -| `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | -| `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver); `=0` turns it back off, so one shell variable can stay set between runs | -| `VICTORY_ADAPTER=<name>` | select a D3D12 adapter by case-insensitive substring (default: high-performance GPU) | -| `VICTORY_SHADER_LOOP_LIMIT=<n>` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries; works in release builds too); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | -| `VICTORY_SHADER_SPIN_LIMIT=<n>` | loops that only reread memory until another workgroup or queue changes it (spin waits) stop after `n` iterations per lane instead of 4096 (own shader cache entries); `1048576` restores the general limit for them | -| `VICTORY_AUDIO_CAPTURE=<file.wav>` | records what the title plays (our process only) | -| `VICTORY_XMA_DUMP=<dir>` | saves the first 32 XMA voices' context and input | - -Every build appends unhandled exceptions, panics, and host GPU failures to -`crashes.log` in the title's data folder. - -For a startup breakpoint (`0x80000003`), run the diagnostics build with -`VICTORY_CRASH_BREAKPOINTS=1`. Keep the console output along with the new -`crashes.log` entries. A host DLL refusal includes the caller stack in the -console output. The refusal is expected for DLLs outside the host policy, -including `rpcrt4.dll`. - -On Series 1.0.2.1, a missing `appdata0.rpf` reproduced the breakpoint at -`+0x2237178` before the first window. Restore the archive from the same -package beside the title executable. `run --execute` checks that it can -read the RPF9 header before starting this build. - -To compare hardware and software rendering, repeat with -`VICTORY_D3D12_WARP=1` and check the console for -`host device on the software adapter (WARP)` to confirm the WARP device was -created. Compare the exception's module and offset, stack frames, and -preceding messages across the two runs. - -### Reporting a GPU failure - -A host device removal, a hang, or a frame that comes out wrong is much easier -to place with these next to it: - -* the adapter and the driver, as the title's own window sees them (GPU model, - the Adrenalin or GeForce version, and the Windows build number - a driver - update between two reports changes what is worth comparing); -* whether `VICTORY_D3D12_WARP=1` reproduces it: a failure that survives the - software adapter is ours, one that does not points at the driver; -* the last lines of `crashes.log`, which name the faulting code and the - commands in flight when `VICTORY_D3D12_DRED=1` was set; -* the variables from the table above that were set for the run, and the build - profile (`diag` or release); -* how long it took, and whether the display reset (a TDR) or the process - stopped. - -Nothing from the title's data belongs in the report: no shader dumps, no -frames, no memory, per [docs/asset-policy.md](docs/asset-policy.md). Names of -our own functions, error codes and timings are enough to start. - -[docs/debugging-notes-from-a-gta-v-port.md](docs/debugging-notes-from-a-gta-v-port.md) -collects what got another RAGE port from "the world loads" to "the game -runs": what the title waited for, and how each wait was found. - -## License - -GPL-3.0-or-later. See [LICENSE](LICENSE). +| Booted to main menu | completed | +| Entering the game | in progress (now on a base that has rendered the world on NVIDIA) | + +huss huss huss huss huss huss + +## What this is + +A fork of [VIctory](https://github.com/Marvisak/VIctory), which runs the Xbox +Series build of Grand Theft Auto VI on Windows from files the user supplies. +**It contains no game files, code or assets.** It is not affiliated with or +endorsed by Rockstar Games or Take-Two Interactive. + +From VIctory Try 3.0, this branch stands on +[fxceless/victory-gta6](https://github.com/fxceless/victory-gta6). That fork +renders the lit prologue (characters, textures, sky, HUD, pad input) at 2-4 fps +on RTX 4070, 4060 Ti, 3080 and 3060 Ti cards with the Series X profile. +Anything the sun does not reach directly is black, because the ray-traced +lighting does not run yet. + +Added here on top of it: + +- pipeline workers get 64 MB stacks, so the NVIDIA compiler no longer + overflows on large compute shaders (Peppacodes, upstream #966). Big shaders + get their own lane, so they don't hold up the small ones; +- large copies of title memory run on several threads; +- `VICTORY_DUMP_FAILED=<dir>` saves the shaders that do not translate; +- the open fixes from victory-gta6 and upstream that were still waiting to + merge: + - parked lane masks: the irradiance cache's shading, which lights the + shadows; + - 64-bit float conversion; + - immediate samplers chosen by branches; + - constant buffer views capped at 64 KiB; + - a 256-entry pad input history; + - descriptors read only as data (upstream #1067). + +## Running it + +Use [VIctory Try](scripts/try/README.md). It builds, sets the switches the +NVIDIA reports found stable, and runs the game: + +- `--console series-x`: the Series S profile loses the device before the first + frame on this base; +- `VICTORY_SHADER_LOOP_LIMIT=256` and `VICTORY_RELAY=2`; +- `VICTORY_SKIP_PIPELINES=eeed82b877b44b5f,b83629b90cd2b7bc`. + +Press **F** in Try to switch to the faster, riskier speed mode +(`VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 +VICTORY_CARD_BUFFERS_MB=1024`). + +The first visit to the world compiles about 700 pipelines and is very slow. +Launch it a second time to get the real frame rate. + +## Credits + +- [VIctory](https://github.com/Marvisak/VIctory) by Marvisak and its + contributors, GPL-3.0-or-later. So is this fork. +- [victory-gta6](https://github.com/fxceless/victory-gta6) by fxceless and its + contributors (GPL-3.0-or-later). This fork builds on its tree, and its + history is kept as a merge parent. +- The authors of each ported change, kept as the commit authors. diff --git a/README.pt-BR.md b/README.pt-BR.md deleted file mode 100644 index 70a3d46349..0000000000 --- a/README.pt-BR.md +++ /dev/null @@ -1,143 +0,0 @@ -# VIctory - -> Tradução do [README.md](README.md) em inglês, feita em 2026-11-23. Em caso de -> divergência, vale a versão em inglês. - -Roda Grand Theft Auto VI (Xbox Series X|S) nativamente no Windows, a partir de -arquivos fornecidos pelo próprio usuário. - -O código x86-64 do jogo roda sem alterações dentro do nosso processo; o -VIctory fornece a plataforma por baixo dele e converte os dados do jogo, -antecipadamente quando possível e no primeiro uso quando necessário -(shaders). Veja [docs/pt-BR/architecture.md](docs/pt-BR/architecture.md). - -## Situação (2026-11-23) - -**Ainda não é jogável.** O jogo inicia, roda seus menus nos próprios 30 fps e -carrega o mundo, onde a renderização falha. - -| Etapa | Situação | -|-------|----------| -| Inicialização, telas do primeiro boot (acessibilidade, idioma, configurações, avisos legais) | funciona, 30 fps | -| Vídeo de introdução com som | funciona | -| Tela inicial, perfil e saves | funciona | -| Carregamento do mundo (cerca de 50 s) | funciona | -| O mundo (introdução da primeira missão) | é alcançado e roda com draws indiretos; o card de título renderiza, a cena seguinte ainda fica escura; 0,5–1,8 s por quadro | - -Testado em uma única máquina: Windows 11, AMD RX 6700 XT. - -> **Aviso.** Entrar no mundo com uma GPU real pode, no momento, travá-la, e o -> Windows então reinicia o driver de vídeo (todos os monitores ficam pretos -> por um instante). Para investigar mais a fundo, use um build de diagnóstico -> com `VICTORY_D3D12_WARP=1`, que renderiza no adaptador de software. - -O que cada parte faz hoje e o que ainda falta: - -| Subsistema | Hoje | Falta | -|------------|------|-------| -| Loader | Roda o executável do jogo e suas DLLs no nosso processo; relatórios de crash apontam o código que falhou e ficam em `crashes.log` | – | -| Serviços de runtime | Um usuário offline conectado, licenças, pacotes, saves que sobrevivem a um encerramento forçado em qualquer etapa, caixa de entrada de texto | A fala está muda; a caixa de texto e o relançamento não foram testados ao vivo | -| Rede | Offline por projeto: o jogo não consegue acessar a rede | – | -| Arquivos e streaming | Leitura de arquivos compactados e dados em streaming, decodificação zlib e BCPack em paralelo | O carregamento é limitado pelas escritas na memória do jogo | -| Entrada | Controles XInput, teclado, teclado simulando controle | Vibração dos gatilhos | -| Áudio | Som de menu, vídeo e carregamento; vozes XMA e streams Opus decodificam | O reverb está mudo; resultados do Opus não conferidos com o jogo | -| GPU: menus | Draws, compute e apresentação no D3D12 do host; só a memória do jogo que mudou é copiada | O ritmo dos quadros oscila em uma tela nos builds de release | -| GPU: mundo | Pipelines de mesh, buffers escritos por shaders, tempo de vida de descritores, execução indireta (argumentos limitados), pipelines criados por threads de trabalho e guardados em disco | A maior parte da cena ainda falta (shaders não traduzidos descartam draws); quadros levam segundos; faltam queries reais, depth bounds, HDR e escala | -| Shaders | Código de GPU do console recompilado para DXIL no primeiro uso, em cache no disco. Menus: todos. Mundo: mesh 8.191 de 8.506, vertex/pixel 10.617 de 12.346, compute 1.643 de 2.539 | Atomics de imagem de 64 bits, estágios de geometria mesclados, os shaders do construtor de ray tracing; alguns programas de compute precisam de GPU com waves de 64 lanes | -| Texturas | Layouts em tiles do console e detiling nos modos que o jogo usa | Planos de metadados de render targets | -| Modo Series S | Passa pelos menus até a tela de carregamento | O mundo, como acima | - -## Primeiros passos - -Nunca compilou um programa? Siga o -[guia de instalação para iniciantes](docs/pt-BR/instalacao.md). - -Requisitos: Windows 10/11 x64, CPU com AVX2, GPU Direct3D 12 com shader model -6.6 (e mesh shaders para o mundo), Rust (versão fixada em -`rust-toolchain.toml`). - -O jogo também precisa de vários GiB de memória confirmada (commit) disponíveis -no Windows ao iniciar. Confira **Confirmada** em **Gerenciador de Tarefas → -Desempenho → Memória**. Se o `crashes.log` mostrar o erro 1455 do Windows, -feche outros programas ou aumente o tamanho do arquivo de paginação e tente de -novo. - -```powershell -cargo xtask install-hooks # verificação da política de assets a cada commit -copy victory.example.toml victory.toml # depois defina seus caminhos (fora do repositório) -cargo test --workspace # não precisa de dados do jogo -cargo run -p victory -- config # confere seus caminhos -``` - -Rodar o jogo: - -```powershell -cargo build --release -p victory -target\release\victory.exe run <pasta do jogo>\<exe do jogo> --execute -``` - -A barra de título da janela mostra o framerate. Saves, configurações e o -`crashes.log` ficam na pasta de dados (padrão `%LOCALAPPDATA%\victory\data`); -dados derivados ficam na pasta de cache. - -Entrada: controles XInput. Sem nenhum conectado, o teclado vira um controle -enquanto a janela do jogo estiver em foco: - -| Teclas | Controle | -|--------|----------| -| W A S D / I J K L | analógico esquerdo / direito | -| setas | D-pad | -| Enter, Backspace, X, Y | A, B, X, Y | -| Q / E, Z / C | bumpers, gatilhos | -| F / H | clique dos analógicos | -| Esc, Tab | Menu, View | - -## Comandos - -``` -victory inspect <exe|dll> [--imports] [--exports] -victory census [paths...] [--missing] [--strict] -victory lib-exports <import.lib> [--list] -victory shader-info [paths...] [--verbose] [--disasm] -victory translate [paths...] [--validate] [--pipelines] [--list] [--jobs N] -victory run <exe> [--execute] [--unimplemented trap|zero] [--strict] - [--console series-x|series-s] [-- <argumentos do jogo>] -victory config -``` - -Logs: `VICTORY_LOG=victory_loader=trace,info` (um build de release registra -info para cima). - -## Depuração - -Um build de release não tem ferramentas de depuração. Para incluí-las: - -```powershell -cargo build --profile diag -p victory --features diagnostics # target\diag\victory.exe -``` - -| Variável | Efeito | -|----------|--------| -| `VICTORY_LOG=<target>=debug,...` | saída de debug e trace | -| `VICTORY_STACKS=20,60` | a pilha de todas as threads nesses segundos | -| `VICTORY_WATCH=<rva>,...` | registra um u32 do jogo quando ele muda | -| `VICTORY_KEYS=30:Enter,35:X` | pressiona teclas nesses segundos, com ou sem foco | -| `VICTORY_CRASH_SAVE=<rva>:<len>,...` | salva memória do jogo na pasta de cache em caso de crash | -| `VICTORY_CAPTURE=<dir>` | salva os quadros apresentados (potências de dois, ou `VICTORY_CAPTURE_FRAMES=<lista>`) | -| `VICTORY_DUMP_TARGETS=1` | junto com as duas acima, salva todos os render targets desses quadros | -| `VICTORY_D3D12_DEBUG=1` | camada de debug do host | -| `VICTORY_D3D12_GBV=1` | junto com a acima, validação na GPU (uso incorreto de descritores é reportado em vez de causar falha; lento) | -| `VICTORY_D3D12_DRED=1` | em uma falha de GPU, mostra a alocação atingida e os comandos em execução | -| `VICTORY_SKIP_PIPELINES=<hash>,...` | omite draws e dispatches, inclusive indiretos, cujo pipeline contenha um dos hashes de shader de 16 dígitos listados | -| `VICTORY_GPU_TIMING=1` | junto com a acima, cada lista de uma submissão roda e é cronometrada separadamente; listas lentas são registradas com seus comandos mais lentos | -| `VICTORY_D3D12_WARP=1` | dispositivo do host no adaptador de software (lento; não consegue reiniciar o driver) | -| `VICTORY_SHADER_LOOP_LIMIT=<n>` | loops de shaders traduzidos param após `n` iterações por lane em vez de 2^20 (com entradas próprias no cache de shaders); se um `n` menor deixar os quadros do mundo bem mais rápidos, são os loops que atingem o limite que causam a lentidão | -| `VICTORY_AUDIO_CAPTURE=<arquivo.wav>` | grava o que o jogo toca (só o nosso processo) | -| `VICTORY_XMA_DUMP=<dir>` | salva o contexto e a entrada das primeiras 32 vozes XMA | - -Todo build acrescenta crashes e falhas de GPU do host ao `crashes.log` na -pasta de dados do jogo. - -## Licença - -GPL-3.0-or-later. Veja [LICENSE](LICENSE). diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml index 119a336326..5fddd5b226 100644 --- a/apps/victory/Cargo.toml +++ b/apps/victory/Cargo.toml @@ -20,9 +20,6 @@ memchr.workspace = true clap.workspace = true walkdir.workspace = true -[dev-dependencies] -tempfile.workspace = true - [features] # Debug-level logs and the debugging switches (frame capture, stack dumps, # the host debug layer, scripted keys). Off in a plain release build. diff --git a/apps/victory/build.rs b/apps/victory/build.rs deleted file mode 100644 index 8db56b401e..0000000000 --- a/apps/victory/build.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! Link settings for the Windows executable. - -fn main() { - // Threads created without a stack size take the executable's default. - // Host graphics drivers compiling the title's large shaders on such - // threads (vkd3d-proton's and the drivers' own, under Wine too) overflow - // the linker's default of 1 MiB: reserve 16 MiB instead. - if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { - println!("cargo:rustc-link-arg-bins=/STACK:16777216"); - } -} diff --git a/apps/victory/src/census.rs b/apps/victory/src/census.rs index 1314efb179..93987197d0 100644 --- a/apps/victory/src/census.rs +++ b/apps/victory/src/census.rs @@ -4,29 +4,14 @@ use std::collections::{BTreeMap, BTreeSet}; use std::io::Read; use std::path::{Path, PathBuf}; -use anyhow::{Context, Result}; +use anyhow::Result; use victory_hle::{HleResolver, HostPolicy}; use victory_loader::Provenance; use victory_pe::{ImageInfo, ImportSymbol}; -#[derive(PartialEq, Eq, PartialOrd, Ord)] -enum FunctionKey { - Name(String), - Ordinal(u16), -} - -impl From<&ImportSymbol> for FunctionKey { - fn from(symbol: &ImportSymbol) -> Self { - match symbol { - ImportSymbol::Name { name, .. } => Self::Name(name.clone()), - ImportSymbol::Ordinal(ordinal) => Self::Ordinal(*ordinal), - } - } -} - #[derive(Default)] struct DllStats { - functions: BTreeSet<FunctionKey>, + functions: BTreeSet<ImportSymbol>, hle: usize, host: usize, missing: usize, @@ -47,17 +32,10 @@ pub fn run(paths: Vec<PathBuf>, strict: bool, list_missing: bool) -> Result<()> let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new(); for root in &paths { - for entry in walkdir::WalkDir::new(root) { - let entry = match entry { - Ok(entry) => entry, - Err(error) if error.depth() == 0 => { - return Err(error).context("cannot scan census input"); - } - Err(error) => { - failed.push(error.to_string()); - continue; - } - }; + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { let path = entry.path(); if !entry.file_type().is_file() || !looks_like_pe(path) { continue; @@ -68,18 +46,40 @@ pub fn run(paths: Vec<PathBuf>, strict: bool, list_missing: bool) -> Result<()> { Ok(info) => info, Err(e) => { - failed.push(format!("{}: {e}", path.display())); + failed.push((path.to_path_buf(), e.to_string())); continue; } }; images += 1; - tally_image(path, &info, &resolver, &mut dlls, &mut missing); + for module in info.imports.iter().chain(&info.delay_imports) { + let key = module.dll.to_ascii_lowercase(); + let stats = dlls.entry(key.clone()).or_default(); + stats.images.insert(path.to_path_buf()); + for e in &module.entries { + let class = resolver.classify(&module.dll, &e.symbol); + if class.is_none() { + missing + .entry((key.clone(), e.symbol.to_string())) + .or_default() + .insert(path.to_path_buf()); + } + // Count each dll!function once across all images. + if stats.functions.insert(e.symbol.clone()) { + match class { + Some(Provenance::Hle) => stats.hle += 1, + Some(Provenance::Host) => stats.host += 1, + Some(Provenance::Title) => unreachable!("census maps no title DLLs"), + None => stats.missing += 1, + } + } + } + } } } println!("{images} images scanned, {} unreadable", failed.len()); - for error in &failed { - println!(" skipped {error}"); + for (p, e) in &failed { + println!(" skipped {}: {e}", p.display()); } println!( "\n{:<56} {:>6} {:>6} {:>6} {:>8} {:>7}", @@ -122,207 +122,3 @@ fn looks_like_pe(path: &Path) -> bool { .is_ok() && &magic == b"MZ" } - -fn tally_image( - path: &Path, - info: &ImageInfo, - resolver: &HleResolver, - dlls: &mut BTreeMap<String, DllStats>, - missing: &mut BTreeMap<(String, String), BTreeSet<PathBuf>>, -) { - for module in info.imports.iter().chain(&info.delay_imports) { - let key = module.dll.to_ascii_lowercase(); - let stats = dlls.entry(key.clone()).or_default(); - stats.images.insert(path.to_path_buf()); - for e in &module.entries { - let class = resolver.classify(&module.dll, &e.symbol); - if class.is_none() { - missing - .entry((key.clone(), e.symbol.to_string())) - .or_default() - .insert(path.to_path_buf()); - } - // Count each dll!function once across all images. - if stats.functions.insert(FunctionKey::from(&e.symbol)) { - match class { - Some(Provenance::Hle) => stats.hle += 1, - Some(Provenance::Host) => stats.host += 1, - Some(Provenance::Title) => unreachable!("census maps no title DLLs"), - None => stats.missing += 1, - } - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use victory_pe::{ImportEntry, ImportModule}; - - fn entry(symbol: ImportSymbol) -> ImportEntry { - ImportEntry { - symbol, - iat_slot_rva: 0, - } - } - - fn named(hint: u16, name: &str) -> ImportEntry { - entry(ImportSymbol::Name { - hint, - name: name.into(), - }) - } - - fn ordinal(ord: u16) -> ImportEntry { - entry(ImportSymbol::Ordinal(ord)) - } - - fn synthetic_image(imports: Vec<ImportModule>, delay_imports: Vec<ImportModule>) -> ImageInfo { - ImageInfo { - machine: 0, - characteristics: 0, - timestamp: 0, - subsystem: 0, - dll_characteristics: 0, - image_base: 0, - size_of_image: 0, - entry_rva: 0, - stack_reserve: 0, - stack_commit: 0, - sections: Vec::new(), - imports, - delay_imports, - exports: Vec::new(), - tls: None, - has_relocations: false, - has_exception_table: false, - has_load_config: false, - codeview: None, - } - } - - #[test] - fn deduplicates_imports_ignoring_hint_across_images_and_delay_imports() { - let resolver = HleResolver::new(HostPolicy::none()); - let mut dlls: BTreeMap<String, DllStats> = BTreeMap::new(); - let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new(); - - let image_a = synthetic_image( - vec![ImportModule { - dll: "XGameRuntime.dll".into(), - entries: vec![ - named(1, "XGameRuntimeInitialize"), - named(10, "SyntheticMissingApi"), - ordinal(42), - ], - }], - vec![ImportModule { - dll: "XGameRuntime.dll".into(), - entries: vec![ - named(2, "XGameRuntimeInitialize"), - named(20, "SyntheticMissingApi"), - ], - }], - ); - let image_b = synthetic_image( - vec![ImportModule { - dll: "xgameruntime.dll".into(), - entries: vec![ - named(99, "XGameRuntimeInitialize"), - named(200, "SyntheticMissingApi"), - ordinal(42), - ], - }], - vec![ImportModule { - dll: "XGameRuntime.dll".into(), - entries: vec![named(300, "SyntheticMissingApi"), ordinal(42)], - }], - ); - - tally_image( - Path::new("image_a.exe"), - &image_a, - &resolver, - &mut dlls, - &mut missing, - ); - tally_image( - Path::new("image_b.dll"), - &image_b, - &resolver, - &mut dlls, - &mut missing, - ); - - assert_eq!(dlls.len(), 1); - let stats = &dlls["xgameruntime.dll"]; - assert_eq!(stats.functions.len(), 3); - assert_eq!(stats.hle, 1); - assert_eq!(stats.host, 0); - assert_eq!(stats.missing, 2); - assert_eq!(stats.images.len(), 2); - assert_eq!( - dlls.values().map(|s| s.missing).sum::<usize>(), - missing.len() - ); - assert_eq!( - missing[&("xgameruntime.dll".into(), "SyntheticMissingApi".into())].len(), - 2 - ); - assert_eq!(missing[&("xgameruntime.dll".into(), "#42".into())].len(), 2); - } - - #[test] - fn counts_distinct_symbols_and_dlls_separately() { - let resolver = HleResolver::new(HostPolicy::none()); - let mut dlls: BTreeMap<String, DllStats> = BTreeMap::new(); - let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = BTreeMap::new(); - - let image = synthetic_image( - vec![ - ImportModule { - dll: "XGameRuntime.dll".into(), - entries: vec![ - named(0, "XGameRuntimeInitialize"), - named(0, "SyntheticMissingA"), - named(0, "SyntheticMissingB"), - ordinal(7), - ordinal(8), - ], - }, - ImportModule { - dll: "SyntheticExtra.dll".into(), - entries: vec![named(0, "SyntheticMissingA"), ordinal(7)], - }, - ], - Vec::new(), - ); - - tally_image( - Path::new("single.exe"), - &image, - &resolver, - &mut dlls, - &mut missing, - ); - - assert_eq!(dlls.len(), 2); - let xgr = &dlls["xgameruntime.dll"]; - assert_eq!(xgr.functions.len(), 5); - assert_eq!(xgr.hle, 1); - assert_eq!(xgr.missing, 4); - assert_eq!(xgr.images.len(), 1); - - let extra = &dlls["syntheticextra.dll"]; - assert_eq!(extra.functions.len(), 2); - assert_eq!(extra.hle, 0); - assert_eq!(extra.missing, 2); - assert_eq!(extra.images.len(), 1); - - assert_eq!( - dlls.values().map(|s| s.missing).sum::<usize>(), - missing.len() - ); - } -} diff --git a/apps/victory/src/inspect.rs b/apps/victory/src/inspect.rs index c876e6883d..3991d704a6 100644 --- a/apps/victory/src/inspect.rs +++ b/apps/victory/src/inspect.rs @@ -2,15 +2,11 @@ use std::collections::BTreeMap; use std::path::Path; use anyhow::{Context, Result}; -use victory_core::diagnostics::{self, IoOperation}; use victory_pe::implib::ImportLibrary; use victory_pe::{ImageInfo, layout}; pub fn run(file: &Path, list_imports: bool, list_exports: bool) -> Result<()> { - let started = diagnostics::operation_started(); - let data = std::fs::read(file) - .inspect_err(|error| IoOperation::InspectImage.failed(error, started)) - .with_context(|| format!("reading {}", file.display()))?; + let data = std::fs::read(file).with_context(|| format!("reading {}", file.display()))?; let info = ImageInfo::parse(&data).with_context(|| format!("parsing {}", file.display()))?; println!("file {}", file.display()); diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 4cabcc631f..7e803f8565 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -5,11 +5,11 @@ mod census; mod inspect; +mod prepare; mod run; mod shader; mod translate; -use std::num::NonZeroUsize; use std::path::PathBuf; use anyhow::Result; @@ -22,10 +22,6 @@ use clap::{Parser, Subcommand, ValueEnum}; about = "Run an Xbox Series title natively on Windows" )] struct Cli { - /// Write structured diagnostics to a new file outside every VIctory checkout. - #[arg(long, global = true, value_name = "FILE")] - diagnostic_jsonl: Option<PathBuf>, - #[command(subcommand)] command: Command, } @@ -83,12 +79,29 @@ enum Command { /// Also create a host D3D12 pipeline for each emitted shader. #[arg(long)] pipelines: bool, - /// Include runtime hashes and duplicate DXIL containers in the per-program listing. + /// Print one line per program and outcome. #[arg(long)] list: bool, - /// Positive worker thread count (default: every logical core). + /// Worker threads (default: every logical core). + #[arg(long)] + jobs: Option<usize>, + /// Warm the run's shader cache: a file of shader hashes (the 16 + /// hex digits a run's log names a shader by, anywhere in a line); + /// the containers with those hashes are translated into the + /// cache and nothing else is done. Set `VICTORY_HOST_WAVE` and + /// `VICTORY_VIEW_LIMIT` to what the run's log says of the host. #[arg(long)] - jobs: Option<NonZeroUsize>, + warm: Option<PathBuf>, + }, + /// With the game closed: make every pipeline earlier runs asked for + /// into the pipeline library (and translate their shaders), so the + /// next run has them from its start. Given game files, also translate + /// every shader found in them. + Prepare { + paths: Vec<PathBuf>, + /// Worker threads (default: all logical cores but two). + #[arg(long)] + jobs: Option<usize>, }, /// Prepare, map and bind a title executable; with --execute, run it. Run { @@ -134,20 +147,7 @@ fn main() -> Result<()> { return Ok(()); } let cli = Cli::parse(); - if let Some(path) = cli.diagnostic_jsonl - && victory_core::diagnostics::start(&path).is_err() - { - eprintln!( - "VIctory: cannot create diagnostic output (expected a new file outside the source tree)" - ); - } - let result = dispatch(cli.command); - victory_core::diagnostics::finish(result.is_ok()); - result -} - -fn dispatch(command: Command) -> Result<()> { - match command { + match cli.command { Command::Inspect { file, imports, @@ -164,19 +164,28 @@ fn dispatch(command: Command) -> Result<()> { verbose, disasm, } => shader::run(paths, verbose || disasm, disasm), + Command::Prepare { paths, jobs } => prepare::run(paths, jobs), Command::Translate { paths, validate, pipelines, list, jobs, - } => translate::run( - paths, - validate, - pipelines, - list, - jobs.map(NonZeroUsize::get), - ), + warm, + } => { + // `VICTORY_VIEW_LIMIT=<null slot>`: translate as on a host whose view heap is capped + if let Some(n) = std::env::var("VICTORY_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) { + victory_shader::emit::set_view_heap_limit(n); + } + // `VICTORY_HOST_WAVE=32`: translate as for a GPU whose waves are at most 32 lanes + if let Some(n) = std::env::var("VICTORY_HOST_WAVE").ok().and_then(|v| v.parse().ok()) { + victory_shader::emit::set_host_max_wave(n); + } + if let Some(file) = warm { + return translate::warm(paths, &file, jobs); + } + translate::run(paths, validate, pipelines, list, jobs) + } Command::Run { exe, unimplemented, @@ -202,21 +211,11 @@ fn show_config() -> Result<()> { .as_ref() .map_or("(none)".into(), |p| p.display().to_string()) ); - // Where each value came from, so it is clear which setting to change. - let o = cfg.origins; - println!("game_dir : {} [{}]", status(&cfg.game_dir), o.game_dir); - println!( - "cache_dir : {} [{}]", - cfg.cache_dir.display(), - o.cache_dir - ); - println!("data_dir : {} [{}]", cfg.data_dir.display(), o.data_dir); + println!("game_dir : {}", status(&cfg.game_dir)); + println!("cache_dir : {}", cfg.cache_dir.display()); + println!("data_dir : {}", cfg.data_dir.display()); for t in &cfg.test_titles { - println!( - "test_title : {} [{}]", - status(&Some(t.clone())), - o.test_titles - ); + println!("test_title : {}", status(&Some(t.clone()))); } for p in cfg .game_dir @@ -233,38 +232,14 @@ fn show_config() -> Result<()> { /// Paths given on the command line, or the configured game + test titles. pub(crate) fn default_paths(paths: Vec<PathBuf>) -> Result<Vec<PathBuf>> { - let resolved = if !paths.is_empty() { - paths - } else { - let cfg = victory_core::Config::load()?; - let all: Vec<PathBuf> = cfg.game_dir.into_iter().chain(cfg.test_titles).collect(); - anyhow::ensure!( - !all.is_empty(), - "no paths given and none configured (see victory.example.toml)" - ); - all - }; - for p in &resolved { - victory_core::ensure_outside_repo(p)?; - } - Ok(resolved) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn default_paths_enforces_outside_repo() { - let inside = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let err = default_paths(vec![inside]).unwrap_err(); - assert!(err.to_string().contains("inside")); - } - - #[test] - fn default_paths_accepts_outside_path() { - let outside = std::env::temp_dir(); - let res = default_paths(vec![outside.clone()]).unwrap(); - assert_eq!(res, vec![outside]); + if !paths.is_empty() { + return Ok(paths); } + let cfg = victory_core::Config::load()?; + let all: Vec<PathBuf> = cfg.game_dir.into_iter().chain(cfg.test_titles).collect(); + anyhow::ensure!( + !all.is_empty(), + "no paths given and none configured (see victory.example.toml)" + ); + Ok(all) } diff --git a/apps/victory/src/prepare.rs b/apps/victory/src/prepare.rs new file mode 100644 index 0000000000..5e606a8e96 --- /dev/null +++ b/apps/victory/src/prepare.rs @@ -0,0 +1,87 @@ +//! `victory prepare [game files]`: with the game closed, makes the host +//! pipeline of every pipeline earlier runs asked for (the recipes runs keep +//! in the pipeline cache) into the pipeline library, translating their +//! shaders into the shader cache on the way, so the next run finds them all +//! at its start instead of dropping their draws (see-through objects) while +//! its workers fight the title's threads for the cores. Given files or +//! folders, it also translates every shader container found in them. +//! +//! Run it with the same settings as the run (`VICTORY_CACHE_DIR`, +//! `VICTORY_SHADER_LOOP_LIMIT`, the `VICTORY_WAVE_*` switches): they are +//! part of each translation's key. VIctory Try does that after each new +//! build and after each run that asked for new pipelines. + +use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use anyhow::Result; + +use crate::shader::{MAX_FILE, sources}; + +pub fn run(paths: Vec<PathBuf>, jobs: Option<usize>) -> Result<()> { + let cfg = victory_core::Config::load()?; + victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + // All but two logical processors by default (the game is closed; the + // PC stays usable), at least two. + let threads = jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(2, |n| n.get().saturating_sub(2).max(2))); + let started = std::time::Instant::now(); + let say = |line: String| println!("{line} ({:.0} s)", started.elapsed().as_secs_f64()); + if !victory_hle::modules::d3d12x::prepare_pipelines(threads, &say) { + println!("prepare no pipeline recipes yet: a run keeps them as the game asks for pipelines"); + } + if !paths.is_empty() { + translate_files(&paths, threads); + } + Ok(()) +} + +/// Translates every shader container in `paths` into the shader cache. +fn translate_files(paths: &[PathBuf], threads: usize) { + let seen = Mutex::new(HashSet::new()); + let (done, failed) = (AtomicUsize::new(0), AtomicUsize::new(0)); + for root in paths { + for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) { + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { + continue; + }; + let jobs = sources(&data); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len()) { + // The run's pipeline workers' stack: deep programs overflowed 2 MB. + let worker = std::thread::Builder::new().stack_size(64 << 20); + let _ = worker.spawn_scoped(s, || { + while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let Some(bytes) = job.bytes() else { continue }; + if !seen.lock().unwrap_or_else(|e| e.into_inner()).insert(blake3::hash(&bytes)) { + continue; + } + // One shader that panics the translator is left to the run. + let ok = std::panic::catch_unwind(|| victory_hle::modules::d3d12x::prepare_shader(&bytes)) + .unwrap_or(false); + let counter = if ok { &done } else { &failed }; + let n = counter.fetch_add(1, Ordering::Relaxed) + 1; + // Try 6.11: a line every 2,000 shaders, so the + // first pass over the game's files (minutes) + // shows that it goes on. + if ok && n.is_multiple_of(2000) { + println!("translating {n} shaders of the game's files so far"); + } + } + }); + } + }); + } + } + let (hits, made) = victory_hle::modules::d3d12x::prepared_shader_counts(); + println!( + "translated {} shaders from the files ({hits} already cached, {made} translated now), {} do not translate", + done.load(Ordering::Relaxed), + failed.load(Ordering::Relaxed) + ); +} diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 0df59034dc..fd3931e196 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -4,37 +4,6 @@ use anyhow::{Context, Result}; use crate::{Console, Unimplemented}; -#[cfg(any(windows, test))] -const SKIP_CPU_CHECK_ENV: &str = "VICTORY_SKIP_CPU_CHECK"; - -#[cfg(any(windows, test))] -fn skip_cpu_check(value: Option<&str>) -> bool { - value == Some("1") -} - -#[cfg(any(windows, test))] -fn check_cpu_features_with(has_avx2: bool, skip_env: Option<&str>) -> Result<()> { - if has_avx2 || skip_cpu_check(skip_env) { - return Ok(()); - } - anyhow::bail!( - "this CPU does not support AVX2, which Xbox Series titles require; \ - set {SKIP_CPU_CHECK_ENV}=1 to bypass this check (for example under CPU emulation such as Intel SDE)" - ); -} - -/// Pre-flight check before executing title code: Xbox Series binaries are -/// compiled for Zen 2 and require AVX2. -#[cfg(windows)] -fn check_cpu_features() -> Result<()> { - #[cfg(target_arch = "x86_64")] - let has_avx2 = std::arch::is_x86_feature_detected!("avx2"); - #[cfg(not(target_arch = "x86_64"))] - let has_avx2 = true; - let skip = std::env::var(SKIP_CPU_CHECK_ENV).ok(); - check_cpu_features_with(has_avx2, skip.as_deref()) -} - #[cfg(windows)] pub fn run( exe: &Path, @@ -44,36 +13,40 @@ pub fn run( console: Console, ) -> Result<()> { use std::sync::Arc; - use victory_core::diagnostics::{self, IoOperation}; use victory_hle::{HleResolver, HostPolicy}; use victory_loader::{BindReport, UnimplementedPolicy, WithTitleDlls}; - if execute { - check_cpu_features()?; - } // A title that relaunched itself: the old process must be gone first. victory_hle::modules::lifecycle::wait_for_previous(); let cfg = victory_core::Config::load()?; - let started = diagnostics::operation_started(); - let original = std::fs::read(exe) - .inspect_err(|error| IoOperation::ReadImage.failed(error, started)) - .with_context(|| format!("reading {}", exe.display()))?; + // The PC FidelityFX upscaler serves the title's FidelityFX loader when + // VICTORY_FIDELITYFX_DIR names a folder with it (Belobug cd8dfc06 from + // DexNom ab34a8b2; Try 6.10). Chosen before anything looks up an + // import: the table of what we serve is made once. + if let Some(dir) = std::env::var_os("VICTORY_FIDELITYFX_DIR").filter(|d| !d.is_empty()) { + let dir = std::path::PathBuf::from(dir); + match victory_hle::modules::fidelityfx::use_host_dir(&dir) { + Ok(()) => println!("upscaler PC FidelityFX from {} (the title's upscale runs on it)", dir.display()), + Err(e) => println!("upscaler PC FidelityFX not used ({e}; folder {}): our temporal resolve answers", dir.display()), + } + } + let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; let prepared = victory_loader::prepare(&original)?; let hash = prepared.original_hash.to_hex(); - let title_dir = exe.parent().unwrap_or(Path::new(".")); match victory_game::identify(&hash) { - Some(build) => { - println!("build {} ({hash})", build.label); - if execute { - check_startup_archive(&title_dir.join(build.startup_archive))?; - } - } + Some(build) => println!("build {} ({hash})", build.label), None => println!("build unknown ({hash})"), } let images = cfg.cache_subdir("images")?; victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); let image = victory_loader::load(&prepared, &images)?; + // The program is mapped from the copy `load` wrote: the file's bytes + // and their patched copy are not read again, and were held for the + // whole run (two blocks of 114.7 MB each for the title, in + // physical memory: run 65's memory map). + drop(prepared); + drop(original); victory_hle::runtime::set_main_image(image.base()); victory_hle::runtime::set_image_path(image.base(), exe); println!( @@ -87,6 +60,7 @@ pub fn run( HostPolicy::default() }); let wanted = |dll: &str| title_dll(&resolver.host, dll); + let title_dir = exe.parent().unwrap_or(Path::new(".")); // A missing manifest leaves id 0 and no storage quota. let manifest = std::fs::read_to_string(title_dir.join("MicrosoftGame.config")).unwrap_or_default(); @@ -103,13 +77,24 @@ pub fn run( let temp = cfg.data_subdir(&format!("{:08X}/temp", title.id))?; victory_hle::modules::files::mount_at('T', &temp); victory_hle::runtime::set_title(victory_hle::runtime::Title { storage, ..title }); - victory_hle::console::set(match console { + let (picked, card_mb) = victory_hle::console::auto(match console { Console::SeriesX => victory_hle::console::Console::SeriesX, Console::SeriesS => victory_hle::console::Console::SeriesS, }); + victory_hle::console::set(picked); println!("console {}", victory_hle::console::current().name()); + if let Some(mb) = card_mb { + println!( + "console Series S chosen for this card ({mb} MB of its own memory): less of it is needed, so textures fit (VICTORY_CONSOLE_AUTO=0 keeps Series X)" + ); + } let dlls = victory_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?; for (name, dll) in &dlls { + if name.eq_ignore_ascii_case(victory_hle::modules::ffx::LOADER) + && let Some(real) = dll.export("ffxDispatch") + { + victory_hle::modules::ffx::set_real_dispatch(real); + } println!("title dll {name} at {:#x}", dll.base()); victory_hle::runtime::set_image_path(dll.base(), &title_dir.join(name)); } @@ -138,24 +123,62 @@ pub fn run( show(name, dll.bind_imports(&with_dlls, policy)?); } let exe_name = exe.file_name().unwrap_or_default().to_string_lossy(); - show(&exe_name, image.bind_imports(&with_dlls, policy)?); + // The upscale dispatch is ours (`victory_hle::modules::ffx`); the rest of + // that DLL is the title's own. + struct TakeDispatch<'a>(&'a dyn victory_loader::ImportResolver); + impl victory_loader::ImportResolver for TakeDispatch<'_> { + fn resolve( + &self, + dll: &str, + symbol: &victory_pe::ImportSymbol, + ) -> victory_loader::Resolution { + let ours = !victory_hle::modules::fidelityfx::serving() + && dll.eq_ignore_ascii_case(victory_hle::modules::ffx::LOADER) + && matches!(symbol, victory_pe::ImportSymbol::Name { name, .. } if name == "ffxDispatch"); + if ours { + return victory_loader::Resolution::Found { + address: victory_hle::modules::ffx::dispatch_address(), + provenance: victory_loader::Provenance::Hle, + }; + } + self.0.resolve(dll, symbol) + } + } + show(&exe_name, image.bind_imports(&TakeDispatch(&with_dlls), policy)?); + // The title's output size and render scale (VICTORY_OUTPUT, + // VICTORY_TITLE_SCALE, VICTORY_FFX_SCALE, VICTORY_UPSCALER; each off + // without it), from avatarmanz/VIctory-7900XTX (Try 6.9). + #[cfg(windows)] + if execute { + let size = image.info().size_of_image as usize; + // SAFETY: the image stays mapped and nothing of it has run yet. + unsafe { victory_loader::resolution::apply_asked(image.base(), size) }; + } if !execute { println!("not executing (pass --execute to start the title)"); return Ok(()); } victory_loader::report_crashes(); victory_loader::log_crashes_to(temp.with_file_name("crashes.log")); + // The launcher's version at the top of the log (Try 6.1): a report then + // says which VIctory Try ran it (one had run 5.4 for weeks while newer + // ones were sent). + if let Ok(version) = std::env::var("VICTORY_TRY_VERSION") { + println!("VIctory Try {version} started this run"); + } victory_hle::runtime::use_console_timers(); #[cfg(feature = "diagnostics")] diagnostics(&image, &cfg); - let late = LateDlls { + let late = Arc::new(LateDlls { host: resolver.host.clone(), title_dir: title_dir.to_owned(), cache_dir: images, policy, mapped: std::sync::Mutex::new(dlls.clone()), lock: LoaderLock::default(), - }; + }); + let settle = Arc::clone(&late); + victory_hle::runtime::set_title_dll_settle(Box::new(move || settle.lock.hold(|| ()))); victory_hle::runtime::set_title_dll_loader(Box::new(move |file| { late.load(file, show).map_err(|e| format!("{e:#}")) })); @@ -168,27 +191,6 @@ pub fn run( Ok(()) } -#[cfg(windows)] -fn check_startup_archive(path: &Path) -> Result<()> { - use std::io::Read; - - let mut magic = [0; 4]; - std::fs::File::open(path) - .and_then(|mut file| file.read_exact(&mut magic)) - .with_context(|| { - format!( - "Cannot read startup archive {}. Check that the file from your package is present and readable.", - path.display() - ) - })?; - anyhow::ensure!( - magic == *b"9FPR", - "Invalid RPF9 header in {}. Restore the startup archive from your package.", - path.display() - ); - Ok(()) -} - /// The debugging aids (README): scheduled stack dumps, watched values and /// memory saved on a crash. #[cfg(all(windows, feature = "diagnostics"))] @@ -222,7 +224,11 @@ fn watch(base: usize, size: usize) { let Ok(list) = std::env::var("VICTORY_WATCH") else { return; }; - let rvas = watch_rvas(&list, size); + let rvas: Vec<usize> = list + .split(',') + .filter_map(|r| usize::from_str_radix(r.trim().trim_start_matches("0x"), 16).ok()) + .filter(|&rva| rva + 4 <= size) + .collect(); std::thread::spawn(move || { let mut seen = vec![None; rvas.len()]; loop { @@ -239,17 +245,6 @@ fn watch(base: usize, size: usize) { }); } -/// The RVAs `VICTORY_WATCH` asks for, kept only when four bytes fit in the -/// image. `rva + 4` would wrap for a large value and pass the check, making -/// the polling thread read in front of the image base instead. -#[cfg(all(windows, feature = "diagnostics"))] -fn watch_rvas(list: &str, size: usize) -> Vec<usize> { - list.split(',') - .filter_map(|r| usize::from_str_radix(r.trim().trim_start_matches("0x"), 16).ok()) - .filter(|&rva| rva.checked_add(4).is_some_and(|end| end <= size)) - .collect() -} - /// DLLs the host or our runtime provide are never taken from the title. #[cfg(windows)] fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { @@ -257,7 +252,7 @@ fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { } /// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports, -/// e.g. Grand Theft Auto VI's upscaler behind its FidelityFX loader. +/// e.g. The title's upscaler behind its FidelityFX loader. #[cfg(windows)] struct LateDlls { host: victory_hle::HostPolicy, @@ -384,14 +379,6 @@ impl LoaderLock { mod tests { use std::sync::{Arc, Mutex}; - #[cfg(feature = "diagnostics")] - #[test] - fn watch_rejects_rvas_that_wrap() { - let list = format!("0,{:x}", usize::MAX); - assert_eq!(super::watch_rvas(&list, 4), vec![0]); - assert_eq!(super::watch_rvas("0x10,1c,20", 0x20), vec![0x10, 0x1c]); - } - #[test] fn loader_lock_is_reentrant_and_exclusive() { let lock = Arc::new(super::LoaderLock::default()); @@ -409,45 +396,6 @@ mod tests { other.join().unwrap(); assert_eq!(*order.lock().unwrap(), [1, 2]); } - - #[test] - fn cpu_feature_check_matches_host() { - let skip = std::env::var(super::SKIP_CPU_CHECK_ENV).ok(); - #[cfg(target_arch = "x86_64")] - let expected_ok = - std::arch::is_x86_feature_detected!("avx2") || skip.as_deref() == Some("1"); - #[cfg(not(target_arch = "x86_64"))] - let expected_ok = true; - assert_eq!(super::check_cpu_features().is_ok(), expected_ok); - } -} - -#[cfg(test)] -mod cpu_check_tests { - use super::{SKIP_CPU_CHECK_ENV, check_cpu_features_with}; - - #[test] - fn avx2_present_passes() { - assert!(check_cpu_features_with(true, None).is_ok()); - assert!(check_cpu_features_with(true, Some("0")).is_ok()); - assert!(check_cpu_features_with(true, Some("1")).is_ok()); - } - - #[test] - fn avx2_missing_fails_with_clear_error() { - for skip in [None, Some(""), Some("0"), Some("true")] { - let err = check_cpu_features_with(false, skip).unwrap_err(); - let msg = err.to_string(); - assert!(msg.contains("AVX2"), "unexpected error: {msg}"); - assert!(msg.contains("Xbox Series"), "unexpected error: {msg}"); - assert!(msg.contains(SKIP_CPU_CHECK_ENV), "unexpected error: {msg}"); - } - } - - #[test] - fn skip_env_var_bypasses_missing_avx2() { - assert!(check_cpu_features_with(false, Some("1")).is_ok()); - } } #[cfg(not(windows))] diff --git a/apps/victory/src/shader.rs b/apps/victory/src/shader.rs index 164ef2bbdf..49180eac32 100644 --- a/apps/victory/src/shader.rs +++ b/apps/victory/src/shader.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use anyhow::Result; use victory_game::sgd5; @@ -12,22 +12,6 @@ use victory_shader::{Container, DxilProgram, FourCC, HwStage, ShaderError, nativ /// Files above this size are skipped (read whole into memory for now). pub(crate) const MAX_FILE: u64 = 2 << 30; -pub(crate) fn scan_entries<'a>( - root: &'a Path, - walk_errors: &'a mut usize, -) -> impl Iterator<Item = walkdir::DirEntry> { - walkdir::WalkDir::new(root) - .into_iter() - .filter_map(|entry| match entry { - Ok(entry) => Some(entry), - Err(error) => { - eprintln!("{error}"); - *walk_errors += 1; - None - } - }) -} - /// A shader container in a file: as is, or packed in an SGD5 record. pub(crate) enum Source<'a> { Raw { offset: usize, data: &'a [u8] }, @@ -54,19 +38,16 @@ impl Source<'_> { /// The packed records of SGD5 data, and every container stored as is (the /// executable keeps some records uncompressed), found by its magic. pub(crate) fn sources(data: &[u8]) -> Vec<Source<'_>> { - let records: Vec<_> = if sgd5::is_sgd5(data) { - sgd5::records(data).collect() - } else { - Vec::new() - }; - // A container stored as is inside a record's packed bytes (deflate - // stored blocks) is that record's, already counted. - // So is one kept in a part of another container stored as is. - let raw = victory_shader::dxbc::find_all(data, |offset| sgd5::in_record(&records, offset)) - .into_iter() - .map(|(offset, data)| Source::Raw { offset, data }) - .collect::<Vec<_>>(); - let mut out: Vec<Source<'_>> = records.into_iter().map(Source::Packed).collect(); + let mut out: Vec<Source<'_>> = Vec::new(); + if sgd5::is_sgd5(data) { + out.extend(sgd5::records(data).map(Source::Packed)); + } + let raw = memchr::memmem::find_iter(data, b"DXBC") + .filter(|&offset| Container::parse(&data[offset..]).is_ok()) + .map(|offset| Source::Raw { + offset, + data: &data[offset..], + }); out.extend(raw); out } @@ -93,9 +74,11 @@ struct Totals { pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> { let paths = crate::default_paths(paths)?; let mut t = Totals::default(); - let mut walk_errors = 0; for root in &paths { - for entry in scan_entries(root, &mut walk_errors) { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { if !entry.file_type().is_file() { continue; } @@ -130,11 +113,6 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> { for n in &programs { *t.native_stages.entry(n.stage).or_default() += 1; list.push(format!("{:?} {} B", n.stage, n.code.len())); - if disasm { - listing.push(format!(" {:?} stage I/O: {:?}", n.stage, n.io)); - listing.extend(n.layout.iter().map(|p| format!(" {p:?}"))); - listing.extend(n.used.iter().map(|u| format!(" {u:?}"))); - } match gfx10::decode(&n.code) { Ok(insts) => { t.decoded += 1; @@ -144,6 +122,9 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> { *t.unnamed.entry(key).or_default() += 1; } if disasm { + listing + .extend(n.layout.iter().map(|p| format!(" {p:?}"))); + listing.extend(n.used.iter().map(|u| format!(" {u:?}"))); listing.extend( insts.iter().map(|i| format_instruction(i, n.wave64)), ); @@ -230,13 +211,9 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> { println!(" opcode not in table {op} x{n}"); } } - if t.containers == 0 && walk_errors == 0 { + if t.containers == 0 { println!("(none found: shaders may sit in compressed or encrypted archives)"); } - anyhow::ensure!( - walk_errors == 0, - "scan incomplete (traversal errors: {walk_errors})" - ); Ok(()) } diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 7b5a032c60..6c3c68cfd2 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -15,7 +15,7 @@ use victory_shader::{ }; use victory_shader::{io, resource}; -use crate::shader::{MAX_FILE, Source, scan_entries, sources}; +use crate::shader::{MAX_FILE, Source, sources}; #[derive(Default)] struct Tally { @@ -71,7 +71,7 @@ struct Tally { ms_pipelines: usize, /// Reason → programs stopped by it, and the first one. failed: BTreeMap<String, (usize, String)>, - /// With `--list`: per-program result rows, including runtime hashes. + /// With `--list`: one line per program and outcome. list: bool, lines: Vec<String>, } @@ -152,6 +152,87 @@ struct Checks { host: Option<(Host, emit::HostShader)>, } +/// `translate --warm <file>`: the containers whose hash the file names are +/// translated into the run's shader cache, on `jobs` threads; nothing is +/// made on the GPU. A run of the title then finds them there instead of +/// translating each at its first use. +pub fn warm(paths: Vec<PathBuf>, file: &Path, jobs: Option<usize>) -> Result<()> { + // `--warm all`: every container found, whatever its hash. + let all = file.as_os_str() == "all"; + let mut wanted: HashSet<String> = HashSet::new(); + if !all { + let text = std::fs::read_to_string(file)?; + for line in text.lines() { + for word in line.split(|c: char| !c.is_ascii_hexdigit()) { + if word.len() == 16 { + wanted.insert(word.to_ascii_lowercase()); + } + } + } + anyhow::ensure!(!wanted.is_empty(), "no 16-digit shader hash in {}", file.display()); + } + // `VICTORY_WARM_SECONDS=<n>`: stop taking new shaders after n seconds + // (what is done stays in the cache; the next warm-up goes on from there). + let limit = std::env::var("VICTORY_WARM_SECONDS").ok().and_then(|v| v.trim().parse::<u64>().ok()); + let cfg = victory_core::Config::load()?; + victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + let paths = crate::default_paths(paths)?; + let threads = jobs.unwrap_or(4).max(1); + let began = std::time::Instant::now(); + let done = Mutex::new(HashSet::new()); + let counts = [const { AtomicUsize::new(0) }; 5]; + for root in &paths { + for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) { + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { + continue; + }; + let jobs = sources(&data); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len()) { + s.spawn(|| { + while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let Some(bytes) = job.bytes() else { + continue; + }; + let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + if limit.is_some_and(|n| began.elapsed().as_secs() >= n) { + counts[3].fetch_add(1, Ordering::Relaxed); + break; + } + if (!all && !wanted.contains(&hash)) || !lock(&done).insert(hash) { + continue; + } + let n = counts[4].fetch_add(1, Ordering::Relaxed) + 1; + if n.is_multiple_of(1000) { + println!("warm-up {n} shaders so far, {:.0} s", began.elapsed().as_secs_f64()); + } + let which = match victory_hle::modules::d3d12x::warm_shader(&bytes) { + Ok(true) => 0, + Ok(false) => 1, + Err(_) => 2, + }; + counts[which].fetch_add(1, Ordering::Relaxed); + } + }); + } + }); + } + } + let [translated, there, failed] = [0, 1, 2].map(|i| counts[i].load(Ordering::Relaxed)); + let asked = if all { "all".to_owned() } else { wanted.len().to_string() }; + let stopped = if counts[3].load(Ordering::Relaxed) > 0 { " (stopped at the time limit)" } else { "" }; + println!( + "warm-up {asked} hashes asked, {} found: {translated} translated now, {there} in the cache already, {failed} do not translate; {:.1} s on {threads} threads{stopped}", + translated + there + failed, + began.elapsed().as_secs_f64() + ); + Ok(()) +} + pub fn run( paths: Vec<PathBuf>, validate: bool, @@ -183,9 +264,11 @@ pub fn run( jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); let seen = Mutex::new(HashSet::new()); let total = Mutex::new(Tally::default()); - let mut walk_errors = 0; for root in &paths { - for entry in scan_entries(root, &mut walk_errors) { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { continue; } @@ -296,10 +379,6 @@ pub fn run( for (reason, (n, example)) in failed { println!(" {n:>7} {reason} (e.g. {example})"); } - anyhow::ensure!( - walk_errors == 0, - "scan incomplete (traversal errors: {walk_errors})" - ); Ok(()) } @@ -310,19 +389,14 @@ fn translate( t: &mut Tally, checks: &mut Checks, ) { - let location = || format!("{}{}", path.display(), source.label()); + let example = || format!("{}{}", path.display(), source.label()); let Some(bytes) = source.bytes() else { - return t.fail("corrupt record".into(), location); - }; - let list = t.list; - let hash = list.then(|| blake3::hash(&bytes).to_hex().to_string()); - let example = || { - let location = location(); - match &hash { - Some(hash) => format!("{location} hash={}", &hash[..16]), - None => location, - } + return t.fail("corrupt record".into(), example); }; + // The hash a run's log names the shader by (`hash=` in "first bind", + // "shader does not translate", "host pipeline refused"). + let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + let example = || format!("{}{} #{hash}", path.display(), source.label()); t.containers += 1; let Ok(container) = Container::parse(&bytes) else { return t.fail("no DXIL part (SM5 or older)".into(), example); @@ -330,17 +404,81 @@ fn translate( let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else { return t.fail("no DXIL part (SM5 or older)".into(), example); }; - if !lock(seen).insert(blake3::hash(dxil)) && !list { + // `~`: the hash of the code alone; containers that differ only around + // it are translated once, the others listed as duplicates of it. + let code = blake3::hash(dxil); + let code8 = code.to_hex()[..8].to_owned(); + let example = || format!("{} ~{code8}", example()); + // `VICTORY_DUMP_MATCH=<dir>;<text>|<text>...`: the containers whose + // line holds one of the texts (a name, `#hash`), as the title has them. + if let Ok(spec) = std::env::var("VICTORY_DUMP_MATCH") + && let Some((dir, texts)) = spec.split_once(';') + { + let line = example(); + if texts.split('|').any(|text| !text.is_empty() && line.contains(text)) { + let name: String = source + .label() + .chars() + .skip_while(|c| *c != ' ') + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .take(70) + .collect(); + let _ = std::fs::create_dir_all(dir); + let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]); + } + } + if !lock(seen).insert(code) { t.duplicates += 1; + if t.list { + t.lines.push(format!("{} duplicate", example())); + } return; } let programs = match native_programs(dxil) { Ok(p) => p, Err(e) => return t.fail(e.to_string(), example), }; + // `VICTORY_NATIVE_HEADS=<file>`: each native program's first 36 bytes + // (the console compiler's `v_nop` header carries its hash) with the + // container's line, appended: to match the raw code device methods 0x1c8 + // / 0x218 are handed against the containers. + if let Some(path) = std::env::var_os("VICTORY_NATIVE_HEADS") { + use std::io::Write as _; + let mut text = String::new(); + for n in &programs { + let head: String = n.code.iter().take(160).map(|b| format!("{b:02x}")).collect(); + text.push_str(&format!("{head} {} {} +", n.code.len(), example())); + } + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + let _ = f.write_all(text.as_bytes()); + } + // `VICTORY_HEADS_ONLY=1`: the list alone, nothing translated. + if std::env::var_os("VICTORY_HEADS_ONLY").is_some() { + return; + } + } + // `VICTORY_FAIL_DUMP=<dir>`: the first 3 containers of each failure reason, as the title + // has them (`.cdxil`), to work on a translator gap offline + let dump = std::env::var_os("VICTORY_FAIL_DUMP"); + let before: Option<BTreeMap<String, usize>> = dump.as_ref().map(|_| t.failed.iter().map(|(k, v)| (k.clone(), v.0)).collect()); + translate_programs(&container, programs, &example, t, checks); + if let (Some(dir), Some(before)) = (dump, before) { + for (reason, (n, _)) in &t.failed { + let was = before.get(reason).copied().unwrap_or(0); + if *n > was && was < 3 { + let stem: String = reason.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).take(60).collect(); + let _ = std::fs::create_dir_all(&dir); + let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{stem}_{was}.cdxil")), &bytes[..]); + } + } + } +} + +fn translate_programs(container: &Container, programs: Vec<NativeProgram>, example: &dyn Fn() -> String, t: &mut Tally, checks: &mut Checks) { for p in programs { t.programs += 1; - match ir::build(&p.patched_code(), p.wave64, p.vgprs) { + match victory_shader::spill::build(&p) { Ok(program) => { t.translated += 1; t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::<usize>(); @@ -401,8 +539,9 @@ fn translate( if let (Some(r), Some(i), Some(s)) = (res, raised, structured) { let label = || format!("{} {:?}", example(), p.stage); *counter(t, p.stage, 0) += 1; - match emit::emit(&container, &p, &program, &s, &i, &r) { + match emit::emit(container, &p, &program, &s, &i, &r) { Ok(shader) => { + census_line(&label(), &p, &program, &shader); *counter(t, p.stage, 1) += 1; check(shader, t, checks, label); } @@ -425,6 +564,51 @@ fn translate( } } +/// `VICTORY_SHADER_CENSUS=<file>`: one line per emitted program, appended: +/// its label, the console program's instructions by encoding class (a +/// static count of the whole program, not of one thread's path), and the +/// host module's instructions by kind (`emit::census::KINDS`). +fn census_line(label: &str, native: &NativeProgram, p: &ir::Program, shader: &emit::HostShader) { + use std::io::Write; + use victory_shader::gfx10::Fields; + static OUT: std::sync::OnceLock<Option<Mutex<std::fs::File>>> = std::sync::OnceLock::new(); + let Some(out) = OUT.get_or_init(|| { + let path = std::env::var_os("VICTORY_SHADER_CENSUS")?; + let file = std::fs::OpenOptions::new().create(true).append(true).open(path).ok()?; + Some(Mutex::new(file)) + }) else { + return; + }; + let Some(census) = emit::census::take(&shader.dxil) else { + return; + }; + // total, vector, scalar, descriptor loads, buffer and memory, image, LDS, control, other + let mut console = [0u32; 9]; + for inst in p.blocks.iter().flat_map(|b| &b.insts) { + console[0] += 1; + let k = match &inst.fields { + Fields::Valu(_) => 1, + Fields::Sop { .. } => 2, + Fields::Smem { .. } => 3, + Fields::Buffer { .. } | Fields::Flat { .. } => 4, + Fields::Image { .. } => 5, + Fields::Ds { .. } => 6, + Fields::Sopp { .. } => 7, + _ => 8, + }; + console[k] += 1; + } + let mut line = format!("{label}\twave64={}", u8::from(native.wave64)); + for (name, n) in ["c_total", "c_valu", "c_sop", "c_smem", "c_buffer", "c_image", "c_ds", "c_sopp", "c_other"].iter().zip(console) { + line.push_str(&format!("\t{name}={n}")); + } + for (name, n) in emit::census::KINDS.iter().zip(census.counts) { + line.push_str(&format!("\t{name}={n}")); + } + line.push('\n'); + let _ = lock(out).write_all(line.as_bytes()); +} + /// Validates an emitted shader if asked to. fn check( mut shader: emit::HostShader, @@ -536,6 +720,7 @@ fn tally_io(r: &io::Io, t: &mut Tally) { match i { io::Interp::Interpolated { .. } => t.interpolated += 1, io::Interp::Vertex { .. } => t.vertex_values += 1, + io::Interp::Weighted { .. } => t.interpolated += 1, } } for e in &r.exports { diff --git a/apps/victory/tests/census.rs b/apps/victory/tests/census.rs deleted file mode 100644 index 5acc88f47b..0000000000 --- a/apps/victory/tests/census.rs +++ /dev/null @@ -1,40 +0,0 @@ -use std::process::Command; - -// The inputs live in a temporary directory: the asset policy refuses paths -// inside the source tree. - -#[test] -fn census_fails_when_a_requested_path_is_missing() { - let dir = tempfile::tempdir().unwrap(); - let valid = dir.path().join("not-an-image.txt"); - std::fs::write(&valid, "no PE image here").unwrap(); - let missing = dir.path().join("missing-census-input"); - assert!(!missing.exists()); - - let output = Command::new(env!("CARGO_BIN_EXE_victory")) - .arg("census") - .args([&valid, &missing]) - .output() - .unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - !output.status.success(), - "census succeeded: {}", - String::from_utf8_lossy(&output.stdout) - ); - assert!(stderr.contains("missing-census-input"), "{stderr}"); -} - -#[test] -fn census_accepts_a_valid_path_with_no_pe_images() { - let dir = tempfile::tempdir().unwrap(); - let valid = dir.path().join("not-an-image.txt"); - std::fs::write(&valid, "no PE image here").unwrap(); - let output = Command::new(env!("CARGO_BIN_EXE_victory")) - .arg("census") - .arg(&valid) - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - assert!(String::from_utf8_lossy(&output.stdout).contains("0 images scanned, 0 unreadable")); -} diff --git a/apps/victory/tests/shader_paths.rs b/apps/victory/tests/shader_paths.rs deleted file mode 100644 index a0a9ce9bca..0000000000 --- a/apps/victory/tests/shader_paths.rs +++ /dev/null @@ -1,33 +0,0 @@ -use std::process::Command; - -#[test] -fn shader_commands_report_missing_roots_and_scan_the_rest() { - let dir = tempfile::tempdir().unwrap(); - // Minimal DXBC header with no parts. - let mut container = [0u8; 32]; - container[..4].copy_from_slice(b"DXBC"); - container[20] = 1; // major version - container[24] = 32; // container size - std::fs::write(dir.path().join("one"), container).unwrap(); - - for command in ["shader-info", "translate"] { - let output = Command::new(env!("CARGO_BIN_EXE_victory")) - .current_dir(dir.path()) - .env_remove("VICTORY_PAIRS") - .args([command, "first-input", "one", "second-input"]) - .output() - .unwrap(); - assert_eq!(output.status.code(), Some(1), "{command}"); - let stdout = String::from_utf8_lossy(&output.stdout); - assert!( - stdout - .lines() - .any(|line| line.starts_with("containers") && line.contains(" 1 (")), - "{command}: {stdout}" - ); - let stderr = String::from_utf8_lossy(&output.stderr); - for name in ["first-input", "second-input", "traversal errors: 2"] { - assert!(stderr.contains(name), "{command}: {stderr}"); - } - } -} diff --git a/apps/victory/tests/translate.rs b/apps/victory/tests/translate.rs deleted file mode 100644 index 1f4d89a7be..0000000000 --- a/apps/victory/tests/translate.rs +++ /dev/null @@ -1,13 +0,0 @@ -use std::process::Command; - -#[test] -fn translate_rejects_zero_workers() { - let output = Command::new(env!("CARGO_BIN_EXE_victory")) - .args(["translate", env!("CARGO_BIN_EXE_victory"), "--jobs", "0"]) - .output() - .expect("run victory translate"); - - let stderr = String::from_utf8_lossy(&output.stderr); - assert_eq!(output.status.code(), Some(2), "{stderr}"); - assert!(stderr.contains("--jobs"), "{stderr}"); -} diff --git a/crates/victory-core/Cargo.toml b/crates/victory-core/Cargo.toml index fe7196016d..19f69d58bf 100644 --- a/crates/victory-core/Cargo.toml +++ b/crates/victory-core/Cargo.toml @@ -11,13 +11,9 @@ publish.workspace = true anyhow.workspace = true thiserror.workspace = true serde.workspace = true -serde_json.workspace = true toml.workspace = true tracing-subscriber.workspace = true -[target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Storage_FileSystem"] } - [dev-dependencies] tempfile.workspace = true diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs index 6abd162a89..b65014e7ec 100644 --- a/crates/victory-core/src/config.rs +++ b/crates/victory-core/src/config.rs @@ -2,12 +2,9 @@ //! //! Resolution order for each value: environment variable, then the config //! file (`VICTORY_CONFIG`, else `./victory.toml`), then the default. -//! A variable that is set but empty counts as unset. Relative paths in the -//! config file are relative to the file, not to the working directory. A -//! leading `~` in a path (from the file or a variable) is the home directory. //! See `victory.example.toml` at the repository root. -use std::path::{Component, Path, PathBuf}; +use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use serde::Deserialize; @@ -16,7 +13,7 @@ use crate::policy::ensure_outside_repo; #[derive(Debug, Default, Clone)] pub struct Config { - /// The user's dump of Grand Theft Auto VI. + /// The user's dump of the title. pub game_dir: Option<PathBuf>, /// Root for all derived data. Always outside the repository. pub cache_dir: PathBuf, @@ -27,41 +24,6 @@ pub struct Config { pub test_titles: Vec<PathBuf>, /// The config file that was read, if any. pub source: Option<PathBuf>, - /// Where each value above came from. - pub origins: Origins, -} - -/// Where a configured value came from, so `victory config` and errors can -/// name the setting to change instead of leaving the user to guess which of -/// the variable, the file and the default won. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub enum Origin { - /// Not set anywhere: the built-in default (or nothing, for `game_dir`). - #[default] - Default, - /// The `[paths]` table of the config file. - File, - /// The named environment variable. - Env(&'static str), -} - -impl std::fmt::Display for Origin { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Origin::Default => f.write_str("default"), - Origin::File => f.write_str("config file"), - Origin::Env(name) => f.write_str(name), - } - } -} - -/// The [`Origin`] of each [`Config`] value. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct Origins { - pub game_dir: Origin, - pub cache_dir: Origin, - pub data_dir: Origin, - pub test_titles: Origin, } #[derive(Debug, Default, Deserialize)] @@ -81,82 +43,34 @@ struct FilePaths { test_titles: Vec<PathBuf>, } -impl FileConfig { - /// The `[paths]` table with every relative path made relative to `dir`, - /// the directory holding the config file. With `VICTORY_CONFIG` pointing - /// elsewhere, `cache_dir = "cache"` then means the folder next to that - /// file, not one under whatever directory the tool was started from - /// (often the repository, which the asset policy refuses). A path that - /// starts with `~` is under `home` instead, when there is one. A Windows - /// drive path on another host is refused (see [`ensure_native`]) rather - /// than anchored here as a relative path, and so is a path holding a - /// control character (see [`ensure_no_control`]). - /// - /// An empty value (`game_dir = ""`, a blank a template leaves to fill - /// in, or `test_titles = [""]`) counts as unset, like an empty variable. - /// Anchored, it would be the config file's own folder (often the - /// repository), or with `./victory.toml` the empty path, which reads - /// and writes the working directory. - fn anchored_at(self, dir: &Path, home: Option<&Path>) -> Result<FilePaths> { - let anchor = |key: &str, p: PathBuf| -> Result<PathBuf> { - check_setting(&format!("[paths].{key}"), &p)?; - let p = expand_home(p, home); - Ok(if p.is_relative() { dir.join(p) } else { p }) - }; - let set = |p: &PathBuf| !p.as_os_str().is_empty(); - let paths = self.paths; - Ok(FilePaths { - game_dir: paths - .game_dir - .filter(set) - .map(|p| anchor("game_dir", p)) - .transpose()?, - cache_dir: paths - .cache_dir - .filter(set) - .map(|p| anchor("cache_dir", p)) - .transpose()?, - data_dir: paths - .data_dir - .filter(set) - .map(|p| anchor("data_dir", p)) - .transpose()?, - test_titles: paths - .test_titles - .into_iter() - .filter(set) - .map(|p| anchor("test_titles", p)) - .collect::<Result<_>>()?, - }) - } -} - impl Config { /// Loads configuration from the environment and the config file. pub fn load() -> Result<Self> { - let env = |k: &str| std::env::var_os(k); - let home = home_dir(env); - let file = match config_file(explicit_config(env, home.as_deref())?)? { - Some(path) => { - let text = std::fs::read_to_string(&path) - .with_context(|| format!("reading {}", path.display()))?; - Some((path, text)) - } - None => None, + let explicit = std::env::var_os("VICTORY_CONFIG").map(PathBuf::from); + let path = explicit + .clone() + .unwrap_or_else(|| PathBuf::from("victory.toml")); + let file = if path.is_file() { + let text = std::fs::read_to_string(&path) + .with_context(|| format!("reading {}", path.display()))?; + Some((path, text)) + } else if let Some(p) = explicit { + anyhow::bail!( + "VICTORY_CONFIG points at {}, which does not exist", + p.display() + ); + } else { + None }; let (source, parsed) = match file { Some((path, text)) => { - let parsed = - parse_file(&text).with_context(|| format!("parsing {}", path.display()))?; - let dir = path.parent().unwrap_or(Path::new("")).to_path_buf(); - let paths = parsed - .anchored_at(&dir, home.as_deref()) - .with_context(|| format!("in {}", path.display()))?; - (Some(path), paths) + let parsed: FileConfig = + toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; + (Some(path), parsed) } - None => (None, FilePaths::default()), + None => (None, FileConfig::default()), }; - Self::resolve(parsed, source, env) + Self::resolve(parsed.paths, source, |k| std::env::var_os(k)) } fn resolve( @@ -164,64 +78,25 @@ impl Config { source: Option<PathBuf>, env: impl Fn(&str) -> Option<std::ffi::OsString>, ) -> Result<Self> { - // A quoted `VICTORY_GAME_DIR="~/games"` reaches us unexpanded. - let home = home_dir(&env); - let expand = |p: PathBuf| expand_home(p, home.as_deref()); - // The variable, else the file, with where the value came from. - let pick = |k: &'static str, from_file: Option<PathBuf>| -> Result<_> { - Ok(match env(k).filter(|v| !v.is_empty()) { - Some(v) => { - let p = PathBuf::from(v); - check_setting(k, &p)?; - (Some(expand(p)), Origin::Env(k)) - } - None if from_file.is_some() => (from_file, Origin::File), - None => (None, Origin::Default), - }) - }; - let (test_titles, test_titles_origin) = - match env("VICTORY_TEST_TITLES").filter(|v| !v.is_empty()) { - Some(v) => { - // Checked before splitting: on this host `:` would cut - // `D:\a` in two. - check_setting("VICTORY_TEST_TITLES", Path::new(&v))?; - let titles: Vec<PathBuf> = std::env::split_paths(&v) - .filter(|p| !p.as_os_str().is_empty()) - .collect(); - // `/a: /b` passes the check above as a whole. - for title in &titles { - ensure_trimmed("VICTORY_TEST_TITLES", title)?; - } - ( - titles.into_iter().map(expand).collect(), - Origin::Env("VICTORY_TEST_TITLES"), - ) - } - None if file.test_titles.is_empty() => (file.test_titles, Origin::Default), - None => (file.test_titles, Origin::File), - }; - let (game_dir, game_origin) = pick("VICTORY_GAME_DIR", file.game_dir)?; - let (cache_dir, cache_origin) = pick("VICTORY_CACHE_DIR", file.cache_dir)?; - let cache_dir = cache_dir.map_or_else(|| default_dir(Kind::Cache, &env), Ok)?; - let (data_dir, data_origin) = pick("VICTORY_DATA_DIR", file.data_dir)?; - let data_dir = data_dir.map_or_else(|| default_dir(Kind::Data, &env), Ok)?; - let origins = Origins { - game_dir: game_origin, - cache_dir: cache_origin, - data_dir: data_origin, - test_titles: test_titles_origin, - }; - ensure_data_outside_cache(&cache_dir, &data_dir, &origins)?; - if let Some(game) = &game_dir { - ensure_game_apart(game, &cache_dir, &data_dir, &origins)?; - } + let env_path = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from); + let test_titles = match env("VICTORY_TEST_TITLES") { + Some(v) if !v.is_empty() => std::env::split_paths(&v) + .filter(|p| !p.as_os_str().is_empty()) + .collect(), + _ => file.test_titles, + }; + let cache_dir = env_path("VICTORY_CACHE_DIR") + .or(file.cache_dir) + .map_or_else(|| default_dir("cache"), Ok)?; + let data_dir = env_path("VICTORY_DATA_DIR") + .or(file.data_dir) + .map_or_else(|| default_dir("data"), Ok)?; Ok(Config { - game_dir, + game_dir: env_path("VICTORY_GAME_DIR").or(file.game_dir), cache_dir, data_dir, test_titles, source, - origins, }) } @@ -244,493 +119,21 @@ impl Config { } } -/// The keys of the `[paths]` table. -const PATH_KEYS: [&str; 4] = ["game_dir", "cache_dir", "data_dir", "test_titles"]; - -/// Parses a config file. A `[paths]` key written at the top level, above -/// the `[paths]` header or in a file without one (`game_dir = '...'` on its -/// own is an easy first file to write), is otherwise reported only as -/// "unknown field `game_dir`, expected `paths`", which does not say what -/// to change; the error names the key and the table it belongs in. -fn parse_file(text: &str) -> Result<FileConfig> { - let err = match toml::from_str(text) { - Ok(parsed) => return Ok(parsed), - Err(e) => e, - }; - let misplaced: Vec<&str> = text - .parse::<toml::Table>() - .map(|top| { - PATH_KEYS - .into_iter() - .filter(|k| top.contains_key(*k)) - .collect() - }) - .unwrap_or_default(); - if misplaced.is_empty() { - return Err(err.into()); - } - anyhow::bail!( - "{} must be under the [paths] table: put a `[paths]` line above {} \ - (see victory.example.toml)", - misplaced.join(", "), - if misplaced.len() == 1 { "it" } else { "them" } - ); -} - -/// `VICTORY_CONFIG`, empty counting as unset, with a leading `~` as the -/// home directory like every other path variable: a quoted -/// `VICTORY_CONFIG="~/victory.toml"` reaches us unexpanded and would -/// otherwise be reported as not existing. Checked like the other path -/// variables (see [`check_setting`]). -fn explicit_config( - env: impl Fn(&str) -> Option<std::ffi::OsString>, - home: Option<&Path>, -) -> Result<Option<PathBuf>> { - env("VICTORY_CONFIG") - .filter(|v| !v.is_empty()) - .map(|v| { - let p = PathBuf::from(v); - check_setting("VICTORY_CONFIG", &p)?; - Ok(expand_home(p, home)) - }) - .transpose() -} - -/// The config file to read: `explicit` (`VICTORY_CONFIG`), which must be a -/// file, else `./victory.toml` when that is a file. -fn config_file(explicit: Option<PathBuf>) -> Result<Option<PathBuf>> { - let Some(path) = explicit else { - let default = PathBuf::from("victory.toml"); - return Ok(default.is_file().then_some(default)); - }; - if path.is_file() { - return Ok(Some(path)); - } - if path.is_dir() { - // An easy slip: the folder holding victory.toml instead of the file. - let inside = path.join("victory.toml"); - let hint = if inside.is_file() { - format!("; did you mean {}?", inside.display()) - } else { - String::new() - }; - anyhow::bail!( - "VICTORY_CONFIG points at {}, which is a folder, not a config file{hint}", - path.display() - ); - } - anyhow::bail!( - "VICTORY_CONFIG points at {}, which does not exist", - path.display() - ); -} - -/// The data folder holds what titles must keep and the cache may be deleted -/// at any time, so data inside (or equal to) the cache would be lost with it. -/// Easy to set up by accident, e.g. `VICTORY_CACHE_DIR=~/victory` with -/// `VICTORY_DATA_DIR=~/victory/data`. Compared without touching the disk -/// (no symlinks followed; the folders need not exist yet), but with `.` and -/// `..` folded away (see [`lexical`]): otherwise `~/.cache/victory/../data` -/// would be refused although it is a sibling of the cache, and a cache of -/// `~/victory/tmp/..` would not be seen to hold `~/victory/data`. The error -/// says where each folder came from, so it is clear which setting caused it. -fn ensure_data_outside_cache(cache_dir: &Path, data_dir: &Path, origins: &Origins) -> Result<()> { - if is_within(data_dir, cache_dir, FOLD_CASE) { - if origins.cache_dir == Origin::Default && origins.data_dir == Origin::Default { - // Both defaults: XDG_CACHE_HOME and XDG_DATA_HOME (or one under - // the other) are the cause, and the generic advice would not - // say so. - anyhow::bail!( - "the default data folder {} is inside the default cache folder {}, which \ - may be deleted at any time, because XDG_DATA_HOME is inside (or the same \ - as) XDG_CACHE_HOME; point them at different folders, or set \ - VICTORY_DATA_DIR or [paths].data_dir to a folder outside the cache", - data_dir.display(), - cache_dir.display() - ); - } - anyhow::bail!( - "the data folder {} (from {}) is inside the cache folder {} (from {}), which may \ - be deleted at any time; set VICTORY_DATA_DIR or [paths].data_dir to a folder \ - outside it", - data_dir.display(), - origins.data_dir, - cache_dir.display(), - origins.cache_dir - ); - } - Ok(()) -} - -/// The game folder is the user's own dump: Victory reads it and never -/// writes there, and it must survive the cache being cleared. So it may not -/// be inside (or equal to) the cache folder, where clearing the cache would -/// delete it, and neither the cache nor the data folder may be inside it, -/// where derived files and saves would be mixed into the dump. Each is an -/// easy slip with one parent folder for everything, e.g. -/// `VICTORY_CACHE_DIR=~/gta` with `VICTORY_GAME_DIR=~/gta/game`, or -/// `[paths].cache_dir = "cache"` in a `victory.toml` kept inside the dump. -/// Compared like [`ensure_data_outside_cache`]: lexically, without the disk. -fn ensure_game_apart(game: &Path, cache: &Path, data: &Path, origins: &Origins) -> Result<()> { - if is_within(game, cache, FOLD_CASE) { - anyhow::bail!( - "the game folder {} (from {}) is inside the cache folder {} (from {}), which may \ - be deleted at any time; set VICTORY_CACHE_DIR or [paths].cache_dir to a folder \ - outside the game folder", - game.display(), - origins.game_dir, - cache.display(), - origins.cache_dir - ); - } - for (name, dir, origin, setting) in [ - ( - "cache", - cache, - origins.cache_dir, - "VICTORY_CACHE_DIR or [paths].cache_dir", - ), - ( - "data", - data, - origins.data_dir, - "VICTORY_DATA_DIR or [paths].data_dir", - ), - ] { - if is_within(dir, game, FOLD_CASE) { - anyhow::bail!( - "the {name} folder {} (from {origin}) is inside the game folder {} (from {}), \ - which holds your dump and is only read; set {setting} to a folder outside it", - dir.display(), - game.display(), - origins.game_dir - ); - } - } - Ok(()) -} - -/// Whether folder names differ only by case on the usual file systems of -/// this host: NTFS (Windows) and APFS (macOS) ignore case by default, so -/// there `C:\Victory\cache` holds `c:\victory\cache\data`. -const FOLD_CASE: bool = cfg!(any(windows, target_os = "macos")); - -/// Whether `path` is `parent` or inside it, compared like -/// [`ensure_data_outside_cache`] says: lexically (see [`lexical`]), and -/// ignoring ASCII case when `fold_case` (a parameter so both behaviours can -/// be tested on any host). Without folding, a cache of `C:\Victory` and a -/// data folder of `c:\victory\data` would be taken as unrelated on Windows -/// although they are one folder and its child. -fn is_within(path: &Path, parent: &Path, fold_case: bool) -> bool { - let path = lexical(path); - let parent = lexical(parent); - if !fold_case { - return path.starts_with(&parent); - } - let mut inner = path.components(); - parent.components().all(|p| { - inner.next().is_some_and(|c| { - c.as_os_str() - .as_encoded_bytes() - .eq_ignore_ascii_case(p.as_os_str().as_encoded_bytes()) - }) - }) -} - -/// `path` with `.` dropped and each `..` removing the component before it, -/// without reading the disk. A `..` with nothing left to remove is kept -/// (it cannot climb above the root, which [`Path::components`] already -/// keeps first). -fn lexical(path: &Path) -> PathBuf { - let mut out = PathBuf::new(); - for part in path.components() { - match part { - Component::CurDir => {} - Component::ParentDir => match out.components().next_back() { - Some(Component::Normal(_)) => { - out.pop(); - } - Some(Component::RootDir | Component::Prefix(_)) => {} - _ => out.push(".."), - }, - other => out.push(other), - } - } - out -} - -/// The checks every configured path goes through before it is used: no -/// control characters ([`ensure_no_control`]), no surrounding quotes -/// ([`ensure_unquoted`]), no surrounding whitespace ([`ensure_trimmed`]), -/// no unexpanded variable ([`ensure_no_variable`]) and no Windows drive -/// path off Windows ([`ensure_native`]). `what` names the setting for the -/// error. -fn check_setting(what: &str, path: &Path) -> Result<()> { - ensure_no_control(what, path)?; - ensure_unquoted(what, path)?; - ensure_trimmed(what, path)?; - ensure_no_variable(what, path)?; - ensure_native(what, path, cfg!(windows)) -} - -/// Refuses a path that names an environment variable instead of its value: -/// `$HOME/Games/gta`, `${XDG_DATA_HOME}/victory` or -/// `%LOCALAPPDATA%\victory` (the form `victory.example.toml` uses for the -/// defaults, so an easy one to copy). Only a shell (or `cmd` for `%...%`) -/// expands these; TOML, an env file read by `docker run --env-file` or -/// systemd, and a launcher or IDE run configuration keep them literally. -/// The path is then relative, so it would be taken as a folder named -/// `$HOME` under the config file's folder or the working directory (often -/// the repository) and reported later only as "does not exist" or "inside -/// the repository". Real folders like `$Recycle.Bin` or `100%` are left -/// alone: a `$` part must be a whole variable name (`$HOME`, not -/// `$HOME.old`), and `%` must enclose one. -fn ensure_no_variable(what: &str, path: &Path) -> Result<()> { - let text = path.to_string_lossy(); - let Some(var) = text.split(['/', '\\']).find_map(variable_in) else { - return Ok(()); - }; - anyhow::bail!( - "{what} is {}, which names the variable {var}; variables are not expanded in \ - the config file or when the value comes from an env file or a launcher rather \ - than a shell, so write the path out in full (a leading ~ is the home directory)", - path.display() - ); -} - -/// The variable reference in one path component, as written: the whole -/// component `$NAME`, or `${NAME}` or `%NAME%` anywhere in it. -fn variable_in(part: &str) -> Option<&str> { - let is_name = |s: &str| { - let mut chars = s.chars(); - chars - .next() - .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') - && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') - }; - if part.strip_prefix('$').is_some_and(is_name) { - return Some(part); - } - if let Some(start) = part.find("${") { - let rest = &part[start + 2..]; - if let Some(end) = rest.find('}') - && is_name(&rest[..end]) - { - return Some(&part[start..start + 2 + end + 1]); - } - } - // `%ProgramFiles(x86)%` is a real Windows variable. - let mut pieces = part.split('%'); - pieces.next(); - let mut offset = part.find('%')?; - for piece in pieces { - let name = piece.replace("(x86)", ""); - let closed = offset + 1 + piece.len() < part.len(); - if closed && is_name(&name) { - return Some(&part[offset..offset + piece.len() + 2]); - } - offset += piece.len() + 1; - } - None -} - -/// Refuses a path that starts or ends with whitespace (a space, or a -/// no-break space pasted from a web page). An env file or launcher keeps -/// what a shell would split off: `VICTORY_GAME_DIR= /games/gta` or a value -/// with a trailing space. A leading space makes the path relative, so it -/// would be taken as a folder named ` ` under the config file's folder or -/// the working directory (often the repository); a trailing one is reported -/// later only as "does not exist", which looks right on screen. Windows -/// strips trailing spaces from folder names, and no real dump or cache -/// folder starts or ends with one; spaces inside the name are left alone. -/// The error quotes the value so the space shows. -fn ensure_trimmed(what: &str, path: &Path) -> Result<()> { - let text = path.to_string_lossy(); - let (start, end) = match (text.chars().next(), text.chars().next_back()) { - (Some(s), Some(e)) => (s.is_whitespace(), e.is_whitespace()), - _ => return Ok(()), - }; - if !start && !end { - return Ok(()); - } - let place = match (start, end) { - (true, true) => "starts and ends", - (true, false) => "starts", - _ => "ends", - }; - anyhow::bail!("{what} is {text:?}, which {place} with whitespace; remove it"); -} - -/// Refuses a path wrapped in a matching pair of quotes (`"/games/gta"` or -/// `'/games/gta'`, quotes included). Only a shell removes them: an env file -/// read by `docker run --env-file`, systemd's `EnvironmentFile=` (single -/// quotes on older versions), an IDE run configuration or a Windows -/// `set VICTORY_GAME_DIR="D:\games"` keeps them as part of the value. The -/// path then starts with a quote, so it is not absolute and would be taken -/// as a folder named `"` under the working directory (often the -/// repository), reported later as "does not exist" or "inside the -/// repository". No real folder name starts and ends with the same quote, -/// and `"` cannot appear in a Windows path at all; a quote elsewhere in -/// the name (`/games/Rockstar's`) is left alone. -fn ensure_unquoted(what: &str, path: &Path) -> Result<()> { - let bytes = path.as_os_str().as_encoded_bytes(); - let quoted = match bytes { - [first, .., last] => first == last && matches!(first, b'"' | b'\''), - _ => false, - }; - if !quoted { - return Ok(()); - } - anyhow::bail!( - "{what} is {}, quotes included; the quotes are not removed when the value comes \ - from an env file or a launcher rather than a shell, so remove them", - path.display() - ); -} - -/// Refuses a path holding a control character (a carriage return, newline, -/// tab, ...). No real folder name has one, but a variable read from a -/// `.env` file with Windows line endings (`set -a; . ./victory.env`, an -/// env file for a container or a Proton/Wine wrapper) ends in an invisible -/// `\r`, and a value pasted from a document can carry a tab or newline. -/// Without this the path is reported later only as "does not exist", which -/// looks right on screen; the error quotes the value so the character shows. -fn ensure_no_control(what: &str, path: &Path) -> Result<()> { - let text = path.to_string_lossy(); - let Some(c) = text.chars().find(|c| c.is_control()) else { - return Ok(()); - }; - let hint = if c == '\r' { - " (a Windows line ending: was it read from a file saved with CRLF line endings?)" - } else { - "" - }; - anyhow::bail!( - "{what} is {text:?}, which contains the control character {c:?}{hint}; remove it" - ); -} - -/// Refuses a Windows drive path (`D:\games`, `D:/games`, `D:`) when the -/// host is not Windows (`on_windows` is `cfg!(windows)`, a parameter so the -/// check can be tested anywhere). There it is not absolute, so it would be -/// taken as a relative path: under the config file's folder, or the working -/// directory for a variable, which is often the repository. The example -/// config ships such a path, so copying it unedited on Linux is an easy way -/// to get here; the error names the setting instead of a confusing -/// "inside the repository" or "does not exist" later on. -fn ensure_native(what: &str, path: &Path, on_windows: bool) -> Result<()> { - if on_windows || !is_drive_path(path) { - return Ok(()); - } - anyhow::bail!( - "{what} is {}, a Windows path, but this host is not Windows; set it to a \ - path on this machine", - path.display() - ); -} - -/// `X:` followed by nothing, `\` or `/`. -fn is_drive_path(path: &Path) -> bool { - match path.as_os_str().as_encoded_bytes() { - [drive, b':'] => drive.is_ascii_alphabetic(), - [drive, b':', sep, ..] => drive.is_ascii_alphabetic() && matches!(sep, b'\\' | b'/'), - _ => false, - } -} - -/// `<root>/<sub>`, created. `sub` must be a plain relative path (names -/// only: no `..`, `.`, root or drive): [`Path::join`] with an absolute `sub` -/// would replace `root` outright, and a `..` would climb out of it, so a -/// title id or other computed part that came out wrong would write outside -/// the cache or data folder, possibly into the dump, without an error. fn subdir(root: &Path, sub: &str) -> Result<PathBuf> { - ensure_plain_subdir(sub)?; let dir = root.join(sub); ensure_outside_repo(&dir)?; std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?; Ok(dir) } -/// Refuses a `sub` for [`subdir`] that is empty or is not made only of -/// ordinary names. -fn ensure_plain_subdir(sub: &str) -> Result<()> { - let path = Path::new(sub); - let plain = !sub.is_empty() - && !is_drive_path(path) - && path.components().all(|c| matches!(c, Component::Normal(_))) - // `Path::components` drops interior `.`; refuse it all the same. - && !sub.split(['/', '\\']).any(|part| part == "." || part == ".."); - if !plain { - anyhow::bail!( - "internal error: subfolder {sub:?} is not a plain relative path; it would \ - leave the cache or data folder" - ); - } - Ok(()) -} - -/// The user's home directory: `HOME`, else `USERPROFILE` (Windows), when -/// set to an absolute path. -fn home_dir(env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> { - ["HOME", "USERPROFILE"] - .into_iter() - .filter_map(|k| env(k).map(PathBuf::from)) - .find(|p| p.is_absolute()) -} - -/// `~` and `~/rest` (`~\rest` on Windows) under `home`. Neither TOML nor a -/// quoted shell value expands `~`, so without this `game_dir = "~/games"` -/// would name a folder called `~`. `~user` is left alone, and so is -/// everything when there is no home directory. -fn expand_home(path: PathBuf, home: Option<&Path>) -> PathBuf { - let Some(home) = home else { return path }; - let mut parts = path.components(); - match parts.next() { - Some(Component::Normal(first)) if first == "~" => { - let rest = parts.as_path(); - if rest.as_os_str().is_empty() { - home.to_path_buf() - } else { - home.join(rest) - } - } - _ => path, - } -} - -#[derive(Clone, Copy)] -enum Kind { - Cache, - Data, -} - -/// `%LOCALAPPDATA%/victory/{cache,data}`. Without `LOCALAPPDATA` (a native -/// non-Windows host), the XDG base directories: the cache under -/// `$XDG_CACHE_HOME` (`~/.cache`), the data under `$XDG_DATA_HOME` -/// (`~/.local/share`), so clearing the user's cache does not take what titles -/// must keep with it. -/// -/// A variable that is set but empty or relative is skipped, as the XDG base -/// directory spec asks: otherwise `XDG_CACHE_HOME=` (or a relative value) -/// would put the directory under the working directory, which is often the -/// repository itself and so refused by the asset policy. -fn default_dir(kind: Kind, env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Result<PathBuf> { - let absolute = |k: &str| env(k).map(PathBuf::from).filter(|p| p.is_absolute()); - if let Some(local) = absolute("LOCALAPPDATA") { - let name = match kind { - Kind::Cache => "cache", - Kind::Data => "data", - }; - return Ok(local.join("victory").join(name)); - } - let (xdg, fallback) = match kind { - Kind::Cache => ("XDG_CACHE_HOME", Path::new(".cache")), - Kind::Data => ("XDG_DATA_HOME", Path::new(".local/share")), - }; - let base = absolute(xdg) - .or_else(|| absolute("HOME").map(|h| h.join(fallback))) +/// `%LOCALAPPDATA%/victory/<name>` (elsewhere the XDG or home cache). +fn default_dir(name: &str) -> Result<PathBuf> { + let base = std::env::var_os("LOCALAPPDATA") + .or_else(|| std::env::var_os("XDG_CACHE_HOME")) + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache"))) .context("cannot determine a user directory; set VICTORY_CACHE_DIR and VICTORY_DATA_DIR")?; - Ok(base.join("victory")) + Ok(base.join("victory").join(name)) } #[cfg(test)] @@ -743,14 +146,9 @@ mod tests { let file = FilePaths { game_dir: Some("from-file".into()), cache_dir: Some("cache-from-file".into()), - data_dir: Some("data-from-file".into()), ..Default::default() }; - let env = |k: &str| match k { - "VICTORY_GAME_DIR" => Some(OsString::from("from-env")), - "HOME" => Some(abs("home")), - _ => None, - }; + let env = |k: &str| (k == "VICTORY_GAME_DIR").then(|| OsString::from("from-env")); let cfg = Config::resolve(file, None, env).unwrap(); assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-env")); assert_eq!(cfg.cache_dir, PathBuf::from("cache-from-file")); @@ -762,832 +160,41 @@ mod tests { game_dir: Some("from-file".into()), ..Default::default() }; - let env = |k: &str| match k { - "VICTORY_GAME_DIR" => Some(OsString::new()), - "HOME" => Some(abs("home")), - _ => None, - }; + let env = |k: &str| (k == "VICTORY_GAME_DIR").then(OsString::new); let cfg = Config::resolve(file, None, env).unwrap(); assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-file")); } - fn defaults(vars: &[(&str, OsString)]) -> Config { - let env = |k: &str| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| v.clone()); - Config::resolve(FilePaths::default(), None, env).unwrap() - } - #[test] - fn local_app_data_holds_cache_and_data() { - let cfg = defaults(&[("LOCALAPPDATA", abs("l")), ("XDG_CACHE_HOME", abs("x"))]); - let base = PathBuf::from(abs("l")).join("victory"); - assert_eq!(cfg.cache_dir, base.join("cache")); - assert_eq!(cfg.data_dir, base.join("data")); - } - - #[test] - fn data_is_not_under_the_xdg_cache() { - let cfg = defaults(&[("XDG_CACHE_HOME", abs("c")), ("XDG_DATA_HOME", abs("d"))]); - assert_eq!(cfg.cache_dir, PathBuf::from(abs("c")).join("victory")); - assert_eq!(cfg.data_dir, PathBuf::from(abs("d")).join("victory")); - - let cfg = defaults(&[("HOME", abs("h"))]); - let home = PathBuf::from(abs("h")); - assert_eq!(cfg.cache_dir, home.join(".cache").join("victory")); - assert_eq!(cfg.data_dir, home.join(".local/share").join("victory")); - assert!(!cfg.data_dir.starts_with(&cfg.cache_dir)); - } - - #[test] - fn empty_or_relative_values_are_ignored() { - let cfg = defaults(&[ - ("LOCALAPPDATA", OsString::new()), - ("XDG_CACHE_HOME", OsString::new()), - ("XDG_DATA_HOME", OsString::from("relative")), - ("HOME", abs("h")), - ]); - let home = PathBuf::from(abs("h")); - assert_eq!(cfg.cache_dir, home.join(".cache").join("victory")); - assert_eq!(cfg.data_dir, home.join(".local/share").join("victory")); - - // A relative LOCALAPPDATA or XDG_CACHE_HOME falls through as well. - let cfg = defaults(&[ - ("LOCALAPPDATA", OsString::from("relative/lad")), - ("XDG_CACHE_HOME", OsString::from("relative/cache")), - ("HOME", abs("h")), - ]); - assert_eq!(cfg.cache_dir, home.join(".cache").join("victory")); - } - - #[test] - fn default_dir_prefers_localappdata_then_xdg_then_home() { - let all = |k: &str| match k { - "LOCALAPPDATA" => Some(abs("lad")), - "XDG_CACHE_HOME" => Some(abs("xdg")), - "HOME" => Some(abs("home")), - _ => None, - }; - assert_eq!( - default_dir(Kind::Cache, all).unwrap(), - PathBuf::from(abs("lad")).join("victory").join("cache") - ); - let no_lad = |k: &str| if k == "LOCALAPPDATA" { None } else { all(k) }; - assert_eq!( - default_dir(Kind::Cache, no_lad).unwrap(), - PathBuf::from(abs("xdg")).join("victory") - ); - let home_only = |k: &str| (k == "HOME").then(|| abs("home")); - assert_eq!( - default_dir(Kind::Cache, home_only).unwrap(), - PathBuf::from(abs("home")).join(".cache").join("victory") - ); - } - - #[test] - fn no_user_directory_is_an_error() { - let env = |_: &str| None; - assert!(Config::resolve(FilePaths::default(), None, env).is_err()); - let nothing_usable = |k: &str| (k == "HOME").then(OsString::new); - assert!(default_dir(Kind::Cache, nothing_usable).is_err()); - assert!(default_dir(Kind::Data, nothing_usable).is_err()); - } - - #[test] - fn empty_test_titles_variable_falls_back_to_the_file() { + fn empty_test_titles_env_is_ignored() { let file = FilePaths { test_titles: vec!["from-file".into()], ..Default::default() }; - let env = |k: &str| match k { - "VICTORY_TEST_TITLES" => Some(OsString::new()), - "HOME" => Some(abs("home")), - _ => None, - }; + let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(OsString::new); let cfg = Config::resolve(file, None, env).unwrap(); assert_eq!(cfg.test_titles, vec![PathBuf::from("from-file")]); } #[test] - fn relative_file_paths_are_relative_to_the_file() { - let text = format!( - "[paths]\ngame_dir = 'game'\ncache_dir = {:?}\ntest_titles = ['t/one']\n", - PathBuf::from(abs("elsewhere")).display().to_string() - ); - let parsed: FileConfig = toml::from_str(&text).unwrap(); - let dir = PathBuf::from(abs("configs")); - let paths = parsed.anchored_at(&dir, None).unwrap(); - assert_eq!(paths.game_dir.unwrap(), dir.join("game")); - // Absolute paths are kept as written. - assert_eq!(paths.cache_dir.unwrap(), PathBuf::from(abs("elsewhere"))); - assert_eq!(paths.data_dir, None); - assert_eq!(paths.test_titles, vec![dir.join("t/one")]); - } - - #[test] - fn empty_file_values_count_as_unset() { - let text = "[paths]\ngame_dir = ''\ncache_dir = \"\"\ndata_dir = ''\n\ - test_titles = ['', 't/one', '']\n"; - let parsed: FileConfig = toml::from_str(text).unwrap(); - let dir = PathBuf::from(abs("configs")); - let paths = parsed.anchored_at(&dir, None).unwrap(); - // Not the config file's folder. - assert_eq!(paths.game_dir, None); - assert_eq!(paths.cache_dir, None); - assert_eq!(paths.data_dir, None); - assert_eq!(paths.test_titles, vec![dir.join("t/one")]); - // With `./victory.toml` they are not the empty path either, and the - // defaults apply with nothing said to come from the file. - let parsed: FileConfig = toml::from_str(text).unwrap(); - let paths = parsed.anchored_at(Path::new(""), None).unwrap(); - let env = |k: &str| match k { - "HOME" => Some(abs("home")), - _ => None, - }; - let cfg = Config::resolve(paths, None, env).unwrap(); - assert_eq!(cfg.game_dir, None); - assert!(cfg.cache_dir.is_absolute(), "{}", cfg.cache_dir.display()); - assert!(cfg.data_dir.is_absolute(), "{}", cfg.data_dir.display()); - assert_eq!(cfg.origins.game_dir, Origin::Default); - assert_eq!(cfg.origins.cache_dir, Origin::Default); - assert_eq!(cfg.origins.data_dir, Origin::Default); - assert_eq!(cfg.test_titles, vec![PathBuf::from("t/one")]); - assert_eq!(cfg.origins.test_titles, Origin::File); - } - - #[test] - fn the_default_config_file_keeps_paths_as_written() { - // `./victory.toml` has an empty parent, so nothing changes. - let parsed: FileConfig = toml::from_str("[paths]\ngame_dir = 'game'\n").unwrap(); - let paths = parsed.anchored_at(Path::new(""), None).unwrap(); - assert_eq!(paths.game_dir.unwrap(), PathBuf::from("game")); - } - - #[test] - fn a_leading_tilde_is_the_home_directory() { - let home = PathBuf::from(abs("home")); - let h = Some(home.as_path()); - assert_eq!(expand_home("~".into(), h), home); - assert_eq!(expand_home("~/games/gta".into(), h), home.join("games/gta")); - // Only a whole leading `~` component counts. - assert_eq!(expand_home("~user/x".into(), h), PathBuf::from("~user/x")); - assert_eq!(expand_home("a/~/b".into(), h), PathBuf::from("a/~/b")); - // Without a home directory nothing changes. - assert_eq!(expand_home("~/x".into(), None), PathBuf::from("~/x")); - } - - #[test] - fn tilde_in_the_file_is_home_not_next_to_the_file() { - let parsed: FileConfig = - toml::from_str("[paths]\ngame_dir = '~/games/gta'\ntest_titles = ['~/t']\n").unwrap(); - let home = PathBuf::from(abs("home")); - let paths = parsed - .anchored_at(&PathBuf::from(abs("configs")), Some(&home)) - .unwrap(); - assert_eq!(paths.game_dir.unwrap(), home.join("games/gta")); - assert_eq!(paths.test_titles, vec![home.join("t")]); - } - - #[test] - fn tilde_in_variables_is_home() { - let sep = if cfg!(windows) { ";" } else { ":" }; - let titles = format!("~/one{sep}~/two"); - let env = |k: &str| match k { - "VICTORY_GAME_DIR" => Some(OsString::from("~/games/gta")), - "VICTORY_CACHE_DIR" => Some(OsString::from("~/cache")), - "VICTORY_TEST_TITLES" => Some(OsString::from(&titles)), - "HOME" => Some(abs("home")), - _ => None, - }; - let cfg = Config::resolve(FilePaths::default(), None, env).unwrap(); - let home = PathBuf::from(abs("home")); - assert_eq!(cfg.game_dir.unwrap(), home.join("games/gta")); - assert_eq!(cfg.cache_dir, home.join("cache")); - assert_eq!(cfg.test_titles, vec![home.join("one"), home.join("two")]); - } - - #[test] - fn home_dir_falls_back_to_userprofile_and_skips_relative() { - let env = |k: &str| match k { - "HOME" => Some(OsString::from("relative")), - "USERPROFILE" => Some(abs("profile")), - _ => None, - }; - assert_eq!(home_dir(env), Some(PathBuf::from(abs("profile")))); - assert_eq!(home_dir(|_: &str| None), None); - } - - #[test] - fn victory_config_expands_tilde_and_ignores_empty() { - let home = PathBuf::from(abs("home")); - let with = |v: &'static str| move |k: &str| (k == "VICTORY_CONFIG").then(|| v.into()); - assert_eq!( - explicit_config(with("~/victory.toml"), Some(&home)).unwrap(), - Some(home.join("victory.toml")) - ); - assert_eq!(explicit_config(with(""), Some(&home)).unwrap(), None); - assert_eq!(explicit_config(|_: &str| None, Some(&home)).unwrap(), None); - // Without a home directory the value is taken as written. - assert_eq!( - explicit_config(with("~/victory.toml"), None).unwrap(), - Some(PathBuf::from("~/victory.toml")) - ); - } - - #[test] - fn control_characters_in_paths_are_refused() { - // A CRLF `.env` file leaves a `\r` on the end of every value. - let err = ensure_no_control("VICTORY_GAME_DIR", Path::new("/games/gta\r")) - .unwrap_err() - .to_string(); - assert!(err.contains("VICTORY_GAME_DIR"), "{err}"); - assert!(err.contains("\"/games/gta\\r\""), "{err}"); - assert!(err.contains("CRLF"), "{err}"); - let err = ensure_no_control("[paths].data_dir", Path::new("/a\tb")) - .unwrap_err() - .to_string(); - assert!(err.contains("'\\t'"), "{err}"); - assert!(!err.contains("CRLF"), "{err}"); - for ok in ["/games/gta", "games with spaces", "~/jeux/été", ""] { - assert!(ensure_no_control("x", Path::new(ok)).is_ok(), "{ok}"); - } - - // Every way in: each path variable, VICTORY_CONFIG and the file. - for var in [ - "VICTORY_GAME_DIR", - "VICTORY_CACHE_DIR", - "VICTORY_DATA_DIR", - "VICTORY_TEST_TITLES", - ] { - let env = |k: &str| match k { - k if k == var => Some(OsString::from("/victory/x\r")), - "HOME" => Some(abs("home")), - _ => None, - }; - let err = Config::resolve(FilePaths::default(), None, env) - .unwrap_err() - .to_string(); - assert!(err.contains(var), "{err}"); - } - let env = |k: &str| (k == "VICTORY_CONFIG").then(|| OsString::from("victory.toml\r")); - let err = explicit_config(env, None).unwrap_err().to_string(); - assert!(err.contains("VICTORY_CONFIG"), "{err}"); - let parsed: FileConfig = toml::from_str("[paths]\ncache_dir = \"cache\\n\"\n").unwrap(); - let err = parsed - .anchored_at(Path::new("/configs"), None) - .unwrap_err() - .to_string(); - assert!(err.contains("[paths].cache_dir"), "{err}"); - } - - #[test] - fn quoted_paths_are_refused() { - // `docker run --env-file` keeps the quotes of `VICTORY_GAME_DIR="/games/gta"`. - let err = ensure_unquoted("VICTORY_GAME_DIR", Path::new("\"/games/gta\"")) - .unwrap_err() - .to_string(); - assert!(err.contains("VICTORY_GAME_DIR"), "{err}"); - assert!(err.contains("\"/games/gta\""), "{err}"); - assert!(err.contains("quotes included"), "{err}"); - assert!(ensure_unquoted("x", Path::new("'~/gta'")).is_err()); - for ok in [ - "/games/gta", - "/games/Rockstar's", - "'/games/gta\"", - "\"", - "'", - "", - "games with spaces", - ] { - assert!(ensure_unquoted("x", Path::new(ok)).is_ok(), "{ok}"); - } - - // Every way in: each path variable, VICTORY_CONFIG and the file. - for var in [ - "VICTORY_GAME_DIR", - "VICTORY_CACHE_DIR", - "VICTORY_DATA_DIR", - "VICTORY_TEST_TITLES", - ] { - let env = |k: &str| match k { - k if k == var => Some(OsString::from("\"/victory/x\"")), - "HOME" => Some(abs("home")), - _ => None, - }; - let err = Config::resolve(FilePaths::default(), None, env) - .unwrap_err() - .to_string(); - assert!(err.contains(var), "{err}"); - assert!(err.contains("quotes included"), "{err}"); - } - let env = |k: &str| (k == "VICTORY_CONFIG").then(|| OsString::from("'victory.toml'")); - let err = explicit_config(env, None).unwrap_err().to_string(); - assert!(err.contains("VICTORY_CONFIG"), "{err}"); - let parsed: FileConfig = toml::from_str("[paths]\ngame_dir = '\"/games/gta\"'\n").unwrap(); - let err = parsed - .anchored_at(Path::new("/configs"), None) - .unwrap_err() - .to_string(); - assert!(err.contains("[paths].game_dir"), "{err}"); - } - - #[test] - fn surrounding_whitespace_in_paths_is_refused() { - let err = ensure_trimmed("VICTORY_GAME_DIR", Path::new(" /games/gta")) - .unwrap_err() - .to_string(); - assert!(err.contains("VICTORY_GAME_DIR"), "{err}"); - assert!(err.contains("\" /games/gta\""), "{err}"); - assert!(err.contains("starts with whitespace"), "{err}"); - let err = ensure_trimmed("x", Path::new("/games/gta ")) - .unwrap_err() - .to_string(); - assert!(err.contains("ends with whitespace"), "{err}"); - let err = ensure_trimmed("x", Path::new(" a ")) - .unwrap_err() - .to_string(); - assert!(err.contains("starts and ends"), "{err}"); - // A no-break space pasted from a web page. - assert!(ensure_trimmed("x", Path::new("/games/gta\u{a0}")).is_err()); - for ok in [ - "/games/gta", - "games with spaces", - "/Program Files/x", - "~/é", - "", - ] { - assert!(ensure_trimmed("x", Path::new(ok)).is_ok(), "{ok}"); - } - - // Every way in: each path variable, VICTORY_CONFIG and the file. - for var in [ - "VICTORY_GAME_DIR", - "VICTORY_CACHE_DIR", - "VICTORY_DATA_DIR", - "VICTORY_TEST_TITLES", - ] { - let env = |k: &str| match k { - k if k == var => Some(OsString::from(" /victory/x")), - "HOME" => Some(abs("home")), - _ => None, - }; - let err = Config::resolve(FilePaths::default(), None, env) - .unwrap_err() - .to_string(); - assert!(err.contains(var), "{err}"); - assert!(err.contains("whitespace"), "{err}"); - } - // The second of several test titles, after the separator. - let sep = if cfg!(windows) { ";" } else { ":" }; - let titles = OsString::from(format!("/victory/a{sep} /victory/b")); - let env = |k: &str| match k { - "VICTORY_TEST_TITLES" => Some(titles.clone()), - "HOME" => Some(abs("home")), - _ => None, - }; - let err = Config::resolve(FilePaths::default(), None, env) - .unwrap_err() - .to_string(); - assert!(err.contains("\" /victory/b\""), "{err}"); - let env = |k: &str| (k == "VICTORY_CONFIG").then(|| OsString::from("victory.toml ")); - let err = explicit_config(env, None).unwrap_err().to_string(); - assert!(err.contains("VICTORY_CONFIG"), "{err}"); - let parsed: FileConfig = toml::from_str("[paths]\ndata_dir = ' data'\n").unwrap(); - let err = parsed - .anchored_at(Path::new("/configs"), None) - .unwrap_err() - .to_string(); - assert!(err.contains("[paths].data_dir"), "{err}"); - } - - #[test] - fn unexpanded_variables_in_paths_are_refused() { - // An env file or the config file keeps `$HOME` literally. - let err = ensure_no_variable("VICTORY_GAME_DIR", Path::new("$HOME/Games/gta")) - .unwrap_err() - .to_string(); - assert!(err.contains("VICTORY_GAME_DIR"), "{err}"); - assert!(err.contains("the variable $HOME;"), "{err}"); - assert!(err.contains("~ is the home directory"), "{err}"); - for (path, var) in [ - ("${XDG_DATA_HOME}/victory", "${XDG_DATA_HOME}"), - ("/srv/${USER}-victory/cache", "${USER}"), - ("/home/$USER/gta", "$USER"), - ("%LOCALAPPDATA%\\victory\\cache", "%LOCALAPPDATA%"), - ("%LocalAppData%/victory", "%LocalAppData%"), - ("%ProgramFiles(x86)%\\gta", "%ProgramFiles(x86)%"), - ("~/%USERNAME%-gta", "%USERNAME%"), - ] { - let err = ensure_no_variable("x", Path::new(path)) - .unwrap_err() - .to_string(); - assert!( - err.contains(&format!("the variable {var};")), - "{path}: {err}" - ); - } - // Real folder names with `$` or `%` in them. - for ok in [ - "/games/gta", - "C:\\$Recycle.Bin\\x", - "/mnt/share$/gta", - "/games/$HOME.old", - "/games/100%", - "/games/50% off/x", - "/a/${}/b", - "/a/$/b", - "/a/%%/b", - "~/games", - "", - ] { - assert!(ensure_no_variable("x", Path::new(ok)).is_ok(), "{ok}"); - } - - // Every way in: each path variable, VICTORY_CONFIG and the file. - for var in [ - "VICTORY_GAME_DIR", - "VICTORY_CACHE_DIR", - "VICTORY_DATA_DIR", - "VICTORY_TEST_TITLES", - ] { - let env = |k: &str| match k { - k if k == var => Some(OsString::from("$HOME/victory/x")), - "HOME" => Some(abs("home")), - _ => None, - }; - let err = Config::resolve(FilePaths::default(), None, env) - .unwrap_err() - .to_string(); - assert!(err.contains(var), "{err}"); - assert!(err.contains("$HOME"), "{err}"); - } - let env = |k: &str| { - (k == "VICTORY_CONFIG").then(|| OsString::from("${XDG_CONFIG_HOME}/victory.toml")) - }; - let err = explicit_config(env, None).unwrap_err().to_string(); - assert!(err.contains("VICTORY_CONFIG"), "{err}"); - let parsed: FileConfig = - toml::from_str("[paths]\ndata_dir = '%LOCALAPPDATA%\\victory\\data'\n").unwrap(); - let err = parsed - .anchored_at(Path::new("/configs"), None) - .unwrap_err() - .to_string(); - assert!(err.contains("[paths].data_dir"), "{err}"); - assert!(err.contains("%LOCALAPPDATA%"), "{err}"); - } - - #[test] - fn victory_config_must_name_a_file() { - let dir = std::env::temp_dir().join(format!("victory-config-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("victory.toml"); - let _ = std::fs::remove_file(&file); - - let err = config_file(Some(dir.clone())).unwrap_err().to_string(); - assert!(err.contains("is a folder"), "{err}"); - assert!(!err.contains("did you mean"), "{err}"); - - std::fs::write(&file, "").unwrap(); - let err = config_file(Some(dir.clone())).unwrap_err().to_string(); - assert!(err.contains("did you mean"), "{err}"); - assert!(err.contains(&file.display().to_string()), "{err}"); - assert_eq!(config_file(Some(file.clone())).unwrap(), Some(file.clone())); - - let missing = dir.join("missing.toml"); - let err = config_file(Some(missing)).unwrap_err().to_string(); - assert!(err.contains("does not exist"), "{err}"); - std::fs::remove_dir_all(&dir).unwrap(); - } - - #[test] - fn data_inside_the_cache_is_refused() { - let env = |k: &str| match k { - "VICTORY_CACHE_DIR" => Some(abs("v")), - "VICTORY_DATA_DIR" => Some(PathBuf::from(abs("v")).join("data").into()), - _ => None, - }; - let err = Config::resolve(FilePaths::default(), None, env) - .unwrap_err() - .to_string(); - assert!(err.contains("inside the cache folder"), "{err}"); - - // The same folder for both counts as inside. - let same = |k: &str| match k { - "VICTORY_CACHE_DIR" | "VICTORY_DATA_DIR" => Some(abs("v")), - _ => None, - }; - assert!(Config::resolve(FilePaths::default(), None, same).is_err()); - - // A sibling whose name merely starts with the cache's is fine, and so - // is the cache inside the data folder. - let sibling = |k: &str| match k { - "VICTORY_CACHE_DIR" => Some(abs("v")), - "VICTORY_DATA_DIR" => Some(abs("v-data")), - _ => None, - }; - assert!(Config::resolve(FilePaths::default(), None, sibling).is_ok()); - let cache_in_data = |k: &str| match k { - "VICTORY_CACHE_DIR" => Some(PathBuf::from(abs("v")).join("cache").into()), - "VICTORY_DATA_DIR" => Some(abs("v")), - _ => None, - }; - assert!(Config::resolve(FilePaths::default(), None, cache_in_data).is_ok()); - } - - #[test] - fn data_inside_the_cache_ignores_dot_dot() { - let with = |cache: PathBuf, data: PathBuf| { - move |k: &str| match k { - "VICTORY_CACHE_DIR" => Some(cache.clone().into_os_string()), - "VICTORY_DATA_DIR" => Some(data.clone().into_os_string()), - _ => None, - } - }; - let v = PathBuf::from(abs("v")); - // `v/cache/../data` is `v/data`, a sibling of the cache: allowed. - let sibling = with(v.join("cache"), v.join("cache").join("..").join("data")); - assert!(Config::resolve(FilePaths::default(), None, sibling).is_ok()); - // A cache of `v/tmp/..` is `v`, which holds `v/./data`: refused. - let inside = with(v.join("tmp").join(".."), v.join(".").join("data")); - let err = Config::resolve(FilePaths::default(), None, inside) - .unwrap_err() - .to_string(); - assert!(err.contains("inside the cache folder"), "{err}"); - } - - #[test] - fn game_folder_is_kept_apart_from_cache_and_data() { - let with = |game: PathBuf, cache: PathBuf, data: PathBuf| { - move |k: &str| match k { - "VICTORY_GAME_DIR" => Some(game.clone().into_os_string()), - "VICTORY_CACHE_DIR" => Some(cache.clone().into_os_string()), - "VICTORY_DATA_DIR" => Some(data.clone().into_os_string()), - _ => None, - } - }; - let v = PathBuf::from(abs("v")); - let err = |env| { - Config::resolve(FilePaths::default(), None, env) - .unwrap_err() - .to_string() - }; - - // The game inside (or equal to) the cache would go with it. - let e = err(with(v.join("game"), v.clone(), v.join("..").join("data"))); - assert!(e.contains("game folder"), "{e}"); - assert!(e.contains("inside the cache folder"), "{e}"); - assert!(e.contains("(from VICTORY_GAME_DIR)"), "{e}"); - let e = err(with(v.clone(), v.clone(), PathBuf::from(abs("d")))); - assert!(e.contains("inside the cache folder"), "{e}"); - - // The cache or the data inside the game would write into the dump. - let e = err(with(v.clone(), v.join("cache"), PathBuf::from(abs("d")))); - assert!(e.contains("cache folder"), "{e}"); - assert!(e.contains("inside the game folder"), "{e}"); - let e = err(with(v.clone(), PathBuf::from(abs("c")), v.join("saves"))); - assert!(e.contains("data folder"), "{e}"); - assert!(e.contains("(from VICTORY_DATA_DIR)"), "{e}"); - // `.` and `..` are folded first: `v/../c` is outside `v`. - let e = err(with( - v.join("."), - v.join("x").join("..").join("c"), - v.join("..").join("d"), - )); - assert!(e.contains("inside the game folder"), "{e}"); - - // Siblings are fine, including one whose name starts with the game's. - let ok = with( - v.clone(), - PathBuf::from(abs("v-cache")), - PathBuf::from(abs("v-data")), - ); - assert!(Config::resolve(FilePaths::default(), None, ok).is_ok()); - let ok = with( - v.join("game"), - v.join("cache"), - v.join("game").join("..").join("data"), - ); - assert!(Config::resolve(FilePaths::default(), None, ok).is_ok()); - - // Without a game folder there is nothing to check. - let none = |k: &str| match k { - "VICTORY_CACHE_DIR" => Some(abs("c")), - "VICTORY_DATA_DIR" => Some(abs("d")), - _ => None, - }; - assert!(Config::resolve(FilePaths::default(), None, none).is_ok()); - } - - #[test] - fn a_config_file_inside_the_dump_cannot_put_the_cache_there() { - // `victory.toml` kept in the game folder with `cache_dir = "cache"`: - // anchored at the file, the cache lands inside the dump. - let dump = PathBuf::from(abs("gta")); - let parsed = parse_file("[paths]\ngame_dir = '.'\ncache_dir = 'cache'\n").unwrap(); - let paths = parsed.anchored_at(&dump, None).unwrap(); - let env = |k: &str| (k == "VICTORY_DATA_DIR").then(|| abs("d")); - let err = Config::resolve(paths, None, env).unwrap_err().to_string(); - assert!(err.contains("inside the game folder"), "{err}"); - assert!(err.contains("(from config file)"), "{err}"); - } - - #[test] - fn lexical_folds_dot_and_dot_dot() { - let l = |p: &str| lexical(Path::new(p)); - assert_eq!(l("a/./b/../c"), PathBuf::from("a/c")); - assert_eq!(l("../a/.."), PathBuf::from("..")); - assert_eq!(l("a/../../b"), PathBuf::from("../b")); - #[cfg(unix)] - { - assert_eq!(l("/../a"), PathBuf::from("/a")); - assert_eq!(l("/x/y/../../z"), PathBuf::from("/z")); - } - } - - #[test] - fn origins_name_the_setting_that_won() { - let file = FilePaths { - game_dir: Some(abs("file-game").into()), - cache_dir: Some(abs("file-cache").into()), - test_titles: vec![abs("file-title").into()], - ..Default::default() - }; - let env = |k: &str| match k { - "VICTORY_GAME_DIR" => Some(abs("env-game")), - "HOME" => Some(abs("home")), - _ => None, - }; + fn test_titles_env_splits_paths() { + let value = std::env::join_paths(["first", "second"]).unwrap(); + let file = FilePaths::default(); + let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(|| value.clone()); let cfg = Config::resolve(file, None, env).unwrap(); assert_eq!( - cfg.origins, - Origins { - game_dir: Origin::Env("VICTORY_GAME_DIR"), - cache_dir: Origin::File, - data_dir: Origin::Default, - test_titles: Origin::File, - } - ); - - // Empty variables are unset, so they are not the origin either. - let env = |k: &str| match k { - "VICTORY_CACHE_DIR" | "VICTORY_TEST_TITLES" => Some(OsString::new()), - "VICTORY_DATA_DIR" => Some(abs("env-data")), - "HOME" => Some(abs("home")), - _ => None, - }; - let cfg = Config::resolve(FilePaths::default(), None, env).unwrap(); - assert_eq!( - cfg.origins, - Origins { - game_dir: Origin::Default, - cache_dir: Origin::Default, - data_dir: Origin::Env("VICTORY_DATA_DIR"), - test_titles: Origin::Default, - } - ); - assert_eq!( - Origin::Env("VICTORY_DATA_DIR").to_string(), - "VICTORY_DATA_DIR" + cfg.test_titles, + vec![PathBuf::from("first"), PathBuf::from("second")] ); - assert_eq!(Origin::File.to_string(), "config file"); - assert_eq!(Origin::Default.to_string(), "default"); - } - - #[test] - fn data_inside_the_cache_names_both_origins() { - // The cache from the file is the home folder, which holds the - // default data folder: the error must say which setting is which. - let file = FilePaths { - cache_dir: Some(abs("home").into()), - ..Default::default() - }; - let env = |k: &str| (k == "HOME").then(|| abs("home")); - let err = Config::resolve(file, None, env).unwrap_err().to_string(); - assert!(err.contains("(from default)"), "{err}"); - assert!(err.contains("(from config file)"), "{err}"); - } - - #[test] - fn windows_drive_paths_are_refused_off_windows() { - for p in ["D:\\victory-data\\game", "d:/games", "D:"] { - assert!(is_drive_path(Path::new(p)), "{p}"); - let err = ensure_native("[paths].game_dir", Path::new(p), false) - .unwrap_err() - .to_string(); - assert!(err.contains("[paths].game_dir"), "{err}"); - assert!(err.contains("Windows path"), "{err}"); - assert!(ensure_native("[paths].game_dir", Path::new(p), true).is_ok()); - } - for p in [ - "/home/me/games", - "games", - "~/games", - "DD:/x", - "1:/x", - "D:x", - "", - ] { - assert!(!is_drive_path(Path::new(p)), "{p}"); - assert!(ensure_native("x", Path::new(p), false).is_ok()); - } - if cfg!(windows) { - return; - } - // Through the file and the variables, naming the setting. - let parsed: FileConfig = - toml::from_str("[paths]\ntest_titles = ['ok', 'E:\\\\t']\n").unwrap(); - let err = parsed - .anchored_at(Path::new("/configs"), None) - .unwrap_err() - .to_string(); - assert!(err.contains("[paths].test_titles"), "{err}"); - for var in [ - "VICTORY_GAME_DIR", - "VICTORY_DATA_DIR", - "VICTORY_TEST_TITLES", - ] { - let env = |k: &str| match k { - k if k == var => Some(OsString::from("D:\\victory")), - "HOME" => Some(abs("home")), - _ => None, - }; - let err = Config::resolve(FilePaths::default(), None, env) - .unwrap_err() - .to_string(); - assert!(err.contains(var), "{err}"); - } } #[test] fn example_config_parses() { let text = include_str!("../../../victory.example.toml"); - let parsed = parse_file(text).unwrap(); + let parsed: FileConfig = toml::from_str(text).unwrap(); assert!(parsed.paths.game_dir.is_some()); } - #[test] - fn top_level_path_keys_say_where_they_belong() { - let err = format!( - "{:#}", - parse_file("game_dir = '/games/gta'\n").expect_err("refused") - ); - assert!( - err.contains("game_dir must be under the [paths] table"), - "{err}" - ); - - // Above the header, two keys, and a [paths] table that is fine. - let text = "cache_dir = 'c'\ntest_titles = []\n[paths]\ndata_dir = 'd'\n"; - let err = format!("{:#}", parse_file(text).expect_err("refused")); - assert!( - err.contains("cache_dir, test_titles must be under"), - "{err}" - ); - assert!(err.contains("above them"), "{err}"); - - // Other mistakes keep the parser's own message. - let err = format!("{:#}", parse_file("[path]\n").expect_err("refused")); - assert!(err.contains("path"), "{err}"); - assert!(!err.contains("must be under"), "{err}"); - let err = format!( - "{:#}", - parse_file("[paths]\ngamedir = 'x'\n").expect_err("refused") - ); - assert!(err.contains("gamedir"), "{err}"); - - // A correct file still parses. - let parsed = parse_file("[paths]\ngame_dir = '/games/gta'\n").expect("parses"); - assert_eq!(parsed.paths.game_dir, Some(PathBuf::from("/games/gta"))); - } - - #[test] - fn subfolders_must_stay_inside_their_root() { - for ok in ["images", "0000ABCD/storage", "a/b/c"] { - assert!(ensure_plain_subdir(ok).is_ok(), "{ok}"); - } - for bad in [ - "", - "/etc", - "../escape", - "a/../../b", - "a/./b", - ".", - "..", - "C:\\x", - "C:/x", - "a\\..\\b", - ] { - let err = ensure_plain_subdir(bad).unwrap_err().to_string(); - assert!(err.contains("not a plain relative path"), "{bad}: {err}"); - } - // Refused before anything is created: the root need not exist. - let cfg = Config { - cache_dir: PathBuf::from("/nonexistent-victory-test-root"), - data_dir: PathBuf::from("/nonexistent-victory-test-data"), - ..Default::default() - }; - assert!(cfg.cache_subdir("/tmp").is_err()); - assert!(cfg.data_subdir("../x").is_err()); - } - #[test] fn cache_inside_repo_is_refused() { let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache"); @@ -1607,49 +214,4 @@ mod tests { }; assert!(cfg.data_subdir("x").is_err()); } - - /// A path that is absolute on the host (`/x` is not absolute on Windows). - #[test] - fn folder_overlap_folds_case_only_when_asked() { - let cache = Path::new("/Victory/Cache"); - assert!(is_within(Path::new("/victory/cache/data"), cache, true)); - assert!(is_within(Path::new("/VICTORY/CACHE"), cache, true)); - assert!(!is_within(Path::new("/victory/cache/data"), cache, false)); - assert!(is_within(Path::new("/Victory/Cache/data"), cache, false)); - // Still whole components, and still with `..` folded first. - assert!(!is_within(Path::new("/victory/cachex"), cache, true)); - assert!(!is_within(Path::new("/victory/cache/../data"), cache, true)); - assert!(!is_within(Path::new("/victory"), cache, true)); - } - - #[test] - fn shared_xdg_base_names_the_xdg_variables() { - let base = abs("shared"); - let env = |k: &str| match k { - "XDG_CACHE_HOME" | "XDG_DATA_HOME" => Some(base.clone()), - _ => None, - }; - let err = Config::resolve(FilePaths::default(), None, env) - .unwrap_err() - .to_string(); - assert!(err.contains("XDG_DATA_HOME is inside"), "{err}"); - assert!(err.contains("VICTORY_DATA_DIR"), "{err}"); - // Overriding either folder is the way out. - let data = abs("elsewhere"); - let env = |k: &str| match k { - "XDG_CACHE_HOME" | "XDG_DATA_HOME" => Some(base.clone()), - "VICTORY_DATA_DIR" => Some(data.clone()), - _ => None, - }; - let cfg = Config::resolve(FilePaths::default(), None, env).unwrap(); - assert_eq!(cfg.data_dir, PathBuf::from(&data)); - } - - fn abs(p: &str) -> OsString { - if cfg!(windows) { - format!("C:\\{p}").into() - } else { - format!("/{p}").into() - } - } } diff --git a/crates/victory-core/src/diagnostics.rs b/crates/victory-core/src/diagnostics.rs deleted file mode 100644 index 2ca46e556e..0000000000 --- a/crates/victory-core/src/diagnostics.rs +++ /dev/null @@ -1,319 +0,0 @@ -//! Opt-in JSONL for structured failures at selected emulator boundaries. - -use std::fs::{File, OpenOptions}; -use std::io::{self, Write}; -use std::path::Path; -use std::sync::{Mutex, OnceLock}; -use std::time::{Instant, SystemTime, UNIX_EPOCH}; - -use serde_json::{Value, json}; - -const MAX_FILE_BYTES: u64 = 4 * 1024 * 1024; -const FOOTER_BYTES: u64 = 1024; -const WIN32_CODES: &str = - "https://learn.microsoft.com/windows/win32/debug/system-error-codes--0-499-"; -static SESSION: OnceLock<Session> = OnceLock::new(); - -struct Session { - id: String, - state: Mutex<State>, -} - -struct State { - file: File, - bytes: u64, - sequence: u64, - dropped: u64, - failed: bool, - finished: bool, -} - -/// Open a new output file outside any VIctory source tree. -pub fn start(path: &Path) -> anyhow::Result<()> { - crate::ensure_outside_repo(path)?; - let file = OpenOptions::new().write(true).create_new(true).open(path)?; - let session = Session::new(file); - session.event( - "session.started", - json!({ - "level": "INFO", - "victory_version": env!("CARGO_PKG_VERSION"), - "git_commit": option_env!("VICTORY_BUILD_COMMIT").filter(|commit| { - matches!(commit.len(), 40 | 64) && commit.bytes().all(|byte| byte.is_ascii_hexdigit()) - }), - "platform": std::env::consts::OS, - "architecture": std::env::consts::ARCH, - "diagnostics_feature": cfg!(feature = "diagnostics"), - }), - ); - SESSION - .set(session) - .map_err(|_| anyhow::anyhow!("a diagnostic session is already active")) -} - -/// Capture a monotonic start time only when structured diagnostics are active. -pub fn operation_started() -> Option<Instant> { - SESSION.get().map(|_| Instant::now()) -} - -/// End the CLI session, including the number of events omitted at the file limit. -pub fn finish(success: bool) { - if let Some(session) = SESSION.get() { - session.finish(success); - } -} - -/// The selected boundaries allow only static operation names, trusted type -/// identifiers, and numeric status codes into the export. -#[derive(Clone, Copy)] -pub enum IoOperation { - InspectImage, - ReadImage, - CreateImageDirectory, - MapImage, -} - -impl IoOperation { - /// Record the failure while leaving the caller's original error intact. - pub fn failed(self, error: &io::Error, started: Option<Instant>) { - if let Some(session) = SESSION.get() { - session.event("operation.failed", self.fields(error, started)); - } - } - - fn fields(self, error: &io::Error, started: Option<Instant>) -> Value { - let (component, module, function, operation, expected) = match self { - Self::InspectImage => ( - "cli", - "victory::inspect", - "run", - "read_image", - "image_bytes", - ), - Self::ReadImage => ("cli", "victory::run", "run", "read_image", "image_bytes"), - Self::CreateImageDirectory => ( - "loader", - "victory_loader::windows", - "load", - "create_image_directory", - "directory_available", - ), - Self::MapImage => ( - "loader", - "victory_loader::windows", - "map_image", - "LoadLibraryExW", - "module_handle", - ), - }; - let code = error.raw_os_error(); - let domain = if cfg!(windows) { "WIN32" } else { "OS" }; - let definition = if cfg!(windows) { - match code { - Some(2) => Some(("ERROR_FILE_NOT_FOUND", "The specified file was not found.")), - Some(3) => Some(("ERROR_PATH_NOT_FOUND", "The specified path was not found.")), - Some(5) => Some(("ERROR_ACCESS_DENIED", "Access was denied.")), - Some(126) => Some(("ERROR_MOD_NOT_FOUND", "A required module was not found.")), - _ => None, - } - } else { - None - }; - let (category, dependency, observed) = match self { - Self::MapImage => ( - if code == Some(126) && cfg!(windows) { - "DEPENDENCY_UNAVAILABLE" - } else { - "DEPENDENCY_ERROR" - }, - json!({ - "name": "Win32 loader", - "binding": "windows-sys", - "binding_locked_version": locked_version("windows-sys"), - }), - "null_handle", - ), - _ => ("IO_ERROR", json!({"name": "Rust std::fs"}), "io_error"), - }; - json!({ - "level": "ERROR", - "category": category, - "component": component, - "module": module, - "function": function, - "operation": operation, - "expected": expected, - "observed": observed, - "dependency": dependency, - "duration_us": started.map(|time| time.elapsed().as_micros()), - "error": { - "type": "std::io::Error", - "kind": format!("{:?}", error.kind()), - "native_code": code.map(|value| json!({ - "domain": domain, - "value": value, - "symbol": definition.map(|(symbol, _)| symbol), - })), - "native_message_status": "omitted", - "recoverable": null, - }, - "diagnostic": { - "definition_status": if definition.is_some() { "documented" } else { "undetermined" }, - "documented_meaning": definition.map(|(_, meaning)| meaning), - "root_cause_status": "undetermined", - "confirmed_facts": [observed], - "hypotheses": [], - "documentation": definition.map_or_else(Vec::new, |_| vec![WIN32_CODES]), - }, - }) - } -} - -fn locked_version(name: &str) -> Option<&'static str> { - let lockfile = include_str!("../../../Cargo.lock"); - let mut versions = - lockfile - .lines() - .zip(lockfile.lines().skip(1)) - .filter_map(|(package, version)| { - let package = package.strip_prefix("name = \"")?.strip_suffix('"')?; - if package != name { - return None; - } - version.strip_prefix("version = \"")?.strip_suffix('"') - }); - let version = versions.next()?; - versions.next().is_none().then_some(version) -} - -impl Session { - fn new(file: File) -> Self { - let clock = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |time| time.as_nanos()); - Self { - id: format!("{clock:x}-{:x}", std::process::id()), - state: Mutex::new(State { - file, - bytes: 0, - sequence: 0, - dropped: 0, - failed: false, - finished: false, - }), - } - } - - fn event(&self, kind: &str, fields: Value) { - let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); - if !state.failed && !state.finished { - self.write(&mut state, kind, fields); - } - } - - fn finish(&self, success: bool) { - let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); - if !state.failed && !state.finished { - let dropped = state.dropped; - self.write( - &mut state, - "session.finished", - json!({"level": "INFO", "success": success, "dropped_events": dropped}), - ); - state.finished = true; - } - } - - fn write(&self, state: &mut State, kind: &str, mut event: Value) { - let sequence = state.sequence + 1; - let event_id = format!("{}-{sequence}", self.id); - let utc_millis = SystemTime::now() - .duration_since(UNIX_EPOCH) - .ok() - .map(|time| time.as_millis()); - event["schema_version"] = json!("1.0"); - event["event"] = json!(kind); - event["timestamp_unix_ms"] = json!(utc_millis); - event["session_id"] = json!(&self.id); - event["sequence"] = json!(sequence); - if kind == "operation.failed" { - event["correlation_id"] = json!(&event_id); - } - event["event_id"] = json!(event_id); - - let mut line = event.to_string(); - line.push('\n'); - let size = line.len() as u64; - let limit = if kind == "session.finished" { - MAX_FILE_BYTES - } else { - MAX_FILE_BYTES - FOOTER_BYTES - }; - if state.bytes + size > limit { - state.dropped += 1; - } else if state.file.write_all(line.as_bytes()).is_err() { - state.failed = true; - eprintln!("VIctory: diagnostic output could not be written"); - } else { - state.bytes += size; - state.sequence = sequence; - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn writes_ordered_events_without_the_original_io_message() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("diagnostics.jsonl"); - let session = Session::new(File::create(&path).unwrap()); - session.event("session.started", json!({"level": "INFO"})); - let error = io::Error::other("private path and guest output"); - session.event( - "operation.failed", - IoOperation::ReadImage.fields(&error, None), - ); - session.finish(false); - let output = std::fs::read_to_string(path).unwrap(); - assert!(!output.contains("private path")); - let events: Vec<Value> = output - .lines() - .map(|line| serde_json::from_str(line).unwrap()) - .collect(); - assert_eq!(events.len(), 3); - assert_eq!(events[0]["session_id"], events[2]["session_id"]); - assert_eq!(events[1]["event_id"], events[1]["correlation_id"]); - assert_eq!(events[1]["sequence"], 2); - assert_eq!(events[1]["diagnostic"]["definition_status"], "undetermined"); - assert_eq!(events[2]["success"], false); - } - - #[test] - fn preserves_space_for_the_summary_at_the_limit() { - let file = tempfile::tempfile().unwrap(); - let session = Session::new(file); - session.state.lock().unwrap().bytes = MAX_FILE_BYTES - FOOTER_BYTES; - session.event("operation.failed", json!({"level": "ERROR"})); - session.finish(false); - let state = session.state.lock().unwrap(); - assert_eq!(state.dropped, 1); - assert_eq!(state.sequence, 1); - assert!(state.finished && state.bytes <= MAX_FILE_BYTES); - } - - #[cfg(windows)] - #[test] - fn explains_a_loader_code_without_guessing_the_root_cause() { - let error = io::Error::from_raw_os_error(126); - let report = IoOperation::MapImage.fields(&error, None); - assert_eq!(report["error"]["native_code"]["value"], 126); - assert_eq!( - report["error"]["native_code"]["symbol"], - "ERROR_MOD_NOT_FOUND" - ); - assert_eq!(report["diagnostic"]["root_cause_status"], "undetermined"); - } -} diff --git a/crates/victory-core/src/lib.rs b/crates/victory-core/src/lib.rs index 0769226c22..011df7e121 100644 --- a/crates/victory-core/src/lib.rs +++ b/crates/victory-core/src/lib.rs @@ -4,12 +4,10 @@ //! * [`policy`]: the runtime half of rule #1, refusing to write //! game-derived data into the source tree. //! * [`logging`]: one tracing setup for all binaries. -//! * [`diagnostics`]: opt-in, structured failure reports. pub mod config; -pub mod diagnostics; pub mod logging; pub mod policy; -pub use config::{Config, Origin, Origins}; +pub use config::Config; pub use policy::{PolicyError, ensure_outside_repo}; diff --git a/crates/victory-core/src/logging.rs b/crates/victory-core/src/logging.rs index cca97cbab0..b4175420b1 100644 --- a/crates/victory-core/src/logging.rs +++ b/crates/victory-core/src/logging.rs @@ -3,10 +3,7 @@ //! Filter with `VICTORY_LOG` (falls back to `RUST_LOG`), e.g. //! `VICTORY_LOG=victory_loader=trace,info`. Debug and trace output exist //! only in builds with the `diagnostics` feature; a plain release build -//! logs info and above whatever the filter asks for. A filter that does not -//! parse is reported on stderr and the default level is used instead, and -//! so is one asking for debug or trace output from a build that cannot -//! produce it. A variable that is set but empty counts as unset. +//! logs info and above whatever the filter asks for. use tracing_subscriber::EnvFilter; use tracing_subscriber::filter::LevelFilter; @@ -21,17 +18,11 @@ const CAP: LevelFilter = if cfg!(feature = "diagnostics") { }; pub fn init(default_level: &str) { - let (victory_log, bad_victory_log) = read_var("VICTORY_LOG", std::env::var("VICTORY_LOG")); - let (rust_log, bad_rust_log) = read_var("RUST_LOG", std::env::var("RUST_LOG")); - let (filter, warning) = choose_filter(victory_log, rust_log, default_level); - let capped = capped_warning(&filter, CAP); - // The subscriber is not installed yet, so these cannot go through it. - for warning in [bad_victory_log, bad_rust_log, warning, capped] - .into_iter() - .flatten() - { - eprintln!("victory: {warning}"); - } + let filter = std::env::var("VICTORY_LOG") + .or_else(|_| std::env::var("RUST_LOG")) + .ok() + .and_then(|v| EnvFilter::try_new(v).ok()) + .unwrap_or_else(|| EnvFilter::new(default_level)); let _ = tracing_subscriber::registry() .with(CAP) .with(filter) @@ -42,157 +33,3 @@ pub fn init(default_level: &str) { ) .try_init(); } - -/// A log variable's value. One that is not valid UTF-8 cannot be a filter; -/// it is treated as unset and the second value says so, instead of being -/// dropped without a word. -fn read_var( - name: &str, - value: Result<String, std::env::VarError>, -) -> (Option<String>, Option<String>) { - match value { - Ok(v) => (Some(v), None), - Err(std::env::VarError::NotPresent) => (None, None), - Err(std::env::VarError::NotUnicode(v)) => ( - None, - Some(format!("ignoring {name}={v:?}: it is not valid UTF-8")), - ), - } -} - -/// The filter from `VICTORY_LOG`, else `RUST_LOG`, else `default_level`. -/// When the variable that was chosen does not parse, the default is used and -/// the second value says why, so a typo is not silently ignored. -fn choose_filter( - victory_log: Option<String>, - rust_log: Option<String>, - default_level: &str, -) -> (EnvFilter, Option<String>) { - // `VICTORY_LOG=` (or `RUST_LOG=`) would otherwise be an empty filter - // that hides everything but errors, and would shadow the other variable. - let set = |v: Option<String>| v.filter(|v| !v.trim().is_empty()); - let chosen = set(victory_log) - .map(|v| ("VICTORY_LOG", v)) - .or_else(|| set(rust_log).map(|v| ("RUST_LOG", v))); - match chosen { - None => (EnvFilter::new(default_level), None), - Some((name, value)) => match EnvFilter::try_new(&value) { - Ok(filter) => (filter, None), - Err(e) => ( - EnvFilter::new(default_level), - Some(format!( - "ignoring {name}={value:?} ({e}); logging at {default_level:?}" - )), - ), - }, - } -} - -/// Says so when `filter` asks for more detail than `cap` lets through, so -/// `VICTORY_LOG=trace` on a build without the `diagnostics` feature does not -/// look like the code has nothing to say. -fn capped_warning(filter: &EnvFilter, cap: LevelFilter) -> Option<String> { - let wanted = filter.max_level_hint()?; - (wanted > cap).then(|| { - format!( - "the log filter asks for {wanted} output, but this build logs {cap} and above; \ - rebuild with `--features diagnostics` for debug and trace" - ) - .to_lowercase() - }) -} - -#[cfg(test)] -mod tests { - use super::{EnvFilter, LevelFilter, capped_warning, choose_filter, read_var}; - - fn s(v: &str) -> Option<String> { - Some(v.to_owned()) - } - - #[test] - fn unset_uses_the_default_quietly() { - let (filter, warning) = choose_filter(None, None, "info"); - assert_eq!(filter.to_string(), "info"); - assert_eq!(warning, None); - } - - #[test] - fn victory_log_wins_over_rust_log() { - let (filter, warning) = choose_filter(s("victory_loader=trace"), s("warn"), "info"); - assert_eq!(filter.to_string(), "victory_loader=trace"); - assert_eq!(warning, None); - } - - #[test] - fn rust_log_is_the_fallback() { - let (filter, warning) = choose_filter(None, s("warn"), "info"); - assert_eq!(filter.to_string(), "warn"); - assert_eq!(warning, None); - } - - #[test] - fn a_bad_filter_is_reported_and_the_default_used() { - let (filter, warning) = choose_filter(s("victory_loader=loud"), None, "info"); - assert_eq!(filter.to_string(), "info"); - let warning = warning.expect("a warning"); - assert!(warning.contains("VICTORY_LOG"), "{warning}"); - assert!(warning.contains("victory_loader=loud"), "{warning}"); - } - - #[test] - fn a_bad_rust_log_names_rust_log() { - let (_, warning) = choose_filter(None, s("x=nope"), "info"); - assert!(warning.expect("a warning").contains("RUST_LOG")); - } - - #[test] - fn empty_values_count_as_unset() { - let (filter, warning) = choose_filter(s(""), s("warn"), "info"); - assert_eq!(filter.to_string(), "warn"); - assert_eq!(warning, None); - let (filter, warning) = choose_filter(s(" "), s(""), "info"); - assert_eq!(filter.to_string(), "info"); - assert_eq!(warning, None); - } - - #[test] - fn a_filter_above_the_cap_is_reported() { - let filter = EnvFilter::new("victory_loader=trace,info"); - let warning = capped_warning(&filter, LevelFilter::INFO).expect("a warning"); - assert!(warning.contains("trace"), "{warning}"); - assert!(warning.contains("diagnostics"), "{warning}"); - assert_eq!(capped_warning(&filter, LevelFilter::TRACE), None); - assert_eq!( - capped_warning(&EnvFilter::new("warn"), LevelFilter::INFO), - None - ); - assert_eq!( - capped_warning(&EnvFilter::new("info"), LevelFilter::INFO), - None - ); - } - - #[test] - fn a_non_utf8_variable_is_reported_and_unset() { - use std::env::VarError; - assert_eq!( - read_var("VICTORY_LOG", Ok("warn".into())), - (s("warn"), None) - ); - assert_eq!( - read_var("VICTORY_LOG", Err(VarError::NotPresent)), - (None, None) - ); - #[cfg(unix)] - { - use std::os::unix::ffi::OsStringExt; - let bad = std::ffi::OsString::from_vec(vec![b'w', 0xff]); - let (value, warning) = read_var("RUST_LOG", Err(VarError::NotUnicode(bad))); - assert_eq!(value, None); - let warning = warning.expect("a warning"); - assert!(warning.contains("RUST_LOG"), "{warning}"); - assert!(warning.contains("UTF-8"), "{warning}"); - } - } -} diff --git a/crates/victory-core/src/policy.rs b/crates/victory-core/src/policy.rs index cd86e2d794..b10e1c64f2 100644 --- a/crates/victory-core/src/policy.rs +++ b/crates/victory-core/src/policy.rs @@ -6,7 +6,6 @@ //! [`ensure_outside_repo`] on the destination first. The static half of the //! rule is `cargo xtask policy`, which checks what git tracks. -use std::io; use std::path::{Component, Path, PathBuf}; /// Marker file at the root of the source tree. @@ -40,25 +39,9 @@ pub enum PolicyError { /// 2. none of its ancestors contains the [`ROOT_MARKER`] file (catches /// other clones/copies of the repository). pub fn ensure_outside_repo(path: &Path) -> Result<(), PolicyError> { - let result = ensure_outside_repo_with(path, |path| std::fs::canonicalize(path)); - #[cfg(windows)] - if let Err(PolicyError::Io { source, .. }) = &result - && source.kind() == io::ErrorKind::PermissionDenied - { - // An AppContainer can open a directory without access to its DOS volume name. - // Compare both paths in the same namespace and still check the resolved ancestors. - return ensure_outside_repo_with(path, canonicalize_native); - } - result -} - -fn ensure_outside_repo_with( - path: &Path, - canonicalize: impl Fn(&Path) -> io::Result<PathBuf>, -) -> Result<(), PolicyError> { - let resolved = resolve(path, &canonicalize)?; + let resolved = resolve(path)?; - if let Ok(root) = canonicalize(&compiled_workspace_root()) + if let Ok(root) = std::fs::canonicalize(compiled_workspace_root()) && root.join(ROOT_MARKER).is_file() && resolved.starts_with(&root) { @@ -81,10 +64,7 @@ fn ensure_outside_repo_with( /// Canonicalizes the longest existing prefix of `path` and re-appends the /// rest, so that paths which do not exist yet can still be compared. -fn resolve( - path: &Path, - canonicalize: impl Fn(&Path) -> io::Result<PathBuf>, -) -> Result<PathBuf, PolicyError> { +fn resolve(path: &Path) -> Result<PathBuf, PolicyError> { let absolute = if path.is_absolute() { path.to_path_buf() } else { @@ -99,7 +79,7 @@ fn resolve( let mut existing = absolute.as_path(); let mut rest = Vec::new(); loop { - match canonicalize(existing) { + match std::fs::canonicalize(existing) { Ok(canon) => { let mut out = canon; for component in rest.iter().rev() { @@ -107,22 +87,11 @@ fn resolve( } return Ok(normalize(&out)); } - Err(source) if cfg!(windows) && source.kind() == io::ErrorKind::PermissionDenied => { - return Err(PolicyError::Io { - path: path.to_path_buf(), - source, - }); - } Err(source) => match (existing.parent(), existing.file_name()) { (Some(parent), Some(name)) => { rest.push(name.to_os_string()); existing = parent; } - // `file_name()` is None for a trailing `..`; keep it so `normalize` resolves it. - (Some(parent), None) if existing.ends_with("..") => { - rest.push("..".into()); - existing = parent; - } _ => { return Err(PolicyError::Io { path: path.to_path_buf(), @@ -134,44 +103,6 @@ fn resolve( } } -#[cfg(windows)] -fn canonicalize_native(path: &Path) -> io::Result<PathBuf> { - use std::fs::OpenOptions; - use std::os::windows::{ffi::OsStringExt, fs::OpenOptionsExt, io::AsRawHandle}; - use windows_sys::Win32::Storage::FileSystem::{ - FILE_FLAG_BACKUP_SEMANTICS, GetFinalPathNameByHandleW, VOLUME_NAME_NT, - }; - - let file = OpenOptions::new() - .access_mode(0) - .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) - .open(path)?; - let mut name = vec![0u16; 512]; - loop { - // SAFETY: the live file owns the handle, and the buffer is writable for its given length. - let len = unsafe { - GetFinalPathNameByHandleW( - file.as_raw_handle(), - name.as_mut_ptr(), - name.len() as u32, - VOLUME_NAME_NT, - ) - } as usize; - if len == 0 { - return Err(io::Error::last_os_error()); - } - if len >= name.len() { - name.resize(len, 0); - continue; - } - - // Make the normalized NT path usable by ordinary Win32 file APIs. - let mut absolute = std::ffi::OsString::from(r"\\?\GLOBALROOT"); - absolute.push(std::ffi::OsString::from_wide(&name[..len])); - return Ok(PathBuf::from(absolute)); - } -} - /// Removes `.` and resolves `..` lexically (only used on the non-existing tail). fn normalize(path: &Path) -> PathBuf { let mut out = PathBuf::new(); @@ -225,36 +156,4 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); ensure_outside_repo(&tmp.path().join("does").join("not").join("exist")).unwrap(); } - - #[cfg(windows)] - #[test] - fn native_paths_still_check_repository_markers() { - let temp = tempfile::tempdir().unwrap(); - let target = temp.path().join("missing").join("cache"); - ensure_outside_repo_with(&target, canonicalize_native).unwrap(); - std::fs::write(temp.path().join(ROOT_MARKER), "").unwrap(); - assert!(matches!( - ensure_outside_repo_with(&target, canonicalize_native), - Err(PolicyError::InsideRepo { .. }) - )); - assert!(matches!( - ensure_outside_repo_with( - &compiled_workspace_root().join("missing").join("cache"), - canonicalize_native, - ), - Err(PolicyError::InsideRepo { .. }) - )); - } - - #[test] - fn resolves_dot_dot_in_a_path_that_does_not_exist_yet() { - let base = std::env::temp_dir().join("victory-policy-no-such"); - let path = base.join("a").join("..").join("b"); - let resolved = resolve(&path, |p: &Path| std::fs::canonicalize(p)) - .expect("a `..` in the missing tail must resolve lexically"); - assert_eq!( - resolved, - resolve(&base.join("b"), |p: &Path| std::fs::canonicalize(p)).unwrap() - ); - } } diff --git a/crates/victory-formats/examples/texture_layout_bench.rs b/crates/victory-formats/examples/texture_layout_bench.rs new file mode 100644 index 0000000000..53c3936d9d --- /dev/null +++ b/crates/victory-formats/examples/texture_layout_bench.rs @@ -0,0 +1,89 @@ +//! Run with `cargo run --release -p victory-formats --example texture_layout_bench`. + +use std::hint::black_box; +use std::time::Instant; + +use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc}; + +fn main() { + const CALLS: u64 = 50_000; + let base = TextureDesc { + dimension: Dimension::Tex2d, + width: 512, + height: 512, + depth_or_array: 1, + mips: 0, + format: 98, // BC7 + samples: 1, + swizzle: Swizzle::SW_64KB_D, + }; + let cases = [ + ("BC7 64KB_D", base), + ( + "BC1 64KB_S", + TextureDesc { + format: 71, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 4KB_D", + TextureDesc { + format: 28, + swizzle: Swizzle::SW_4KB_D, + ..base + }, + ), + ( + "R8 64KB_S", + TextureDesc { + format: 61, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 volume 64KB_S", + TextureDesc { + dimension: Dimension::Tex3d, + width: 128, + height: 128, + depth_or_array: 64, + format: 28, + swizzle: Swizzle::SW_64KB_S, + ..base + }, + ), + ( + "RGBA8 linear", + TextureDesc { + format: 28, + swizzle: Swizzle::LINEAR, + ..base + }, + ), + ]; + + for (name, desc) in cases { + let mut samples = [0.0; 7]; + black_box(Texture::new(black_box(&desc)).unwrap()); + let mut checksum = 0u64; + for sample in &mut samples { + let start = Instant::now(); + for i in 0..CALLS { + let desc = TextureDesc { + width: desc.width + (i % 32) as u32, + ..desc + }; + let texture = black_box(Texture::new(black_box(&desc)).unwrap()); + let layout = &texture.planes[0].layout; + checksum = + checksum.wrapping_add(texture.size + layout.offset(0, 7, 11, 0).unwrap()); + } + *sample = start.elapsed().as_secs_f64() * 1e9 / CALLS as f64; + } + samples.sort_by(f64::total_cmp); + println!("{name:22} {:8.1} ns/layout {checksum}", samples[3]); + } +} diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs index c8d35378df..11dada0f96 100644 --- a/crates/victory-formats/src/bcpack.rs +++ b/crates/victory-formats/src/bcpack.rs @@ -744,10 +744,19 @@ fn pbits(mode: u16) -> bool { matches!(mode, 0 | 1 | 3 | 6 | 7) } +/// Channel rotation bits; only BC7 modes 4 and 5 have a rotation field. +fn rotation(ctrl: u16) -> usize { + if matches!(ctrl & 7, 4 | 5) { + usize::from(ctrl >> 3 & 3) + } else { + 0 + } +} + /// Channel precisions: the p-bit is red's lowest bit; rotation swaps alpha /// with the rotated channel. fn bc7_precision(ctrl: u16) -> [u8; 4] { - let (mode, rot) = (ctrl & 7, usize::from(ctrl >> 3 & 3)); + let (mode, rot) = (ctrl & 7, rotation(ctrl)); let mut p = BC7_BITS[usize::from(mode)]; if rot != 0 { p.swap(3, rot - 1); @@ -852,7 +861,7 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { let mode = ctrl & 7; let subsets = usize::from((ctrl & 0xff) >> 6); let part = usize::from(ctrl >> 8 & 63); - let rot = usize::from(ctrl >> 3 & 3); + let rot = rotation(ctrl); let mut w = Bits::default(); w.put(1 << mode, u32::from(mode) + 1); match mode { @@ -1341,6 +1350,102 @@ mod tests { assert_eq!(dst, w.v.to_le_bytes()); } + #[test] + fn bc7_rotation_applies_only_to_modes_4_and_5() { + const BC7_WIDTHS: [u8; 16] = [3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4]; + const CTRL7_OFFSET: usize = MODELS * BUCKETS * 2 + 256 + 64 + 256 + 64 + 64; + let tables_for = |ctrl: u16| { + let mut raw = tables(); + raw[CTRL7_OFFSET..CTRL7_OFFSET + 2].copy_from_slice(&ctrl.to_le_bytes()); + let t = Tables::parse(&raw).unwrap(); + assert_eq!(t.ctrl7[0], ctrl); + t + }; + + let mut record = vec![0u8; 32]; + for (i, &val) in [11, 23, 5, 19, 13, 29, 7, 17, 3, 25, 9, 21, 15, 31, 1, 12] + .iter() + .enumerate() + { + record[4 + i] = zigzag(val); + } + record[20] = zigzag(6); + record[21] = zigzag(14); + + // Modes without a BC7 rotation field must ignore ctrl bits 4:3 instead of + // panicking on shift overflow (modes 0/1/3 with rot=1) or corrupting channels. + for (mode, subsets) in [(0u16, 3u16), (1, 2), (2, 3), (3, 2), (6, 1), (7, 2)] { + let base_ctrl = (subsets << 6) | mode; + let base_tables = tables_for(base_ctrl); + let base_src = stream(&base_tables, &BC7_WIDTHS, 2, std::slice::from_ref(&record)); + let mut want = [0u8; 16]; + decode(7, &base_src, &mut want, &base_tables).unwrap(); + + for rot in 1..=3u16 { + let ctrl = base_ctrl | (rot << 3); + let t = tables_for(ctrl); + let src = stream(&t, &BC7_WIDTHS, 2, std::slice::from_ref(&record)); + let mut got = [0u8; 16]; + decode(7, &src, &mut got, &t).unwrap(); + assert_eq!(got, want, "mode {mode} rot {rot}"); + assert_eq!( + bc7_precision(ctrl), + bc7_precision(base_ctrl), + "mode {mode} rot {rot}" + ); + } + } + + // Modes 4 and 5 do have a 2-bit rotation field: rotation swaps alpha with channel rot-1. + for (mode, base_bits) in [(4u16, [5u8, 5, 5, 6]), (5u16, [7u8, 7, 7, 8])] { + for rot in 1..=3usize { + let ctrl = (1 << 6) | ((rot as u16) << 3) | mode; + let mut expected_prec = base_bits; + expected_prec.swap(3, rot - 1); + assert_eq!(bc7_precision(ctrl), expected_prec, "mode {mode} rot {rot}"); + } + + // Decode mode 4/5 with rot=1 (swap R and A) and check the packed BC7 block. + let ctrl = (1 << 6) | (1 << 3) | mode; + let t = tables_for(ctrl); + let mut s = vec![0u8; 32]; + s[4] = zigzag(0x21); // stored R0 (holds alpha precision after rot=1) + s[5] = zigzag(0x12); // stored R1 + s[6] = zigzag(0x05); // stored G0 + s[7] = zigzag(0x06); // stored G1 + s[8] = zigzag(0x09); // stored B0 + s[9] = zigzag(0x0a); // stored B1 + s[10] = zigzag(0x0d); // stored A0 (holds color precision after rot=1) + s[11] = zigzag(0x0e); // stored A1 + let src = stream(&t, &BC7_WIDTHS, 2, &[s]); + let mut dst = [0u8; 16]; + decode(7, &src, &mut dst, &t).unwrap(); + + let color_bits = u32::from(base_bits[0]); + let alpha_bits = u32::from(base_bits[3]); + let mut w = Bits::default(); + w.put(1 << mode, u32::from(mode) + 1); + w.put(1, 2); // rotation = 1 + if mode == 4 { + w.put(0, 1); // indexSelectionBit = 0 + } + // Endpoint order after rot=1 swaps indices 3 and 0: [3 (R), 1 (G), 2 (B), 0 (A)]. + for (v, n) in [ + (0x0d, color_bits), + (0x0e, color_bits), + (0x05, color_bits), + (0x06, color_bits), + (0x09, color_bits), + (0x0a, color_bits), + (0x21, alpha_bits), + (0x12, alpha_bits), + ] { + w.put(v, n); + } + assert_eq!(dst, w.v.to_le_bytes(), "mode {mode} rot 1"); + } + } + #[test] fn malformed_input_is_an_error() { let t = Tables::parse(&tables()).unwrap(); diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 87f6edd816..bf2a65bf5a 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -30,6 +30,8 @@ //! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, //! EXPRESS OR IMPLIED. +use std::sync::OnceLock; + /// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Swizzle(pub u32); @@ -174,11 +176,14 @@ pub struct Layout { /// The first mip in the tail; `mips.len()` without one. pub first_tail_mip: u32, pub mips: Vec<Mip>, - /// Byte offsets inside a block of each element coordinate bit, per - /// axis; empty for linear and unsupported modes. - pattern: [Vec<u32>; 3], + /// Byte offsets inside a block for each coordinate, per axis. + /// Empty for linear and unsupported modes. + pattern: &'static SwizzlePattern, } +type SwizzlePattern = [Vec<u32>; 3]; +static EMPTY_PATTERN: SwizzlePattern = [const { Vec::new() }; 3]; + /// Micro tile (256 bytes) patterns by log2 of the element size: for each /// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...), /// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S` @@ -247,6 +252,18 @@ fn spread(bits: &[u32]) -> Vec<u32> { .collect() } +/// Tables depend only on the micro-tile kind, block size and element size. +/// Texture extents, mip placement and array slices only affect the base +/// address, so layouts with the same key can share these immutable tables. +fn shared_pattern(kind: usize, element_log2: u32, block_log2: u32) -> &'static SwizzlePattern { + // Indexed by MICRO kind, block size (256 B, 4 KiB, 64 KiB), then element size. + static PATTERNS: [[[OnceLock<SwizzlePattern>; 5]; 3]; 3] = + [const { [const { [const { OnceLock::new() }; 5] }; 3] }; 3]; + let block_index = ((block_log2 - 8) / 4) as usize; + PATTERNS[kind][block_index][element_log2 as usize] + .get_or_init(|| pattern(kind, element_log2, block_log2).map(|bits| spread(&bits))) +} + const MAX_MIPS: u32 = 16; /// The largest width, height and depth (or array size) accepted, in texels. @@ -322,7 +339,7 @@ impl Layout { alignment: 256, first_tail_mip: d.mips, mips, - pattern: Default::default(), + pattern: &EMPTY_PATTERN, } } @@ -330,18 +347,13 @@ impl Layout { let element_log2 = d.element_bytes.trailing_zeros(); let bpe = u64::from(d.element_bytes); let block_bytes = 1u64 << block_log2; - let thick = - d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display()); + let thick = d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display()); let block = if thick { // ComputeThickBlockDimension let amp = (block_log2 - 10) / 3; let rest = (block_log2 - 10) % 3; let b = BLOCK_1K_3D[element_log2 as usize]; - [ - b[0] << amp, - b[1] << (amp + rest / 2), - b[2] << (amp + u32::from(rest != 0)), - ] + [b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + u32::from(rest != 0))] } else { // ComputeThinBlockDimension let samples_log2 = d.samples.trailing_zeros(); @@ -352,17 +364,19 @@ impl Layout { }; let slices = d.depth.next_multiple_of(block[2]); let three_d = d.dimension == Dimension::Tex3d; - // Mip depths placed by a thick layout (thin ones store depth as - // slices). - let mip_depth = |i: u32| if thick { padded_dim(d.depth, i, 1) } else { 1 }; + // A thin volume allocates the full mip chain in each depth slice. + let padded_depth = |i: u32| { + if thick { + padded_dim(d.depth, i, 1) + } else if three_d { + d.depth + } else { + 1 + } + }; let depth_of = |i: u32| if three_d { dim(d.depth, i, 1) } else { 1 }; let (width, height) = (|i| dim(d.width, i, d.block), |i| dim(d.height, i, d.block)); - let padded = |i| { - ( - padded_dim(d.width, i, d.block), - padded_dim(d.height, i, d.block), - ) - }; + let padded = |i| (padded_dim(d.width, i, d.block), padded_dim(d.height, i, d.block)); let mut mips = Vec::with_capacity(d.mips as usize); let mut first_tail_mip = d.mips; let mut slice_size = 0u64; @@ -377,8 +391,10 @@ impl Layout { offset: 0, tail: None, }); - slice_size = - u64::from(mips[0].pitch) * u64::from(mips[0].rows) * bpe * u64::from(d.samples); + slice_size = u64::from(mips[0].pitch) + * u64::from(mips[0].rows) + * bpe + * u64::from(d.samples); } else { // GetMipTailDim: the largest mip the tail takes. let mut tail_max = block; @@ -420,7 +436,6 @@ impl Layout { } let pitch = w.next_multiple_of(block[0]); let rows = h.next_multiple_of(block[1]); - let depth = mip_depth(i).next_multiple_of(block[2]); let one = u64::from(pitch) * u64::from(rows) * bpe; slice_size += one; sizes.push(one * u64::from(block[2])); @@ -430,7 +445,7 @@ impl Layout { depth: depth_of(i), pitch, rows, - depth_pitch: if three_d { depth } else { 1 }, + depth_pitch: padded_depth(i).next_multiple_of(block[2]), offset: 0, tail: None, }); @@ -472,9 +487,9 @@ impl Layout { pitch, rows, depth_pitch: if thick { - mip_depth(i).next_multiple_of(BLOCK_256_3D[element_log2 as usize][2]) + padded_depth(i).next_multiple_of(BLOCK_256_3D[element_log2 as usize][2]) } else { - 1 + padded_depth(i) }, offset: 0, tail: Some(Tail { @@ -498,9 +513,9 @@ impl Layout { } else { usize::from(d.swizzle.display()) }; - pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)) + shared_pattern(kind, element_log2, block_log2) } else { - Default::default() + &EMPTY_PATTERN }; Layout { desc: d, @@ -572,8 +587,7 @@ impl Layout { // offset inside the tail block. let y = y + m.tail.map_or(0, |t| t.y); let blocks = u64::from(y / bh) * u64::from(m.pitch / bw); - (blocks << log2) - + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize]) + (blocks << log2) + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize]) } /// The part of an address that depends on the column. @@ -590,8 +604,40 @@ impl Layout { self.mips.get(mip as usize).map_or(0, |m| m.depth) } + /// The bytes from the texture's start that mip `first` and the smaller + /// ones take: the smaller a mip, the nearer the start it lies, so a + /// title that streams textures has memory for the smaller mips only and + /// another texture right behind them. All of the layout where slices + /// follow each other (each holds its whole chain). + pub fn bytes_from(&self, first: u32) -> u64 { + let whole = first == 0 + || self.slices != 1 + || self.thick + || self.desc.dimension == Dimension::Tex3d + || self.desc.samples != 1 + || first >= self.desc.mips; + if whole { + return self.size; + } + self.mips[first as usize..] + .iter() + .map(|m| match m.tail { + Some(_) => self.alignment, + None => { + m.offset + + u64::from(m.pitch) + * u64::from(m.rows) + * u64::from(self.desc.element_bytes) + } + }) + .max() + .unwrap_or(self.size) + .min(self.size) + } + /// Copies one subresource out of tiled memory (the whole texture, - /// [`Layout::size`] bytes) into linear rows: mip `mip` of array slice + /// [`Layout::size`] bytes, or the [`Layout::bytes_from`] of the mip) + /// into linear rows: mip `mip` of array slice /// `slice` (3D: every depth slice of the mip, `slice` 0). Rows are /// `row_pitch` bytes apart, depth slices `depth_pitch`. pub fn detile( @@ -603,17 +649,7 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk( - tiled.len(), - mip, - slice, - linear.len(), - row_pitch, - depth_pitch, - |t, l, len| { - linear[l..][..len].copy_from_slice(&tiled[t..][..len]); - }, - ) + self.walk::<true>(tiled, linear, mip, slice, row_pitch, depth_pitch) } /// The reverse of [`Layout::detile`]: linear rows into tiled memory. @@ -626,30 +662,19 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk( - tiled.len(), - mip, - slice, - linear.len(), - row_pitch, - depth_pitch, - |t, l, len| { - tiled[t..][..len].copy_from_slice(&linear[l..][..len]); - }, - ) + self.walk::<false>(linear, tiled, mip, slice, row_pitch, depth_pitch) } - /// Visits contiguous runs as (tiled byte offset, linear byte offset, length). + /// Copies contiguous runs in one direction between the two layouts. #[allow(clippy::too_many_arguments)] - fn walk( + fn walk<const DETILE: bool>( &self, - tiled_len: usize, + src: &[u8], + dst: &mut [u8], mip: u32, slice: u32, - linear_len: usize, row_pitch: usize, depth_pitch: usize, - mut copy: impl FnMut(usize, usize, usize), ) -> Result<(), Error> { let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; let depth = m.depth; @@ -669,21 +694,18 @@ impl Layout { } let n = self.desc.element_bytes as usize; let bytes = m.width as usize * n; - let slice_bytes = (m.height as usize - 1) - .checked_mul(row_pitch) - .and_then(|offset| offset.checked_add(bytes)) - .ok_or(Error::TooSmall)?; - - // Multiple depth slices must not overwrite each other. - if depth > 1 && depth_pitch < slice_bytes { - return Err(Error::TooSmall); - } - let need = (depth as usize - 1) .checked_mul(depth_pitch) - .and_then(|offset| offset.checked_add(slice_bytes)) + .zip((m.height as usize - 1).checked_mul(row_pitch)) + .and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset)) + .and_then(|offset| offset.checked_add(bytes)) .ok_or(Error::TooSmall)?; - if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { + let (tiled_len, linear_len) = if DETILE { + (src.len(), dst.len()) + } else { + (dst.len(), src.len()) + }; + if tiled_len < self.bytes_from(mip) as usize || linear_len < need || row_pitch < bytes { return Err(Error::TooSmall); } let linear = self.desc.swizzle == Swizzle::LINEAR; @@ -704,6 +726,13 @@ impl Layout { } runs.push((first_tiled, first_linear, bytes - first_linear)); } + // A mip can end partway through the last run. Check the other runs + // once so each row can copy them as fixed-size chunks. + let (body, last) = runs.split_at(runs.len().saturating_sub(1)); + let chunk_size = body.first().map(|run| run.2).filter(|&size| { + body.iter() + .all(|&(offset, _, len)| len == size && offset.is_multiple_of(size)) + }); for z in 0..depth { let (s, inner) = self.split(first + z); let base = u64::from(s) * self.slice_size + m.offset; @@ -711,12 +740,22 @@ impl Layout { let linear_row = z as usize * depth_pitch + y as usize * row_pitch; if linear { let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64; - copy(tiled_row as usize, linear_row, bytes); + copy_run::<DETILE>(src, dst, tiled_row as usize, linear_row, bytes); } else { let tiled_row = (base + self.row(m, y, inner)) as usize; - for &(tiled, linear, len) in &runs { - copy(tiled_row + tiled, linear_row + linear, len); + match chunk_size { + Some(8) if tiled_row.is_multiple_of(8) => { + copy_runs::<8, DETILE>(src, dst, body, tiled_row, linear_row) + } + Some(16) if tiled_row.is_multiple_of(16) => { + copy_runs::<16, DETILE>(src, dst, body, tiled_row, linear_row) + } + Some(32) if tiled_row.is_multiple_of(32) => { + copy_runs::<32, DETILE>(src, dst, body, tiled_row, linear_row) + } + _ => copy_runs::<0, DETILE>(src, dst, body, tiled_row, linear_row), } + copy_runs::<0, DETILE>(src, dst, last, tiled_row, linear_row); } } } @@ -724,6 +763,50 @@ impl Layout { } } +fn copy_run<const DETILE: bool>( + src: &[u8], + dst: &mut [u8], + tiled: usize, + linear: usize, + len: usize, +) { + let (from, to) = if DETILE { + (tiled, linear) + } else { + (linear, tiled) + }; + dst[to..][..len].copy_from_slice(&src[from..][..len]); +} + +/// A row of equal runs is contiguous in linear memory. Treat it as a +/// slice of arrays so only the tiled chunk needs a bounds check per copy. +/// Use the byte ranges for irregular runs and the last run of each row. +fn copy_runs<const N: usize, const DETILE: bool>( + src: &[u8], + dst: &mut [u8], + runs: &[(usize, usize, usize)], + tiled_row: usize, + linear_row: usize, +) { + if N == 0 { + for &(tiled, linear, len) in runs { + copy_run::<DETILE>(src, dst, tiled_row + tiled, linear_row + linear, len); + } + } else if DETILE { + let tiled = src.as_chunks::<N>().0; + let linear = dst[linear_row..][..runs.len() * N].as_chunks_mut::<N>().0; + for (out, &(offset, ..)) in linear.iter_mut().zip(runs) { + *out = tiled[(tiled_row + offset) / N]; + } + } else { + let tiled = dst.as_chunks_mut::<N>().0; + let linear = src[linear_row..][..runs.len() * N].as_chunks::<N>().0; + for (input, &(offset, ..)) in linear.iter().zip(runs) { + tiled[(tiled_row + offset) / N] = *input; + } + } +} + /// What a DXGI format stores per element: bytes, texels per element side /// (4 for block compression), and whether its stencil is a second plane /// (the GPU keeps depth and stencil apart). @@ -786,9 +869,13 @@ pub struct Plane { } /// Every data plane of a texture (depth, then stencil), placed one after -/// the other. `size` covers the data planes only: the host GPU has no use -/// for the console's compression metadata, and [`metadata`] sizes that -/// memory separately for callers that reserve console-sized pools. +/// the other. +/// +/// shortcut: no compression metadata planes (HTILE, CMASK, FMASK, DCC); +/// the console adds them to render targets and depth buffers unless the +/// description denies them, so those are smaller here than on the console. +/// The host GPU renders them, so nothing reads that memory; add the planes +/// if a title sizes a pool from console sizes and runs out. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Texture { pub planes: Vec<Plane>, @@ -796,33 +883,6 @@ pub struct Texture { pub alignment: u64, } -/// The alignment and the minimum reservation for a metadata plane. The -/// console's metadata is bank-aligned and its smallest block is 4 KiB. -pub const METADATA_ALIGNMENT: u64 = 64 << 10; - -/// Bytes the console reserves for a render target's compression metadata -/// (HTILE for depth, CMASK and DCC for color), in addition to its data -/// planes. Only render-capable textures get any; sampled textures have no -/// metadata to allocate. -/// -/// The console's exact HTILE, CMASK and DCC forms depend on the GPU's pipe -/// configuration and are not published here, so this is an upper bound: -/// one eighth of the data for depth, one sixteenth for color, rounded up to -/// a metadata block. A title that sizes a pool from the layout gets at -/// least as much room as it would on the console; the host keeps rendering -/// into the data planes with no metadata of its own. -pub fn metadata(desc: &TextureDesc, texture: &Texture, depth: bool, render: bool) -> u64 { - if !render || texture.size == 0 || desc.dimension == Dimension::Tex1d { - return 0; - } - let divisor = if depth { 8 } else { 16 }; - texture - .size - .checked_div(divisor) - .unwrap_or(0) - .next_multiple_of(METADATA_ALIGNMENT) -} - impl Texture { pub fn new(desc: &TextureDesc) -> Result<Texture, Error> { let f = format(desc.format).ok_or(Error::Invalid)?; @@ -832,14 +892,7 @@ impl Texture { 1 }; let mips = match desc.mips { - 0 => { - 32 - desc - .width - .max(desc.height) - .max(depth3d) - .max(1) - .leading_zeros() - } + 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(), n => n, }; let plane = |bytes| Desc { @@ -896,25 +949,6 @@ mod tests { } } - fn texture_desc(d: &Desc) -> TextureDesc { - TextureDesc { - dimension: d.dimension, - width: d.width, - height: d.height, - depth_or_array: d.depth, - mips: d.mips, - format: match d.element_bytes { - 1 => 60, - 2 => 48, - 8 => 9, - 16 => 1, - _ => 23, - }, - samples: d.samples, - swizzle: d.swizzle, - } - } - /// Sizes past the hardware's 16384 texels per side are refused instead /// of overflowing the size arithmetic (found by random-input testing). #[test] @@ -936,51 +970,6 @@ mod tests { } } - #[test] - fn metadata_reserves_room_only_for_render_targets() { - let d = desc(1920, 1080, 1, 4, Swizzle::SW_64KB_R_X); - let td = texture_desc(&d); - let t = Texture::new(&td).unwrap(); - assert_eq!(metadata(&td, &t, false, false), 0, "a sampled texture"); - let color = metadata(&td, &t, false, true); - let depth = metadata(&td, &t, true, true); - assert!(color > 0 && color.is_multiple_of(METADATA_ALIGNMENT)); - assert!(depth > color, "HTILE is larger than color metadata"); - assert_eq!( - depth / METADATA_ALIGNMENT, - (t.size / 8).div_ceil(METADATA_ALIGNMENT) - ); - let one_d = texture_desc(&Desc { - dimension: Dimension::Tex1d, - ..desc(256, 1, 1, 4, Swizzle::LINEAR) - }); - assert_eq!( - metadata(&one_d, &Texture::new(&one_d).unwrap(), false, true), - 0 - ); - } - - #[test] - fn metadata_never_overlaps_or_overflows() { - for (w, h, bpe) in [(1, 1, 1), (17, 9, 2), (4096, 4096, 16), (16384, 16384, 16)] { - let td = texture_desc(&desc(w, h, 1, bpe, Swizzle::SW_64KB_Z_X)); - let t = Texture::new(&td).unwrap(); - let m = metadata(&td, &t, true, true); - let offset = t.size.next_multiple_of(METADATA_ALIGNMENT); - assert!(offset >= t.size, "metadata starts after the data"); - assert!(m > 0 && offset.checked_add(m).is_some(), "{w}x{h}"); - } - // Round-up must not overflow even for an absurd reported size. - let huge = texture_desc(&desc(u32::MAX, 1, 1, 4, Swizzle::SW_64KB_R_X)); - let fake = Texture { - planes: Vec::new(), - size: u64::MAX, - alignment: 1, - }; - let m = metadata(&huge, &fake, true, true); - assert!(m > 0 && m.is_multiple_of(METADATA_ALIGNMENT)); - } - #[test] fn blocks_hold_their_size_in_elements() { for log2 in [8u32, 12, 16] { @@ -1035,11 +1024,7 @@ mod tests { let mut seen = vec![false; l.size as usize]; let mut tiled = vec![0u8; l.size as usize]; let n = d.element_bytes as usize; - let slices = if d.dimension == Dimension::Tex3d { - 1 - } else { - d.depth - }; + let slices = if d.dimension == Dimension::Tex3d { 1 } else { d.depth }; for slice in 0..slices { for mip in 0..d.mips { let m = l.mips[mip as usize]; @@ -1068,17 +1053,65 @@ mod tests { seen[at] = true; } } - assert!( - back[base + plane - 11..base + plane] - .iter() - .all(|&b| b == 0xcc) - ); + assert!(back[base + plane - 11..base + plane].iter().all(|&b| b == 0xcc)); } } } } } + #[test] + fn tiled_chunks_match_element_offsets_with_odd_row_pitches() { + for swizzle in [ + Swizzle::SW_256B_S, + Swizzle::SW_256B_D, + Swizzle::SW_4KB_S, + Swizzle::SW_4KB_D, + Swizzle::SW_64KB_S, + Swizzle::SW_64KB_D, + ] { + for n in [1, 2, 4, 8, 16] { + let l = Layout::new(&Desc { + depth: 2, + ..desc(73, 39, 7, n, swizzle) + }) + .unwrap(); + let n = n as usize; + let tiled: Vec<_> = (0..l.size) + .map(|i| (i.wrapping_mul(0x9e37_79b9) >> 24) as u8) + .collect(); + let mut retiled = vec![0xbb; tiled.len()]; + let mut expected_tiled = retiled.clone(); + for slice in 0..l.slices { + for (mip, m) in l.mips.iter().enumerate() { + let mip = mip as u32; + let bytes = m.width as usize * n; + let pitch = bytes + 3; + // Keep padding between rows, with exactly the active + // bytes in the last row. + let len = (m.height as usize - 1) * pitch + bytes; + let mut linear = vec![0xcc; len]; + let mut expected = linear.clone(); + for y in 0..m.height { + for x in 0..m.width { + let src = l.offset(mip, x, y, slice).unwrap() as usize; + let dst = y as usize * pitch + x as usize * n; + expected[dst..][..n].copy_from_slice(&tiled[src..][..n]); + expected_tiled[src..][..n].copy_from_slice(&tiled[src..][..n]); + } + } + l.detile(&tiled, mip, slice, &mut linear, pitch, len) + .unwrap(); + assert_eq!(linear, expected, "{swizzle:?} {n} mip {mip} slice {slice}"); + l.tile(&mut retiled, mip, slice, &expected, pitch, len) + .unwrap(); + } + } + assert_eq!(retiled, expected_tiled, "{swizzle:?} {n}"); + } + } + } + /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12, /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first. @@ -1099,6 +1132,41 @@ mod tests { assert_eq!(l.offset(0, 0, 16, 0), Ok(8192)); } + #[test] + fn layouts_share_identical_swizzle_tables() { + for (swizzle, kind, dimension, block_log2) in [ + (Swizzle::SW_256B_S, 0, Dimension::Tex2d, 8), + (Swizzle::SW_256B_D, 1, Dimension::Tex2d, 8), + (Swizzle::SW_4KB_S, 0, Dimension::Tex2d, 12), + (Swizzle::SW_4KB_D, 1, Dimension::Tex2d, 12), + (Swizzle::SW_64KB_S, 0, Dimension::Tex2d, 16), + (Swizzle::SW_64KB_D, 1, Dimension::Tex2d, 16), + (Swizzle::SW_4KB_S, 2, Dimension::Tex3d, 12), + (Swizzle::SW_64KB_S, 2, Dimension::Tex3d, 16), + ] { + for element_log2 in 0..5 { + let d = Desc { + dimension, + depth: 8, + ..desc(128, 96, 7, 1 << element_log2, swizzle) + }; + let first = Layout::new(&d).unwrap(); + let second = Layout::new(&Desc { + width: 32, + height: 24, + mips: 3, + depth: 1, + ..d + }) + .unwrap(); + let expected = pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)); + assert_eq!(first.pattern, &expected); + assert!(std::ptr::eq(first.pattern, second.pattern)); + assert!(std::ptr::eq(first.pattern, first.clone().pattern)); + } + } + } + /// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8, /// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail. #[test] @@ -1124,6 +1192,74 @@ mod tests { assert_eq!(l.mips[0].offset, 8192 + 16384); } + /// The smaller mips lie first: they are read from the memory that holds + /// them alone, as from the whole texture's. + #[test] + fn smaller_mips_need_only_the_start_of_the_texture() { + // 1024x1024 BC1 (8-byte elements) in 4 KiB blocks: the tail (from + // 64x64 on), then 128x128 in two blocks, 256x256 in eight. + let l = Layout::new(&Desc { + block: 4, + ..desc(1024, 1024, 9, 8, Swizzle::SW_4KB_S) + }) + .unwrap(); + assert_eq!(l.bytes_from(0), l.size); + let needs: Vec<u64> = (0..9).map(|mip| l.bytes_from(mip)).collect(); + assert!(needs.windows(2).all(|w| w[0] >= w[1]), "{needs:?}"); + assert_eq!((l.bytes_from(4), l.bytes_from(8)), (4096, 4096)); + let tiled: Vec<u8> = (0..l.size).map(|i| ((i * 7) >> 3) as u8).collect(); + for mip in 1..9 { + let m = l.mips[mip as usize]; + let pitch = m.width as usize * 8; + let read = |tiled: &[u8]| { + let mut linear = vec![0; pitch * m.height as usize]; + l.detile(tiled, mip, 0, &mut linear, pitch, pitch * m.height as usize) + .map(|()| linear) + }; + let len = l.bytes_from(mip) as usize; + let expected = read(&tiled).unwrap(); + assert_eq!(read(&tiled[..len]).unwrap(), expected); + let mut prefix = vec![0; len]; + l.tile( + &mut prefix, + mip, + 0, + &expected, + pitch, + pitch * m.height as usize, + ) + .unwrap(); + assert_eq!(read(&prefix).unwrap(), expected); + assert_eq!(read(&tiled[..len - 1]), Err(Error::TooSmall)); + } + // Slices each hold their chain: the whole texture. + let l = Layout::new(&Desc { + depth: 2, + block: 4, + ..desc(1024, 1024, 9, 8, Swizzle::SW_4KB_S) + }) + .unwrap(); + assert_eq!(l.bytes_from(4), l.size); + } + + #[test] + fn thin_volume_mips_report_the_depth_allocated_per_chain() { + let d = Desc { + dimension: Dimension::Tex3d, + depth: 8, + ..desc(128, 128, 4, 4, Swizzle::SW_64KB_R_X) + }; + let layout = Layout::new(&d).unwrap(); + assert!(!layout.thick); + assert_eq!(layout.slices, 8); + assert_eq!(layout.size, layout.slice_size * 8); + assert!(layout.first_tail_mip > 0 && layout.first_tail_mip < d.mips); + for (i, mip) in layout.mips.iter().enumerate() { + assert_eq!(mip.depth, d.depth >> i); + assert_eq!(mip.depth_pitch, d.depth); + } + } + #[test] fn depth_stencil_is_two_planes() { let t = Texture::new(&TextureDesc { @@ -1160,81 +1296,6 @@ mod tests { ); } - fn volume_pitch_layout(swizzle: Swizzle) -> Layout { - Layout::new(&Desc { - dimension: Dimension::Tex3d, - depth: 2, - ..desc(4, 2, 1, 4, swizzle) - }) - .unwrap() - } - - #[test] - fn depth_pitch_rejects_overlapping_detile() { - for swizzle in [Swizzle::LINEAR, Swizzle::SW_4KB_S] { - let l = volume_pitch_layout(swizzle); - let tiled = vec![0x42; l.size as usize]; - let mut linear = [0xcc; 72]; - - for pitch in [0, 16, 35] { - assert_eq!( - l.detile(&tiled, 0, 0, &mut linear, 20, pitch), - Err(Error::TooSmall), - "{swizzle:?}, pitch {pitch}" - ); - - assert_eq!(linear, [0xcc; 72]); - } - } - } - - #[test] - fn depth_pitch_rejects_overlapping_tile() { - for swizzle in [Swizzle::LINEAR, Swizzle::SW_4KB_S] { - let l = volume_pitch_layout(swizzle); - let mut tiled = vec![0xcc; l.size as usize]; - let linear = [0x42; 72]; - - for pitch in [0, 16, 35] { - assert_eq!( - l.tile(&mut tiled, 0, 0, &linear, 20, pitch), - Err(Error::TooSmall), - "{swizzle:?}, pitch {pitch}" - ); - - assert!(tiled.iter().all(|&b| b == 0xcc)); - } - } - } - - #[test] - fn depth_pitch_accepts_exact_and_padded_slices() { - for swizzle in [Swizzle::LINEAR, Swizzle::SW_4KB_S] { - let l = volume_pitch_layout(swizzle); - - for pitch in [36usize, 40, 64] { - let len = pitch + 36; - let mut tiled = vec![0; l.size as usize]; - - let linear: Vec<u8> = (0..len).map(|i| i as u8).collect(); - - let mut back = vec![0xcc; len]; - - l.tile(&mut tiled, 0, 0, &linear, 20, pitch).unwrap(); - - l.detile(&tiled, 0, 0, &mut back, 20, pitch).unwrap(); - - for z in 0..2 { - for y in 0..2 { - let start = z * pitch + y * 20; - - assert_eq!(back[start..start + 16], linear[start..start + 16]); - } - } - } - } - } - #[test] fn volume_copy_rejects_overflowing_depth_pitch() { let layout = Layout::new(&Desc { diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index 73a92a0565..3a1f51f5e7 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -149,25 +149,10 @@ fn next_frame(data: &[u8], start: usize, end: usize) -> Option<usize> { } let last = number + 1 >= header.frames; let mut end = end; - // A frame that ends in a packet where no frame begins (the tail of a frame - // that crossed packets, then padding) is the last one before the next - // packet that has frames. - let ends_in_packet_without_frames = end / PACKET_BITS != index - && !end.is_multiple_of(PACKET_BITS) - && packet(data, end / PACKET_BITS)?.frames == 0; - if end.is_multiple_of(PACKET_BITS) - || (last && end / PACKET_BITS == index) - || ends_in_packet_without_frames - { - // The next frame begins in the next packet of this stream that has one; - // a packet with none (a frame spans all of it) holds no start. - let mut next = - (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; - let mut header = packet(data, next)?; - while header.frames == 0 { - next += 1 + header.skip as usize; - header = packet(data, next)?; - } + if end.is_multiple_of(PACKET_BITS) || (last && end / PACKET_BITS == index) { + // The next frame begins in the next packet of this stream. + let next = (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; + let header = packet(data, next)?; end = next * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; } (end / 8 < data.len()).then_some(end) @@ -191,10 +176,16 @@ impl Bits<'_> { (v << (24 + self.pos % 8) >> 32) as u32 } + /// The next `n` bits as an unsigned number. Past 32 bits only the low 32 + /// are kept, and all `n` are consumed. fn read(&mut self, n: u32) -> u32 { if n == 0 { return 0; } + if n > 32 { + self.pos += (n - 32) as usize; + return self.read(32); + } let v = self.peek32() >> (32 - n); self.pos += n as usize; v @@ -204,8 +195,17 @@ impl Bits<'_> { self.read(1) != 0 } + /// The next `n` bits as a two's complement number. Zero bits read as 0; + /// from 32 bits on, the low 32 are the value, as with `read`. fn signed(&mut self, n: u32) -> i32 { - ((self.read(n) << (32 - n)) as i32) >> (32 - n) + match n { + 0 => 0, + 1..32 => { + let shift = 32 - n; + ((self.read(n) << shift) as i32) >> shift + } + _ => self.read(n) as i32, + } } fn consumed(&self) -> usize { @@ -222,8 +222,6 @@ impl Bits<'_> { struct Vlc { /// Left-aligned code, length, symbol; sorted by code. codes: Vec<(u32, u8, i32)>, - /// Candidate range for each leading eight-bit prefix. - prefixes: [(usize, usize); 256], } impl Vlc { @@ -234,24 +232,12 @@ impl Vlc { codes.push((code as u32, len, symbol)); code += 1 << (32 - len); } - let prefixes = std::array::from_fn(|prefix| { - let low = (prefix as u32) << 24; - let high = low | 0x00ff_ffff; - let first = codes.partition_point(|c| c.0 <= low) - 1; - let end = codes.partition_point(|c| c.0 <= high); - (first, end) - }); - Vlc { codes, prefixes } + Vlc { codes } } fn read(&self, bits: &mut Bits) -> i32 { let v = bits.peek32(); - let (first, end) = self.prefixes[(v >> 24) as usize]; - let i = if end == first + 1 { - first - } else { - first + self.codes[first..end].partition_point(|c| c.0 <= v) - 1 - }; + let i = self.codes.partition_point(|c| c.0 <= v) - 1; let (_, len, symbol) = self.codes[i]; bits.pos += len as usize; symbol @@ -277,20 +263,10 @@ fn codes() -> &'static Codes { scale: pairs(&SCALE, -60), scale_rl: pairs(&SCALE_RL, 0), coef: [ - Vlc::new( - COEF0_SYMS - .iter() - .zip(COEF0_LENS) - .map(|(&s, l)| (s as i32, l)), - ), + Vlc::new(COEF0_SYMS.iter().zip(COEF0_LENS).map(|(&s, l)| (s as i32, l))), pairs(&COEF1, 0), ], - vec4: Vlc::new( - VEC4_SYMS - .iter() - .zip(VEC4_LENS) - .map(|(&s, l)| (s as i32 - 1, l)), - ), + vec4: Vlc::new(VEC4_SYMS.iter().zip(VEC4_LENS).map(|(&s, l)| (s as i32 - 1, l))), vec2: pairs(&VEC2, -1), vec1: pairs(&VEC1, 0), } @@ -322,180 +298,59 @@ fn log2(v: usize) -> u32 { /// `n` coefficients to the middle `n` samples of the 2n-sample window, /// negated and scaled by `scale`. Computed as a DCT-IV through an /// n/2-point complex FFT. -/// -/// The rotations come from [`Rotations`], built once per subframe size, so -/// a subframe costs no sines or cosines and no allocation. fn imdct_half(input: &[f32], out: &mut [f32], scale: f32) { let n = input.len(); let m = n / 2; - let built; - let rotations = match rotations().get(log2(n).wrapping_sub(7) as usize) { - Some(r) if r.pre_re.len() == m => r, - _ => { - built = Rotations::new(n); - &built - } - }; - let mut stack = [0f64; FRAME_SAMPLES]; - let mut heap = Vec::new(); - let (re, im) = if m <= stack.len() / 2 { - stack.split_at_mut(m) - } else { - heap.resize(2 * m, 0f64); - heap.split_at_mut(m) - }; - let im = &mut im[..m]; - // Pre-rotation, each point stored at its bit-reversed place, which is - // where the FFT's input permutation would move it. - let pre = rotations - .pre_re - .iter() - .zip(&rotations.pre_im) - .zip(&rotations.reversed); - for (k, ((&c, &s), &to)) in pre.enumerate() { + let mut re = vec![0f64; m]; + let mut im = vec![0f64; m]; + for k in 0..m { let (a, b) = (input[2 * k] as f64, input[n - 1 - 2 * k] as f64); - re[to as usize] = a * c - b * s; - im[to as usize] = a * s + b * c; + let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos(); + (re[k], im[k]) = (a * c - b * s, a * s + b * c); } - rotations.butterflies(re, im); - let post = rotations.post_re.iter().zip(&rotations.post_im); - for (k, ((&re, &im), (&c, &s))) in re.iter().zip(im.iter()).zip(post).enumerate() { - let (wr, wi) = (re * c - im * s, re * s + im * c); + fft(&mut re, &mut im); + for k in 0..m { + let (s, c) = (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos(); + let (wr, wi) = (re[k] * c - im[k] * s, re[k] * s + im[k] * c); // DCT-IV: c[2k] = Re, c[n-1-2k] = -Im; output j is c[n-1-j]. out[n - 1 - 2 * k] = (wr as f32) * scale; out[2 * k] = -(wi as f32) * scale; } } -/// Everything [`imdct_half`] needs for one size `n` that does not depend on -/// the coefficients: the pre-rotation `exp(-iπk/n)` and post-rotation -/// `exp(-iπ(4k+1)/4n)` of each of the n/2 FFT points, the FFT's bit-reversed -/// order and its butterfly rotations. Each value is computed with the same -/// expression (for the butterflies the same running product) the transform -/// used to work out on every call, so it gives the same bits. -struct Rotations { - pre_re: Vec<f64>, - pre_im: Vec<f64>, - post_re: Vec<f64>, - post_im: Vec<f64>, - /// Where the bit-reversal permutation puts each point. - reversed: Vec<u16>, - /// The butterfly rotations of every stage, the stage of length `len` - /// starting at `len / 2 - 1`. - twiddle_re: Vec<f64>, - twiddle_im: Vec<f64>, -} - -impl Rotations { - fn new(n: usize) -> Rotations { - let m = n / 2; - let (pre_re, pre_im) = (0..m) - .map(|k| { - let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos(); - (c, s) - }) - .unzip(); - let (post_re, post_im) = (0..m) - .map(|k| { - let (s, c) = - (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos(); - (c, s) - }) - .unzip(); - // The swaps of the in-place bit-reversal, applied to the identity. - let mut reversed: Vec<u16> = (0..m as u16).collect(); - let mut j = 0; - for i in 1..m { - let mut bit = m >> 1; - while j & bit != 0 { - j ^= bit; - bit >>= 1; - } - j |= bit; - if i < j { - reversed.swap(i, j); - } +/// In-place radix-2 forward DFT (`exp(-2πi nk/N)`). +fn fft(re: &mut [f64], im: &mut [f64]) { + let n = re.len(); + let mut j = 0; + for i in 1..n { + let mut bit = n >> 1; + while j & bit != 0 { + j ^= bit; + bit >>= 1; + } + j |= bit; + if i < j { + re.swap(i, j); + im.swap(i, j); } - let mut twiddle_re = Vec::with_capacity(m.saturating_sub(1)); - let mut twiddle_im = Vec::with_capacity(m.saturating_sub(1)); - let mut len = 2; - while len <= m { - let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos(); + } + let mut len = 2; + while len <= n { + let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos(); + for start in (0..n).step_by(len) { let (mut cr, mut ci) = (1.0, 0.0); - for _ in 0..len / 2 { - twiddle_re.push(cr); - twiddle_im.push(ci); + for k in 0..len / 2 { + let (a, b) = (start + k, start + k + len / 2); + let (tr, ti) = (re[b] * cr - im[b] * ci, re[b] * ci + im[b] * cr); + (re[b], im[b]) = (re[a] - tr, im[a] - ti); + (re[a], im[a]) = (re[a] + tr, im[a] + ti); (cr, ci) = (cr * wc - ci * ws, cr * ws + ci * wc); } - len <<= 1; } - Rotations { - pre_re, - pre_im, - post_re, - post_im, - reversed, - twiddle_re, - twiddle_im, - } - } - - /// The butterfly stages of an in-place radix-2 forward DFT - /// (`exp(-2πi nk/N)`) on points already in bit-reversed order. - fn butterflies(&self, re: &mut [f64], im: &mut [f64]) { - let m = re.len().min(im.len()); - let mut len = 2; - while len <= m { - let half = len / 2; - let wr = &self.twiddle_re[half - 1..][..half]; - let wi = &self.twiddle_im[half - 1..][..half]; - let blocks = re[..m] - .chunks_exact_mut(len) - .zip(im[..m].chunks_exact_mut(len)); - for (re, im) in blocks { - let (are, bre) = re.split_at_mut(half); - let (aim, bim) = im.split_at_mut(half); - butterfly_block(are, aim, bre, bim, wr, wi); - } - len <<= 1; - } - } -} - -/// One block of butterflies: `a + w·b` into `a`, `a − w·b` into `b`. -#[inline(always)] -fn butterfly_block( - are: &mut [f64], - aim: &mut [f64], - bre: &mut [f64], - bim: &mut [f64], - wr: &[f64], - wi: &[f64], -) { - let lanes = are - .iter_mut() - .zip(aim) - .zip(bre.iter_mut().zip(bim)) - .zip(wr.iter().zip(wi)); - for (((ar, ai), (br, bi)), (&cr, &ci)) in lanes { - let (tr, ti) = (*br * cr - *bi * ci, *br * ci + *bi * cr); - (*br, *bi) = (*ar - tr, *ai - ti); - (*ar, *ai) = (*ar + tr, *ai + ti); + len <<= 1; } } -/// [`Rotations`] for subframes of 128, 256 and 512 samples. -fn rotations() -> &'static [Rotations; 3] { - static ROTATIONS: OnceLock<[Rotations; 3]> = OnceLock::new(); - ROTATIONS.get_or_init(|| { - [ - Rotations::new(128), - Rotations::new(256), - Rotations::new(512), - ] - }) -} - /// `ff_sine_windows`: the rising half of a sine window of length `n`. fn sine_window(n: usize) -> Vec<f32> { (0..n) @@ -653,10 +508,7 @@ impl Decoder { let mut b = Bits { data, pos: 0, - // Past the data there are only zeros to read. A count beyond it - // would never let a stereo tile header overread, and its loop - // takes no subframe on zero bits, so it would spin for good. - end: bits.min(data.len().saturating_mul(8)), + end: bits, }; let len = b.read(LENGTH_BITS) as usize; let result = self.frame(&mut b, len); @@ -920,11 +772,7 @@ impl Decoder { ch.scale_factors = target; if ch.reuse_sf { let from = ch.saved_scale_factors[ch.scale_factor_idx]; - for (sf, &offset) in ch.saved_scale_factors[target] - .iter_mut() - .zip(&sf_offsets) - .take(self.num_bands) - { + for (sf, &offset) in ch.saved_scale_factors[target].iter_mut().zip(&sf_offsets).take(self.num_bands) { *sf = from[offset]; } } @@ -1057,11 +905,7 @@ impl Decoder { } quant += 31; } - quant_step += if negative { - -(quant + step) - } else { - quant + step - }; + quant_step += if negative { -(quant + step) } else { quant + step }; } if self.channels_for_cur_subframe == 1 { self.ch[self.channel_indexes[0]].quant_step = quant_step; @@ -1104,21 +948,13 @@ impl Decoder { let sf = ch.saved_scale_factors[ch.scale_factors]; for band in 0..self.num_bands { let end = sfb[band + 1].min(subframe_len); - let exp = - ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; + let exp = ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; let quant = 10f32.powf(exp as f32 / 20.0); - for (t, &c) in tmp[sfb[band]..end] - .iter_mut() - .zip(&ch.coeffs[sfb[band]..end]) - { + for (t, &c) in tmp[sfb[band]..end].iter_mut().zip(&ch.coeffs[sfb[band]..end]) { *t = c * quant; } } - imdct_half( - &tmp[..subframe_len], - &mut ch.out[at..at + subframe_len], - scale, - ); + imdct_half(&tmp[..subframe_len], &mut ch.out[at..at + subframe_len], scale); } } else { for i in 0..self.channels_for_cur_subframe { @@ -1135,10 +971,7 @@ impl Decoder { start += (winlen - subframe_len) / 2; winlen = subframe_len; } - window_overlap( - &mut ch.out[start..start + winlen], - &windows()[log2(winlen) as usize - 7], - ); + window_overlap(&mut ch.out[start..start + winlen], &windows()[log2(winlen) as usize - 7]); ch.prev_block_len = subframe_len; } @@ -1205,183 +1038,6 @@ fn to_i16(v: f32) -> i16 { mod tests { use super::*; - fn vlc_books() -> [&'static Vlc; 7] { - let c = codes(); - [ - &c.scale, - &c.scale_rl, - &c.coef[0], - &c.coef[1], - &c.vec4, - &c.vec2, - &c.vec1, - ] - } - - fn vlc_reference(vlc: &Vlc, bits: &mut Bits<'_>) -> i32 { - let v = bits.peek32(); - let i = vlc.codes.partition_point(|c| c.0 <= v) - 1; - let (_, len, symbol) = vlc.codes[i]; - bits.pos += len as usize; - symbol - } - - #[test] - fn vlc_prefix_matches_binary_search() { - for book in vlc_books() { - let mut probes = vec![0, u32::MAX]; - - for &(code, _, _) in &book.codes { - probes.push(code); - probes.push(code.saturating_sub(1)); - probes.push(code.saturating_add(1)); - } - - for prefix in 0..256u32 { - probes.push(prefix << 24); - probes.push((prefix << 24) | 0x00ff_ffff); - } - - let mut seed = 123456789u32; - for _ in 0..4096 { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - probes.push(seed); - } - - for value in probes { - for shift in 0..8usize { - let data = (u64::from(value) << (32 - shift)).to_be_bytes(); - - let mut expected = Bits { - data: &data, - pos: shift, - end: 64, - }; - - let mut actual = Bits { - data: &data, - pos: shift, - end: 64, - }; - - assert_eq!( - book.read(&mut actual), - vlc_reference(book, &mut expected), - "value={value:#x}, shift={shift}" - ); - - assert_eq!(actual.pos, expected.pos); - } - } - } - } - - #[test] - #[ignore = "synthetic release microbenchmark"] - fn vlc_prefix_benchmark() { - use std::hint::black_box; - use std::time::Instant; - - fn measure<const OPT: bool>(samples: &[(usize, [u8; 4])], books: &[&Vlc; 7]) -> (f64, i64) { - let start = Instant::now(); - let mut sum = 0i64; - - for _ in 0..64 { - for &(index, ref data) in samples { - let book = black_box(books[index]); - - let mut bits = Bits { - data: black_box(data), - pos: 0, - end: 32, - }; - - let symbol = if OPT { - book.read(&mut bits) - } else { - vlc_reference(book, &mut bits) - }; - - sum = sum - .wrapping_add(i64::from(symbol)) - .wrapping_add(bits.pos as i64); - } - } - - (start.elapsed().as_secs_f64() * 1000.0, black_box(sum)) - } - - let books = vlc_books(); - - for (label, short_only) in [("all_codes", false), ("short_codes", true)] { - let mut corpus = Vec::new(); - - for (index, book) in books.iter().enumerate() { - for &(code, len, _) in &book.codes { - if !short_only || len <= 8 { - corpus.push((index, code.to_be_bytes())); - } - } - } - - assert!(!corpus.is_empty()); - - let mut seed = 123456789u32; - - let samples: Vec<_> = (0..16384) - .map(|_| { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - corpus[seed as usize % corpus.len()] - }) - .collect(); - - let warmup_a = measure::<false>(&samples, &books); - let warmup_b = measure::<true>(&samples, &books); - assert_eq!(warmup_a.1, warmup_b.1); - - let mut reference = Vec::new(); - let mut candidate = Vec::new(); - - for round in 0..5 { - let (a, b) = if round % 2 == 0 { - let a = measure::<false>(&samples, &books); - let b = measure::<true>(&samples, &books); - (a, b) - } else { - let b = measure::<true>(&samples, &books); - let a = measure::<false>(&samples, &books); - (a, b) - }; - - assert_eq!(a.1, b.1); - reference.push(a.0); - candidate.push(b.0); - - println!( - "{label} round={round}: \ - reference={:.3}ms candidate={:.3}ms", - a.0, b.0 - ); - } - - reference.sort_by(f64::total_cmp); - candidate.sort_by(f64::total_cmp); - - println!( - "MEDIAN {label}: \ - reference={:.3}ms candidate={:.3}ms \ - speedup={:.3}x checksum=OK", - reference[2], - candidate[2], - reference[2] / candidate[2] - ); - } - } - /// Writes `value` as `n` bits, MSB first, at bit `pos`. fn put_bits(data: &mut [u8], pos: usize, n: u32, value: u32) { for i in 0..n as usize { @@ -1391,6 +1047,36 @@ mod tests { } } + /// Bit widths at the edges of what `Bits` can return: none, a full + /// 32-bit word, and more than one word. None of them may overflow a shift. + #[test] + fn bits_read_zero_full_and_oversized_widths() { + let mut data = [0u8; 16]; + put_bits(&mut data, 0, 6, 0b11_1110); // -2 in 6 bits + put_bits(&mut data, 6, 32, 0x1234_5678); + put_bits(&mut data, 38, 32, 0xffff_fffe); // -2 in 32 bits + put_bits(&mut data, 70, 8, 0xab); // dropped high bits of a 40-bit read + put_bits(&mut data, 78, 32, 0x8000_0001); + let mut b = Bits { + data: &data, + pos: 0, + end: data.len() * 8, + }; + + assert_eq!(b.signed(0), 0); + assert_eq!(b.read(0), 0); + assert_eq!(b.consumed(), 0, "zero-width reads consume nothing"); + assert_eq!(b.signed(6), -2); + assert_eq!(b.read(32), 0x1234_5678); + assert_eq!(b.signed(32), -2); + assert_eq!(b.read(40), 0x8000_0001, "the low 32 bits of a 40-bit field"); + assert_eq!(b.consumed(), 110); + + b.pos = 70; + assert_eq!(b.signed(40), 0x8000_0001_u32 as i32); + assert_eq!(b.consumed(), 110); + } + /// A damaged packet whose first frame says it is 0 bits long: finding /// the frame after a later one must give up, not walk in place forever /// (found by random-input testing). @@ -1406,40 +1092,6 @@ mod tests { assert_eq!(frame.next, None); } - /// A frame that crosses a packet where no frame begins (a full - /// continuation) and ends in another such packet, followed by padding: the - /// next frame is the first one of the next packet that has frames, not the - /// padding the frame ended in. - #[test] - fn the_frame_after_continuation_packets_starts_in_the_next_packet_with_frames() { - let mut data = vec![0u8; 4 * PACKET_BYTES]; - let header = |frames: u32, first: u32| (frames << 26) | (first << 11); - put_bits(&mut data, 0, 32, header(2, 0)); - // Packet 1 is all of one frame; packet 2 holds only its last 64 bits. - put_bits(&mut data, PACKET_BITS, 32, header(0, 0x7fff)); - put_bits(&mut data, 2 * PACKET_BITS, 32, header(0, 64)); - put_bits(&mut data, 3 * PACKET_BITS, 32, header(1, 0)); - // A first frame of 16000 bits, then one from the end of its payload - // through packets 1 and 2. - let second = HEADER_BITS + 16000; - put_bits(&mut data, HEADER_BITS, LENGTH_BITS, 16000); - let tail = PACKET_BITS - second; - let bits = tail + (PACKET_BITS - HEADER_BITS) + 64; - put_bits(&mut data, second, LENGTH_BITS, bits as u32); - put_bits(&mut data, 3 * PACKET_BITS + HEADER_BITS, LENGTH_BITS, 100); - let first = read_frame(&data, HEADER_BITS).unwrap(); - assert_eq!(first.next, Some(second)); - let frame = read_frame(&data, second).unwrap(); - assert_eq!(frame.bits, bits); - assert_eq!(frame.next, Some(3 * PACKET_BITS + HEADER_BITS)); - assert_eq!( - read_frame(&data, 3 * PACKET_BITS + HEADER_BITS) - .unwrap() - .next, - None - ); - } - /// The direct sum `imdct_half` stands for (FFmpeg's naive inverse MDCT: /// the standard formula, negated). fn imdct_reference(input: &[f32]) -> Vec<f32> { @@ -1450,9 +1102,7 @@ mod tests { -(input .iter() .enumerate() - .map(|(k, &x)| { - x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos() - }) + .map(|(k, &x)| x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos()) .sum::<f64>() as f32) }) .collect() @@ -1471,147 +1121,6 @@ mod tests { } } - /// The transform as it was before [`Rotations`]: every rotation worked - /// out again on each call, the FFT on two fresh buffers. - fn imdct_half_untabled(input: &[f32], out: &mut [f32], scale: f32) { - let n = input.len(); - let m = n / 2; - let mut re = vec![0f64; m]; - let mut im = vec![0f64; m]; - for k in 0..m { - let (a, b) = (input[2 * k] as f64, input[n - 1 - 2 * k] as f64); - let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos(); - (re[k], im[k]) = (a * c - b * s, a * s + b * c); - } - let mut j = 0; - for i in 1..m { - let mut bit = m >> 1; - while j & bit != 0 { - j ^= bit; - bit >>= 1; - } - j |= bit; - if i < j { - re.swap(i, j); - im.swap(i, j); - } - } - let mut len = 2; - while len <= m { - let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos(); - for start in (0..m).step_by(len) { - let (mut cr, mut ci) = (1.0, 0.0); - for k in 0..len / 2 { - let (a, b) = (start + k, start + k + len / 2); - let (tr, ti) = (re[b] * cr - im[b] * ci, re[b] * ci + im[b] * cr); - (re[b], im[b]) = (re[a] - tr, im[a] - ti); - (re[a], im[a]) = (re[a] + tr, im[a] + ti); - (cr, ci) = (cr * wc - ci * ws, cr * ws + ci * wc); - } - } - len <<= 1; - } - for k in 0..m { - let (s, c) = (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos(); - let (wr, wi) = (re[k] * c - im[k] * s, re[k] * s + im[k] * c); - out[n - 1 - 2 * k] = (wr as f32) * scale; - out[2 * k] = -(wi as f32) * scale; - } - } - - /// Pseudo-random coefficients spread over many magnitudes, as dequantised - /// subframes are. - fn noise(n: usize, seed: u64) -> Vec<f32> { - let mut state = seed | 1; - (0..n) - .map(|_| { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - let mantissa = (state >> 40) as f32 / (1u64 << 24) as f32 - 0.5; - mantissa * 2f32.powi((state % 24) as i32 - 4) - }) - .collect() - } - - /// The tables change nothing: every subframe size (and sizes the decoder - /// never uses, which build their tables on the spot) gives the bits the - /// untabled transform gives. - #[test] - fn tabled_imdct_gives_the_same_bits() { - for n in [2usize, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048] { - for seed in 0..16 { - let input = noise(n, seed * 7919 + n as u64); - let scale = 2.0 / n as f32 / 32768.0; - let mut tabled = vec![0f32; n]; - let mut untabled = vec![0f32; n]; - imdct_half(&input, &mut tabled, scale); - imdct_half_untabled(&input, &mut untabled, scale); - let tabled: Vec<u32> = tabled.iter().map(|v| v.to_bits()).collect(); - let untabled: Vec<u32> = untabled.iter().map(|v| v.to_bits()).collect(); - assert_eq!(tabled, untabled, "n {n}, seed {seed}"); - } - } - let mut out = [0f32; 0]; - imdct_half(&[], &mut out, 1.0); - } - - /// The cached tables are the ones the sizes ask for. - #[test] - fn cached_rotations_match_their_sizes() { - for (r, n) in rotations().iter().zip([128usize, 256, 512]) { - let fresh = Rotations::new(n); - assert_eq!((&r.pre_re, &r.pre_im), (&fresh.pre_re, &fresh.pre_im)); - assert_eq!((&r.post_re, &r.post_im), (&fresh.post_re, &fresh.post_im)); - assert_eq!(r.reversed, fresh.reversed); - assert_eq!( - (&r.twiddle_re, &r.twiddle_im), - (&fresh.twiddle_re, &fresh.twiddle_im) - ); - assert_eq!(r.pre_re.len(), n / 2); - assert_eq!(r.twiddle_re.len(), n / 2 - 1); - // The order is a permutation that undoes itself. - for (i, &to) in r.reversed.iter().enumerate() { - assert_eq!(r.reversed[to as usize] as usize, i); - } - } - } - - /// Release benchmark of one inverse transform per subframe size, tabled - /// against untabled: - /// `cargo test --release -p victory-formats imdct_throughput -- --ignored --nocapture`. - #[test] - #[ignore = "benchmark"] - fn imdct_throughput() { - for n in [128usize, 256, 512] { - let inputs: Vec<Vec<f32>> = (0..64).map(|seed| noise(n, seed)).collect(); - let mut out = vec![0f32; n]; - let rounds = 20_000; - let mut time = |f: fn(&[f32], &mut [f32], f32)| { - let mut best = f64::MAX; - for _ in 0..3 { - let started = std::time::Instant::now(); - for i in 0..rounds { - f( - std::hint::black_box(&inputs[i % inputs.len()]), - &mut out, - 1.0, - ); - std::hint::black_box(&out); - } - best = best.min(started.elapsed().as_secs_f64() * 1e9 / rounds as f64); - } - best - }; - let before = time(imdct_half_untabled); - let after = time(imdct_half); - println!( - "n {n}: untabled {before:.0} ns, tabled {after:.0} ns, {:.1}x", - before / after - ); - } - } - /// Windowed MDCT blocks of a signal, put back together the way the /// decoder does (half IMDCT, then window and overlap), give the signal. #[test] @@ -1645,12 +1154,7 @@ mod tests { } } for i in n..5 * n { - assert!( - (out[i] - signal[i]).abs() < 1e-3, - "{i}: {} vs {}", - out[i], - signal[i] - ); + assert!((out[i] - signal[i]).abs() < 1e-3, "{i}: {} vs {}", out[i], signal[i]); } } @@ -1694,240 +1198,6 @@ mod tests { assert_eq!(c.next, None); } - /// Deterministic noise: xorshift64, as in BCPack's noise test. - struct Noise(u64); - - impl Noise { - fn next(&mut self) -> u64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - self.0 - } - - /// A number below `n`. - fn below(&mut self, n: usize) -> usize { - (self.next() % n as u64) as usize - } - - /// `len` bytes of even noise, or of mostly zeros (`density` 1) or - /// mostly ones (2), which take other paths through a frame. - fn bytes(&mut self, len: usize, density: usize) -> Vec<u8> { - (0..len) - .map(|_| { - let r = self.next(); - let (a, b, c) = (r as u8, (r >> 8) as u8, (r >> 16) as u8); - match density { - 0 => a, - 1 => a & b & c, - _ => a | b | c, - } - }) - .collect() - } - } - - /// Writes `value` as `n` bits, MSB first, at bit `pos`, over what is there. - fn set_bits(data: &mut [u8], pos: usize, n: u32, value: u32) { - for i in 0..n as usize { - let (p, bit) = (pos + i, (value >> (n as usize - 1 - i)) & 1); - data[p / 8] = (data[p / 8] & !(0x80 >> (p % 8))) | ((bit as u8) << (7 - p % 8)); - } - } - - /// `packets` packets of one stream: back-to-back frames of noise after - /// their length fields, 300 to 4299 bits long (so every packet but the - /// last has a frame start, and at most 55 do), then padding of ones. - /// The headers count the frames that begin in each packet. Also gives - /// the number of frames. - fn noise_stream(noise: &mut Noise, packets: usize, density: usize) -> (Vec<u8>, usize) { - const PAYLOAD: usize = PACKET_BITS - HEADER_BITS; - let mut data = noise.bytes(packets * PACKET_BYTES, density); - // Where payload bit `q` of the stream is in the buffer. - let at = |q: usize| q / PAYLOAD * PACKET_BITS + HEADER_BITS + q % PAYLOAD; - let mut headers = vec![(0u32, 0u32); packets]; - let (mut q, mut frames) = (0, 0); - loop { - let len = 300 + noise.below(4000); - if q + len > packets * PAYLOAD { - break; - } - let header = &mut headers[q / PAYLOAD]; - if header.0 == 0 { - header.1 = (q % PAYLOAD) as u32; - } - header.0 += 1; - for i in 0..LENGTH_BITS { - let bit = (len >> (LENGTH_BITS - 1 - i)) as u32 & 1; - set_bits(&mut data, at(q + i as usize), 1, bit); - } - q += len; - frames += 1; - } - for padding in q..packets * PAYLOAD { - set_bits(&mut data, at(padding), 1, 1); - } - for (p, &(count, first)) in headers.iter().enumerate() { - set_bits(&mut data, p * PACKET_BITS, 32, count << 26 | first << 11); - } - (data, frames) - } - - /// Packets of noise, streams of frames of noise, and such streams with - /// headers and bits damaged: walking the frames from the first packet - /// and decoding each, mono and stereo, gives a frame of samples per - /// frame and ends within the frames the buffer can hold (each is over - /// 15 bits and the walk only moves on). - #[test] - fn noise_packets_walk_and_decode() { - let mut noise = Noise(0x2545_f491_4f6c_dd1d); - for round in 0..60 { - let packets = 1 + round % 4; - let density = [0, 0, 1, 2][round / 3 % 4]; - let (mut data, written) = match round % 3 { - 0 => (noise.bytes(packets * PACKET_BYTES, density), 0), - _ => noise_stream(&mut noise, packets, density), - }; - if round % 3 == 2 { - for _ in 0..1 + noise.below(3) { - let p = noise.below(packets); - set_bits(&mut data, p * PACKET_BITS, 32, noise.next() as u32); - } - for _ in 0..noise.below(16) { - let bit = noise.below(data.len() * 8); - data[bit / 8] ^= 0x80 >> (bit % 8); - } - } - let budget = data.len() * 8 / 16; - for channels in [1, 2] { - let mut decoder = Decoder::new(channels, 48_000); - let per_frame = FRAME_SAMPLES * channels; - let (mut pcm, mut frames) = (Vec::new(), 0); - let mut at = packet(&data, 0).map(|p| HEADER_BITS + p.first_frame_bit as usize); - while let Some(frame) = at.and_then(|bit| read_frame(&data, bit)) { - frames += 1; - let moves_on = frame.next.is_none_or(|next| next > frame.start); - assert!(frames <= budget && moves_on, "round {round}"); - let _ = decoder.decode(&frame.data, frame.bits, &mut pcm); - assert_eq!(pcm.len(), frames * per_frame, "round {round}"); - at = frame.next; - } - if round % 3 == 1 { - // A clean stream: every frame is walked. - assert_eq!(frames, written, "round {round}"); - } - decoder.flush(&mut pcm); - assert_eq!(pcm.len(), frames * per_frame + per_frame / 2); - } - } - } - - /// Frames of noise, mono and stereo at each sample rate, with bit - /// counts up to the end of the data: every decode gives one frame of - /// samples, whether the frame decodes or not. - #[test] - fn noise_frames_decode_to_a_frame_of_samples() { - let mut noise = Noise(0x9e37_79b9_7f4a_7c15); - for channels in [1, 2] { - for rate in [24_000, 32_000, 44_100, 48_000] { - let mut decoder = Decoder::new(channels, rate); - let mut pcm = Vec::new(); - for round in 0..48 { - let data = noise.bytes(round * 89 % 4096, [0, 0, 1, 2][round % 4]); - let bits = match round % 2 { - 0 => data.len() * 8, - _ => noise.below(data.len() * 8 + 1), - }; - pcm.clear(); - let _ = decoder.decode(&data, bits, &mut pcm); - assert_eq!( - pcm.len(), - FRAME_SAMPLES * channels, - "{channels} channels, {rate} Hz, round {round}" - ); - if round % 16 == 15 { - decoder.reset(); - } - } - pcm.clear(); - decoder.flush(&mut pcm); - assert_eq!(pcm.len(), FRAME_SAMPLES / 2 * channels); - } - } - } - - /// Bit counts past the end of a frame's data, up to `usize::MAX`: the - /// decoding ends, with a frame of samples. A stereo tile header that ran - /// out of data used to loop on the zeros past it for good (found by - /// this test). - #[test] - fn noise_frames_with_bit_counts_past_the_data() { - let mut noise = Noise(0xd1b5_4a32_d192_ed03); - for channels in [1, 2] { - let mut decoder = Decoder::new(channels, 48_000); - let mut pcm = Vec::new(); - for round in 0..48 { - let len = [0, 1, 2, 3, 5, 8, 40, 300][round % 8]; - let data = noise.bytes(len, [0, 0, 1, 2][round / 8 % 4]); - let bits = match round % 3 { - 0 => data.len() * 8 + 1 + noise.below(1 << 16), - 1 => usize::MAX / 2 + noise.below(1 << 20), - _ => usize::MAX, - }; - pcm.clear(); - let _ = decoder.decode(&data, bits, &mut pcm); - assert_eq!( - pcm.len(), - FRAME_SAMPLES * channels, - "{channels} channels, round {round}" - ); - } - } - } - - /// `read_frame` from any bit of a buffer of noise and past it, and - /// `packet` at any index: a frame read stays inside its limits. - #[test] - fn noise_offsets_read_a_frame_or_nothing() { - let mut noise = Noise(0x6a09_e667_f3bc_c908); - for round in 0..24 { - let packets = 1 + round % 3; - let data = noise.bytes(packets * PACKET_BYTES, [0, 0, 1, 2][round % 4]); - let all = data.len() * 8; - let edges = [ - 0, - 1, - HEADER_BITS - 1, - HEADER_BITS, - PACKET_BITS - LENGTH_BITS as usize, - PACKET_BITS - 1, - PACKET_BITS, - all - 1, - all, - all + 1, - usize::MAX / 2, - usize::MAX - PACKET_BITS + 1, - usize::MAX, - ]; - let mut starts = edges.to_vec(); - starts.extend((0..32).map(|_| noise.below(all))); - for start in starts { - if let Some(frame) = read_frame(&data, start) { - let lengths = LENGTH_BITS as usize + 1..0x7fff; - assert!(lengths.contains(&frame.bits), "start {start}"); - assert_eq!(frame.data.len(), frame.bits.div_ceil(8)); - if let Some(next) = frame.next { - assert!(next > start && next / 8 < data.len(), "start {start}"); - } - } - } - let far = usize::MAX / PACKET_BYTES; - for index in [0, packets - 1, packets, far, usize::MAX] { - assert_eq!(packet(&data, index).is_some(), index < packets, "{index}"); - } - } - } - /// Walks and decodes saved input buffers (`VICTORY_XMA_STREAMS=<dir>` of /// `*.xma` files with their `*.ctx` context words, made outside the /// repository): the frames walked from the first packet must be the diff --git a/crates/victory-formats/src/xma/tables.rs b/crates/victory-formats/src/xma/tables.rs index 7a789933d6..bf8fc43f4c 100644 --- a/crates/victory-formats/src/xma/tables.rs +++ b/crates/victory-formats/src/xma/tables.rs @@ -4,871 +4,407 @@ //! (symbol, code length) in canonical code order. pub(super) const CRITICAL_FREQ: [u16; 28] = [ - 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, 3700, - 4400, 5300, 6400, 7700, 9500, 12000, 15500, 20675, 28575, 41375, 63875, + 100, 200, 300, 400, 510, 630, 770, 920, + 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, + 3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500, + 20675, 28575, 41375, 63875, ]; pub(super) const SCALE: [(u16, u8); 121] = [ - (58, 5), - (64, 6), - (66, 7), - (65, 7), - (62, 5), - (63, 6), - (68, 9), - (69, 10), - (54, 15), - (19, 19), - (20, 19), - (21, 19), - (22, 19), - (23, 19), - (24, 19), - (25, 19), - (26, 19), - (27, 19), - (28, 19), - (29, 19), - (30, 19), - (31, 19), - (32, 19), - (33, 19), - (34, 19), - (17, 19), - (36, 19), - (37, 19), - (38, 19), - (39, 19), - (40, 19), - (41, 19), - (42, 19), - (43, 19), - (44, 19), - (45, 19), - (46, 19), - (47, 19), - (48, 19), - (49, 19), - (50, 19), - (51, 19), - (52, 19), - (15, 19), - (16, 19), - (14, 19), - (13, 19), - (12, 19), - (11, 19), - (10, 19), - (0, 19), - (9, 19), - (8, 19), - (7, 19), - (6, 19), - (5, 19), - (4, 19), - (55, 13), - (70, 13), - (3, 19), - (2, 19), - (1, 19), - (35, 19), - (71, 19), - (72, 19), - (73, 19), - (74, 19), - (75, 19), - (76, 19), - (77, 19), - (78, 19), - (79, 19), - (80, 19), - (81, 19), - (82, 19), - (83, 19), - (84, 19), - (85, 19), - (86, 19), - (87, 19), - (88, 19), - (89, 19), - (90, 19), - (91, 19), - (92, 19), - (93, 19), - (94, 19), - (95, 19), - (96, 19), - (97, 19), - (98, 19), - (99, 19), - (100, 19), - (101, 19), - (102, 19), - (103, 19), - (104, 19), - (105, 19), - (106, 19), - (107, 19), - (108, 19), - (109, 19), - (110, 19), - (111, 19), - (112, 19), - (113, 19), - (114, 19), - (115, 19), - (116, 19), - (117, 19), - (118, 19), - (119, 19), - (120, 19), - (18, 18), - (53, 16), - (56, 11), - (57, 8), - (67, 7), - (61, 3), - (59, 2), + (58, 5), (64, 6), (66, 7), (65, 7), (62, 5), (63, 6), (68, 9), (69, 10), + (54, 15), (19, 19), (20, 19), (21, 19), (22, 19), (23, 19), (24, 19), (25, 19), + (26, 19), (27, 19), (28, 19), (29, 19), (30, 19), (31, 19), (32, 19), (33, 19), + (34, 19), (17, 19), (36, 19), (37, 19), (38, 19), (39, 19), (40, 19), (41, 19), + (42, 19), (43, 19), (44, 19), (45, 19), (46, 19), (47, 19), (48, 19), (49, 19), + (50, 19), (51, 19), (52, 19), (15, 19), (16, 19), (14, 19), (13, 19), (12, 19), + (11, 19), (10, 19), (0, 19), (9, 19), (8, 19), (7, 19), (6, 19), (5, 19), + (4, 19), (55, 13), (70, 13), (3, 19), (2, 19), (1, 19), (35, 19), (71, 19), + (72, 19), (73, 19), (74, 19), (75, 19), (76, 19), (77, 19), (78, 19), (79, 19), + (80, 19), (81, 19), (82, 19), (83, 19), (84, 19), (85, 19), (86, 19), (87, 19), + (88, 19), (89, 19), (90, 19), (91, 19), (92, 19), (93, 19), (94, 19), (95, 19), + (96, 19), (97, 19), (98, 19), (99, 19), (100, 19), (101, 19), (102, 19), (103, 19), + (104, 19), (105, 19), (106, 19), (107, 19), (108, 19), (109, 19), (110, 19), (111, 19), + (112, 19), (113, 19), (114, 19), (115, 19), (116, 19), (117, 19), (118, 19), (119, 19), + (120, 19), (18, 18), (53, 16), (56, 11), (57, 8), (67, 7), (61, 3), (59, 2), (60, 1), ]; pub(super) const SCALE_RL: [(u16, u8); 120] = [ - (103, 7), - (80, 11), - (60, 11), - (18, 10), - (56, 10), - (21, 12), - (90, 12), - (58, 11), - (27, 11), - (69, 12), - (84, 15), - (48, 15), - (86, 14), - (47, 13), - (19, 10), - (32, 9), - (78, 6), - (5, 5), - (28, 4), - (53, 5), - (9, 7), - (31, 8), - (38, 8), - (10, 7), - (88, 11), - (25, 12), - (105, 12), - (118, 11), - (23, 12), - (82, 14), - (98, 16), - (110, 16), - (108, 15), - (93, 13), - (68, 10), - (72, 12), - (97, 12), - (81, 12), - (42, 12), - (64, 8), - (4, 4), - (1, 2), - (7, 6), - (14, 7), - (0, 9), - (55, 9), - (61, 9), - (117, 10), - (24, 12), - (44, 12), - (67, 12), - (70, 16), - (99, 18), - (96, 21), - (95, 21), - (2, 21), - (77, 21), - (52, 21), - (111, 21), - (102, 20), - (101, 17), - (46, 15), - (73, 15), - (109, 15), - (51, 14), - (92, 14), - (30, 7), - (11, 7), - (66, 7), - (15, 8), - (16, 8), - (116, 9), - (65, 9), - (57, 10), - (59, 10), - (115, 9), - (12, 7), - (35, 9), - (17, 9), - (41, 9), - (20, 11), - (91, 11), - (26, 12), - (75, 15), - (45, 15), - (107, 14), - (83, 14), - (100, 15), - (89, 15), - (43, 11), - (62, 9), - (37, 9), - (104, 8), - (6, 5), - (39, 8), - (40, 9), - (34, 9), - (79, 7), - (8, 6), - (63, 6), - (87, 12), - (94, 14), - (49, 14), - (50, 13), - (22, 11), - (119, 10), - (33, 9), - (36, 9), - (113, 11), - (106, 12), - (112, 13), - (71, 15), - (85, 15), - (74, 14), - (76, 10), - (114, 7), - (29, 5), - (54, 6), - (13, 6), - (3, 2), + (103, 7), (80, 11), (60, 11), (18, 10), (56, 10), (21, 12), (90, 12), (58, 11), + (27, 11), (69, 12), (84, 15), (48, 15), (86, 14), (47, 13), (19, 10), (32, 9), + (78, 6), (5, 5), (28, 4), (53, 5), (9, 7), (31, 8), (38, 8), (10, 7), + (88, 11), (25, 12), (105, 12), (118, 11), (23, 12), (82, 14), (98, 16), (110, 16), + (108, 15), (93, 13), (68, 10), (72, 12), (97, 12), (81, 12), (42, 12), (64, 8), + (4, 4), (1, 2), (7, 6), (14, 7), (0, 9), (55, 9), (61, 9), (117, 10), + (24, 12), (44, 12), (67, 12), (70, 16), (99, 18), (96, 21), (95, 21), (2, 21), + (77, 21), (52, 21), (111, 21), (102, 20), (101, 17), (46, 15), (73, 15), (109, 15), + (51, 14), (92, 14), (30, 7), (11, 7), (66, 7), (15, 8), (16, 8), (116, 9), + (65, 9), (57, 10), (59, 10), (115, 9), (12, 7), (35, 9), (17, 9), (41, 9), + (20, 11), (91, 11), (26, 12), (75, 15), (45, 15), (107, 14), (83, 14), (100, 15), + (89, 15), (43, 11), (62, 9), (37, 9), (104, 8), (6, 5), (39, 8), (40, 9), + (34, 9), (79, 7), (8, 6), (63, 6), (87, 12), (94, 14), (49, 14), (50, 13), + (22, 11), (119, 10), (33, 9), (36, 9), (113, 11), (106, 12), (112, 13), (71, 15), + (85, 15), (74, 14), (76, 10), (114, 7), (29, 5), (54, 6), (13, 6), (3, 2), ]; pub(super) const SCALE_RL_RUN: [u8; 120] = [ - 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, - 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, - 4, 5, 6, 7, 8, 9, 10, 0, 1, 0, 1, 0, 1, + 0, 0, 0, 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 0, 1, 2, + 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 0, + 1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 0, 1, 0, 1, 0, 1, ]; pub(super) const SCALE_RL_LEVEL: [u8; 120] = [ - 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, + 0, 0, 1, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 6, + 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 7, 7, 8, 8, 9, 9, ]; pub(super) const COEF0_LENS: [u8; 272] = [ - 2, 9, 14, 14, 13, 12, 13, 14, 15, 15, 12, 10, 10, 10, 13, 14, 15, 15, 12, 11, 13, 14, 14, 13, - 15, 15, 14, 12, 12, 8, 10, 10, 15, 15, 14, 13, 14, 14, 13, 15, 20, 20, 19, 21, 21, 20, 19, 17, - 17, 18, 18, 15, 15, 13, 12, 14, 15, 15, 14, 15, 15, 12, 11, 6, 7, 8, 9, 13, 13, 13, 14, 14, 11, - 10, 7, 8, 14, 14, 14, 14, 12, 13, 13, 12, 12, 12, 11, 9, 13, 14, 14, 12, 11, 11, 11, 9, 8, 7, - 14, 15, 15, 14, 14, 12, 13, 15, 16, 17, 17, 14, 12, 12, 12, 15, 15, 14, 14, 14, 13, 13, 9, 9, - 11, 11, 10, 7, 6, 13, 15, 15, 14, 14, 14, 13, 14, 15, 15, 13, 14, 14, 14, 14, 10, 9, 10, 10, - 11, 11, 10, 8, 9, 13, 14, 14, 12, 11, 14, 15, 15, 13, 12, 14, 14, 14, 14, 13, 14, 14, 3, 5, 8, - 10, 10, 15, 15, 14, 14, 16, 16, 15, 12, 11, 11, 11, 7, 8, 8, 9, 12, 13, 13, 12, 14, 15, 15, 13, - 10, 11, 11, 13, 14, 14, 13, 14, 14, 11, 10, 13, 15, 15, 14, 12, 11, 4, 6, 6, 8, 12, 12, 12, 13, - 13, 12, 13, 13, 14, 14, 13, 13, 13, 9, 7, 9, 11, 14, 14, 13, 14, 14, 13, 10, 8, 7, 5, 9, 12, - 13, 14, 15, 15, 12, 12, 10, 14, 14, 13, 12, 13, 14, 14, 12, 13, 13, 12, 12, 12, 9, 7, 6, 3, 4, - 4, + 2, 9, 14, 14, 13, 12, 13, 14, + 15, 15, 12, 10, 10, 10, 13, 14, + 15, 15, 12, 11, 13, 14, 14, 13, + 15, 15, 14, 12, 12, 8, 10, 10, + 15, 15, 14, 13, 14, 14, 13, 15, + 20, 20, 19, 21, 21, 20, 19, 17, + 17, 18, 18, 15, 15, 13, 12, 14, + 15, 15, 14, 15, 15, 12, 11, 6, + 7, 8, 9, 13, 13, 13, 14, 14, + 11, 10, 7, 8, 14, 14, 14, 14, + 12, 13, 13, 12, 12, 12, 11, 9, + 13, 14, 14, 12, 11, 11, 11, 9, + 8, 7, 14, 15, 15, 14, 14, 12, + 13, 15, 16, 17, 17, 14, 12, 12, + 12, 15, 15, 14, 14, 14, 13, 13, + 9, 9, 11, 11, 10, 7, 6, 13, + 15, 15, 14, 14, 14, 13, 14, 15, + 15, 13, 14, 14, 14, 14, 10, 9, + 10, 10, 11, 11, 10, 8, 9, 13, + 14, 14, 12, 11, 14, 15, 15, 13, + 12, 14, 14, 14, 14, 13, 14, 14, + 3, 5, 8, 10, 10, 15, 15, 14, + 14, 16, 16, 15, 12, 11, 11, 11, + 7, 8, 8, 9, 12, 13, 13, 12, + 14, 15, 15, 13, 10, 11, 11, 13, + 14, 14, 13, 14, 14, 11, 10, 13, + 15, 15, 14, 12, 11, 4, 6, 6, + 8, 12, 12, 12, 13, 13, 12, 13, + 13, 14, 14, 13, 13, 13, 9, 7, + 9, 11, 14, 14, 13, 14, 14, 13, + 10, 8, 7, 5, 9, 12, 13, 14, + 15, 15, 12, 12, 10, 14, 14, 13, + 12, 13, 14, 14, 12, 13, 13, 12, + 12, 12, 9, 7, 6, 3, 4, 4, ]; pub(super) const COEF0_SYMS: [u16; 272] = [ - 2, 25, 111, 94, 69, 58, 87, 93, 136, 135, 59, 37, 34, 36, 82, 182, 120, 138, 195, 45, 168, 216, - 178, 86, 140, 219, 186, 162, 239, 18, 156, 35, 127, 236, 109, 85, 180, 253, 88, 147, 268, 264, - 256, 266, 270, 262, 260, 248, 246, 252, 258, 137, 189, 230, 64, 179, 146, 208, 101, 118, 238, - 163, 46, 9, 153, 0, 26, 247, 169, 76, 202, 131, 194, 38, 13, 19, 132, 106, 191, 97, 65, 198, - 77, 62, 66, 164, 48, 27, 81, 183, 102, 60, 47, 49, 159, 227, 20, 14, 112, 263, 144, 217, 104, - 63, 79, 209, 269, 250, 254, 203, 241, 196, 61, 220, 148, 124, 185, 100, 80, 78, 193, 28, 50, - 235, 41, 1, 10, 171, 226, 150, 103, 114, 115, 170, 105, 211, 149, 249, 108, 188, 107, 255, 231, - 155, 42, 40, 55, 160, 39, 21, 29, 215, 234, 184, 228, 51, 116, 142, 145, 172, 165, 181, 130, - 113, 117, 89, 128, 204, 3, 7, 154, 157, 43, 141, 265, 133, 225, 271, 244, 221, 74, 54, 56, 52, - 15, 222, 22, 30, 83, 199, 173, 73, 123, 210, 143, 175, 44, 53, 237, 174, 139, 134, 110, 218, - 129, 161, 213, 177, 267, 151, 125, 67, 223, 5, 11, 192, 23, 214, 243, 166, 200, 176, 68, 224, - 187, 257, 261, 232, 96, 251, 31, 16, 32, 57, 207, 121, 91, 126, 119, 99, 158, 24, 212, 8, 33, - 70, 92, 205, 240, 242, 75, 197, 233, 259, 190, 98, 71, 201, 122, 206, 72, 90, 95, 84, 167, 245, - 229, 17, 12, 4, 152, 6, + 2, 25, 111, 94, 69, 58, 87, 93, + 136, 135, 59, 37, 34, 36, 82, 182, + 120, 138, 195, 45, 168, 216, 178, 86, + 140, 219, 186, 162, 239, 18, 156, 35, + 127, 236, 109, 85, 180, 253, 88, 147, + 268, 264, 256, 266, 270, 262, 260, 248, + 246, 252, 258, 137, 189, 230, 64, 179, + 146, 208, 101, 118, 238, 163, 46, 9, + 153, 0, 26, 247, 169, 76, 202, 131, + 194, 38, 13, 19, 132, 106, 191, 97, + 65, 198, 77, 62, 66, 164, 48, 27, + 81, 183, 102, 60, 47, 49, 159, 227, + 20, 14, 112, 263, 144, 217, 104, 63, + 79, 209, 269, 250, 254, 203, 241, 196, + 61, 220, 148, 124, 185, 100, 80, 78, + 193, 28, 50, 235, 41, 1, 10, 171, + 226, 150, 103, 114, 115, 170, 105, 211, + 149, 249, 108, 188, 107, 255, 231, 155, + 42, 40, 55, 160, 39, 21, 29, 215, + 234, 184, 228, 51, 116, 142, 145, 172, + 165, 181, 130, 113, 117, 89, 128, 204, + 3, 7, 154, 157, 43, 141, 265, 133, + 225, 271, 244, 221, 74, 54, 56, 52, + 15, 222, 22, 30, 83, 199, 173, 73, + 123, 210, 143, 175, 44, 53, 237, 174, + 139, 134, 110, 218, 129, 161, 213, 177, + 267, 151, 125, 67, 223, 5, 11, 192, + 23, 214, 243, 166, 200, 176, 68, 224, + 187, 257, 261, 232, 96, 251, 31, 16, + 32, 57, 207, 121, 91, 126, 119, 99, + 158, 24, 212, 8, 33, 70, 92, 205, + 240, 242, 75, 197, 233, 259, 190, 98, + 71, 201, 122, 206, 72, 90, 95, 84, + 167, 245, 229, 17, 12, 4, 152, 6, ]; pub(super) const COEF1: [(u16, u8); 244] = [ - (2, 2), - (3, 3), - (102, 3), - (4, 4), - (148, 6), - (134, 9), - (171, 10), - (18, 10), - (11, 8), - (159, 8), - (14, 9), - (156, 14), - (235, 15), - (61, 15), - (38, 13), - (153, 13), - (48, 14), - (49, 14), - (23, 11), - (203, 13), - (208, 19), - (204, 19), - (129, 18), - (94, 17), - (87, 16), - (62, 15), - (174, 15), - (147, 15), - (29, 12), - (191, 12), - (64, 15), - (65, 15), - (146, 14), - (164, 13), - (142, 5), - (132, 4), - (103, 5), - (154, 7), - (165, 9), - (181, 11), - (109, 12), - (30, 12), - (86, 16), - (92, 16), - (239, 15), - (138, 14), - (39, 13), - (50, 14), - (115, 15), - (238, 21), - (228, 21), - (236, 21), - (222, 21), - (216, 20), - (226, 20), - (196, 18), - (192, 17), - (120, 16), - (221, 14), - (51, 14), - (24, 11), - (143, 8), - (7, 6), - (9, 7), - (152, 10), - (136, 12), - (160, 12), - (241, 15), - (66, 15), - (168, 14), - (219, 14), - (113, 14), - (193, 12), - (19, 10), - (173, 10), - (105, 8), - (149, 9), - (15, 9), - (205, 13), - (207, 13), - (125, 17), - (190, 17), - (182, 16), - (68, 15), - (70, 15), - (67, 15), - (137, 13), - (31, 12), - (223, 14), - (116, 15), - (210, 19), - (220, 19), - (198, 18), - (126, 17), - (88, 16), - (41, 13), - (25, 11), - (40, 13), - (73, 15), - (243, 15), - (53, 14), - (195, 12), - (183, 11), - (225, 14), - (52, 14), - (71, 15), - (121, 16), - (89, 16), - (170, 14), - (55, 14), - (69, 15), - (83, 15), - (209, 13), - (108, 11), - (32, 12), - (54, 14), - (122, 16), - (184, 16), - (176, 15), - (42, 13), - (12, 8), - (161, 8), - (6, 5), - (167, 9), - (106, 9), - (20, 10), - (145, 12), - (111, 13), - (43, 13), - (26, 11), - (175, 10), - (107, 10), - (34, 12), - (33, 12), - (197, 12), - (74, 15), - (128, 17), - (232, 20), - (212, 20), - (224, 19), - (202, 18), - (90, 16), - (57, 14), - (227, 14), - (97, 16), - (93, 16), - (140, 15), - (185, 11), - (27, 11), - (16, 9), - (158, 11), - (211, 13), - (56, 14), - (117, 15), - (72, 15), - (166, 13), - (91, 16), - (95, 16), - (80, 15), - (101, 16), - (194, 17), - (127, 17), - (82, 15), - (21, 10), - (144, 10), - (177, 10), - (151, 6), - (10, 7), - (157, 7), - (8, 6), - (5, 4), - (13, 8), - (0, 9), - (213, 13), - (46, 13), - (199, 12), - (35, 12), - (162, 12), - (135, 10), - (169, 9), - (45, 13), - (59, 14), - (114, 14), - (44, 13), - (188, 16), - (186, 16), - (75, 15), - (79, 15), - (118, 15), - (187, 11), - (112, 13), - (139, 14), - (178, 15), - (81, 15), - (110, 12), - (28, 11), - (163, 8), - (133, 6), - (104, 6), - (17, 9), - (22, 10), - (229, 14), - (172, 14), - (217, 13), - (201, 12), - (36, 12), - (218, 20), - (242, 22), - (240, 22), - (234, 21), - (230, 19), - (206, 18), - (200, 18), - (214, 18), - (130, 17), - (131, 17), - (141, 15), - (84, 15), - (76, 15), - (215, 13), - (58, 14), - (231, 14), - (233, 14), - (180, 15), - (77, 15), - (37, 12), - (189, 11), - (179, 10), - (155, 10), - (47, 13), - (96, 16), - (99, 16), - (119, 15), - (63, 14), - (237, 14), - (78, 15), - (85, 15), - (60, 14), - (98, 16), - (100, 16), - (124, 16), - (123, 16), - (150, 11), - (1, 7), + (2, 2), (3, 3), (102, 3), (4, 4), (148, 6), (134, 9), (171, 10), (18, 10), + (11, 8), (159, 8), (14, 9), (156, 14), (235, 15), (61, 15), (38, 13), (153, 13), + (48, 14), (49, 14), (23, 11), (203, 13), (208, 19), (204, 19), (129, 18), (94, 17), + (87, 16), (62, 15), (174, 15), (147, 15), (29, 12), (191, 12), (64, 15), (65, 15), + (146, 14), (164, 13), (142, 5), (132, 4), (103, 5), (154, 7), (165, 9), (181, 11), + (109, 12), (30, 12), (86, 16), (92, 16), (239, 15), (138, 14), (39, 13), (50, 14), + (115, 15), (238, 21), (228, 21), (236, 21), (222, 21), (216, 20), (226, 20), (196, 18), + (192, 17), (120, 16), (221, 14), (51, 14), (24, 11), (143, 8), (7, 6), (9, 7), + (152, 10), (136, 12), (160, 12), (241, 15), (66, 15), (168, 14), (219, 14), (113, 14), + (193, 12), (19, 10), (173, 10), (105, 8), (149, 9), (15, 9), (205, 13), (207, 13), + (125, 17), (190, 17), (182, 16), (68, 15), (70, 15), (67, 15), (137, 13), (31, 12), + (223, 14), (116, 15), (210, 19), (220, 19), (198, 18), (126, 17), (88, 16), (41, 13), + (25, 11), (40, 13), (73, 15), (243, 15), (53, 14), (195, 12), (183, 11), (225, 14), + (52, 14), (71, 15), (121, 16), (89, 16), (170, 14), (55, 14), (69, 15), (83, 15), + (209, 13), (108, 11), (32, 12), (54, 14), (122, 16), (184, 16), (176, 15), (42, 13), + (12, 8), (161, 8), (6, 5), (167, 9), (106, 9), (20, 10), (145, 12), (111, 13), + (43, 13), (26, 11), (175, 10), (107, 10), (34, 12), (33, 12), (197, 12), (74, 15), + (128, 17), (232, 20), (212, 20), (224, 19), (202, 18), (90, 16), (57, 14), (227, 14), + (97, 16), (93, 16), (140, 15), (185, 11), (27, 11), (16, 9), (158, 11), (211, 13), + (56, 14), (117, 15), (72, 15), (166, 13), (91, 16), (95, 16), (80, 15), (101, 16), + (194, 17), (127, 17), (82, 15), (21, 10), (144, 10), (177, 10), (151, 6), (10, 7), + (157, 7), (8, 6), (5, 4), (13, 8), (0, 9), (213, 13), (46, 13), (199, 12), + (35, 12), (162, 12), (135, 10), (169, 9), (45, 13), (59, 14), (114, 14), (44, 13), + (188, 16), (186, 16), (75, 15), (79, 15), (118, 15), (187, 11), (112, 13), (139, 14), + (178, 15), (81, 15), (110, 12), (28, 11), (163, 8), (133, 6), (104, 6), (17, 9), + (22, 10), (229, 14), (172, 14), (217, 13), (201, 12), (36, 12), (218, 20), (242, 22), + (240, 22), (234, 21), (230, 19), (206, 18), (200, 18), (214, 18), (130, 17), (131, 17), + (141, 15), (84, 15), (76, 15), (215, 13), (58, 14), (231, 14), (233, 14), (180, 15), + (77, 15), (37, 12), (189, 11), (179, 10), (155, 10), (47, 13), (96, 16), (99, 16), + (119, 15), (63, 14), (237, 14), (78, 15), (85, 15), (60, 14), (98, 16), (100, 16), + (124, 16), (123, 16), (150, 11), (1, 7), ]; pub(super) const COEF0_RUN: [u16; 272] = [ - 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, - 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, - 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, - 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, - 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 0, 1, 2, 3, 4, 5, 6, - 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, - 31, 32, 33, 34, 35, 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, - 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 0, 0, 0, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, + 62, 63, 64, 65, 66, 67, 68, 69, + 70, 71, 72, 73, 74, 75, 76, 77, + 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 100, 101, + 102, 103, 104, 105, 106, 107, 108, 109, + 110, 111, 112, 113, 114, 115, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, + 126, 127, 128, 129, 130, 131, 132, 133, + 134, 135, 136, 137, 138, 139, 140, 141, + 142, 143, 144, 145, 146, 147, 148, 149, + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 0, 1, + 2, 3, 4, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, ]; pub(super) const COEF0_LEVEL: [f32; 272] = [ - 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, - 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 5.0, 5.0, 6.0, - 6.0, 7.0, 7.0, 8.0, 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, 13.0, 14.0, 14.0, - 15.0, 15.0, 16.0, 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, 21.0, 22.0, 22.0, - 23.0, 23.0, 24.0, 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, + 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, + 5.0, 5.0, 5.0, 6.0, 6.0, 7.0, 7.0, 8.0, + 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, + 12.0, 13.0, 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, + 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, + 20.0, 21.0, 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, + 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, ]; pub(super) const COEF1_RUN: [u16; 244] = [ - 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, - 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, - 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 0, 1, 2, 0, 1, 2, - 0, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, + 0, 0, 0, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, + 62, 63, 64, 65, 66, 67, 68, 69, + 70, 71, 72, 73, 74, 75, 76, 77, + 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 0, 1, + 2, 3, 4, 5, 0, 1, 2, 0, + 1, 2, 0, 1, 2, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 0, 0, ]; pub(super) const COEF1_LEVEL: [f32; 244] = [ - 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, - 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, - 6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, 13.0, - 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, 21.0, - 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0, 29.0, - 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, 33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0, 37.0, - 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0, 41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0, 45.0, - 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0, 49.0, 50.0, 51.0, 52.0, + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, + 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, + 6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0, + 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, + 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0, + 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, + 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0, + 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0, + 29.0, 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, + 33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0, + 37.0, 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0, + 41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0, + 45.0, 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0, + 49.0, 50.0, 51.0, 52.0, ]; pub(super) const VEC4_LENS: [u8; 127] = [ - 1, 6, 8, 10, 10, 10, 10, 8, 8, 10, 10, 9, 8, 8, 9, 12, 12, 11, 12, 12, 11, 9, 9, 8, 8, 9, 9, 8, - 8, 9, 9, 12, 12, 12, 14, 14, 13, 11, 11, 9, 8, 9, 9, 11, 11, 10, 9, 8, 6, 6, 6, 6, 6, 6, 11, - 11, 10, 11, 11, 10, 10, 11, 11, 9, 7, 6, 7, 7, 6, 6, 6, 5, 7, 11, 11, 10, 9, 8, 6, 9, 9, 10, - 10, 9, 8, 8, 6, 6, 6, 8, 8, 9, 12, 12, 11, 10, 8, 8, 8, 10, 10, 10, 10, 9, 9, 8, 10, 11, 11, 9, - 8, 8, 8, 9, 9, 10, 11, 12, 12, 9, 9, 9, 8, 8, 7, 7, 7, + 1, 6, 8, 10, 10, 10, 10, 8, + 8, 10, 10, 9, 8, 8, 9, 12, + 12, 11, 12, 12, 11, 9, 9, 8, + 8, 9, 9, 8, 8, 9, 9, 12, + 12, 12, 14, 14, 13, 11, 11, 9, + 8, 9, 9, 11, 11, 10, 9, 8, + 6, 6, 6, 6, 6, 6, 11, 11, + 10, 11, 11, 10, 10, 11, 11, 9, + 7, 6, 7, 7, 6, 6, 6, 5, + 7, 11, 11, 10, 9, 8, 6, 9, + 9, 10, 10, 9, 8, 8, 6, 6, + 6, 8, 8, 9, 12, 12, 11, 10, + 8, 8, 8, 10, 10, 10, 10, 9, + 9, 8, 10, 11, 11, 9, 8, 8, + 8, 9, 9, 10, 11, 12, 12, 9, + 9, 9, 8, 8, 7, 7, 7, ]; pub(super) const VEC4_SYMS: [u16; 127] = [ - 0, 4370, 275, 8195, 4146, 12545, 8225, 290, 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, 5121, - 8961, 321, 1041, 51, 4641, 546, 4610, 530, 513, 8451, 4385, 4130, 33, 8211, 5, 66, 4161, 1281, - 81, 6, 801, 8196, 8481, 8449, 4611, 531, 561, 769, 12290, 8226, 19, 4097, 2, 4369, 274, 4354, - 4114, 12291, 16641, 12305, 49, 12321, 260, 4100, 516, 21, 12546, 8466, 4353, 4371, 4626, 257, - 18, 17, 1, 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, 276, 50, 785, 4116, 8209, 4099, 273, - 4113, 258, 259, 4609, 35, 1026, 1025, 16401, 305, 34, 529, 289, 770, 12289, 4, 4145, 4356, - 12306, 8193, 12801, 261, 16386, 4881, 3, 514, 4129, 545, 306, 36, 4101, 65, 20481, 786, 4401, - 4866, 8721, 291, 8450, 8465, 4115, + 0, 4370, 275, 8195, 4146, 12545, 8225, 290, + 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, + 5121, 8961, 321, 1041, 51, 4641, 546, 4610, + 530, 513, 8451, 4385, 4130, 33, 8211, 5, + 66, 4161, 1281, 81, 6, 801, 8196, 8481, + 8449, 4611, 531, 561, 769, 12290, 8226, 19, + 4097, 2, 4369, 274, 4354, 4114, 12291, 16641, + 12305, 49, 12321, 260, 4100, 516, 21, 12546, + 8466, 4353, 4371, 4626, 257, 18, 17, 1, + 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, + 276, 50, 785, 4116, 8209, 4099, 273, 4113, + 258, 259, 4609, 35, 1026, 1025, 16401, 305, + 34, 529, 289, 770, 12289, 4, 4145, 4356, + 12306, 8193, 12801, 261, 16386, 4881, 3, 514, + 4129, 545, 306, 36, 4101, 65, 20481, 786, + 4401, 4866, 8721, 291, 8450, 8465, 4115, ]; pub(super) const VEC2: [(u16, u8); 137] = [ - (19, 5), - (165, 10), - (211, 11), - (46, 11), - (75, 10), - (177, 11), - (12, 11), - (86, 8), - (83, 7), - (38, 7), - (133, 9), - (178, 10), - (28, 10), - (104, 9), - (73, 9), - (35, 5), - (52, 6), - (113, 9), - (8, 9), - (101, 8), - (69, 7), - (0, 3), - (71, 8), - (119, 9), - (91, 10), - (179, 10), - (114, 8), - (166, 10), - (10, 10), - (44, 10), - (145, 10), - (66, 6), - (21, 6), - (24, 8), - (146, 9), - (26, 9), - (65, 7), - (5, 7), - (226, 11), - (225, 12), - (15, 12), - (180, 10), - (147, 9), - (115, 8), - (40, 8), - (89, 9), - (134, 9), - (84, 7), - (54, 7), - (42, 9), - (60, 10), - (31, 11), - (193, 11), - (181, 10), - (76, 10), - (148, 9), - (37, 6), - (67, 6), - (33, 6), - (3, 6), - (17, 6), - (2, 6), - (102, 8), - (87, 8), - (116, 8), - (56, 8), - (50, 5), - (20, 5), - (120, 9), - (58, 9), - (29, 10), - (194, 10), - (135, 9), - (97, 8), - (7, 8), - (105, 9), - (13, 11), - (241, 12), - (16, 12), - (45, 10), - (149, 9), - (74, 9), - (98, 7), - (23, 7), - (85, 7), - (70, 7), - (195, 10), - (161, 10), - (129, 9), - (72, 8), - (51, 5), - (36, 5), - (117, 8), - (61, 10), - (11, 10), - (162, 9), - (1, 7), - (4, 6), - (49, 6), - (68, 6), - (9, 9), - (27, 9), - (130, 8), - (39, 7), - (53, 6), - (99, 7), - (25, 8), - (150, 9), - (90, 9), - (103, 8), - (163, 9), - (196, 10), - (210, 10), - (136, 9), - (121, 9), - (41, 8), - (131, 8), - (43, 9), - (164, 9), - (118, 8), - (88, 8), - (81, 7), - (6, 7), - (55, 7), - (59, 9), - (30, 10), - (209, 11), - (14, 11), - (151, 9), - (106, 9), - (82, 6), - (22, 6), - (100, 7), - (132, 8), - (57, 8), - (18, 4), + (19, 5), (165, 10), (211, 11), (46, 11), (75, 10), (177, 11), (12, 11), (86, 8), + (83, 7), (38, 7), (133, 9), (178, 10), (28, 10), (104, 9), (73, 9), (35, 5), + (52, 6), (113, 9), (8, 9), (101, 8), (69, 7), (0, 3), (71, 8), (119, 9), + (91, 10), (179, 10), (114, 8), (166, 10), (10, 10), (44, 10), (145, 10), (66, 6), + (21, 6), (24, 8), (146, 9), (26, 9), (65, 7), (5, 7), (226, 11), (225, 12), + (15, 12), (180, 10), (147, 9), (115, 8), (40, 8), (89, 9), (134, 9), (84, 7), + (54, 7), (42, 9), (60, 10), (31, 11), (193, 11), (181, 10), (76, 10), (148, 9), + (37, 6), (67, 6), (33, 6), (3, 6), (17, 6), (2, 6), (102, 8), (87, 8), + (116, 8), (56, 8), (50, 5), (20, 5), (120, 9), (58, 9), (29, 10), (194, 10), + (135, 9), (97, 8), (7, 8), (105, 9), (13, 11), (241, 12), (16, 12), (45, 10), + (149, 9), (74, 9), (98, 7), (23, 7), (85, 7), (70, 7), (195, 10), (161, 10), + (129, 9), (72, 8), (51, 5), (36, 5), (117, 8), (61, 10), (11, 10), (162, 9), + (1, 7), (4, 6), (49, 6), (68, 6), (9, 9), (27, 9), (130, 8), (39, 7), + (53, 6), (99, 7), (25, 8), (150, 9), (90, 9), (103, 8), (163, 9), (196, 10), + (210, 10), (136, 9), (121, 9), (41, 8), (131, 8), (43, 9), (164, 9), (118, 8), + (88, 8), (81, 7), (6, 7), (55, 7), (59, 9), (30, 10), (209, 11), (14, 11), + (151, 9), (106, 9), (82, 6), (22, 6), (100, 7), (132, 8), (57, 8), (18, 4), (34, 4), ]; pub(super) const VEC1: [(u16, u8); 101] = [ - (7, 5), - (32, 8), - (59, 10), - (60, 10), - (83, 11), - (82, 11), - (62, 10), - (33, 8), - (45, 9), - (61, 10), - (84, 11), - (85, 11), - (1, 6), - (13, 5), - (19, 6), - (25, 7), - (34, 8), - (46, 9), - (47, 9), - (14, 5), - (6, 5), - (64, 10), - (87, 11), - (86, 11), - (63, 10), - (88, 11), - (90, 11), - (35, 8), - (26, 7), - (0, 7), - (48, 9), - (65, 10), - (66, 10), - (36, 8), - (15, 5), - (20, 6), - (91, 11), - (89, 11), - (67, 10), - (49, 9), - (50, 9), - (69, 10), - (92, 11), - (93, 11), - (27, 7), - (5, 5), - (37, 8), - (68, 10), - (71, 10), - (51, 9), - (52, 9), - (70, 10), - (94, 11), - (96, 11), - (38, 8), - (21, 6), - (16, 5), - (4, 5), - (28, 7), - (53, 9), - (95, 11), - (97, 11), - (73, 10), - (39, 8), - (29, 7), - (72, 10), - (98, 11), - (99, 11), - (54, 9), - (40, 8), - (22, 6), - (30, 7), - (55, 9), - (74, 10), - (76, 10), - (56, 9), - (75, 10), - (77, 10), - (17, 5), - (3, 5), - (23, 6), - (41, 8), - (57, 9), - (78, 10), - (79, 10), - (31, 7), - (10, 4), - (9, 4), - (100, 5), - (2, 5), - (11, 4), - (8, 4), - (18, 5), - (42, 8), - (58, 9), - (80, 10), - (81, 10), - (43, 8), - (44, 8), - (24, 6), - (12, 4), + (7, 5), (32, 8), (59, 10), (60, 10), (83, 11), (82, 11), (62, 10), (33, 8), + (45, 9), (61, 10), (84, 11), (85, 11), (1, 6), (13, 5), (19, 6), (25, 7), + (34, 8), (46, 9), (47, 9), (14, 5), (6, 5), (64, 10), (87, 11), (86, 11), + (63, 10), (88, 11), (90, 11), (35, 8), (26, 7), (0, 7), (48, 9), (65, 10), + (66, 10), (36, 8), (15, 5), (20, 6), (91, 11), (89, 11), (67, 10), (49, 9), + (50, 9), (69, 10), (92, 11), (93, 11), (27, 7), (5, 5), (37, 8), (68, 10), + (71, 10), (51, 9), (52, 9), (70, 10), (94, 11), (96, 11), (38, 8), (21, 6), + (16, 5), (4, 5), (28, 7), (53, 9), (95, 11), (97, 11), (73, 10), (39, 8), + (29, 7), (72, 10), (98, 11), (99, 11), (54, 9), (40, 8), (22, 6), (30, 7), + (55, 9), (74, 10), (76, 10), (56, 9), (75, 10), (77, 10), (17, 5), (3, 5), + (23, 6), (41, 8), (57, 9), (78, 10), (79, 10), (31, 7), (10, 4), (9, 4), + (100, 5), (2, 5), (11, 4), (8, 4), (18, 5), (42, 8), (58, 9), (80, 10), + (81, 10), (43, 8), (44, 8), (24, 6), (12, 4), ]; + diff --git a/crates/victory-game/Cargo.toml b/crates/victory-game/Cargo.toml index 2b49cbe589..92170b42fd 100644 --- a/crates/victory-game/Cargo.toml +++ b/crates/victory-game/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "victory-game" -description = "Everything specific to Grand Theft Auto VI: its containers, build identities, patches." +description = "Everything specific to the title: its containers, build identities, patches." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -9,11 +9,7 @@ publish.workspace = true [dependencies] memchr.workspace = true -miniz_oxide.workspace = true - -[dev-dependencies] -# The shader survey's raw container scan, checked together with records. -victory-shader.workspace = true +zlib-rs.workspace = true [lints] workspace = true diff --git a/crates/victory-game/src/lib.rs b/crates/victory-game/src/lib.rs index 339ebb5866..affa682b48 100644 --- a/crates/victory-game/src/lib.rs +++ b/crates/victory-game/src/lib.rs @@ -1,27 +1,21 @@ -//! Everything specific to Grand Theft Auto VI: its container formats, build +//! Everything specific to the title: its container formats, build //! identities, and the hooks we place in its code (located by per-build //! offsets or byte-pattern signatures). What may and may not be stored here //! is defined in docs/asset-policy.md. pub mod sgd5; -/// A specific build of the Grand Theft Auto VI executable we know how to run. +/// A specific build of the title executable we know how to run. #[derive(Debug, Clone, Copy)] pub struct KnownBuild { /// Our own label, e.g. "1.0.0 retail". pub label: &'static str, /// BLAKE3 of the original executable, hex. pub blake3: &'static str, - /// RPF9 archive the title needs during startup, relative to its executable. - pub startup_archive: &'static str, } -/// Executables identified from a local package. -pub const KNOWN_BUILDS: &[KnownBuild] = &[KnownBuild { - label: "Series 1.0.2.1", - blake3: "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93", - startup_archive: "appdata0.rpf", -}]; +/// Builds we support. Empty until the executable is available. +pub const KNOWN_BUILDS: &[KnownBuild] = &[]; /// Looks up a build by the BLAKE3 hash of its executable. pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> { @@ -29,54 +23,3 @@ pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> { .iter() .find(|b| b.blake3.eq_ignore_ascii_case(blake3_hex)) } - -#[cfg(test)] -mod tests { - use super::*; - - /// A BLAKE3 digest written the way `blake3::Hash::to_hex` writes it. - fn is_blake3_hex(s: &str) -> bool { - s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) - } - - #[test] - fn known_builds_are_well_formed() { - for (i, build) in KNOWN_BUILDS.iter().enumerate() { - assert!(!build.label.trim().is_empty(), "build {i} has no label"); - assert!( - is_blake3_hex(build.blake3), - "{:?}: blake3 must be 64 lowercase hex digits, got {:?}", - build.label, - build.blake3 - ); - for other in &KNOWN_BUILDS[..i] { - assert_ne!(other.blake3, build.blake3, "{:?} listed twice", build.label); - assert_ne!( - other.label, build.label, - "label {:?} used twice", - build.label - ); - } - } - } - - #[test] - fn every_known_build_is_identified_by_its_hash() { - for build in KNOWN_BUILDS { - let found = identify(build.blake3).expect("own hash identifies the build"); - assert_eq!(found.label, build.label); - let upper = build.blake3.to_ascii_uppercase(); - assert_eq!(identify(&upper).map(|b| b.label), Some(build.label)); - } - } - - #[test] - fn unknown_hashes_are_not_identified() { - // BLAKE3 of empty input: no executable hashes to it. - let empty = "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"; - assert!(is_blake3_hex(empty)); - assert!(identify(empty).is_none()); - assert!(identify("").is_none()); - assert!(identify("not a hash").is_none()); - } -} diff --git a/crates/victory-game/src/sgd5.rs b/crates/victory-game/src/sgd5.rs index 5e5de7d3b8..5605b51622 100644 --- a/crates/victory-game/src/sgd5.rs +++ b/crates/victory-game/src/sgd5.rs @@ -11,30 +11,6 @@ pub const MAGIC: &[u8; 4] = b"SGD5"; const MARKER: [u8; 4] = 0x000D_DCE7_u32.to_le_bytes(); /// Containers are at most a few MiB; refuse to allocate for absurd sizes. const MAX_UNPACKED: usize = 64 << 20; -/// Bytes a record's packed stream may hold beyond what deflate needs (see -/// [`max_packed`]): the stream's end is not checked, so allow some padding. -const PACKED_SLACK: usize = 4096; -/// Packed bytes read, and unpacked bytes made, to tell whether a record's -/// bytes are a deflate stream (see [`starts_stream`]). -const PROBE: usize = 4096; - -/// The most packed bytes a container of `unpacked` bytes can take. Deflate -/// never spends more than 9 bits a byte (fixed codes), and stored blocks only -/// 5 bytes per 65535, so a size beyond this is not a record's: it is bytes -/// that look like a marker (in a container stored between records, say). -fn max_packed(unpacked: usize) -> usize { - unpacked + unpacked / 8 + PACKED_SLACK -} - -/// The fewest packed bytes a container of `unpacked` bytes can take. The -/// smallest deflate stream (one empty fixed-code block) is 2 bytes, and no -/// stream does better than one 258-byte match per 2 bits (1-bit length and -/// distance codes, no extra bits): 1032 bytes a byte. Fewer packed bytes is -/// not a record's, and taking it for one would make its span (12 bytes and -/// up) swallow the header of a real record right after it. -fn min_packed(unpacked: usize) -> usize { - (unpacked / 1032).max(2) -} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Record<'a> { @@ -53,214 +29,88 @@ pub struct Record<'a> { impl Record<'_> { /// The container, or `None` if the stream is corrupt. pub fn unpack(&self) -> Option<Vec<u8>> { - miniz_oxide::inflate::decompress_to_vec_with_limit(self.packed, self.unpacked_size) - .ok() - .filter(|out| out.len() == self.unpacked_size) - } - - /// Whether the packed bytes are a deflate stream of the stated size (or - /// its start: the stream's end is not checked). - fn is_stream(&self) -> bool { - starts_stream(self.packed, self.unpacked_size) - } - - /// The file bytes from the marker to the end of the packed stream. - pub fn span(&self) -> std::ops::Range<usize> { - self.offset..self.offset + 12 + self.packed.len() + let mut state = zlib_rs::Inflate::new(false, 15); + let mut out = Vec::new(); + let (mut in_pos, mut out_pos) = (0usize, 0usize); + loop { + if out_pos == self.unpacked_size { + let mut extra = [0u8; 1]; + let status = state + .decompress( + &self.packed[in_pos..], + &mut extra, + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + return (status == zlib_rs::Status::StreamEnd + && state.total_out() as usize == self.unpacked_size) + .then_some(out); + } + if out_pos == out.len() { + let next_len = if out.is_empty() { + self.unpacked_size + .min(self.packed.len().saturating_mul(4).max(4096)) + } else { + out.len().saturating_mul(2).min(self.unpacked_size) + }; + out.resize(next_len, 0); + } + let status = state + .decompress( + &self.packed[in_pos..], + &mut out[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + match status { + zlib_rs::Status::StreamEnd => { + out.truncate(next_out); + return (next_out == self.unpacked_size).then_some(out); + } + zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => { + in_pos = next_in; + out_pos = next_out; + } + zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None, + } + } } } -/// Whether `offset` lies inside one of `records`, taken in the order -/// [`records`] yields them (file order, disjoint). Bytes there belong to a -/// record: a container stored as is inside its packed stream (deflate stored -/// blocks) is that record's container, not another one. -pub fn in_record(records: &[Record<'_>], offset: usize) -> bool { - let i = records.partition_point(|r| r.span().end <= offset); - records.get(i).is_some_and(|r| r.span().contains(&offset)) -} - /// An SGD5 file, or a file holding one (an archive: records are found by /// their marker, so no index is needed). pub fn is_sgd5(file: &[u8]) -> bool { memchr::memmem::find(file, MAGIC).is_some() } -/// Every record in an SGD5 file, in file order. The search starts at the -/// first magic: bytes before it (an archive's other files) belong to no SGD5 -/// file, whatever markers they happen to hold. It resumes after each -/// record's packed bytes: a marker inside them (stored deflate blocks carry a -/// container's bytes as they are) is part of that record, and so is any part -/// of the next record's header or name, which must follow them. A record -/// whose packed bytes run past the end of the file (a truncated file) is not -/// yielded, and ends the search: every byte after its marker is its own. -/// Sizes that no deflate stream of the stated unpacked size could have (too -/// many packed bytes, or too few) do not form a record, and neither do bytes -/// running past the end that do not start a deflate stream, nor bytes that -/// are no deflate stream laid over a record that is one, so such bytes -/// neither end the search nor hide records. A corrupt record that covers no -/// other record is still yielded (its [`Record::unpack`] is `None`). +/// Every record in an SGD5 file, in file order. pub fn records(file: &[u8]) -> impl Iterator<Item = Record<'_>> { - let finder = memchr::memmem::Finder::new(&MARKER); - // Where the next record may start: after the magic, then after each - // record's packed bytes. No magic: past the end, so nothing is found. - let mut floor = memchr::memmem::find(file, MAGIC).map_or(file.len(), |m| m + MAGIC.len()); - // A marker needs its name's NUL, the kind and `n` (6 bytes) before it. - let mut from = floor + 6; - let mut streams = Streams::default(); - std::iter::from_fn(move || { - while let Some(found) = finder.find(file.get(from..)?) { - let at = from + found; - match record(&file[floor..], at - floor) { - Found::Record(r) => { - let r = Record { offset: at, ..r }; - if covers_a_record(file, &r, &mut streams) && !r.is_stream() { - // Bytes that only look like a marker, laid over a - // real record: the real one wins. - from = at + 1; - continue; - } - floor = r.span().end; - from = floor + 6; - return Some(r); - } - Found::Truncated => { - from = file.len() + 1; - return None; - } - Found::Nothing => from = at + 1, - } - } - None - }) + memchr::memmem::find_iter(file, &MARKER).filter_map(|at| record(file, at)) } -enum Found<'a> { - Record(Record<'a>), - /// A record header whose packed bytes run past the end of the file. - Truncated, - Nothing, -} - -/// The record whose marker is at `at`, reading nothing before `file`. -fn record(file: &[u8], at: usize) -> Found<'_> { +fn record(file: &[u8], at: usize) -> Option<Record<'_>> { let u32_at = |o: usize| { - file.get(o..o.checked_add(4)?) + file.get(o..o + 4) .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")) as usize) }; - let Some(nul) = at.checked_sub(6) else { - return Found::Nothing; - }; - let (Some(n), Some(n2), Some(unpacked_size)) = (u32_at(at - 4), u32_at(at + 4), u32_at(at + 8)) - else { - return Found::Nothing; - }; - if n2 != n - || n < 12 - || unpacked_size > MAX_UNPACKED - || n - 12 > max_packed(unpacked_size) - || n - 12 < min_packed(unpacked_size) - { - return Found::Nothing; + let n = u32_at(at.checked_sub(4)?)?; + let unpacked_size = u32_at(at + 8)?; + if u32_at(at + 4)? != n || n < 12 || unpacked_size > MAX_UNPACKED { + return None; } - let Some(packed) = at.checked_add(n).and_then(|end| file.get(at + 12..end)) else { - // Bytes that only look like a marker (in a container stored between - // records, say) may have sizes that fit and still run past the end. - // Only a record whose bytes so far are a deflate stream is one. - return if starts_stream(file.get(at + 12..).unwrap_or_default(), unpacked_size) { - Found::Truncated - } else { - Found::Nothing - }; - }; - Found::Record(Record { + let nul = at.checked_sub(6)?; + Some(Record { offset: at, name: (file[nul] == 0).then(|| name_before(file, nul)).flatten(), kind: file[at - 5], - packed, + packed: file.get(at + 12..at + n)?, unpacked_size, }) } -/// Whether a record whose packed bytes are a deflate stream starts (its -/// header, 6 bytes before its marker) inside `r`'s span. Such a record inside -/// a real one is that record's (stored deflate blocks); but if `r`'s own -/// bytes are no deflate stream, `r` is bytes that look like a marker (in a -/// container stored between records, say) and the record it covers is real. -fn covers_a_record(file: &[u8], r: &Record<'_>, streams: &mut Streams) -> bool { - let span = r.span(); - // Its header must be after `r`'s marker, and a marker from - // `span.end + 6` on has its header after the span. - let hi = file.len().min(span.end + 6 + MARKER.len() - 1); - streams.any_in(file, r.offset + 7, hi) -} - -/// Which markers start a record whose packed bytes are a deflate stream, as -/// far as [`records`] has asked. Its questions move forward through the -/// file, and markers in bytes that only look like records may each cover -/// all the rest of it: asking each of them anew rescans and reinflates the -/// same bytes, so a crafted file of `n` such markers takes `n²` work and -/// more. Each marker is looked at once instead. -#[derive(Default)] -struct Streams { - /// No marker at an offset in `from..to` starts such a record. - from: usize, - to: usize, - /// The marker at `to` does (and was the first found from `from` on). - hit: bool, -} - -impl Streams { - /// Whether a marker that lies wholly in `lo..hi` starts such a record - /// (its header read from `lo` on). - fn any_in(&mut self, file: &[u8], lo: usize, hi: usize) -> bool { - if lo < self.from || lo > self.to { - *self = Self { - from: lo, - to: lo, - hit: false, - }; - } - if !self.hit { - let window = file.get(self.to..hi).unwrap_or_default(); - match memchr::memmem::find_iter(window, &MARKER) - .map(|m| self.to + m) - .find(|&at| matches!(record(&file[at - 6..], 6), Found::Record(inner) if inner.is_stream())) - { - Some(at) => (self.to, self.hit) = (at, true), - // Markers at offsets up to `hi - 4` have been looked at. - None => self.to = self.to.max(hi.saturating_sub(MARKER.len() - 1)), - } - } - self.hit && self.to + MARKER.len() <= hi - } -} - -/// Whether `bytes` are the start of a deflate stream of `unpacked` bytes: -/// they run out before the stream ends, or the stream ends having produced -/// exactly that many bytes. -/// -/// Only the first [`PROBE`] bytes are read, and at most [`PROBE`] bytes -/// inflated: [`records`] asks this of every marker that might be a record, -/// and in bytes that only look like records each such marker's bytes may run -/// on through all the ones after it (stored blocks that each end where the -/// next marker's begin), so reading them all makes a file of `n` markers -/// take `n²` work. Real records are told from noise long before that. -fn starts_stream(bytes: &[u8], unpacked: usize) -> bool { - use miniz_oxide::inflate::{TINFLStatus, decompress_to_vec_with_limit}; - let limit = unpacked.min(PROBE); - match decompress_to_vec_with_limit(&bytes[..bytes.len().min(PROBE)], limit) { - Ok(out) => out.len() == unpacked, - Err(e) => { - e.status == TINFLStatus::FailedCannotMakeProgress - // Inflated as far as the probe goes, with more to come. - || (e.status == TINFLStatus::HasMoreOutput && limit < unpacked) - } - } -} - -/// The printable name that ends at `nul` and follows its length byte. A -/// length byte of 1 (no characters) is not a name: any `01 00` before the -/// kind would read as one. +/// The printable name that ends at `nul` and follows its length byte. fn name_before(file: &[u8], nul: usize) -> Option<&str> { let run = file[..nul] .iter() @@ -270,7 +120,6 @@ fn name_before(file: &[u8], nul: usize) -> Option<&str> { (run.saturating_sub(1)..nul) .find(|&l| usize::from(file[l]) == nul - l) .and_then(|l| std::str::from_utf8(&file[l + 1..nul]).ok()) - .filter(|name| !name.is_empty()) } #[cfg(test)] @@ -278,7 +127,13 @@ mod tests { use super::*; fn record_bytes(name: &str, kind: u8, payload: &[u8]) -> Vec<u8> { - let packed = miniz_oxide::deflate::compress_to_vec(payload, 6); + let mut buf = vec![0u8; zlib_rs::compress_bound(payload.len())]; + let config = zlib_rs::DeflateConfig { + window_bits: -15, + ..zlib_rs::DeflateConfig::new(6) + }; + let (packed, rc) = zlib_rs::compress_slice(&mut buf, payload, config); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); let n = (packed.len() + 12) as u32; let mut out = vec![0xF4, 0x01, 0, 0, name.len() as u8 + 1]; out.extend_from_slice(name.as_bytes()); @@ -286,7 +141,7 @@ mod tests { for v in [n, 0x000D_DCE7, n, payload.len() as u32] { out.extend_from_slice(&v.to_le_bytes()); } - out.extend_from_slice(&packed); + out.extend_from_slice(packed); out } @@ -321,575 +176,43 @@ mod tests { assert!(!is_sgd5(&archive[..0x1000])); } - #[test] - fn marker_inside_a_record_is_not_another_record() { - let inner = record_bytes("PS_inner", 0x32, b"inner container"); - // Level 0: stored blocks, so the inner record's bytes appear as they are. - let packed = miniz_oxide::deflate::compress_to_vec(&inner, 0); - assert!(memchr::memmem::find(&packed, &MARKER).is_some()); - let n = (packed.len() + 12) as u32; - let mut file = MAGIC.to_vec(); - file.extend_from_slice(&[0xF4, 0x01, 0, 0, 9]); - file.extend_from_slice(b"PS_outer\0\x32"); - for v in [n, 0x000D_DCE7, n, inner.len() as u32] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend_from_slice(&packed); - file.extend(record_bytes("PS_after", 0x32, b"next")); - - let found: Vec<_> = records(&file).collect(); - let names: Vec<_> = found.iter().map(|r| r.name).collect(); - assert_eq!(names, [Some("PS_outer"), Some("PS_after")]); - assert_eq!(found[0].unpack(), Some(inner)); - } - - #[test] - fn offsets_inside_records() { - // A container stored as is (level 0) inside a record's packed bytes. - let container = b"DXBC stored as is"; - let mut file = MAGIC.to_vec(); - file.extend_from_slice(b"\x05PS_a\0\x32"); - let packed = miniz_oxide::deflate::compress_to_vec(container, 0); - let n = (packed.len() + 12) as u32; - for v in [n, 0x000D_DCE7, n, container.len() as u32] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend_from_slice(&packed); - let between = file.len(); - file.extend_from_slice(b"DXBC between records"); - file.extend(record_bytes("PS_b", 0x32, b"second")); - let after = file.len(); - file.extend_from_slice(b"DXBC after"); - - let found: Vec<_> = records(&file).collect(); - assert_eq!(found.len(), 2); - let stored = memchr::memmem::find(&file, b"DXBC").unwrap(); - assert!(stored < between); - assert!(in_record(&found, stored)); - assert!(!in_record(&found, 0), "the magic"); - assert!(!in_record(&found, between)); - assert!(!in_record(&found, after)); - for r in &found { - let span = r.span(); - assert!(in_record(&found, span.start)); - assert!(in_record(&found, span.end - 1)); - assert!(!in_record(&found, span.start - 1), "the header"); - } - assert!(!in_record(&[], stored)); - } - - #[test] - fn header_inside_a_record_is_not_another_record() { - // The record's packed bytes end (after the deflate stream, which - // ignores them) with what would be the next header: NUL, kind, `n`. - let mut packed = miniz_oxide::deflate::compress_to_vec(b"first", 6); - let tail = miniz_oxide::deflate::compress_to_vec(b"phantom", 6); - let tail_n = (tail.len() + 12) as u32; - packed.extend_from_slice(&[0, 0x32]); - packed.extend_from_slice(&tail_n.to_le_bytes()); - let n = (packed.len() + 12) as u32; - let mut file = MAGIC.to_vec(); - file.extend_from_slice(b"\x09PS_first\0\x32"); - for v in [n, 0x000D_DCE7, n, 5] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend_from_slice(&packed); - // Right after it, a marker with no header of its own. - for v in [0x000D_DCE7, tail_n, 7] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend_from_slice(&tail); - - let found: Vec<_> = records(&file).collect(); - let names: Vec<_> = found.iter().map(|r| r.name).collect(); - assert_eq!(names, [Some("PS_first")]); - assert_eq!(found[0].unpack().as_deref(), Some(&b"first"[..])); - } - - #[test] - fn records_before_the_magic_are_not_read() { - // An archive whose other file happens to hold a well-formed record. - let mut archive = record_bytes("PS_elsewhere", 0x32, b"not ours"); - assert_eq!(records(&archive).count(), 0, "no magic, no records"); - archive.extend_from_slice(MAGIC); - archive.extend(record_bytes("PS_ours", 0x32, b"ours")); - let names: Vec<_> = records(&archive).map(|r| r.name).collect(); - assert_eq!(names, [Some("PS_ours")]); - } - - #[test] - fn truncated_file_yields_only_whole_records() { - let mut file = MAGIC.to_vec(); - file.extend(record_bytes("PS_a", 0x32, &[5; 200])); - let first_end = file.len(); - file.extend(record_bytes("PS_b", 0x41, b"second")); - for cut in 0..=file.len() { - let part = &file[..cut]; - let found: Vec<_> = records(part).collect(); - let expected = usize::from(cut >= first_end) + usize::from(cut == file.len()); - assert_eq!(found.len(), expected, "cut at {cut}"); - for r in found { - assert!( - r.unpack().is_some(), - "cut at {cut}: {:?} does not unpack", - r.name - ); - } - } - } - - #[test] - fn truncated_record_hides_the_records_it_stores() { - // A record whose packed bytes (stored blocks) hold a whole record, - // cut off after that inner record but before its own end. - let inner = record_bytes("PS_inner", 0x32, b"inner container"); - let mut payload = inner.clone(); - payload.extend_from_slice(&[0x55; 64]); - let packed = miniz_oxide::deflate::compress_to_vec(&payload, 0); - let n = (packed.len() + 12) as u32; - let mut file = MAGIC.to_vec(); - file.extend(record_bytes("PS_first", 0x32, b"first")); - file.extend_from_slice(b"\x09PS_outer\0\x32"); - for v in [n, 0x000D_DCE7, n, payload.len() as u32] { - file.extend_from_slice(&v.to_le_bytes()); - } - let stored = file.len(); - file.extend_from_slice(&packed); - let inner_end = stored + memchr::memmem::find(&packed, &inner).unwrap() + inner.len(); - let names: Vec<_> = records(&file).map(|r| r.name).collect(); - assert_eq!(names, [Some("PS_first"), Some("PS_outer")]); - - // Before: [PS_first, PS_inner]. - let names: Vec<_> = records(&file[..inner_end]).map(|r| r.name).collect(); - assert_eq!(names, [Some("PS_first")]); - } - - #[test] - fn marker_with_impossible_sizes_does_not_end_the_search() { - // Bytes between records that read as a marker whose packed size runs - // past the end of the file, but is far more than a deflate stream of - // 16 bytes could take. - let mut file = MAGIC.to_vec(); - file.extend_from_slice(b"DXBC"); - for v in [u32::MAX, 0x000D_DCE7, u32::MAX, 16] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend(record_bytes("PS_after", 0x32, b"after")); - // Before: [] (the phantom was a truncated record and ended the search). - let names: Vec<_> = records(&file).map(|r| r.name).collect(); - assert_eq!(names, [Some("PS_after")]); - } - - #[test] - fn marker_running_past_the_end_without_a_stream_does_not_end_the_search() { - // Bytes between records that read as a marker with sizes that fit - // (64 KiB both ways) and run past the end of the file, followed by - // bytes that are no deflate stream (block type 3 is reserved). - let mut file = MAGIC.to_vec(); - file.extend(record_bytes("PS_first", 0x32, b"first")); - file.extend_from_slice(b"DXBC"); - for v in [0x1_0000_u32, 0x000D_DCE7, 0x1_0000, 0x1_0000] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend_from_slice(&[0x07; 16]); - file.extend(record_bytes("PS_after", 0x32, b"after")); - // Before: [PS_first] (the phantom was a truncated record and ended - // the search). - let names: Vec<_> = records(&file).map(|r| r.name).collect(); - assert_eq!(names, [Some("PS_first"), Some("PS_after")]); - } - - #[test] - fn truncated_stream_is_told_from_noise() { - let payload: Vec<u8> = (0..4000u32).map(|i| (i * 7 % 251) as u8).collect(); - for level in [0, 1, 6, 10] { - let packed = miniz_oxide::deflate::compress_to_vec(&payload, level); - for cut in 0..packed.len() { - assert!( - starts_stream(&packed[..cut], payload.len()), - "level {level}, cut at {cut}" - ); - } - assert!(starts_stream(&packed, payload.len()), "level {level}"); - // A whole stream of another size is not this record's. - assert!(!starts_stream(&packed, payload.len() + 1), "level {level}"); - assert!(!starts_stream(&packed, payload.len() - 1), "level {level}"); - } - // Reserved block type, and a stored block whose length check fails. - assert!(!starts_stream(&[0x07, 0, 0], 100)); - assert!(!starts_stream(&[0x01, 0x05, 0x00, 0x00, 0x00, 1, 2, 3], 5)); - } - - #[test] - fn packed_size_bound_holds_for_every_level() { - // Incompressible bytes, at every level miniz writes: the bound is - // never reached, so no real record is refused. - let mut x = 0x1234_5678_u32; - let noise: Vec<u8> = (0..200_000) - .map(|_| { - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - x as u8 - }) - .collect(); - for len in [0, 1, 100, 65_535, 65_536, noise.len()] { - for level in 0..=10 { - let packed = miniz_oxide::deflate::compress_to_vec(&noise[..len], level); - assert!(packed.len() <= max_packed(len), "len {len} level {level}"); - } - } - } - - #[test] - fn empty_container_unpacks() { - let mut file = MAGIC.to_vec(); - file.extend(record_bytes("PS_empty", 0x32, b"")); - let r = records(&file).next().unwrap(); - assert_eq!(r.unpack(), Some(Vec::new())); - } - - /// Every single-byte change to a small file: no panic, and the records - /// found are in file order, inside the file and do not overlap. - #[test] - fn damaged_file_yields_disjoint_records() { - let mut file = MAGIC.to_vec(); - file.extend(record_bytes("PS_a", 0x32, &[5; 40])); - file.extend(record_bytes("VS_b", 0x41, b"second")); - for at in 0..file.len() { - for value in [0x00, 0x01, 0x0C, 0x0D, 0x7F, 0xDC, 0xE7, 0xFF] { - let mut damaged = file.clone(); - damaged[at] = value; - let mut end = 0; - for r in records(&damaged) { - let start = r.offset - 6; - assert!(start >= end, "byte {at} = {value:#x}: records overlap"); - end = r.span().end; - assert!(end <= damaged.len()); - let _ = r.unpack(); - } - } - } - } - - /// Seeded random files: gaps of noise and of near-miss markers between - /// records, some records stored as is (level 0) and holding records of - /// their own. Exactly the planted records are found, each with its - /// container, and [`in_record`] agrees with a scan of their spans. - #[test] - fn random_files_yield_exactly_the_planted_records() { - let mut x = 0x9E37_79B9_u32; - let mut next = move || { - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - x - }; - for seed in 0..200 { - let mut file = MAGIC.to_vec(); - // (offset of the marker, name, container) - let mut planted: Vec<(usize, String, Vec<u8>)> = Vec::new(); - for i in 0..1 + next() % 6 { - // A gap: noise, then sometimes a marker whose sizes disagree - // or that no deflate stream could have. - for _ in 0..next() % 40 { - file.push(next() as u8); - } - match next() % 3 { - 0 => { - for v in [20_u32, 0x000D_DCE7, 21, 8] { - file.extend_from_slice(&v.to_le_bytes()); - } - } - 1 => { - for v in [u32::MAX, 0x000D_DCE7, u32::MAX, 16] { - file.extend_from_slice(&v.to_le_bytes()); - } - } - _ => {} - } - // A name's length byte follows the gap; a long name's is - // printable, so noise right before it is kept non-printable. - file.push(0x01); - let name = format!("PS_{seed}_{i}_{}", "w".repeat(next() as usize % 50)); - let mut payload: Vec<u8> = (0..next() % 300).map(|_| next() as u8).collect(); - let level = if next() % 2 == 0 { - // Stored as is, holding a record and a container's magic. - payload.extend(record_bytes("PS_stored", 0x32, b"stored")); - payload.extend_from_slice(b"DXBC"); - 0 - } else { - 6 - }; - let packed = miniz_oxide::deflate::compress_to_vec(&payload, level); - let n = (packed.len() + 12) as u32; - file.push(name.len() as u8 + 1); - file.extend_from_slice(name.as_bytes()); - file.extend_from_slice(&[0, 0x32]); - planted.push((file.len() + 4, name, payload.clone())); - for v in [n, 0x000D_DCE7, n, payload.len() as u32] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend_from_slice(&packed); - } - for _ in 0..next() % 40 { - file.push(next() as u8); - } - - let found: Vec<_> = records(&file).collect(); - let got: Vec<_> = found - .iter() - .map(|r| (r.offset, r.name.map(str::to_owned), r.unpack())) - .collect(); - let want: Vec<_> = planted - .iter() - .map(|(at, name, payload)| (*at, Some(name.clone()), Some(payload.clone()))) - .collect(); - assert_eq!(got, want, "seed {seed}"); - for offset in 0..=file.len() { - let linear = found.iter().any(|r| r.span().contains(&offset)); - assert_eq!( - in_record(&found, offset), - linear, - "seed {seed}, offset {offset}" - ); - } - } - } - - #[test] - fn empty_name_is_no_name() { - // A record whose name would be empty: `01 00` before the kind. - let mut file = MAGIC.to_vec(); - file.extend(record_bytes("", 0x32, b"nameless")); - file.extend(record_bytes("PS_named", 0x32, b"named")); - let found: Vec<_> = records(&file).collect(); - let names: Vec<_> = found.iter().map(|r| r.name).collect(); - assert_eq!(names, [None, Some("PS_named")]); - assert_eq!(found[0].unpack().as_deref(), Some(&b"nameless"[..])); - } - - #[test] - fn archive_with_two_sgd5_files_yields_both() { - // Two SGD5 files one after the other in an archive, with another - // file's bytes between them: the second magic sits in a gap. - let mut archive = b"other file".to_vec(); - archive.extend_from_slice(MAGIC); - archive.extend(record_bytes("PS_one", 0x32, b"first file")); - archive.extend_from_slice(b"another file between"); - archive.extend_from_slice(MAGIC); - archive.extend(record_bytes("PS_two", 0x41, b"second file")); - let found: Vec<_> = records(&archive).collect(); - let names: Vec<_> = found.iter().map(|r| r.name).collect(); - assert_eq!(names, [Some("PS_one"), Some("PS_two")]); - assert_eq!(found[1].kind, 0x41); - assert_eq!(found[1].unpack().as_deref(), Some(&b"second file"[..])); - } - - #[test] - fn packed_size_lower_bound_holds_for_every_level() { - // The most compressible bytes, at every level miniz writes: no real - // record has fewer packed bytes than the bound. - let zeros = vec![0_u8; 4 << 20]; - for len in [0, 1, 2, 258, 259, 1032, 65_536, 1 << 20, zeros.len()] { - for level in 0..=10 { - let packed = miniz_oxide::deflate::compress_to_vec(&zeros[..len], level); - assert!(packed.len() >= min_packed(len), "len {len} level {level}"); - } - } - } - - #[test] - fn marker_with_too_few_packed_bytes_does_not_hide_the_next_record() { - // Bytes between records that read as a marker with no packed bytes - // (or one) for a 1 MiB container, right before a real record: taken - // for a record, its span would cover the real record's header. - for packed_len in [0_u32, 1, 2, 3] { - let mut file = MAGIC.to_vec(); - file.extend(record_bytes("PS_first", 0x32, b"first")); - file.extend_from_slice(b"DXBC"); - let n = 12 + packed_len; - for v in [n, 0x000D_DCE7, n, 1 << 20] { - file.extend_from_slice(&v.to_le_bytes()); - } - // The next record from its length byte on: with packed bytes, - // the phantom's span would start over it. - let mut next = record_bytes("PS_after", 0x32, b"after"); - next.drain(..4); - file.extend(next); - // Before: [PS_first, None, None] for a phantom of 1 to 3 packed - // bytes (its span swallowed PS_after's length byte, so PS_after - // lost its name), and [PS_first, None, PS_after] for none (a - // record that never unpacks). - let names: Vec<_> = records(&file).map(|r| r.name).collect(); - assert_eq!( - names, - [Some("PS_first"), Some("PS_after")], - "{packed_len} packed bytes" - ); - } - } - - #[test] - fn smallest_containers_are_records() { - // The fewest packed bytes deflate writes: every small container at - // every level is still found. - for len in [0_usize, 1, 2, 3] { - for level in 0..=10 { - let payload = vec![0x41; len]; - let packed = miniz_oxide::deflate::compress_to_vec(&payload, level); - let n = (packed.len() + 12) as u32; - let mut file = MAGIC.to_vec(); - file.extend_from_slice(b"\x05PS_s\0\x32"); - for v in [n, 0x000D_DCE7, n, len as u32] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend_from_slice(&packed); - let found: Vec<_> = records(&file).collect(); - assert_eq!(found.len(), 1, "len {len} level {level}"); - assert_eq!(found[0].unpack(), Some(payload), "len {len} level {level}"); - } - } - } - - #[test] - fn marker_without_a_stream_does_not_hide_the_record_it_covers() { - // Bytes between records that read as a marker with sizes that fit - // and stay inside the file, followed by bytes that are no deflate - // stream (block type 3 is reserved) and then a real record: taken - // for a record, its span covers the real record's header. - let mut file = MAGIC.to_vec(); - file.extend(record_bytes("PS_first", 0x32, b"first")); - let after = record_bytes("PS_after", 0x32, b"after"); - // PS_after's header (6 bytes before its marker) starts 16 + 13 bytes - // into the phantom's packed bytes: from 30 on they cover it. - for span in [30, 35, after.len(), after.len() + 31] { - let mut file = file.clone(); - file.extend_from_slice(b"DXBC"); - let n = (12 + span) as u32; - for v in [n, 0x000D_DCE7, n, 64] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend_from_slice(&[0x07; 16]); - file.extend(&after); - file.extend_from_slice(&[0x5A; 16]); - // Before: [PS_first, None] (the phantom hid PS_after). - let found: Vec<_> = records(&file).collect(); - let names: Vec<_> = found.iter().map(|r| r.name).collect(); - assert_eq!(names, [Some("PS_first"), Some("PS_after")], "span {span}"); - assert_eq!(found[1].unpack().as_deref(), Some(&b"after"[..])); - } - } - - #[test] - fn corrupt_record_is_still_a_record() { - // A real record whose stream is damaged covers no other record: it - // is yielded (and does not unpack), and so is the record after it. - let mut file = MAGIC.to_vec(); - file.extend(record_bytes("CS_x", 0x3c, &[1; 64])); - file[31] = 0xFF; - file.extend(record_bytes("PS_after", 0x32, b"after")); - let found: Vec<_> = records(&file).collect(); - let names: Vec<_> = found.iter().map(|r| r.name).collect(); - assert_eq!(names, [Some("CS_x"), Some("PS_after")]); - assert_eq!(found[0].unpack(), None); - assert_eq!(found[1].unpack().as_deref(), Some(&b"after"[..])); - } - - #[test] - fn nested_markers_without_streams_take_linear_work() { - // Bytes that each read as a marker whose span runs to the end of the - // file and covers every one after it, then a real record: each is - // skipped in favour of the record it covers. Before, every one of - // them rescanned (and reinflated) the rest of the file: these 8000 - // (150 KB) took 43 s in a test build, and now take milliseconds. - let real = record_bytes("PS_real", 0x32, b"real"); - let count = 8000; - let end = MAGIC.len() + count * 19 + real.len(); - let mut file = MAGIC.to_vec(); - for _ in 0..count { - let n = (end - (file.len() + 6)) as u32; - file.extend_from_slice(&[0, 0x32]); - for v in [n, 0x000D_DCE7, n, 1 << 20] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.push(0x07); // reserved block type: no deflate stream - } - file.extend(&real); - assert_eq!(file.len(), end); - let started = std::time::Instant::now(); - let found: Vec<_> = records(&file).collect(); - let names: Vec<_> = found.iter().map(|r| r.name).collect(); - assert_eq!(names, [Some("PS_real")]); - assert_eq!(found[0].unpack().as_deref(), Some(&b"real"[..])); - assert!(started.elapsed() < std::time::Duration::from_secs(5)); - } - #[test] fn corrupt_stream_does_not_unpack() { - let mut file = MAGIC.to_vec(); - file.extend(record_bytes("CS_x", 0x3c, &[1; 64])); - file[31] = 0xFF; // first packed byte: reserved block type + let mut file = record_bytes("CS_x", 0x3c, &[1; 64]); + file[27] = 0xFF; // first packed byte: reserved block type let r = records(&file).next().unwrap(); assert_eq!(r.unpack(), None); } - /// `count` markers between the magic and a real record, each followed by - /// a stored block that ends where the next marker's stored block starts, - /// so the deflate stream after every marker runs through all the ones - /// after it, to a reserved block (no deflate stream) just before the - /// real record. `n(at)` is each marker's `n`, given its offset. - fn chained_markers(count: usize, n: impl Fn(usize) -> u32, real: &[u8]) -> Vec<u8> { - const PAD: usize = 41; - let len = (PAD + 18) as u16; - let mut file = MAGIC.to_vec(); - for _ in 0..count { - file.extend_from_slice(&[0, 0x32]); - let n = n(file.len() + 4); - for v in [n, 0x000D_DCE7, n, n] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.push(0x00); // stored, not final - file.extend_from_slice(&len.to_le_bytes()); - file.extend_from_slice(&(!len).to_le_bytes()); - file.extend_from_slice(&[0x5A; PAD]); - } - file.extend_from_slice(&[0x5A; 18]); - file.push(0x07); // reserved block type - file.extend_from_slice(real); - file - } - #[test] - fn chained_markers_past_the_end_take_linear_work() { - // Each marker's packed size runs past the end of the file, so its - // bytes are checked for the start of a deflate stream. Before, each - // check inflated the rest of the chain: these 32000 (2 MB) took 9 s - // in a test build. The chain is a valid deflate stream for far more - // than the probe reads, so the first marker is now taken for a - // truncated record, as a cut-off file's last record would be. - let real = record_bytes("PS_real", 0x32, b"real"); - let file = chained_markers(32_000, |_| MAX_UNPACKED as u32, &real); - let started = std::time::Instant::now(); - assert_eq!(records(&file).count(), 0); - assert!(started.elapsed() < std::time::Duration::from_secs(5)); - } + fn handles_empty_and_rejects_mismatched_or_truncated_streams() { + let empty = record_bytes("CS_empty", 0x3c, &[]); + assert_eq!(records(&empty).next().unwrap().unpack(), Some(Vec::new())); - #[test] - fn chained_markers_inside_the_file_take_linear_work() { - // Each marker's packed bytes end at the end of the file, so the - // first covers all the others and each of them is checked for a - // deflate stream. Before, each check inflated the rest of the chain - // (9 s for these 32000 in a test build). The first is yielded as a - // corrupt record whose span is all of them. - let count = 32_000; - let end = chained_markers(count, |_| 0, &[]).len(); - let file = chained_markers(count, |at| (end - at) as u32, &[]); - let started = std::time::Instant::now(); - let found: Vec<_> = records(&file).collect(); - assert_eq!(found.len(), 1); - assert_eq!(found[0].span(), MAGIC.len() + 6..file.len()); - assert_eq!(found[0].unpack(), None); - assert!(started.elapsed() < std::time::Duration::from_secs(5)); + let payload: Vec<u8> = (0..16_384u32) + .map(|i| (i.wrapping_mul(31) ^ (i >> 5)) as u8) + .collect(); + let good = record_bytes("PS_big", 0x32, &payload); + let r = records(&good).next().unwrap(); + assert_eq!(r.unpack(), Some(payload.clone())); + + // Oversized stream (declared unpacked_size smaller than actual output). + let mut smaller = good.clone(); + smaller[r.offset + 8..r.offset + 12] + .copy_from_slice(&((payload.len() - 1) as u32).to_le_bytes()); + assert_eq!(records(&smaller).next().unwrap().unpack(), None); + + // Under-filled stream (declared unpacked_size larger than actual output). + let mut larger = good.clone(); + larger[r.offset + 8..r.offset + 12] + .copy_from_slice(&((payload.len() + 1) as u32).to_le_bytes()); + assert_eq!(records(&larger).next().unwrap().unpack(), None); + + // Truncated raw deflate stream. + let mut truncated = good[..good.len() - 1].to_vec(); + let new_n = (truncated.len() - r.offset) as u32; + truncated[r.offset - 4..r.offset].copy_from_slice(&new_n.to_le_bytes()); + truncated[r.offset + 4..r.offset + 8].copy_from_slice(&new_n.to_le_bytes()); + assert_eq!(records(&truncated).next().unwrap().unpack(), None); } } diff --git a/crates/victory-game/tests/survey.rs b/crates/victory-game/tests/survey.rs deleted file mode 100644 index e1c33072a6..0000000000 --- a/crates/victory-game/tests/survey.rs +++ /dev/null @@ -1,188 +0,0 @@ -//! SGD5 records and the raw `DXBC` scan together, as `victory shader` -//! (`apps/victory/src/shader.rs`, `sources`) combines them: every record, -//! then every container stored as is outside the records and outside the -//! parts of other containers. The CLI does not build on Linux, so its -//! composition is checked here. - -use victory_game::sgd5::{self, MAGIC}; -use victory_shader::Container; -use victory_shader::dxbc::find_all; - -/// What `sources` yields: the records, and the raw containers as (offset, -/// bytes). -fn survey(data: &[u8]) -> (Vec<sgd5::Record<'_>>, Vec<(usize, &[u8])>) { - let records: Vec<_> = if sgd5::is_sgd5(data) { - sgd5::records(data).collect() - } else { - Vec::new() - }; - let raw = find_all(data, |offset| sgd5::in_record(&records, offset)); - (records, raw) -} - -/// A container with the given parts, laid out the way `Container::parse` -/// reads one. -fn container(parts: &[(&[u8; 4], &[u8])]) -> Vec<u8> { - let table = 0x20 + 4 * parts.len(); - let mut body = Vec::new(); - let mut offsets = Vec::new(); - for (fourcc, data) in parts { - offsets.push((table + body.len()) as u32); - body.extend_from_slice(*fourcc); - body.extend_from_slice(&(data.len() as u32).to_le_bytes()); - body.extend_from_slice(data); - } - let mut out = b"DXBC".to_vec(); - out.extend_from_slice(&[0xA5; 16]); - out.extend_from_slice(&[1, 0, 0, 0]); - out.extend_from_slice(&((table + body.len()) as u32).to_le_bytes()); - out.extend_from_slice(&(parts.len() as u32).to_le_bytes()); - for o in offsets { - out.extend_from_slice(&o.to_le_bytes()); - } - out.extend(body); - out -} - -/// A record at the end of `file`, returning its marker's offset. -fn push_record(file: &mut Vec<u8>, name: &str, payload: &[u8], level: u8) -> usize { - let packed = miniz_oxide::deflate::compress_to_vec(payload, level); - let n = (packed.len() + 12) as u32; - file.push(name.len() as u8 + 1); - file.extend_from_slice(name.as_bytes()); - file.extend_from_slice(&[0, 0x32]); - let at = file.len() + 4; - for v in [n, 0x000D_DCE7, n, payload.len() as u32] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend_from_slice(&packed); - at -} - -#[test] -fn stored_record_container_is_counted_once() { - // A record stored as is (level 0), so its container's bytes, magic and - // all, sit in the file as they are; then a container between records. - let inner = container(&[(b"SFI0", &[1, 2, 3, 4])]); - let mut file = MAGIC.to_vec(); - file.push(0x01); - let first = push_record(&mut file, "PS_stored", &inner, 0); - let between = file.len(); - let gap = container(&[(b"STAT", &[7; 12])]); - file.extend_from_slice(&gap); - file.push(0x01); - let second = push_record(&mut file, "PS_packed", &inner, 6); - - let (records, raw) = survey(&file); - let offsets: Vec<_> = records.iter().map(|r| r.offset).collect(); - assert_eq!(offsets, [first, second]); - for r in &records { - let bytes = r.unpack().expect("record unpacks"); - assert!(Container::parse(&bytes).is_ok()); - } - assert_eq!(raw, [(between, &gap[..])]); - - // Without the magic the file is no SGD5 file: the stored container is - // found as is, at its place in the record's packed bytes. - let plain = &file[MAGIC.len()..]; - let (records, raw) = survey(plain); - assert!(records.is_empty()); - let stored = memchr::memmem::find(plain, b"DXBC").unwrap(); - let offsets: Vec<_> = raw.iter().map(|&(o, _)| o).collect(); - assert_eq!(offsets, [stored, between - MAGIC.len()]); - assert_eq!(raw[0].1, &inner[..]); -} - -/// Seeded random archives: another file's container before the magic, then -/// records (some stored as is, holding a container, a record and a container -/// of their own) with gaps of noise, magics that do not parse, and -/// containers stored as is, some keeping another container in a part. The -/// survey yields exactly the planted records and the planted top-level -/// containers, each once, and no raw container overlaps a record. -#[test] -fn random_archives_survey_each_container_once() { - let mut x = 0x2545_F491_u32; - let mut next = move || { - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - x - }; - for seed in 0..200 { - let mut planted_raw: Vec<(usize, Vec<u8>)> = Vec::new(); - let mut planted: Vec<(usize, Vec<u8>)> = Vec::new(); - let mut gap_container = |file: &mut Vec<u8>, next: &mut dyn FnMut() -> u32| { - let data: Vec<u8> = (0..4 + next() % 60).map(|_| next() as u8).collect(); - let c = if next() & 1 == 0 { - let kept = container(&[(b"SFI0", &data)]); - container(&[(b"ILDB", &kept), (b"HASH", &[9; 20])]) - } else { - container(&[(b"STAT", &data)]) - }; - planted_raw.push((file.len(), c.clone())); - file.extend_from_slice(&c); - }; - - let mut file = b"other file".to_vec(); - gap_container(&mut file, &mut next); - file.extend_from_slice(MAGIC); - for i in 0..1 + next() % 5 { - for _ in 0..next() % 30 { - file.push(next() as u8); - } - if next() % 3 == 0 { - // A magic whose header does not parse (size past the end). - file.extend_from_slice(b"DXBC"); - file.extend_from_slice(&[0xFF; 28]); - } - if next() & 1 == 0 { - gap_container(&mut file, &mut next); - } - // Noise before a name's length byte must not read as the name. - file.push(0x01); - let data: Vec<u8> = (0..4 + next() % 200).map(|_| next() as u8).collect(); - let mut payload = container(&[(b"DXIL", &data), (b"HASH", &[3; 20])]); - let level = if next() & 1 == 0 { - let mut stored = Vec::new(); - push_record(&mut stored, "PS_stored", &payload, 0); - payload.extend(stored); - payload.extend(container(&[(b"SFI0", &[5; 8])])); - 0 - } else { - 6 - }; - let at = push_record(&mut file, &format!("PS_{seed}_{i}"), &payload, level); - planted.push((at, payload)); - } - for _ in 0..next() % 30 { - file.push(next() as u8); - } - if next() & 1 == 0 { - gap_container(&mut file, &mut next); - } - - let (records, raw) = survey(&file); - let got: Vec<_> = records.iter().map(|r| (r.offset, r.unpack())).collect(); - let want: Vec<_> = planted - .iter() - .map(|(at, payload)| (*at, Some(payload.clone()))) - .collect(); - assert_eq!(got, want, "seed {seed}: records"); - for (_, bytes) in &got { - let bytes = bytes.as_deref().unwrap(); - assert!(Container::parse(bytes).is_ok(), "seed {seed}"); - } - let raw_got: Vec<_> = raw.iter().map(|&(o, b)| (o, b.to_vec())).collect(); - assert_eq!(raw_got, planted_raw, "seed {seed}: raw containers"); - for &(offset, bytes) in &raw { - let span = offset..offset + bytes.len(); - for r in &records { - let rs = r.span(); - assert!( - span.end <= rs.start || rs.end <= span.start, - "seed {seed}: raw {span:?} overlaps record {rs:?}" - ); - } - } - } -} diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index e186e8e7ee..e6d8445220 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -9,7 +9,7 @@ publish.workspace = true [dependencies] blake3.workspace = true -miniz_oxide.workspace = true +zlib-rs.workspace = true tracing.workspace = true anyhow.workspace = true victory-formats.workspace = true @@ -27,10 +27,9 @@ diagnostics = [] workspace = true [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_EventLog", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", - "Win32_Graphics_Direct3D_Dxc", "Win32_Graphics_Direct3D_Fxc", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs new file mode 100644 index 0000000000..8bb8d9ba2b --- /dev/null +++ b/crates/victory-gpu/src/ambient.rs @@ -0,0 +1,586 @@ +//! A least amount of indirect light. +//! +//! Grand Theft Auto VI's indirect diffuse light comes from probes it fills +//! by tracing rays, which do not run here yet: its program that resolves +//! them (`CS_ScreenProbes_TemporalResolve_*`) leaves next to nothing, and +//! whatever the sun does not reach directly is black. Right after that +//! program, its output is replaced by a constant (it used to be a floor +//! under what the program wrote, but that is garbage: see the shader). The +//! constant is the same everywhere: the light in these images does not go with the title's exposure +//! (well-lit surfaces hold about the same in a shot at -5.5 EV and in one at +//! -9.75). The title's own lighting then applies it with the surfaces' +//! colors. Raised, not added: the result is the next frame's history. +//! +//! `VICTORY_AMBIENT=<level>` sets it (0.45 by default, 0 for none); `off` +//! keeps the title's own output. +//! shortcut: the same light everywhere, from everywhere; gone once rays run. + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU32, Ordering}; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::s; + +use crate::host::{HostList, host}; +use crate::object::This; + +/// The programs it follows, by the start of their name. +pub(crate) const PROGRAM: &[u8] = b"CS_ScreenProbes_TemporalResolve"; +/// Where they write the indirect diffuse light (R9G9B9E5 as 32-bit +/// integers): root parameter and place in its table. +pub(crate) const LIGHT: (u8, u32) = (1, 176); + +/// 0.6 looked balanced in run a2; Try 6.4: 0.45, as people came out too +/// bright with 0.6 (the level is the same in every shot, and the title +/// raises its exposure in dark ones, at night and indoors, which made skin +/// and clothes glow). `VICTORY_AMBIENT=off` leaves what the title's resolve +/// wrote; 0 is no indirect diffuse light at all. +const DEFAULT: f32 = 0.45; + +/// The floor; `None` if off. +pub(crate) fn level() -> Option<f32> { + static LEVEL: OnceLock<f32> = OnceLock::new(); + let level = *LEVEL.get_or_init(|| { + let set = std::env::var("VICTORY_AMBIENT").unwrap_or_default(); + if set.trim() == "off" { + return -1.0; + } + set.trim().parse().ok().filter(|l: &f32| l.is_finite() && *l >= 0.0).unwrap_or(DEFAULT) + }); + (level >= 0.0).then_some(level) +} + +/// The light's colour: warm white, or what `VICTORY_AMBIENT_TINT=r,g,b` +/// gives. With `VICTORY_AMBIENT_FILE=<file>` (diagnostics builds) the file's +/// `level r g b` is read again twice a second, to tune both by eye in a +/// running game. +fn tint() -> [f32; 3] { + let live = LIVE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, tint)) = *live { + return tint; + } + static SET: OnceLock<[f32; 3]> = OnceLock::new(); + *SET.get_or_init(|| { + let set: Vec<f32> = std::env::var("VICTORY_AMBIENT_TINT") + .unwrap_or_default() + .split(',') + .filter_map(|v| v.trim().parse().ok()) + .collect(); + match set[..] { + [r, g, b] => [r, g, b], + _ => [1.0, 0.98, 0.94], + } + }) +} + +/// The level and colour last read from `VICTORY_AMBIENT_FILE`, if any. +static LIVE: std::sync::Mutex<Option<(f32, [f32; 3])>> = std::sync::Mutex::new(None); + +/// Where the resolve reads the scene's depth (reversed, D32 with stencil): +/// root parameter and place in its table. +pub(crate) const DEPTH: (u8, u32) = (0, 464); + +/// How much less of the light reaches creases and corners, worked out from +/// the depth image alone: strength (0 for none), the radius looked at in +/// metres, the near plane's distance, and the tangent of half the vertical +/// field of view (the last two are guesses the picture is not sensitive +/// to). `VICTORY_AMBIENT_SHADE=s,r,n,t` sets them; the file's values after +/// its first four replace them. +/// shortcut: stands in for the occlusion the title's traced probes carry. +static SHADE: std::sync::Mutex<Option<[f32; 4]>> = std::sync::Mutex::new(None); + +fn shade() -> [f32; 4] { + if let Some(live) = *SHADE.lock().unwrap_or_else(|e| e.into_inner()) { + return live; + } + static SET: OnceLock<[f32; 4]> = OnceLock::new(); + *SET.get_or_init(|| { + let mut shade = [1.0, 0.6, 0.1, 0.45]; + let set = std::env::var("VICTORY_AMBIENT_SHADE").unwrap_or_default(); + for (to, v) in shade.iter_mut().zip(set.split(',')) { + if let Ok(v) = v.trim().parse() { + *to = v; + } + } + shade + }) +} + +/// The level from `VICTORY_AMBIENT_FILE`, if it gave one; starts the thread +/// that reads the file. +fn live_level() -> Option<f32> { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + if !cfg!(feature = "diagnostics") { + return; + } + let Some(file) = std::env::var_os("VICTORY_AMBIENT_FILE") else { return }; + let _ = std::thread::Builder::new().name("victory-ambient".into()).spawn(move || { + loop { + let read: Vec<f32> = std::fs::read_to_string(&file) + .unwrap_or_default() + .split_whitespace() + .filter_map(|v| v.parse().ok()) + .collect(); + if let [level, r, g, b, ref rest @ ..] = read[..] { + if let [s, r, n, t] = rest[..] { + *SHADE.lock().unwrap_or_else(|e| e.into_inner()) = Some([s, r, n, t]); + } + let new = Some((level.max(0.0), [r, g, b])); + let mut live = LIVE.lock().unwrap_or_else(|e| e.into_inner()); + if *live != new { + tracing::info!(level, r, g, b, "ambient light set from the file"); + *live = new; + } + } + std::thread::sleep(std::time::Duration::from_millis(500)); + } + }); + }); + LIVE.lock().unwrap_or_else(|e| e.into_inner()).map(|(level, _)| level) +} + +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=12, b0), DescriptorTable(UAV(u0), SRV(t0), SRV(t1), UAV(u1))" +cbuffer Floor : register(b0) { + float level; float3 tint; + float strength; float radius; float near; float tan_y; + float follow; float least; float steep; float spare; +}; +RWTexture2D<uint> light : register(u0); +Texture2D<float> depth : register(t0); +// Try 6.6: the lit scene the resolve reads, and what the card keeps of its +// brightness from frame to frame (adapted log2 brightness, the high mark, +// frames, the factor on the light). +Texture2D<float4> scene : register(t1); +RWByteAddressBuffer state : register(u1); +groupshared float sums[64]; +groupshared float counts[64]; +// The eye's adaptation, on the card alone (no read back, no wait): the +// scene's mean log brightness from 256 points, eased in over frames, and +// against the brightest it has been lately. The darker the scene than that +// (night, indoors), the less of the constant light: the title raises its +// exposure there, which made people glow. +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void measure(uint3 id : SV_GroupThreadID) { + uint w, h; + scene.GetDimensions(w, h); + float sum = 0.0, n = 0.0; + for (uint k = 0; k < 4; k++) { + uint i = id.x * 4 + k; + float2 uv = (float2(i % 16, i / 16) + 0.5) / 16.0; + float3 c = scene.Load(int3(int2(uv * float2(w, h)), 0)).rgb; + float l = dot(c, float3(0.2126, 0.7152, 0.0722)); + if (!isnan(l) && !isinf(l)) { + sum += log2(clamp(l, 1e-6, 65504.0)); + n += 1.0; + } + } + sums[id.x] = sum; + counts[id.x] = n; + GroupMemoryBarrierWithGroupSync(); + for (uint s = 32; s > 0; s >>= 1) { + if (id.x < s) { + sums[id.x] += sums[id.x + s]; + counts[id.x] += counts[id.x + s]; + } + GroupMemoryBarrierWithGroupSync(); + } + if (id.x == 0) { + float now = counts[0] > 0.0 ? sums[0] / counts[0] : 0.0; + float adapted = asfloat(state.Load(0)); + float high = asfloat(state.Load(4)); + uint frames = state.Load(8); + if (frames == 0 || isnan(adapted) || isnan(high) || isinf(adapted) || isinf(high)) { + adapted = now; + high = now; + } + adapted = lerp(adapted, now, 0.1); + high = max(high - 0.004, adapted); + float factor = max(least, exp2(-max(high - adapted, 0.0) * steep)); + state.Store(0, asuint(adapted)); + state.Store(4, asuint(high)); + state.Store(8, frames + 1); + state.Store(12, asuint(factor)); + } +} +// The point seen at a texel, in metres from the eye (x right, y up, z away). +float3 seen(int2 p, float2 size) { + float d = depth.Load(int3(clamp(p, int2(0, 0), int2(size) - 1), 0)); + float z = near / max(d, 1e-7); + float2 ndc = (float2(p) + 0.5) / size * 2.0 - 1.0; + return float3(ndc.x * tan_y * size.x / size.y * z, -ndc.y * tan_y * z, z); +} +// How much of the light from around reaches the texel: 1 in the open. +float open_to_light(int2 p, float2 size) { + float3 c = seen(p, size); + if (c.z > 400.0) return 1.0; + float3 l = seen(p + int2(-1, 0), size), r = seen(p + int2(1, 0), size); + float3 u = seen(p + int2(0, -1), size), d = seen(p + int2(0, 1), size); + float3 dx = abs(l.z - c.z) < abs(r.z - c.z) ? c - l : r - c; + float3 dy = abs(u.z - c.z) < abs(d.z - c.z) ? c - u : d - c; + float3 n = normalize(cross(dy, dx)); + if (dot(n, c) > 0.0) n = -n; + float px = radius * size.y / (2.0 * tan_y * c.z); + if (px < 1.5) return 1.0; + px = min(px, 128.0); + float noise = frac(52.9829189 * frac(dot(float2(p), float2(0.06711056, 0.00583715)))); + float sum = 0.0; + const int N = 16; + for (int i = 0; i < N; i++) { + float a = i * 2.399963 + noise * 6.2831853; + float2 o = float2(cos(a), sin(a)) * (sqrt((i + 0.5) / N) * px); + float3 v = seen(p + int2(round(o)), size) - c; + float vv = dot(v, v); + float over = dot(v, n) - 0.004 * c.z - 0.005; + sum += max(over, 0.0) / sqrt(vv + 1e-6) * saturate(1.0 - vv / (radius * radius)); + } + return saturate(1.0 - strength * 2.0 * sum / N); +} +float3 unpack(uint v) { + return float3(v & 511, (v >> 9) & 511, (v >> 18) & 511) * exp2(float(v >> 27) - 24.0); +} +uint pack(float3 c) { + c = clamp(c, 0.0, 65408.0); + float most = max(c.r, max(c.g, c.b)); + int e = clamp(int(floor(log2(max(most, 1e-9)))) + 16, 0, 31); + float scale = exp2(float(24 - e)); + if (most * scale >= 511.5) { e = min(e + 1, 31); scale = exp2(float(24 - e)); } + uint3 m = min(uint3(c * scale + 0.5), 511u); + return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); +} +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void main(uint3 at : SV_DispatchThreadID) { + uint w, h; + light.GetDimensions(w, h); + if (at.x >= w || at.y >= h) return; + // What the resolve left is not kept: without rays its inputs are never + // written and it holds whatever their memory did (bright magenta on + // translucent surfaces, blocks of colours indoors: run v6, 2026-11-25). + float open = strength > 0.0 ? open_to_light(int2(at.xy), float2(w, h)) : 1.0; + float f = follow > 0.5 ? asfloat(state.Load(12)) : 1.0; + if (!(f > 0.0) || f > 1.0) f = 1.0; + light[at.xy] = pack(tint * level * f * open); +} +"#; + +/// Views, used in turn: more than the passes of every list in flight. +const SLOTS: u32 = 1024; + +struct Pass { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// Try 6.6: the brightness measure ([`follow`]) and its state. + measure: ID3D12PipelineState, + state: ID3D12Resource, + views: ID3D12DescriptorHeap, + step: u32, + next: AtomicU32, +} +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Pass {} +// SAFETY: as above. +unsafe impl Sync for Pass {} + +/// Try 6.6, the fill light follows the scene (`VICTORY_AMBIENT_FOLLOW=0`: +/// the same everywhere, as before): the least share of it in the darkest +/// scenes (`VICTORY_AMBIENT_FOLLOW_MIN`, 0.35) and how fast it falls per +/// stop the scene is darker than its brightest lately +/// (`VICTORY_AMBIENT_FOLLOW_STEEP`, 0.35). Every modern renderer scales +/// its indirect light with the scene's; this one is measured on the card +/// from the lit scene the resolve reads, with no read back. +fn follow() -> Option<(f32, f32)> { + static SET: OnceLock<Option<(f32, f32)>> = OnceLock::new(); + *SET.get_or_init(|| { + if std::env::var_os("VICTORY_AMBIENT_FOLLOW").is_some_and(|v| v == "0") { + return None; + } + let get = |name: &str, default: f32| { + std::env::var(name).ok().and_then(|v| v.trim().parse::<f32>().ok()).filter(|v| v.is_finite()).unwrap_or(default) + }; + Some((get("VICTORY_AMBIENT_FOLLOW_MIN", 0.35).clamp(0.0, 1.0), get("VICTORY_AMBIENT_FOLLOW_STEEP", 0.35).clamp(0.0, 4.0))) + }) +} + +/// The view format the brightness measure reads a resource of `format` +/// with, if it is a lit scene's (a floating-point colour image). +fn scene_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> { + match format { + DXGI_FORMAT_R11G11B10_FLOAT => Some(DXGI_FORMAT_R11G11B10_FLOAT), + DXGI_FORMAT_R16G16B16A16_FLOAT | DXGI_FORMAT_R16G16B16A16_TYPELESS => Some(DXGI_FORMAT_R16G16B16A16_FLOAT), + DXGI_FORMAT_R32G32B32A32_FLOAT | DXGI_FORMAT_R32G32B32A32_TYPELESS => Some(DXGI_FORMAT_R32G32B32A32_FLOAT), + DXGI_FORMAT_R9G9B9E5_SHAREDEXP => Some(DXGI_FORMAT_R9G9B9E5_SHAREDEXP), + _ => None, + } +} + +fn compile(entry: windows::core::PCSTR) -> windows::core::Result<Vec<u8>> { + let mut code: Option<ID3DBlob> = None; + let mut errors: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; out pointers ours. + let compiled = unsafe { + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + s!("ambient"), + None, + None, + entry, + s!("cs_5_1"), + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + let text = |b: &ID3DBlob| { + // SAFETY: the blob's own bytes. + unsafe { std::slice::from_raw_parts(b.GetBufferPointer().cast::<u8>(), b.GetBufferSize()) } + .to_vec() + }; + if let Err(e) = compiled { + if let Some(errors) = errors { + tracing::warn!("ambient light: {}", String::from_utf8_lossy(&text(&errors))); + } + return Err(e); + } + Ok(text(&code.ok_or_else(windows::core::Error::empty)?)) +} + +fn make(device: &ID3D12Device) -> windows::core::Result<Pass> { + let code = compile(s!("main"))?; + let measure_code = compile(s!("measure"))?; + // SAFETY: the root signature is inside the shader; plain creations. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?; + let measure = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: measure_code.as_ptr().cast(), + BytecodeLength: measure_code.len(), + }, + ..Default::default() + })?; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let buffer = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let mut state: Option<ID3D12Resource> = None; + device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, None, &mut state)?; + let state = state.ok_or_else(windows::core::Error::empty)?; + let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + })?; + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + let views = device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: SLOTS * 4, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })?; + Ok(Pass { + root, + pso, + measure, + state, + views, + step: device.GetDescriptorHandleIncrementSize(kind), + next: AtomicU32::new(0), + }) + } +} + +fn uav_barrier(list: &ID3D12GraphicsCommandList) { + let barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + ..Default::default() + }; + // SAFETY: an open list; the barrier names no resource. + unsafe { list.ResourceBarrier(&[barrier]) }; +} + +/// Raises what `light` holds to the floor, in `list`, after the program that +/// wrote it as an image. Whether it recorded anything (the list's bindings +/// are then ours). +pub(crate) fn raise(list: &HostList, light: This, depth: Option<This>, scenes: &[This]) -> bool { + let (Some(level), Some(host)) = (level(), host()) else { + return false; + }; + let Some(light) = crate::resource::host_resource(light) else { + return false; + }; + static PASS: OnceLock<Option<Pass>> = OnceLock::new(); + let Some(pass) = PASS + .get_or_init(|| { + make(&host.device) + .inspect_err(|e| tracing::warn!(error = %e, "no ambient light")) + .ok() + }) + .as_ref() + else { + return false; + }; + // SAFETY: a live resource. + let d = unsafe { light.GetDesc() }; + static ONCE: std::sync::Once = std::sync::Once::new(); + if d.Format != DXGI_FORMAT_R32_UINT { + ONCE.call_once(|| tracing::warn!(format = d.Format.0, "no ambient light: another format")); + return false; + } + ONCE.call_once(|| { + tracing::info!(level, width = d.Width, height = d.Height, "ambient light"); + }); + let slot = pass.next.fetch_add(1, Ordering::Relaxed) % SLOTS * 4; + // The lit scene among what the resolve reads: the first colour image + // in floating point other than the light itself ([`follow`]). + let scene = follow().and_then(|_| { + scenes.iter().filter_map(|&t| crate::resource::host_resource(t)).find_map(|t| { + // SAFETY: a live resource. + let s = unsafe { t.GetDesc() }; + let format = scene_format(s.Format)?; + (s.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && s.Width >= 64 && s.Height >= 64 && t != light) + .then_some((t, format, s.Width, s.Height, s.Format.0)) + }) + }); + static SCENE_ONCE: std::sync::Once = std::sync::Once::new(); + SCENE_ONCE.call_once(|| match scene { + Some((_, _, width, height, format)) => tracing::info!( + width, + height, + format, + "ambient light follows the scene's brightness, measured on the card (VICTORY_AMBIENT_FOLLOW=0: the same everywhere)" + ), + None => tracing::info!( + candidates = scenes.len(), + "ambient light: no lit scene among what the resolve reads, the same everywhere" + ), + }); + if let Some((t, ..)) = scene { + list.keep(t); + } + list.keep(light); + // The depth the resolve just read, in the state it read it in; of the + // light's size, or the shading is left out. + let depth = depth.and_then(crate::resource::host_resource).filter(|t| { + // SAFETY: a live resource. + let t = unsafe { t.GetDesc() }; + t.Format == DXGI_FORMAT_R32G8X24_TYPELESS && (t.Width, t.Height) == (d.Width, d.Height) + }); + if let Some(depth) = depth { + list.keep(depth); + } + let l = &list.list; + uav_barrier(l); + // SAFETY: an open list; a live texture the list keeps, in the + // unordered-access state as the program before left it; a view in a slot + // no list in flight reads. + unsafe { + let cpu = pass.views.GetCPUDescriptorHandleForHeapStart(); + let gpu = pass.views.GetGPUDescriptorHandleForHeapStart(); + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: cpu.ptr + (slot * pass.step) as usize, + }; + let view = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + host.device + .CreateUnorderedAccessView(light, None::<&ID3D12Resource>, Some(&view), at); + let seen = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, + }, + }; + let beside = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: at.ptr + pass.step as usize }; + host.device.CreateShaderResourceView(depth, Some(&seen), beside); + let lit = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: scene.map_or(DXGI_FORMAT_R16G16B16A16_FLOAT, |s| s.1), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, + }, + }; + let third = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: at.ptr + 2 * pass.step as usize }; + host.device.CreateShaderResourceView(scene.map(|s| s.0), Some(&lit), third); + let kept = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: 0, + NumElements: 64, + StructureByteStride: 0, + CounterOffsetInBytes: 0, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + }, + }, + }; + let fourth = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: at.ptr + 3 * pass.step as usize }; + host.device + .CreateUnorderedAccessView(&pass.state, None::<&ID3D12Resource>, Some(&kept), fourth); + l.SetDescriptorHeaps(&[Some(pass.views.clone())]); + l.SetComputeRootSignature(&pass.root); + l.SetPipelineState(&pass.pso); + let [r, g, b] = tint(); + let level = live_level().unwrap_or(level); + let [strength, radius, near, tan_y] = shade(); + let strength = if depth.is_some() { strength } else { 0.0 }; + let (least, steep) = follow().unwrap_or((1.0, 0.0)); + let following = if scene.is_some() { 1.0 } else { 0.0 }; + let constants = [level, r, g, b, strength, radius, near, tan_y, following, least, steep, 0.0]; + l.SetComputeRoot32BitConstants(0, 12, constants.as_ptr().cast(), 0); + l.SetComputeRootDescriptorTable( + 1, + D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: gpu.ptr + u64::from(slot * pass.step), + }, + ); + if scene.is_some() { + l.SetPipelineState(&pass.measure); + l.Dispatch(1, 1, 1); + uav_barrier(l); + l.SetPipelineState(&pass.pso); + } + l.Dispatch((d.Width as u32).div_ceil(8), d.Height.div_ceil(8), 1); + } + uav_barrier(l); + true +} + +#[cfg(test)] +mod tests { + /// The pass compiles with the system's compiler and the host takes it. + #[test] + fn ambient_pass_builds() { + let Some(host) = crate::host::host() else { + return; + }; + super::make(&host.device).expect("the ambient pass"); + } +} diff --git a/crates/victory-gpu/src/awake.rs b/crates/victory-gpu/src/awake.rs new file mode 100644 index 0000000000..816440b7b0 --- /dev/null +++ b/crates/victory-gpu/src/awake.rs @@ -0,0 +1,207 @@ +//! Keeps the card's clocks up between submissions (`VICTORY_CARD_AWAKE=1`; off +//! by default). The card stands idle half of every frame, some thirty times for +//! a millisecond or two each, while the CPU prepares the next submission. The +//! driver takes that for a light load and lowers the clocks, and what comes +//! next starts slow: a captured frame whose lists take 30 ms sent in one go +//! takes 38-40 ms with waits of 1.2-2.4 ms between its submissions +//! (`victory replay --pace`). From avatarmanz/VIctory-7900XTX 5f86fa30 and +//! 040aa272. +//! +//! One group of 64 threads counts on a compute queue, over and +//! over: it takes one or two of the card's few thousand wave slots, and the +//! card is never idle. Nothing is sent once no submission has gone out for +//! a quarter of a second (a title that stands still; not a menu, which goes on +//! drawing: the system's counter shows the compute queue at 100 % there too). + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; + +use windows::Win32::Foundation::CloseHandle; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::Interface; + +/// About 2 ms at full clocks: 500 sends a second. +const COUNT: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer sum : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + uint x = id.x; + [loop] for (uint i = 0; i < 400000u; i++) x = x * 1664525u + 1013904223u; + sum.Store(id.x * 4u, x); +} +"#; + +/// Quiet this long after the last submission. +const QUIET_MS: u64 = 250; + +fn now_ms() -> u64 { + static START: OnceLock<std::time::Instant> = OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// When a submission was last sent ([`now_ms`] plus one; 0: never). +static LAST: AtomicU64 = AtomicU64::new(0); + +fn wanted() -> bool { + let (last, now) = (LAST.load(Ordering::Relaxed), now_ms()); + last != 0 && now + 1 < last + QUIET_MS && (mode() != Mode::ByTurns || now / TURN_MS % 2 == 1) +} + +/// With `VICTORY_CARD_AWAKE=turns`: this long on, this long off. +const TURN_MS: u64 = 20_000; + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + Off, + On, + /// On and off by turns, to compare the two in one run (the log says when). + ByTurns, +} + +fn mode() -> Mode { + static MODE: OnceLock<Mode> = OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_CARD_AWAKE").as_deref() { + Ok("1") => Mode::On, + Ok("turns") => Mode::ByTurns, + _ => Mode::Off, + }) +} + +/// A submission of the title's goes to `device`'s drawing queue. +pub(super) fn sent(device: &ID3D12Device) { + if mode() == Mode::Off { + return; + } + let now = now_ms(); + let before = LAST.swap(now + 1, Ordering::Relaxed); + if mode() == Mode::ByTurns && before.saturating_sub(1) / TURN_MS != now / TURN_MS { + tracing::info!(on = now / TURN_MS % 2 == 1, "the card is kept awake, by turns"); + } + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + // Runs as long as the process does. + std::mem::forget(start(device, wanted)); + }); +} + +/// The thread that keeps the card busy; it ends when this is dropped. +pub(crate) struct Awake { + stop: std::sync::Arc<AtomicBool>, + thread: Option<std::thread::JoinHandle<()>>, +} + +impl Drop for Awake { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +/// Keeps the card of `device` busy while `wanted`. +pub(crate) fn start(device: &ID3D12Device, wanted: impl Fn() -> bool + Send + 'static) -> Option<Awake> { + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let (device, ended) = (device.clone(), stop.clone()); + let thread = std::thread::Builder::new() + .name("victory-card-awake".into()) + .spawn(move || { + if let Err(e) = run(&device, &wanted, &ended) { + tracing::warn!(error = %e, "the card is not kept awake"); + } + }) + .ok()?; + Some(Awake { + stop, + thread: Some(thread), + }) +} + +fn run(device: &ID3D12Device, wanted: &dyn Fn() -> bool, stop: &AtomicBool) -> windows::core::Result<()> { + let code = super::compile(COUNT, windows::core::s!("main"), windows::core::s!("cs_5_1"))?; + // SAFETY: plain object creation; the code lives through the calls, the + // root signature is inside it. Two closed lists, sent in turn, whose + // objects live until what was sent last has run. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?; + let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + })?; + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, + Priority: D3D12_COMMAND_QUEUE_PRIORITY_NORMAL.0, + ..Default::default() + })?; + let mut sum: Option<ID3D12Resource> = None; + device.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut sum, + )?; + let sum = sum.ok_or_else(windows::core::Error::empty)?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE)?; + let mut lists = Vec::new(); + for _ in 0..2 { + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &allocator, &pso)?; + list.SetComputeRootSignature(&root); + list.SetComputeRootUnorderedAccessView(0, sum.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.Close()?; + lists.push(Some(list.cast::<ID3D12CommandList>()?)); + } + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + let mut value = 0u64; + let mut result = Ok(()); + while !stop.load(Ordering::Relaxed) && result.is_ok() { + if !wanted() { + std::thread::sleep(Duration::from_millis(2)); + continue; + } + // Never more than two on the way. + if value >= 2 && fence.GetCompletedValue() + 2 <= value { + result = fence.SetEventOnCompletion(value - 1, event); + if result.is_ok() { + WaitForSingleObject(event, 1000); + result = device.GetDeviceRemovedReason(); + } + continue; + } + queue.ExecuteCommandLists(&lists[(value % 2) as usize..][..1]); + value += 1; + result = queue.Signal(&fence, value); + } + if result.is_ok() && fence.GetCompletedValue() < value && fence.SetEventOnCompletion(value, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + let _ = CloseHandle(event); + result + } +} + diff --git a/crates/victory-gpu/src/backreads.rs b/crates/victory-gpu/src/backreads.rs new file mode 100644 index 0000000000..4d9a862bb6 --- /dev/null +++ b/crates/victory-gpu/src/backreads.rs @@ -0,0 +1,694 @@ +//! Diagnostics: who touches what the copy-back stored +//! (`VICTORY_BACK_READS`; off unless set; diagnostics builds only). +//! +//! What shaders wrote is fetched from the card and merged into title +//! memory after every submission (`Shadow::card_merge_relay`, +//! `Shadow::relay_merge`), 41 to 59 MB a frame in the first room, whether +//! or not anything reads those bytes there afterwards. This module counts, +//! per frame and per host copy, what happens to each stored 64 KiB page of +//! title memory between one store and the next: which reader of ours took +//! it, whether the title wrote it, and (for one page in [`SAMPLE`], view +//! memory stored through a view of our own only) whether ANYTHING touched +//! it through the title's addresses. +//! +//! The touch is seen without changing a byte or a protection. After the +//! store the 4 KiB pages of the stored stretch are taken out of the +//! process's working set at every title address that shows them +//! (`VirtualUnlock` of pages that are not locked: the documented way, as +//! `crate::pipeline::library::trim` does for the pipeline file). The bytes +//! stay in physical memory (our own view of the section holds the same +//! pages valid). The next access through a title address, by the title, by +//! a reader of ours or by the kernel on someone's behalf, is a soft fault +//! that Windows resolves by itself and that puts the page back in the +//! working set, where `QueryWorkingSetEx` shows it. Nothing faults into a +//! handler, a kernel call that reads or writes the page succeeds as +//! before, a read-only guard stays read-only and still takes the title's +//! writes. Measured on this PC (a probe outside the game): 5.4 +//! us to trim a 64 KiB piece beside six running threads, 2.8 us to ask +//! about its 16 pages, 0.89 us for each 4 KiB page somebody then reads. +//! +//! Values: `1` counts only (stores, readers of ours, title writes; no +//! page leaves the working set); `2` also looks at one page in [`SAMPLE`]; +//! `alt` is twenty seconds of `2` and twenty of `1` in turn, each change +//! said in the log, so that the look's own cost shows in the frame log. +//! +//! What a look cannot tell: WHO touched. A reader of ours is told apart by +//! the hooks in `crate::host` (`read_into`, `copy_mapped`, `write_mapped`); +//! a touch with no hook and no write is "something else", which is the +//! title's own reads at most (it also holds readers of ours that read in +//! place with no hook: a texture's refresh in place, the rectangle +//! vertices of `crate::draw`, and host libraries called by the title). + +use std::cell::Cell; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed}; +use std::sync::{Mutex, MutexGuard, OnceLock}; + +use crate::watch::PAGE; + +const KERNEL_PAGE: usize = 4096; +/// One stored page in this many is looked at (`2`, `alt`). +const SAMPLE: u64 = 8; +/// A stored page not stored again within this many frames is closed. +const KEEP: u64 = 8; +/// Frames between two summary lines; the buffers' table follows every +/// eighth of them. +const EVERY: f64 = 256.0; + +/// Readers of ours, as bits of `Seen::layer`. +pub(crate) const MERGE: u8 = 0; +pub(crate) const REFRESH: u8 = 1; +const REFRESH_OTHER: u8 = 2; +pub(crate) const UNDER: u8 = 3; +pub(crate) const TITLE_COPY: u8 = 4; +const STORE: u8 = 5; +const OTHER: u8 = 6; +const WHO: usize = 7; + +/// 0 off, 1 counted only, 2 with looks, 3 in turn. +fn setting() -> u8 { + static MODE: OnceLock<u8> = OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_BACK_READS").as_deref().map(str::trim) { + Ok("1") => 1, + Ok("2") => 2, + Ok("alt") => 3, + _ => 0, + }) +} + +/// Whether anything is counted at all. +pub(crate) fn on() -> bool { + setting() != 0 +} + +/// Whether stored pages are looked at now. +fn looking() -> bool { + match setting() { + 2 => true, + 3 => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: AtomicU8 = AtomicU8::new(2); + if LAST.swap(u8::from(on), Relaxed) != u8::from(on) { + tracing::info!( + "pages that came back are looked at for a touch from now (VICTORY_BACK_READS=alt): {}", + if on { "ON" } else { "off, counted only" } + ); + } + on + } + _ => false, + } +} + +/// Whether `page` is one of the pages looked at in `frame`: one in +/// [`SAMPLE`] by its number, another set every 512 frames. +fn sampled(page: usize, frame: u64) -> bool { + ((page as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 40) % SAMPLE == (frame / 512) % SAMPLE +} + +/// Sums, of one host copy or of all. +#[derive(Default, Clone, Copy)] +struct Tally { + /// Stretches stored, their bytes, those stored through a view of our + /// own and their bytes, pages stored for the first time in their + /// frame, and stores of a page stored a frame before or in the same. + stores: u64, + bytes: u64, + own: u64, + own_bytes: u64, + pages: u64, + again: u64, + /// Stores followed to their end, by which reader of ours took them + /// meanwhile ([`MERGE`]..), those whose guard was clean right after + /// the store, and of those the ones the title wrote. + ended: u64, + who: [u64; WHO], + clean: u64, + written: u64, + /// Stores whose pages were taken out of the working set, and those + /// looked at afterwards. + trimmed: u64, + looked: u64, + /// Of the looked at: nothing touched them (and their bytes); the + /// title wrote; readers of ours and no write; something else (and + /// their bytes). + untouched: u64, + untouched_bytes: u64, + wrote: u64, + ours: u64, + other: u64, + other_bytes: u64, + /// Their 4 KiB pages: touched, asked about. + small: [u64; 2], + /// Ends: no store of the page again within [`KEEP`] frames; the + /// runtime remapped the page; no look because a mapping was changing. + late: u64, + remapped: u64, + busy: u64, +} + +/// A stored page, from its store to the next one. +struct Seen { + /// The copy that stored: its number, and its title buffer's start and + /// bytes. + id: u64, + copy: (u64, u64), + /// The page's number at the address stored at. + page: usize, + frame: u64, + bytes: u64, + /// The stretch as whole 4 KiB pages: offsets in the 64 KiB page. + from: usize, + to: usize, + /// The page's address in every title view that shows it. + shown: Vec<usize>, + /// Not ended yet. + open: bool, + /// Stored through a view of our own. + own: bool, + trimmed: bool, + /// The guard of the page was clean right after the store, and the + /// journal's number for the page then. + clean: bool, + stamp: u64, + /// Readers of ours since the store. + layer: u8, +} + +/// What an ended store was found to be. +struct Judged { + written: bool, + /// 4 KiB pages touched, asked about. + looked: Option<(u32, u32)>, + busy: bool, +} + +#[derive(Default)] +struct State { + /// By page number (the address of the last store). + seen: HashMap<usize, Seen>, + /// Every title page number of a seen page: its key in `seen`. + names: HashMap<usize, usize>, + /// By copy (start, bytes), since the start. + buffers: HashMap<(u64, u64), Tally>, + since: Tally, + all: Tally, + frames: f64, + lines: u64, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); + +fn state() -> MutexGuard<'static, Option<State>> { + STATE.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A bit per title page number (its low 18 bits): set while the page may +/// be a seen one. What the hooks look at first, without a lock. +const BITS: usize = 1 << 18; +static TRACKED: [AtomicU64; BITS / 64] = [const { AtomicU64::new(0) }; BITS / 64]; + +fn bit(page: usize) -> (usize, u64) { + let b = page & (BITS - 1); + (b / 64, 1u64 << (b % 64)) +} + +fn mark(page: usize) { + let (word, b) = bit(page); + TRACKED[word].fetch_or(b, Relaxed); +} + +fn marked(page: usize) -> bool { + let (word, b) = bit(page); + TRACKED[word].load(Relaxed) & b != 0 +} + +thread_local! { + /// Which reader of ours this thread is now, and for which copy. + static AS: Cell<(u8, u64)> = const { Cell::new((OTHER, 0)) }; +} + +/// Puts back what the thread was reading as. +pub(crate) struct Scope((u8, u64)); + +impl Drop for Scope { + fn drop(&mut self) { + AS.with(|a| a.set(self.0)); + } +} + +/// Until what it returns is dropped, this thread's reads of title memory +/// count as `who`'s, for copy number `copy`. +pub(crate) fn reading_as(who: u8, copy: u64) -> Option<Scope> { + if !on() { + return None; + } + Some(Scope(AS.with(|a| a.replace((who, copy))))) +} + +fn each(s: &mut State, copy: (u64, u64), f: impl Fn(&mut Tally)) { + f(&mut s.since); + f(&mut s.all); + f(s.buffers.entry(copy).or_default()); +} + +/// The 4 KiB pages of the stretch found in the working set at any of the +/// page's title addresses, and how many there are; `None` if Windows did +/// not answer. +fn valid(seen: &Seen) -> Option<(u32, u32)> { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let pages = ((seen.to - seen.from) / KERNEL_PAGE).min(16); + let mut touched = [false; 16]; + for &base in &seen.shown { + // SAFETY: plain data. + let mut info: [PSAPI_WORKING_SET_EX_INFORMATION; 16] = unsafe { std::mem::zeroed() }; + for (i, entry) in info[..pages].iter_mut().enumerate() { + entry.VirtualAddress = (base + seen.from + i * KERNEL_PAGE) as *mut _; + } + // SAFETY: `pages` entries of the size given; our own process. The + // call reads page table state and touches no page. + let asked = unsafe { + K32QueryWorkingSetEx( + GetCurrentProcess(), + info.as_mut_ptr().cast(), + (pages * size_of::<PSAPI_WORKING_SET_EX_INFORMATION>()) as u32, + ) + } != 0; + if !asked { + return None; + } + for (i, entry) in info[..pages].iter().enumerate() { + // Bit 0 of the answer: the page is in the working set. + // SAFETY: plain data the query filled in. + if unsafe { entry.VirtualAttributes.Flags } & 1 != 0 { + touched[i] = true; + } + } + } + Some((touched[..pages].iter().filter(|&&t| t).count() as u32, pages as u32)) +} + +/// Takes the stretch's 4 KiB pages out of the working set at every title +/// address of the page; false, with nothing done, while the runtime +/// changes a mapping. +fn trim(shown: &[usize], from: usize, to: usize) -> bool { + use windows_sys::Win32::System::Memory::VirtualUnlock; + // No mapping changes until the addresses have been used. + let Some(_still) = crate::watch::title_memory_reading_now() else { + return false; + }; + for &base in shown { + // SAFETY: only the working set changes. Unlocking pages that are + // not locked fails, as expected, and takes them out of it; an + // address with nothing mapped fails and does nothing. Each range + // lies inside one 64 KiB page, so inside one view. + unsafe { VirtualUnlock((base + from) as *const _, to - from) }; + } + true +} + +/// Looks at an ended store, with no lock of ours held: whether the title +/// wrote the page (a store through our own view that left the guard +/// clean: the guard is open now, or the journal found the page written +/// since), and which of its trimmed pages are back in the working set. +fn judge(seen: &Seen) -> Judged { + let written = seen.own + && seen.clean + && (!crate::watch::clean(seen.page) || crate::watch::stamp(seen.page) > seen.stamp); + let looked = if seen.trimmed { + match crate::watch::title_memory_reading_now() { + Some(_still) => valid(seen), + None => None, + } + } else { + None + }; + Judged { written, looked, busy: seen.trimmed && looked.is_none() } +} + +/// Counts an ended store. `how`: 0 the page's next store, 1 none within +/// [`KEEP`] frames, 2 a remapping. +fn tally(s: &mut State, seen: &Seen, judged: &Judged, how: u8) { + let (layer, bytes, guarded) = (seen.layer, seen.bytes, seen.own && seen.clean); + let (written, looked, busy) = (judged.written, judged.looked, judged.busy); + each(s, seen.copy, |t| { + t.ended += 1; + for (who, count) in t.who.iter_mut().enumerate() { + if layer & (1 << who) != 0 { + *count += 1; + } + } + if guarded { + t.clean += 1; + } + if written { + t.written += 1; + } + match how { + 1 => t.late += 1, + 2 => t.remapped += 1, + _ => {} + } + if busy { + t.busy += 1; + } + if let Some((touched, asked)) = looked { + t.looked += 1; + t.small[0] += u64::from(touched); + t.small[1] += u64::from(asked); + if touched == 0 { + t.untouched += 1; + t.untouched_bytes += bytes; + } else if written { + t.wrote += 1; + } else if layer != 0 { + t.ours += 1; + } else { + t.other += 1; + t.other_bytes += bytes; + } + } + }); +} + +/// A merge is about to read title memory at `at` and may store there: the +/// page's last store ends here, before our own read touches the page. +/// Called by the thread that copies back, ahead of the merge's read. +pub(crate) fn before(at: usize) { + if !on() { + return; + } + let page = at / PAGE; + if !marked(page) { + return; + } + let (key, mut seen) = { + let mut guard = state(); + let Some(s) = guard.as_mut() else { + return; + }; + let Some(&key) = s.names.get(&page) else { + return; + }; + if !s.seen.get(&key).is_some_and(|seen| seen.open) { + return; + } + let Some(seen) = s.seen.remove(&key) else { + return; + }; + (key, seen) + }; + let judged = judge(&seen); + let mut guard = state(); + let Some(s) = guard.as_mut() else { + return; + }; + tally(s, &seen, &judged, 0); + seen.open = false; + // Kept, closed, for "stored again within a frame". + s.seen.entry(key).or_insert(seen); +} + +/// A merge of copy `id` (title buffer `copy`: start, bytes) stored +/// `[at, at + n)` of title memory, inside one 64 KiB page; `own`: through +/// a view of our own (`Shadow::put_back_own`), else through the kernel at +/// the title's address. +pub(crate) fn stored(id: u64, copy: (u64, u64), at: usize, n: usize, own: bool) { + if !on() || n == 0 { + return; + } + let page = at / PAGE; + let base = page * PAGE; + let from = (at - base) & !(KERNEL_PAGE - 1); + let to = (at - base + n).min(PAGE).next_multiple_of(KERNEL_PAGE); + let frame = crate::frame::current(); + // Asked with no lock of ours held. + let mut shown = crate::inplace::pages_of(base); + let many = shown.len() > crate::watch::MANY_VIEWS; + if shown.is_empty() || many { + shown = vec![base]; + } + let (clean, stamp) = if own { (crate::watch::clean(page), crate::watch::stamp(page)) } else { (false, 0) }; + // Only what went through our own view: its pages stay in physical + // memory whatever happens to the title's addresses (our view holds + // them), and the guard tells the title's writes there. + let trimmed = own && !many && looking() && sampled(page, frame) && trim(&shown, from, to); + let mut guard = state(); + let s = guard.get_or_insert_with(State::default); + let key = s.names.get(&page).copied().unwrap_or(page); + let old = s.seen.remove(&key); + let (again, first) = match &old { + Some(old) => (old.frame + 1 >= frame, old.frame != frame), + None => (false, true), + }; + if let Some(old) = old { + if old.open { + // A store with no `before` ahead of it: ended unlooked. + tally(s, &old, &Judged { written: false, looked: None, busy: old.trimmed }, 0); + } + for a in &old.shown { + s.names.remove(&(a / PAGE)); + } + } + each(s, copy, |t| { + t.stores += 1; + t.bytes += n as u64; + if own { + t.own += 1; + t.own_bytes += n as u64; + } + if first { + t.pages += 1; + } + if again { + t.again += 1; + } + if trimmed { + t.trimmed += 1; + } + }); + for a in &shown { + s.names.insert(a / PAGE, page); + mark(a / PAGE); + } + s.seen.insert( + page, + Seen { id, copy, page, frame, bytes: n as u64, from, to, shown, open: true, own, trimmed, clean, stamp, layer: 0 }, + ); +} + +/// A reader of ours reads title memory `[at, at + len)` (`store`: it +/// writes there through the kernel, as a merge does the old way). The +/// seen pages whose stored stretch it meets are noted read by it. +pub(crate) fn touched(at: usize, len: usize, store: bool) { + if !on() || len == 0 { + return; + } + let end = at.saturating_add(len); + let (first, last) = (at / PAGE, (end - 1) / PAGE); + if last - first > 1 << 16 || !(first..=last).any(marked) { + return; + } + let (who, copy) = AS.with(|a| a.get()); + let mut guard = state(); + let Some(s) = guard.as_mut() else { + return; + }; + for page in first..=last { + let Some(&key) = s.names.get(&page) else { + continue; + }; + let Some(seen) = s.seen.get_mut(&key) else { + continue; + }; + if !seen.open { + continue; + } + let base = page * PAGE; + let (a, b) = (at.max(base) - base, end.min(base + PAGE) - base); + if a >= seen.to || b <= seen.from { + continue; + } + let who = if store { + STORE + } else if who == REFRESH && copy != seen.id { + REFRESH_OTHER + } else { + who + }; + seen.layer |= 1 << who; + } +} + +/// The runtime mapped or unmapped title memory `[at, at + len)` +/// (`crate::watch::title_memory_remapped`): the seen pages there end, +/// unlooked (their addresses show something else from now on). +pub(crate) fn remapped(at: usize, len: usize) { + if !on() || len == 0 { + return; + } + let (first, last) = (at / PAGE, (at.saturating_add(len) - 1) / PAGE); + let mut guard = state(); + let Some(s) = guard.as_mut() else { + return; + }; + if s.names.is_empty() { + return; + } + let keys: Vec<usize> = if last - first < s.names.len() { + (first..=last).filter_map(|page| s.names.get(&page).copied()).collect() + } else { + s.names.iter().filter(|(page, _)| (first..=last).contains(*page)).map(|(_, key)| *key).collect() + }; + for key in keys { + // (A key may be named twice: two addresses of one page.) + let Some(seen) = s.seen.remove(&key) else { + continue; + }; + if seen.open { + tally(s, &seen, &Judged { written: false, looked: None, busy: false }, 2); + } + for a in &seen.shown { + s.names.remove(&(a / PAGE)); + } + } +} + +/// The sums as text, each divided by `per` (frames, or 1 for totals). +fn words(t: &Tally, per: f64) -> String { + let n = |v: u64| v as f64 / per; + let mb = |v: u64| v as f64 / per / (1 << 20) as f64; + let stores = format!( + "{:.1} stretches {:.2} MB stored in {:.1} pages ({:.1} stretches {:.2} MB through views of our own; the rest the \ + old way, counted and never looked at); {:.1} were of a page stored a frame before or in the same frame", + n(t.stores), + mb(t.bytes), + n(t.pages), + n(t.own), + mb(t.own_bytes), + n(t.again), + ); + let readers = format!( + "{:.1} stores followed to their end, taken meanwhile by: a refresh of the copy that stored {:.1}, a refresh of \ + another copy {:.1}, another merge {:.1}, the look for title bytes under flights {:.1}, a title copy or a fill \ + {:.1}, a store the old way {:.1}, another reader of ours {:.1}; the guard was clean after {:.1} stores and the \ + title wrote {:.1} of those", + n(t.ended), + n(t.who[REFRESH as usize]), + n(t.who[REFRESH_OTHER as usize]), + n(t.who[MERGE as usize]), + n(t.who[UNDER as usize]), + n(t.who[TITLE_COPY as usize]), + n(t.who[STORE as usize]), + n(t.who[OTHER as usize]), + n(t.clean), + n(t.written), + ); + let looks = format!( + "looked at {:.1} of {:.1} taken out of the working set (one page in {SAMPLE}): untouched {:.1} ({:.2} MB), \ + written by the title {:.1}, touched with readers of ours and no write {:.1}, touched by something else (the \ + title's reads at most) {:.1} ({:.2} MB); of their 4 KiB pages {:.1} of {:.1} were touched; ended with no store \ + of the page again in {KEEP} frames {:.1}, by a remapping {:.1}, with no look because a mapping was changing {:.1}", + n(t.looked), + n(t.trimmed), + n(t.untouched), + mb(t.untouched_bytes), + n(t.wrote), + n(t.ours), + n(t.other), + mb(t.other_bytes), + n(t.small[0]), + n(t.small[1]), + n(t.late), + n(t.remapped), + n(t.busy), + ); + format!("{stores}; {readers}; {looks}") +} + +/// The ten copies with the most bytes stored, and everything, since the +/// start. +fn table(s: &State) { + let mut rows: Vec<(&(u64, u64), &Tally)> = s.buffers.iter().collect(); + rows.sort_by_key(|(_, t)| std::cmp::Reverse(t.bytes)); + tracing::info!( + "what came back from the card and who touched it, since the start (VICTORY_BACK_READS), totals not per frame: {} \ + buffers; all of them: {}", + rows.len(), + words(&s.all, 1.0) + ); + for ((start, len), t) in rows.into_iter().take(10) { + tracing::info!(" came back to {start:#x}+{len:#x}: {}", words(t, 1.0)); + } +} + +unsafe extern "C" { + fn atexit(f: extern "C" fn()) -> i32; +} + +/// At process exit (not reached when the process is ended from outside: +/// the table is also logged with every eighth line). +extern "C" fn at_exit() { + if let Ok(guard) = STATE.try_lock() + && let Some(s) = guard.as_ref() + { + table(s); + } +} + +/// With the frame-rate line, over `frames` more frames: stores not +/// followed by another within [`KEEP`] frames end here, and every +/// [`EVERY`] frames the sums are said. +pub(crate) fn line(frames: f64) { + if !on() { + return; + } + static AT_EXIT: std::sync::Once = std::sync::Once::new(); + // SAFETY: registers a function with the host CRT's exit table. + AT_EXIT.call_once(|| unsafe { + atexit(at_exit); + }); + let frame = crate::frame::current(); + let old: Vec<Seen> = { + let mut guard = state(); + let s = guard.get_or_insert_with(State::default); + let keys: Vec<usize> = s.seen.iter().filter(|(_, seen)| seen.frame + KEEP < frame).map(|(key, _)| *key).collect(); + let old: Vec<Seen> = keys.into_iter().filter_map(|key| s.seen.remove(&key)).collect(); + old + }; + // Looked at with no lock of ours held. + let judged: Vec<Option<Judged>> = old.iter().map(|seen| seen.open.then(|| judge(seen))).collect(); + let mut guard = state(); + let s = guard.get_or_insert_with(State::default); + for (seen, judged) in old.iter().zip(&judged) { + if let Some(judged) = judged { + tally(s, seen, judged, 1); + } + } + // The names of what is gone, and the hooks' filter anew (a hook that + // looks while it is rebuilt may miss one read). + let seen = &s.seen; + s.names.retain(|_, key| seen.contains_key(key)); + for word in &TRACKED { + word.store(0, Relaxed); + } + for page in s.names.keys() { + mark(*page); + } + s.frames += frames; + if s.frames < EVERY { + return; + } + let (since, over) = (std::mem::take(&mut s.since), std::mem::replace(&mut s.frames, 0.0)); + tracing::info!( + "what came back from the card and who touched it, per frame over {over:.0} frames (VICTORY_BACK_READS={}): {}", + std::env::var("VICTORY_BACK_READS").unwrap_or_default(), + words(&since, over) + ); + s.lines += 1; + if s.lines.is_multiple_of(8) { + table(s); + } +} diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index c69155b44e..18cae57611 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -20,18 +20,167 @@ pub(crate) fn folder() -> Option<&'static PathBuf> { /// too, and their draws traced at debug level. pub(crate) fn listed(n: u64) -> bool { static LIST: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new(); - LIST.get_or_init(|| { - let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default(); + let named = LIST + .get_or_init(|| { + let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default(); + list.split(',') + .filter_map(|f| f.trim().parse().ok()) + .collect() + }) + .contains(&n); + // `VICTORY_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first + // one that ran 500 draws or more (a title's first 3D frames: their + // numbers depend on how long the menus were shown), and the 30th and + // the 80th (the title opens with a cutscene made in the + // engine: later shots of it, in case the first is dark by design). + // + // `VICTORY_CAPTURE_WORLD_ALSO` (comma-separated): more frames counted + // from that first one (the title's blue patches show from + // about the 118th frame on, when the window's model has arrived and + // the reflections hold values: none of the four above has them). + static ALSO: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new(); + let also = ALSO.get_or_init(|| { + let list = std::env::var("VICTORY_CAPTURE_WORLD_ALSO").unwrap_or_default(); list.split(',') .filter_map(|f| f.trim().parse().ok()) .collect() + }); + let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); + let after = n.wrapping_sub(first); + named || first != u64::MAX && ([2, 6, 30, 80].contains(&after) || also.contains(&after)) +} + +/// With a capture folder, for the frames [`listed`]: `what` is added to +/// the frame's `frame-<n>-ops.txt`, one line per draw, dispatch, copy or +/// drop in the order recorded (the title records on several threads, so +/// lines of different lists interleave; each names its list). The file +/// says which pass writes which target, to find the pass whose output +/// stays empty. +#[cfg(feature = "diagnostics")] +pub(crate) fn op(list: usize, what: impl FnOnce() -> String) { + // A frame shot (`crate::shot`) keeps every line of its frame. + if crate::shot::keeping_lines() { + let text = what(); + crate::shot::line(list, &text); + return op_listed(list, move || text); + } + op_listed(list, what); +} + +/// [`op`] for the frames [`listed`] and the lines before the world. +#[cfg(feature = "diagnostics")] +fn op_listed(list: usize, what: impl FnOnce() -> String) { + use std::io::Write; + let frame = crate::queue::presented() + 1; + if !listed(frame) { + // Before the world: the last lines are kept, and written out when + // it starts (`before-world-ops.txt`): what the title drew just + // before (the title shows a title card there, whose text + // did not show). + if world_on() && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX { + // At most 300 lines of a frame: the world's first frame alone + // (thousands of operations, recorded before it is known to be + // the world's) pushed everything before it out. + static IN_FRAME: std::sync::Mutex<(u64, u32)> = std::sync::Mutex::new((0, 0)); + { + let mut in_frame = IN_FRAME.lock().unwrap_or_else(|e| e.into_inner()); + if in_frame.0 != frame { + *in_frame = (frame, 0); + } + in_frame.1 += 1; + if in_frame.1 > 300 { + return; + } + } + let what = what(); + let mut ring = RING.lock().unwrap_or_else(|e| e.into_inner()); + if ring.len() >= RING_LINES { + ring.pop_front(); + } + ring.push_back(format!("frame {frame} list {list:#x} {what}")); + } + return; + } + let Some(folder) = folder() else { + return; + }; + static FILE: std::sync::Mutex<Option<(u64, u64, std::fs::File)>> = std::sync::Mutex::new(None); + let what = what(); + let mut file = FILE.lock().unwrap_or_else(|e| e.into_inner()); + if file.as_ref().is_none_or(|f| f.0 != frame) { + let Ok(made) = std::fs::File::create(folder.join(format!("frame-{frame}-ops.txt"))) else { + return; + }; + *file = Some((frame, 0, made)); + } + if let Some((_, n, f)) = file.as_mut() { + *n += 1; + let _ = writeln!(f, "{n} list {list:#x} {what}"); + } +} + +/// The last lines of [`op`] before the world. +#[cfg(feature = "diagnostics")] +static RING: std::sync::Mutex<std::collections::VecDeque<String>> = + std::sync::Mutex::new(std::collections::VecDeque::new()); +#[cfg(feature = "diagnostics")] +const RING_LINES: usize = 6000; + +/// Whether `VICTORY_CAPTURE_WORLD` is set. +fn world_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CAPTURE_WORLD").is_some()) +} + +/// Every how many world frames a picture is saved with +/// `VICTORY_CAPTURE_WORLD` (`VICTORY_CAPTURE_WORLD_EVERY`, 8 unless said). +/// +/// A saved frame is read back at once and written as a PNG inside the +/// present: run 225's frame log has every saved frame of the cell at 371 ms +/// against a usual 136 (the present's own copy and show 137 ms instead of +/// 2, and 123 ms more waiting for the card). At every 8th frame that was +/// the regular dip of every test run, and a fifth of its time. A run that +/// measures speed asks for 64 or more. +fn world_every() -> u64 { + static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| { + std::env::var("VICTORY_CAPTURE_WORLD_EVERY").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(8) }) - .contains(&n) +} + +/// The first frame that ran 500 draws or more (`VICTORY_CAPTURE_WORLD`). +static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX); + +/// At the present of `frame`: the draws run on the host so far. +pub(crate) fn frame_drew(frame: u64, drawn: u64) { + use std::sync::atomic::Ordering::Relaxed; + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let before = LAST.swap(drawn, Relaxed); + if world_on() + && drawn.saturating_sub(before) >= 500 + && WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed).is_ok() + { + tracing::info!(frame, "the first frame of 500 draws or more: frames {} and {} are captured", frame + 2, frame + 6); + #[cfg(feature = "diagnostics")] + if let Some(folder) = folder() { + let lines: Vec<String> = std::mem::take(&mut *RING.lock().unwrap_or_else(|e| e.into_inner())).into(); + let _ = std::fs::write(folder.join("before-world-ops.txt"), lines.join(" +")); + } + } } /// Whether frame `n` is saved. pub(crate) fn wanted(n: u64) -> bool { - folder().is_some() && (n.is_power_of_two() || listed(n)) + // Before the world, with `VICTORY_CAPTURE_WORLD`: every 16th frame too + // (small pictures of menus, loading screens and title cards). + let before_world = world_on() && n.is_multiple_of(16) && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX; + // In the world: every 8th frame's picture, a timeline of the opening + // cutscene (its shots do not fall on the same frame numbers from run to + // run, so single frames cannot be compared between runs). + let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); + let in_world = world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(world_every()); + folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world) } /// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`. @@ -63,11 +212,10 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: header.extend(h.to_be_bytes()); header.extend([8, 2, 0, 0, 0]); // 8-bit RGB chunk(&mut png, b"IHDR", &header); - chunk( - &mut png, - b"IDAT", - &miniz_oxide::deflate::compress_to_vec_zlib(&raw, 3), - ); + let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())]; + let (idat, rc) = zlib_rs::compress_slice(&mut compressed, &raw, zlib_rs::DeflateConfig::new(3)); + debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok); + chunk(&mut png, b"IDAT", idat); chunk(&mut png, b"IEND", &[]); let path = folder.join(format!("{name}.png")); match std::fs::write(&path, png) { @@ -76,6 +224,24 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: } } +/// A PNG of `w` by `h` 8-bit RGB pixels; `raw` is its rows, each after a +/// filter byte 0 (for `crate::shot`, whose pictures have names and sizes +/// of their own). +pub(crate) fn png_rgb(w: u32, h: u32, raw: &[u8]) -> Vec<u8> { + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut header = Vec::new(); + header.extend(w.to_be_bytes()); + header.extend(h.to_be_bytes()); + header.extend([8, 2, 0, 0, 0]); // 8-bit RGB + chunk(&mut png, b"IHDR", &header); + let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())]; + let (idat, rc) = zlib_rs::compress_slice(&mut compressed, raw, zlib_rs::DeflateConfig::new(3)); + debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok); + chunk(&mut png, b"IDAT", idat); + chunk(&mut png, b"IEND", &[]); + png +} + fn chunk(png: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) { png.extend((data.len() as u32).to_be_bytes()); let start = png.len(); @@ -102,6 +268,17 @@ pub(crate) fn read_back( device: &ID3D12Device, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource, +) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { + read_back_of(device, list, texture, 0) +} + +/// As [`read_back`], of subresource `sub` (the stencil plane of a +/// one-level, one-slice depth-stencil texture is subresource 1). +pub(crate) fn read_back_of( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, + sub: u32, ) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); let mut total = 0; @@ -110,7 +287,7 @@ pub(crate) fn read_back( let desc = texture.GetDesc(); device.GetCopyableFootprints( &desc, - 0, + sub, 1, 0, Some(&mut footprint), @@ -161,7 +338,7 @@ pub(crate) fn read_back( pResource: std::mem::transmute_copy(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: 0, + SubresourceIndex: sub, }, }; list.CopyTextureRegion(&to, 0, 0, 0, &from, None); @@ -213,101 +390,8 @@ fn dump_on() -> bool { *ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some()) } -/// `VICTORY_SHOW_TARGET=<w>x<h>-f<format>` (e.g. `2560x1440-f28`): the size and format of -/// the render target to show in place of the title's frame. -fn show_spec() -> Option<(u64, u32, i32)> { - static SPEC: std::sync::OnceLock<Option<(u64, u32, i32)>> = std::sync::OnceLock::new(); - *SPEC.get_or_init(|| parse_show_spec(&std::env::var("VICTORY_SHOW_TARGET").ok()?)) -} - -/// `<w>x<h>-f<format>` as (width, height, DXGI format); `None` if malformed. -fn parse_show_spec(v: &str) -> Option<(u64, u32, i32)> { - let (size, format) = v.trim().split_once("-f")?; - let (w, h) = size.split_once('x')?; - Some((w.parse().ok()?, h.parse().ok()?, format.parse().ok()?)) -} - -#[cfg(test)] -mod show_tests { - #[test] - fn show_spec_reads_size_and_format() { - assert_eq!( - super::parse_show_spec(" 2560x1440-f28 "), - Some((2560, 1440, 28)) - ); - assert_eq!(super::parse_show_spec("2560x1440"), None); - assert_eq!(super::parse_show_spec("2560-f28"), None); - assert_eq!(super::parse_show_spec("ax1440-f28"), None); - } -} - -/// The last render target bound that matches [`show_spec`]. -static SHOWN: std::sync::Mutex<Option<std::sync::Arc<crate::resource::HostTexture>>> = - std::sync::Mutex::new(None); - -/// Records, into `list`, a copy of the [`SHOWN`] target to the top left of -/// `back` (in the copy-destination state); false (nothing recorded) without -/// one or when the formats differ. -/// shortcut: copies 1:1 without scaling or conversion; a blit shader would fit any target. -pub(crate) fn show(list: &ID3D12GraphicsCommandList, back: &ID3D12Resource) -> bool { - let Some(shown) = SHOWN.lock().unwrap_or_else(|e| e.into_inner()).clone() else { - return false; - }; - let texture = &shown.texture; - // SAFETY: live resources. - let (d, b) = unsafe { (texture.GetDesc(), back.GetDesc()) }; - if d.Format != b.Format { - return false; - } - let state = D3D12_RESOURCE_STATES(crate::host::legal_state( - texture, - shown.state.load(std::sync::atomic::Ordering::Relaxed), - ) as i32); - let copy = D3D12_RESOURCE_STATE_COPY_SOURCE; - let area = D3D12_BOX { - right: d.Width.min(b.Width) as u32, - bottom: d.Height.min(b.Height), - back: 1, - ..Default::default() - }; - // SAFETY: an open list of ours; both live, `back` already a copy destination. - unsafe { - if state != copy { - list.ResourceBarrier(&[crate::host::transition(texture, state, copy)]); - } - let dst = D3D12_TEXTURE_COPY_LOCATION { - pResource: std::mem::transmute_copy(back), - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: 0, - }, - }; - let src = D3D12_TEXTURE_COPY_LOCATION { - pResource: std::mem::transmute_copy(texture), - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: 0, - }, - }; - list.CopyTextureRegion(&dst, 0, 0, 0, &src, Some(&area)); - if state != copy { - list.ResourceBarrier(&[crate::host::transition(texture, copy, state)]); - } - } - true -} - /// Notes a title texture the frame being built renders to or writes. pub(crate) fn note_target(resource: crate::object::This) { - if let Some((w, h, f)) = show_spec() - && let Some(copy) = crate::resource::host_copy(resource) - { - // SAFETY: a live resource. - let d = unsafe { copy.texture.GetDesc() }; - if (d.Width, d.Height, d.Format.0) == (w, h, f) { - *SHOWN.lock().unwrap_or_else(|e| e.into_inner()) = Some(copy); - } - } if resource.is_null() || !dump_on() || !listed(crate::queue::presented() + 1) { return; } @@ -323,9 +407,7 @@ pub(crate) fn note_target(resource: crate::object::This) { pub(crate) fn dump_targets(frame: u64) { use std::sync::atomic::Ordering::Relaxed; let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner())); - let Some(host) = crate::host::host() else { - return; - }; + let Some(host) = crate::host::host() else { return }; for (i, (resource, copy)) in targets.iter().enumerate() { let texture = ©.texture; // SAFETY: a live resource. @@ -335,15 +417,7 @@ pub(crate) fn dump_targets(frame: u64) { } // Every submission has run; the dump's list moves it there and back. let state = copy.state.load(Relaxed); - dump_one( - host, - texture, - state, - frame, - i, - *resource as crate::object::This, - &d, - ); + dump_one(host, texture, state, frame, i, *resource as crate::object::This, &d); } } @@ -366,17 +440,28 @@ fn dump_one( .ResourceBarrier(&[crate::host::transition(texture, state, copy)]); } let read = read_back(&host.device, &list.list, texture); + // The stencil plane of a depth-stencil target, which the title's + // lighting reads (material class in the low bits; 0x08 "inside a + // room", which the lamps of a room are multiplied by): the plane + // after the depth plane of a one-level, one-slice texture. + let stencil = (matches!(d.Format.0, 19..=22 | 44..=47) + && d.MipLevels == 1 + && d.DepthOrArraySize == 1) + .then(|| read_back_of(&host.device, &list.list, texture, 1)) + .flatten(); if state != copy { list.list .ResourceBarrier(&[crate::host::transition(texture, copy, state)]); } - read + (read, stencil) }; + let (read, stencil) = read; list.close(); host.execute(&[&list]); - let Some((buffer, footprint)) = read else { - return; - }; + if let Some((buffer, footprint)) = stencil { + stencil_values(&buffer, &footprint, frame, resource); + } + let Some((buffer, footprint)) = read else { return }; let f = footprint.Footprint; let mut data = std::ptr::null_mut(); // SAFETY: the copy finished; the mapping spans the footprint's rows. @@ -386,13 +471,27 @@ fn dump_one( } let pitch = f.RowPitch as usize; let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * f.Height as usize); - if let Some(rgba) = to_rgba( - f.Format.0 as u32, - f.Width as usize, - f.Height as usize, - pitch, - rows, - ) { + // A 24-bit depth plane comes back as 32-bit words: which depth values + // (low 24 bits) and which top bytes it holds, the most common first. + if matches!(d.Format.0, 44..=47) { + let mut depths = std::collections::HashMap::<u32, u32>::new(); + let mut tops = std::collections::HashMap::<u32, u32>::new(); + for y in 0..f.Height as usize { + for x in 0..f.Width as usize { + let at = y * pitch + x * 4; + let w = u32::from_le_bytes(rows[at..at + 4].try_into().unwrap_or([0; 4])); + *depths.entry(w & 0xff_ffff).or_default() += 1; + *tops.entry(w >> 24).or_default() += 1; + } + } + let most = |m: std::collections::HashMap<u32, u32>| { + let mut v: Vec<(u32, u32)> = m.into_iter().collect(); + v.sort_by_key(|e| std::cmp::Reverse(e.1)); + (v.len(), v.into_iter().take(12).collect::<Vec<_>>()) + }; + tracing::info!(?resource, depths = ?most(depths), top_bytes = ?most(tops), "24-bit depth plane values (value, texels)"); + } + if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) { let name = format!( "frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}", d.Width, d.Height, d.Format.0 @@ -405,12 +504,69 @@ fn dump_one( } } +/// Logs which values a stencil plane read back by [`read_back_of`] holds +/// (the most common first), how many texels have each of its bits, and the +/// box of the texels with bit 3 (0x08). +fn stencil_values( + buffer: &ID3D12Resource, + footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + frame: u64, + resource: crate::object::This, +) { + let f = footprint.Footprint; + let (w, h, pitch) = (f.Width as usize, f.Height as usize, f.RowPitch as usize); + let mut data = std::ptr::null_mut(); + // SAFETY: the copy finished; the mapping spans the footprint's rows of + // one byte a texel, the last row without its padding. + unsafe { + if h == 0 || w == 0 || buffer.Map(0, None, Some(&mut data)).is_err() { + return; + } + let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * (h - 1) + w); + let mut values = [0u32; 256]; + let mut bits = [0u32; 8]; + // Left, top, right, bottom of the texels with bit 3. + let mut inside = [u32::MAX, u32::MAX, 0, 0]; + for y in 0..h { + for (x, &v) in rows[y * pitch..y * pitch + w].iter().enumerate() { + values[usize::from(v)] += 1; + for (bit, count) in bits.iter_mut().enumerate() { + *count += u32::from(v >> bit & 1); + } + if v & 8 != 0 { + inside = [ + inside[0].min(x as u32), + inside[1].min(y as u32), + inside[2].max(x as u32), + inside[3].max(y as u32), + ]; + } + } + } + let mut most: Vec<(usize, u32)> = values + .iter() + .copied() + .enumerate() + .filter(|v| v.1 != 0) + .collect(); + most.sort_by_key(|v| std::cmp::Reverse(v.1)); + most.truncate(16); + tracing::info!( + frame, + ?resource, + width = w, + height = h, + values = ?most, + texels_with_bit = ?bits, + bit3_box = ?inside, + "stencil plane values (value, texels)" + ); + buffer.Unmap(0, None); + } +} + fn half(h: u16) -> f32 { - let (sign, exp, man) = ( - (h >> 15) as u32, - ((h >> 10) & 0x1f) as i32, - (h & 0x3ff) as f32, - ); + let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32); let v = match exp { 0 => man * 2f32.powi(-24), 31 => f32::INFINITY, @@ -434,12 +590,11 @@ fn small_float(bits: u32, man: u32) -> f32 { /// as channel values scaled so the largest finite one is white (single /// channels: lowest black, highest white, as grey). `None` for formats not /// handled. -fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option<Vec<u8>> { +pub(crate) fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option<Vec<u8>> { let mut out = Vec::with_capacity(w * h * 4); let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n]; let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]); - let u32_at = - |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4])); + let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4])); // Channel values as floats, then scaled. type Decode = Box<dyn Fn(&[u8]) -> [f32; 3]>; let (n, decode): (usize, Decode) = match format { @@ -462,62 +617,23 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } return Some(out); } - 23..=25 | 89 => ( - 4, - Box::new(move |b| { - let v = u32_at(b, 0); - [ - (v & 0x3ff) as f32, - (v >> 10 & 0x3ff) as f32, - (v >> 20 & 0x3ff) as f32, - ] - }), - ), - 26 => ( - 4, - Box::new(move |b| { - let v = u32_at(b, 0); - [ - small_float(v & 0x7ff, 6), - small_float(v >> 11 & 0x7ff, 6), - small_float(v >> 22, 5), - ] - }), - ), - 9..=10 => ( - 8, - Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))]), - ), - 11..=14 => ( - 8, - Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i)))), - ), - 33..=34 => ( - 4, - Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0]), - ), - 1..=2 => ( - 16, - Box::new(move |b| [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i)))), - ), - 15..=16 => ( - 8, - Box::new(move |b| { - [ - f32::from_bits(u32_at(b, 0)), - f32::from_bits(u32_at(b, 1)), - 0.0, - ] - }), - ), - 35..=38 => ( - 4, - Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0]), - ), - 48..=52 => ( - 2, - Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0]), - ), + 23..=25 | 89 => (4, Box::new(move |b| { + let v = u32_at(b, 0); + [(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32] + })), + 26 => (4, Box::new(move |b| { + let v = u32_at(b, 0); + [small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)] + })), + 9..=10 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])), + 11..=14 => (8, Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i))))), + 33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])), + 1..=2 => (16, Box::new(move |b| { + [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i))) + })), + 15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])), + 35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])), + 48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])), // Single channels (and depth planes): shown as grey. 39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), 19..=22 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), @@ -539,9 +655,90 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option (0.0, finite.fold(0.0f32, f32::max)) }; let range = (high - low).max(1e-20); - tracing::info!(format, low, high, "target values"); + // How much of the target holds anything: a lit scene and one bright + // lamp on black have the same highest value. + let above = values.iter().filter(|v| v.iter().any(|c| c.is_finite() && *c > low)).count(); + let nonzero_percent = above as f32 * 100.0 / values.len().max(1) as f32; + tracing::info!(format, low, high, nonzero_percent, "target values"); + // Small float colour targets (the 1x1 luminance and exposure targets): + // every texel's four channels as numbers. The picture has no alpha and + // eight bits a channel. + if matches!(format, 1..=2 | 9..=10) && w * h <= 16 { + for y in 0..h { + for x in 0..w { + let b = px(x, y, n); + let texel: [f32; 4] = if n == 16 { + [0, 1, 2, 3].map(|i| f32::from_bits(u32_at(b, i))) + } else { + [0, 1, 2, 3].map(|i| half(u16_at(b, i))) + }; + tracing::info!(format, x, y, ?texel, "target texel"); + } + } + } + // R32_UINT targets hold packed light (the title reads them back as + // R9G9B9E5): as floats their low, high and share above the lowest say + // nothing. How many texels hold any bit, and the highest channel value + // of the packed reading. + if format == 42 { + let (mut set, mut packed_high) = (0usize, 0f32); + for y in 0..h { + for x in 0..w { + let v = u32_at(px(x, y, 4), 0); + set += usize::from(v != 0); + let scale = 2f32.powi((v >> 27) as i32 - 24); + for k in 0..3 { + packed_high = packed_high.max((v >> (9 * k) & 0x1ff) as f32 * scale); + } + } + } + let nonzero_bits_percent = set as f32 * 100.0 / (w * h).max(1) as f32; + tracing::info!(format, nonzero_bits_percent, packed_high, "target values as packed light"); + // The same words as plain numbers, by class. Tables of indices and + // masks say nothing as floats or as packed light: in the title's + // shadow-mask table 0 is a block in full shadow, a word up to 255 + // one value for the block, above that a block of the atlas, and all + // ones a texel never written. + let mut classes = [0usize; 6]; + let mut highest_below_ones = 0u32; + for y in 0..h { + for x in 0..w { + let v = u32_at(px(x, y, 4), 0); + classes[match v { + 0 => 0, + 1..=15 => 1, + 16..=255 => 2, + 256..=0x00ff_ffff => 3, + u32::MAX => 5, + _ => 4, + }] += 1; + if v != u32::MAX { + highest_below_ones = highest_below_ones.max(v); + } + } + } + tracing::info!( + format, + width = w, + height = h, + zero = classes[0], + one_to_15 = classes[1], + to_255 = classes[2], + to_24_bits = classes[3], + larger = classes[4], + all_ones = classes[5], + highest_below_ones, + "target values as words" + ); + } + // Float colours (scene light) go through a cube root: scaled linearly, + // a night scene under one lamp of 50 units came out all black. + let curved = matches!(format, 1..=2 | 9..=10 | 26); for v in values { - let c = v.map(|c| (((c - low) / range).clamp(0.0, 1.0) * 255.0) as u8); + let c = v.map(|c| { + let t = ((c - low) / range).clamp(0.0, 1.0); + ((if curved { t.cbrt() } else { t }) * 255.0) as u8 + }); out.extend([c[0], c[1], c[2], 255]); } Some(out) @@ -686,20 +883,11 @@ mod tests { fn unorm16_and_xr_bias_targets_decode_as_their_formats() { // Red 0x8000 (a half-float -0), green 0x4000, blue 0. let unorm16 = [0x00, 0x80, 0x00, 0x40, 0, 0, 0xff, 0xff]; - assert_eq!( - super::to_rgba(11, 1, 1, 8, &unorm16), - Some(vec![255, 127, 0, 255]) - ); + assert_eq!(super::to_rgba(11, 1, 1, 8, &unorm16), Some(vec![255, 127, 0, 255])); // Red 0x3ff, green 0x1ff, blue 0, alpha 3. let xr = (0x3ffu32 | 0x1ff << 10 | 3 << 30).to_le_bytes(); - assert_eq!( - super::to_rgba(89, 1, 1, 4, &xr), - Some(vec![255, 127, 0, 255]) - ); + assert_eq!(super::to_rgba(89, 1, 1, 4, &xr), Some(vec![255, 127, 0, 255])); // B8G8R8A8 still swaps to RGBA. - assert_eq!( - super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), - Some(vec![3, 2, 1, 255]) - ); + assert_eq!(super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), Some(vec![3, 2, 1, 255])); } } diff --git a/crates/victory-gpu/src/cardmeter.rs b/crates/victory-gpu/src/cardmeter.rs new file mode 100644 index 0000000000..bd22598901 --- /dev/null +++ b/crates/victory-gpu/src/cardmeter.rs @@ -0,0 +1,560 @@ +//! What the card's time goes to, by kind of list, in every run. +//! +//! The card's clock (`crate::host`) says how long the card had work of +//! ours, not which work. The timing run (`VICTORY_GPU_TIMING`) names every +//! title command but sends each list on its own, which changes the frame, +//! and it never timed the lists the layer adds for itself: the one that +//! brings copies in the card's memory up to date and hashes their pieces +//! again, and the one that compares pieces after a submission's lists. +//! Run 187's table left 64 ms a frame of card time unexplained beside +//! them (40 ms by the count outside timing runs); with draw windows off +//! the card is the frame's limit (run 225: 85 to 98 % busy), so that sum +//! decides what is worth changing. +//! +//! Here a list gets one timestamp where it begins and one where it ends, +//! both resolved into one read-back buffer by the list itself. The card +//! writes them when it gets there; a pair is read a second and a half +//! after it was recorded, when every flight of that time has long landed, +//! and its length goes to the frame log's totals by kind. So the frame +//! log's card columns are of the frames of a moment ago: right for the +//! usual frame, not for placing one long frame. +//! +//! On by default in diagnostics builds; `VICTORY_CARD_METER=0` or `1` says +//! otherwise. Two queries and a resolve a list. + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +/// What a timed list is. +#[derive(Clone, Copy)] +pub(crate) enum Kind { + /// Ours: changed bytes go up to copies in the card's memory and their + /// pieces are hashed again (`Host::card_before`). + Sync, + /// Ours: the compare of the pieces a submission's shaders may have + /// written, and the fetch of the flagged ones inside the flight. + Check, + /// Every other host list: the title's own, our present copies. + Lists, + /// Inside one of those: from where a pipeline is bound to where the + /// next one is, or the list ends ([`begin_named`]). + Pipeline, + /// Inside one of those: the clamp of an indirect command, from before + /// its first barrier to after its second ([`clamp_begin`]; a sample). + Clamp, +} + +/// Pairs of timestamps in the ring. +const PAIRS: u32 = 32768; +/// A pair is read this long after it was recorded. +const AFTER: std::time::Duration = std::time::Duration::from_millis(1000); + +/// A pair being recorded: its place in the ring, or none. +#[derive(Clone, Copy)] +pub(crate) struct Span(u32); + +impl Span { + pub(crate) const NONE: Span = Span(u32::MAX); + /// For keeping in an atomic. + pub(crate) fn raw(self) -> u32 { + self.0 + } + pub(crate) fn from_raw(raw: u32) -> Span { + Span(raw) + } +} + +struct Meter { + heap: ID3D12QueryHeap, + back: ID3D12Resource, + /// The read-back buffer's bytes, mapped for good. + mapped: usize, + /// Ticks a second of the queue's clock. + frequency: u64, + next: u32, + /// Pairs recorded and not read yet: place, kind, when recorded. + pending: std::collections::VecDeque<(u32, Kind, std::time::Instant)>, + /// What the list of a pair mostly is ([`end_named`]), by place, until + /// the pair is read. + names: std::collections::HashMap<u32, String>, + /// Since the last table: by name, the lists and their microseconds. + by_name: std::collections::HashMap<String, (u64, u64)>, + /// The same by pipeline ([`begin_named`]): the times it was bound and + /// the microseconds until the next one was. + by_pipeline: std::collections::HashMap<String, (u64, u64)>, + /// Frames since the last table. + frames: u64, + /// What each place held when it was last read: a place the card has + /// not written since (its list never ran) still holds that, and is + /// not counted again. + seen: Vec<(u64, u64)>, + /// Since the last line "the card per frame": where each whole list + /// began and ended, in ticks of the queue's clock ([`gaps_line`]). + spans: Vec<(u64, u64)>, + /// Frames since that line, and when it was last written. + gap_frames: u64, + gap_line: std::time::Instant, + /// Since that line: clamps timed and their microseconds ([`clamp_begin`]). + clamps: (u64, u64), + /// Since that line, by kind (the title's lists, our send-and-hash + /// lists, our compares): lists and their microseconds. Try 6.16: the + /// frame log has them too, but Try's builds run without it. + kinds: [(u64, u64); 3], + /// When the last table by name was written: at least once a minute + /// (256 frames are 85 s at 3 fps). + table_at: std::time::Instant, +} + +// SAFETY: host objects (free-threaded) and a mapping only read, behind a lock. +unsafe impl Send for Meter {} + +static METER: Mutex<Option<Option<Meter>>> = Mutex::new(None); + +/// Whether lists are timed. +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var_os("VICTORY_CARD_METER") { + Some(v) => v != "0", + None => cfg!(feature = "diagnostics"), + }) +} + +fn make() -> Option<Meter> { + let host = crate::host::host()?; + let device = host.device(); + let mut heap: Option<ID3D12QueryHeap> = None; + let mut back: Option<ID3D12Resource> = None; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(PAIRS) * 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + // SAFETY: plain object creation; the buffer is mapped once and stays so. + unsafe { + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: PAIRS * 2, NodeMask: 0 }, + &mut heap, + ) + .ok()?; + device + .CreateCommittedResource(&readback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back) + .ok()?; + let (heap, back) = (heap?, back?); + let mut mapped = std::ptr::null_mut(); + back.Map(0, None, Some(&mut mapped)).ok()?; + let frequency = host.timestamp_frequency(); + if mapped.is_null() || frequency == 0 { + return None; + } + tracing::info!( + "the card's time is measured by kind of list, a timestamp where each list begins and ends (VICTORY_CARD_METER=0: not)" + ); + Some(Meter { + heap, + back, + mapped: mapped as usize, + frequency, + next: 0, + pending: Default::default(), + names: Default::default(), + by_name: Default::default(), + by_pipeline: Default::default(), + frames: 0, + seen: vec![(0, 0); PAIRS as usize], + spans: Vec::new(), + gap_frames: 0, + gap_line: std::time::Instant::now(), + clamps: (0, 0), + kinds: [(0, 0); 3], + table_at: std::time::Instant::now(), + }) + } +} + +/// A list of `kind` begins here: the first timestamp of a pair. +pub(crate) fn begin(list: &ID3D12GraphicsCommandList, kind: Kind) -> Span { + if !on() { + return Span::NONE; + } + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + let Some(m) = meter.get_or_insert_with(make) else { + return Span::NONE; + }; + // The ring must not come round to pairs that were not read yet. + if m.pending.len() as u32 >= PAIRS - 64 { + return Span::NONE; + } + let pair = m.next; + m.next = (m.next + 1) % PAIRS; + m.pending.push_back((pair, kind, std::time::Instant::now())); + // SAFETY: an open list and our query heap. + unsafe { list.EndQuery(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, pair * 2) }; + Span(pair) +} + +/// The list ends here: the pair's second timestamp, and both go to the +/// read-back buffer when the card has run the list. +pub(crate) fn end(list: &ID3D12GraphicsCommandList, span: Span) { + if span.0 == u32::MAX { + return; + } + let meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(m)) = meter.as_ref() else { + return; + }; + // SAFETY: an open list, our heap and our read-back buffer, the pair's + // own sixteen bytes of it. + unsafe { + list.EndQuery(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, span.0 * 2 + 1); + list.ResolveQueryData(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, span.0 * 2, 2, &m.back, u64::from(span.0) * 16); + } +} + +/// Whether the card's time is also measured pipeline by pipeline inside the +/// title's lists (`VICTORY_CARD_METER_PIPELINES=1`; off by default: two +/// more queries and a resolve at every change of pipeline). +pub(crate) fn pipelines() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| on() && std::env::var_os("VICTORY_CARD_METER_PIPELINES").is_some_and(|v| v == "1")) +} + +/// The pipeline `name` is bound on `list` here: the first timestamp of a +/// pair that [`end`] closes where the next pipeline is bound or the list +/// ends. What the card does between the two (the draws or dispatches of +/// that pipeline, and what the layer records around them) is that +/// pipeline's time in the table. +pub(crate) fn begin_named(list: &ID3D12GraphicsCommandList, name: &str) -> Span { + let span = begin(list, Kind::Pipeline); + if span.0 != u32::MAX { + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(Some(m)) = meter.as_mut() { + m.names.insert(span.0, name.to_owned()); + } + } + span +} + +/// [`end`] for one of the title's lists, with what it mostly is: the +/// pipelines it binds (`names`, in order, as the list keeps them). Every +/// 256 frames the card's time is logged by that name: which of the title's +/// passes the card's time goes to, in a run like any other (the timing run +/// that names every command sends each list alone and needs the +/// device-removed notes). +pub(crate) fn end_named(list: &ID3D12GraphicsCommandList, span: Span, names: &std::collections::BTreeSet<String>) { + if span.0 == u32::MAX { + return; + } + end(list, span); + let name = name_of(names); + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(Some(m)) = meter.as_mut() { + m.names.insert(span.0, name); + } +} + +/// A list's name in the table: how many pipelines it binds and the first +/// two of them (the set is in the order of the names, so a pass has the +/// same name every frame). +fn name_of(names: &std::collections::BTreeSet<String>) -> String { + let short = |n: &String| n.chars().take(60).collect::<String>(); + let mut first = names.iter(); + match (first.next(), first.next()) { + (None, _) => "no pipeline (copies, clears, barriers)".to_string(), + (Some(a), None) => format!("1 pipeline: {}", short(a)), + (Some(a), Some(b)) => format!("{} pipelines: {} / {}", names.len(), short(a), short(b)), + } +} + +/// One clamp in how many is timed (`VICTORY_CARD_METER_CLAMPS=<n>`, 1 to +/// 4096; unset or 0: none). Each timed clamp adds two timestamps and a +/// resolve to the list, which the card writes when it gets there: they wait +/// for nothing and change no command the title recorded. Risk-free, but a +/// timestamp is itself a small point of order on some cards, so a sample. +fn clamp_every() -> u64 { + static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *N.get_or_init(|| { + if !on() { + return 0; + } + std::env::var("VICTORY_CARD_METER_CLAMPS").ok().and_then(|v| v.trim().parse::<u64>().ok()).map_or(0, |n| n.min(4096)) + }) +} + +/// Every clamp recorded since the line "the card per frame" ([`clamp_begin`]). +static CLAMPS_ALL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// An indirect command's clamp begins here (`crate::indirect`, before its +/// first barrier): the first timestamp of a pair if this clamp is one of +/// the sample, else none. Every clamp is counted, to scale the sample. +pub(crate) fn clamp_begin(list: &ID3D12GraphicsCommandList) -> Span { + let every = clamp_every(); + if every == 0 { + return Span::NONE; + } + let n = CLAMPS_ALL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if !n.is_multiple_of(every) { + return Span::NONE; + } + begin(list, Kind::Clamp) +} + +/// Microseconds between two timestamps of a clock of `frequency` ticks a +/// second; 0 if the second is not after the first (a pair the card has not +/// written, or a list that never ran). +fn micros(begin: u64, end: u64, frequency: u64) -> u64 { + if end <= begin || frequency == 0 { + return 0; + } + ((end - begin) as u128 * 1_000_000 / frequency as u128).min(10_000_000) as u64 +} + +/// The line "the card per frame": of the direct queue's time by its own +/// clock, how long a list of ours was running (the union of the lists' +/// stamps) and how long none was, between one list's end and the next +/// list's begin, by the length of the gap. The frame line's "card: idle" +/// says how much of a frame had nothing of ours queued; what the gaps +/// hold beyond that is the card standing with work of ours queued, which +/// no line said (runs 293 to 300: 26 to 43 ms a frame). Short gaps are +/// what the card pays between two lists; long ones are waits: for the +/// title, for a present, for memory to be mapped under a texture, for +/// another program's turn on the card. Diagnostics, every five seconds. +fn gaps_line(m: &mut Meter) { + let frames = m.gap_frames.max(1) as f64; + let kinds = std::mem::take(&mut m.kinds); + if kinds.iter().any(|k| k.0 > 0) { + let ms = |us: u64| us as f64 / 1e3 / frames; + let n = |lists: u64| lists as f64 / frames; + tracing::info!( + "the card's time per frame by kind of list (VICTORY_CARD_METER): the title's lists {:.1} ms in {:.0}, our send-and-hash lists {:.1} ms in {:.0}, \ + our compares after a submission {:.1} ms in {:.0}", + ms(kinds[0].1), + n(kinds[0].0), + ms(kinds[1].1), + n(kinds[1].0), + ms(kinds[2].1), + n(kinds[2].0) + ); + } + m.gap_frames = 0; + let mut spans = std::mem::take(&mut m.spans); + if spans.len() < 2 || m.frequency == 0 { + return; + } + spans.sort_unstable(); + let us = |ticks: u64| (ticks as u128 * 1_000_000 / m.frequency as u128) as u64; + // Gaps under 0.1 ms, to 2 ms, to 20 ms, and longer: how many, and + // their microseconds. + let mut gaps = [(0u64, 0u64); 4]; + let (mut running, mut summed) = (0u64, 0u64); + let mut reached = spans[0].0; + for &(begin, end) in &spans { + summed += us(end - begin); + if begin > reached { + let gap = us(begin - reached); + let class = match gap { + 0..100 => 0, + 100..2_000 => 1, + 2_000..20_000 => 2, + _ => 3, + }; + gaps[class].0 += 1; + gaps[class].1 += gap; + reached = begin; + } + if end > reached { + running += us(end - reached); + reached = end; + } + } + let ms = |us: u64| us as f64 / 1e3 / frames; + // The clamps of indirect commands, from the sample ([`clamp_begin`]): + // before its first barrier to after its second, which holds the card's + // waits for every earlier shader write on both sides of the clamp. + let (timed, timed_us) = std::mem::take(&mut m.clamps); + let all = CLAMPS_ALL.swap(0, std::sync::atomic::Ordering::Relaxed); + if timed > 0 { + let each = timed_us as f64 / timed as f64; + tracing::info!( + "the clamps of indirect commands per frame (one in {} timed, VICTORY_CARD_METER_CLAMPS): {:.0} clamps, {:.0} timed, \ + {:.1} us each from before the first barrier to after the second, so about {:.1} ms a frame for all of them", + clamp_every(), + all as f64 / frames, + timed as f64 / frames, + each, + each * all as f64 / 1e3 / frames + ); + } + tracing::info!( + "the card per frame ({frames:.0} frames, the direct queue by its own clock): a list of ours running {:.1} ms (the lists' \ + stamps add to {:.1} ms; {:.0} lists); no list running between one list's end and the next one's begin: {:.1} ms in \ + {:.0} gaps under 0.1 ms, {:.1} ms in {:.0} gaps of 0.1 to 2 ms, {:.1} ms in {:.0} gaps of 2 to 20 ms, {:.1} ms in \ + {:.0} gaps over 20 ms (of the gaps' time, the frame line's \"card: idle\" had nothing of ours queued; the rest is the \ + card standing with work of ours queued)", + ms(running), + ms(summed), + spans.len() as f64 / frames, + ms(gaps[0].1), + gaps[0].0 as f64 / frames, + ms(gaps[1].1), + gaps[1].0 as f64 / frames, + ms(gaps[2].1), + gaps[2].0 as f64 / frames, + ms(gaps[3].1), + gaps[3].0 as f64 / frames, + ); +} + +/// The pairs recorded long enough ago are read and added to the frame +/// log's totals. Called once a frame. +pub(crate) fn collect() { + if !on() { + return; + } + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(m)) = meter.as_mut() else { + return; + }; + let now = std::time::Instant::now(); + while let Some(&(pair, kind, at)) = m.pending.front() { + if now.duration_since(at) < AFTER { + break; + } + m.pending.pop_front(); + // SAFETY: the pair's sixteen bytes of the mapped read-back buffer; + // the card wrote them long ago or never. + let (begin, end) = unsafe { + let p = (m.mapped as *const u64).add(pair as usize * 2); + (p.read_volatile(), p.add(1).read_volatile()) + }; + if std::mem::replace(&mut m.seen[pair as usize], (begin, end)) == (begin, end) { + continue; + } + let us = micros(begin, end, m.frequency); + // A whole list (not a pipeline's stretch inside one), run by the + // card: for the gaps between lists. + if !matches!(kind, Kind::Pipeline | Kind::Clamp) && begin != 0 && end > begin { + m.spans.push((begin, end)); + } + use crate::framelog::{T, add}; + match kind { + Kind::Sync => { + add(T::CardSyncUs, us); + add(T::CardSyncLists, 1); + m.kinds[1].0 += 1; + m.kinds[1].1 += us; + } + Kind::Check => { + add(T::CardCheckUs, us); + add(T::CardCheckLists, 1); + m.kinds[2].0 += 1; + m.kinds[2].1 += us; + } + Kind::Lists => { + add(T::CardListsUs, us); + add(T::CardLists, 1); + m.kinds[0].0 += 1; + m.kinds[0].1 += us; + if let Some(name) = m.names.remove(&pair) { + let e = m.by_name.entry(name).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } + } + Kind::Pipeline => { + if let Some(name) = m.names.remove(&pair) { + let e = m.by_pipeline.entry(name).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } + } + Kind::Clamp => { + // A pair the card wrote (a list that ran): counted. + if us > 0 { + m.clamps.0 += 1; + m.clamps.1 += us; + } + } + } + } + m.gap_frames += 1; + if now.duration_since(m.gap_line) >= std::time::Duration::from_secs(5) { + gaps_line(m); + m.gap_line = now; + } + m.frames += 1; + if m.frames >= 256 || (m.frames >= 16 && now.duration_since(m.table_at) >= std::time::Duration::from_secs(60)) { + m.table_at = now; + let frames = m.frames as f64; + let mut table: Vec<(String, (u64, u64))> = m.by_name.drain().collect(); + table.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + let all: u64 = table.iter().map(|&(_, (_, us))| us).sum(); + tracing::info!( + "card time of the title's lists by what they bind, per frame over {} frames: {:.1} ms in {:.0} lists of {} kinds; the largest follow", + m.frames, + all as f64 / 1e3 / frames, + table.iter().map(|&(_, (n, _))| n).sum::<u64>() as f64 / frames, + table.len() + ); + for (name, (n, us)) in table.into_iter().take(24) { + tracing::info!(" card {:6.2} ms a frame in {:5.1} lists: {name}", us as f64 / 1e3 / frames, n as f64 / frames); + } + if !m.by_pipeline.is_empty() { + let mut table: Vec<(String, (u64, u64))> = m.by_pipeline.drain().collect(); + table.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + let all: u64 = table.iter().map(|&(_, (_, us))| us).sum(); + tracing::info!( + "card time by pipeline (from where it is bound to where the next is), per frame over {} frames: {:.1} ms in {:.0} bindings of {} pipelines; the largest follow", + m.frames, + all as f64 / 1e3 / frames, + table.iter().map(|&(_, (n, _))| n).sum::<u64>() as f64 / frames, + table.len() + ); + for (name, (n, us)) in table.into_iter().take(48) { + tracing::info!( + " pipeline {:6.2} ms a frame in {:6.1} bindings ({:7.1} us each): {name}", + us as f64 / 1e3 / frames, + n as f64 / frames, + us as f64 / n.max(1) as f64 + ); + } + } + m.frames = 0; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_list_is_named_by_the_pipelines_it_binds() { + let mut names = std::collections::BTreeSet::new(); + assert_eq!(name_of(&names), "no pipeline (copies, clears, barriers)"); + names.insert("compute CS_Blur".to_string()); + assert_eq!(name_of(&names), "1 pipeline: compute CS_Blur"); + names.insert("mesh VS_A, pixel PS_B".to_string()); + names.insert("a".repeat(100)); + assert_eq!(name_of(&names), format!("3 pipelines: {} / compute CS_Blur", "a".repeat(60))); + } + + #[test] + fn a_pairs_length_is_in_microseconds_of_the_queues_clock() { + assert_eq!(micros(1_000, 11_000, 10_000_000), 1_000); + assert_eq!(micros(0, 25_000_000, 25_000_000), 1_000_000); + // Not written, or the wrong way round: nothing. + assert_eq!(micros(5, 5, 1_000), 0); + assert_eq!(micros(9, 5, 1_000), 0); + assert_eq!(micros(1, 2, 0), 0); + // A stale second stamp from the ring's last round cannot add hours. + assert_eq!(micros(1, u64::MAX, 1), 10_000_000); + } +} diff --git a/crates/victory-gpu/src/console.rs b/crates/victory-gpu/src/console.rs index 6070d2d67f..79196cf27b 100644 --- a/crates/victory-gpu/src/console.rs +++ b/crates/victory-gpu/src/console.rs @@ -17,7 +17,7 @@ impl Console { /// advanced configuration; Series S has one range, counted as standard /// (7,776 MiB, the published console-mode figure). // shortcut: later system updates gave Series S titles more (amount not - // published here); Grand Theft Auto VI sizes nothing from this figure + // published here); the title sizes nothing from this figure // (it goes by the device type), so update it if a title does. pub const fn title_memory(self) -> (usize, usize) { match self { @@ -41,6 +41,121 @@ pub fn set(console: Console) { SERIES_S.store(console == Console::SeriesS, Ordering::Relaxed); } +/// The adapter the host device is made on (Try 6.0): the one Windows ranks +/// fastest (`EnumAdapterByGpuPreference`, high performance), not the first +/// one. On a laptop with the CPU's own graphics and an NVIDIA card the +/// first adapter can be the CPU's graphics (it drives the screen), and +/// `D3D12CreateDevice` with no adapter then made the device there unless +/// the NVIDIA control panel said otherwise. `VICTORY_ADAPTER=first`: the +/// first adapter, as before. `None`: let `D3D12CreateDevice` pick. +#[cfg(windows)] +pub(crate) fn fast_adapter() -> Option<windows::Win32::Graphics::Dxgi::IDXGIAdapter1> { + use windows::Win32::Graphics::Dxgi::*; + if std::env::var_os("VICTORY_ADAPTER").is_some_and(|v| v == "first") { + return None; + } + // SAFETY: plain DXGI queries; nothing is created on the card. + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter1 = factory.EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE).ok()?; + let desc = adapter.GetDesc1().ok()?; + (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0).then_some(adapter) + } +} + +/// Every hardware adapter, said once in the log: name, vendor, its own +/// memory and the PC memory it may share, and whether it looks like the +/// CPU's own graphics (little memory of its own). The one the device is +/// made on is [`fast_adapter`]; the others are named so a report shows +/// what the PC has. +#[cfg(windows)] +pub(crate) fn log_adapters() { + use windows::Win32::Graphics::Dxgi::*; + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + // SAFETY: plain DXGI queries. + unsafe { + let Ok(factory) = CreateDXGIFactory1::<IDXGIFactory1>() else { + return; + }; + for i in 0..8 { + let Ok(adapter) = factory.EnumAdapters1(i) else { + break; + }; + let Ok(desc) = adapter.GetDesc1() else { + continue; + }; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + continue; + } + let end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + let name = String::from_utf16_lossy(&desc.Description[..end]); + let own_mb = desc.DedicatedVideoMemory as u64 >> 20; + tracing::info!( + index = i, + name = name.as_str(), + vendor = format_args!("{:#x}", desc.VendorId), + own_mb, + shared_mb = desc.SharedSystemMemory as u64 >> 20, + integrated = own_mb < 1024, + "graphics adapter" + ); + } + } + }); +} + +/// The dedicated memory of the card the host device is made on +/// ([`fast_adapter`], or else the first hardware adapter, as +/// `D3D12CreateDevice` with no adapter picks it), in MiB; `None` if DXGI +/// will not say. +#[cfg(windows)] +pub fn card_memory_mb() -> Option<u64> { + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, DXGI_ADAPTER_FLAG_SOFTWARE, IDXGIFactory1}; + if let Some(adapter) = fast_adapter() + // SAFETY: a plain query that fills a structure. + && let Ok(desc) = unsafe { adapter.GetDesc1() } + { + return Some(desc.DedicatedVideoMemory as u64 >> 20); + } + // SAFETY: plain DXGI queries; nothing is created on the card. + unsafe { + let factory: IDXGIFactory1 = CreateDXGIFactory1().ok()?; + for i in 0..8 { + let adapter = factory.EnumAdapters1(i).ok()?; + let desc = adapter.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return Some(desc.DedicatedVideoMemory as u64 >> 20); + } + } + } + None +} + +#[cfg(not(windows))] +pub fn card_memory_mb() -> Option<u64> { + None +} + +/// The console to run as when Series X was asked for: Series S on a card +/// with 9 GiB of its own memory or less (6 and 8 GB cards), unless +/// `VICTORY_CONSOLE_AUTO=0`. Series X's render targets and memory took +/// 2.3 to 3 GB more of such a card than it has to give, and every texture +/// that did not fit then drew black (2026-11-25 and 11-26 reports: the +/// card at 5.8 GB of a 5.2 GB budget, 22,000 textures waiting). Series S +/// renders at a smaller size and the title asks for less memory. The +/// launcher's own switch to Series S never reached a running launcher that +/// had updated itself, so it is made here. +pub fn auto(asked: Console) -> (Console, Option<u64>) { + if asked != Console::SeriesX || std::env::var_os("VICTORY_CONSOLE_AUTO").is_some_and(|v| v == "0") { + return (asked, None); + } + match card_memory_mb() { + Some(mb) if mb > 0 && mb <= 9 * 1024 => (Console::SeriesS, Some(mb)), + _ => (asked, None), + } +} + pub fn current() -> Console { if SERIES_S.load(Ordering::Relaxed) { Console::SeriesS diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 0d71d3f816..e069703df2 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -37,8 +37,129 @@ pub(crate) enum C { TexWatched, TexHashed, TexChanged, + /// Frames presented since the last line (what the line divides by). + Frames, + /// Calls of list methods that record into a host list, and the + /// nanoseconds they took, summed over the title's recording threads. + RecordCalls, + RecordNs, + /// Waiting for host pipelines being made (`pipeline::make`). + PipelineWaitUs, + /// Dynamic descriptor slots: tables asked for, refused (no free run), + /// and the nanoseconds of the searches. + DynamicAsked, + DynamicRefused, + DynamicNs, + /// Marker texts for device-removed data (`HostList::note`). + NoteNs, + /// Ranges given to shaders (steps), their snapshots, and the bytes + /// compared after the submission. + GpuWrites, + SnapshotUs, + BackCompared, + /// Reading around unmapped pages after a failed bulk read. + SparseUs, + /// Guarding view memory (part of the write-watch askings' time). + GuardUs, + /// Bytes copied whole because their memory is neither write-watched + /// nor a view (`Shadow::update_free`). + WholeBytes, + /// Submissions with ranges shaders write (they need the GPU's results + /// before they return). + BackSubmissions, + /// The title's frame waits (`frame::wait`) and the time slept in them, + /// over all its threads. + PaceWaits, + PaceUs, + /// After a present: until the title's first list call and until its + /// first submission; and from its last submission to its next present. + UntilRecordUs, + UntilSubmitUs, + TailUs, + /// Resetting host lists (`HostList::reset`). + ResetNs, + /// What shaders wrote: finding the 64 KiB pieces that differ, how many + /// do, and putting them into title memory. + BackScanUs, + BackDiffer, + BackSyncUs, + /// Texture uploads recorded, and left out as unchanged. + TexUploads, + TexSkipped, + /// Held submissions a present ran although their waits were not met. + Forced, + /// Ranges named through unordered access views by shaders that cannot + /// store to buffers, not given to shaders as written, and their bytes. + GpuWritesLeftOut, + GpuWritesLeftOutBytes, + /// Waits for memory values looked at (`list::ValueWait::met`) and the + /// nanoseconds the looks took, on every thread. + WaitChecks, + WaitCheckNs, + /// Host lists made (`Host::new_list`: for the lists a queue holds and + /// for the parts of lists cut at waits) and the nanoseconds that took. + HostLists, + HostListNs, + /// Parts of held submissions that ran while the part behind them could + /// have run with them (its waits were met already). + PartsTogether, + /// Microseconds of the copies counted in `WholeBytes`. + WholeUs, + /// Submissions by how long the card was waited for (under 2 ms, 2-8, + /// 8-32, longer), and the microseconds waited in each class. + CardUnder2, + Card2To8, + Card8To32, + CardOver32, + CardUnder2Us, + Card2To8Us, + Card8To32Us, + CardOver32Us, + /// Submissions that hand nothing back to the title (no range shaders + /// write, no value written when done), and the microseconds the card + /// was waited for them. + NothingBack, + NothingBackUs, + /// Waits for every earlier shader write recorded into host lists: for + /// the title's barrier groups, for its barriers on buffers, and the + /// indirect commands bounded (each a dispatch of ours between two such + /// waits). + WaitsForGroups, + WaitsForBuffers, + IndirectBounded, + /// `watch::writes` kernel askings that failed (the range is not + /// write-watched: view memory or not watchable). + WatchFailed, + /// `watch::writes` askings not made because the range's first block is + /// already known to be guarded view memory (no kernel call). + WatchKnownView, + /// Microseconds of the `watch::writes` askings whose kernel call failed + /// and fell to the guards: the failed call, the look at what the + /// memory is, the guards' walk. + WatchFailedUs, + /// Microseconds of the askings answered by the guards with no kernel + /// call (`WatchKnownView`). + WatchKnownUs, + /// Refreshes of a watched host copy's range (`Shadow::update_free`) + /// that copied nothing, and their microseconds (the asking included). + RefreshNone, + RefreshNoneUs, + /// The ones that copied something, and their microseconds. + RefreshSome, + RefreshSomeUs, + /// With `VICTORY_REFRESH_COUNT=1`: of the refreshes that copied + /// nothing, those known unchanged before asking + /// (`crate::watch::unchanged_known`), and their microseconds: what a + /// skip of them would take off at most. + RefreshKnown, + RefreshKnownUs, + /// Refreshes skipped as known unchanged (`VICTORY_REGION_SKIP`). + RefreshSkipped, } -const COUNTERS: usize = 22; +/// One slot per counter: follows the enum (a fixed 80 was outrun by the +/// refresh counters and ended run 324 with an index past the end). +const COUNTERS: usize = C::RefreshSkipped as usize + 1; +const _: () = assert!(COUNTERS <= 256, "the counters' array stays small"); static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; pub(crate) fn add(c: C, n: u64) { @@ -59,6 +180,112 @@ pub(crate) fn mode() -> u8 { type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>; static RANGES: Mutex<Option<Ranges>> = Mutex::new(None); +/// Per range copied whole because its memory is not watched (start, +/// length): copies and microseconds. +static WHOLE: Mutex<Option<HashMap<(usize, usize), (u64, u64)>>> = Mutex::new(None); + +/// `len` bytes at `src`, memory that is not watched, were copied whole in +/// `us`. +pub(crate) fn whole(src: usize, len: usize, us: u64) { + add(C::WholeUs, us); + let mut map = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); + e.0 += 1; + e.1 += us; +} + +/// The longest wait for the card since the last line: microseconds, and +/// what ran (lists and pipelines). +static LONGEST: Mutex<(u64, String)> = Mutex::new((0, String::new())); + +/// The waits for the card since the last line by what ran (lists and +/// pipelines): how many, and their microseconds. +static WAITS_BY_WORK: Mutex<Option<HashMap<String, (u64, u64)>>> = Mutex::new(None); + +/// With `VICTORY_GPU_TIMING`: the commands' time on the card since the last +/// line by what they ran (a pipeline, or the kind of command): how many, +/// their microseconds, and the longest one's. +static COMMANDS_BY_WORK: Mutex<Option<HashMap<String, (u64, u64, u64)>>> = Mutex::new(None); + +/// A command took `ms` on the card (timing run). `op` is its note: the +/// kind and size first, then the pipeline in brackets, then what it binds. +pub(crate) fn command_took(op: &str, ms: f64) { + let us = (ms * 1e3) as u64; + let mut by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let e = by.get_or_insert_with(HashMap::new).entry(command_key(op)).or_insert((0, 0, 0)); + e.0 += 1; + e.1 += us; + e.2 = e.2.max(us); +} + +/// What a command's note is summed under: its pipeline (`[compute ...]`, +/// `[mesh ..., pixel ...]`) with the command's first word, or without a +/// pipeline its first two words. +fn command_key(op: &str) -> String { + let head = op.split(" | ").next().unwrap_or(op); + let word = head.split(' ').next().unwrap_or(""); + match (head.find('['), head.find(']')) { + (Some(a), Some(b)) if a < b => format!("{word} {}", &head[a..=b]), + _ => head.split(' ').take(2).collect::<Vec<_>>().join(" "), + } +} + +/// The card was waited for `us` for a submission; `what` names it if it is +/// the longest since the last line. +pub(crate) fn card_waited(us: u64, what: impl FnOnce() -> String) { + let (n, t) = match us { + 0..2_000 => (C::CardUnder2, C::CardUnder2Us), + 2_000..8_000 => (C::Card2To8, C::Card2To8Us), + 8_000..32_000 => (C::Card8To32, C::Card8To32Us), + _ => (C::CardOver32, C::CardOver32Us), + }; + add(n, 1); + add(t, us); + // Every submission is named (some forty a frame): the same lists run + // every frame, and the eight longest waits of a line were one list + // eight times. + let text = what(); + { + let mut by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let e = by.get_or_insert_with(HashMap::new).entry(text.clone()).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } + let mut longest = LONGEST.lock().unwrap_or_else(|e| e.into_inner()); + if us > longest.0 { + *longest = (us, text); + } +} + +/// Whether an experiment on barriers is on (`VICTORY_BARRIER_TEST`): bit 0 +/// for `groups` (the title's barrier groups record no wait for earlier +/// shader writes), bit 1 for `indirect` (the pass that bounds an indirect +/// command runs without its two such waits; its state changes stay), both +/// bits for `both`. For timing only: without the waits a shader may read +/// what another has not finished writing. +pub(crate) fn barrier_test() -> u8 { + static TEST: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *TEST.get_or_init(|| match std::env::var("VICTORY_BARRIER_TEST").as_deref() { + Ok("groups") => 1, + Ok("indirect") => 2, + Ok("both") => 3, + _ => 0, + }) +} + +/// Per range compared after a submission (start, length): times, and the +/// bytes of it written back to the title. +static COMPARED: Mutex<Option<HashMap<(usize, usize), (u64, u64)>>> = Mutex::new(None); + +/// `len` bytes at `src` were compared after a submission and `written` of +/// them put back into title memory. +pub(crate) fn compared(src: usize, len: usize, written: usize) { + let mut map = COMPARED.lock().unwrap_or_else(|e| e.into_inner()); + let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); + e.0 += 1; + e.1 += written as u64; +} + /// A copy of `len` bytes from `src` (memory type `kind`) took `us`. pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner()); @@ -71,57 +298,850 @@ pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { e.2 += us; } -/// A process-wide memory snapshot for the diagnostics line. PrivateUsage -/// is the process commit charge; WorkingSetSize is the resident physical set. -#[derive(Clone, Copy)] -struct ProcessMemory { - page_faults: u64, - private_usage: u64, - working_set: u64, +/// Our own allocations alive now, by size of block (under 4 KiB, to 64 KiB, +/// to 1 MiB, larger): bytes, then blocks. "Our own" is the Rust code of +/// every crate in the process: in diagnostics builds [`Counting`] stands in +/// front of the system's heap. The memory map's "process heap segments" +/// hold the blocks under about half a megabyte of ours, of the graphics +/// runtime and of the driver alike (3.5 GB in run 60's gameplay, growing by +/// some 2 MB a frame, and nothing said whose): this says which part is +/// ours. Bigger blocks are allocations of their own in the map. +static OWN: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// The class of [`OWN`] a block of `size` bytes counts in. +fn block_class(size: usize) -> usize { + match size { + 0..0x1000 => 0, + 0x1000..0x1_0000 => 1, + 0x1_0000..0x10_0000 => 2, + _ => 3, + } +} + +fn own(size: usize, made: bool) { + let class = block_class(size); + if made { + OWN[class].fetch_add(size as u64, Relaxed); + OWN[4 + class].fetch_add(1, Relaxed); + } else { + OWN[class].fetch_sub(size as u64, Relaxed); + OWN[4 + class].fetch_sub(1, Relaxed); + } +} + +/// Our own blocks of [`BIG`] bytes and more alive now: where each is (0: +/// none) and its bytes. The memory map lists the process's big allocations +/// by size without saying whose they are (run 65: one of 544 MB, one of +/// 401 MB, two of 174 MB, two of 115 MB); the sizes here say which of them +/// are ours. +static BIG_AT: [std::sync::atomic::AtomicUsize; 64] = [const { std::sync::atomic::AtomicUsize::new(0) }; 64]; +static BIG_BYTES: [AtomicU64; 64] = [const { AtomicU64::new(0) }; 64]; +const BIG: usize = 32 << 20; + +/// A block of [`BIG`] bytes or more was made at `at`, or released there. +fn big(at: *mut u8, size: usize, made: bool) { + if size < BIG { + return; + } + for (place, bytes) in BIG_AT.iter().zip(&BIG_BYTES) { + if made { + if place.compare_exchange(0, at as usize, Relaxed, Relaxed).is_ok() { + bytes.store(size as u64, Relaxed); + return; + } + } else if place.load(Relaxed) == at as usize { + bytes.store(0, Relaxed); + place.store(0, Relaxed); + return; + } + } +} + +/// The sizes of our own big blocks alive, largest first, in MB. +fn big_blocks() -> String { + let mut sizes: Vec<u64> = BIG_BYTES.iter().map(|b| b.load(Relaxed)).filter(|&b| b != 0).collect(); + sizes.sort_unstable_by(|a, b| b.cmp(a)); + let text: Vec<String> = sizes.iter().map(|b| format!("{:.2}", *b as f64 / (1 << 20) as f64)).collect(); + if text.is_empty() { "none".into() } else { text.join(", ") } } -fn process_memory() -> Option<ProcessMemory> { +/// The system's allocator with every block counted in [`OWN`] (two atomic +/// additions per allocation and per release: diagnostics builds only). +struct Counting; + +// SAFETY: every call goes to the system's allocator unchanged; only +// counters are kept beside it. +unsafe impl std::alloc::GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let at = unsafe { std::alloc::System.alloc(layout) }; + if !at.is_null() { + own(layout.size(), true); + big(at, layout.size(), true); + } + at + } + + unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let at = unsafe { std::alloc::System.alloc_zeroed(layout) }; + if !at.is_null() { + own(layout.size(), true); + big(at, layout.size(), true); + } + at + } + + unsafe fn dealloc(&self, at: *mut u8, layout: std::alloc::Layout) { + own(layout.size(), false); + big(at, layout.size(), false); + // SAFETY: the caller's contract, passed on. + unsafe { std::alloc::System.dealloc(at, layout) }; + } + + unsafe fn realloc(&self, at: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let moved = unsafe { std::alloc::System.realloc(at, layout, size) }; + if !moved.is_null() { + own(layout.size(), false); + own(size, true); + big(at, layout.size(), false); + big(moved, size, true); + } + moved + } +} + +#[global_allocator] +static HEAP: Counting = Counting; + +#[cfg(test)] +mod command_tests { + /// Commands are summed by pipeline and first word; those without a + /// pipeline by their first two words. + #[test] + fn commands_are_named_by_their_pipeline() { + use super::command_key; + assert_eq!( + command_key("dispatch 182x1x1 [compute 24f989b98dcb03f0] | 24f989b98dcb03f0: u4=0xa6b080 [heap 341380: x]"), + "dispatch [compute 24f989b98dcb03f0]" + ); + assert_eq!( + command_key("indirect kind 10 max 1 at 0xd9358fce0 [mesh 0750cb2d975c7563, pixel 085d374c5a795549] | t"), + "indirect [mesh 0750cb2d975c7563, pixel 085d374c5a795549]" + ); + assert_eq!(command_key("texture upload 0x271b61c28b0 (2048x2048x1 f99 mips 10) sub 0"), "texture upload"); + assert_eq!(command_key("alias copy of 0x26f66aca780 into 0x26fbdc93890"), "alias copy"); + } +} + +#[cfg(test)] +mod counter_tests { + /// Every counter has a slot: the last one too (run 324 ended with an + /// index past the end of a fixed-size array). + #[test] + fn the_last_counter_has_a_slot() { + use super::{C, COUNT, add}; + use std::sync::atomic::Ordering::Relaxed; + let before = COUNT[C::RefreshSkipped as usize].load(Relaxed); + add(C::RefreshSkipped, 1); + add(C::RefreshKnownUs, 0); + assert!(COUNT[C::RefreshSkipped as usize].load(Relaxed) > before); + } +} + +#[cfg(test)] +mod own_tests { + use super::{OWN, block_class}; + use std::sync::atomic::Ordering::Relaxed; + + #[test] + fn blocks_count_in_their_size_class() { + assert_eq!(block_class(0), 0); + assert_eq!(block_class(4095), 0); + assert_eq!(block_class(4096), 1); + assert_eq!(block_class(65535), 1); + assert_eq!(block_class(65536), 2); + assert_eq!(block_class((1 << 20) - 1), 2); + assert_eq!(block_class(1 << 20), 3); + } + + /// A block of 32 MiB or more is listed by its size while it lives. + #[test] + fn big_blocks_are_listed_while_they_live() { + let size = (48usize << 20) + 4096; + let listed = |at: usize| { + super::BIG_AT + .iter() + .zip(&super::BIG_BYTES) + .any(|(place, bytes)| place.load(Relaxed) == at && bytes.load(Relaxed) == size as u64) + }; + let block = vec![0u8; size]; + let at = block.as_ptr() as usize; + assert!(listed(at)); + assert!(super::big_blocks().contains("48.00")); + drop(block); + assert!(!listed(at)); + } + + /// A big block shows in the counters while it lives (other tests + /// allocate small blocks meanwhile: only the big class is looked at, + /// and only for at least this block). + #[test] + fn a_block_is_counted_while_it_lives() { + let block = vec![1u8; 8 << 20]; + assert!(OWN[3].load(Relaxed) >= 8 << 20); + assert!(OWN[7].load(Relaxed) >= 1); + drop(block); + assert!(OWN[7].load(Relaxed) < u64::MAX / 2, "no count below zero"); + } +} + +/// The process's memory in bytes: in physical memory, and committed +/// (private bytes). +fn process_memory() -> (u64, u64) { use windows_sys::Win32::System::ProcessStatus::{ - K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX, + K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, }; use windows_sys::Win32::System::Threading::GetCurrentProcess; - - let mut counters = PROCESS_MEMORY_COUNTERS_EX { - cb: size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32, + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, ..Default::default() }; - // The Win32 API accepts the base structure pointer, but uses cb to read - // the extended structure and fill PrivateUsage as well. - // SAFETY: our own process and a correctly sized extended structure. + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + (c.WorkingSetSize as u64, c.PagefileUsage as u64) +} + +/// The PC's memory in bytes: physical memory free, and what is left to +/// commit. +fn system_memory() -> (u64, u64) { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = size_of::<MEMORYSTATUSEX>() as u32; + // SAFETY: a sized structure. + unsafe { GlobalMemoryStatusEx(&mut m) }; + (m.ullAvailPhys, m.ullAvailPageFile) +} + +/// Whether the address space is walked for the memory map line +/// ([`log_memory_map`]). On by default (this module is in diagnostics +/// builds only); `VICTORY_MEMORY_MAP=0` leaves the walk out. +fn memory_map() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MEMORY_MAP").is_none_or(|v| v != "0")) +} + +/// Asks which of the pages in `asked` (address, answer) are in physical +/// memory and adds the bytes each stands for (kind, bytes) to its kind. +fn in_memory(asked: &mut Vec<[usize; 2]>, stands: &mut Vec<(usize, u64)>, present: &mut [u64; 10]) { + use windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: our own process; `asked` holds that many entries of two + // words each, as the call fills them in. let ok = unsafe { - K32GetProcessMemoryInfo( - GetCurrentProcess(), - (&mut counters as *mut PROCESS_MEMORY_COUNTERS_EX).cast::<PROCESS_MEMORY_COUNTERS>(), - counters.cb, - ) + K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32) + } != 0; + if ok { + for (a, &(kind, bytes)) in asked.iter().zip(stands.iter()) { + // Bit 0 of the answer: the page is in the process's memory. + if a[1] & 1 != 0 { + present[kind] += bytes; + } + } + } + asked.clear(); + stands.clear(); +} + +/// Logs what the process has committed by kind, from a walk of its address +/// space, and how much of each kind is in physical memory (one page in +/// sixteen is asked about). The kinds tell the title's own memory from +/// ours: the title's heaps and page views lie at console addresses (below +/// 1 TiB), everything the host allocates lies far above. Run 30, seen +/// from outside at 18.0 GB private: 4.6 GB the title's heaps, 2.6 GB in +/// 162 segments of the process heap, 2.7 GB in 707 allocations of 4 MiB +/// (windows of title memory), 0.46 GB the pipeline library's file; mapped +/// and so not private: 6.2 GB the title's page pool, 2.0 GB the driver's +/// shader cache file. +/// shortcut: the walk takes about 0.6 s on a thread of its own, and a +/// query of a region of gigabytes holds up other threads' memory calls +/// for its length (89 ms for the 6.2 GB pool), so it runs with every +/// sixth memory line only. +fn log_memory_map() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_WRITECOMBINE, + VirtualQuery, + }; + const KINDS: [&str; 10] = [ + "the title's heaps (private, console addresses)", + "views of the title's pages (mapped, console addresses)", + "the title's page pool (mapped, 1 GB and more)", + "process heap segments (private, 15.8 MB each)", + "windows of title memory and other 4 MiB allocations", + "write-combined (buffers shared with the card)", + "other private allocations of 1 MB and more", + "other private allocations under 1 MB", + "files and other mappings at host addresses", + "programs and libraries", + ]; + /// Console addresses lie below this. + const HOST: usize = 1 << 40; + /// One page asked about stands for this much. + const STEP: usize = 64 << 10; + let started = std::time::Instant::now(); + // Allocation, start, bytes, committed, type, protection. + type Region = (usize, usize, usize, bool, u32, u32); + let mut regions: Vec<Region> = Vec::new(); + let mut at = 0usize; + loop { + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + if unsafe { VirtualQuery(at as *const _, &mut m, size_of_val(&m)) } == 0 { + break; + } + if m.State != MEM_FREE { + regions.push(( + m.AllocationBase as usize, + m.BaseAddress as usize, + m.RegionSize, + m.State == MEM_COMMIT, + m.Type, + m.Protect, + )); + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize); + if next <= at { + break; + } + at = next; + } + // Each allocation's whole size, reserved parts included. + let mut whole: HashMap<usize, usize> = HashMap::new(); + for r in ®ions { + *whole.entry(r.0).or_default() += r.2; + } + let kind = |r: &Region| -> usize { + let size = whole.get(&r.0).copied().unwrap_or(0); + let console = r.0 < HOST; + if r.4 == MEM_IMAGE { + 9 + } else if r.4 == MEM_MAPPED { + match (console, size >= 1 << 30) { + (false, _) => 8, + (true, true) => 2, + (true, false) => 1, + } + } else if console { + 0 + } else if size == 0xfd_0000 { + 3 + } else if size == 4 << 20 { + 4 + } else if r.5 & PAGE_WRITECOMBINE != 0 { + 5 + } else if size >= 1 << 20 { + 6 + } else { + 7 + } }; - if ok == 0 { - return None; + let mut committed = [0u64; 10]; + let mut present = [0u64; 10]; + let mut asked: Vec<[usize; 2]> = Vec::with_capacity(4096); + let mut stands: Vec<(usize, u64)> = Vec::with_capacity(4096); + for r in regions.iter().filter(|r| r.3) { + let k = kind(r); + committed[k] += r.2 as u64; + let mut offset = 0; + while offset < r.2 { + asked.push([r.1 + offset, 0]); + stands.push((k, STEP.min(r.2 - offset) as u64)); + if asked.len() == 4096 { + in_memory(&mut asked, &mut stands, &mut present); + } + offset += STEP; + } + } + if !asked.is_empty() { + in_memory(&mut asked, &mut stands, &mut present); + } + let text: Vec<String> = (0..KINDS.len()) + .filter(|&k| committed[k] > 0) + .map(|k| format!("{} {} MB ({} MB in memory)", KINDS[k], committed[k] >> 20, present[k] >> 20)) + .collect(); + tracing::info!( + "memory map ({} regions, {} ms): {}", + regions.len(), + started.elapsed().as_millis(), + text.join("; ") + ); + // The private allocations the kinds above leave as "other" (and the + // write-combined ones), grouped by their size: the sizes name their + // owners (the pipeline library's file to the byte, a snapshot buffer + // of a title heap's size, the driver's blocks). Committed bytes by + // allocation first, then allocations by (kind, whole size). + let mut by_allocation: HashMap<usize, (usize, u64)> = HashMap::new(); + for r in regions.iter().filter(|r| r.3) { + let k = kind(r); + if k == 5 || k == 6 { + by_allocation.entry(r.0).or_insert((k, 0)).1 += r.2 as u64; + } + } + let mut groups: HashMap<(usize, usize), (u64, u64)> = HashMap::new(); + for (base, &(k, bytes)) in &by_allocation { + let group = groups.entry((k, whole.get(base).copied().unwrap_or(0))).or_default(); + group.0 += 1; + group.1 += bytes; } + let mut groups: Vec<((usize, usize), (u64, u64))> = groups.into_iter().collect(); + groups.sort_by_key(|g| std::cmp::Reverse(g.1.1)); + let biggest: Vec<String> = groups + .iter() + .take(20) + .map(|&((k, size), (n, bytes))| { + format!( + "{n} of {:.2} MB{}: {} MB", + size as f64 / (1 << 20) as f64, + if k == 5 { " write-combined" } else { "" }, + bytes >> 20 + ) + }) + .collect(); + tracing::info!( + "memory map, other private allocations by size, the {} biggest groups of {} (committed): {}", + biggest.len(), + groups.len(), + biggest.join("; ") + ); +} - Some(ProcessMemory { - page_faults: u64::from(counters.PageFaultCount), - private_usage: counters.PrivateUsage as u64, - working_set: counters.WorkingSetSize as u64, - }) +/// Logs where the memory is: the process and the PC, then what this crate +/// holds by kind (alive now), then the host buffers made since the start. +fn log_memory() { + use std::sync::atomic::Ordering::Relaxed; + let mb = |v: u64| v as f64 / (1 << 20) as f64; + let (working, private) = process_memory(); + let (free, left) = system_memory(); + let copies = crate::shadow::memory(); + let staged = crate::texture::memory(); + let textures = [0, 1].map(|i| crate::resource::HOST_TEXTURES[i].load(Relaxed)); + let made: Vec<u64> = crate::host::MADE.iter().map(|m| m.load(Relaxed)).collect(); + let windows = crate::shadow::windows(); + let stagings = crate::texture::let_go(); + let census = crate::resource::census(); + let kinds: Vec<u64> = crate::resource::KINDS.iter().map(|k| k.load(Relaxed)).collect(); + let card = crate::host::host() + .and_then(|h| h.video_memory()) + .unwrap_or_default(); + // Everything the system says of the two memory groups, beside the + // budget and use the lines below print. + if let Some(h) = crate::host::host() { + h.log_video_memory("with the memory line"); + } + // What else holds memory: the map, on a thread of its own, with every + // sixth line; and what the shader table and the pipeline library keep. + static LINES: AtomicU64 = AtomicU64::new(0); + static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if memory_map() && LINES.fetch_add(1, Relaxed) % 6 == 5 && !WALKING.swap(true, Relaxed) { + let walk = std::thread::Builder::new().name("victory-memory-map".into()).spawn(|| { + log_memory_map(); + WALKING.store(false, Relaxed); + }); + if walk.is_err() { + WALKING.store(false, Relaxed); + } + } + let kept = crate::pipeline::kept(); + tracing::info!( + "memory kept beside the lines below: {} shader containers {:.0} MB, {} translations \ + {:.0} MB; the pipeline library's file {:.0} MB (its last save wrote {:.0} MB)", + kept[0], + mb(kept[1]), + kept[2], + mb(kept[3]), + mb(kept[4]), + mb(kept[5]), + ); + tracing::info!( + "memory of textures: {} title textures have no host copy yet ({:.0} MB of title memory); \ + host copies the host renders to or writes: {} alive {:.0} MB; host copies the title \ + fills: {} alive {:.0} MB ({} of them placed), {} let go {:.0} MB and {} made again \ + {:.0} MB since the start; {} host copies made in all; passes that made none for lack of \ + room: {}; the card: {:.0} MB in use of a budget of {:.0} MB, {:.0} MB of the PC's memory \ + shared with it in use", + census[2], + mb(census[3]), + census[0], + mb(census[1]), + census[4], + mb(census[5]), + census[6], + kinds[2], + mb(kinds[3]), + kinds[4], + mb(kinds[5]), + kinds[6], + crate::draw::HEAP_TEXTURES_FULL.load(Relaxed), + mb(card[1]), + mb(card[0]), + mb(card[3]), + ); + // Upstream VIctory #3198: textures the card had no room for are asked + // for again instead of staying without a host copy for the run. + let no_room = crate::resource::NOT_MADE_FOR_NOW.load(Relaxed); + if no_room > 0 { + tracing::info!( + "host textures the card had no room for when asked: {} times since the start, {} of them \ + made on a later use", + no_room, + crate::resource::MADE_AFTER_NO_ROOM.load(Relaxed), + ); + } + let targets = crate::resource::targets_census(); + tracing::info!( + "host copies the sweep never lets go: {} the host renders to or writes {:.0} MB ({} of them placed {:.0} MB); of them {} have title memory that is not mapped now {:.0} MB, {} were not used for 30 s and are held by no list and no slot {:.0} MB, {} are both {:.0} MB; and {} copies of textures the title fills that the host copied into {:.0} MB", + targets[0], + mb(targets[1]), + targets[10], + mb(targets[11]), + targets[2], + mb(targets[3]), + targets[4], + mb(targets[5]), + targets[6], + mb(targets[7]), + targets[8], + mb(targets[9]), + ); + tracing::info!( + "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \ + {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \ + asked for in each", + windows[0], + mb(windows[1]), + stagings[0], + mb(stagings[1]), + mb(windows[2]), + ); + tracing::info!( + "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB \ + left to commit); host copies of title memory: {} alive {:.0} MB, of them {} windows \ + outside buffers {:.0} MB; snapshot buffers kept: {} reserving {:.0} MB; staging of \ + textures: {} alive {:.0} MB, {} kept by their texture; host textures: {} alive {:.0} MB, \ + {} placed in title memory; made so far: {} upload buffers {:.0} MB ({} of them {:.0} MB in the card's memory, Resizable BAR), {} shared buffers \ + {:.0} MB, {} card buffers {:.0} MB", + mb(private), + mb(working), + mb(free), + mb(left), + copies[0], + mb(copies[1]), + copies[2], + mb(copies[3]), + copies[4], + mb(copies[5]), + staged[0], + mb(staged[1]), + staged[2], + textures[0], + mb(textures[1]), + crate::resource::placed_textures(), + made[0], + mb(made[1]), + crate::host::GPU_UPLOADS[0].load(Relaxed), + mb(crate::host::GPU_UPLOADS[1].load(Relaxed)), + made[2], + mb(made[3]), + made[4], + mb(made[5]), + ); + tracing::info!( + "memory, placed textures: {} of them were asked for again with other filler words in their description (one resource and host copy each since the filler left the key; VICTORY_PLACED_FILLER=1 keeps it)", + crate::resource::placed_filler_twins() + ); + // What the line above leaves open: what is alive of the buffers "made + // so far", what the windows hold and what holds them, and what our own + // code has allocated. + let alive: Vec<u64> = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect(); + let window = crate::shadow::window_use(); + let views = crate::descriptor::views_kept(); + let own: Vec<u64> = OWN.iter().map(|o| o.load(Relaxed)).collect(); + tracing::info!( + "memory, what holds it: {} host lists alive; their scratch memory: {} chunks {:.0} MB, of them {} chunks {:.0} MB spare ({} taken from the spare ones so far); their other upload buffers: {} alive {:.0} MB; windows outside buffers (grid {} KiB): {:.0} MB of their pages ever copied, {} shown by descriptor slots {:.0} MB, {} held by lists or the pass over the heap {:.0} MB, {} asked for without a length {:.0} MB; buffer views of the heap whose slot showed another copy than the one brought up to date: {}; distinct views kept: {} ({} free) {:.0} MB; our own allocations: {:.0} MB in {} blocks (under 4 KiB {:.0} MB in {}, to 64 KiB {:.0} MB in {}, to 1 MiB {:.0} MB in {}, larger {:.0} MB in {})", + alive[0], + alive[1], + mb(alive[2]), + alive[3], + mb(alive[4]), + alive[5], + alive[6], + mb(alive[7]), + window[7] >> 10, + mb(window[0]), + window[1], + mb(window[2]), + window[3], + mb(window[4]), + window[5], + mb(window[6]), + crate::draw::HEAP_VIEWS_ELSEWHERE.load(Relaxed), + views[0], + views[1], + mb(views[2]), + mb(own[..4].iter().sum()), + own[4..].iter().sum::<u64>(), + mb(own[0]), + own[4], + mb(own[1]), + own[5], + mb(own[2]), + own[6], + mb(own[3]), + own[7], + ); + // Round 2: what the view table still holds and what goes around it, + // what host lists cost, the card's share that is the layer's own or + // the title's no more, and which big blocks are ours. + let lists: Vec<u64> = crate::host::LISTS.iter().map(|l| l.load(Relaxed)).collect(); + tracing::info!( + "memory, more: views named whole in their records since the start: {} constant buffer \ + views, {} views of placed memory; of the view table's entries {} are constant buffer \ + views and {} views of placed memory; shapes of placed views kept: {}; host lists: {} \ + made by the host, {} preludes made for them, private bytes grew {:.0} MB while \ + lists were made; twins of depth textures: {:.0} MB; host copies of \ + placed textures whose title memory is not mapped any more (estimate): {:.0} MB, of \ + them still shown by a descriptor slot {:.0} MB; the pipeline library's mapped file \ + let go from memory so far: {:.0} MB; our own blocks of 32 MB and more, in MB: {}", + views[6], + views[7], + views[3], + views[4], + views[5], + lists[0], + lists[1], + lists[2] as i64 as f64 / (1 << 20) as f64, + mb(census[7]), + mb(census[8]), + mb(census[9]), + mb(kept[6]), + big_blocks(), + ); + // Round 3: whether windows hold the same memory more than once (they + // can, once they are cut finer than 4 MiB), and how many host lists + // the title made and never used. + tracing::info!( + "memory, windows: the {:.0} MB of windows lie over {:.0} MB of title memory (the rest is \ + memory that is in more than one window, and is copied once for each); host lists never \ + reset since they were made: {}", + mb(copies[3]), + mb(crate::shadow::window_cover()), + lists[3], + ); +} + +/// Microseconds since the first call. +fn now_us() -> u64 { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 +} + +/// When the last frame was presented and when the last submission returned +/// ([`now_us`]), and whether a list call and a submission followed that +/// present yet. +static PRESENTED_AT: AtomicU64 = AtomicU64::new(0); +static SUBMITTED_AT: AtomicU64 = AtomicU64::new(0); +static RECORDED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); +static SUBMITTED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +/// What a thread that submits did between its submissions and in them +/// (microseconds; list calls in nanoseconds). +#[derive(Default, Clone, Copy)] +struct Submitter { + submissions: u64, + /// From a submission's return to the next one's call: wall time, of it + /// the thread running (user, kernel), and inside our list calls. + between: u64, + between_user: u64, + between_kernel: u64, + between_ours: u64, + /// Waiting for the submission lock; running inside submissions. + lock: u64, + inside_user: u64, + inside_kernel: u64, +} + +/// By thread: the submitting threads, and list-call time (nanoseconds, +/// calls) of every recording thread. +static SUBMITTERS: Mutex<Vec<(u32, Submitter)>> = Mutex::new(Vec::new()); +static RECORDERS: Mutex<Vec<(u32, u64, u64)>> = Mutex::new(Vec::new()); + +thread_local! { + /// This thread's last submission: when it returned ([`now_us`]) and the + /// thread's processor time then (user, kernel). + static LEFT: std::cell::Cell<Option<(u64, u64, u64)>> = const { std::cell::Cell::new(None) }; + /// The thread's processor time when its running submission was called. + static ENTERED: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; + /// List-call nanoseconds of this thread since its last submission. + static OURS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; + /// List-call time not yet added to `RECORDERS` (nanoseconds, calls). + static UNSENT: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; +} + +fn thread_id() -> u32 { + // SAFETY: a plain query. + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } +} + +fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 { + (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10 +} + +/// This thread's processor time so far (user, kernel), in microseconds. +fn thread_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own thread and four valid out pointers. + unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +/// The process's processor time so far (user, kernel), in microseconds. +fn process_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own process and four valid out pointers. + unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter { + let at = match all.iter().position(|s| s.0 == id) { + Some(at) => at, + None => { + all.push((id, Submitter::default())); + all.len() - 1 + } + }; + &mut all[at].1 +} + +/// A list call on this thread that began at `started` has returned. +pub(crate) fn recorded(started: std::time::Instant) { + let ns = started.elapsed().as_nanos() as u64; + add(C::RecordCalls, 1); + add(C::RecordNs, ns); + crate::framelog::add(crate::framelog::T::RecordCalls, 1); + crate::framelog::add(crate::framelog::T::RecordNs, ns); + crate::framelog::here(crate::framelog::H::RecordNs, ns); + if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) { + let began = now_us().saturating_sub(ns / 1000); + add(C::UntilRecordUs, began.saturating_sub(PRESENTED_AT.load(Relaxed))); + } + OURS.with(|o| o.set(o.get() + ns)); + let (unsent, calls) = UNSENT.with(|u| u.get()); + let (unsent, calls) = (unsent + ns, calls + 1); + // By thread, a couple of milliseconds at a time. + if unsent < 2_000_000 { + UNSENT.with(|u| u.set((unsent, calls))); + return; + } + UNSENT.with(|u| u.set((0, 0))); + if crate::framelog::on() { + crate::framelog::add(crate::framelog::T::RecordLooks, 1); + if crate::framelog::on_slow_core() { + crate::framelog::add(crate::framelog::T::RecordSlow, 1); + } + } + let id = thread_id(); + let mut all = RECORDERS.lock().unwrap_or_else(|e| e.into_inner()); + match all.iter_mut().find(|r| r.0 == id) { + Some(r) => (r.1, r.2) = (r.1 + unsent, r.2 + calls), + None => all.push((id, unsent, calls)), + } +} + +/// A submission is called on this thread (before it waits for the +/// submission lock). +pub(crate) fn submission_begins() { + let now = now_us(); + if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) { + add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed))); + } + let (user, kernel) = thread_times(); + ENTERED.with(|e| e.set((user, kernel))); + let ours = OURS.with(|o| o.replace(0)); + if let Some((left, u, k)) = LEFT.with(|l| l.get()) { + let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()); + let s = submitter(&mut all, thread_id()); + s.between += now.saturating_sub(left); + s.between_user += user.saturating_sub(u); + s.between_kernel += kernel.saturating_sub(k); + s.between_ours += ours; + } +} + +/// The submission returns; it waited `lock` microseconds for the +/// submission lock. +pub(crate) fn submission_ends(lock: u64) { + let now = now_us(); + SUBMITTED_AT.store(now, Relaxed); + let (user, kernel) = thread_times(); + let (u, k) = ENTERED.with(|e| e.get()); + LEFT.with(|l| l.set(Some((now, user, kernel)))); + OURS.with(|o| o.set(0)); + let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()); + let s = submitter(&mut all, thread_id()); + s.submissions += 1; + s.lock += lock; + s.inside_user += user.saturating_sub(u); + s.inside_kernel += kernel.saturating_sub(k); +} + +/// The title calls its present (before our own copy to the window runs). +pub(crate) fn present_begins() { + add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed))); +} + +/// A frame was presented. +pub(crate) fn presented() { + add(C::Frames, 1); + PRESENTED_AT.store(now_us(), Relaxed); + RECORDED_SINCE.store(false, Relaxed); + SUBMITTED_SINCE.store(false, Relaxed); } -/// Logs the counters per frame over `frames` frames, and the ranges that -/// took most bytes. +fn page_faults() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{ + K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + u64::from(c.PageFaultCount) +} + +/// Logs the counters per frame, and the ranges that took most bytes. The +/// counters run from line to line, so they are divided by the frames +/// presented since the last line, not by `frames` (the frames of the last +/// second or more: a 4 s frame after an unlogged 4 s frame showed two +/// frames' counts as one's). pub(crate) fn log(frames: f64) { + let counted = COUNT[C::Frames as usize].swap(0, Relaxed); + let frames = if counted > 0 { counted as f64 } else { frames }; static FAULTS: AtomicU64 = AtomicU64::new(0); - let memory = process_memory(); - // Keep the previous successful sample when the OS query fails; otherwise - // the next successful read would count all lifetime faults as one interval. - let faults = memory.map_or(0, |m| { - let previous = FAULTS.swap(m.page_faults, Relaxed); - m.page_faults.saturating_sub(previous) - }); + let faults = page_faults(); + let faults = faults - FAULTS.swap(faults, Relaxed).min(faults); let c: Vec<f64> = COUNT .iter() .map(|a| a.swap(0, Relaxed) as f64 / frames) @@ -158,14 +1178,237 @@ pub(crate) fn log(frames: f64) { mb(c[C::TexHashed as usize]), mb(c[C::TexChanged as usize]), ); - if let Some(memory) = memory { - const GIB: f64 = 1024.0 * 1024.0 * 1024.0; + tracing::info!( + "recording per frame ({frames:.0} frames): {:.0} list calls {:.1} ms (all recording \ + threads); {:.1} ms waiting for pipelines; dynamic slots: {:.0} tables asked, {:.0} \ + refused, {:.1} ms searching; notes {:.1} ms; shader-written ranges: {:.0} steps in \ + {:.1} submissions, snapshots {:.1} ms, {:.1} MB compared back; sparse reads {:.1} ms; \ + guards {:.1} ms; {:.1} MB copied whole (memory not watched); {:.1} frame waits \ + sleeping {:.1} ms (all threads); ranges of shaders that cannot store to buffers: \ + {:.0} steps {:.1} MB left out", + c[C::RecordCalls as usize], + c[C::RecordNs as usize] / 1e6, + ms(c[C::PipelineWaitUs as usize]), + c[C::DynamicAsked as usize], + c[C::DynamicRefused as usize], + c[C::DynamicNs as usize] / 1e6, + c[C::NoteNs as usize] / 1e6, + c[C::GpuWrites as usize], + c[C::BackSubmissions as usize], + ms(c[C::SnapshotUs as usize]), + mb(c[C::BackCompared as usize]), + ms(c[C::SparseUs as usize]), + ms(c[C::GuardUs as usize]), + mb(c[C::WholeBytes as usize]), + c[C::PaceWaits as usize], + ms(c[C::PaceUs as usize]), + c[C::GpuWritesLeftOut as usize], + mb(c[C::GpuWritesLeftOutBytes as usize]), + ); + crate::draw::tables_line(frames); + let [together, written, mapped] = + [0, 1, 2].map(|n| crate::watch::ALIASES[n].load(std::sync::atomic::Ordering::Relaxed)); + tracing::info!( + "guards over several views of a page, since the start: {together} blocks guarded with their other views, \ + {written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped" + ); + // Where the wall clock of a frame goes: the phases of a frame, the + // processor time of the whole process, and what each submitting and + // recording thread did. + static CPU: Mutex<(u64, u64)> = Mutex::new((0, 0)); + let (user, kernel) = process_times(); + let (user, kernel) = { + let mut last = CPU.lock().unwrap_or_else(|e| e.into_inner()); + let spent = (user.saturating_sub(last.0), kernel.saturating_sub(last.1)); + *last = (user, kernel); + (spent.0 as f64 / 1e3 / frames, spent.1 as f64 / 1e3 / frames) + }; + tracing::info!( + "frame account per frame: after a present {:.1} ms until the first list call and {:.1} ms \ + until the first submission; {:.1} ms from the last submission to the present call; \ + lists reset in {:.1} ms; the process ran {user:.0} ms user + {kernel:.0} ms kernel on \ + all threads; what shaders wrote: {:.1} ms finding {:.0} pieces that differ, {:.1} ms \ + putting them back; texture uploads: {:.0} recorded, {:.0} left out; {:.1} held \ + submissions run at the present with their waits not met; waits for memory values: \ + {:.0} looks {:.1} ms; {:.0} host lists made {:.1} ms; {:.0} parts of held submissions \ + ran alone that the next part could have run with", + ms(c[C::UntilRecordUs as usize]), + ms(c[C::UntilSubmitUs as usize]), + ms(c[C::TailUs as usize]), + c[C::ResetNs as usize] / 1e6, + ms(c[C::BackScanUs as usize]), + c[C::BackDiffer as usize], + ms(c[C::BackSyncUs as usize]), + c[C::TexUploads as usize], + c[C::TexSkipped as usize], + c[C::Forced as usize], + c[C::WaitChecks as usize], + c[C::WaitCheckNs as usize] / 1e6, + c[C::HostLists as usize], + c[C::HostListNs as usize] / 1e6, + c[C::PartsTogether as usize], + ); + // What is copied whole, largest first: memory nobody tells us about. + let whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut whole: Vec<_> = whole.into_iter().flatten().collect(); + whole.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); + tracing::info!( + " copied whole (memory not watched): {:.1} ms per frame in {} ranges; the largest follow", + ms(c[C::WholeUs as usize]), + whole.len() + ); + for ((src, len), (n, us)) in whole.into_iter().take(6) { tracing::info!( - private_gib = memory.private_usage as f64 / GIB, - working_set_gib = memory.working_set as f64 / GIB, - "process memory" + " copied whole from {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame", + n as f64 / frames, + (len as u64 * n) as f64 / 1e6 / frames, + us as f64 / 1e3 / frames ); } + // The waiting for the card: many short waits or a few long ones, how + // much of it is for submissions the title gets nothing back from, and + // the longest one. + let longest = std::mem::take(&mut *LONGEST.lock().unwrap_or_else(|e| e.into_inner())); + tracing::info!( + " waiting for the card per frame: {:.1} submissions under 2 ms ({:.1} ms), {:.1} of 2-8 ms \ + ({:.1} ms), {:.1} of 8-32 ms ({:.1} ms), {:.1} longer ({:.1} ms); {:.1} submissions hand \ + nothing back to the title ({:.1} ms of the waiting); the longest since the last line: \ + {:.1} ms, {}", + c[C::CardUnder2 as usize], + ms(c[C::CardUnder2Us as usize]), + c[C::Card2To8 as usize], + ms(c[C::Card2To8Us as usize]), + c[C::Card8To32 as usize], + ms(c[C::Card8To32Us as usize]), + c[C::CardOver32 as usize], + ms(c[C::CardOver32Us as usize]), + c[C::NothingBack as usize], + ms(c[C::NothingBackUs as usize]), + longest.0 as f64 / 1e3, + longest.1 + ); + let by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut by: Vec<_> = by.into_iter().flatten().collect(); + by.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + for (what, (n, us)) in by.into_iter().take(12) { + tracing::info!( + " the card's time by what ran: {:.1} ms a frame in {:.1} submissions a frame: {}", + us as f64 / 1e3 / frames, + n as f64 / frames, + what.chars().take(700).collect::<String>() + ); + } + let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut by: Vec<_> = by.into_iter().flatten().collect(); + by.sort_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us)); + // All of them together, and by their first word: the forty lines below + // are the heaviest only (100 of 226 ms waited in run 102), and what the + // commands do not account for is the layer's own lists (the card + // copies' passes, preludes) and the waits themselves. + if !by.is_empty() { + let mut kinds: Vec<(String, u64, u64)> = Vec::new(); + for (what, (n, us, _)) in &by { + let word = what.split(' ').next().unwrap_or("").to_owned(); + match kinds.iter_mut().find(|k| k.0 == word) { + Some(k) => (k.1, k.2) = (k.1 + n, k.2 + us), + None => kinds.push((word, *n, *us)), + } + } + kinds.sort_by_key(|k| std::cmp::Reverse(k.2)); + let all: u64 = kinds.iter().map(|k| k.2).sum(); + let text: Vec<String> = + kinds.iter().map(|(word, n, us)| format!("{word} {:.1} ms in {:.0}", *us as f64 / 1e3 / frames, *n as f64 / frames)).collect(); + tracing::info!( + " the card's time by command (timing run), all {} kinds together: {:.1} ms a frame; by first word: {}", + by.len(), + all as f64 / 1e3 / frames, + text.join(", ") + ); + } + for (what, (n, us, longest)) in by.into_iter().take(40) { + tracing::info!( + " the card's time by command (timing run): {:.2} ms a frame in {:.1} commands a frame, the longest {:.2} ms: {what}", + us as f64 / 1e3 / frames, + n as f64 / frames, + longest as f64 / 1e3 + ); + } + tracing::info!( + " write-watch askings per frame that failed in the kernel: {:.0} ({:.2} ms in all with their guard walks); \ + not made because the range is known guarded view memory: {:.0} ({:.2} ms in all) (VICTORY_VIEW_ASK=1 asks \ + the kernel anyway; VICTORY_VIEW_KNOWN=1 keeps written view blocks known); such ranges left \ + out of the submissions' askings ahead: {:.0}", + c[C::WatchFailed as usize], + c[C::WatchFailedUs as usize] / 1e3, + c[C::WatchKnownView as usize], + c[C::WatchKnownUs as usize] / 1e3, + crate::watch::AHEAD_VIEWS.swap(0, Relaxed) as f64 / frames, + ); + tracing::info!( + " refreshes of watched host copies per frame: {:.0} copied nothing ({:.2} ms), {:.0} copied something \ + ({:.2} ms); of those that copied nothing, {:.0} were known unchanged before asking ({:.2} ms; \ + VICTORY_REFRESH_COUNT=1 looks: every block of the range read-only by our hand and clean, or the range \ + asked ahead, and no page noted written since the copy took it); skipped as known unchanged \ + (VICTORY_REGION_SKIP): {:.0}", + c[C::RefreshNone as usize], + c[C::RefreshNoneUs as usize] / 1e3, + c[C::RefreshSome as usize], + c[C::RefreshSomeUs as usize] / 1e3, + c[C::RefreshKnown as usize], + c[C::RefreshKnownUs as usize] / 1e3, + c[C::RefreshSkipped as usize], + ); + crate::draw::window_line(frames); + tracing::info!( + " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \ + for its barriers on buffers; {:.0} indirect commands bounded (a dispatch of ours between two \ + such waits each); barrier experiment {}", + c[C::WaitsForGroups as usize], + c[C::WaitsForBuffers as usize], + c[C::IndirectBounded as usize], + barrier_test() + ); + // What is compared after submissions, largest first, and how much of + // it shaders had written. + let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut compared: Vec<_> = compared.into_iter().flatten().collect(); + compared.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); + tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len()); + for ((src, len), (n, written)) in compared.into_iter().take(8) { + tracing::info!( + " compared {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.3} MB/frame of it written back", + n as f64 / frames, + (len as u64 * n) as f64 / 1e6 / frames, + written as f64 / 1e6 / frames + ); + } + let mut submitters = std::mem::take(&mut *SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner())); + submitters.sort_by_key(|s| std::cmp::Reverse(s.1.submissions)); + for (id, s) in submitters.into_iter().take(4) { + let per = |v: u64| v as f64 / 1e3 / frames; + tracing::info!( + " thread {id} submitted {:.1}x/frame: between its submissions {:.1} ms (running \ + {:.1} ms user + {:.1} ms kernel; {:.1} ms in list calls), in them running {:.1} ms \ + user + {:.1} ms kernel, {:.1} ms waiting for the submission lock", + s.submissions as f64 / frames, + per(s.between), + per(s.between_user), + per(s.between_kernel), + s.between_ours as f64 / 1e6 / frames, + per(s.inside_user), + per(s.inside_kernel), + per(s.lock), + ); + } + let mut recorders = std::mem::take(&mut *RECORDERS.lock().unwrap_or_else(|e| e.into_inner())); + recorders.sort_by_key(|r| std::cmp::Reverse(r.1)); + let busiest: Vec<String> = recorders + .iter() + .take(6) + .map(|r| format!("thread {} {:.0} ms in {:.0} calls", r.0, r.1 as f64 / 1e6 / frames, r.2 as f64 / frames)) + .collect(); + tracing::info!(" list calls by thread: {} threads; {}", recorders.len(), busiest.join(", ")); + log_memory(); let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut ranges: Vec<_> = ranges.into_iter().flatten().collect(); ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes)); diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 039dab596b..500fa18c13 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -34,7 +34,7 @@ pub(crate) struct HeapDesc { nodes: u32, } -/// Newer titles (Grand Theft Auto VI) pass the description followed by +/// Newer titles (the title) pass the description followed by /// memory of their own for the descriptors: an address and its size in /// bytes, or a null address to have the heap allocate (inferred from the /// title's call sites; older titles pass the plain description). @@ -59,11 +59,10 @@ pub(crate) struct Heap { host: std::sync::OnceLock<Option<host::HostHeap>>, #[cfg(windows)] pending: std::sync::Mutex<Vec<u32>>, - /// The write-watch asking (see [`crate::watch::writes`]) up to which - /// the host heap has caught up with what the title wrote into its - /// memory itself (see [`resync_title_writes`]). + /// Changed pages of a placed shader-visible heap. Some titles copy + /// descriptor records into it as bytes, without a descriptor API call. #[cfg(windows)] - synced: std::sync::atomic::AtomicU64, + written: Option<crate::watch::Tracked>, } pub(crate) fn heap<'a>(this: This) -> &'a Heap { @@ -78,7 +77,7 @@ impl Heap { } /// The host heap, made on first use from what the title wrote so far. - /// Made late because a host view heap the size of Grand Theft Auto VI's + /// Made late because a host view heap the size of the title's /// costs over 100 MB of commit, which its boot needs for its page pool. #[cfg(windows)] pub(crate) fn host(&self) -> Option<&host::HostHeap> { @@ -104,6 +103,13 @@ impl Heap { .as_ref() } + /// The handle of descriptor `index` of this heap. + #[cfg(windows)] + pub(crate) fn handle(&self, index: u32) -> Option<u64> { + let step = u64::from(increment(self.desc.kind)?); + (index < self.desc.count).then(|| self.start + u64::from(index) * step) + } + /// The descriptor index of `handle` in this heap, if it lies in it. pub(crate) fn index(&self, handle: u64) -> Option<u32> { let step = u64::from(increment(self.desc.kind)?); @@ -119,13 +125,24 @@ const SHADER_VISIBLE: u32 = 1; /// Shader-visible heaps by address range, for mirroring descriptor writes: /// start, end, heap. +/// +/// Read by every lookup and by [`sync_heaps`], written only when a heap is +/// made or dropped. It was a mutex, and [`sync_heaps`] holds it for its +/// whole pass (15 ms a frame on the submitting thread): the profile of run +/// 225 has the title's six recording threads waiting 48.5 ms a frame in +/// [`shader_slot`] for it, each lookup itself a few nanoseconds. Readers no +/// longer wait for each other. Nothing a holder calls takes it again. #[cfg(windows)] -static SHADER_HEAPS: std::sync::Mutex<Vec<(u64, u64, usize)>> = std::sync::Mutex::new(Vec::new()); +static SHADER_HEAPS: std::sync::RwLock<Vec<(u64, u64, usize)>> = std::sync::RwLock::new(Vec::new()); + +/// One [`sync_heaps`] at a time, as when the list above was a mutex. +#[cfg(windows)] +static SYNCING: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// The shader-visible heap holding `handle`, and the descriptor's index. #[cfg(windows)] fn shader_slot<'a>(handle: u64) -> Option<(&'a Heap, u32)> { - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); let &(_, _, at) = heaps .iter() .find(|&&(start, end, _)| (start..end).contains(&handle))?; @@ -153,59 +170,366 @@ fn mirror(handle: u64) { } } -/// Brings the host heaps up to date with descriptors the title wrote into -/// heap memory itself (copies of whole slots, which no create or copy call -/// reports), before a submission runs: slots read directly by index (not -/// through a table) are made only from what was mirrored, so a slot the -/// title turned from a texture into a constant buffer kept the texture, -/// whose upper half the shader read as a buffer at address 0: a GPU page -/// fault and a lost device in the world. Only the 64 KiB blocks written -/// since the last call are looked at; heaps in memory the kernel does not -/// watch (ours, not the title's) are left as they are. +/// Mirrors records copied directly into placed shader-visible heaps. Calls +/// to `Create*View` are already mirrored by [`mirror`]; raw CPU copies leave +/// only write-watch pages to reveal which slots changed. +/// +/// Upstream VIctory 86a5ed6 does the same and counts 1,300 to 14,400 such +/// slots a frame in the world of the title this fork works on, against a +/// few hundred views made by calls; without it those host slots stayed +/// null, or went on showing what they showed before. +/// `VICTORY_HEAP_SYNC=0`: not done, as before. [`SYNCED`] counts. #[cfg(windows)] -pub(crate) fn resync_title_writes() { +pub(crate) fn sync_heaps() { use std::sync::atomic::Ordering::Relaxed; - // Held throughout: registered heaps stay alive while it is. - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "0")) { + return; + } + let started = std::time::Instant::now(); + let (mut pages, mut looked, mut mirrored) = (0u64, 0u64, 0u64); + let mut page_bytes: Vec<u8> = Vec::new(); + let _one = SYNCING.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); for &(start, end, at) in heaps.iter() { // SAFETY: registered heaps are live (removed when dropped). let heap = unsafe { &*(at as *const Heap) }; - let (Some(Some(host)), Some(step)) = (heap.host.get(), increment(heap.desc.kind)) else { - continue; // no host heap yet: its first use mirrors everything - }; - let page = crate::watch::PAGE as u64; - let (first, last) = (start / page * page, end.div_ceil(page) * page); - let Some((now, written)) = crate::watch::writes(first as usize, last as usize, true) else { + let (Some(Some(host)), Some(written), Some(step)) = + (heap.host.get(), &heap.written, increment(heap.desc.kind)) + else { continue; }; - let before = heap.synced.swap(now, Relaxed); let step = u64::from(step); - for (p, asked) in written { - if asked <= before { - continue; + // Capped host heaps have no counterparts for the title slots reserved + // for per-draw tables; raw writes there must not be mirrored. + let mirrored_count = heap.desc.count.min(host.count()); + // With `VICTORY_HEAP_SYNC_CUT`: only the pages that hold slots the + // host heap has title slots for are taken and read ([`sync_cut`]). + let looked_end = if sync_cut() { + (start as usize).saturating_add(mirrored_count as usize * step as usize).min(end as usize) + } else { + end as usize + }; + let asking = std::time::Instant::now(); + let ranges = written.take(start as usize, looked_end); + SYNC_PARTS[0].fetch_add(asking.elapsed().as_micros() as u64, Relaxed); + for (range_from, range_end) in ranges { + let mut page = range_from & !(crate::watch::PAGE - 1); + while page < range_end { + let from = page.max(range_from); + let to = (page + crate::watch::PAGE).min(range_end); + // The page's records are read through the kernel, into a + // copy: a page the title unmaps meanwhile fails the read + // where 2,048 reads in place would fault. + page_bytes.resize(to - from, 0); + let reading = std::time::Instant::now(); + let read = crate::host::read_into(from as *const u8, &mut page_bytes); + SYNC_PARTS[1].fetch_add(reading.elapsed().as_micros() as u64, Relaxed); + if read { + pages += 1; + let slots = changed_slots(from, to, start as usize, step, mirrored_count); + // The page's records in one go, under one lock + // (`HostHeap::mirror_copied_page`); one by one below + // with `VICTORY_HEAP_SYNC_PAGE=0`. + let slots = if page_at_once() { + let (seen, made) = host.mirror_copied_page(slots, (start, step), from, &page_bytes); + looked += seen; + mirrored += made; + 0..0 + } else { + slots + }; + for index in slots { + let handle = start + index * step; + // A record that straddles the range's ends is left + // to the range that holds its first byte. + let Some(at) = (handle as usize).checked_sub(from) else { + continue; + }; + let Some(record) = page_bytes.get(at..at + step as usize) else { + continue; + }; + looked += 1; + // Only a record that is not the one last seen there + // (`HostHeap::mirror_copied`). + if host.mirror_copied(index as u32, handle, record) { + mirrored += 1; + } + } + } + page += crate::watch::PAGE; } - let from = (p as u64 * page).max(start); - let to = ((p as u64 + 1) * page).min(end); - for i in (from - start) / step..(to - start).div_ceil(step) { - let i = i as u32; - if i < heap.desc.count { - host.mirror(i, start + u64::from(i) * step, false); + } + } + drop(heaps); + for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, started.elapsed().as_micros() as u64]) { + count.fetch_add(n, Relaxed); + } +} + +/// Whether a submission's pass over the title's view heaps ([`sync_heaps`]) +/// and the making of the slots that waited for a texture's host copy +/// ([`make_waiting`]) run on a thread of their own while the submitting +/// thread prepares the submission (`VICTORY_SYNC_BESIDE=1`; off by default: +/// both on the submitting thread before preparing, as before). `alt`: +/// twenty seconds with, twenty without, in turn, each change said in the +/// log; decided once per submission. +/// +/// Why: the pass is 9.0 to 11.1 ms a frame on the submitting thread in the +/// boat-save runs 311-316 (its by-part line; "making the host slots of the +/// changed records" 6.0 to 7.6 of it, 7,000 to 10,000 records a frame), +/// and that thread is the frame's wall (at work 68 of a 79 ms usual frame, +/// run 316). Preparing (40 to 60 ms) reads and writes title memory and host +/// copies, not the host heap's slots; the slots are read when the lists +/// run, after [`sync_end`]. +/// +/// What changes: the pass starts after the once-a-second sweep instead of +/// before it (the sweep lets go only of what no slot names, so nothing the +/// pass names is let go under it), and after the submission counts as +/// started (what its slot writes retire waits for this submission too). It +/// runs beside the submitting thread's steps, which may write title +/// memory (memory-to-memory copies); records such a step writes into a +/// view heap may be mirrored in this submission instead of the next. +#[cfg(windows)] +pub(crate) fn sync_beside() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_SYNC_BESIDE").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "the pass over the title's view heap runs beside the preparing from now (VICTORY_SYNC_BESIDE=alt): {}", + if on { "ON" } else { "off, on the submitting thread before it as usual" } + ); + } + on + } + } +} + +/// [`sync_beside`]'s hand-over: 0 nothing asked, 1 asked, 2 running. +#[cfg(windows)] +static BESIDE: (std::sync::Mutex<u8>, std::sync::Condvar) = (std::sync::Mutex::new(0), std::sync::Condvar::new()); + +/// Since the line last took them: passes run beside, microseconds the +/// submitting thread waited for one at [`sync_end`], passes it found done. +#[cfg(windows)] +static BESIDE_COUNTS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Hands the pass and [`make_waiting`] to their thread (started once); the +/// submitting thread goes on preparing. Without the thread both run here. +#[cfg(windows)] +pub(crate) fn sync_begin() { + static THREAD: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let started = *THREAD.get_or_init(|| { + std::thread::Builder::new() + .name("victory-heap-sync".into()) + .spawn(|| { + crate::framelog::keep_on_fast_cores("victory-heap-sync"); + loop { + { + let mut state = BESIDE.0.lock().unwrap_or_else(|e| e.into_inner()); + while *state != 1 { + state = BESIDE.1.wait(state).unwrap_or_else(|e| e.into_inner()); + } + *state = 2; + } + sync_heaps(); + make_waiting(); + *BESIDE.0.lock().unwrap_or_else(|e| e.into_inner()) = 0; + BESIDE.1.notify_all(); } + }) + .is_ok() + }); + if !started { + sync_heaps(); + make_waiting(); + return; + } + let mut state = BESIDE.0.lock().unwrap_or_else(|e| e.into_inner()); + // (One submission at a time holds the submission lock, and each ends + // with [`sync_end`]: nothing is running here now.) + while *state != 0 { + state = BESIDE.1.wait(state).unwrap_or_else(|e| e.into_inner()); + } + *state = 1; + BESIDE_COUNTS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + BESIDE.1.notify_all(); +} + +/// Waits until the pass handed over by [`sync_begin`] is done (at once if +/// none is out). +#[cfg(windows)] +pub(crate) fn sync_end() { + use std::sync::atomic::Ordering::Relaxed; + let waiting = std::time::Instant::now(); + let mut state = BESIDE.0.lock().unwrap_or_else(|e| e.into_inner()); + if *state == 0 { + BESIDE_COUNTS[2].fetch_add(1, Relaxed); + return; + } + while *state != 0 { + state = BESIDE.1.wait(state).unwrap_or_else(|e| e.into_inner()); + } + BESIDE_COUNTS[1].fetch_add(waiting.elapsed().as_micros() as u64, Relaxed); +} + +/// Whether [`sync_heaps`] leaves alone the part of a title view heap the +/// host heap has no title slots for (`VICTORY_HEAP_SYNC_CUT=1`; off by +/// default; `alt`: twenty seconds with, twenty without, in turn, each +/// change said in the log). +/// +/// On a host that caps view heaps at 1,000,000 the host heap holds the +/// title's slots below 737,855 and the title's heap has 1,245,184. The +/// records past the host's title slots were never mirrored +/// ([`changed_slots`] cuts them off), but their pages were asked about and +/// read all the same, and they are the busiest of the heap: the title +/// keeps its own per-draw tables there and rewrites them every frame +/// (measured in run 285 with an instrument since removed: about 100,000 +/// records a frame that are not zeros, a third of them live view objects, +/// a fifth constant views; about half of the changed pages a frame). The +/// layer serves those tables from slots of its own when a draw names +/// them. With the switch the pass asks the write watch about, and reads, +/// the mirrored part only: the same records are mirrored. +#[cfg(windows)] +fn sync_cut() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_HEAP_SYNC_CUT").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "the pass over the title's view heap leaves the part the host has no title slots for alone from now (VICTORY_HEAP_SYNC_CUT=alt): {}", + if on { "ON" } else { "off, every changed page is read as usual" } + ); } + on } } } +/// Microseconds of [`sync_heaps`] by part, since its line last took them: +/// asking the write tracking which pages changed, reading the pages, the +/// walk over their records (`HostHeap::mirror_copied_page`), and making +/// the host slots of the records that changed. An instrument: the pass is +/// 8 to 13 ms a frame and cutting the pages read took nothing off it (run +/// 286). +pub(crate) static SYNC_PARTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Since the last frame line, of [`sync_heaps`]: changed pages of placed +/// shader-visible heaps looked at, slots on them, slots whose record was +/// not the one last seen (mirrored), and the microseconds it took. +#[cfg(windows)] +pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// With the frame line: what [`sync_heaps`] did per frame over `frames`. +/// Nothing while no heap page changed. +#[cfg(windows)] +pub(crate) fn sync_line(frames: f64) { + let [pages, looked, mirrored, micros] = [0, 1, 2, 3].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + if pages == 0 { + return; + } + tracing::info!( + "descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \ + {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.0} left to the \n draws that read them through tables (VICTORY_HEAP_SYNC_TABLES=1 mirrors those too), {:.2} ms", + pages as f64 / frames, + looked as f64 / frames, + mirrored as f64 / frames, + host::COPIED_TABLED.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames, + micros as f64 / 1000.0 / frames + ); + let [beside, waited_us, found_done] = [0, 1, 2].map(|i| BESIDE_COUNTS[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + if beside > 0 { + tracing::info!( + "the pass over the title's view heap beside the preparing (VICTORY_SYNC_BESIDE), per frame: {:.1} passes, the submitting thread waited {:.2} ms for them, {:.1} found done", + beside as f64 / frames, + waited_us as f64 / 1e3 / frames, + found_done as f64 / frames + ); + } + let parts = [0, 1, 2, 3].map(|i| SYNC_PARTS[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / 1e3 / frames); + tracing::info!( + "the pass over the title's view heap by part, ms per frame: asking which pages changed {:.2}, reading the pages {:.2}, the walk over their records {:.2}, making the host slots of the changed records {:.2}", + parts[0], + parts[1], + parts[2], + parts[3] + ); + #[cfg(feature = "diagnostics")] + { + use std::sync::atomic::Ordering::Relaxed; + let n = host::MIRRORED.each_ref().map(|a| a.swap(0, Relaxed) as f64 / frames); + let us = host::MIRROR_US.each_ref().map(|a| a.swap(0, Relaxed) as f64 / 1e3 / frames); + tracing::info!( + "the view-heap pass's records made, per frame, by what making them did (count, ms): made already {:.0} {:.2}, \ + not a view of ours {:.0} {:.2}, the same view as made {:.0} {:.2}, the old view kept {:.0} {:.2}, \ + left for later (a null view made) {:.0} {:.2}, a view created {:.0} {:.2}, other {:.0} {:.2}; inside: \ + buffer notes and stale slots {:.2} ms, creating views {:.2} ms, keeping the slots' resources {:.2} ms", + n[0], n[7], n[1], n[8], n[2], n[9], n[3], n[10], n[4], n[11], n[5], n[12], n[6], n[13], us[0], us[1], us[2] + ); + } +} + +/// Whether [`sync_heaps`] hands a changed page's records to the host heap +/// in one go (`host::HostHeap::mirror_copied_page`). On by default: the +/// same records are mirrored either way. `VICTORY_HEAP_SYNC_PAGE=0`: one +/// by one, as before. +#[cfg(windows)] +fn page_at_once() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC_PAGE").is_none_or(|v| v != "0")) +} + +/// Title descriptor slots in a changed byte range that have host counterparts. +/// `range_end` is exclusive. +#[cfg(windows)] +fn changed_slots( + range_from: usize, + range_end: usize, + heap_start: usize, + step: u64, + mirrored_count: u32, +) -> std::ops::Range<u64> { + let from = (range_from - heap_start) as u64; + let to = (range_end - heap_start) as u64; + let first = from / step; + let last = to.div_ceil(step).min(u64::from(mirrored_count)); + first.min(last)..last +} + /// Gives back dynamic slots of the host heap behind the title heap at -/// `heap`, if that heap still exists. +/// `heap`, if that heap is still there, and `id` says it is the one that +/// took them ([crate::descriptor::host::HostHeap::id]): the title can release +/// the heap a list's slots came from, and a later heap can be made at the +/// same address before the list is reset. #[cfg(windows)] -pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { - let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); +pub(crate) fn release_dynamic(heap: usize, id: u64, first: u32, n: u32) { + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); if heaps.iter().any(|&(_, _, h)| h == heap) // SAFETY: registered heaps are live (removed when dropped). && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() { - host.release(first, n); + host.release(id, first, n); } } @@ -213,8 +537,15 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { impl Drop for Heap { fn drop(&mut self) { let at = std::ptr::from_ref::<Heap>(self) as usize; - let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); heaps.retain(|&(_, _, h)| h != at); + drop(heaps); + // Its run of title-memory views goes with it: a heap made later at + // the same address must not find this one's run (fork pull request + // #589, AscilCH). + if let Some(Some(host)) = self.host.get() { + crate::memory::forget_heap(host); + } } } @@ -243,6 +574,15 @@ const RTV_TAG: u32 = u32::from_le_bytes(*b"vRTV"); const _: () = assert!(size_of::<RtvRecord>() <= 112); impl RtvRecord { + /// All the view it records is made from: records with equal keys have + /// equal views (of the same host texture). + #[cfg(windows)] + pub(crate) fn key(&self) -> (usize, [u32; 7]) { + let mut words = [self.described; 7]; + words[1..].copy_from_slice(&self.desc); + (self.resource as usize, words) + } + /// The view description in the host's type (the same layout). #[cfg(windows)] pub(crate) fn desc( @@ -279,7 +619,8 @@ impl RtvRecord { 0, ] }; - words[0] = crate::resource::target_format(words[0]); + // A target or depth view: of a target, in its stand-in format. + words[0] = crate::resource::target_format(crate::resource::pc_format(words[0])); // SAFETY: both host view descriptions are 24 bytes in this layout. Some(unsafe { (&raw const words).cast::<T>().read_unaligned() }) } @@ -366,9 +707,21 @@ impl View { /// generation, so descriptors (and host slots made from them) naming the /// old one go stale instead of naming whatever is made at the same address /// next. -/// shortcut: views without a resource object (constant buffers, memory -/// views, samplers) are kept for the run; they are bounded by the title's -/// memory and sampler states. +/// +/// Views without a resource object have nothing that releases them, and a +/// title copies descriptors as bytes, so nothing says when the last +/// descriptor naming an entry is gone: such entries were kept for the run. +/// The title writes some 14,000 constant buffer views a frame, +/// each at the address its constants have that frame: 2,450,139 entries +/// after four minutes of play, 1,047 MB with the index, and 11,000 more +/// every second (run 65). So the two kinds that carry an address are not +/// entries any more: their records name them whole ([`constant_words`], +/// [`placed_words`]), and the table holds only what is bounded: views of +/// resource objects (freed with the resource), samplers (as many as there +/// are sampler states), and the shapes of placed views (their descriptions +/// without the address: as many as the title has kinds of textures and +/// buffers, however often it moves them). +/// `VICTORY_VIEW_INLINE=0`: every view is an entry, as before. struct Views { /// Each entry's view and generation. list: Vec<(View, u32)>, @@ -376,16 +729,254 @@ struct Views { /// Entries naming each resource. by_resource: std::collections::BTreeMap<usize, Vec<u32>>, free: Vec<u32>, + /// The shapes of views of placed memory, and where each is. + shapes: Vec<Shape>, + shape_index: std::collections::BTreeMap<Shape, u32>, } -static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views { +/// Read far more often than written: every slot a draw reads through a +/// table is looked up here, on several recording threads at once in the +/// world. Readers share it; only a view not seen before (a new table entry +/// or shape) and a released resource take it alone. +static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views { list: Vec::new(), index: std::collections::BTreeMap::new(), by_resource: std::collections::BTreeMap::new(), free: Vec::new(), + shapes: Vec::new(), + shape_index: std::collections::BTreeMap::new(), }); const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE"); +/// A record is the tag and two words, `i` and `generation` (the host keeps +/// them as one 64-bit key per slot). The top two bits of `generation` say +/// what the other 62 bits are: 0, entry `i` of the table at that +/// generation; [`CONSTANT`], a constant buffer view, whole; [`PLACED`], a +/// view of placed memory: its address and the number of its shape. +const KIND_SHIFT: u32 = 30; +/// Table generations stay below the kind bits (and above 0). +const GENERATIONS: u32 = (1 << KIND_SHIFT) - 1; +const CONSTANT: u32 = 1; +const PLACED: u32 = 2; +/// Bits of a constant buffer view's address in its record: any address a +/// program can have. The 15 bits above them are its size. +const CONSTANT_ADDRESS_BITS: u32 = 47; +/// Bits of a placed view's address in its record: placed memory is title +/// memory, which lies below 1 TiB. The 22 bits above them number its shape. +const PLACED_ADDRESS_BITS: u32 = 40; +const SHAPES: usize = 1 << (62 - PLACED_ADDRESS_BITS); + +/// A view of placed memory without its address: whether it is unordered +/// access, the resource description, and the view's words but the two that +/// hold the address (10 and 11). +type Shape = (bool, [u32; 14], [u32; 14]); + +/// Whether constant buffer views and views of placed memory are named whole +/// in their records ([`Views`]). On by default; `VICTORY_VIEW_INLINE=0` +/// makes every view a table entry, as before. +fn inline() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_INLINE").is_none_or(|v| v != "0")) +} + +/// Views named whole in their records since the start: constant buffer +/// views, views of placed memory (for the memory line). +static NAMED_WHOLE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The two record words of the 62 bits `payload` of kind `kind`. +fn kind_words(kind: u32, payload: u64) -> [u32; 2] { + [payload as u32, kind << KIND_SHIFT | (payload >> 32) as u32] +} + +/// The 62 bits two record words carry beside their kind. +fn payload(i: u32, generation: u32) -> u64 { + u64::from(generation & GENERATIONS) << 32 | u64::from(i) +} + +/// The record words that name the constant buffer view of `size` bytes at +/// `address` whole; `None` if they cannot: an address past 47 bits, or a +/// size of 16 KiB or more that is no multiple of 256 or reaches 4 MiB (the +/// size has 15 bits: bytes below 16 KiB, else units of 256 bytes). Such a +/// view is a table entry. +fn constant_words(address: u64, size: u32) -> Option<[u32; 2]> { + if address >> CONSTANT_ADDRESS_BITS != 0 { + return None; + } + let code = if size < 1 << 14 { + u64::from(size) + } else if size.is_multiple_of(256) && size >> 8 < 1 << 14 { + 1 << 14 | u64::from(size >> 8) + } else { + return None; + }; + Some(kind_words(CONSTANT, code << CONSTANT_ADDRESS_BITS | address)) +} + +/// The constant buffer view [`constant_words`] named. +fn constant_of(i: u32, generation: u32) -> View { + let payload = payload(i, generation); + let code = (payload >> CONSTANT_ADDRESS_BITS) as u32; + let size = if code >> 14 == 0 { code } else { (code & 0x3fff) << 8 }; + View::Constant(payload & ((1 << CONSTANT_ADDRESS_BITS) - 1), size) +} + +/// A placed view's shape and its address. +fn shape_of(unordered: bool, resource: &[u32; 14], desc: &[u32; 16]) -> (Shape, u64) { + let mut rest = [0u32; 14]; + rest[..10].copy_from_slice(&desc[..10]); + rest[10..].copy_from_slice(&desc[12..]); + ( + (unordered, *resource, rest), + u64::from(desc[10]) | u64::from(desc[11]) << 32, + ) +} + +/// The record words that name the view of placed memory at `address` with +/// shape number `shape`. +fn placed_words(shape: u32, address: u64) -> [u32; 2] { + kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address) +} + +impl Views { + /// The number of `shape`, a new one if it is not there yet; `None` when + /// the shapes are full (the view is then a table entry). + fn shape(&mut self, shape: Shape) -> Option<u32> { + if let Some(&at) = self.shape_index.get(&shape) { + return Some(at); + } + if self.shapes.len() >= SHAPES { + return None; + } + let at = self.shapes.len() as u32; + self.shapes.push(shape); + self.shape_index.insert(shape, at); + Some(at) + } + + /// The view of placed memory [`placed_words`] named. + fn placed_of(&self, i: u32, generation: u32) -> Option<View> { + let payload = payload(i, generation); + let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); + let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; + let mut desc = [0u32; 16]; + desc[..10].copy_from_slice(&rest[..10]); + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + desc[12..].copy_from_slice(&rest[10..]); + Some(View::Placed(unordered, resource, desc)) + } + + /// The record words of `view` as a table entry, if it has one. + fn entry_of(&self, view: &View) -> Option<[u32; 2]> { + let &i = self.index.get(view)?; + Some([i, self.list[i as usize].1]) + } + + /// The record words of `view` as a table entry: its entry (a new or a + /// freed one if the view is not there yet) and that entry's generation. + fn entry(&mut self, view: View) -> [u32; 2] { + let i = match self.index.get(&view) { + Some(&i) => i, + None => { + let i = match self.free.pop() { + Some(i) => { + self.list[i as usize].0 = view.clone(); + i + } + None => { + self.list.push((view.clone(), 1)); + self.list.len() as u32 - 1 + } + }; + for r in view.resources().into_iter().filter(|&r| r != 0) { + self.by_resource.entry(r).or_default().push(i); + } + self.index.insert(view, i); + i + } + }; + [i, self.list[i as usize].1] + } +} + +/// The two words that name `view` in a record: the view itself where its +/// kind allows ([`Views`]), else its table entry. +fn words_for(view: View) -> [u32; 2] { + use std::sync::atomic::Ordering::Relaxed; + if inline() { + match &view { + View::Constant(address, size) => { + if let Some(words) = constant_words(*address, *size) { + NAMED_WHOLE[0].fetch_add(1, Relaxed); + return words; + } + } + View::Placed(unordered, resource, desc) => { + let (shape, address) = shape_of(*unordered, resource, desc); + if address >> PLACED_ADDRESS_BITS == 0 { + // Nearly every placed view has a shape seen before. + let known = views_read().shape_index.get(&shape).copied(); + let shape = known.or_else(|| views_write().shape(shape)); + if let Some(shape) = shape { + NAMED_WHOLE[1].fetch_add(1, Relaxed); + return placed_words(shape, address); + } + } + } + _ => {} + } + } + // A view written before keeps its entry and generation. + if let Some(words) = views_read().entry_of(&view) { + return words; + } + views_write().entry(view) +} + +fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { + VIEWS.read().unwrap_or_else(|e| e.into_inner()) +} + +fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { + VIEWS.write().unwrap_or_else(|e| e.into_inner()) +} + +/// For the memory line: the distinct views kept ([`Views`]), those of them +/// free for reuse, and the bytes the table and its index hold for them (an +/// estimate: an entry of the table, and one of the index with its share of +/// a tree node; the shapes likewise); then the entries that are constant +/// buffer views and views of placed memory (those that did not fit a +/// record, or all of them with `VICTORY_VIEW_INLINE=0`), the shapes of +/// placed views kept, and the views named whole in their records since the +/// start: constant buffer views, views of placed memory. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn views_kept() -> [u64; 8] { + use std::sync::atomic::Ordering::Relaxed; + let views = views_read(); + let each = size_of::<(View, u32)>() as u64; + let shape = size_of::<Shape>() as u64; + let (mut constants, mut placed) = (0, 0); + for (view, _) in &views.list { + match view { + View::Constant(..) => constants += 1, + View::Placed(..) => placed += 1, + _ => {} + } + } + [ + views.list.len() as u64, + views.free.len() as u64, + views.list.capacity() as u64 * each + + views.index.len() as u64 * each * 3 / 2 + + views.shapes.capacity() as u64 * shape + + views.shape_index.len() as u64 * shape * 3 / 2, + constants, + placed, + views.shapes.len() as u64, + NAMED_WHOLE[0].load(Relaxed), + NAMED_WHOLE[1].load(Relaxed), + ] +} + impl View { /// The resource objects the view names. fn resources(&self) -> [usize; 2] { @@ -395,44 +986,123 @@ impl View { _ => [0, 0], } } + + /// The texture object the view is of, if that texture has no host copy + /// yet (`crate::resource::host_waits`): a slot written with such a + /// view is left null until the texture is first used. + #[cfg(windows)] + fn waiting_texture(&self) -> Option<usize> { + match *self { + View::Shader(r, _) | View::Unordered(r, _, _) + if crate::resource::host_waits(r as This) => + { + Some(r) + } + _ => None, + } + } } -fn record(handle: u64, view: View) { - if handle == 0 { - return; +/// Title slots (their handles) written with a view of a texture object +/// that had no host copy then, by texture. A title texture gets its host +/// copy on first use (`resource.rs` `Hosted`), and the title +/// writes each texture's views into its view heap when it creates the +/// texture: making those host slots would make every host copy at once. +/// They are made when the texture is: translated shaders index the heap +/// directly, so a slot is not always made again by the draw that reads it. +#[cfg(windows)] +static WAITING: std::sync::Mutex<std::collections::BTreeMap<usize, Vec<u64>>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// Textures given their host copy since [`make_waiting`] last ran. +#[cfg(windows)] +static MADE_LATE: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new()); + +/// Title texture `resource` was given its host copy (called under that +/// texture's own lock: nothing else is locked here). +#[cfg(windows)] +pub(crate) fn texture_made(resource: usize) { + MADE_LATE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(resource); +} + +/// The slot at `handle` was written with a view of texture `resource`, +/// which has no host copy: it waits for one. +#[cfg(windows)] +fn wait_for(resource: usize, handle: u64) { + /// A texture with more slots waiting than this is in use for all we + /// know (its views are being copied about): its host copy is made. + const MOST: usize = 64; + let many = { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + let slots = waiting.entry(resource).or_default(); + if !slots.contains(&handle) { + slots.push(handle); + } + slots.len() > MOST + }; + if many { + // Makes it, and notes it made. + let _ = crate::resource::host_copy(resource as This); + } else if !crate::resource::host_waits(resource as This) { + // Made by another thread since the slot was looked at: that making + // may have been taken by `make_waiting` before this slot was noted. + texture_made(resource); } - let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - let i = match views.index.get(&view) { - Some(&i) => i, - None => { - let i = match views.free.pop() { - Some(i) => { - views.list[i as usize].0 = view.clone(); - i - } - None => { - views.list.push((view.clone(), 1)); - views.list.len() as u32 - 1 - } +} + +/// Makes the host slots that waited for a texture's host copy, for the +/// textures made since the last call. Called before a submission runs, by +/// the thread that submits: a slot is read when a list runs. +#[cfg(windows)] +pub(crate) fn make_waiting() { + let made = std::mem::take(&mut *MADE_LATE.lock().unwrap_or_else(|e| e.into_inner())); + for resource in made { + let handles = WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource); + for handle in handles.into_iter().flatten() { + // Only if the slot still holds a view of that texture: the + // title may have written it since (and a view of another + // texture without a host copy must go on waiting). + // (Looked up first: the handle is read only while its heap is + // there.) + let Some((heap, index)) = shader_slot(handle) else { + continue; + }; + let same = match view(handle) { + Some(View::Shader(r, _) | View::Unordered(r, _, _)) => r == resource, + _ => false, }; - for r in view.resources().into_iter().filter(|&r| r != 0) { - views.by_resource.entry(r).or_default().push(i); + if same && let Some(Some(host)) = heap.host.get() { + host.mirror(index, handle, true); } - views.index.insert(view, i); - i } - }; - let generation = views.list[i as usize].1; + } +} + +fn record(handle: u64, view: View) { + if handle == 0 { + return; + } + let [i, generation] = words_for(view); // SAFETY: the handle is a descriptor slot, at least 16 bytes. unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) }; - drop(views); #[cfg(windows)] mirror(handle); } /// The title released `resource`: the views naming it go stale. pub(crate) fn forget(resource: usize) { - let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + #[cfg(windows)] + WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource); + let mut views = views_write(); let Some(entries) = views.by_resource.remove(&resource) else { return; }; @@ -444,19 +1114,81 @@ pub(crate) fn forget(resource: usize) { continue; } views.index.remove(&view); - views.list[i as usize].1 = generation.wrapping_add(1).max(1); + // (Below the bits that say a record is no table entry.) + views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1); // The view's other resource (a counter) keeps a stale entry, which // `forget` of that resource skips. views.free.push(i); + if crate::heap_pass::marked_set() { + note_forgotten(i); + } } } -/// The view of entry `i` if `generation` is still its own. -#[cfg(windows)] +/// With `VICTORY_HEAP_PASS_MARKED` (`crate::heap_pass`): table entries +/// freed since the pass over the heap's buffer views last asked +/// ([`take_forgotten`]): records that name them read nothing now, though no +/// slot was written. Kept only once a pass has asked. +static FORGOTTEN: std::sync::Mutex<(bool, bool, Vec<u32>)> = std::sync::Mutex::new((false, false, Vec::new())); + +/// More entries than this between two asks: the list is dropped, and the +/// next ask is told it does not know. +const FORGOTTEN_MOST: usize = 1 << 20; + +fn note_forgotten(i: u32) { + let mut forgotten = FORGOTTEN.lock().unwrap_or_else(|e| e.into_inner()); + let (asked, overflowed, list) = &mut *forgotten; + if !*asked || *overflowed { + return; + } + if list.len() >= FORGOTTEN_MOST { + *overflowed = true; + *list = Vec::new(); + return; + } + list.push(i); +} + +/// The table entries freed since the last call (in any order, maybe +/// twice); `None` on the first call and when too many were to be kept. +pub(crate) fn take_forgotten() -> Option<Vec<u32>> { + let mut forgotten = FORGOTTEN.lock().unwrap_or_else(|e| e.into_inner()); + let (asked, overflowed, list) = &mut *forgotten; + let known = *asked && !*overflowed; + *asked = true; + *overflowed = false; + let list = std::mem::take(list); + known.then_some(list) +} + +/// The record at `handle` (a descriptor slot in title memory): its tag and +/// two words, read as they are. +pub(crate) fn record_at(handle: u64) -> [u32; 3] { + // SAFETY: the handle is a descriptor slot in title memory, at least 16 + // bytes. + unsafe { (handle as *const [u32; 3]).read_unaligned() } +} + +/// The view table entry a record names, if it names one (not a view named +/// whole in its record, not a record of no view). +pub(crate) fn record_entry(record: [u32; 3]) -> Option<u32> { + let [tag, i, generation] = record; + (tag == VIEW_TAG && generation >> KIND_SHIFT == 0).then_some(i) +} + +/// The view the record words `i` and `generation` name: the one they hold +/// whole, or the view of entry `i` if `generation` is still its own. fn view_at(i: u32, generation: u32) -> Option<View> { - let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - let (view, current) = views.list.get(i as usize)?; - (*current == generation).then(|| view.clone()) + match generation >> KIND_SHIFT { + 0 => { + let views = views_read(); + let (view, current) = views.list.get(i as usize)?; + (*current == generation).then(|| view.clone()) + } + CONSTANT => Some(constant_of(i, generation)), + PLACED => views_read().placed_of(i, generation), + _ => None, + } } /// The view recorded at `handle`, if one is (and its resource is alive). @@ -466,9 +1198,25 @@ pub(crate) fn view(handle: u64) -> Option<View> { } // SAFETY: the handle is a descriptor slot the title passes back. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; - let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); - let (view, current) = views.list.get(i as usize)?; - (tag == VIEW_TAG && *current == generation).then(|| view.clone()) + if tag != VIEW_TAG { + return None; + } + view_at(i, generation) +} + +/// The view recorded at `handle`, and what says which record that is +/// (`host::HostHeap::publish`). +#[cfg(windows)] +pub(crate) fn view_and_key(handle: u64) -> Option<(View, u64)> { + if handle == 0 { + return None; + } + // SAFETY: as in `view`. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + if tag != VIEW_TAG { + return None; + } + Some((view_at(i, generation)?, u64::from(generation) << 32 | u64::from(i))) } /// A description of `N` words, if the title passes one. @@ -507,6 +1255,23 @@ pub(crate) extern "system" fn create_uav( record(handle, view); } +/// Copy only the fields of a placed resource description. Padding can differ +/// between two views of the same texture and the caller may leave it unwritten. +fn placed_resource_words(desc: *const [u32; 14]) -> Option<[u32; 14]> { + if desc.is_null() { + return None; + } + let src = desc.cast::<u32>(); + let mut fields = [0; 14]; + // SAFETY: the caller supplies a 56-byte ResourceDesc, possibly unaligned. + // Dimension occupies word 0. Alignment through Flags occupy words 2..13. + unsafe { + fields[0] = src.read_unaligned(); + fields[2..13].copy_from_slice(&src.add(2).cast::<[u32; 11]>().read_unaligned()); + } + Some(fields) +} + /// Device methods 0x230 and 0x238: shader resource and unordered access /// views of memory the title placed itself, `(resource desc, view desc, /// handle)`. @@ -516,7 +1281,7 @@ pub(crate) extern "system" fn create_placed_srv( desc: *const [u32; 16], handle: u64, ) { - if let (Some(resource), Some(desc)) = (words(resource), words(desc)) { + if let (Some(resource), Some(desc)) = (placed_resource_words(resource), words(desc)) { record(handle, View::Placed(false, resource, desc)); } } @@ -527,7 +1292,7 @@ pub(crate) extern "system" fn create_placed_uav( desc: *const [u32; 16], handle: u64, ) { - if let (Some(resource), Some(desc)) = (words(resource), words(desc)) { + if let (Some(resource), Some(desc)) = (placed_resource_words(resource), words(desc)) { record(handle, View::Placed(true, resource, desc)); } } @@ -673,12 +1438,14 @@ pub(crate) extern "system" fn create_heap( #[cfg(windows)] pending: Default::default(), #[cfg(windows)] - synced: std::sync::atomic::AtomicU64::new(0), + written: (placed && visible) + .then(|| crate::watch::track(start as usize, size as usize, true)) + .flatten(), }); #[cfg(windows)] if visible { let at = std::ptr::from_ref::<Heap>(&heap) as usize; - let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); heaps.push((start, start + size, at)); } #[cfg(not(windows))] @@ -731,6 +1498,132 @@ mod tests { create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out) } + #[cfg(windows)] + #[test] + fn raw_heap_sync_stops_before_dynamic_host_slots() { + let start = 0x1000usize; + let step = 32; + let capped = 5; + assert_eq!( + changed_slots( + start + 3 * step + 4, + start + 4 * step + 8, + start, + step as u64, + capped + ), + 3..5 + ); + assert_eq!( + changed_slots( + start + 6 * step, + start + 9 * step, + start, + step as u64, + capped + ), + 5..5 + ); + } + + /// A released view heap takes its run of title-memory views with it + /// (`memory::forget_heap`): a heap made later at the same address starts + /// its own run. (Fork pull request #589's test, on our helpers.) + #[cfg(windows)] + #[test] + fn a_released_view_heap_forgets_its_title_memory_run() { + let Some(device) = crate::host::host() else { + return; // no host GPU + }; + let list = device.new_list().expect("a host list"); + let desc = HeapDesc { + kind: VIEWS_KIND, + count: 64, + flags: SHADER_VISIBLE, + nodes: 1, + }; + let none = Placement { + address: 0, + size: 0, + }; + let mut h: This = std::ptr::null(); + assert_eq!(create(desc, none, &mut h), S_OK); + let host_heap = heap(h).host().expect("a host view heap"); + let key = std::ptr::from_ref(host_heap) as usize; + assert!(crate::memory::ready(&list, host_heap, &[], &[], false).is_some()); + assert!(crate::memory::has_run(key), "the heap's run is kept while it lives"); + assert_eq!(object::release_boxed::<Heap>(h), 0); + assert!(!crate::memory::has_run(key), "a released heap's run is forgotten"); + } + + /// A table made afresh for a draw holds the descriptors its shader + /// moves halves through (`HostShader::half_views`), also past the range + /// starts its used-resource entries give: with one entry for a range + /// from dword 0 and a 16-bit float buffer view at dword 8, the table + /// takes two dynamic slots, so the next allocation does not land on the + /// view's. (The case avt0m4t48 found in review on #927.) + #[cfg(windows)] + #[test] + fn a_fresh_table_holds_the_half_views_past_its_range_starts() { + use victory_shader::{ResourceType, RootType, UsedResource}; + let Some(device) = crate::host::host() else { + return; // no host GPU + }; + let list = device.new_list().expect("a host list"); + let desc = HeapDesc { + kind: VIEWS_KIND, + count: 2, + flags: SHADER_VISIBLE, + nodes: 1, + }; + let none = Placement { + address: 0, + size: 0, + }; + let mut h: This = std::ptr::null(); + assert_eq!(create(desc, none, &mut h), S_OK); + let title = heap(h); + let host_heap = title.host().expect("a host view heap"); + let (first, second) = (title.handle(0).unwrap(), title.handle(1).unwrap()); + // An R16G16B16A16_FLOAT buffer view of memory in the second slot. + let memory = [0u64; 64]; + let address = memory.as_ptr() as u64; + let resource = [1, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0]; + let mut words = [0u32; 16]; + words[..10].copy_from_slice(&[10, 1, 5768, 0, 0, 0, 64, 0, 0, 0]); + words[10] = address as u32; + words[11] = (address >> 32) as u32; + create_placed_srv(std::ptr::null(), &resource, &words, second); + assert!(view(second).as_ref().and_then(host::half_view).is_some()); + let mut state = crate::draw::State::default(); + state.set_heaps(&[h]); + state.set_table(true, 1, first); + let range = UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 8, + dwords: 4, + user_data: 4, + slot: 1, + }; + let made = state.tables(&list, &[range], &[], &[(1, 8)], true, &[], &mut Vec::new()); + let [(1, offset)] = made[..] else { + panic!("one fresh table for root parameter 1, not {made:?}"); + }; + assert_ne!(offset, u32::MAX, "the table found no dynamic slots"); + let next = host_heap.dynamic(1).expect("a dynamic slot"); + host_heap.release(host_heap.id(), next, 1); + drop(state); + slot::<extern "system" fn(This) -> u32>(h, 0x10)(h); + assert_eq!( + next, + offset / 32 + 2, + "the next allocation took the table's second slot" + ); + } + #[test] fn heaps_hold_count_descriptors_from_their_start() { let null = std::ptr::null(); @@ -757,6 +1650,87 @@ mod tests { assert_eq!(create(bad, none, &mut h), E_INVALIDARG); } + /// A descriptor copied into a placed heap as bytes is mirrored before + /// the next submission, even though no descriptor method saw the copy. + #[cfg(windows)] + #[test] + fn records_copied_as_bytes_are_made_at_the_next_sync() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + let memory = unsafe { + VirtualAlloc( + std::ptr::null(), + crate::watch::PAGE, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + }; + assert!(!memory.is_null()); + let desc = HeapDesc { + kind: SAMPLERS, + count: 64, + flags: SHADER_VISIBLE, + nodes: 1, + }; + let placement = Placement { + address: memory as u64, + size: 64 * 16, + }; + let mut h: This = std::ptr::null(); + assert_eq!(create(desc, placement, &mut h), S_OK); + if let Some(host) = heap(h).host() { + let mut elsewhere = [0u64; 2]; + let source = elsewhere.as_mut_ptr() as u64; + let sampler = [21, 3, 3, 3, 0, 1, 0, 0, 0, 0, 0, 0x7f7f_ffff, 0]; + create_sampler(std::ptr::null(), &sampler, source); + // SAFETY: the heap slot and source both hold 16 descriptor bytes. + unsafe { + std::ptr::copy_nonoverlapping( + source as *const u8, + memory.cast::<u8>().add(5 * 16), + 16, + ) + }; + assert!(!host.made(5)); + sync_heaps(); + assert!(host.made(5)); + } + slot::<extern "system" fn(This) -> u32>(h, 0x10)(h); + // SAFETY: this allocation belongs to the test. + unsafe { VirtualFree(memory, 0, MEM_RELEASE) }; + } + + #[test] + fn placed_views_share_resources_across_description_padding() { + let mut slot = [0u32; 8]; + let handle = slot.as_mut_ptr() as u64; + let view_desc = [0u32; 16]; + let null = std::ptr::null(); + let mut resource = [3, 0, 0, 0, 8, 0, 8, 0x10001, 28, 1, 0, 0, 0, 0]; + let expected = resource; + for (unordered, create) in [ + (false, create_placed_srv as extern "system" fn(_, _, _, _)), + (true, create_placed_uav), + ] { + create(null, &expected, &view_desc, handle); + let first = slot; + resource[1] = 0xaaaa_aaaa; + resource[13] = 0xbbbb_bbbb; + create(null, &resource, &view_desc, handle); + assert_eq!(slot, first); + assert_eq!( + view(handle), + Some(View::Placed(unordered, expected, view_desc)) + ); + let mut other = resource; + other[12] = 4; + create(null, &other, &view_desc, handle); + assert_ne!(slot, first); + } + } + #[test] fn views_survive_copies() { let null = std::ptr::null(); @@ -791,6 +1765,82 @@ mod tests { heap[0] = 0; } + /// Constant buffer views are named whole in their records: any address + /// a program can have, any size below 16 KiB, multiples of 256 bytes + /// up to 4 MiB; what does not fit says so. + #[test] + fn constant_views_fit_their_records() { + let top = (1u64 << CONSTANT_ADDRESS_BITS) - 1; + for address in [0u64, 0x100, 0x2602_0000, 0xd_6b60_0000, 0x7ffd_a34f_0000, top] { + for size in [0u32, 1, 255, 256, 4000, (1 << 14) - 1, 1 << 14, 65536, (1 << 22) - 256] { + let [i, generation] = constant_words(address, size).expect("fits"); + assert_eq!(generation >> KIND_SHIFT, CONSTANT); + assert_eq!(view_at(i, generation), Some(View::Constant(address, size)), "{address:#x} {size}"); + } + } + assert_eq!(constant_words(top + 1, 256), None, "an address past 47 bits"); + assert_eq!(constant_words(0x1000, (1 << 14) + 1), None, "16 KiB or more, no multiple of 256"); + assert_eq!(constant_words(0x1000, 1 << 22), None, "4 MiB"); + // Different views never share their words. + assert_ne!(constant_words(0x1000, 256), constant_words(0x1000, 512)); + assert_ne!(constant_words(0x1000, 256), constant_words(0x1100, 256)); + assert_ne!(constant_words(0x1000, 1 << 14), constant_words(0x1000, 64)); + } + + /// The leak of run 65: a title that writes constant buffer views and + /// views of placed memory at ever new addresses adds nothing to the + /// table; one shape stands for all the placed views alike. + #[test] + fn views_at_new_addresses_add_no_entries() { + if !inline() { + return; + } + let null = std::ptr::null(); + let slots = [0u64; 4]; + let at = slots.as_ptr() as u64; + // A resource description and a view no other test uses (its padding + // words, 1 and 13, zero: `placed_resource_words` leaves them out). + let resource: [u32; 14] = std::array::from_fn(|k| if k == 1 || k == 13 { 0 } else { 0x5ee0_0000 + k as u32 }); + let mut desc: [u32; 16] = std::array::from_fn(|k| 0x7a70_0000 + k as u32); + let mine = |v: &View| match v { + View::Constant(address, _) => (0x6_0000_0000..0x6_1000_0000).contains(address), + View::Placed(_, r, _) => *r == resource, + _ => false, + }; + let entries = || VIEWS.read().unwrap().list.iter().filter(|(v, _)| mine(v)).count(); + let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == resource).count(); + for n in 0..20_000u64 { + let address = 0x6_0000_0000 + n * 0x100; + create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at); + assert_eq!(view(at), Some(View::Constant(address, 512))); + let placed = 0xd_4940_0000 + n * 0x1_0000; + (desc[10], desc[11]) = (placed as u32, (placed >> 32) as u32); + create_placed_srv(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(false, resource, desc))); + } + assert_eq!(entries(), 0, "no table entries"); + assert_eq!(shapes(), 1, "one shape for 20,000 placed views"); + // The same shape, unordered: another shape. + create_placed_uav(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(true, resource, desc))); + assert_eq!(shapes(), 2); + // Placed memory past 1 TiB (not title memory) is a table entry. + (desc[10], desc[11]) = (0, 0x100); + create_placed_srv(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(false, resource, desc))); + assert_eq!(entries(), 1); + // A record's words are the same for the same view (the host knows + // a slot's view by them), and differ with the address. + // SAFETY: both handles are slots of 32 bytes above. + let words = |handle: u64| unsafe { *(handle as *const [u32; 3]) }; + let other = [0u64; 4]; + create_cbv(null, &[0x40, 6, 512, 0], at); + create_cbv(null, &[0x40, 6, 512, 0], other.as_ptr() as u64); + assert_eq!(words(at), words(other.as_ptr() as u64)); + create_cbv(null, &[0x140, 6, 512, 0], other.as_ptr() as u64); + assert_ne!(words(at), words(other.as_ptr() as u64)); + } + /// A released resource's views go stale; the same view of a new /// resource at the same address is a new record. #[test] @@ -810,7 +1860,7 @@ mod tests { assert_ne!(old, new, "a new generation"); } - /// Grand Theft Auto VI places its shader-visible heap in its own memory + /// The title places its shader-visible heap in its own memory /// and checks that the heap starts there. #[test] fn placed_heaps_start_at_the_title_memory() { diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 4eac2c24bf..ef401eed74 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -6,34 +6,1168 @@ //! reads it through a table and finds the slot changed. use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; -use crate::host::{Host, host}; +use crate::host::host; + +/// The locks [`HostHeap::kept`] is spread over: slot `i` is behind lock +/// `i % KEPT_PIECES`, at place `i / KEPT_PIECES`. Neighbouring slots are +/// behind different locks on purpose: the recording threads take their +/// tables' dynamic slots from one ring, next to one another. +const KEPT_PIECES: u32 = 64; + +/// Each host heap's identity, handed out in order: a range of dynamic slots +/// is given back to the heap that took it, and a heap made later at the same +/// address is not that heap ([`HostHeap::release`]). +static NEXT_ID: AtomicU64 = AtomicU64::new(1); + +/// Whether the recording threads are spared the heap's two busiest locks +/// (`VICTORY_HEAP_LOCKS=1`; after fork pull request #1146, part 1; OFF +/// unless set until a run of ours has carried it). +/// +/// Run 298's profile: the recording threads wait 49.6 ms a mean frame on +/// contended locks, about three fifths of it in [`HostHeap::mirror`] and a +/// fifth in [`HostHeap::keep`]. With the switch: a slot already made from +/// the record its draw names is found in [`HostHeap::made_now`] without +/// the slots' lock (the same answer the lock gives: nothing is done for +/// such a slot under it either), and `keep` holds only its slot's own +/// piece of `kept`, and lets the old resource go after giving it back. +/// Without it: every `mirror` takes the slots' lock, and every `keep` +/// stands in one line (`kept_one`) across the letting go, as before. +/// +/// `alt`: twenty seconds with, twenty without, in turn, each change said +/// in the log. +fn heap_locks() -> bool { + use std::sync::atomic::Ordering::Relaxed; + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_HEAP_LOCKS").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Relaxed) != u8::from(on) { + tracing::info!( + "the host heap's slots are found made without their lock, and kept without the one line, from now (VICTORY_HEAP_LOCKS=alt): {}", + if on { "ON" } else { "off, both locks as usual" } + ); + } + on + } + } +} pub(crate) struct HostHeap { + /// The frame of this heap's last pass over its buffer views + /// (`draw::State::heap_buffers`): each heap its own, not one for all + /// (codec_d, cool_fox 18bdf79). + pub(crate) buffer_frame: std::sync::atomic::AtomicU64, pub(crate) heap: ID3D12DescriptorHeap, cpu: usize, step: u32, - /// Slots mirroring the title's; `spare` more follow them. + /// Slots mirroring the title's; view heaps have `dynamic` more. count: u32, - /// Dynamic slots past the title's: [`DYNAMIC`] in a view heap (or - /// [`MIN_DYNAMIC`] where the host refused that heap), - /// [`SAMPLER_DYNAMIC`] in a capped sampler heap, none in another. - spare: u32, + /// Dynamic slots past `count`: [`DYNAMIC`] in view heaps, none in + /// sampler heaps. (Upstream falls back to 2^16 on a capped host heap; + /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.) + dynamic: u32, sampler: bool, /// The record (view index and generation) each slot was last made from. made: Mutex<Vec<u64>>, + /// The same, readable without the lock ([`heap_locks`]): written under + /// the lock wherever `made` is, to 0 before a slot is made again and + /// to its record only once the slot is made and kept. + made_now: Vec<std::sync::atomic::AtomicU64>, + /// A fingerprint of the record each slot held when the pass over + /// records copied in as bytes last looked at it + /// ([`HostHeap::mirror_copied`]; 0: never looked at). Made on first use. + copied: Mutex<Vec<u64>>, /// The host resource each slot views, held while the slot does: shaders /// index heaps directly, so a slot the title has not rewritten since it /// released the resource may still be read, and a freed host resource /// read there is a GPU page fault (the console reads stale memory). - kept: Mutex<Vec<Option<ID3D12Resource>>>, + /// In [`KEPT_PIECES`] pieces, each behind its own lock. + kept: Vec<Mutex<Vec<Option<ID3D12Resource>>>>, + /// Without [`heap_locks`]: the one line every `keep` stands in, as + /// when `kept` was behind one lock. + kept_one: Mutex<()>, /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec<bool>)>, + /// How many dynamic slots are free (changed under `next`'s lock): with + /// fewer than a table needs, the search is not made. Once the world + /// had taken them all, every later table of the frame searched every + /// slot before it was refused. + free: std::sync::atomic::AtomicU32, + /// The shortest table that found no run of free slots since slots were + /// last given back (changed under `next`'s lock; `u32::MAX`: none). + /// Until something is given back the free runs only shrink, so a table + /// of that length or longer is refused without the search. Enough + /// slots were free, but in pieces, and every such table walked the + /// whole ring before it was refused: 0.33 ms each with 131,072 slots, + /// 1.0 s of the recording threads in a frame that refused 3,143 (run + /// 45), under the lock all of them need. (A free run that lies across + /// the place the search starts from is seen by neither.) + too_long: std::sync::atomic::AtomicU32, + /// View heaps: the bytes per element of the buffer view at each title + /// slot, for shaders that pick a buffer by an index they compute + /// (`victory_shader::emit::SLOT_STRIDES`): an upload buffer of + /// `SLOT_STRIDES_COUNT` dwords, its GPU address and its mapping. + strides: Option<(ID3D12Resource, u64, usize)>, + /// Title slots holding buffer views. Such a view gets its host slot + /// (and its memory a host copy) only when something reads it: a draw + /// through a table, or [`HostHeap::buffer_slots`] for shaders that pick + /// buffers from the whole heap. + buffers: Mutex<std::collections::BTreeSet<u32>>, + /// Of those and of the slots that left the set: the ones written since + /// [`HostHeap::buffer_changes`] last took them. + changed: Mutex<std::collections::HashSet<u32>>, + /// Title slots holding a view of a texture the title may fill itself (a + /// placed texture, a texture object), with the frame from which they + /// are due: such a texture is uploaded when a draw reads it through a + /// table; one a shader picks by a computed index is brought up to date + /// from here ([`HostHeap::texture_slots_due`]). + textures: Mutex<TextureQueue>, + /// Per title slot, the frame (plus one; 0: never) in which a draw last + /// read it through a table, or made a table it lies in (with + /// [`TABLED_READ`] set if the draw read it). The draw that + /// reads such a slot brings its texture up to date itself and the slot + /// then leaves `textures`; a write of a slot that was a table's within + /// the last [`TABLED_FRAMES`] frames is due only [`TABLED_GRACE`] + /// frames later, by when its draw has read it. A title that builds a + /// table per draw writes thousands of texture views a frame into slots + /// only tables read (the title: some 2,500 a frame in its + /// opening cutscene, a few hundred textures over and over), and every + /// one of them stood in the queue of textures picked by index, ahead + /// of or behind the ones shaders do pick by index. + tabled: Vec<std::sync::atomic::AtomicU32>, + /// The title memory each placed texture view of this heap describes, + /// by slot and by address ([`Spans`]): which slots a newer view of + /// other memory there makes stale, and which to look at again when the + /// runtime maps, unmaps or writes memory ([`remapped`]). + placed: std::sync::Arc<Mutex<Spans>>, + /// [`NEXT_ID`]'s number for this heap ([`HostHeap::release`]). + id: u64, +} + +/// Diagnostics, since the last line (`crate::draw::tables_line`): the host +/// heap's locks as the recording threads and the others meet them. +/// 0, 1: calls of [`HostHeap::mirror`] not for a draw, for a draw; 2, 3: of +/// them, the calls that found the slot's record changed or gone; 4, 5: +/// takes of `made` that found it held, and the nanoseconds they waited +/// (every such wait is timed; a take that finds the lock free reads no +/// clock); 6, 7: of one call in 16 of each thread, the nanoseconds `made` +/// was held where the slot was as it was, where it had changed; 8, 9: the +/// calls so timed; 10: calls of `keep`; 11, 12: takes of `kept` that found +/// it held and their nanoseconds; 13, 14: the same for `next` +/// ([`HostHeap::dynamic`]). +#[cfg(feature = "diagnostics")] +pub(crate) static LOCKS: [std::sync::atomic::AtomicU64; 15] = [const { std::sync::atomic::AtomicU64::new(0) }; 15]; + +/// Diagnostics, since the last line (`crate::draw::tables_line`): why +/// [`HostHeap::dynamic`] refused a table. 0: fewer slots were free than it +/// asked (the ring is full: nothing to search); 1: enough were free but a +/// search for a table no longer had failed since the last release, so none +/// was made (`too_long`); 2: a search found no run of free slots that long +/// (the free slots lie apart). 3: tables that got a run lying across the +/// place the search starts from, which the search missed before it went on +/// past that place. +#[cfg(feature = "diagnostics")] +pub(crate) static DYNAMIC_WHY: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Diagnostics: the fewest free dynamic slots [`HostHeap::dynamic`] saw +/// since the last line (`u32::MAX`: it was not called). +#[cfg(feature = "diagnostics")] +pub(crate) static DYNAMIC_LOW: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(u32::MAX); + +/// Takes `lock`. Diagnostics builds count a take that finds it held in +/// [`LOCKS`]`[at]` and add the nanoseconds it then waits to `[at + 1]`. +#[cfg(feature = "diagnostics")] +fn locked<T>(lock: &Mutex<T>, at: usize) -> std::sync::MutexGuard<'_, T> { + use std::sync::atomic::Ordering::Relaxed; + match lock.try_lock() { + Ok(guard) => guard, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + let started = std::time::Instant::now(); + let guard = lock.lock().unwrap_or_else(|e| e.into_inner()); + LOCKS[at].fetch_add(1, Relaxed); + LOCKS[at + 1].fetch_add(started.elapsed().as_nanos() as u64, Relaxed); + guard + } + } +} + +#[cfg(not(feature = "diagnostics"))] +fn locked<T>(lock: &Mutex<T>, _: usize) -> std::sync::MutexGuard<'_, T> { + lock.lock().unwrap_or_else(|e| e.into_inner()) +} + +#[cfg(feature = "diagnostics")] +thread_local! { + /// This thread's calls of [`HostHeap::mirror`], for timing one in 16. + static MIRRORS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) }; +} + +/// Diagnostics: one call of [`HostHeap::mirror`] while it holds `made` +/// ([`LOCKS`] 0 to 3 and 6 to 9). Declared after the lock's guard, so it +/// is dropped before the lock is given back. +#[cfg(feature = "diagnostics")] +struct Held { + for_draw: bool, + started: Option<std::time::Instant>, + changed: std::cell::Cell<bool>, +} + +#[cfg(feature = "diagnostics")] +impl Held { + fn start(for_draw: bool) -> Held { + LOCKS[usize::from(for_draw)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let timed = MIRRORS.with(|n| { + n.set(n.get().wrapping_add(1)); + n.get().is_multiple_of(16) + }); + Held { + for_draw, + started: timed.then(std::time::Instant::now), + changed: std::cell::Cell::new(false), + } + } + + /// The slot's record was not the one the slot was made from. + fn slot_changed(&self) { + if !self.changed.replace(true) { + LOCKS[2 + usize::from(self.for_draw)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } +} + +#[cfg(feature = "diagnostics")] +impl Drop for Held { + fn drop(&mut self) { + if let Some(started) = self.started { + use std::sync::atomic::Ordering::Relaxed; + let at = usize::from(self.changed.get()); + LOCKS[6 + at].fetch_add(started.elapsed().as_nanos() as u64, Relaxed); + LOCKS[8 + at].fetch_add(1, Relaxed); + } + } +} + +/// The spans of every view heap made ([`HostHeap::placed`]), for the +/// texture code, which has no heap at hand ([`next_start`], +/// [`first_viewed`]). +static PLACED_SPANS: Mutex<Vec<std::sync::Weak<Mutex<Spans>>>> = Mutex::new(Vec::new()); + +/// Where the next texture placed inside `[start, end)` starts, past the +/// first bytes of the one at `start` ([`HEAD`]): what is there of the +/// texture at `start` ends there, whatever its full size. `None`: no view +/// in a slot shaders pick by index describes memory in that range. +pub(crate) fn next_start(start: u64, end: u64) -> Option<u64> { + let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).next_start(start, end)) + .min() +} + +/// The lowest level that a view of the placed texture at `start` shows, +/// over the slots shaders pick by index that hold one now. The title +/// views a texture from the first level it holds. `None`: no such slot. +pub(crate) fn first_viewed(start: u64) -> Option<u32> { + let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).first_viewed(start)) + .min() +} + +/// Levels on demand (`crate::tiles`): where the placed textures start +/// whose first level with memory changed since a texture pass last took +/// them ([`HostHeap::texture_views_remade`]). +static RESHOWN: Mutex<Vec<u64>> = Mutex::new(Vec::new()); + +/// Since the start, of [`HostHeap::texture_views_remade`]: view slots made +/// again, those of them made while a submission was in flight, and passes +/// put off because one was (`VICTORY_VIEWS_REMADE_QUIET=1`). +static VIEWS_REMADE: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// [`VIEWS_REMADE`]'s first two counts (slots made again; those made again +/// under a flight), for the seconds a device removal's report says. +pub(crate) fn views_remade() -> [u64; 2] { + [0, 1].map(|i| VIEWS_REMADE[i].load(std::sync::atomic::Ordering::Relaxed)) +} + +/// Whether view slots of textures with levels on demand are made again +/// only while no submission is in flight (`VICTORY_VIEWS_REMADE_QUIET=1`; +/// off by default: at every texture pass, as before). A texture then +/// shows its new level a pass or more later. After fork pull request +/// #1219, whose author lost the device with slots rewritten under lists +/// already sent; whether that is behind the losses here is not known. +fn views_remade_quiet() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEWS_REMADE_QUIET").is_some_and(|v| v == "1")) +} + +/// The first level with memory of the placed texture at `start` changed: +/// its slots are made again at the next texture pass. +pub(crate) fn levels_changed(start: u64) { + RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start); +} + +/// Levels on demand (`crate::tiles`): where the placed textures start +/// whose last upload left a held level without tiles (the card had no +/// room, or no heap could be had), and when (`crate::host::moment`). A +/// texture pass makes their slots due again once the card has room +/// ([`HostHeap::texture_slots_waiting`]). +static WAITING: Mutex<std::collections::BTreeMap<u64, u64>> = Mutex::new(std::collections::BTreeMap::new()); + +/// The last upload of the placed texture at `start` left a held level +/// without tiles. A texture picked by index is uploaded once and then +/// only when its memory is found changed, and its staging buffer goes +/// with the upload: without this the level stayed empty (the texture +/// blurred, or black if no level had tiles) for as long as the title left +/// its memory alone, where a texture refused for want of room is tried +/// again. +pub(crate) fn levels_waiting(start: u64) { + WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(start, crate::host::moment()); +} + +/// Texture quality (`crate::tiles::top_dropped`): where the placed textures +/// start whose last upload left their largest levels out while the card +/// was short of memory (drawn blurred). +static BLURRED: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new()); + +/// The placed texture at `start` was uploaded blurred ([`BLURRED`]). +pub(crate) fn blurred(start: u64) { + BLURRED.lock().unwrap_or_else(|e| e.into_inner()).insert(start); +} + +/// Try 6.3: where the placed textures start whose last upload left their +/// largest levels out for the texture rush (`crate::tiles::rush_levels`). +static RUSHED: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new()); + +/// The placed texture at `start` was uploaded without its largest levels +/// for the texture rush ([`RUSHED`]). +pub(crate) fn rushed(start: u64) { + RUSHED.lock().unwrap_or_else(|e| e.into_inner()).insert(start); +} + +/// Try 6.16: where the placed textures start that [`unrush`] made due to +/// get their detail back: their next detile leaves out no level for the +/// rush ([`unrushing`]), or a rush that starts meanwhile makes them soft +/// again and puts them back in [`RUSHED`] (the 6.15 report: the same +/// textures uploaded soft and sharp in turn, about once a second). +static UNRUSHING: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new()); + +/// Whether the texture at `start` is being made whole again after the +/// rush ([`UNRUSHING`]); asked by its detile, which takes it off the list. +pub(crate) fn unrushing(start: u64) -> bool { + let mut set = UNRUSHING.lock().unwrap_or_else(|e| e.into_inner()); + if set.is_empty() { + return false; + } + set.remove(&start) +} + +/// Once the texture rush is over, up to `most` textures it made soft are +/// made due as if their upload had left a level waiting: uploaded again, +/// with the levels texture quality allows now. Since the start: how many. +pub(crate) fn unrush(most: usize) -> u64 { + static UNRUSHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if crate::tiles::rush_levels() == 0 { + let starts: Vec<u64> = { + let mut rushed = RUSHED.lock().unwrap_or_else(|e| e.into_inner()); + let starts: Vec<u64> = rushed.iter().copied().take(most).collect(); + for start in &starts { + rushed.remove(start); + } + starts + }; + if !starts.is_empty() { + UNRUSHING.lock().unwrap_or_else(|e| e.into_inner()).extend(starts.iter().copied()); + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + for &start in &starts { + waiting.entry(start).or_insert(1); + } + UNRUSHED.fetch_add(starts.len() as u64, std::sync::atomic::Ordering::Relaxed); + } + } + UNRUSHED.load(std::sync::atomic::Ordering::Relaxed) +} + +/// While texture quality leaves nothing out (the card has memory to spare +/// again), up to `most` textures uploaded blurred are made due as if their +/// upload had left a level waiting: uploaded again, with every level. They +/// stayed blurred for the rest of the run. Since the start: how many. +pub(crate) fn sharpen(most: usize) -> u64 { + static SHARPENED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if crate::tiles::top_dropped() == 0 { + let starts: Vec<u64> = { + let mut blurred = BLURRED.lock().unwrap_or_else(|e| e.into_inner()); + let starts: Vec<u64> = blurred.iter().copied().take(most).collect(); + for start in &starts { + blurred.remove(start); + } + starts + }; + if !starts.is_empty() { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + for &start in &starts { + waiting.entry(start).or_insert(1); + } + SHARPENED.fetch_add(starts.len() as u64, std::sync::atomic::Ordering::Relaxed); + } + } + SHARPENED.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Title memory by the placed texture views that describe it: per span of +/// memory (its start, its end at full size) the title slots holding a +/// view of a texture that takes exactly that span. A console title need +/// not clear a descriptor when it streams a texture out, so a newer view +/// that cannot be there together with an older one is all that says the +/// older one is stale ([`Rule`] says when that is). Views of one span with +/// different descriptions (the formats of one family, say) are one +/// texture's. +/// +/// Spans may overlap: a texture's smallest levels lie at the start of its +/// memory, and a title that holds only those puts the next texture where +/// the larger ones would be (the title: three 512x256 textures +/// of 0x2c000 bytes each whose starts are 0x2000 and 0x4000 apart, all +/// three read by the same frame's draws, run 188). What is there of a +/// texture ends where the next one starts. +/// No host heap is needed, so it is tested without one. +#[derive(Default)] +pub(crate) struct Spans { + /// When a newer view makes an older one stale. + rule: Rule, + by_start: std::collections::BTreeMap<u64, (u64, std::collections::BTreeSet<u32>)>, + by_slot: std::collections::HashMap<u32, u64>, + /// The level each slot's view starts at ([`Spans::shows`]). + first: std::collections::HashMap<u32, u32>, + /// The bytes a placed texture takes, by resource description: worked + /// out once for each (a title writes the views of a few thousand + /// descriptions, thousands of times a frame). + sizes: std::collections::HashMap<[u32; 14], Option<u64>>, +} + +/// When a view the title writes makes an older view of other memory stale. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Rule { + /// When it starts where the older one starts: at the same address + /// with another length, or within the older one's first [`HEAD`] + /// bytes (or the older within its own). No two textures share the + /// block of their smallest levels. A view that only reaches into the + /// address range of an older texture's larger levels says nothing. + #[default] + Start, + /// Whenever their spans at full size overlap (the rule until run + /// 188, where it made null the slots of textures packed as above: + /// each view written took its neighbours out of the queue and off the + /// card, for good). `VICTORY_STALE_TEXTURES=overlap`. + Overlap, + /// Never; a view that would be stale under [`Rule::Overlap`] is left + /// out of the spans instead. `VICTORY_STALE_TEXTURES=0`, as before. + Never, +} + +/// The first bytes of a placed texture that are its own under +/// [`Rule::Start`]: the 4 KiB block its smallest levels share. (Of 129 +/// pairs of overlapping neighbours in the listings of runs 188 and 189, +/// none starts closer than 0x2000 to the one before it.) +const HEAD: u64 = 4096; + +impl Spans { + /// The bytes of title memory a placed texture with the resource + /// description `desc` takes (`crate::resource::placed_bytes`). + fn bytes(&mut self, desc: &[u32; 14]) -> Option<u64> { + if let Some(&known) = self.sizes.get(desc) { + return known; + } + let bytes = crate::resource::placed_bytes(desc); + self.sizes.insert(*desc, bytes); + bytes + } + + /// The starts of the spans that overlap `[start, end)`, each taken to + /// end where the next one starts: the last span that starts before + /// `start`, if it reaches past it at full size, and every span that + /// starts inside. + fn overlapping(&self, start: u64, end: u64) -> Vec<u64> { + let before = self + .by_start + .range(..start) + .next_back() + .filter(|(_, span)| span.0 > start) + .map(|(at, _)| *at); + before.into_iter().chain(self.by_start.range(start..end).map(|(at, _)| *at)).collect() + } + + /// Slot `index` holds a view of a texture in `[start, end)`. `newer`: + /// the title wrote it now, so the slots whose views cannot be there + /// with it ([`Rule`]) are stale: they are returned, and forgotten. + /// Otherwise (a draw made the slot from what it held), and under + /// [`Rule::Never`], a view that clashes with other spans is left out. + fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec<u32> { + let same = |span: Option<&(u64, std::collections::BTreeSet<u32>)>| span.is_some_and(|s| s.0 == end); + if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) { + return Vec::new(); + } + self.forget(index); + if end <= start { + return Vec::new(); + } + let rule = self.rule; + // The spans the view cannot be there with. + let clashing: Vec<u64> = match rule { + Rule::Start => self + .by_start + .range(start.saturating_sub(HEAD - 1)..start.saturating_add(HEAD)) + .map(|(at, _)| *at) + .collect(), + Rule::Overlap | Rule::Never => self.overlapping(start, end), + }; + let mut stale = Vec::new(); + for at in clashing { + if at == start && same(self.by_start.get(&at)) { + continue; + } + if !newer || rule == Rule::Never { + return stale; + } + if let Some((old_end, slots)) = self.by_start.remove(&at) { + // The first of them are said with both spans, to tell a + // replacement from a neighbour in one launch's log. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 48 { + tracing::info!( + slot = index, + start = format_args!("{start:#x}"), + end = format_args!("{end:#x}"), + stale_start = format_args!("{at:#x}"), + stale_end = format_args!("{old_end:#x}"), + stale_slots = slots.len(), + rule = ?rule, + "a placed texture view makes older views of other memory stale" + ); + } + for slot in slots { + self.by_slot.remove(&slot); + stale.push(slot); + } + } + } + self.by_start.entry(start).or_insert_with(|| (end, Default::default())).1.insert(index); + self.by_slot.insert(index, start); + stale + } + + /// The view in slot `index` starts at level `first` of its texture. + fn shows(&mut self, index: u32, first: u32) { + self.first.insert(index, first); + } + + /// The lowest level a view of the texture at `start` starts at. + fn first_viewed(&self, start: u64) -> Option<u32> { + self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied() + } + + /// The first span that starts inside `[start, end)` past the first + /// [`HEAD`] bytes of it. + fn next_start(&self, start: u64, end: u64) -> Option<u64> { + self.by_start.range(start.saturating_add(HEAD)..end).next().map(|(at, _)| *at) + } + + /// The slots that hold a view of the texture at `start`. + fn slots_at(&self, start: u64) -> Vec<u32> { + self.by_start.get(&start).map(|span| span.1.iter().copied().collect()).unwrap_or_default() + } + + /// Slot `index` holds no placed texture view any more. + fn forget(&mut self, index: u32) { + self.first.remove(&index); + let Some(start) = self.by_slot.remove(&index) else { + return; + }; + if let Some(span) = self.by_start.get_mut(&start) { + span.1.remove(&index); + if span.1.is_empty() { + self.by_start.remove(&start); + } + } + } + + /// The slots whose texture's memory overlaps `[start, end)`. + fn slots_in(&self, start: u64, end: u64) -> Vec<u32> { + self.overlapping(start, end) + .iter() + .filter_map(|at| self.by_start.get(at)) + .flat_map(|span| span.1.iter().copied()) + .collect() + } + + /// The slots of the textures that hold bytes of `[start, end)`, for a + /// write there: as [`Spans::slots_in`], but when a texture starts at + /// `start` itself the one before it is left out (it ends where that + /// one starts, and a request that fills a texture begins at its first + /// byte: `slots_in` would name its neighbour with every such write). + fn slots_holding(&self, start: u64, end: u64) -> Vec<u32> { + if end <= start { + return Vec::new(); + } + let before = if self.by_start.contains_key(&start) { + None + } else { + self.by_start.range(..start).next_back().filter(|(_, span)| span.0 > start).map(|(_, span)| span) + }; + before + .into_iter() + .chain(self.by_start.range(start..end).map(|(_, span)| span)) + .flat_map(|span| span.1.iter().copied()) + .collect() + } +} + +/// Title memory written behind the guards' back whose bytes are there +/// (DirectStorage's reads into physical pages, at the addresses the title +/// has them mapped; `crate::watch::title_memory_written`), since a texture +/// pass last took the ranges ([`page_written`]). Kept apart from +/// [`REMAPPED`] so that what such writes do is counted by itself. +static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new()); + +/// Since the start: such ranges kept for a pass; ranges dropped because no +/// pass took them; slots of placed textures that held bytes of them when a +/// pass took them; of those, the slots whose texture had been uploaded +/// before the write (out of the queue, or in it after an upload): they are +/// the ones that kept the bytes from before, and the ones made due when +/// `VICTORY_PAGE_WRITES` asks for it. +pub(crate) static PAGE_WRITES: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Frames from the pass that takes a written range to the look at its +/// slots: the levels of one texture arrive in a few requests, and a look +/// two frames on takes those of the next frame with it. +const PAGE_WRITE_AFTER: u64 = 2; + +/// The bytes of a write the guards do not see are in title memory `[at, +/// at + len)`: the placed textures there changed with no descriptor +/// written and nothing mapped. Kept for the next texture pass +/// ([`HostHeap::texture_slots_page_written`]), as [`remapped`] keeps its +/// ranges; locks one mutex and calls nothing. +pub(crate) fn page_written(at: usize, len: usize) { + use std::sync::atomic::Ordering::Relaxed; + /// Ranges kept until a pass takes them (as many as [`remapped`] keeps). + const MOST: usize = 1 << 18; + let (start, end) = (at as u64, at.saturating_add(len) as u64); + if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) { + return; + } + let mut ranges = PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + PAGE_WRITES[0].fetch_add(1, Relaxed); + if let Some(last) = ranges.last_mut() + && last.1 == start + { + last.1 = end; + return; + } + if ranges.len() >= MOST { + PAGE_WRITES[1].fetch_add(ranges.len() as u64, Relaxed); + compact(&mut ranges, MOST); + } + ranges.push((start, end)); +} + +/// Title memory the runtime mapped, unmapped or is about to write since a +/// texture pass last took the ranges ([`remapped`]). +static REMAPPED: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new()); + +/// The lowest start and the highest end of any span of [`Spans`] so far +/// (the start is `u64::MAX` until there is one): what the runtime does to +/// memory outside is none of the texture pass's business. +static SPANNED: [std::sync::atomic::AtomicU64; 2] = [ + std::sync::atomic::AtomicU64::new(u64::MAX), + std::sync::atomic::AtomicU64::new(0), +]; + +/// Since the start: slots whose view a newer view of other memory there +/// made stale; ranges of memory noted as mapped, unmapped or written; +/// ranges dropped because no pass took them; slots made due by such +/// ranges; and made slots whose memory was found unmapped (made null). +pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] = + [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// When a view the title writes makes older views of other memory stale +/// ([`Rule`]): where it starts in the block of their smallest levels, by +/// default; `VICTORY_STALE_TEXTURES=0`: never, as before; +/// `VICTORY_STALE_TEXTURES=overlap`: wherever their spans overlap, the rule +/// until run 188. +fn stale_rule() -> Rule { + static RULE: std::sync::OnceLock<Rule> = std::sync::OnceLock::new(); + *RULE.get_or_init(|| match std::env::var("VICTORY_STALE_TEXTURES").as_deref() { + Ok("0") => Rule::Never, + Ok("overlap") => Rule::Overlap, + _ => Rule::Start, + }) +} + +/// The runtime mapped or unmapped title memory `[at, at + len)`, or is +/// about to write it through the kernel (`crate::watch`): the placed +/// textures there may have arrived, gone, or changed with no descriptor +/// written. The range is kept for the next texture pass +/// ([`HostHeap::texture_slots_remapped`]). Called with the runtime's own +/// locks held: this locks one mutex of its own and calls nothing. +pub(crate) fn remapped(at: usize, len: usize) { + use std::sync::atomic::Ordering::Relaxed; + /// Ranges kept until a pass takes them. (Try 6.13, from + /// edsuuu/VI-BR-PORT 47fa23c9, by myokex, victory-amd 4436f8f1: a + /// world's first minutes note tens of thousands between two passes, and + /// at 32,768 the list overflowed and was dropped whole: textures streamed + /// into placed memory were not looked at again until their slots fell + /// due by themselves, blurry or missing meanwhile. 4 MB at most.) + const MOST: usize = 1 << 18; + let (start, end) = (at as u64, at.saturating_add(len) as u64); + if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) { + return; + } + let mut ranges = REMAPPED.lock().unwrap_or_else(|e| e.into_inner()); + STALE[1].fetch_add(1, Relaxed); + // Pages are mapped one after the other. + if let Some(last) = ranges.last_mut() + && last.1 == start + { + last.1 = end; + return; + } + if ranges.len() >= MOST { + // No pass runs (no shader that picks textures by index is bound): + // the slots there are looked at when they are due, as before. + STALE[2].fetch_add(ranges.len() as u64, Relaxed); + compact(&mut ranges, MOST); + } + ranges.push((start, end)); +} + +/// A full list of changed ranges made room in, keeping every change: those +/// that touch or overlap made one, then, while more than half of `most` are +/// left, each two neighbours one range over both (a pass looks at a little +/// more memory than changed). Clearing the list here instead (as before) let +/// a texture uploaded already keep old bytes after its memory changed: the +/// intro's video frames went back during the streaming bursts. Try 6.13, +/// from edsuuu/VI-BR-PORT 87dc3075 (after fxceless/victory-fork PR #896). +fn compact(ranges: &mut Vec<(u64, u64)>, most: usize) { + join(ranges); + while ranges.len() > most / 2 { + let wide: Vec<(u64, u64)> = ranges.chunks(2).map(|pair| (pair[0].0, pair[pair.len() - 1].1)).collect(); + *ranges = wide; + } +} + +/// Ranges of memory, those that touch made one (DexNom/VIctory 921d8d3b: +/// several threads map and write, some 5,000 ranges a frame, the same +/// textures' over and over, and each was looked up). +fn join(ranges: &mut Vec<(u64, u64)>) { + ranges.sort_unstable(); + ranges.dedup_by(|next, last| { + if next.0 > last.1 { + return false; + } + last.1 = last.1.max(next.1); + true + }); +} + +/// Frames for which a slot a draw read through a table counts as a table's +/// slot ([`HostHeap::tabled`]). +const TABLED_FRAMES: u64 = 240; + +/// Frames a write of a table's slot waits in the queue for the draw that +/// reads it, before the slot is taken for one shaders pick by index. +/// Frames as `crate::frame::current` counts them: in its opening cutscene +/// The title begins two or three of them per frame it presents +/// (435 begun in the 353 s of run 52's, for some 140 presented). +const TABLED_GRACE: u64 = 8; + +/// In [`HostHeap::tabled`]: a draw read the slot in that frame. +const TABLED_READ: u32 = 1 << 31; + +/// Since the start: writes of texture views into slots that count as a +/// table's (due later), and slots that left the queue because a draw read +/// them through a table. +pub(crate) static TABLED_WRITES: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether slots draws read through tables leave the queue of textures +/// picked by index; `VICTORY_TABLED_TEXTURES=1` keeps them in it as +/// before. +fn tabled_out() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_TEXTURES").is_none_or(|v| v != "1")) +} + +/// What the queue of textures picked by index knows of a title slot. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Waiting { + /// The frame from which the slot is due. + due: u64, + /// The frame it was written in. + written: u64, + /// Which write of the queue put it here: the pass hands it back with + /// what it did, so a slot written again meanwhile stays as written. + write: u64, + /// Looks in a row that found nothing to upload (its memory not mapped, + /// or no more of it than at the last upload). + looks: u8, + /// Bytes of its memory that were mapped when it was last uploaded + /// without all of it there; 0: not uploaded yet. + mapped: u64, + /// For a slot uploaded whole and looked at again + /// ([`TextureQueue::recheck`]): where its memory is (address, bytes), + /// the fingerprint it had at the upload, how many looks found it + /// unchanged, and the frame of the upload. A fingerprint of 0: none. + checked: (u64, u64, u64, u8, u64), +} + +thread_local! { + /// This thread is inside [`HostHeap::publish`]. + static PUBLISHING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// The queue of title slots whose texture view waits to be brought up to +/// date for shaders that pick textures by index: which are due, and in +/// which order (no host heap needed, so it is tested without one). +#[derive(Default)] +pub(crate) struct TextureQueue { + slots: std::collections::BTreeMap<u32, Waiting>, + writes: u64, + /// Slots held back because the card had no room for the host copy + /// they need ([`TextureQueue::hold`]), each with the write it was + /// held as. + held: std::collections::BTreeMap<u32, u64>, +} + +impl TextureQueue { + /// A texture view was written into slot `index` in `frame`, due from + /// frame `due`. `seen`: it was not written, a draw or the pass made + /// the host slot from a view the queue may hold already, which then + /// stays as it is. + fn written(&mut self, index: u32, frame: u64, due: u64, seen: bool) { + if seen && self.slots.contains_key(&index) { + return; + } + self.writes += 1; + let write = self.writes; + self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + } + + fn remove(&mut self, index: u32) { + self.slots.remove(&index); + } + + /// Up to `max` slots due at `frame`, each with its write number, in + /// the order to serve them: + /// - first the ones looked at before (their memory was not mapped, or + /// only part of it): the look is a query, and memory that has + /// arrived since is what the title streamed in last; + /// - then the others, the newest write first and the oldest next, in + /// turns: slot order served the low slots of a backlog of + /// 25,000-40,000 while the textures of the shot on screen waited + /// (run 52: 98% of the drawn pixels had no colour texture in the + /// first 3D frames). + fn due(&self, frame: u64, max: usize) -> Vec<(u32, u64)> { + let mut again: Vec<(u64, u32, u64)> = Vec::new(); + let mut fresh: Vec<(u64, u32, u64)> = Vec::new(); + for (&index, w) in self.slots.iter().filter(|(_, w)| w.due <= frame) { + let class = if w.looks > 0 || w.mapped > 0 { &mut again } else { &mut fresh }; + class.push((w.written, index, w.write)); + } + // By the number of the write, counted over the run. + let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2); + again.sort_unstable_by(newest_first); + fresh.sort_unstable_by(newest_first); + let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect(); + let (mut new, mut old) = (0, fresh.len()); + while new < old && order.len() < max { + order.push((fresh[new].1, fresh[new].2)); + new += 1; + if new < old && order.len() < max { + old -= 1; + order.push((fresh[old].1, fresh[old].2)); + } + } + order.truncate(max); + order + } + + /// The entry of `index` if it is still the write the pass was handed. + fn same(&mut self, index: u32, write: u64) -> Option<&mut Waiting> { + self.slots.get_mut(&index).filter(|w| w.write == write) + } + + /// Slot `index` is up to date: out of the queue until written again. + fn done(&mut self, index: u32, write: u64) { + if self.same(index, write).is_some() { + self.slots.remove(&index); + } + } + + /// Nothing to upload at slot `index` now: looked at again after 1, 2, + /// 4, ... frames, at most `most`. + fn later(&mut self, index: u32, write: u64, frame: u64, most: u64) { + if let Some(w) = self.same(index, write) { + w.due = frame + (1u64 << w.looks.min(16)).min(most.max(1)); + w.looks = w.looks.saturating_add(1); + } + } + + /// The card has no room for the host copy slot `index` needs: it is + /// not handed out again before frame `due`, or before the card has + /// room again ([`TextureQueue::room`]). Nothing else of it changes: it + /// is not a slot "waiting for its memory", and when it is due it has + /// its old place among the slots never looked at. (It stayed due, so + /// every pass on a full card looked at the same few hundred slots + /// again and stopped there, and the slots behind them were never + /// reached: the ones whose host copy exists and only wants bringing up + /// to date, and the ones whose memory went, which is what lets host + /// copies go and makes room.) + fn hold(&mut self, index: u32, write: u64, due: u64) { + if let Some(w) = self.same(index, write) { + w.due = w.due.max(due); + self.held.insert(index, write); + } + } + + /// The card has room again at `frame`: the slots held back for lack of + /// it are due now, as if they had never been held. Returns how many. + fn room(&mut self, frame: u64) -> usize { + let held = std::mem::take(&mut self.held); + let mut back = 0; + for (index, write) in held { + if let Some(w) = self.same(index, write) { + w.due = w.due.min(frame); + back += 1; + } + } + back + } + + /// Slot `index` was uploaded with `mapped` bytes of its memory there, + /// not all of it: looked at again from frame `due`. + fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) { + if let Some(w) = self.same(index, write) { + (w.due, w.looks, w.mapped) = (due, 0, mapped.max(1)); + } + } + + /// Slot `index` was uploaded whole from memory `at` (address, bytes) + /// with fingerprint `print`: looked at again from frame `due`, for a + /// title that fills a texture's memory after it wrote the view (the + /// `looks`-th such look; `uploaded` is the upload's frame). + #[allow(clippy::too_many_arguments)] + fn recheck(&mut self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64) { + if let Some(w) = self.same(index, write) { + (w.due, w.looks, w.mapped) = (due, 1, 0); + w.checked = (at.0, at.1, print, looks, uploaded); + } + } + + /// Of the slots `indices`, the ones that wait for their upload, due or + /// not and held or not, each with its write number as + /// [`TextureQueue::due`] hands it out: for a pass that has to bring + /// those very slots up to date now (`crate::draw::State::bake_sources`). + /// Not the ones uploaded whole that wait for another look. + fn queued(&self, indices: &[u32]) -> Vec<(u32, u64)> { + indices + .iter() + .filter_map(|&index| self.slots.get(&index).filter(|w| w.checked.2 == 0).map(|w| (index, w.write))) + .collect() + } + + /// Puts the slots `indices` into the queue as written in `frame` and + /// due at once, unless they wait in it for their upload already: for + /// texture views a shader is about to pick by index whose host slot + /// shows nothing and which nothing would bring up to date (a view the + /// spans took for stale when the title wrote a newer one of memory it + /// clashes with, [`Spans::note`], and which the title reads all the + /// same). One uploaded whole that waits for another look is put back + /// too: that look would find its memory unchanged and leave it. + fn requeue(&mut self, indices: &[u32], frame: u64) { + for &index in indices { + if self.slots.get(&index).is_none_or(|w| w.checked.2 != 0) { + self.written(index, frame, frame, false); + } + } + } + + /// What [`TextureQueue::recheck`] noted of slot `index`, if it is + /// waiting for such a look. + fn checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { + self.slots.get(&index).map(|w| w.checked).filter(|c| c.2 != 0) + } + + /// The memory slot `index`'s texture lies in was mapped, unmapped or + /// written in `frame`: the slot is looked at from frame `due` as one + /// written now, whatever was known of it (a pass at work on it does + /// not take it out). + fn changed(&mut self, index: u32, frame: u64, due: u64) { + self.writes += 1; + let write = self.writes; + let due = self.slots.get(&index).map_or(due, |w| w.due.min(due)); + self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + } + + /// Bytes of slot `index`'s memory that were mapped at its last upload + /// (0: not uploaded, or all of it was). + fn mapped(&self, index: u32) -> u64 { + self.slots.get(&index).map_or(0, |w| w.mapped) + } + + /// For the frame line: slots in the queue; of them due at `frame`; + /// waiting for their memory (looked at, never uploaded); uploaded in + /// part; and the frames the oldest due one has waited since its write. + fn census(&self, frame: u64) -> [u64; 5] { + let mut c = [self.slots.len() as u64, 0, 0, 0, 0]; + for w in self.slots.values() { + if w.mapped > 0 { + c[3] += 1; + } else if w.looks > 0 { + c[2] += 1; + } + if w.due <= frame { + c[1] += 1; + c[4] = c[4].max(frame.saturating_sub(w.written)); + } + } + c + } +} + +/// Whether `view` is of a texture the title may fill itself: a texture it +/// placed in memory, or a texture object. +pub(crate) fn is_texture_view(view: &View) -> bool { + match view { + View::Placed(false, resource, _) => resource[0] != 1, + View::Shader(r, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_none(), + _ => false, + } +} + +/// Buffer views left null because the host would refuse them +/// ([`buffer_view_ok`]), since the start. +pub(crate) static REFUSED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Buffer views of no elements, left null: what the console's view does +/// too (reads give zero, writes go nowhere), so not counted as refused. +pub(crate) static EMPTY_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Raw shader views not on 16 bytes made as typed 32-bit views of the same +/// dwords ([`raw_as_typed`]). +pub(crate) static RAW_TYPED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// `VICTORY_RAW_TYPED=1`: a raw shader view whose first dword is not on 16 +/// bytes (the console takes any dword, the host refuses it) is made as a +/// typed R32_UINT view of the same dwords instead of left null. +/// shortcut: off by default. A shader declares the view raw; reading a +/// typed descriptor through it is what NVIDIA's buffer descriptors allow +/// but D3D12 leaves undefined, so it is untried on other cards. +fn raw_as_typed() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RAW_TYPED").is_some_and(|v| v == "1")) +} + +/// Whether the host device is gone, and why (the first time it is asked +/// after that): for passes that make many views, to name the one that did +/// it. +pub(crate) fn device_removed() -> Option<String> { + let host = host()?; + // SAFETY: a plain query. + let reason = unsafe { host.device.GetDeviceRemovedReason() }; + reason.err().map(|e| e.to_string()) +} + +/// Writes of title view-heap slots with a placed texture view and with a +/// view of a texture object, since the start (diagnostic counts). +/// Slots asked again by [`HostHeap::texture_slots_blank`] since the start: +/// shown with no level judged held (Z), null in no queue (N). +#[cfg(feature = "diagnostics")] +pub(crate) static REASKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The packed word of the table of strides for `view`: its stride and, for a +/// typed buffer view of an integer format, `victory_shader::emit::VIEW_INTEGER` +/// (and `VIEW_SIGNED`), whose d16 accesses keep their bits (VIctory 4243a96a, +/// avatarmanz 9a6c829d; codec_d, cool_fox f4b48ad). +fn view_stride_word(view: &View) -> u32 { + let (stride, kind) = view_stride_and_kind(view); + stride.unwrap_or(0) | kind +} + +/// Bytes per element of a buffer view, as the console's descriptor holds +/// them for indexed reads (structured: the stride; raw: 1, the index is the +/// byte; typed: the format's; `None` if `view` is not a buffer view), and +/// the integer kind bits of a typed buffer view. +fn view_stride_and_kind(view: &View) -> (Option<u32>, u32) { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + let Some((stride, raw, format)) = view_elements(view) else { + return (None, 0); + }; + let bytes = if stride > 0 { + stride + } else if raw { + 1 + } else { + crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32) + }; + let kind = if stride == 0 && !raw { + match format { + 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => VIEW_INTEGER, + 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => VIEW_INTEGER | VIEW_SIGNED, + _ => 0, + } + } else { + 0 + }; + (Some(bytes), kind) +} + +/// A buffer view's structure stride, whether it is raw, and its format; +/// `None` if `view` is not a buffer view. +fn view_elements(view: &View) -> Option<(u32, bool, u32)> { + const BUFFER: u32 = 1; + let (words, unordered): (&[u32; 10], bool) = match view { + View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), + View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true), + View::Placed(unordered, resource, d) if resource[0] == BUFFER => { + (d[..10].try_into().ok()?, *unordered) + } + _ => return None, + }; + // SAFETY: buffer views' union members. + let (stride, raw, format) = unsafe { + if unordered { + let d = uav_desc(words); + let b = d.Anonymous.Buffer; + (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format) + } else { + let d = srv_desc(words); + let b = d.Anonymous.Buffer; + (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format) + } + }; + Some((stride, raw, format.0 as u32)) } /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for @@ -52,77 +1186,78 @@ pub(crate) fn near_heaps(va: u64) -> String { } else if va < start + bytes { format!("inside, slot {}", (va - start) / step) } else { - format!( - "{:#x} past its end (slot {})", - va - start - bytes, - (va - start) / step - ) + format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step) }; text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}")); } text } -/// The host's limit for shader-visible view heaps on every resource -/// binding tier, unless the device reports a larger one -/// ([`max_view_heap`]). NVIDIA creates a larger heap without an error, -/// but the runtime refuses it (debug layer #645) and the device is removed -/// once it is used (upstream #735). +/// The host's limit for shader-visible view heaps on resource binding +/// tiers 1 and 2; tier 3 hardware may take more. const PORTABLE_VIEWS: u32 = 1_000_000; -/// The largest shader-visible view heap the device takes: what -/// `D3D12_OPTIONS19` reports (Agility runtimes), else [`PORTABLE_VIEWS`]. -fn max_view_heap(host: &Host) -> u32 { - let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); - // SAFETY: the query writes its own structure of the given size. - let asked = unsafe { - host.device.CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS19, - (&raw mut options).cast(), - size_of_val(&options) as u32, - ) - }; - match asked { - Ok(()) => options.MaxViewDescriptorHeapSize.max(PORTABLE_VIEWS), - Err(_) => PORTABLE_VIEWS, - } -} - -/// The view heaps to try for `count` title slots on a device that takes -/// `limit` views, in order: (heap size, title slots, dynamic slots). The -/// full dynamic range always: on top of every title slot where that fits, -/// else the title's slots are cut to make room for it (shortcut: -/// descriptors past the host's limit are left out; a title that reaches -/// them needs remapping). A capped heap with 2^16 dynamic slots ran dry in -/// every world submission and dropped most indirect draws, where 2^18 -/// dropped none (upstream #747: RTX 4070 Ti, 5060 Ti, 5070 Ti). Then, if -/// the host refuses that, the smaller range. None is over `limit`. -fn view_heap_sizes(count: u32, limit: u32) -> Vec<(u32, u32, u32)> { - let planned = |extra: u32| match count.checked_add(extra) { - Some(size) if size <= limit => (size, count, extra), - _ => (limit, limit.saturating_sub(extra), extra), - }; - vec![planned(DYNAMIC), planned(MIN_DYNAMIC)] +/// The size of every host view heap on a host that takes more than +/// [`PORTABLE_VIEWS`] (AMD): the title's heap (a little over 1,000,000 +/// views in the retail game) plus [`DYNAMIC`] fits with room to spare, and +/// the last slot is the null slot every view index at or past it reads. +const UNCAPPED_VIEWS: u32 = 1 << 21; + +/// Picks, once, the null slot at the end of every host view heap and tells +/// the translator now (`set_view_heap_limit`) instead of when the title's +/// heap is made: a shader keeps the limit it was translated with, and the +/// title makes 25 pipelines (their shaders translated at once) before it +/// makes its view heap. Called before a shader is translated and before a +/// view heap is made. +/// +/// Every host clamps. A host that caps view heaps at [`PORTABLE_VIEWS`] +/// (NVIDIA) hung on a view index past the heap; one that does not (AMD +/// RDNA3, RX 7900 XT) took a page fault and removed the device on entering +/// the world: a compute program read view slot 16,777,088 (0xffff80) of a +/// heap of 1,507,328, past its end. Unclamped, that index is undefined on +/// any host. +pub(crate) fn probe_view_limit() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let Some(host) = host() else { return }; + let fits = |count: u32| { + // SAFETY: plain heap creation; the heap is released at once. + let made: windows::core::Result<ID3D12DescriptorHeap> = unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + }; + made.is_ok() + }; + let views = if fits(UNCAPPED_VIEWS) { + UNCAPPED_VIEWS + } else { + PORTABLE_VIEWS + }; + tracing::info!( + views, + "host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on" + ); + victory_shader::emit::set_view_heap_limit(views - 1); + }); } /// Slots past the title's in a view heap, for tables a draw needs made /// afresh (constant buffers copied per draw). A list holds the slots it /// took until it is reset (its submissions have run) or released. -/// 2^16 ran out seconds into the world (every world run on an RX 9070 XT, -/// each a device removal shortly after; upstream #59). -const DYNAMIC: u32 = 1 << 18; - -/// The dynamic slots of a view heap the host refused with [`DYNAMIC`]: a -/// last resort, too few for the world (upstream #747). -const MIN_DYNAMIC: u32 = 1 << 16; - -/// The host's limit for shader-visible sampler heaps, on every binding -/// tier. -const SAMPLERS: u32 = D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE; - -/// Dynamic slots of a sampler heap capped at [`SAMPLERS`], for tables -/// reaching past the title slots it keeps. -const SAMPLER_DYNAMIC: u32 = 256; +/// 2^16 ran out in the world ("no free dynamic descriptor slots", run 11; +/// upstream PR #336 takes 2^18). On a host heap capped at 1,000,000 views +/// (NVIDIA) these come out of the title's slots, whose highest seen is +/// about 720,000: 2^17 left 868,000 of them, and ran out in the opening +/// cutscene (a frame asks for up to 16,000 tables while the frame before +/// still holds its own; a draw refused its table read slots never made +/// for it, and the card stopped within frames). 2^18 leaves 737,000; a +/// table past them is made afresh in these slots like any other. +pub(crate) const DYNAMIC: u32 = 1 << 18; impl HostHeap { pub(crate) fn new(sampler: bool, count: u32) -> Option<Self> { @@ -144,305 +1279,978 @@ impl HostHeap { }) } }; - if sampler && count > SAMPLERS { - // shortcut: samplers past the host's limit are left out; tables - // reaching them are made afresh in the dynamic slots. - tracing::warn!(count, "host sampler heap capped at {SAMPLERS}"); - let heap = match make(SAMPLERS) { - Ok(heap) => heap, + let extra = if sampler { 0 } else { DYNAMIC }; + // A view heap ends at the null slot shaders clamp view indices to + // (`probe_view_limit`), whatever the title's own count: the title's + // slots, then the dynamic ones, then null up to and with that slot. + if !sampler { + probe_view_limit(); + } + let null = if sampler { + 0 + } else { + victory_shader::emit::view_heap_limit() + }; + let (heap, count, size) = if null == 0 { + match make(count + extra) { + Ok(heap) => (heap, count, count + extra), Err(e) => { tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); return None; } + } + } else { + let size = null + 1; + let fitted = if count + extra <= null { + count + } else { + // shortcut: descriptors past the host's limit are left out; a title that reaches + // them needs remapping. They read the null slot instead. + tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot"); + null - extra }; - return Self::with( - host, - heap, - kind, - SAMPLERS - SAMPLER_DYNAMIC, - SAMPLER_DYNAMIC, - ); + match make(size) { + Ok(heap) => (heap, fitted, size), + Err(e) => { + tracing::warn!(error = %e, count, size, "no host view heap"); + return None; + } + } + }; + // SAFETY: a live heap. + let (cpu, step) = unsafe { + ( + heap.GetCPUDescriptorHandleForHeapStart().ptr, + host.device.GetDescriptorHandleIncrementSize(kind), + ) + }; + tracing::debug!(count, sampler, "host descriptor heap"); + // SAFETY: a live shader-visible heap. + let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; + GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( + gpu, + u64::from(size) * u64::from(step), + u64::from(step), + sampler, + )); + let strides = (!sampler) + .then(|| { + let bytes = u64::from(victory_shader::emit::SLOT_STRIDES_COUNT) * 4; + let (buffer, data) = host.upload_buffer(bytes)?; + // SAFETY: the buffer's whole mapping; a live buffer. + let gpu = unsafe { + std::ptr::write_bytes(data, 0, bytes as usize); + buffer.GetGPUVirtualAddress() + }; + crate::host::name(&buffer, || "element strides by view heap slot".to_owned()); + Some((buffer, gpu, data as usize)) + }) + .flatten(); + let h = HostHeap { + buffer_frame: std::sync::atomic::AtomicU64::new(u64::MAX), + id: NEXT_ID.fetch_add(1, Ordering::Relaxed), + heap, + cpu, + step, + count, + dynamic: extra, + sampler, + made: Mutex::new(vec![0; count as usize]), + made_now: (0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), + copied: Mutex::new(Vec::new()), + kept: (0..KEPT_PIECES) + .map(|_| Mutex::new(vec![None; (count + extra).div_ceil(KEPT_PIECES) as usize])) + .collect(), + kept_one: Mutex::new(()), + next: Mutex::new((0, vec![false; DYNAMIC as usize])), + free: std::sync::atomic::AtomicU32::new(DYNAMIC), + too_long: std::sync::atomic::AtomicU32::new(u32::MAX), + strides, + buffers: Mutex::default(), + changed: Mutex::default(), + textures: Mutex::default(), + tabled: (0..if sampler { 0 } else { count }) + .map(|_| std::sync::atomic::AtomicU32::new(0)) + .collect(), + placed: { + let spans = std::sync::Arc::<Mutex<Spans>>::default(); + if !sampler { + PLACED_SPANS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(std::sync::Arc::downgrade(&spans)); + } + spans + }, + }; + // A slot never written is undefined: shaders reading one (a slot + // the title wrote in a way we do not know, or a table entry no + // used-resource entry names) read a wild address. Every slot starts + // null instead. + let started = std::time::Instant::now(); + if let Err(e) = h.fill_null(kind, size) { + tracing::warn!(error = %e, "host descriptor heap not made null"); } - let made = if sampler { - make(count).map(|heap| (heap, count, 0)) - } else { - let limit = max_view_heap(host); - let mut tried = view_heap_sizes(count, limit).into_iter(); - // Never empty: the last size fits `limit` by construction. - let (size, titles, extra) = tried.next()?; - let mut made = make(size).map(|heap| (heap, titles, extra)); - for (size, titles, extra) in tried { - if made.is_ok() { - break; + tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null"); + Some(h) + } + + /// Makes the first `total` slots null: one null slot in a CPU-side heap, + /// doubled by copies to a block, the block copied over the heap. + fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> { + const BLOCK: u32 = 1 << 16; + let Some(host) = host() else { return Ok(()) }; + // SAFETY: plain heap creation and copies inside live heaps. + unsafe { + let block: ID3D12DescriptorHeap = + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: BLOCK, + ..Default::default() + })?; + let start = block.GetCPUDescriptorHandleForHeapStart(); + let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + (i * self.step) as usize, + }; + if self.sampler { + null_sampler(start); + } else { + null_view(start); + } + let mut filled = 1; + while filled < BLOCK { + let n = filled.min(BLOCK - filled); + host.device.CopyDescriptorsSimple(n, at(filled), start, kind); + filled += n; + } + let mut done = 0; + while done < total { + let n = BLOCK.min(total - done); + host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); + done += n; + } + } + Ok(()) + } + + /// A plain point sampler at slot `index`, for sampler slots without a + /// view. + fn null_sampler(&self, index: u32) { + null_sampler(self.cpu(index)); + } +} + +/// A plain point sampler at `at`. +fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxAnisotropy: 1, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + ..Default::default() + }; + // SAFETY: a slot of a sampler heap of ours. + unsafe { host.device.CreateSampler(&desc, at) }; +} + +impl HostHeap { + /// `n` consecutive free dynamic slots (view heaps only), taken until + /// [`HostHeap::release`]: the first's index. + pub(crate) fn dynamic(&self, n: u32) -> Option<u32> { + if self.sampler || n == 0 || n > self.dynamic { + return None; + } + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::DynamicAsked, 1); + let mut guard = locked(&self.next, 13); + let (next, taken) = &mut *guard; + let free = self.free.load(std::sync::atomic::Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + DYNAMIC_LOW.fetch_min(free, std::sync::atomic::Ordering::Relaxed); + let room = free >= n; + let enough = room && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed); + let n = n as usize; + // Search from `next` on, then from the start and on past `next` by + // n - 1 slots: a free run that lies across `next` is found only + // there (the first part sees its end, the second its start; upstream + // c1c32819e9). Without that such a table was refused with room for + // it, and `too_long` then refused every table as long until the + // next release. + let (cursor, end) = (*next as usize, self.dynamic as usize); + let starts = (cursor..end).chain(0..(cursor + n - 1).min(end)); + let mut run = 0; + let mut found = None; + let mut last = usize::MAX; + for (step, at) in starts.enumerate().take(if enough { usize::MAX } else { 0 }) { + // A run cannot wrap past the end. + if at != last.wrapping_add(1) { + run = 0; + } + last = at; + run = if taken[at] { 0 } else { run + 1 }; + if run == n { + found = Some(at + 1 - n); + // Past `next` in the second part: a run across it. + #[cfg(feature = "diagnostics")] + if step >= end { + DYNAMIC_WHY[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); } - made = make(size).map(|heap| (heap, titles, extra)); + #[cfg(not(feature = "diagnostics"))] + let _ = step; + break; } - if let Ok((_, titles, extra)) = &made - && *titles < count + } + let Some(first) = found else { + if enough { + self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed); + } + #[cfg(feature = "diagnostics")] + DYNAMIC_WHY[if !room { + 0 + } else if !enough { + 1 + } else { + 2 + }] + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); + #[cfg(windows)] + crate::host::slots_ran_out(); + #[cfg(feature = "diagnostics")] { - tracing::warn!(count, limit, "host view heap capped at {}", titles + extra); + use crate::copystat::{C, add}; + add(C::DynamicRefused, 1); + add(C::DynamicNs, started.elapsed().as_nanos() as u64); + } + return None; + }; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64); + taken[first..first + n].fill(true); + self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); + *next = ((first + n) % DYNAMIC as usize) as u32; + Some(self.count + first as u32) + } + + /// The title slots this heap has host slots for; fewer than the title's + /// when the host caps its size. + pub(crate) fn count(&self) -> u32 { + self.count + } + + /// This heap's identity ([`NEXT_ID`]): dynamic slots are given back only + /// to it, never to a heap made later at the same address. + pub(crate) fn id(&self) -> u64 { + self.id + } + + /// The GPU address of the table of element strides by title slot (view + /// heaps). + pub(crate) fn strides_gpu(&self) -> Option<u64> { + self.strides.as_ref().map(|s| s.1) + } + + /// The table's buffer, for a list to hold. + pub(crate) fn strides_buffer(&self) -> Option<&ID3D12Resource> { + self.strides.as_ref().map(|s| &s.0) + } + + /// Up to `max` title slots whose texture view is due at `frame`, each + /// with its write number, in the order to serve them + /// ([`TextureQueue::due`]), and the queue's counts + /// ([`TextureQueue::census`]). + pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) + } + + /// See [`TextureQueue::requeue`]. + pub(crate) fn texture_slots_requeue(&self, indices: &[u32], frame: u64) { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).requeue(indices, frame); + } + + /// See [`TextureQueue::queued`]. + pub(crate) fn texture_slots_queued(&self, indices: &[u32]) -> Vec<(u32, u64)> { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).queued(indices) + } + + /// Every title slot of the queue that is due at `frame`, and whether + /// it was uploaded before (in part, or whole and waiting for another + /// look): for the card accounting line + /// (`crate::resource::card_accounting`). + pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures + .slots + .iter() + .filter(|(_, w)| w.due <= frame) + .map(|(&index, w)| (index, w.mapped > 0 || w.checked.2 != 0)) + .collect() + } + + /// The texture view of title slot `index` (as handed out with `write`) + /// was brought up to date: due again from frame `again` (uploaded with + /// that many bytes of its memory there, not all), or not until the + /// slot is written again. + pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + match again { + Some((frame, mapped)) => textures.partly(index, write, frame, mapped), + None => textures.done(index, write), + } + } + + /// Title slot `index` was uploaded whole: see [`TextureQueue::recheck`]. + #[allow(clippy::too_many_arguments)] + pub(crate) fn texture_slot_recheck( + &self, + index: u32, + write: u64, + due: u64, + at: (u64, u64), + print: u64, + looks: u8, + uploaded: u64, + ) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures.recheck(index, write, due, at, print, looks, uploaded); + } + + /// See [`TextureQueue::checked`]. + pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index) + } + + /// Nothing to upload at title slot `index` now (its memory is not + /// mapped, or no more of it than before): looked at again after 1, 2, + /// 4, ... frames, at most `most`. + pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures.later(index, write, frame, most); + } + + /// See [`TextureQueue::hold`]. + pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due); + } + + /// See [`TextureQueue::room`]. + pub(crate) fn texture_slots_room(&self, frame: u64) -> usize { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame) + } + + /// Bytes of title slot `index`'s memory that were mapped when it was + /// last uploaded in part (0: not uploaded, or whole). + pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index) + } + + /// Takes the ranges of title memory the runtime mapped, unmapped or + /// wrote since the last call ([`remapped`]) and makes the slots whose + /// placed texture lies there due from the next frame (by when a write + /// under way has landed): memory that arrived is uploaded, memory that + /// went makes the slot null ([`HostHeap::texture_slot_gone`]), and a + /// texture streamed into the place of another of the same description + /// is uploaded although no descriptor says so. Slots tables read are + /// left to their draws. Returns how many slots it made due. + /// shortcut: the ranges are kept in one place for all heaps; the heap + /// whose pass runs first takes them (a title has one view heap). + pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize { + use std::sync::atomic::Ordering::Relaxed; + self.texture_slots_page_written(frame); + let mut ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner())); + if ranges.is_empty() { + return 0; + } + join(&mut ranges); + let mut slots: Vec<u32> = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &slots { + textures.changed(slot, frame, frame + 1); + } + STALE[3].fetch_add(slots.len() as u64, Relaxed); + slots.len() + } + + /// Takes the ranges of title memory written behind the guards' back + /// since the last call ([`page_written`]) and finds the slots whose + /// placed texture holds bytes of them ([`Spans::slots_holding`]). A + /// slot whose texture was uploaded before the write shows the bytes + /// from before: with `VICTORY_PAGE_WRITES` (`crate::watch::page_writes`, + /// bit 2) it is due again [`PAGE_WRITE_AFTER`] frames on, as memory + /// mapped under it would make it ([`HostHeap::texture_slots_remapped`]); + /// its host copy exists, so the upload needs no room on the card. A + /// slot still waiting for its first upload is left as it is: that + /// upload takes the bytes that are there by then. Slots tables read + /// are left to their draws. Counted either way; returns how many slots + /// it made due. + fn texture_slots_page_written(&self, frame: u64) -> usize { + let ranges = std::mem::take(&mut *PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner())); + if ranges.is_empty() { + return 0; + } + self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2] + } + + /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end): + /// the slots that held bytes of them, those of them uploaded before, + /// and those made due (the latter, if `due`). + fn slots_written_under(&self, ranges: &[(u64, u64)], frame: u64, due: bool) -> [usize; 3] { + use std::sync::atomic::Ordering::Relaxed; + let mut slots: Vec<u32> = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let held = slots.len(); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + // Uploaded before: out of the queue, or in it after an upload (in + // part, or whole and being looked at again). + slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); + PAGE_WRITES[2].fetch_add(held as u64, Relaxed); + PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed); + if !due { + return [held, slots.len(), 0]; + } + for &slot in &slots { + textures.changed(slot, frame, frame + PAGE_WRITE_AFTER); + } + [held, slots.len(), slots.len()] + } + + /// Whether host slot `index` is made from the very record the title + /// has at `handle` now. Its host texture then exists (a slot keeps what + /// it views), so bringing that texture up to date takes no memory of + /// the card. + pub(crate) fn texture_slot_made_from(&self, index: u32, handle: u64) -> bool { + if index >= self.count { + return false; + } + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + let key = u64::from(generation) << 32 | u64::from(i); + if tag != VIEW_TAG { + return false; + } + // And the slot holds a host resource: a slot is also noted as made + // from a view the host could not make (`make` gave nothing, the + // slot is null and keeps nothing). The host copy of such a + // texture is held by no slot, may have been let go, and would be + // made anew here, with the card full. `made` first, then `kept`, + // as `mirror` takes them. + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + made.get(index as usize).is_some_and(|&made| made != 0 && made == key) + && self.kept[(index % KEPT_PIECES) as usize] + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get((index / KEPT_PIECES) as usize) + .is_some_and(Option::is_some) + } + + /// Levels on demand (`crate::tiles`): makes again the host slots of the + /// placed textures whose first level with memory changed since the + /// last call ([`levels_changed`]), each from the view it was made + /// from, so that it shows the texture from that level ([`make`]). Only + /// slots that are made; a slot draws read through a table is made by + /// its draw. Returns how many it made. + /// shortcut: the starts are kept in one place for all heaps; the heap + /// whose pass runs first takes them (a title has one view heap). + /// Levels on demand (`crate::tiles`): the card has room, so the slots + /// of up to [`Self::WAITING_A_PASS`] placed textures whose upload left + /// a held level without tiles at least a second ago + /// ([`levels_waiting`]) are due again from the next frame, as memory + /// mapped under them would make them + /// ([`HostHeap::texture_slots_remapped`]): the upload then gives the + /// level its tiles. To be called only while the card has room: without + /// it the upload would give nothing again. Slots tables read are left + /// to their draws (`texture.rs` `upload` asks again for those). Returns + /// how many slots it made due. + /// shortcut: kept in one place for all heaps, as the starts below. + pub(crate) fn texture_slots_waiting(&self, frame: u64) -> usize { + if self.sampler { + return 0; + } + let starts: Vec<u64> = { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + if waiting.is_empty() { + return 0; + } + let starts: Vec<u64> = waiting + .iter() + .filter(|&(_, &since)| crate::host::long_ago(since, 1000, 2)) + .map(|(&start, _)| start) + .take(Self::WAITING_A_PASS) + .collect(); + for start in &starts { + waiting.remove(start); + } + starts + }; + if starts.is_empty() { + return 0; + } + let mut slots: Vec<u32> = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + starts.iter().flat_map(|&start| placed.slots_at(start)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &slots { + textures.changed(slot, frame, frame + 1); + } + crate::tiles::STATS[10].fetch_add(slots.len() as u64, std::sync::atomic::Ordering::Relaxed); + slots.len() + } + + /// `VICTORY_REASK_BLANK=1` (off by default): see + /// [`HostHeap::texture_slots_blank`]. + #[cfg(feature = "diagnostics")] + fn reask_blank() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_REASK_BLANK").is_some_and(|v| v == "1")) + } + + /// Slots of placed textures that read zeros for good and that nothing + /// asks for again, whose memory's first page is mapped now: up to + /// [`Self::REASK_A_PASS`] made due from the next frame, about once a + /// second (`VICTORY_REASK_BLANK=1`). Two classes of the census + /// ([`HostHeap::placed_slot_census`]): (Z) shown, made level by level, + /// showing no level and judged holding none at its last upload; (N) + /// null and in no texture queue. Run 319 at the boat: about 384 and 795 + /// of 13,000 slots, never asked again by anything else (gfx41). A slot + /// asked three times that is still blank is left alone for 30 s. + /// Returns how many. (Diagnostics builds only for now: an experiment, + /// built on the census's helpers.) + #[cfg(feature = "diagnostics")] + pub(crate) fn texture_slots_blank(&self, frame: u64) -> usize { + use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + static LAST: AtomicU64 = AtomicU64::new(0); + static ASKED: Mutex<Option<std::collections::HashMap<u32, (u8, u64)>>> = Mutex::new(None); + if self.sampler || !Self::reask_blank() { + return 0; + } + let now = crate::host::now_ms(); + let last = LAST.load(Relaxed); + if now.saturating_sub(last) < 1_000 || LAST.swap(now, Relaxed) != last { + return 0; + } + let slots: Vec<(u32, u64)> = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + placed.by_slot.iter().map(|(&slot, &start)| (slot, start)).collect() + }; + let keys: Vec<u64> = { + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + slots.iter().map(|&(slot, _)| made.get(slot as usize).copied().unwrap_or(0)).collect() + }; + let queued: Vec<bool> = { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + slots.iter().map(|&(slot, _)| textures.slots.contains_key(&slot)).collect() + }; + let mut asked = ASKED.lock().unwrap_or_else(|e| e.into_inner()); + let asked = asked.get_or_insert_with(std::collections::HashMap::new); + let mut due = Vec::new(); + let (mut z, mut n) = (0u64, 0u64); + for (i, &(slot, start)) in slots.iter().enumerate() { + if due.len() >= Self::REASK_A_PASS { + break; + } + if self.tabled_lately(slot, frame) { + continue; + } + let key = keys[i]; + let shows = key != 0 + && self.kept[(slot % KEPT_PIECES) as usize] + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get((slot / KEPT_PIECES) as usize) + .is_some_and(Option::is_some); + let class_z = shows + && view_at(key as u32, (key >> 32) as u32) + .and_then(|view| match view { + View::Placed(false, resource, desc) => crate::resource::texture_at_made( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + &resource, + ), + View::Shader(texture, _) => Some(texture as crate::object::This), + _ => None, + }) + .and_then(|texture| { + let on_demand = crate::resource::host_tiled(texture)?; + let tiled = on_demand.tiled()?; + Some(tiled.first_shown().is_none() && tiled.held_now() == 0) + }) + .unwrap_or(false); + let class_n = !shows && key == 0 && !queued[i]; + if !(class_z || class_n) { + asked.remove(&slot); + continue; + } + let (times, since) = asked.get(&slot).copied().unwrap_or((0, 0)); + if times >= 3 && now.saturating_sub(since) < 30_000 { + continue; + } + if !crate::texture::committed(start as *const u8, 1) { + continue; + } + asked.insert(slot, (if times >= 3 { 1 } else { times + 1 }, now)); + if class_z { + z += 1; + } else { + n += 1; + } + due.push(slot); + } + if due.is_empty() { + return 0; + } + { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &due { + textures.changed(slot, frame, frame + 1); + } + } + REASKED[0].fetch_add(z, Relaxed); + REASKED[1].fetch_add(n, Relaxed); + due.len() + } + + /// Blank slots a pass asks again ([`HostHeap::texture_slots_blank`]). + #[cfg(feature = "diagnostics")] + const REASK_A_PASS: usize = 128; + + /// Textures a pass asks again for their levels + /// ([`HostHeap::texture_slots_waiting`]): the first ones given tiles + /// may take the room the others were asked for, and an upload that + /// gives nothing is a whole texture staged and copied for nothing. + const WAITING_A_PASS: usize = 128; + + pub(crate) fn texture_views_remade(&self) -> usize { + use std::sync::atomic::Ordering::Relaxed; + if self.sampler { + return 0; + } + // The slots made again here are live slots of the heap the card + // reads, and the making is the layer's own, at a moment the title + // knows nothing of: a list already sent may be reading a slot while + // it is written (Direct3D 12 asks that a descriptor a submitted + // list reads is left alone until the list has run). Counted always; + // with `VICTORY_VIEWS_REMADE_QUIET=1` the pass is put off while a + // submission is in flight, and what is due stays due. + let flying = crate::host::submissions_in_flight(); + if flying > 0 && views_remade_quiet() { + if !RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).is_empty() { + VIEWS_REMADE[2].fetch_add(1, Relaxed); } - made + return 0; + } + let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner())); + if starts.is_empty() { + return 0; + } + let slots: Vec<u32> = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + starts.iter().flat_map(|&start| placed.slots_at(start)).collect() }; - let (heap, count, extra) = match made { - Ok(made) => made, - Err(e) => { - tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); - return None; + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + let mut remade = 0; + for slot in slots { + let Some(&key) = made.get(slot as usize) else { + continue; + }; + if key == 0 { + continue; } - }; - Self::with(host, heap, kind, count, extra) + let Some(view) = view_at(key as u32, (key >> 32) as u32) else { + continue; + }; + if let Some(kept) = make(&view, self.cpu(slot)) { + self.keep(slot, kept); + remade += 1; + } + } + let before = VIEWS_REMADE[0].fetch_add(remade as u64, Relaxed); + if flying > 0 { + VIEWS_REMADE[1].fetch_add(remade as u64, Relaxed); + } + // Said at every 1,024 slots made again. + if (before + remade as u64) / 1024 != before / 1024 { + tracing::info!( + "view slots of textures with levels on demand made again, since the start: {}, {} of them while a submission was in flight \ + (a list already sent may have been reading the slot); {} passes put off for that (VICTORY_VIEWS_REMADE_QUIET=1: {})", + before + remade as u64, + VIEWS_REMADE[1].load(Relaxed), + VIEWS_REMADE[2].load(Relaxed), + if views_remade_quiet() { "on" } else { "off" } + ); + } + remade } - /// The host heap over `heap`: `count` title slots, then `extra` dynamic - /// ones, all made null. - fn with( - host: &Host, - heap: ID3D12DescriptorHeap, - kind: D3D12_DESCRIPTOR_HEAP_TYPE, - count: u32, - extra: u32, - ) -> Option<Self> { - let sampler = kind == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; - // SAFETY: a live heap. - let (cpu, step) = unsafe { - ( - heap.GetCPUDescriptorHandleForHeapStart().ptr, - host.device.GetDescriptorHandleIncrementSize(kind), - ) - }; - tracing::debug!(count, sampler, "host descriptor heap"); - // SAFETY: a live shader-visible heap. - let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; - GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( - gpu, - u64::from(count + extra) * u64::from(step), - u64::from(step), - sampler, - )); - let h = HostHeap { - heap, - cpu, - step, - count, - spare: extra, - sampler, - made: Mutex::new(vec![0; count as usize]), - kept: Mutex::new(vec![None; (count + extra) as usize]), - next: Mutex::new((0, vec![false; extra as usize])), + /// The memory of the texture title slot `index` views is not mapped + /// (any more): a host slot made from it becomes null again, so that + /// the host copy can be let go (`crate::resource::let_go_idle`; a slot + /// keeps what it views). True if the slot was made. + pub(crate) fn texture_slot_gone(&self, index: u32) -> bool { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if made.get(index as usize).is_none_or(|&key| key == 0) { + return false; + } + self.unmake(&mut made, index); + STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true + } + + /// Makes host slot `index` null again, as it is before its view is + /// made: a null view of the kind it held. + fn unmake(&self, made: &mut [u64], index: u32) { + let Some(key) = made.get_mut(index as usize).map(std::mem::take) else { + return; }; - // A slot never written is undefined: shaders reading one (a slot - // the title wrote in a way we do not know, or a table entry no - // used-resource entry names) read a wild address. Every slot starts - // null instead. - let started = std::time::Instant::now(); - if let Err(e) = h.fill_null(kind, count + extra) { - tracing::warn!(error = %e, "host descriptor heap not made null"); - return None; + if let Some(now) = self.made_now.get(index as usize) { + now.store(0, std::sync::atomic::Ordering::Release); } - tracing::debug!( - ms = started.elapsed().as_millis(), - "host descriptor heap made null" - ); - Some(h) + if key == 0 { + return; + } + match view_at(key as u32, (key >> 32) as u32) { + Some(view) => null_for(&view, self.cpu(index)), + None => null_view(self.cpu(index)), + } + self.keep(index, None); } - /// Makes the first `total` slots null: one null slot in a CPU-side heap, - /// doubled by copies to a block, the block copied over the heap. - fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> { - let Some(host) = host() else { return Ok(()) }; - let block_count = total.min(if self.sampler { - D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE - } else { - 1 << 16 - }); - // SAFETY: plain heap creation and copies inside live heaps. - unsafe { - let block: ID3D12DescriptorHeap = - host.device - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: block_count, - ..Default::default() - })?; - let start = block.GetCPUDescriptorHandleForHeapStart(); - let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { - ptr: start.ptr + (i * self.step) as usize, - }; - if self.sampler { - null_sampler(start); - } else { - null_view(start); - } - let mut filled = 1; - while filled < block_count { - let n = filled.min(block_count - filled); - host.device - .CopyDescriptorsSimple(n, at(filled), start, kind); - filled += n; + /// Title slot `index` is a table's ([`HostHeap::tabled`]). `read`: a + /// draw read it through the table and brought what it views up to + /// date, so the slot leaves the queue of textures picked by index; the + /// caller makes the host slot in place ([`HostHeap::mirror`]), as the + /// pass would have, for a shader that picks it by index all the same. + pub(crate) fn texture_slot_tabled(&self, index: u32, read: bool) { + self.tabled_in(index, read, crate::frame::current()); + } + + /// [`HostHeap::texture_slot_tabled`] in frame `frame`. + fn tabled_in(&self, index: u32, read: bool, frame: u64) { + use std::sync::atomic::Ordering::Relaxed; + let Some(stamp) = self.tabled.get(index as usize) else { + return; + }; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + let old = stamp.load(Relaxed); + if !read { + if old & !TABLED_READ != now { + stamp.store(now, Relaxed); } - let mut done = 0; - while done < total { - let n = block_count.min(total - done); - host.device - .CopyDescriptorsSimple(n, self.cpu(done), start, kind); - done += n; + return; + } + // Once per slot and frame: tables are read by every draw. + if old != now | TABLED_READ { + stamp.store(now | TABLED_READ, Relaxed); + if tabled_out() { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + if textures.slots.remove(&index).is_some() { + TABLED_WRITES[1].fetch_add(1, Relaxed); + } } } - Ok(()) } - /// A plain point sampler at slot `index`, for sampler slots without a - /// view. - fn null_sampler(&self, index: u32) { - null_sampler(self.cpu(index)); + /// Whether title slot `index` was a table's within the last + /// [`TABLED_FRAMES`] frames before `frame` (never, if such slots are + /// to be queued as any other). + fn tabled_lately(&self, index: u32, frame: u64) -> bool { + let stamp = self.tabled_stamp(index) & !TABLED_READ; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + tabled_out() && stamp != 0 && u64::from(now.wrapping_sub(stamp)) <= TABLED_FRAMES } -} -/// A plain point sampler at `at`. -fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { - let Some(host) = host() else { return }; - let desc = D3D12_SAMPLER_DESC { - Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, - AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, - MaxAnisotropy: 1, - ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, - ..Default::default() - }; - // SAFETY: a slot of a sampler heap of ours. - unsafe { host.device.CreateSampler(&desc, at) }; -} + /// What `tabled` holds for title slot `index`; 0: never a table's. + fn tabled_stamp(&self, index: u32) -> u32 { + self.tabled + .get(index as usize) + .map_or(0, |s| s.load(std::sync::atomic::Ordering::Relaxed)) + } -impl HostHeap { - /// `n` consecutive free dynamic slots (view heaps and capped sampler - /// heaps), taken until [`HostHeap::release`]: the first's index. - pub(crate) fn dynamic(&self, n: u32) -> Option<u32> { - if n == 0 || self.spare == 0 { - return None; + /// The queue's part of a write of title slot `index` in `frame`: + /// `texture`, whether it now holds a view of a texture the title may + /// fill; `seen` as for [`HostHeap::note_buffer`]. + fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) { + if PUBLISHING.get() { + return; } - if n > self.spare { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!( - n, - spare = self.spare, - sampler = self.sampler, - "a table larger than the dynamic slots is not made" - ); - }); - return None; + let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 }; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + // A table's slot lately: the draw that reads it uploads its + // texture, so its write waits for that draw. + let lately = stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES; + // Made now by a draw of this frame that read it through a table: + // up to date. + let read_now = seen && stamp == now | TABLED_READ; + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + if texture && !read_now { + let due = if lately && !seen { + TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + frame + TABLED_GRACE + } else { + 0 + }; + textures.written(index, frame, due, seen); + } else { + textures.remove(index); } - let spare = self.spare as usize; - let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); - let (next, taken) = &mut *guard; - let n = n as usize; - // Search from `next` on, then from the start. - let starts = (*next as usize..spare).chain(0..*next as usize); - let mut run = 0; - let mut found = None; - let mut last = usize::MAX; - for at in starts { - // A run cannot wrap past the end. - if at != last.wrapping_add(1) { - run = 0; + } + + /// The title slots that hold buffer views. + pub(crate) fn buffer_slots(&self) -> Vec<u32> { + let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); + buffers.iter().copied().collect() + } + + /// The title slots whose buffer view was written, or went, since the + /// last call. + pub(crate) fn buffer_changes(&self) -> Vec<u32> { + let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner()); + std::mem::take(&mut *changed).into_iter().collect() + } + + /// Records what title slot `index` now holds for shaders that pick + /// buffers from the heap: its element stride in the table, and whether + /// it is a buffer view at all. + /// `seen`: the slot was not written now, a draw or a pass made its + /// host slot from what it held. + /// Returns the title slots whose placed texture view the write made + /// stale ([`Spans`]): out of the queue of textures already, their host + /// slots are the caller's to make null (it holds `made`). + fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec<u32> { + if self.sampler { + return Vec::new(); + } + // Measured for the texture side of the same gap (textures a shader + // picks by a computed index are neither made, if placed, nor + // uploaded): slots written with a placed texture view, and with a + // view of a texture object. + let texture = match view { + Some(View::Placed(false, resource, _)) if resource[0] != 1 => { + PLACED_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true } - last = at; - run = if taken[at] { 0 } else { run + 1 }; - if run == n { - found = Some(at + 1 - n); - break; + Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => { + OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true } - } - let Some(first) = found else { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(n, "no free dynamic descriptor slots: a table is not made") + _ => false, + }; + self.queue_texture(index, texture, seen, crate::frame::current()); + // The memory a placed texture view describes. Not for a slot + // tables read (thousands of writes a frame, each read by its + // draw): no pass looks at it, and the same texture's view in a + // slot shaders pick by index says what it says. + let placed_view = match view { + Some(View::Placed(false, resource, desc)) + if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) => + { + // (And the level the view starts at: word 4 of a texture + // view's description, after format, dimension, mapping + // and a pad.) + Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4])) + } + _ => None, + }; + let stale = { + use std::sync::atomic::Ordering::Relaxed; + let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + let span = placed_view.and_then(|(resource, start, first)| { + Some((start, start.saturating_add(placed.bytes(resource)?), first)) }); - return None; + match span { + Some((start, end, first)) => { + SPANNED[0].fetch_min(start, Relaxed); + SPANNED[1].fetch_max(end, Relaxed); + placed.rule = stale_rule(); + let stale = placed.note(index, start, end, !seen); + placed.shows(index, first); + stale + } + None => { + placed.forget(index); + Vec::new() + } + } }; - taken[first..first + n].fill(true); - *next = ((first + n) % spare) as u32; - Some(self.count + first as u32) - } - - /// The title slots this heap has host slots for; fewer than the title's - /// when the host caps its size. - pub(crate) fn count(&self) -> u32 { - self.count + if !stale.is_empty() { + STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &stale { + textures.remove(slot); + } + } + let (stride, kind) = view.map_or((None, 0), view_stride_and_kind); + self.write_stride(index, stride.unwrap_or(0) | kind); + let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); + let was = if stride.is_some() { + buffers.insert(index); + true + } else { + buffers.remove(&index) + }; + if was { + self.changed + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(index); + } + stale } /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] - /// returned). + /// returned), if they were taken by this heap: `id` is [`HostHeap::id`]'s. + /// The title can release the heap a list's slots came from, and a later + /// heap can be made at the same address; the list's reset then names the + /// old heap, and must not free the new one's slots ([NEXT_ID]). /// /// [`dynamic`]: HostHeap::dynamic - pub(crate) fn release(&self, first: u32, n: u32) { + pub(crate) fn release(&self, id: u64, first: u32, n: u32) { + if id != self.id { + return; + } let Some(at) = first.checked_sub(self.count) else { return; }; let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); - let end = at.saturating_add(n).min(self.spare) as usize; + let end = (at + n).min(self.dynamic) as usize; if let Some(slots) = guard.1.get_mut(at as usize..end) { + let given = slots.iter().filter(|taken| **taken).count() as u32; + self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed); + self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed); slots.fill(false); } } - /// Makes a matched native UAV pair from the CPU view. The GPU slot is - /// held until list reset like the descriptors in a fresh table. - pub(crate) fn clear_texture_uav( - &self, - list: &crate::host::HostList, - texture: &ID3D12Resource, - words: Option<&[u32; 10]>, - ) -> Option<( - u32, - D3D12_GPU_DESCRIPTOR_HANDLE, - D3D12_CPU_DESCRIPTOR_HANDLE, - )> { - let mut desc = words.map(uav_desc); - if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { - return None; - } - let device = &host()?.device; - let cpu = list.clear_uav_cpu()?; - let slot = self.dynamic(1)?; - // SAFETY: both handles name live heap slots. Copy from the - // CPU-only heap to the shader-visible heap. - let gpu = unsafe { - device.CreateUnorderedAccessView( - texture, - None::<&ID3D12Resource>, - desc.as_ref().map(std::ptr::from_ref), - cpu, - ); - device.CopyDescriptorsSimple( - 1, - self.cpu(slot), - cpu, - D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - ); - D3D12_GPU_DESCRIPTOR_HANDLE { - ptr: self.heap.GetGPUDescriptorHandleForHeapStart().ptr - + u64::from(slot) * u64::from(self.step), - } - }; - // The list's texture state retains the resource through execution. - self.keep(slot, None); - Some((slot, gpu, cpu)) - } - /// Makes slot `index` (a dynamic one) from `view`; a null view if the /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { let kept = make(view, self.cpu(index)); if kept.is_none() { - if self.sampler { - self.null_sampler(index); - } else { - null_for(view, self.cpu(index)); - } + null_for(view, self.cpu(index)); } + // (the table of strides and view kinds for the dynamic slots of + // tables too: codec_d, cool_fox f4b48ad) + self.write_stride(index, if kept.is_some() { view_stride_word(view) } else { 0 }); self.keep(index, kept.flatten()); } @@ -452,34 +2260,86 @@ impl HostHeap { self.null_sampler(index); } else { null_view(self.cpu(index)); + self.write_stride(index, 0); } self.keep(index, None); } + /// Writes `word` (stride | format kind) for view heap slot `index` into + /// the host's table of strides ([`victory_shader::emit::SLOT_STRIDES`], + /// [`victory_shader::emit::SLOT_TABLE_STRIDES`]). + #[inline] + fn write_stride(&self, index: u32, word: u32) { + if let Some((_, _, data)) = &self.strides + && index < victory_shader::emit::SLOT_STRIDES_COUNT + { + // SAFETY: inside the mapping; shaders read it while we write (a + // single aligned dword: either value is one the slot had). + unsafe { (*data as *mut u32).add(index as usize).write_volatile(word) }; + } + } + /// Slot `index` now views `resource` (or nothing of the host's). fn keep(&self, index: u32, resource: Option<ID3D12Resource>) { - let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(slot) = kept.get_mut(index as usize) { + #[cfg(feature = "diagnostics")] + LOCKS[10].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let piece = &self.kept[(index % KEPT_PIECES) as usize]; + let at = (index / KEPT_PIECES) as usize; + if heap_locks() { + let (old, lean) = { + let mut kept = locked(piece, 11); + match kept.get_mut(at) { + Some(slot) => { + let lean = slot + .as_ref() + .is_some_and(|old| crate::host::slot_rewritten(old, resource.as_ref())); + (std::mem::replace(slot, resource), lean) + } + None => (None, false), + } + }; + // A running submission may still read the old resource through + // this slot. (Outside the lock: letting go takes another lock, + // or frees a host resource.) The same object written again is + // held by the slot's new reference: the old one goes now. + if let Some(old) = old { + if lean { + drop(old); + } else { + crate::host::retire(old); + } + } + return; + } + // As before: one line for the whole heap, held across the letting + // go. (The line's waits are the ones counted; the piece's lock is + // free under it.) + let _one = locked(&self.kept_one, 11); + let mut kept = piece.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(slot) = kept.get_mut(at) { + let lean = slot + .as_ref() + .is_some_and(|old| crate::host::slot_rewritten(old, resource.as_ref())); // A running submission may still read the old resource through - // this slot. + // this slot (the same object written again: held by the new + // reference, the old one goes now). if let Some(old) = std::mem::replace(slot, resource) { - crate::host::retire(old); + if lean { + drop(old); + } else { + crate::host::retire(old); + } } } } - /// The shader-visible handle of slot `index`. - pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE { - // SAFETY: a live shader-visible heap. - let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr }; - D3D12_GPU_DESCRIPTOR_HANDLE { ptr: start + u64::from(index) * u64::from(self.step) } - } - /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes - /// of `buffer` from byte `offset` (4-byte units, rounded down), holding - /// the buffer while the slot does. - pub(crate) fn raw_srv_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { + /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a + /// size, whose reads past it return zeros instead of reaching whatever + /// the host placed after the buffer. + pub(crate) fn raw_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { let Some(host) = host() else { return }; + let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32; let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, ViewDimension: D3D12_SRV_DIMENSION_BUFFER, @@ -487,28 +2347,108 @@ impl HostHeap { Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Buffer: D3D12_BUFFER_SRV { FirstElement: offset / 4, - NumElements: (len / 4).clamp(1, u64::from(u32::MAX)) as u32, + NumElements: elements, StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_RAW, }, }, }; - // SAFETY: a live buffer and a slot of our heap; the range lies in it. + // SAFETY: a slot of our heap and a live buffer covering the range. unsafe { host.device .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index)) }; + self.write_stride(index, 1); + self.keep(index, Some(buffer.clone())); + } + + /// Makes slot `index` (a dynamic one) a raw buffer view that reads + /// zeros. + pub(crate) fn null_raw_at(&self, index: u32) { + null_buffer_view(self.cpu(index)); + self.write_stride(index, 0); + self.keep(index, None); + } + + /// Makes slot `index` (a dynamic one) a raw unordered access view of + /// `len` bytes of `buffer` from byte `offset` (a multiple of 16): a + /// root UAV with a size, whose accesses past it do nothing instead of + /// reaching whatever the host placed after the buffer. + pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { + let Some(host) = host() else { return }; + let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: offset / 4, + NumElements: elements, + StructureByteStride: 0, + CounterOffsetInBytes: 0, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + }, + }, + }; + // SAFETY: a slot of our heap and a live buffer covering the range. + unsafe { + host.device.CreateUnorderedAccessView( + buffer, + None::<&ID3D12Resource>, + Some(&desc), + self.cpu(index), + ) + }; + self.write_stride(index, 1); self.keep(index, Some(buffer.clone())); } + /// Makes slot `index` (a dynamic one) a raw unordered access view of + /// nothing: reads give zeros, writes are dropped. + pub(crate) fn null_raw_uav_at(&self, index: u32) { + self.write_stride(index, 0); + self.keep(index, None); + let Some(host) = host() else { return }; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: 1, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&desc), + self.cpu(index), + ) + }; + } + + /// The shader-visible handle of slot `index`. + pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE { + // SAFETY: a live shader-visible heap. + let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr }; + D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: start + u64::from(index) * u64::from(self.step), + } + } + /// Makes slot `index` (a dynamic one) a constant buffer view of host /// memory (the list's own, which it holds). pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { + self.write_stride(index, 0); self.keep(index, None); let Some(host) = host() else { return }; let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, - SizeInBytes: size.next_multiple_of(256), + SizeInBytes: constant_view_size(size), }; // SAFETY: a slot of our heap; the memory is the caller's. unsafe { @@ -517,10 +2457,161 @@ impl HostHeap { }; } - fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { - D3D12_CPU_DESCRIPTOR_HANDLE { - ptr: self.cpu + index as usize * self.step as usize, + fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: self.cpu + index as usize * self.step as usize, + } + } + + /// For a slot on a page of the title's heap that changed with no call + /// (`super::sync_heaps`: the title copies records into its heap as + /// bytes): [`HostHeap::mirror`], if the `bytes` bytes of the record at + /// `handle` are not the ones this last saw there. True if it did. + /// + /// The page says only that something on it was written, and `mirror` + /// by itself would take every buffer or placed-texture record on it for + /// newly written each time (it leaves such a slot unmade until a draw + /// or a pass uses it): the texture queue's entry for the slot would + /// start again, and the buffer pass would look at 2,048 slots for one + /// that changed. + /// `record`: the record's bytes as the caller read them (through the + /// kernel, which fails on a page the title unmapped meanwhile where a + /// read in place would fault: the title unmaps heap pages too). + pub(crate) fn mirror_copied(&self, index: u32, handle: u64, record: &[u8]) -> bool { + if index >= self.count { + return false; + } + // A slot draws read through a table lately is left to its draws, + // as the passes over slots picked by index leave it + // (`texture_slots_remapped`, `slots_written_under`): the title + // writes its per-draw tables into the same heap every frame, and + // each draw makes what its table shows in a slot of its own. Those + // were most of the 26,000 to 43,000 records a frame this pass + // mirrored in run 200 and in the play session after it, each then + // made and brought up to date once more by the pass over buffer + // views (some 50 ms a frame). `VICTORY_HEAP_SYNC_TABLES=1`: they + // are mirrored too, as in run 200. + if !sync_tables() && self.tabled_lately(index, crate::frame::current()) { + COPIED_TABLED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return false; + } + let n = record.len(); + // Never 0, which is "never looked at". (A multiply-and-fold over + // the record's words: BLAKE3 here was most of the 35 to 42 ms a + // frame this pass took over some 250,000 to 300,000 records, run + // 200.) + let print = record_print(record) | 1; + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if copied.is_empty() { + copied.resize(self.count as usize, 0); + } + let Some(last) = copied.get_mut(index as usize) else { + return false; + }; + // A slot never looked at that holds nothing: as it was. + if *last == print || (*last == 0 && record[..n].iter().all(|&b| b == 0)) { + return false; + } + *last = print; + } + self.mirror(index, handle, false); + true + } + + /// [`HostHeap::mirror_copied`] for every record of one changed page of + /// the title's heap (`super::sync_heaps`): title slots `slots`, the + /// record of slot `i` at title address `start + i * step`, and `page` + /// the bytes read from title address `from` on. Returns the records + /// looked at and those mirrored. + /// + /// The same records are mirrored as one by one. What differs is the + /// work for the others, which are nearly all of them (some 330,000 + /// looked at a frame for 14,000 mirrored, 16 ms, run 225): the lock of + /// the fingerprints is taken once for the page and not once for each + /// record, and a record whose fingerprint is the one last seen is done + /// with before the question whether its slot was a table's lately. So + /// the count of slots "left to the draws" is now of records that + /// changed, not of every record on the page. The slots to mirror are + /// made after the page's walk, in slot order as before. + pub(crate) fn mirror_copied_page( + &self, + slots: std::ops::Range<u64>, + (start, step): (u64, u64), + from: usize, + page: &[u8], + ) -> (u64, u64) { + let (frame, tables) = (crate::frame::current(), sync_tables()); + let mut looked = 0u64; + let mut due: Vec<(u32, u64)> = Vec::new(); + let walking = std::time::Instant::now(); + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if copied.is_empty() { + copied.resize(self.count as usize, 0); + } + for index in slots { + let handle = start + index * step; + // A record that straddles the range's ends is left to the + // range that holds its first byte. + let Some(at) = (handle as usize).checked_sub(from) else { + continue; + }; + let Some(record) = page.get(at..at + step as usize) else { + continue; + }; + looked += 1; + // None past the host heap's slots, as `mirror_copied`. + let Some(last) = copied.get_mut(index as usize) else { + continue; + }; + // Never 0, which is "never looked at". + let print = record_print(record) | 1; + // The record last seen, or a slot never looked at that + // holds nothing: as it was. + if *last == print || (*last == 0 && record.iter().all(|&b| b == 0)) { + continue; + } + // A table's slot lately: left to its draws, and looked at + // again next time. + if !tables && self.tabled_lately(index as u32, frame) { + COPIED_TABLED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + continue; + } + *last = print; + due.push((index as u32, handle)); + } + } + let making = std::time::Instant::now(); + for &(index, handle) in &due { + #[cfg(feature = "diagnostics")] + MIRROR_HOW.with(|how| how.set(MIRROR_UNSET)); + #[cfg(feature = "diagnostics")] + let one = std::time::Instant::now(); + self.mirror(index, handle, false); + #[cfg(feature = "diagnostics")] + mirror_counted(one.elapsed().as_micros() as u64); + } + super::SYNC_PARTS[2].fetch_add((making - walking).as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + super::SYNC_PARTS[3].fetch_add(making.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + (looked, due.len() as u64) + } + + /// Makes host slot `index` from the record at `handle` if it is still + /// the one with `key`, whose texture's upload is in the queue now + /// (`crate::heap_worker`). The slot's place in the queue of textures + /// picked by index was settled when that upload was recorded, and stays + /// as it is. False if the title wrote the slot again. + pub(crate) fn publish(&self, index: u32, handle: u64, key: u64) -> bool { + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + if tag != VIEW_TAG || u64::from(generation) << 32 | u64::from(i) != key { + return false; } + PUBLISHING.set(true); + let shown = self.mirror(index, handle, true).is_some(); + PUBLISHING.set(false); + shown } /// Makes host slot `index` from the record the title has at `handle` @@ -546,20 +2637,110 @@ impl HostHeap { let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; // Generations start at 1, so a made slot's key is never 0. let key = u64::from(generation) << 32 | u64::from(i); - let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + // Made from this record already ([`heap_locks`]): what the lock + // would find, without it. (The view is looked up first, as under + // the lock: a record whose view is gone is not served here.) + if tag == VIEW_TAG + && heap_locks() + && self.made_now[index as usize].load(std::sync::atomic::Ordering::Acquire) == key + && let Some(view) = view_at(i, generation) + { + #[cfg(feature = "diagnostics")] + mirror_how(MIRROR_FAST); + return Some(view); + } + let mut made = locked(&self.made, 4); + #[cfg(feature = "diagnostics")] + let held = Held::start(for_draw); let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); let Some(view) = view else { // Not a view of ours (never written, or of a resource the // title released): nothing to read. + #[cfg(feature = "diagnostics")] + mirror_how(MIRROR_NOT_VIEW); if made[index as usize] != 0 { + #[cfg(feature = "diagnostics")] + held.slot_changed(); made[index as usize] = 0; + self.made_now[index as usize].store(0, std::sync::atomic::Ordering::Release); self.make_null(index); + let _ = self.note_buffer(index, None, false); + } else if for_draw { + // Left for later and stale since: out of the sets and the stride table. + let _ = self.note_buffer(index, None, false); } return None; }; if made[index as usize] != key { - let later = !for_draw && view.is_buffer(); + #[cfg(feature = "diagnostics")] + held.slot_changed(); + // Being made again: not "made" to a reader without the lock + // until it is (the store after `keep` below). + self.made_now[index as usize].store(0, std::sync::atomic::Ordering::Release); + // Views of other textures in the memory this one describes + // are stale: their host slots read nothing from here on, and + // let go of the host copies they held. + #[cfg(feature = "diagnostics")] + let noting = std::time::Instant::now(); + for stale in self.note_buffer(index, Some(&view), for_draw) { + if stale != index { + self.unmake(&mut made, stale); + } + } + #[cfg(feature = "diagnostics")] + if mirror_timing() { + MIRROR_US[0].fetch_add(noting.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); + } + // A view of a texture object that has no host copy yet waits + // for it, as buffer views wait for a draw: the slot is made + // when the texture is first used (`super::make_waiting`), or + // here when a draw reads the slot through a table. + let waiting = if for_draw { None } else { view.waiting_texture() }; + if let Some(texture) = waiting { + super::wait_for(texture, handle); + } + let later = !for_draw && (view.is_buffer() || waiting.is_some()); + // Another view of the placed texture the slot shows already (a + // title that streams a texture in writes its view again with + // more mips each time some arrive): the slot goes on showing + // the old view until a draw or the texture pass makes the new + // one and uploads what it shows. Made null here, the texture + // read as nothing for as long as it waited in the queue, every + // time it got sharper. + let shown = made[index as usize]; + if later + && keep_views() + && let Some(old) = view_at(shown as u32, (shown >> 32) as u32) + { + let kin = kin(&old, &view); + if kin == Kin::Same { + KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + mirror_how(MIRROR_KEPT); + // The slot goes on showing what it was made from. + self.made_now[index as usize].store(made[index as usize], std::sync::atomic::Ordering::Release); + return Some(view); + } + // And of another texture that can stand for it + // ([`keep_shown`]; avatarmanz/VIctory-7900XTX d1c412c5): + // black, then grey for a frame or two is what popped. + if is_texture_view(&old) { + let kept = kin.kept(keep_shown()); + rewritten(kin, kept); + if kept { + #[cfg(feature = "diagnostics")] + mirror_how(MIRROR_KEPT); + // The slot goes on showing what it was made from. + self.made_now[index as usize].store(made[index as usize], std::sync::atomic::Ordering::Release); + return Some(view); + } + } + } made[index as usize] = if later { 0 } else { key }; + #[cfg(feature = "diagnostics")] + mirror_how(if later { MIRROR_LATER } else { MIRROR_MADE }); + #[cfg(feature = "diagnostics")] + let creating = std::time::Instant::now(); let kept = if later { None } else { @@ -568,21 +2749,194 @@ impl HostHeap { if kept.is_none() && !self.sampler { null_for(&view, self.cpu(index)); } + #[cfg(feature = "diagnostics")] + let keeping = std::time::Instant::now(); self.keep(index, kept.flatten()); + #[cfg(feature = "diagnostics")] + if mirror_timing() { + use std::sync::atomic::Ordering::Relaxed; + MIRROR_US[1].fetch_add((keeping - creating).as_micros() as u64, Relaxed); + MIRROR_US[2].fetch_add(keeping.elapsed().as_micros() as u64, Relaxed); + } + // After the slot is made and kept: a reader without the lock + // takes the record as made only once it is. + self.made_now[index as usize].store(made[index as usize], std::sync::atomic::Ordering::Release); } + #[cfg(feature = "diagnostics")] + mirror_how(MIRROR_SAME); Some(view) } + /// Whether slot `index` is backed by a made host descriptor (tests). + #[cfg(test)] + pub(crate) fn made(&self, index: u32) -> bool { + self.made + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(index as usize) + .is_some_and(|&key| key != 0) + } + + /// Whether host slot `index` shows `buffer`; `None` if it shows no + /// resource (diagnostics: a buffer view's slot must show the host copy + /// that is brought up to date for it). + #[cfg(feature = "diagnostics")] + pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option<bool> { + let kept = self.kept[(index % KEPT_PIECES) as usize].lock().unwrap_or_else(|e| e.into_inner()); + let shown = kept.get((index / KEPT_PIECES) as usize)?.as_ref()?; + Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer)) + } + + /// What the queue of textures picked by index knows of title slot + /// `index` at `frame`, in a few words (diagnostics). + #[cfg(feature = "diagnostics")] + pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + match textures.slots.get(&index) { + None => "not queued".into(), + Some(w) => format!( + "queued due={} written@{} looks={} part_mapped={} recheck={}", + if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) }, + w.written, + w.looks, + w.mapped, + w.checked.2 != 0 + ), + } + } + + /// For the log, at most every five seconds (diagnostics): the title + /// slots that hold a placed texture view shaders may pick by index (not + /// a table's lately), by what their host slot shows now. A count each: + /// slots; shown with a host copy that has its contents; shown with a + /// host copy made level by level that has no level with tiles (reads + /// zeros); made from the record but null (the host could not make it); + /// null and held for room; null and waiting for their memory to be + /// mapped; null and in the queue otherwise (due, or looked at later); + /// null and in no queue (made stale, or let go and not asked again); of + /// the last, those whose memory's first page is mapped now (every 16th + /// asked, times 16). The black of a surface is one of the null or zero + /// classes; which one is what this line tells, for the heap as a whole. + #[cfg(feature = "diagnostics")] + pub(crate) fn placed_slot_census(&self) { + use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + static LAST: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + let last = LAST.load(Relaxed); + if self.sampler || now.saturating_sub(last) < 5_000 || LAST.swap(now, Relaxed) != last { + return; + } + let began = std::time::Instant::now(); + // (slot, start of its texture's memory), taken under the spans' lock alone. + let slots: Vec<(u32, u64)> = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + placed.by_slot.iter().map(|(&slot, &start)| (slot, start)).collect() + }; + // The keys, then the queue, each under its own lock alone. + let keys: Vec<u64> = { + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + slots.iter().map(|&(slot, _)| made.get(slot as usize).copied().unwrap_or(0)).collect() + }; + // 0 not queued, 1 held, 2 waiting for memory, 3 other. + let queued: Vec<u8> = { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + slots + .iter() + .map(|&(slot, _)| match textures.slots.get(&slot) { + None => 0, + Some(_) if textures.held.contains_key(&slot) => 1, + Some(w) if w.looks > 0 && w.mapped == 0 && w.checked.2 == 0 => 2, + Some(_) => 3, + }) + .collect() + }; + let mut c = [0u64; 10]; + let mut forgotten = 0u64; + for (i, &(slot, start)) in slots.iter().enumerate() { + c[0] += 1; + let key = keys[i]; + let shows = key != 0 + && self.kept[(slot % KEPT_PIECES) as usize] + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get((slot / KEPT_PIECES) as usize) + .is_some_and(Option::is_some); + if shows { + // Made level by level with no level shown: zeros. + let blank = view_at(key as u32, (key >> 32) as u32) + .and_then(|view| match view { + View::Placed(false, resource, desc) => crate::resource::texture_at_made( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + &resource, + ), + View::Shader(texture, _) => Some(texture as crate::object::This), + _ => None, + }) + // The levels judged the title's at its last upload, if it + // shows none (0 also if never uploaded). + .and_then(|texture| { + let on_demand = crate::resource::host_tiled(texture)?; + let tiled = on_demand.tiled()?; + tiled.first_shown().is_none().then(|| tiled.held_now()) + }); + match blank { + None => c[1] += 1, + Some(0) => { + c[2] += 1; + c[9] += 1; + } + Some(_) => c[2] += 1, + } + continue; + } + if key != 0 { + c[3] += 1; + continue; + } + match queued[i] { + 1 => c[4] += 1, + 2 => c[5] += 1, + 3 => c[6] += 1, + _ => { + c[7] += 1; + forgotten += 1; + if forgotten.is_multiple_of(16) && crate::texture::committed(start as *const u8, 1) { + c[8] += 16; + } + } + } + } + tracing::info!( + "placed texture slots picked by index, by what the host slot shows: {} slots; {} shown with their contents; \ + {} shown from a copy made level by level that has no level with tiles (reads zeros); {} made but null (the host \ + could not make the view); null: {} held for room, {} waiting for their memory, {} in the queue otherwise, {} in no \ + queue (about {} of those with their first page mapped now); the census took {} ms; placed views the host could \ + not make since the start: {} shader views, {} unordered; of the slots that read zeros, {} show a copy with no \ + level judged the title's at its last upload (never uploaded, or nothing held: no room is asked for those); asked again since the start (VICTORY_REASK_BLANK): {} shown with no level held, {} null in no queue", + c[0], + c[1], + c[2], + c[3], + c[4], + c[5], + c[6], + c[7], + c[8], + began.elapsed().as_millis(), + PLACED_NOT_MADE[0].load(Relaxed), + PLACED_NOT_MADE[1].load(Relaxed), + c[9], + REASKED[0].load(Relaxed), + REASKED[1].load(Relaxed), + ); + } + /// The view host slot `index` was made from, in a few words, with the /// title and host addresses of a buffer view (diagnostics). "null" for /// a slot never made or left null. #[cfg(feature = "diagnostics")] pub(crate) fn describe_slot(&self, index: u32) -> Option<String> { - let key = *self - .made - .lock() - .unwrap_or_else(|e| e.into_inner()) - .get(index as usize)?; + let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; if key == 0 { return Some("null".into()); } @@ -616,6 +2970,76 @@ fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC { } } +/// The unsigned integer format with the layout of a 16-bit float or +/// signed integer format (one, two or four channels), if `format` is one. +pub(crate) fn half_format(format: u32) -> Option<u32> { + match format { + // R16G16B16A16_FLOAT and _SINT: R16G16B16A16_UINT. + 10 | 14 => Some(12), + // R16G16_FLOAT and _SINT: R16G16_UINT. + 34 | 38 => Some(36), + // R16_FLOAT and _SINT: R16_UINT. + 54 | 59 => Some(57), + _ => None, + } +} + +/// `view` as a shader is shown it where it moves a buffer's 16-bit +/// channels as unsigned integers +/// (`victory_shader::emit::HostShader::half_views`): a buffer view in a +/// 16-bit float or signed format, in the unsigned format of the same +/// layout, through which every 16-bit pattern is read and stored as it +/// is. `None` for every other view: the title's own serves (an unsigned +/// one already carries the bits; a texture can only be viewed in the +/// formats it was made for). +pub(crate) fn half_view(view: &View) -> Option<View> { + // Buffer views: dimension 1 in the title's description of either kind. + const BUFFER: u32 = 1; + match view { + View::Shader(resource, Some(desc)) if desc[1] == BUFFER => { + let mut desc = *desc; + desc[0] = half_format(desc[0])?; + Some(View::Shader(*resource, Some(desc))) + } + View::Unordered(resource, counter, Some(desc)) if desc[1] == BUFFER => { + let mut desc = *desc; + desc[0] = half_format(desc[0])?; + Some(View::Unordered(*resource, *counter, Some(desc))) + } + View::Placed(unordered, resource, desc) if resource[0] == BUFFER && desc[1] == BUFFER => { + let mut desc = *desc; + desc[0] = half_format(desc[0])?; + Some(View::Placed(*unordered, *resource, desc)) + } + _ => None, + } +} + +/// The format of `view`, a buffer view through which a shader moves +/// 16-bit channels as unsigned integers +/// (`victory_shader::emit::HostShader::half_views`), if those integers +/// are not what the console gives: a format of wider channels, a +/// normalised one or a signed 8-bit one, whose values the console converts +/// to and from halves. `None` for the formats the integers serve exactly +/// (16 bits a channel of any kind, through [`half_view`] where needed, and +/// unsigned channels of fewer bits; the title's are 16-bit unsigned) and +/// for any other view. +pub(crate) fn half_inexact(view: &View) -> Option<u32> { + // Buffer views: dimension 1 in the title's description of either kind. + const BUFFER: u32 = 1; + // R16G16B16A16, R16G16 and R16 (float, unsigned, signed), then + // R10G10B10A2, R8G8B8A8, R8G8 and R8 unsigned. + const EXACT: [u32; 13] = [10, 12, 14, 34, 36, 38, 54, 57, 59, 25, 30, 50, 62]; + let format = match view { + View::Shader(_, Some(desc)) | View::Unordered(_, _, Some(desc)) if desc[1] == BUFFER => { + desc[0] + } + View::Placed(_, resource, desc) if resource[0] == BUFFER && desc[1] == BUFFER => desc[0], + _ => return None, + }; + (!EXACT.contains(&format)).then_some(format) +} + fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { let mut words = *words; words[0] = crate::resource::pc_format(words[0]); @@ -627,6 +3051,27 @@ fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { } } +/// The format the host makes a typed buffer view in. Translated shaders +/// declare every typed buffer load and store as 32-bit float +/// (`victory_shader` `emit/lower.rs`), and a view in a 32-bit integer format +/// converts between float and integer values on the way: a store of an +/// integer's bits as a float is written as the integer the float rounds to +/// (zero for most of them), where the console moves the bits. The float +/// format of the same width moves them unchanged, and matches what the +/// shader declares. (The meshlet culling programs append packed meshlet +/// numbers to an `R32_UINT` list this way.) +fn bit_exact_format(format: DXGI_FORMAT) -> DXGI_FORMAT { + match format { + DXGI_FORMAT_R32G32B32A32_UINT | DXGI_FORMAT_R32G32B32A32_SINT => { + DXGI_FORMAT_R32G32B32A32_FLOAT + } + DXGI_FORMAT_R32G32B32_UINT | DXGI_FORMAT_R32G32B32_SINT => DXGI_FORMAT_R32G32B32_FLOAT, + DXGI_FORMAT_R32G32_UINT | DXGI_FORMAT_R32G32_SINT => DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R32_UINT | DXGI_FORMAT_R32_SINT => DXGI_FORMAT_R32_FLOAT, + other => other, + } +} + /// A buffer view of title memory at `address` on its host copy: the first /// element moves by the copy's offset. /// Bytes per element of a buffer view. @@ -674,6 +3119,72 @@ pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> { )) } +/// The title memory the host slot of buffer view `view` is made on +/// (address, bytes): the whole buffer the view is of, which is what +/// [`make`] finds the host copy by. [`buffer_range`] is the part of it the +/// view reads. +pub(crate) fn buffer_extent(view: &View) -> Option<(u64, u64)> { + match view { + View::Shader(r, Some(_)) | View::Unordered(r, _, Some(_)) => { + let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?; + Some((data as u64, len)) + } + View::Placed(_, resource, desc) if resource[0] == 1 => Some(( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + u64::from(resource[4]) | u64::from(resource[5]) << 32, + )), + _ => None, + } +} + +/// Whether a buffer view is brought up to date in the host copy its slot +/// shows ([`buffer_copy`]). On by default; `VICTORY_VIEW_EXTENT=0` looks the +/// copy up by the view's range alone, as before. +fn view_extent() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_EXTENT").is_none_or(|v| v != "0")) +} + +/// The host copy buffer view `view` reads, and the title range (address, +/// bytes) it reads there; `None` for other views and empty ranges. +/// +/// The copy is the one the view's slot shows: [`make`] finds it by the +/// whole buffer the view is of ([`buffer_extent`]). Looked up by the range +/// the view reads, as it was, the copy is another one wherever the two +/// lookups differ: for memory outside buffer objects, a view of a part of a +/// buffer that crosses a window line (the buffer's window is two cells, the +/// part's one), and for buffer objects, a part that also lies in a smaller +/// buffer object. The slot then showed a copy nothing brought up to date, +/// and what shaders wrote through it was looked for in the other copy. +pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc<crate::shadow::Shadow>, u64, u64)> { + let (address, len) = buffer_range(view)?; + if len == 0 { + return None; + } + // A view off its buffer's elements is made on a copy of its own bytes + // (`own_bytes`): the same question `buffer_srv` and `buffer_uav` ask, + // of the copy they find, so that the copy brought up to date is the + // one the slot shows. + if let Some((base, width)) = buffer_extent(view) + && let Some((first, count, element, stride, unknown)) = buffer_fields(view) + && let Some(whole) = crate::shadow::find(base, width) + && let Some((start, bytes)) = own_bytes(whole.offset(base), base, first, count, element, stride, unknown) + && let Some(own) = crate::shadow::exact(start, bytes) + { + return Some((own, start, bytes)); + } + if view_extent() + && let Some((base, width)) = buffer_extent(view) + // (The console is lax: a view may begin past its buffer's end.) + && address >= base + && address - base < width.max(1) + && let Some(shadow) = crate::shadow::find(base, width) + { + return Some((shadow, address, len)); + } + crate::shadow::find(address, len).map(|shadow| (shadow, address, len)) +} + /// [`buffer_range`] of an unordered access view of memory at `base`. fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { let desc = uav_desc(words); @@ -692,18 +3203,267 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { )) } -/// Whether a raw buffer view may start at element `first` (4 bytes each): -/// the host wants 16-byte aligned starts, the console only 4, and refuses -/// the call (removing the device) for the rest. -/// shortcut: a view the host refuses reads nothing (a null view); starting -/// it 16 bytes lower would need the shader to add the difference. -fn raw_start_fits(first: u64) -> bool { - first.is_multiple_of(4) -} - /// The host resource a slot made by [`make`] views, if any. type Kept = Option<ID3D12Resource>; +/// Whether the pass over records copied in as bytes also mirrors slots +/// that draws read through tables lately (`VICTORY_HEAP_SYNC_TABLES=1`; +/// off by default: [`HostHeap::mirror_copied`]). +fn sync_tables() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC_TABLES").is_some_and(|v| v == "1")) +} + +/// Since the last frame line: slots on changed heap pages that +/// [`HostHeap::mirror_copied`] left to their draws (tables' slots). +pub(crate) static COPIED_TABLED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +// What the view-heap pass's "make" does with each record it mirrors +// (`HostHeap::mirror_copied_page`; fps41 round 12), by outcome of +// `HostHeap::mirror`: made already (the lock-free look), not a view of +// ours, the same view as made (under the lock), the old view kept, left +// for later (a buffer or a texture with no host copy: a null view made), +// made (a host view created). Diagnostics only. +#[cfg(feature = "diagnostics")] +const MIRROR_UNSET: usize = 6; +/// Not inside the pass's timed `mirror` (draws and other passes mirror too). +#[cfg(feature = "diagnostics")] +const MIRROR_IDLE: usize = 7; +#[cfg(feature = "diagnostics")] +const MIRROR_FAST: usize = 0; +#[cfg(feature = "diagnostics")] +const MIRROR_NOT_VIEW: usize = 1; +#[cfg(feature = "diagnostics")] +const MIRROR_SAME: usize = 2; +#[cfg(feature = "diagnostics")] +const MIRROR_KEPT: usize = 3; +#[cfg(feature = "diagnostics")] +const MIRROR_LATER: usize = 4; +#[cfg(feature = "diagnostics")] +const MIRROR_MADE: usize = 5; +#[cfg(feature = "diagnostics")] +thread_local! { + /// The outcome of the `mirror` call being timed on this thread. + static MIRROR_HOW: std::cell::Cell<usize> = const { std::cell::Cell::new(MIRROR_IDLE) }; +} +/// By outcome (the six above and "other"): records, and their microseconds. +#[cfg(feature = "diagnostics")] +pub(crate) static MIRRORED: [std::sync::atomic::AtomicU64; 14] = [const { std::sync::atomic::AtomicU64::new(0) }; 14]; +/// Inside `mirror`, summed over the records: the buffer notes and the +/// unmaking of stale slots, creating the view (or the null one), keeping +/// the slot's resource (the old one retired). +#[cfg(feature = "diagnostics")] +pub(crate) static MIRROR_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +#[cfg(feature = "diagnostics")] +fn mirror_how(how: usize) { + MIRROR_HOW.with(|cell| { + if cell.get() == MIRROR_UNSET { + cell.set(how); + } + }); +} + +/// Whether this thread is inside the pass's timed `mirror`. +#[cfg(feature = "diagnostics")] +fn mirror_timing() -> bool { + MIRROR_HOW.with(|cell| cell.get() != MIRROR_IDLE) +} + +#[cfg(feature = "diagnostics")] +fn mirror_counted(us: u64) { + use std::sync::atomic::Ordering::Relaxed; + let how = MIRROR_HOW.with(|cell| cell.replace(MIRROR_IDLE)).min(MIRROR_UNSET); + MIRRORED[how].fetch_add(1, Relaxed); + MIRRORED[7 + how].fetch_add(us, Relaxed); +} + +/// A 64-bit fingerprint of a descriptor record's bytes (16 or 32 of them): +/// equal records give equal prints, and two different records the same +/// print about once in 2^64. Not a hash anyone can attack: the records +/// are our own. +fn record_print(record: &[u8]) -> u64 { + const K: u64 = 0x9e37_79b9_7f4a_7c15; + let mut h = K ^ record.len() as u64; + let mut words = record.chunks_exact(8); + for word in &mut words { + let w = u64::from_le_bytes(word.try_into().unwrap_or([0; 8])); + h = (h ^ w).wrapping_mul(K); + h ^= h >> 29; + } + for &b in words.remainder() { + h = (h ^ u64::from(b)).wrapping_mul(K); + } + h ^ (h >> 32) +} + +/// Diagnostics (`crate::draw::tables_line`): two fingerprints of the `n` +/// records of the table at `table`, as `crate::draw::State::tables` reads +/// them (the tag and two words of each 32-byte slot). The first is of the +/// records whole. The second takes a constant buffer view named whole in +/// its record (`super::constant_words`) by its size alone, without its +/// address: two tables with the same second fingerprint differ at most in +/// where their constants are. +#[cfg(feature = "diagnostics")] +pub(crate) fn table_prints(table: u64, n: u32) -> (u64, u64) { + const K: u64 = 0x9e37_79b9_7f4a_7c15; + let (mut whole, mut shape) = (K ^ u64::from(n), !K ^ u64::from(n)); + for k in 0..n { + let at = table + u64::from(k) * 32; + let [tag, i, generation] = super::record_at(at); + let mut bytes = [0u8; 12]; + bytes[..4].copy_from_slice(&tag.to_le_bytes()); + bytes[4..8].copy_from_slice(&i.to_le_bytes()); + bytes[8..].copy_from_slice(&generation.to_le_bytes()); + let print = record_print(&bytes); + whole = (whole ^ print).wrapping_mul(K); + whole ^= whole >> 29; + let constant = tag == VIEW_TAG && generation >> super::KIND_SHIFT == super::CONSTANT; + let part = if constant { + // The size's code: the 15 bits above the address's 47. + let code = (generation & super::GENERATIONS) >> (super::CONSTANT_ADDRESS_BITS - 32); + u64::from(code) | (1 << 40) + } else { + print + }; + shape = (shape ^ part).wrapping_mul(K); + shape ^= shape >> 29; + } + (whole, shape) +} + +/// Whether a buffer view off its buffer's elements gets a copy of its own +/// bytes (`VICTORY_VIEW_OWN_COPY=0`: it is refused and reads zeros, as +/// before). +fn own_copy_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_OWN_COPY").is_none_or(|v| v != "0")) +} + +/// The title memory (start, bytes) of a buffer view that cannot be made on +/// the host copy of its buffer: `count` elements of `element` bytes from +/// element `first` of the buffer at `base`, which lies `offset` bytes into +/// that copy, where `offset` is not a whole number of elements and the view +/// cannot be a raw view of the same bytes either ([`raw_window`]: +/// `unknown`, the view has no format, and `stride` is its structure's). +/// The host counts a view's first element from its buffer's start, so such +/// a view has no host view there; it is made on a copy of its own bytes +/// (`crate::shadow::exact`), where it starts at element 0. `None`: the +/// view is made on its buffer's copy, as every other. +fn own_bytes(offset: u64, base: u64, first: u64, count: u32, element: u64, stride: u32, unknown: bool) -> Option<(u64, u64)> { + own_bytes_if(own_copy_on(), offset, base, first, count, element, stride, unknown) +} + +#[allow(clippy::too_many_arguments)] +fn own_bytes_if( + on: bool, + offset: u64, + base: u64, + first: u64, + count: u32, + element: u64, + stride: u32, + unknown: bool, +) -> Option<(u64, u64)> { + if !on || element == 0 || count == 0 || offset.is_multiple_of(element) { + return None; + } + if unknown && raw_window(offset, first, count, stride).is_some() { + return None; + } + let start = base.checked_add(first.checked_mul(element)?)?; + Some((start, u64::from(count) * element)) +} + +/// Of a buffer view: its first element, its elements, the bytes of one (a +/// raw view's: 4), its structure's stride, and whether it has no format. +/// As [`buffer_srv`] and [`buffer_uav`] read them from the same words. +fn buffer_fields(view: &View) -> Option<(u64, u32, u64, u32, bool)> { + const BUFFER: u32 = 1; + let (words, unordered): (&[u32; 10], bool) = match view { + View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), + View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true), + View::Placed(unordered, resource, d) if resource[0] == BUFFER => (d[..10].try_into().ok()?, *unordered), + _ => return None, + }; + if unordered { + let d = uav_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { d.Anonymous.Buffer }; + let element = if b.StructureByteStride > 0 { + u64::from(b.StructureByteStride) + } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(d.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + Some((b.FirstElement, b.NumElements, element, b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN)) + } else { + let d = srv_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { d.Anonymous.Buffer }; + Some((b.FirstElement, b.NumElements, element_size(&d), b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN)) + } +} + +/// A structured buffer view (`first`, `count` elements of `stride` bytes, +/// `offset` bytes into its host copy) as a raw view of the same bytes: +/// its first dword and its dwords. Translated shaders read untyped buffers +/// as raw bytes at `element * stride + offset` (the stride from the +/// used-resource entry, or from the table by heap slot for a buffer picked +/// by index), and a raw read through a structured view gives zeros on +/// NVIDIA (reported upstream with PR #193; structured reads through raw +/// views were right there). So the host's view is raw whenever it can be: +/// the bytes must start on 16 (the host's raw view alignment) and be whole +/// dwords. A view that cannot stays structured. +fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, u32)> { + if stride == 0 { + return None; + } + let start = first.checked_mul(u64::from(stride))?.checked_add(offset)?; + let bytes = u64::from(count) * u64::from(stride); + (start % 16 == 0 && bytes % 4 == 0) + .then(|| u32::try_from(bytes / 4).ok().map(|dwords| (start / 4, dwords))) + .flatten() +} + +/// Whether the host accepts a buffer view with these fields of a buffer of +/// `width` bytes. It removes the device for one it does not (view creation +/// returns nothing), and the console is laxer: the title's heap holds +/// views past their memory's end, of no elements, of typeless formats +/// without the raw flag, with strides the host has no structured buffers +/// for. Since every buffer view of the heap is made for shaders that pick +/// them by index, one such view ended the run (2026-11-24, run 10). +fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> bool { + use crate::resource::family; + let f = format.0 as u32; + let element = if raw { + // raw: R32 typeless, counted in dwords, starting on 16 bytes + if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || !first.is_multiple_of(4) { + return false; + } + 4 + } else if stride > 0 { + // structured: no format, a stride the host takes + if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || !stride.is_multiple_of(4) { + return false; + } + u64::from(stride) + } else { + // typed: a format with a size that is not typeless + let typeless = family(f) == f && family(f + 1) == f; + match crate::resource::element(f) { + Some((bytes, 1)) if f != 0 && !typeless && bytes > 0 => bytes, + _ => return false, + } + }; + count > 0 + && first + .checked_add(u64::from(count)) + .and_then(|end| end.checked_mul(element)) + .is_some_and(|end| end <= width) +} + fn buffer_srv( address: u64, len: u64, @@ -711,23 +3471,83 @@ fn buffer_srv( at: D3D12_CPU_DESCRIPTOR_HANDLE, ) -> Option<Kept> { let shadow = crate::shadow::find(address, len)?; + let offset = shadow.offset(address); + // Off the elements of that copy: on a copy of its own bytes, from its + // element 0 (`own_bytes`). + let (shadow, offset) = { + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + let unknown = desc.Format == DXGI_FORMAT_UNKNOWN; + match own_bytes(offset, address, b.FirstElement, b.NumElements, element_size(&desc), b.StructureByteStride, unknown) + .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) + { + Some(own) => { + desc.Anonymous.Buffer.FirstElement = 0; + (own, 0) + } + None => (shadow, offset), + } + }; + // A structured view as a raw view of the same bytes (see `raw_window`). + // SAFETY: a buffer view's union member. + let structured = unsafe { desc.Anonymous.Buffer }; + let window = (desc.Format == DXGI_FORMAT_UNKNOWN) + .then(|| raw_window(offset, structured.FirstElement, structured.NumElements, structured.StructureByteStride)) + .flatten(); + if let Some((first, count)) = window { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_SRV { + FirstElement: first, + NumElements: count, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }; + } + desc.Format = bit_exact_format(desc.Format); let element = element_size(&desc); // SAFETY: a buffer view's union member. let buffer = unsafe { &mut desc.Anonymous.Buffer }; - let offset = shadow.offset(address); - if element == 0 || offset % element != 0 { + if window.is_none() { + if element == 0 || offset % element != 0 { + once!( + offset, + element, + "buffer view not on an element of its host copy" + ); + return None; + } + buffer.FirstElement += offset / element; + } + let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); + let mut raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; + if count == 0 { + EMPTY_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return None; + } + if raw && !first.is_multiple_of(4) && raw_as_typed() { + buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + desc.Format = DXGI_FORMAT_R32_UINT; + raw = false; + RAW_TYPED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + // SAFETY: a live buffer. + let width = unsafe { shadow.buffer.GetDesc() }.Width; + if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { + REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); once!( - offset, - element, - "buffer view not on an element of its host copy" + format = desc.Format.0, + first, + count, + stride, + raw, + width, + "buffer view the host would refuse left null" ); return None; } - buffer.FirstElement += offset / element; - if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 && !raw_start_fits(buffer.FirstElement) { - let first = buffer.FirstElement; - once!(first, "raw buffer view not on 16 bytes of its host copy"); - return None; + // The console has no component mapping; one the host does not know is the default's. + if desc.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING { + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; } let host = host()?; // SAFETY: a live buffer and a slot of our heap. @@ -750,6 +3570,29 @@ fn buffer_uav( at: D3D12_CPU_DESCRIPTOR_HANDLE, ) -> Option<Kept> { let shadow = crate::shadow::find(address, len)?; + // Off the elements of that copy: on a copy of its own bytes, from its + // element 0 (`own_bytes`). + let (shadow, own) = { + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + let element = if b.StructureByteStride > 0 { + u64::from(b.StructureByteStride) + } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + let unknown = desc.Format == DXGI_FORMAT_UNKNOWN; + match own_bytes(shadow.offset(address), address, b.FirstElement, b.NumElements, element, b.StructureByteStride, unknown) + .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) + { + Some(own) => { + desc.Anonymous.Buffer.FirstElement = 0; + (own, true) + } + None => (shadow, false), + } + }; // SAFETY: a live buffer. let flags = unsafe { shadow.buffer.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { @@ -765,75 +3608,68 @@ fn buffer_uav( } else { crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) }; - let offset = shadow.offset(address); - if element == 0 || offset % element != 0 { - once!( - offset, - element, - "unordered buffer view not on an element of its host copy" - ); + let offset = if own { 0 } else { shadow.offset(address) }; + // A structured view as a raw view of the same bytes (see `raw_window`). + let window = (desc.Format == DXGI_FORMAT_UNKNOWN) + .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride)) + .flatten(); + if let Some((first, count)) = window { + buffer.FirstElement = first; + buffer.NumElements = count; + buffer.StructureByteStride = 0; + buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } else { + if element == 0 || offset % element != 0 { + once!(offset, element, "unordered buffer view not on an element of its host copy"); + return None; + } + buffer.FirstElement += offset / element; + } + buffer.CounterOffsetInBytes = 0; + let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); + let raw = buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; + desc.Format = bit_exact_format(desc.Format); + if window.is_some() { + // (Left out at first: every structured unordered access view was then + // refused by `buffer_view_ok` and left null, runs 15 and 16.) + desc.Format = DXGI_FORMAT_R32_TYPELESS; + } + if count == 0 { + EMPTY_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); return None; } - buffer.FirstElement += offset / element; - if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 && !raw_start_fits(buffer.FirstElement) { - let first = buffer.FirstElement; + // SAFETY: a live buffer. + let width = unsafe { shadow.buffer.GetDesc() }.Width; + if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { + REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); once!( + format = desc.Format.0, first, - "raw unordered buffer view not on 16 bytes of its host copy" + count, + stride, + raw, + width, + "unordered buffer view the host would refuse left null" ); return None; } - buffer.CounterOffsetInBytes = 0; let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { - host.device.CreateUnorderedAccessView( - &shadow.buffer, - None::<&ID3D12Resource>, - Some(&desc), - at, - ) + host.device + .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) }; Some(Some(shadow.buffer.clone())) } -/// Whether the host lets views of a typed resource name another format of -/// its family (`CastingFullyTypedFormatSupported`; never SNORM for UNORM, -/// nor FLOAT for another type), which [`fits`] uses for sRGB and linear -/// twins only. -fn casts_typed() -> bool { - static CASTS: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *CASTS.get_or_init(|| { - let Some(host) = host() else { return false }; - let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); - // SAFETY: the query writes its own structure of the given size. - let asked = unsafe { - host.device.CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS3, - (&raw mut options).cast(), - size_of_val(&options) as u32, - ) - }; - let casts = asked.is_ok() && options.CastingFullyTypedFormatSupported.as_bool(); - if !casts { - tracing::warn!( - "the host does not cast typed formats: sRGB views of linear textures (and the reverse) read in the texture's own format" - ); - } - casts - }) -} - /// Whether the host can make a shader (or unordered access) view of /// `texture` in `format` (none: the texture's own). The console allows any /// view; the host refuses (and removes the device for) views without the /// resource's permission, of typed depth, and in another format than a -/// typed resource's, but for casts it allows (see [`casts_typed`]). A view -/// of a typed texture in another format of its family takes the texture's -/// format, unless it is the texture's sRGB or linear twin and the host -/// casts: then the hardware converts (or not) as the console does. -/// shortcut: other casts within a family (UINT of UNORM, say) read as the -/// texture's own format. +/// typed resource's. A view of a typed texture in another format of its +/// family takes the texture's format. +/// shortcut: such a view (sRGB of UNORM, say) reads without its +/// conversion; cast with castable formats if colors come out wrong. fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool { use crate::resource::{DEPTH_FORMATS, family}; // SAFETY: a live resource. @@ -845,6 +3681,9 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere }; let own = d.Format.0 as u32; if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) { + if unordered { + crate::resource::DEPTH_UNORDERED[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } once!( unordered, format = own, @@ -867,8 +3706,8 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere if view == 0 { return !typeless; } - // A texture whose console format PC forbids as a render target or UAV - // was substituted (`resource::target_format`): views name its host format. + // A view of a target whose format the host refuses, in the title's + // format: in the stand-in the host copy has. if view != own && crate::resource::target_format(view) == own { if let Some(format) = format { *format = d.Format; @@ -879,60 +3718,102 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere once!(view, own, "view format of another family"); return false; } - let twin = crate::resource::SRGB - .iter() - .any(|&(s, l)| (s, l) == (view, own) || (l, s) == (view, own)); if let Some(format) = format && !typeless - && !(twin && casts_typed()) { *format = d.Format; } true } -/// A shader view of a typeless depth texture names the readable aspect. -/// For a 2D view D3D12 also requires the plane index to match that format. -fn texture_srv_desc( - resource: &D3D12_RESOURCE_DESC, - words: &[u32; 10], -) -> D3D12_SHADER_RESOURCE_VIEW_DESC { - let mut view = srv_desc(words); - if !resource - .Flags - .contains(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) - { - return view; +/// The title's unordered access view of a depth texture, as a view of the +/// texture's colour twin `twin` ([`crate::resource::Twin`]): the same mip +/// and slices, in the colour format of the twin's family for a depth or +/// typeless format (R16_UNORM for 16-bit depth, R32_FLOAT for 32-bit; the +/// bits are the same). Without a description: mip 0 of every slice. +/// The twin of a stencil plane (R8) stands for the views of that plane +/// only, which become R8_UINT views of its one plane; `None` for a view of +/// the depth plane, which the twin does not stand for. The depth plane has +/// a twin of its own, viewed as a depth texture's without stencil: a view +/// in the format of the depth plane of a depth-stencil format (21, 46) +/// takes the twin's colour format too. +fn twin_uav( + twin: &ID3D12Resource, + desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, +) -> Option<D3D12_UNORDERED_ACCESS_VIEW_DESC> { + // SAFETY: a live resource. + let d = unsafe { twin.GetDesc() }; + let mut desc = desc.cloned().unwrap_or_else(|| { + let mut all = D3D12_UNORDERED_ACCESS_VIEW_DESC { + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + if d.DepthOrArraySize > 1 { + all.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + all.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { + ArraySize: u32::from(d.DepthOrArraySize), + ..Default::default() + }; + } + all + }); + // A stencil plane's twin (R8 typeless, 60): the title's view is of the + // stencil plane if it names plane 1 or a stencil view format (22, 47). + if d.Format.0 == 60 { + let mut plane = 0; + match desc.ViewDimension { + D3D12_UAV_DIMENSION_TEXTURE2D => { + // SAFETY: the member the dimension names. + let mut view = unsafe { desc.Anonymous.Texture2D }; + plane = std::mem::take(&mut view.PlaneSlice); + desc.Anonymous.Texture2D = view; + } + D3D12_UAV_DIMENSION_TEXTURE2DARRAY => { + // SAFETY: the member the dimension names. + let mut view = unsafe { desc.Anonymous.Texture2DArray }; + plane = std::mem::take(&mut view.PlaneSlice); + desc.Anonymous.Texture2DArray = view; + } + _ => {} + } + if plane != 1 && !matches!(desc.Format.0, 22 | 47) { + return None; + } + desc.Format.0 = 62; + return Some(desc); } - let (dsv, depth, stencil) = match resource.Format { - DXGI_FORMAT_R32G8X24_TYPELESS => ( - DXGI_FORMAT_D32_FLOAT_S8X24_UINT, - DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, - Some(DXGI_FORMAT_X32_TYPELESS_G8X24_UINT), - ), - DXGI_FORMAT_R24G8_TYPELESS => ( - DXGI_FORMAT_D24_UNORM_S8_UINT, - DXGI_FORMAT_R24_UNORM_X8_TYPELESS, - Some(DXGI_FORMAT_X24_TYPELESS_G8_UINT), - ), - DXGI_FORMAT_R32_TYPELESS => (DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R32_FLOAT, None), - DXGI_FORMAT_R16_TYPELESS => (DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM, None), - _ => return view, - }; - let plane = if Some(view.Format) == stencil { - 1 - } else if [DXGI_FORMAT_UNKNOWN, resource.Format, dsv, depth].contains(&view.Format) { - view.Format = depth; - 0 - } else { - return view; + // None, typeless and depth formats (R16: 0, 53, 55; R32: 0, 39, 40), + // and those of a depth-stencil format's depth plane (19 to 21, 44 to + // 46), for the twin of such a plane. + desc.Format.0 = match (desc.Format.0, d.Format.0) { + (0 | 53 | 55 | 19..=21 | 44..=46, 53) => 56, + (0 | 39 | 40 | 19..=21 | 44..=46, 39) => 41, + (other, _) => other, }; - match view.ViewDimension { - D3D12_SRV_DIMENSION_TEXTURE2D => view.Anonymous.Texture2D.PlaneSlice = plane, - D3D12_SRV_DIMENSION_TEXTURE2DARRAY => view.Anonymous.Texture2DArray.PlaneSlice = plane, - _ => {} + Some(desc) +} + +/// The size of a constant buffer view the host takes: 256-byte steps, and +/// at most 4,096 vectors (65,536 bytes, `D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT`). +/// The title names constant views of more (one of 1,306,368 bytes, in the +/// world); `CreateConstantBufferView` with such a size is an invalid call, +/// and NVIDIA removes the device for it (`DXGI_ERROR_INVALID_CALL`), in +/// the frame the view is made. A shader reads at most 4,096 vectors through +/// a constant view, so nothing it can read is lost. +fn constant_view_size(size: u32) -> u32 { + const MOST: u32 = 4096 * 16; + // The cap before the rounding (fork pull request #1206): a size within + // 255 of the largest number would round past it, to 0 in a release + // build, and a view of no bytes be made with no line said. + if size > MOST { + once!(size, "a constant buffer view over 64 KiB, made 64 KiB (the host takes no more)"); + return MOST; } - view + // A view of no bytes stays one: a shader reads zeros through it, as on the + // console. Rounded up from 1 it became 256 bytes of whatever lies at its + // address in the host copy (the ring of per-draw constants among it), other + // bytes every frame: a floor in the first rooms flickered. + size.next_multiple_of(256) } /// Makes the host descriptor for `view` at `at`: the host resource it @@ -953,7 +3834,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> { } let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, - SizeInBytes: size.next_multiple_of(256), + SizeInBytes: constant_view_size(size), }; // SAFETY: a slot of our heap; the range lies in the host copy. unsafe { device.CreateConstantBufferView(Some(&desc), at) }; @@ -962,12 +3843,71 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> { View::Shader(resource, desc) => { let resource = *resource as crate::object::This; if let Some(texture) = crate::resource::host_resource(resource) { - // SAFETY: a live host texture. - let info = unsafe { texture.GetDesc() }; - let mut desc = desc.as_ref().map(|words| texture_srv_desc(&info, words)); + // The title's views of textures with a stencil plane, as it + // describes them (format, dimension, component mapping, a + // pad, then first level, levels, plane): each distinct one + // once. They say how its shaders read the stencil plane + // (the lighting takes each pixel's material class and its + // "inside a room" bit from it). + #[cfg(feature = "diagnostics")] + { + // SAFETY: a live resource. + let own = unsafe { texture.GetDesc() }.Format.0; + if matches!(own, 19..=22 | 44..=47) { + static SEEN: Mutex<Vec<(i32, Option<[u32; 10]>)>> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.len() < 64 && !seen.contains(&(own, *desc)) { + seen.push((own, *desc)); + tracing::info!( + ?resource, + texture_format = own, + view = ?desc, + "shader view of a depth-stencil texture" + ); + } + } + } + let mut desc = desc.as_ref().map(srv_desc); if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { return None; } + // Levels on demand: a texture made level by level with no + // level that has memory yet reads zeros, drawn black: a + // placeholder of its kind instead ([`placeholder`]), until + // a level gets memory and the slot is made again. + if crate::resource::host_tiled(resource) + .is_some_and(|t| t.tiled().is_some_and(|t| t.first_shown().is_none())) + && let Some(d) = &desc + && placeholder(d.Format, d.ViewDimension.0 as u32, at, true) + { + return Some(Some(texture.clone())); + } + // Levels on demand (`crate::tiles`): a texture made level by + // level is shown from the first level that is the title's + // and has memory, if the title's view starts before it (a + // level without memory reads zeros: a black texture). The + // title's own view mostly starts there already. + if let Some(first) = crate::resource::first_shown(resource) + && first > 0 + { + // SAFETY: a live resource. + let own = unsafe { texture.GetDesc() }; + // The texture's own view (the title gave none): all of it. + let whole = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: own.Format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: u32::MAX, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }; + crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels)); + } // SAFETY: a live texture and a slot of our heap. unsafe { device.CreateShaderResourceView( @@ -995,7 +3935,37 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> { _ => None, }; }; + // The first such views of depth textures are logged as the + // title describes them (format, dimension, then mip, slices and + // plane): they say which planes shaders write, and as what. + if crate::resource::depth_and_unordered(resource) { + static LOGGED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 512 { + tracing::info!( + ?resource, + view = ?desc, + "unordered access view of a depth texture" + ); + } + } let mut desc = desc.as_ref().map(uav_desc); + // A depth texture's unordered access is its colour twin's: the + // host gives a depth texture none. + let twin = crate::resource::twin_resource(resource) + .and_then(|twin| Some((twin, twin_uav(twin, desc.as_ref())?))) + // A view of the depth plane of a texture with a stencil + // plane: of that plane's own twin. + .or_else(|| { + let twin = crate::resource::twin_plane_resource(resource)?; + Some((twin, twin_uav(twin, desc.as_ref())?)) + }); + let texture = match twin { + Some((twin, view)) => { + desc = Some(view); + twin + } + None => texture, + }; if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { return None; } @@ -1012,17 +3982,19 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> { } View::Sampler(words) => { // SAFETY: 13 words in the host's layout. - let desc = unsafe { + let mut desc = unsafe { std::ptr::from_ref(words) .cast::<D3D12_SAMPLER_DESC>() .read_unaligned() }; + crate::sampler::enhance(&mut desc); // SAFETY: a slot of our sampler heap. unsafe { device.CreateSampler(&desc, at) }; Some(None) } View::ConsoleSampler(words) => { - let desc = crate::sampler::console(words); + let mut desc = crate::sampler::console(words); + crate::sampler::enhance(&mut desc); // SAFETY: a slot of our sampler heap. unsafe { device.CreateSampler(&desc, at) }; Some(None) @@ -1033,19 +4005,24 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> { } const BUFFER: u32 = 1; if resource[0] != BUFFER { + // Counted by kind: a shader view lands here only if no + // resource could be made at its address. + PLACED_NOT_MADE[usize::from(*unordered)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); // shortcut: unordered access to a texture the title placed // itself is not mirrored; give it a resource as shader // views of such textures get when a dispatch writes one. - once!( - dimension = resource[0], - "placed unordered texture view not mirrored" - ); + once!(dimension = resource[0], "placed unordered texture view not mirrored"); return None; } // The resource description's width, after the alignment. let len = u64::from(resource[4]) | u64::from(resource[5]) << 32; let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]); + // An empty title buffer: nothing to view, and no host copy to + // look for (#70: such views were in flight at device removals). + if len == 0 { + return None; + } if *unordered { buffer_uav(address, len, uav_desc(words), at) } else { @@ -1055,6 +4032,135 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> { } } +/// Placed texture views [`make`] could not make, since the start: shader +/// views (no resource at the address) and unordered access views. +pub(crate) static PLACED_NOT_MADE: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Writes of a slot with another view of the placed texture it showed, +/// since the start: the slot kept showing the old view. +pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether a slot written with another view of the placed texture it +/// shows keeps showing the old one until the new is made; +/// `VICTORY_KEEP_VIEWS=0` makes it null at once, as before. +fn keep_views() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0")) +} + +/// What the texture view a slot is written with has to do with the one it +/// shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kin { + /// A view of the same placed texture ([`same_placed_texture`]). + Same, + /// A texture of the same description placed elsewhere (moved, or one of + /// its kind). + Moved, + /// One of the same format and shape in another size: the same texture + /// with more or fewer levels, as a title streams it. + Sized, + /// A view of the same dimension, of another texture. + Other, + /// A view no shader that reads the one can read. + None, +} + +impl Kin { + /// Whether the slot goes on showing what it shows, by [`keep_shown`]. + fn kept(self, keep: u8) -> bool { + match self { + Kin::Same => true, + Kin::Moved | Kin::Sized => keep >= 1, + Kin::Other => keep >= 2, + Kin::None => false, + } + } +} + +/// [`Kin`] of the view `old`, which a slot shows, and `new`. +fn kin(old: &View, new: &View) -> Kin { + if same_placed_texture(old, new) { + return Kin::Same; + } + if let (View::Placed(false, a, from), View::Placed(false, b, to)) = (old, new) { + if a[0] == 1 || b[0] == 1 || from[1] != to[1] { + return Kin::None; + } + // (Width, 64 bits, height, depth and levels, format: words 4 to 8.) + if a[0] == b[0] && a[2..13] == b[2..13] { + return Kin::Moved; + } + let (wide, high) = ([a[4], b[4]].map(u64::from), [a[6], b[6]].map(u64::from)); + return if from[0] == to[0] && a[0] == b[0] && wide[0] * high[1] == wide[1] * high[0] { + Kin::Sized + } else { + Kin::Other + }; + } + let dimension = |view: &View| match view { + View::Placed(false, resource, desc) if resource[0] != 1 => desc[1], + View::Shader(r, Some(desc)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => desc[1], + _ => 0, + }; + match (dimension(old), dimension(new)) { + (0, _) | (_, 0) => Kin::None, + (a, b) if a == b => Kin::Other, + _ => Kin::None, + } +} + +/// Whether a slot that is written with a view of another texture goes on +/// showing the one it shows until the new one is made and its upload has run +/// (`VICTORY_KEEP_SHOWN`): 0: never, it reads as zeros, then as the neutral +/// texture; 1: one of the same kind in another place or size; 2: any of the +/// same dimension. +fn keep_shown() -> u8 { + static KEEP: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *KEEP.get_or_init(|| std::env::var("VICTORY_KEEP_SHOWN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1)) +} + +/// Slots that showed a texture and were written with a view of another, +/// since the start, by [`Kin`] (moved, sized, other, none), and those of +/// them that kept what they showed. +static REWRITTEN: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +fn rewritten(kin: Kin, kept: bool) { + use std::sync::atomic::Ordering::Relaxed; + let class = match kin { + Kin::Moved | Kin::Same => 0, + Kin::Sized => 1, + Kin::Other => 2, + Kin::None => 3, + }; + REWRITTEN[class].fetch_add(1, Relaxed); + REWRITTEN[4].fetch_add(u64::from(kept), Relaxed); + let n: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum(); + if n.is_multiple_of(5000) { + tracing::info!( + "slots that showed a texture and were written with another, since the start: {} of the same kind elsewhere, {} of another size, {} others, {} of another dimension; {} of them kept what they showed meanwhile (VICTORY_KEEP_SHOWN)", + REWRITTEN[0].load(Relaxed), + REWRITTEN[1].load(Relaxed), + REWRITTEN[2].load(Relaxed), + REWRITTEN[3].load(Relaxed), + REWRITTEN[4].load(Relaxed) + ); + } +} + +/// Whether both are shader views of one texture the title placed in +/// memory: the same address and the same resource description, whatever +/// part of it each shows. +fn same_placed_texture(a: &View, b: &View) -> bool { + match (a, b) { + (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => { + resource[0] != 1 && resource == other && desc[10..12] == other_desc[10..12] + } + _ => false, + } +} + /// A shader view of a texture the title placed in memory itself, as a view /// of the resource made for that memory (on first use). pub(crate) fn placed_texture(view: &View) -> Option<View> { @@ -1071,8 +4177,8 @@ pub(crate) fn placed_texture(view: &View) -> Option<View> { } /// A null view of the kind `view` is, for a slot whose view the host -/// cannot make: unordered access (to a buffer or a texture of the title's -/// dimension) or a shader view. Writes to it are dropped, reads give zeros. +/// cannot make: unordered access (to a buffer or a 2D texture) or a shader +/// view. Writes to it are dropped, reads give zeros. fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some(); @@ -1093,9 +4199,21 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at), // Textures: a null view of the title's dimension (1D, arrays, 3D, // cubes), not always 2D. - View::Shader(_, Some(desc)) => return null_like(desc, at), + View::Shader(_, Some(desc)) => { + // A texture not there yet (or gone): a placeholder of its kind + // ([`placeholder`]), block-compressed formats only (never a + // render target, so always one the title fills). + if placeholder_like(desc, at, false) { + return; + } + return null_like(desc, at); + } View::Placed(false, _, desc) => { - return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at); + let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]); + if placeholder_like(words, at, false) { + return; + } + return null_like(words, at); } View::Constant(..) => { let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default(); @@ -1127,7 +4245,7 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { /// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays, /// 3D), 2D if it names none: a 2D null view where the shader writes a 3D /// texture is a mismatch GPU-based validation reports (the world's wind -/// field update, 2026-11-24). +/// field, CS_CopyWindFieldBeforeUpdateWithSmooth, 2026-11-24). fn null_uav_desc(dimension: Option<u32>) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_UINT, @@ -1187,6 +4305,163 @@ fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { }; } +/// Try 5.8, placeholders (as emulators with asynchronous textures show +/// one until the real texture is ready): a texture slot whose texture is +/// not on the card yet (waiting for room, for its memory, for its turn in +/// the queue) read zeros, so whatever used it drew black: walls, roads +/// and faces in every report, 22,000 textures waiting. Now it reads a +/// one-texel texture of what its kind most likely holds, told by its +/// format: +/// - colour formats in sRGB (block-compressed or not): a mid grey +/// (surfaces look unpainted, not black), opaque. Not the ones with an +/// explicit alpha (BC2, BC3), mostly cut-outs (leaves, fences): those +/// stay transparent rather than grey squares; +/// - two-channel normal maps (BC5, unsigned): a flat normal, so light falls +/// on the surface as on a plain one (zeros tilt it fully sideways); +/// - one-channel maps (BC4, unsigned: occlusion, roughness, masks): white, +/// unshadowed and matte (zeros are fully occluded, black). +/// +/// Anything else reads zeros as before. `VICTORY_PLACEHOLDERS=0`: off. +/// Writes the view into `at`; false when it does not (the caller makes +/// its null view). +/// `any`: uncompressed sRGB formats too (only for textures known to be the +/// title's to fill: those may also be render targets otherwise). +fn placeholder(format: DXGI_FORMAT, dimension: u32, at: D3D12_CPU_DESCRIPTOR_HANDLE, any: bool) -> bool { + const TEXTURE2D: u32 = 4; + const TEXTURE2DARRAY: u32 = 5; + if dimension != TEXTURE2D && dimension != TEXTURE2DARRAY { + return false; + } + let kind = match format { + DXGI_FORMAT_BC1_UNORM_SRGB | DXGI_FORMAT_BC7_UNORM_SRGB => 0, + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB | DXGI_FORMAT_B8G8R8X8_UNORM_SRGB + if any => + { + 0 + } + DXGI_FORMAT_BC5_UNORM => 1, + DXGI_FORMAT_BC4_UNORM => 2, + _ => return false, + }; + let Some(textures) = placeholders() else { + return false; + }; + let Some(host) = host() else { + return false; + }; + let desc = if dimension == TEXTURE2D { + D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + } + } else { + D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MipLevels: 1, + ArraySize: 1, + ..Default::default() + }, + }, + } + }; + PLACEHOLDERS_SHOWN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // SAFETY: a live texture of ours and a slot of our heap. + unsafe { host.device.CreateShaderResourceView(&textures.0[kind], Some(&desc), at) }; + true +} + +/// [`placeholder`] for a title's view description. +fn placeholder_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE, any: bool) -> bool { + let desc = srv_desc(words); + placeholder(desc.Format, desc.ViewDimension.0 as u32, at, any) +} + +/// Slots given a placeholder since the start. +pub(crate) static PLACEHOLDERS_SHOWN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The three placeholder textures (grey, flat normal, white). +struct Placeholders([ID3D12Resource; 3]); + +// SAFETY: D3D12 resources are free-threaded; these are only read. +unsafe impl Send for Placeholders {} +// SAFETY: as above. +unsafe impl Sync for Placeholders {} + +/// The placeholder textures, made once: one texel each, in memory the CPU +/// writes (a custom heap), filled with `WriteToSubresource`, read by +/// shaders from the common state. +fn placeholders() -> Option<&'static Placeholders> { + static MADE: std::sync::OnceLock<Option<Placeholders>> = std::sync::OnceLock::new(); + MADE.get_or_init(|| { + if std::env::var_os("VICTORY_PLACEHOLDERS").is_some_and(|v| v == "0") { + return None; + } + let host = host()?; + // Linear values (the views read them as UNORM): grey 0.3, a flat + // normal, white. + let texels: [[u8; 4]; 3] = [[77, 77, 77, 255], [128, 128, 255, 255], [255, 255, 255, 255]]; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + CreationNodeMask: 0, + VisibleNodeMask: 0, + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + ..Default::default() + }; + let mut made = Vec::with_capacity(3); + for texel in &texels { + let mut texture: Option<ID3D12Resource> = None; + // SAFETY: plain creation; then the texture is mapped (no + // pointer: a texture), written and unmapped, all on our own + // data. + let done = unsafe { + host.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut texture) + .and_then(|()| { + let t = texture.as_ref().ok_or_else(windows::core::Error::empty)?; + t.Map(0, None, None)?; + let written = t.WriteToSubresource(0, None, texel.as_ptr().cast(), 4, 4); + t.Unmap(0, None); + written + }) + }; + match (done, texture) { + (Ok(()), Some(texture)) => made.push(texture), + (Err(e), _) => { + tracing::warn!(error = %e, "no placeholder textures: textures not there yet read zeros (black) as before"); + return None; + } + _ => return None, + } + } + let made: [ID3D12Resource; 3] = made.try_into().ok()?; + tracing::info!("placeholder textures made: textures not on the card yet show grey, flat or white instead of black (VICTORY_PLACEHOLDERS=0: off)"); + Some(Placeholders(made)) + }) + .as_ref() +} + /// A texture view that reads zeros with the dimension (and mip and array /// counts) of the title's description `words`; 2D if it names none. fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) { @@ -1242,6 +4517,333 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// A full list of changed ranges is made smaller, never emptied: every + /// change is still covered (edsuuu/VI-BR-PORT 87dc3075). + #[test] + fn a_full_change_list_keeps_every_change() { + let mut ranges: Vec<(u64, u64)> = (0..10u64).map(|i| (i * 10, i * 10 + 1)).collect(); + compact(&mut ranges, 8); + assert!(ranges.len() <= 4); + for i in 0..10u64 { + assert!(ranges.iter().any(|r| r.0 <= i * 10 && i * 10 < r.1), "change {i} lost"); + } + let mut touching = vec![(0, 5), (5, 9), (20, 30)]; + compact(&mut touching, 4); + assert_eq!(touching, [(0, 9), (20, 30)]); + } + + /// A range of dynamic slots is given back only to the heap that took it: + /// the title can release a heap while a list still holds slots of it, + /// and a later heap can be made at the same address before that list is + /// reset. + #[cfg(windows)] + #[test] + fn dynamic_slots_are_given_back_only_to_the_heap_that_took_them() { + use std::sync::atomic::Ordering::Relaxed; + let Some(a) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + let Some(b) = HostHeap::new(false, 4) else { + return; + }; + assert_ne!(a.id(), b.id()); + let first = a.dynamic(2).expect("two dynamic slots"); + let free = a.free.load(Relaxed); + a.release(b.id(), first, 2); + assert_eq!( + a.free.load(Relaxed), + free, + "another heap's identity gave the range back" + ); + a.release(a.id(), first, 2); + assert_eq!( + a.free.load(Relaxed), + free + 2, + "their own heap did not get the range back" + ); + } + + /// A constant view is made in 256-byte steps and at most 64 KiB, the + /// most the host takes (a larger size removes the device on NVIDIA). + #[test] + fn constant_views_are_at_most_64_kib() { + assert_eq!(constant_view_size(0), 0); + assert_eq!(constant_view_size(1), 256); + assert_eq!(constant_view_size(16), 256); + assert_eq!(constant_view_size(256), 256); + assert_eq!(constant_view_size(65_536), 65_536); + assert_eq!(constant_view_size(1_306_368), 65_536); + assert_eq!(constant_view_size(65_537), 65_536); + assert_eq!(constant_view_size(u32::MAX), 65_536); + assert_eq!(constant_view_size(u32::MAX - 100), 65_536); + } + + /// Typed buffer views of 32-bit integer formats are made in the float + /// format of the same width (the shaders' float loads and stores then + /// move the bits); every other format is the title's. + #[test] + fn typed_buffer_views_of_32_bit_integers_move_bits() { + for (title, host) in [ + (DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_FLOAT), + (DXGI_FORMAT_R32_SINT, DXGI_FORMAT_R32_FLOAT), + (DXGI_FORMAT_R32G32_UINT, DXGI_FORMAT_R32G32_FLOAT), + (DXGI_FORMAT_R32G32B32_SINT, DXGI_FORMAT_R32G32B32_FLOAT), + (DXGI_FORMAT_R32G32B32A32_UINT, DXGI_FORMAT_R32G32B32A32_FLOAT), + ] { + assert_eq!(bit_exact_format(title), host); + assert_eq!( + crate::resource::element(title.0 as u32), + crate::resource::element(host.0 as u32) + ); + } + for kept in [ + DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_UNKNOWN, + DXGI_FORMAT_R16G16_UINT, + DXGI_FORMAT_R8G8B8A8_UNORM, + ] { + assert_eq!(bit_exact_format(kept), kept); + } + } + + /// The unsigned twin of a 16-bit float or signed format has its layout, + /// and only buffer views in such a format are shown as another view. + #[test] + fn only_16_bit_float_and_signed_buffer_views_get_an_unsigned_twin() { + for (format, unsigned) in [(10, 12), (14, 12), (34, 36), (38, 36), (54, 57), (59, 57)] { + assert_eq!(half_format(format), Some(unsigned)); + assert_eq!( + crate::resource::element(format), + crate::resource::element(unsigned), + "format {format}" + ); + } + // The unsigned formats themselves, normalised 16-bit formats, and + // wider and narrower ones. + for other in [0, 12, 36, 57, 11, 13, 35, 37, 56, 58, 42, 17, 30, 61] { + assert_eq!(half_format(other), None, "format {other}"); + } + const BUFFER: u32 = 1; + let words = |format: u32, dimension: u32| [format, dimension, 5768, 0, 0, 0, 64, 0, 0, 0]; + // R16G16B16A16_FLOAT: a buffer of halves a program moves as they are. + assert_eq!( + half_view(&View::Unordered(7, 0, Some(words(10, BUFFER)))), + Some(View::Unordered(7, 0, Some(words(12, BUFFER)))) + ); + assert_eq!( + half_view(&View::Shader(7, Some(words(54, BUFFER)))), + Some(View::Shader(7, Some(words(57, BUFFER)))) + ); + let mut placed = [0u32; 16]; + placed[..10].copy_from_slice(&words(38, BUFFER)); + placed[10] = 0x1234_0000; + let mut twin = placed; + twin[0] = 36; + let memory = [BUFFER, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0]; + assert_eq!( + half_view(&View::Placed(true, memory, placed)), + Some(View::Placed(true, memory, twin)) + ); + // The title's kind (R16G16B16A16_UINT and R16_UINT buffers), a + // texture view (dimension 4: 2D), a view without a description, a + // constant buffer: the title's own. + assert_eq!( + half_view(&View::Unordered(7, 0, Some(words(12, BUFFER)))), + None + ); + assert_eq!(half_view(&View::Shader(7, Some(words(57, BUFFER)))), None); + assert_eq!(half_view(&View::Unordered(7, 0, Some(words(10, 4)))), None); + assert_eq!(half_view(&View::Shader(7, None)), None); + assert_eq!(half_view(&View::Constant(0x1000, 256)), None); + } + + /// The buffer views through which the integers a shader moves halves + /// as are not what the console gives are named; the title's are not. + #[test] + fn views_whose_values_the_console_would_convert_are_named() { + const BUFFER: u32 = 1; + let words = |format: u32, dimension: u32| [format, dimension, 5768, 0, 0, 0, 64, 0, 0, 0]; + for exact in [10, 12, 14, 34, 36, 38, 54, 57, 59, 25, 30, 50, 62] { + let view = View::Unordered(7, 0, Some(words(exact, BUFFER))); + assert_eq!(half_inexact(&view), None, "format {exact}"); + } + // R32_FLOAT, R32_UINT, R16G16B16A16_UNORM, R8G8B8A8_UNORM, R8_SINT, + // and a structured or raw view (no format). + for inexact in [41, 42, 11, 28, 64, 0] { + let view = View::Shader(7, Some(words(inexact, BUFFER))); + assert_eq!(half_inexact(&view), Some(inexact)); + } + let mut placed = [0u32; 16]; + placed[..10].copy_from_slice(&words(41, BUFFER)); + let memory = [BUFFER, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0]; + assert_eq!(half_inexact(&View::Placed(true, memory, placed)), Some(41)); + // Not a buffer view. + assert_eq!(half_inexact(&View::Shader(7, Some(words(41, 4)))), None); + assert_eq!(half_inexact(&View::Constant(0x1000, 256)), None); + } + + /// The two ways a translated `buffer_load_format_d16_xyzw` and + /// `buffer_store_format_d16_xyzw` have moved a typed buffer's 16-bit + /// channels, on the host device, over a buffer that holds every 16-bit + /// pattern. As unsigned integers through an unsigned view (the title's + /// own R16G16B16A16_UINT, or the twin `half_view` gives a float one) + /// every pattern comes back as it was. By way of floats, as before + /// (load as floats, each to its half's bits; each half widened and + /// stored as a float): through the title's integer view that is + /// outside what D3D12 defines, and what the device gives is printed, + /// not checked (1 pattern of 65,536 on the cards tried: the network + /// that moves the title's faces computed zeros). + #[test] + fn halves_cross_an_unsigned_buffer_view_unchanged() { + const MOVES: &str = r#" +#define RS "DescriptorTable(UAV(u0, numDescriptors=2))" +#ifdef BY_FLOATS +RWBuffer<float4> from : register(u0); +RWBuffer<float4> to : register(u1); +#else +RWBuffer<uint4> from : register(u0); +RWBuffer<uint4> to : register(u1); +#endif +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void BY_FLOATS_OR_NOT(uint3 id : SV_DispatchThreadID) { +#ifdef BY_FLOATS + uint4 h = f32tof16(from[id.x]); +#else + uint4 h = from[id.x] & 0xffff; +#endif + uint low = h.x | h.y << 16; + uint high = h.z | h.w << 16; +#ifdef BY_FLOATS + to[id.x] = float4(f16tof32(low), f16tof32(low >> 16), f16tof32(high), f16tof32(high >> 16)); +#else + to[id.x] = uint4(low & 0xffff, low >> 16, high & 0xffff, high >> 16); +#endif +} +"#; + const ELEMENTS: usize = 1 << 14; + const BYTES: u64 = ELEMENTS as u64 * 8; + const TITLES: u32 = 12; // R16G16B16A16_UINT + let Some(host) = host() else { + return; // no host GPU + }; + let heap: ID3D12DescriptorHeap = { + let desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }; + // SAFETY: plain heap creation. + unsafe { host.device.CreateDescriptorHeap(&desc) }.expect("a view heap") + }; + // How many of the 65,536 patterns come back as they were, moved by + // the program `by_floats` or not, through views in `format`. + let moved = |by_floats: bool, format: u32| -> usize { + let source = if by_floats { + MOVES + .replace("BY_FLOATS_OR_NOT", "main") + .replace("#ifdef BY_FLOATS", "#if 1") + } else { + MOVES + .replace("BY_FLOATS_OR_NOT", "main") + .replace("#ifdef BY_FLOATS", "#if 0") + }; + let code = crate::host::compile( + &source, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + ) + .expect("the test's shader"); + let (from, filled) = host.shared_buffer(BYTES).expect("a buffer"); + let (to, result) = host.shared_buffer(BYTES).expect("a buffer"); + // SAFETY: the shader's own root signature and plain creation + // calls; both mappings hold `BYTES` bytes; the views are of + // live buffers, in slots of the heap made above; an open list. + unsafe { + let root: ID3D12RootSignature = host + .device + .CreateRootSignature(0, &code) + .expect("a root signature"); + let pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .expect("a pipeline"); + let filled = std::slice::from_raw_parts_mut(filled.cast::<u16>(), ELEMENTS * 4); + for (pattern, half) in filled.iter_mut().enumerate() { + *half = pattern as u16; + } + std::ptr::write_bytes(result, 0xee, BYTES as usize); + let view = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(format as i32), + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: ELEMENTS as u32, + ..Default::default() + }, + }, + }; + let start = heap.GetCPUDescriptorHandleForHeapStart(); + let step = host + .device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; + host.device.CreateUnorderedAccessView( + &from, + None::<&ID3D12Resource>, + Some(&view), + start, + ); + let second = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + step, + }; + host.device.CreateUnorderedAccessView( + &to, + None::<&ID3D12Resource>, + Some(&view), + second, + ); + let list = host.new_list().expect("a host list"); + list.list.SetDescriptorHeaps(&[Some(heap.clone())]); + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + list.list + .SetComputeRootDescriptorTable(0, heap.GetGPUDescriptorHandleForHeapStart()); + list.list.Dispatch(ELEMENTS as u32 / 64, 1, 1); + list.close(); + host.execute(&[&list]); + assert!( + host.device.GetDeviceRemovedReason().is_ok(), + "the device, after views in format {format}" + ); + let result = std::slice::from_raw_parts(result.cast::<u16>(), ELEMENTS * 4); + (0..=u16::MAX) + .filter(|&p| result[usize::from(p)] == p) + .count() + } + }; + // A float view of halves is shown as the title's kind of view. + assert_eq!(half_format(10), Some(TITLES)); + let unsigned = moved(false, TITLES); + let by_floats = moved(true, TITLES); + eprintln!( + "halves through an R16G16B16A16_UINT buffer view: {unsigned} of 65536 patterns came back unchanged moved as unsigned integers, {by_floats} moved by way of floats" + ); + assert_eq!( + unsigned, 65_536, + "patterns unchanged, moved as unsigned integers" + ); + } + /// A null texture UAV keeps the title's dimension (3D for the world's /// wind field), and is 2D when the title names none. #[test] @@ -1262,6 +4864,123 @@ mod tests { assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D); } + /// What the texture code asks of the spans (levels on demand): where + /// the next texture starts inside a span, the lowest level a view of a + /// texture shows, and a texture's slots. + #[test] + fn spans_say_the_next_start_and_the_lowest_level_viewed() { + let mut spans = Spans::default(); + // A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1, + // and the next one 0x6000 after it (run 188). + spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true); + spans.shows(1, 3); + spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true); + spans.shows(2, 1); + spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true); + assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000)); + assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None); + assert_eq!(spans.first_viewed(0x1_0000), Some(1)); + assert_eq!(spans.first_viewed(0x1_6000), None); + assert_eq!(spans.slots_at(0x1_0000), vec![1, 2]); + // The view from level 1 goes: the texture is viewed from level 3. + spans.forget(2); + assert_eq!(spans.first_viewed(0x1_0000), Some(3)); + } + + /// Views of one placed texture are told from views of others by the + /// address and the resource description, not by what they show. + #[test] + fn views_of_one_placed_texture_are_told_by_address_and_description() { + let texture = [3, 0, 0, 0, 512, 0, 512, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; + let view = |resource: [u32; 14], first_mip: u32, address: u32| { + let mut desc = [0u32; 16]; + (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = (98, 4, first_mip, 8 - first_mip, address, 0xb); + View::Placed(false, resource, desc) + }; + let low = view(texture, 3, 0x1000_0000); + // more mips of the same texture + assert!(same_placed_texture(&low, &view(texture, 0, 0x1000_0000))); + // another address, another description, a buffer, an unordered view + assert!(!same_placed_texture(&low, &view(texture, 3, 0x2000_0000))); + let mut wider = texture; + wider[4] = 1024; + assert!(!same_placed_texture(&low, &view(wider, 3, 0x1000_0000))); + let mut buffer = texture; + buffer[0] = 1; + assert!(!same_placed_texture(&view(buffer, 3, 0x1000_0000), &view(buffer, 3, 0x1000_0000))); + let View::Placed(_, resource, desc) = low.clone() else { unreachable!() }; + assert!(!same_placed_texture(&low, &View::Placed(true, resource, desc))); + assert!(!same_placed_texture(&low, &View::Shader(0, None))); + } + + #[test] + fn ranges_that_touch_are_one() { + let mut ranges = vec![(40, 50), (30, 40), (35, 40), (10, 20), (45, 60), (60, 61), (1, 1)]; + join(&mut ranges); + assert_eq!(ranges, [(1, 1), (10, 20), (30, 61)]); + join(&mut ranges); + assert_eq!(ranges.len(), 3); + } + + /// What may stand for a texture that is not there yet: one of its kind in + /// another place or size; another one only if asked; nothing a shader + /// cannot read in its place. + #[test] + fn a_slot_shows_on_what_can_stand_for_its_new_texture() { + let texture = [3, 0, 0, 0, 512, 0, 256, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; + let view = |resource: [u32; 14], format: u32, dimension: u32, address: u32| { + let mut desc = [0u32; 16]; + (desc[0], desc[1], desc[10], desc[11]) = (format, dimension, address, 0xb); + View::Placed(false, resource, desc) + }; + let old = view(texture, 98, 4, 0x1000_0000); + let mut twice = texture; + (twice[4], twice[6], twice[7]) = (1024, 512, 0x9_0001); + let mut square = texture; + square[6] = 512; + let mut buffer = texture; + buffer[0] = 1; + assert_eq!(kin(&old, &view(texture, 98, 4, 0x1000_0000)), Kin::Same); + assert_eq!(kin(&old, &view(texture, 98, 4, 0x2000_0000)), Kin::Moved); + assert_eq!(kin(&old, &view(twice, 98, 4, 0x2000_0000)), Kin::Sized); + assert_eq!(kin(&old, &view(square, 98, 4, 0x2000_0000)), Kin::Other); + assert_eq!(kin(&old, &view(twice, 83, 4, 0x2000_0000)), Kin::Other); + assert_eq!(kin(&old, &view(texture, 98, 9, 0x2000_0000)), Kin::None); + assert_eq!(kin(&old, &view(buffer, 98, 1, 0x2000_0000)), Kin::None); + for (kin, kept) in [(Kin::Same, [true; 3]), (Kin::Moved, [false, true, true]), (Kin::Sized, [false, true, true]), (Kin::Other, [false, false, true]), (Kin::None, [false; 3])] { + assert_eq!([0, 1, 2].map(|keep| kin.kept(keep)), kept, "{kin:?}"); + } + } + + /// A constant buffer view larger than the host takes is cut to what it + /// takes: the device, which such a view removes, stays. + #[test] + fn an_oversized_constant_buffer_view_leaves_the_device_alive() { + let Some(host) = host() else { + return; // no host GPU + }; + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + // SAFETY: a plain device query. + let alive = || unsafe { host.device.GetDeviceRemovedReason() }.is_ok(); + // Made first: an allocation that fails on a removed device must not + // end the test early. + let (buffer, _) = host.upload_buffer(1 << 20).expect("an upload buffer"); + let memory = vec![0u8; 2 << 20]; + let at = (memory.as_ptr() as u64).next_multiple_of(64 << 10); + for size in [969_472u32, 896_256] { + assert!(make(&View::Constant(at, size), heap.cpu(0)).is_some()); + assert!(alive(), "a view of {size} bytes"); + } + // SAFETY: a live upload buffer. + heap.constant_at(1, unsafe { buffer.GetGPUVirtualAddress() }, 969_472); + assert!(alive(), "a view of the list's own memory"); + assert_eq!(constant_view_size(480), 512); + assert_eq!(constant_view_size(64 << 10), 64 << 10); + assert_eq!(constant_view_size(u32::MAX), 64 << 10); + } + /// A null 3D UAV made on the real device leaves it alive. #[test] fn null_3d_uav_is_accepted_by_the_device() { @@ -1277,173 +4996,534 @@ mod tests { assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); } - /// The CPU-side block used to initialize null samplers must fit the - /// same portable sampler limit as the shader-visible heap. + /// Dynamic slots stay taken until given back, and runs do not wrap. #[test] - fn portable_sampler_null_fill_fits_the_host_limit() { - if host().is_none() { - return; // no host GPU + fn a_structured_view_made_raw_passes_the_host_check() { + // 100 elements of 20 bytes from element 8, in a copy that starts 32 + // bytes before the view's memory: bytes 192..2192. + let (first, count) = raw_window(32, 8, 100, 20).unwrap(); + assert_eq!((first, count), (48, 500)); + assert!(buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 4096)); + // the format a raw view must name; the structured one's is refused + assert!(!buffer_view_ok(DXGI_FORMAT_UNKNOWN, first, count, 0, true, 4096)); + // past the buffer, not on 16 bytes, no elements + assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 2000)); + assert!(raw_window(4, 0, 100, 20).is_none()); + assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true, 4096)); + // a structured view the host takes as it is + assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096)); + } + + /// The queue of textures picked by index serves the slots looked at + /// before first, then the newest write and the oldest in turns; a + /// slot whose memory is not there is looked at again after + /// 1, 2, 4 frames up to the limit; and what the pass reports about a + /// slot written again meanwhile is dropped. + #[test] + fn the_texture_queue_serves_the_newest_writes_first() { + let mut q = TextureQueue::default(); + // Slots 10..18 written in frames 1..9, slot 5 last. + for i in 0..8u32 { + q.written(10 + i, u64::from(i) + 1, 0, false); } - let heap = HostHeap::new(true, D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE) - .expect("portable sampler heap must initialize"); - assert!( - heap.fill_null( - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE, - ) - .is_ok() - ); + q.written(5, 9, 0, false); + let order: Vec<u32> = q.due(9, 100).into_iter().map(|d| d.0).collect(); + // newest, oldest, newest, oldest, and so on + assert_eq!(order, [5, 10, 17, 11, 16, 12, 15, 13, 14]); + assert_eq!(q.due(9, 2).len(), 2); + assert_eq!(q.census(9), [9, 9, 0, 0, 8]); + // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4. + let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1; + let w17 = write(&q, 17); + let mut frame = 9; + for wait in [1, 2, 4, 4] { + q.later(17, w17, frame, 4); + assert!(!q.due(frame + wait - 1, 100).iter().any(|d| d.0 == 17)); + frame += wait; + // Due again, and ahead of every slot never looked at. + assert_eq!(q.due(frame, 100)[0].0, 17); + } + assert_eq!(q.census(9)[2], 1); + q.done(17, w17); + assert!(!q.due(u64::MAX, 100).iter().any(|d| d.0 == 17)); + // Uploaded with part of its memory there: kept, with what was there. + let w16 = write(&q, 16); + q.partly(16, w16, 12, 4096); + assert_eq!(q.mapped(16), 4096); + assert_eq!(q.due(12, 100)[0].0, 16); + // The title writes slot 16 again while the pass works on it: what + // the pass then says about the old write changes nothing. + q.written(16, 13, 0, false); + q.done(16, w16); + q.later(16, w16, 13, 4); + assert_eq!(q.mapped(16), 0); + assert_eq!(q.due(13, 100)[0].0, 16); + // A draw that makes the host slot (`seen`) keeps what the queue knows, + let w15 = write(&q, 15); + q.partly(15, w15, 20, 8192); + q.written(15, 14, 0, true); + assert_eq!(q.mapped(15), 8192); + // and queues a slot the queue did not hold. + q.written(99, 14, 0, true); + assert!(q.due(14, 100).iter().any(|d| d.0 == 99)); + // A write due later (a table's slot) is not handed out before. + q.written(98, 14, 16, false); + assert!(!q.due(15, 100).iter().any(|d| d.0 == 98)); + assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); } - /// A view heap is never sized past what the device takes: 2^20 title - /// slots plus the dynamic range asked for 1,310,720 views on a device - /// that takes 1,000,000 (upstream #735). + /// Slots held back for lack of room on the card are not handed out + /// until their frame, keep their place, are not counted as waiting + /// for their memory, and all come back at once when the card has room; + /// a slot written again meanwhile is the title's new write. #[test] - fn view_heaps_stay_within_the_device_limit() { - // 2^20 title slots on a 1M device: the full dynamic range, the - // title's slots cut (upstream #735, #747). - assert_eq!( - view_heap_sizes(1 << 20, PORTABLE_VIEWS), - [ - (PORTABLE_VIEWS, PORTABLE_VIEWS - DYNAMIC, DYNAMIC), - (PORTABLE_VIEWS, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC), - ] - ); - assert_eq!( - view_heap_sizes(4, PORTABLE_VIEWS), - [(4 + DYNAMIC, 4, DYNAMIC), (4 + MIN_DYNAMIC, 4, MIN_DYNAMIC)] - ); - assert_eq!( - view_heap_sizes(800_000, PORTABLE_VIEWS), - [ - (PORTABLE_VIEWS, PORTABLE_VIEWS - DYNAMIC, DYNAMIC), - (800_000 + MIN_DYNAMIC, 800_000, MIN_DYNAMIC), - ] - ); - // A device that reports a larger limit keeps every title slot. - assert_eq!( - view_heap_sizes(1 << 20, 1 << 21)[0], - ((1 << 20) + DYNAMIC, 1 << 20, DYNAMIC) - ); - for count in [0, 1, 999_999, 1_000_000, u32::MAX] { - let sizes = view_heap_sizes(count, PORTABLE_VIEWS); - assert_eq!(sizes[0].2, DYNAMIC); - for (size, titles, extra) in sizes { - assert!(size <= PORTABLE_VIEWS && titles + extra == size && titles <= count); - } + fn slots_held_for_lack_of_room_come_back_when_there_is_room() { + let mut q = TextureQueue::default(); + for i in 0..4u32 { + q.written(20 + i, 1, 0, false); + } + let due = q.due(1, 100); + assert_eq!(due.len(), 4); + // The card is full: slots 20 and 21 are held back until frame 101. + for &(index, write) in due.iter().filter(|d| d.0 < 22) { + q.hold(index, write, 101); } + let now: Vec<u32> = q.due(2, 100).into_iter().map(|d| d.0).collect(); + assert!(!now.contains(&20) && !now.contains(&21)); + assert!(now.contains(&22) && now.contains(&23)); + assert_eq!(q.census(2)[2], 0, "held slots do not wait for their memory"); + // Due again at their frame, in the order they had. + assert_eq!(q.due(101, 100), due); + // Slot 21 is written again while held: due as written. + q.written(21, 3, 0, false); + assert!(q.due(3, 100).iter().any(|d| d.0 == 21)); + // Room again at frame 5: slot 20 is due at once, and only it was + // still held as it was. + assert_eq!(q.room(5), 1); + assert!(q.due(5, 100).iter().any(|d| d.0 == 20)); + assert_eq!(q.room(6), 0); } - /// Dynamic slots stay taken until given back, and runs do not wrap. + /// The slots a draw names are handed out whatever their turn: not due + /// yet, or held back for lack of room. One uploaded whole that waits + /// for another look is not waiting for its upload; put back, it is + /// due at once as a slot written now, and so is one the queue did not + /// hold. A slot that waits for its upload already keeps its place. #[test] - fn dynamic_slots_are_held_until_released() { - let Some(heap) = HostHeap::new(false, 4) else { + fn slots_a_draw_names_are_handed_out_whatever_their_turn() { + let mut q = TextureQueue::default(); + q.written(5, 1, 0, false); + q.written(6, 1, 50, false); + q.written(7, 1, 0, false); + let due = q.due(1, 100); + let write = |index: u32| due.iter().find(|d| d.0 == index).map(|d| d.1).unwrap(); + assert!(!due.iter().any(|d| d.0 == 6), "slot 6 is not due before frame 50"); + q.hold(7, write(7), 101); + let named = |q: &TextureQueue| -> Vec<u32> { q.queued(&[5, 6, 7, 8]).into_iter().map(|d| d.0).collect() }; + assert_eq!(named(&q), [5, 6, 7]); + assert_eq!(q.queued(&[7]), [(7, write(7))], "with the write the pass hands back"); + q.recheck(5, write(5), 9, (0x1000, 0x100), 1234, 0, 1); + assert_eq!(named(&q), [6, 7]); + let six = q.queued(&[6]); + q.requeue(&[5, 6, 8], 3); + assert_eq!(named(&q), [5, 6, 7, 8]); + assert_eq!(q.checked(5), None); + assert_eq!(q.queued(&[6]), six, "slot 6 waited already: as it was"); + let now: Vec<u32> = q.due(3, 100).into_iter().map(|d| d.0).collect(); + assert!(now.contains(&5) && now.contains(&8) && !now.contains(&6) && !now.contains(&7)); + } + + /// Textures of which only the smallest levels are held, packed into + /// one another's address range (the three of run 188: 0x2c000 bytes + /// each at full size, their starts 0x2000 and 0x4000 apart): writing + /// any of them, in any order and again, leaves the others. + #[test] + fn packed_neighbours_stay() { + let mut spans = Spans::default(); + assert_eq!(spans.rule, Rule::Start); + let at = 0xb_86bf_8000u64; + let (a, b, c) = (at, at + 0x2000, at + 0x6000); + assert!(spans.note(105_998, a, a + 0x2c000, true).is_empty()); + assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty()); + assert!(spans.note(108_521, c, c + 0x2c000, true).is_empty()); + // The first written again (as a title does when levels arrive), + // from another slot too: its span reaches over the other two. + assert!(spans.note(7, a, a + 0x2c000, true).is_empty()); + assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty()); + let mut all = spans.slots_in(0, u64::MAX); + all.sort_unstable(); + assert_eq!(all, [7, 105_998, 106_004, 108_521]); + // A draw makes a slot of the second texture: it is one of them. + assert!(spans.note(9, b, b + 0x2c000, false).is_empty()); + assert_eq!(spans.by_slot.get(&9), Some(&b)); + } + + /// A texture written where another starts replaces it: at the same + /// address with another length, or inside the block of its smallest + /// levels. The packed neighbours of the one replaced stay. + #[test] + fn a_texture_written_at_the_start_of_another_replaces_it() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + // Another length from the same start: slot 1 is stale, slot 2 not. + assert_eq!(spans.note(3, at, at + 0xb000, true), [1]); + // A start inside the first 4 KiB of slot 3's texture: stale too. + assert_eq!(spans.note(4, at + 0x800, at + 0x1800, true), [3]); + // And the other way: a texture that starts just before one. + assert_eq!(spans.note(5, at + 0x1800, at + 0x4800, true), [2]); + let mut left = spans.slots_in(0, u64::MAX); + left.sort_unstable(); + assert_eq!(left, [4, 5]); + // Exactly 4 KiB apart: both there. + assert!(spans.note(6, at + 0x2800, at + 0x3800, true).is_empty()); + // A draw's view that clashes is left out, and nothing is stale. + assert!(spans.note(8, at + 0x900, at + 0x2900, false).is_empty()); + assert_eq!(spans.by_slot.get(&8), None); + assert_eq!(spans.by_slot.len(), 3); + } + + /// A slot written with another texture leaves its old span; the same + /// view written again changes nothing. + #[test] + fn a_slot_rewritten_moves_to_its_new_span() { + let mut spans = Spans::default(); + assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty()); + assert!(spans.note(2, 0x12000, 0x3e000, true).is_empty()); + assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty()); + assert_eq!(spans.slots_in(0x10000, 0x10001), [1]); + // Slot 1 now views a texture far away. + assert!(spans.note(1, 0x90000, 0x91000, true).is_empty()); + assert_eq!(spans.slots_in(0x10000, 0x10001), [] as [u32; 0]); + assert_eq!(spans.slots_in(0x12000, 0x12001), [2]); + assert_eq!(spans.slots_in(0x90000, 0x90001), [1]); + spans.forget(1); + spans.forget(2); + assert!(spans.by_start.is_empty() && spans.by_slot.is_empty()); + } + + /// Memory the runtime maps, unmaps or writes names the textures that + /// are there: among packed neighbours the one whose held levels the + /// range lies in (it ends where the next one starts), and the ones + /// that start inside the range. + #[test] + fn memory_changed_under_packed_neighbours_names_the_ones_there() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty()); + // Inside the first one's held levels. + assert_eq!(spans.slots_in(at + 0x1000, at + 0x2000), [1]); + // Inside the second's: not the first, which ends where it starts. + assert_eq!(spans.slots_in(at + 0x3000, at + 0x4000), [2]); + // Past the last start: the last one. + assert_eq!(spans.slots_in(at + 0x20000, at + 0x21000), [3]); + // A range over all of them. + assert_eq!(spans.slots_in(at, at + 0x8000), [1, 2, 3]); + // Past the end of all: none. + assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]); + } + + /// A write names the textures that hold its bytes: the one that + /// starts where the write starts, not the neighbour before it, whose + /// held levels end there. + #[test] + fn a_write_at_the_start_of_a_packed_texture_names_it_alone() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty()); + // A request that fills the second texture's held levels. + assert_eq!(spans.slots_in(at + 0x2000, at + 0x6000), [1, 2]); + assert_eq!(spans.slots_holding(at + 0x2000, at + 0x6000), [2]); + // From inside the first one's held levels on: both. + assert_eq!(spans.slots_holding(at + 0x1000, at + 0x3000), [1, 2]); + // A whole 64 KiB page: every texture that starts in it. + assert_eq!(spans.slots_holding(at, at + 0x10000), [1, 2, 3]); + // Past the last start, the last one; past all, or no bytes, none. + assert_eq!(spans.slots_holding(at + 0x20000, at + 0x21000), [3]); + assert_eq!(spans.slots_holding(at + 0x32000, at + 0x33000), [] as [u32; 0]); + assert_eq!(spans.slots_holding(at + 0x2000, at + 0x2000), [] as [u32; 0]); + } + + /// A write behind the guards' back under a placed texture: a slot + /// waiting for its first upload is left alone, one uploaded before is + /// counted, and made due two frames on when that is asked for. (The + /// ranges are handed over here, not through the list all heaps share.) + #[test] + fn a_page_write_makes_an_uploaded_texture_slot_due_when_asked() { + let Some(heap) = HostHeap::new(false, 8) else { return; // no host GPU }; - let spare = heap.spare; - assert!(spare == DYNAMIC || spare == MIN_DYNAMIC, "{spare}"); - let a = heap.dynamic(spare - 100).unwrap(); - let b = heap.dynamic(60).unwrap(); - assert_eq!((a, b), (4, 4 + spare - 100)); - // 40 left at the end: 50 do not fit until something is given back. - assert_eq!(heap.dynamic(50), None); - heap.release(a, 50); - assert_eq!(heap.dynamic(50), Some(4)); - assert_eq!(heap.dynamic(40), Some(4 + spare - 40)); + let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + // 64x64 BC7, one mip, at an address no test and no title uses. + let at = 0x7fed_0000_0000u64; + let mut desc = [0u32; 16]; + (desc[10], desc[11]) = (at as u32, (at >> 32) as u32); + let view = View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc); + assert!(heap.note_buffer(1, Some(&view), false).is_empty()); + let written = [(at, at + 0x1000)]; + // Waiting for its first upload: held, not uploaded, nothing done. + assert_eq!(heap.slots_written_under(&written, 50, true), [1, 0, 0]); + let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; + assert_eq!(queued, 1); + heap.texture_slot_done(1, write, None); + assert_eq!(slots(u64::MAX), []); + // Uploaded and out of the queue. Memory elsewhere: nothing. + assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]); + // Under it, counted only: it stays out of the queue. + assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]); + assert_eq!(slots(u64::MAX), []); + // Under it, asked for: due two frames on, not before. + assert_eq!(heap.slots_written_under(&written, 60, true), [1, 1, 1]); + assert_eq!(slots(61), []); + assert_eq!(slots(62), [1]); } - /// A sampler heap past the host's limit is capped, not lost, and keeps - /// dynamic slots for the tables reaching past what it holds. + /// A slot whose texture was uploaded ahead shows it when it is + /// published, and does not go back into the queue of textures picked by + /// index for that; one the title wrote again is left alone. #[test] - fn large_sampler_heap_is_capped() { - let Some(heap) = HostHeap::new(true, 4 * SAMPLERS) else { + fn a_published_slot_stays_out_of_the_queue() { + let Some(heap) = HostHeap::new(false, 8) else { return; // no host GPU }; - let count = SAMPLERS - SAMPLER_DYNAMIC; - assert_eq!(heap.count(), count); - assert_eq!(heap.dynamic(SAMPLER_DYNAMIC + 1), None); - let a = heap.dynamic(SAMPLER_DYNAMIC).unwrap(); - assert_eq!(a, count); - assert_eq!(heap.dynamic(1), None); - heap.release(a, 8); - assert_eq!(heap.dynamic(8), Some(count)); + // 64x64 BC7, one mip, at an address no test and no title uses. + let view = |at: u64| { + let mut desc = [0u32; 16]; + (desc[0], desc[1], desc[2], desc[5]) = (98, 4, 5768, 1); + (desc[10], desc[11]) = (at as u32, (at >> 32) as u32); + View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc) + }; + let title = [0u32; 8]; + let handle = title.as_ptr() as u64; + crate::descriptor::record(handle, view(0x7fec_0000_0000)); + let (first, key) = crate::descriptor::view_and_key(handle).unwrap(); + assert!(heap.note_buffer(1, Some(&first), false).is_empty()); + let (index, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; + assert_eq!(index, 1); + // Its upload was recorded: out of the queue, the slot not made yet. + heap.texture_slot_done(1, write, None); + assert!(!heap.made(1)); + assert!(heap.publish(1, handle, key)); + assert!(heap.made(1)); + assert!(heap.texture_slots_due(u64::MAX, 8).0.is_empty()); + // Written again since the upload was recorded. + crate::descriptor::record(handle, view(0x7feb_0000_0000)); + assert!(!heap.publish(1, handle, key)); + assert_ne!(crate::descriptor::view_and_key(handle).unwrap().1, key); + } + + /// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that + /// overlaps others is left out of the spans, as before. + #[test] + fn never_stale_leaves_overlapping_views_out() { + let mut spans = Spans { rule: Rule::Never, ..Default::default() }; + assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(2, 0x2000, 0x4000, true).is_empty()); + assert!(spans.note(3, 0x1000, 0x2000, true).is_empty()); + assert_eq!(spans.slots_in(0, u64::MAX), [1]); + } + + /// The rule until run 188 (`VICTORY_STALE_TEXTURES=overlap`): a view + /// written over memory that older views describe otherwise makes + /// those stale; views of the same span are one texture's. + #[test] + fn a_newer_view_of_other_memory_makes_the_older_stale() { + let mut spans = Spans { rule: Rule::Overlap, ..Default::default() }; + // Three textures side by side, the first in two slots. + assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(3, 0x3000, 0x4000, true).is_empty()); + assert!(spans.note(4, 0x8000, 0x9000, true).is_empty()); + // The same slot written with the same span again: nothing changes. + assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); + assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]); + assert_eq!(spans.slots_in(0x4000, 0x8000), [] as [u32; 0]); + // A draw makes a slot whose view overlaps them: left out, nothing stale. + assert!(spans.note(9, 0x2000, 0x3800, false).is_empty()); + assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]); + // The title writes a texture over the end of the first and all of + // the second: their three slots are stale. + let mut stale = spans.note(5, 0x2000, 0x4000, true); + stale.sort_unstable(); + assert_eq!(stale, [1, 2, 3]); + assert_eq!(spans.slots_in(0, u64::MAX), [5, 4]); + // Another start in the same memory: stale in turn. Another length + // from the same start too. + assert_eq!(spans.note(6, 0x2800, 0x3000, true), [5]); + assert_eq!(spans.note(7, 0x2800, 0x2c00, true), [6]); + // A slot that moves to another texture leaves its span behind. + assert!(spans.note(7, 0x8000, 0x9000, true).is_empty()); + assert_eq!(spans.slots_in(0x2800, 0x2c00), [] as [u32; 0]); + assert_eq!(spans.slots_in(0x8000, 0x8001), [4, 7]); + spans.forget(4); + spans.forget(7); + assert!(spans.by_start.is_empty() && spans.by_slot.is_empty()); + } + + /// Memory the runtime maps under a slot's texture makes the slot due + /// again from the next frame; a stale slot leaves the queue. + #[test] + fn remapped_memory_makes_its_texture_slots_due() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + // 64x64 BC7, one mip, at an address no test and no title uses. + let at = 0x7fee_0000_0000u64; + let view = |address: u64, width: u32| { + let mut desc = [0u32; 16]; + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc) + }; + let len = crate::resource::placed_bytes(&[3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0]).unwrap(); + assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty()); + let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; + assert_eq!(queued, 1); + heap.texture_slot_done(1, write, None); + assert_eq!(slots(u64::MAX), []); + // Memory elsewhere: nothing. Under the texture: due from the next frame. + remapped((at + 2 * len) as usize, 0x1000); + remapped(at as usize, 0x1000); + assert_eq!(heap.texture_slots_remapped(50), 1); + assert_eq!(slots(50), []); + assert_eq!(slots(51), [1]); + // A wider texture written at the same address: slot 1 is stale. + assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]); + assert_eq!(slots(u64::MAX), [2]); + } + + /// A slot a draw read through a table leaves the queue; the title's + /// next write of it waits for its draw, and is due after the grace + /// frames if none reads it. + #[test] + fn slots_read_through_tables_leave_the_texture_queue() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let frame = 100; + let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + let texture = View::Placed(false, [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], [0; 16]); + assert!(is_texture_view(&texture)); + heap.queue_texture(2, true, false, frame); + heap.queue_texture(3, true, false, frame); + assert_eq!(slots(frame), [3, 2]); + heap.tabled_in(3, true, frame); + assert_eq!(slots(frame), [2]); + // Made in place by the draw that read it: still out. + heap.queue_texture(3, true, true, frame); + assert_eq!(slots(frame), [2]); + // Written again in the next frame: due once the grace frames have + // passed without a draw that reads it. + heap.queue_texture(3, true, false, frame + 1); + assert_eq!(slots(frame + TABLED_GRACE), [2]); + assert_eq!(slots(frame + 1 + TABLED_GRACE), [3, 2]); + // The draw comes after all: out again. + heap.tabled_in(3, true, frame + 1); + assert_eq!(slots(u64::MAX), [2]); + // A slot of a table no draw read stays queued; its next write waits. + heap.tabled_in(2, false, frame + 1); + assert_eq!(slots(frame + 1), [2]); + heap.queue_texture(2, true, false, frame + 2); + assert_eq!(slots(frame + 2), []); + // Long after the last table, a write is due at once. + heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES); + assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]); } - /// A sampler heap within the limit has a slot per title slot and no - /// dynamic ones. #[test] - fn small_sampler_heap_has_no_dynamic_slots() { - let Some(heap) = HostHeap::new(true, 16) else { + fn a_free_run_across_the_place_the_search_starts_from_is_found() { + let Some(heap) = HostHeap::new(false, 4) else { return; // no host GPU }; - assert_eq!(heap.count(), 16); + // Slots 0..8 and 8..16 of the ring: the search now starts at 16. + assert_eq!((heap.dynamic(8), heap.dynamic(8)), (Some(4), Some(12))); + // Everything after them, so that only what is given back is free. + let rest = heap.dynamic - 16; + assert_eq!(heap.dynamic(rest), Some(4 + 16)); + // The search starts at 0 again. Slots 0..16 back, then 0..12 taken: + // it starts at 12, with 12..16 free. + heap.release(heap.id(), 4, 16); + assert_eq!(heap.dynamic(12), Some(4)); + // 10..12 back: the free run 10..16 lies across 12. Six slots fit + // only there. + heap.release(heap.id(), 4 + 10, 2); + assert_eq!(heap.dynamic(6), Some(4 + 10)); + // And nothing is found where nothing is. assert_eq!(heap.dynamic(1), None); } #[test] - fn depth_srv_uses_the_requested_aspect() { - for (own, request, expected, plane) in [ - (19, 20, 21, 0), - (19, 22, 22, 1), - (44, 45, 46, 0), - (44, 47, 47, 1), - (44, 120, 47, 1), - (44, 119, 46, 0), - (39, 40, 41, 0), - (53, 55, 56, 0), - (19, 0, 21, 0), - (44, 44, 46, 0), - ] { - let resource = D3D12_RESOURCE_DESC { - Format: DXGI_FORMAT(own), - Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, - ..Default::default() - }; - for dim in [ - D3D12_SRV_DIMENSION_TEXTURE2D, - D3D12_SRV_DIMENSION_TEXTURE2DARRAY, - ] { - let mut words = [0; 10]; - words[0] = request; - words[1] = dim.0 as u32; - words[2] = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - words[4] = 2; // MostDetailedMip - words[5] = 3; // MipLevels - if dim == D3D12_SRV_DIMENSION_TEXTURE2DARRAY { - words[6] = 1; // FirstArraySlice - words[7] = 2; // ArraySize - } - let plane_word = if dim == D3D12_SRV_DIMENSION_TEXTURE2DARRAY { - 8 - } else { - 6 - }; - words[plane_word] = 1 - plane; - let view = texture_srv_desc(&resource, &words); - assert_eq!(view.Format.0, expected); - // SAFETY: read the member selected by the input view dimension. - unsafe { - if dim == D3D12_SRV_DIMENSION_TEXTURE2DARRAY { - let a = view.Anonymous.Texture2DArray; - assert_eq!( - ( - a.MostDetailedMip, - a.MipLevels, - a.FirstArraySlice, - a.ArraySize, - a.PlaneSlice - ), - (2, 3, 1, 2, plane) - ); - } else { - let a = view.Anonymous.Texture2D; - assert_eq!( - (a.MostDetailedMip, a.MipLevels, a.PlaneSlice), - (2, 3, plane) - ); - } - } + fn dynamic_slots_are_held_until_released() { + let Some(heap) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + let a = heap.dynamic(heap.dynamic - 100).unwrap(); + let b = heap.dynamic(60).unwrap(); + assert_eq!((a, b), (4, 4 + heap.dynamic - 100)); + // 40 left at the end: 50 do not fit until something is given back. + assert_eq!(heap.dynamic(50), None); + heap.release(heap.id(), a, 50); + assert_eq!(heap.dynamic(50), Some(4)); + assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); + } +} + +#[cfg(test)] +mod record_print_tests { + use super::record_print; + + /// Equal records print alike; a record that differs in any one byte, + /// or in its length, prints otherwise. + #[test] + fn a_record_that_changed_prints_otherwise() { + let record: Vec<u8> = (0..32u8).map(|i| i.wrapping_mul(37).wrapping_add(5)).collect(); + let print = record_print(&record); + assert_eq!(print, record_print(&record.clone())); + for at in 0..32 { + for bit in 0..8 { + let mut other = record.clone(); + other[at] ^= 1 << bit; + assert_ne!(record_print(&other), print, "byte {at} bit {bit}"); } } + assert_ne!(record_print(&record[..16]), print); + assert_ne!(record_print(&[0u8; 32]), record_print(&[0u8; 16])); + // A record of zeros is told from "never looked at" by the caller's `| 1`. + assert_ne!(record_print(&[0u8; 32]) | 1, 0); + } +} + +#[cfg(test)] +mod own_copy_tests { + use super::own_bytes_if; + + /// A buffer view gets a copy of its own bytes only when it has no host + /// view on its buffer's copy: off that copy's elements, and not a + /// structured view that can be a raw view of the same bytes. + #[test] + fn a_view_off_its_copys_elements_gets_its_own_bytes() { + let base = 0xd_9000_0000u64; + // On an element: the buffer's copy (the two cases of every run's + // log are the ones below). + assert_eq!(own_bytes_if(true, 24, base, 3, 10, 12, 0, false), None); + assert_eq!(own_bytes_if(true, 0, base, 0, 10, 12, 0, false), None); + // A typed view of 12-byte elements, 5,222,240 bytes into its copy + // (8 past an element): its own bytes, from its first element. + assert_eq!(own_bytes_if(true, 5_222_240, base, 3, 10, 12, 0, false), Some((base + 36, 120))); + // A structured view of 32-byte elements 8 bytes in: not on 16, so + // no raw view of the copy either. + assert_eq!(own_bytes_if(true, 8, base, 2, 4, 32, 32, true), Some((base + 64, 128))); + // The same 16 bytes in: off its elements, but a raw view of the + // copy's bytes does (as before). + assert_eq!(own_bytes_if(true, 16, base, 2, 4, 32, 32, true), None); + // No elements, no size, or the switch off: as before. + assert_eq!(own_bytes_if(true, 8, base, 2, 0, 32, 32, true), None); + assert_eq!(own_bytes_if(true, 8, base, 2, 4, 0, 0, false), None); + assert_eq!(own_bytes_if(false, 8, base, 2, 4, 32, 32, true), None); } } diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index 0e8dd27213..1a57711dd3 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -29,7 +29,7 @@ pub static IID: Iid = guid( ); /// The levels the device answers to, as on PC: `ID3D12Device1` to -/// `ID3D12Device8`, and `ID3D12Device11`, which Grand Theft Auto VI creates +/// `ID3D12Device8`, and `ID3D12Device11`, which the title creates /// its device as. Each level's table is the one before plus its methods. const LEVEL_IIDS: [Iid; 9] = [ guid( @@ -94,7 +94,7 @@ pub(crate) fn is_device(iid: *const Iid) -> bool { } /// The interface version these layouts were checked against (2.4). Both -/// Minecraft (March 2022) and Grand Theft Auto VI (April 2026) pass it. +/// Minecraft (March 2022) and the title (April 2026) pass it. pub const CHECKED_VERSION: u32 = 0x0002_0004; /// Feature level 12_2, what the console hardware supports. @@ -160,7 +160,7 @@ pub extern "system" fn create( /// queues then have the newer layouts (two more methods each; see /// `list` and `queue`), although the interface version stays 2.4. /// shortcut: the creation interface is the only sign of the newer layouts -/// we have (Grand Theft Auto VI, April 2026, versus Minecraft, March 2022); +/// we have (the title, April 2026, versus Minecraft, March 2022); /// look for a better one if a title breaks the rule. static NEWER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -273,16 +273,12 @@ extern "system" fn check_feature_support( const FEATURE_LEVELS: u32 = 2; const FORMAT_SUPPORT: u32 = 3; const MULTISAMPLE: u32 = 4; - const FORMAT_INFO: u32 = 5; - const VIRTUAL_ADDRESS: u32 = 6; let expected = match feature { OPTIONS_QUERY => size_of_val(&OPTIONS), ARCHITECTURE => 16, FEATURE_LEVELS => size_of::<FeatureLevels>(), FORMAT_SUPPORT => 12, MULTISAMPLE => 16, - FORMAT_INFO => 8, - VIRTUAL_ADDRESS => 8, _ => { tracing::warn!(feature, size, "device feature query not implemented"); return E_NOTIMPL; @@ -324,33 +320,10 @@ extern "system" fn check_feature_support( q[3] = u32::from(matches!(q[1], 1 | 2 | 4 | 8)); S_OK } - FORMAT_INFO => { - // SAFETY: checked size and non-null. - let q = unsafe { &mut *data.cast::<[u32; 2]>() }; - // DXGI_FORMAT in, plane count out (the byte is padded to 8). - q[1] = plane_count(q[0]); - S_OK - } - VIRTUAL_ADDRESS => { - // SAFETY: checked size and non-null. - let q = unsafe { &mut *data.cast::<[u32; 2]>() }; - // The bits OPTIONS reports for a resource, and user space's - // 48 bits for the process (addresses are CPU addresses here). - q[0] = OPTIONS[9]; - q[1] = 48; - S_OK - } _ => feature_levels(data), } } -/// The planes of the depth/stencil format families; everything else has -/// one. These are the DXGI format numbers, including the typeless and -/// read-only views of the same two planes. -fn plane_count(format: u32) -> u32 { - 1 + u32::from(matches!(format, 19..=22 | 44..=47)) -} - fn feature_levels(data: *mut c_void) -> HRESULT { // SAFETY: the caller checked size and non-null. let query = unsafe { &mut *data.cast::<FeatureLevels>() }; @@ -373,16 +346,164 @@ fn feature_levels(data: *mut c_void) -> HRESULT { } } -/// The host device's state: the console's device is removed when the host's is. -extern "system" fn removed_reason(_: This) -> HRESULT { +/// Device methods 0x1c8 and 0x218 (`SLOT`). The title calls both +/// (title+0x2477578 and title+0x24800d5) as `(this, description, interface +/// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the +/// object `out` names and draws with it. They are the console's +/// pipelines from precompiled binaries (code and metadata per stage, the +/// title's root signature, a register image), called in one burst while +/// loading: a cache. On failure the title makes the same pipeline later the +/// usual way (`create_stream`), so nothing goes missing (run 335: every call +/// in the first 36 s, then 727 mesh and 1,016 pixel pipelines made normally; +/// upstream VIctory #3163 says the same, and that answering them made things +/// worse there). The calls fail as they always did, with `out` null, and the +/// first ones log what the description holds. +/// shortcut: not implemented. Answering `S_OK` here without making the +/// pipeline would hand the title whatever its stack held as an object. +extern "system" fn unknown_pipeline<const SLOT: usize>( + _: This, + desc: *const u8, + _iid: *const Iid, + out: *mut This, +) -> HRESULT { + use std::sync::atomic::{AtomicU32, Ordering}; + static CALLS: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2]; + let calls = CALLS[usize::from(SLOT == 0x218)].fetch_add(1, Ordering::Relaxed) + 1; + if !out.is_null() { + // SAFETY: the title's out pointer (a local of its own). + unsafe { *out = std::ptr::null() }; + } + if calls <= 4 || calls.is_power_of_two() { + // Sixteen 64-bit words at `at`, read through the kernel: neither + // pointer is known to be mapped. + #[cfg(windows)] + let words = |at: usize| -> Option<Vec<u64>> { + let mut bytes = [0u8; 128]; + (at != 0 && crate::host::read_into(at as *const u8, &mut bytes)).then(|| { + bytes + .as_chunks::<8>().0.iter() + .map(|c| c.iter().rev().fold(0u64, |v, &b| v << 8 | u64::from(b))) + .collect() + }) + }; + #[cfg(not(windows))] + let words = |_: usize| None::<Vec<u64>>; + let description = words(desc as usize); + let first = description + .as_ref() + .and_then(|w| words(w[0] as usize)); + tracing::warn!( + slot = format_args!("{:#x}", SLOT), + calls, + description = format_args!("{description:x?}"), + first_points_at = format_args!("{first:x?}"), + "a pipeline creation method that is not implemented: the title goes without this pipeline" + ); + // The first calls also log the bytes of each (address, length) pair + // of the description (words 1-12: the root signature is word 0), for + // writing the methods from them. + #[cfg(windows)] + if calls <= 3 + && let Some(w) = &description + { + for i in (1..12).step_by(2) { + let (at, len) = (w[i] as usize, w[i + 1] as usize); + if at == 0 || len == 0 || len > 0x800 { + continue; + } + let mut bytes = vec![0u8; len]; + if crate::host::read_into(at as *const u8, &mut bytes) { + let hex: String = bytes + .as_chunks::<4>() + .0 + .iter() + .map(|c| format!("{:08x} ", u32::from_le_bytes(*c))) + .collect(); + tracing::warn!( + slot = format_args!("{:#x}", SLOT), + calls, + word = i, + at = format_args!("{at:#x}"), + len = format_args!("{len:#x}"), + "pipeline description piece: {hex}" + ); + } + } + } + } #[cfg(windows)] - if let Some(host) = crate::host::host() { - // SAFETY: a plain query. - if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } { - return e.code().0; + if let Some(dir) = std::env::var_os("VICTORY_NATIVE_PSO_DUMP") { + dump_native(SLOT, desc as usize, std::path::Path::new(&dir)); + } + E_NOTIMPL +} + +/// `VICTORY_NATIVE_PSO_DUMP=<dir>` (diagnostics; off unless set): the blobs +/// a 0x1c8 / 0x218 description names, once per description key (0x218: its +/// word 11, a 64-bit hash; 0x1c8: the code pointers of words 5 and 9). +/// Files: `<dir>/<slot>_<key>/desc.bin` (the first 0x80 bytes), `root.bin` +/// (0x80 bytes at word 0), `w<i>_<size>.bin` for each (pointer, size) pair +/// at words (1,2) (3,4) (5,6) (7,8) (9,10) (11,12), and `p9.bin` / +/// `p10.bin` (0x100 bytes at 0x218's two unsized pointers). Everything is +/// read through the kernel (`host::read_into`): an unmapped pointer is +/// skipped, never touched. +#[cfg(windows)] +fn dump_native(slot: usize, desc: usize, dir: &std::path::Path) { + use std::sync::Mutex; + static SEEN: Mutex<Vec<(usize, u64)>> = Mutex::new(Vec::new()); + let read = |at: usize, n: usize| -> Option<Vec<u8>> { + let mut b = vec![0u8; n]; + (at != 0 && n <= 1 << 20 && crate::host::read_into(at as *const u8, &mut b)).then_some(b) + }; + let Some(d) = read(desc, 0x100) else { + return; + }; + let w = |i: usize| u64::from_le_bytes(d[8 * i..8 * i + 8].try_into().unwrap_or([0; 8])); + // 0x218: its code pointer (word 11 is not a key: gfx41); 0x1c8: the + // code pointers of words 5 and 9. + let key = if slot == 0x218 { w(5) } else { w(5) ^ (w(9) << 1) }; + { + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.contains(&(slot, key)) || seen.len() >= 16384 { + return; + } + seen.push((slot, key)); + } + let sub = dir.join(format!("{slot:x}_{key:016x}")); + let _ = std::fs::create_dir_all(&sub); + let _ = std::fs::write(sub.join("desc.bin"), &d); + if let Some(r) = read(w(0) as usize, 0x80) { + let _ = std::fs::write(sub.join("root.bin"), r); + } + // The root signature's serialized form, once per root object. + { + static ROOTS: Mutex<Vec<u64>> = Mutex::new(Vec::new()); + let mut roots = ROOTS.lock().unwrap_or_else(|e| e.into_inner()); + if !roots.contains(&w(0)) { + roots.push(w(0)); + if let Some(b) = crate::root::blob(w(0) as usize as crate::object::This) { + let _ = std::fs::create_dir_all(dir.join("roots")); + let _ = std::fs::write(dir.join("roots").join(format!("{:x}.bin", w(0))), b); + } + } + } + let pairs: &[usize] = if slot == 0x218 { &[1, 3, 5, 7] } else { &[1, 3, 5, 7, 9, 11, 13, 15] }; + for &i in pairs { + let (at, size) = (w(i) as usize, w(i + 1) as usize); + if at == 0 || size == 0 || size > 1 << 20 { + continue; + } + if let Some(b) = read(at, size) { + let _ = std::fs::write(sub.join(format!("w{i}_{size:x}.bin")), b); + } + } + if slot == 0x218 { + for i in [9usize, 10] { + if let Some(b) = read(w(i) as usize, 0x100) { + let _ = std::fs::write(sub.join(format!("p{i}.bin")), b); + } } } - S_OK } /// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the @@ -417,15 +538,15 @@ static FUNCTIONS: Table<160> = { f[28] = resource::create_heap as *const (); // 0xe0 f[29] = resource::create_placed as *const (); // 0xe8 f[36] = fence::create as *const (); // 0x120 - f[37] = removed_reason as *const (); // 0x128 f[38] = resource::copyable_footprints as *const (); // 0x130 f[39] = query::create as *const (); // 0x138 f[41] = signature::create as *const (); // 0x148 f[48] = queue::create_x as *const (); // 0x180 - f[57] = object::ignore as *const (); // 0x1c8 + f[55] = pipeline::create_derived as *const (); // 0x1b8 + f[57] = unknown_pipeline::<0x1c8> as *const (); // 0x1c8 f[61] = descriptor::create_sampler_x as *const (); // 0x1e8 f[62] = pipeline::create_compute_x as *const (); // 0x1f0 - f[67] = object::ignore as *const (); // 0x218 + f[67] = unknown_pipeline::<0x218> as *const (); // 0x218 f[69] = object::ignore as *const (); // 0x228 debug error filter f[70] = descriptor::create_placed_srv as *const (); // 0x230 f[71] = descriptor::create_placed_uav as *const (); // 0x238 @@ -473,15 +594,11 @@ mod tests { ); let missing = slot::<extern "system" fn() -> HRESULT>(device, 0xf0); assert_eq!(missing(), E_NOTIMPL); - let s1c8 = slot::<extern "system" fn() -> HRESULT>(device, 0x1c8); - assert_eq!(s1c8(), S_OK); - let s218 = slot::<extern "system" fn() -> HRESULT>(device, 0x218); - assert_eq!(s218(), S_OK); } #[test] fn newer_device_levels_are_the_same_device() { - // ID3D12Device11, as Grand Theft Auto VI asks for it. + // ID3D12Device11, as the title asks for it. let (hr, device) = create_as(&LEVEL_IIDS[8]); assert_eq!((hr, device), (S_OK, super::device())); let mut same = std::ptr::null(); @@ -575,89 +692,4 @@ mod tests { assert_eq!(query(&levels, 0x10).0, E_INVALIDARG); assert_eq!(query(&levels[4..], 0x18).0, UNSUPPORTED); } - - #[test] - fn format_info_reports_the_planes_of_depth_formats() { - type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; - let check = slot::<Check>(device(), 0x68); - let query = |format: u32, size| { - let mut info = [format, u32::MAX]; - let hr = check(device(), 5, (&raw mut info).cast(), size); - (hr, info[1]) - }; - assert_eq!(query(28, 8), (S_OK, 1), "R8G8B8A8_UNORM"); - assert_eq!(query(45, 8), (S_OK, 2), "D24_UNORM_S8_UINT"); - assert_eq!(query(20, 8), (S_OK, 2), "D32_FLOAT_S8X24_UINT"); - assert_eq!(query(19, 8), (S_OK, 2), "R32G8X24_TYPELESS"); - assert_eq!(query(47, 8), (S_OK, 2), "X24_TYPELESS_G8_UINT"); - assert_eq!(query(28, 4).0, E_INVALIDARG, "wrong size"); - } - - #[test] - fn virtual_address_support_matches_the_reported_address_space() { - type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; - let check = slot::<Check>(device(), 0x68); - let mut info = [0u32; 2]; - assert_eq!(check(device(), 6, (&raw mut info).cast(), 8), S_OK); - assert_eq!(info[0], OPTIONS[9], "resource bits agree with OPTIONS"); - assert_eq!(info[1], 48); - assert_eq!(check(device(), 6, (&raw mut info).cast(), 4), E_INVALIDARG); - } - - #[test] - fn feature_options_report_the_rdna2_tiers() { - type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; - let device = device(); - let check = slot::<Check>(device, 0x68); - let mut options = [0u32; 16]; - assert_eq!(check(device, 0, options.as_mut_ptr().cast(), 64), S_OK); - assert_eq!(options, OPTIONS); - assert_eq!( - (options[3], options[4], options[8], options[9], options[15]), - (3, 3, 3, 40, 2) - ); - assert_eq!( - check(device, 0, options.as_mut_ptr().cast(), 60), - E_INVALIDARG - ); - assert_eq!(check(device, 0, std::ptr::null_mut(), 64), E_INVALIDARG); - } - - #[test] - fn feature_architecture_is_unified_and_coherent() { - type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; - let device = device(); - let check = slot::<Check>(device, 0x68); - let mut arch = [0u32; 4]; - assert_eq!(check(device, 1, arch.as_mut_ptr().cast(), 16), S_OK); - assert_eq!(arch, [0, 0, 1, 1]); - arch[0] = 1; - assert_eq!(check(device, 1, arch.as_mut_ptr().cast(), 16), E_INVALIDARG); - } - - #[test] - fn feature_multisample_has_one_level_for_the_hardware_counts() { - type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; - let device = device(); - let check = slot::<Check>(device, 0x68); - let levels = |samples: u32| { - // Format, sample count, flags in; quality levels out. - let mut query = [28, samples, 0, 99]; - assert_eq!(check(device, 4, query.as_mut_ptr().cast(), 16), S_OK); - query[3] - }; - for samples in [1, 2, 4, 8] { - assert_eq!(levels(samples), 1, "{samples} samples"); - } - for samples in [0, 3, 16] { - assert_eq!(levels(samples), 0, "{samples} samples"); - } - } - - #[test] - fn a_healthy_device_reports_no_removal() { - let device = device(); - let reason = slot::<extern "system" fn(This) -> HRESULT>(device, 0x128); - assert_eq!(reason(device), S_OK); - } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 57cd226b26..f325a4d919 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -10,15 +10,14 @@ use std::sync::atomic::{AtomicU64, Ordering}; +use victory_shader::resource::RootIndexedView; use victory_shader::{ResourceType, RootType, UsedResource}; use crate::descriptor::View; use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; use windows::Win32::Graphics::Direct3D12::*; -use windows::Win32::Graphics::Dxgi::Common::{ - DXGI_FORMAT, DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_UNKNOWN, -}; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; use windows::core::Interface; use crate::host::HostList; @@ -40,9 +39,9 @@ enum Root { #[repr(C)] #[derive(Debug, Clone, Copy, Default)] pub(crate) struct VertexView { - pub(crate) address: u64, - pub(crate) size: u32, - pub(crate) stride: u32, + address: u64, + size: u32, + stride: u32, } #[repr(C)] @@ -53,20 +52,448 @@ pub(crate) struct IndexView { format: u32, } -const SHADER_RESOURCE: u32 = 0x40 | 0x80; +/// Host states of a depth target, and of a texture shaders read. const DEPTH_WRITE: u32 = 0x10; const DEPTH_READ: u32 = 0x20; +const SHADER_RESOURCE: u32 = 0x40 | 0x80; + +thread_local! { + /// While a draw is prepared (`State::bind`, then its targets' states): + /// the depth target the draw only tests (0: none, or one it writes), + /// and whether a view its shaders read is of that same texture. + static TESTED_DEPTH: std::cell::Cell<(usize, bool)> = + const { std::cell::Cell::new((0, false)) }; + /// While a stage's tables are walked (`State::tables`): whether that + /// stage's shader can store to buffers (`Translated::stores`). + static STORES: std::cell::Cell<bool> = const { std::cell::Cell::new(true) }; + /// While `State::early_textures` runs the texture pass: the + /// milliseconds and the bytes that run may take, in place of the + /// pass's own per frame. + static PASS_BUDGET: std::cell::Cell<Option<(u64, u64)>> = const { std::cell::Cell::new(None) }; + /// For the run of the texture pass `State::bake_sources_pass` makes + /// before a draw of the title's skin bake: the title slots that draw + /// samples and that wait in the queue. That run serves them alone, + /// whatever their turn, and none of the queue's upkeep. Set and taken + /// on the thread that records the draw only: the worker's passes + /// (`crate::heap_worker`) never see it. + static PASS_SOURCES: std::cell::RefCell<Option<Vec<u32>>> = const { std::cell::RefCell::new(None) }; + /// What that run did with them: uploaded, their bytes, left because + /// their memory is not mapped, and left because no more of their + /// memory is mapped than at their last upload. + static PASS_SOURCED: std::cell::Cell<[u64; 4]> = const { std::cell::Cell::new([0; 4]) }; + /// The tables a pixel shader reads as a skin bake does + /// ([`bake_tables`]), by the shader's hash. + static BAKE_TABLES: std::cell::RefCell<std::collections::HashMap<String, Option<BakeTables>>> = + std::cell::RefCell::new(std::collections::HashMap::new()); +} + +/// The milliseconds of every frame the pass that uploads textures picked +/// by index takes before a shader that picks by index has asked for it +/// (`VICTORY_EARLY_TEXTURES_MS`, 12; 0: never, as before), and the +/// milliseconds it may take just before a draw of the title's decoration +/// bake (`VICTORY_BAKE_TEXTURES_MS`, 1500; 0: nothing special). +/// +/// The pass ran only from the first world frame on, where it met some +/// 24,000 slots at once and needed 60-80 frames for them. The title bakes +/// its characters' skin and decorations into textures of its own while it +/// loads, 159-1,165 frames before that (runs 156-174), with a pixel shader +/// that picks its sources by index: whatever was not on the card then was +/// baked as nothing, once, for the run. On the console a texture is there +/// when its bytes are. +fn early_budgets() -> (u64, u64) { + static MS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + *MS.get_or_init(|| { + let ms = |name: &str, default: u64| { + std::env::var(name).ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(default) + }; + (ms("VICTORY_EARLY_TEXTURES_MS", 12), ms("VICTORY_BAKE_TEXTURES_MS", 1500)) + }) +} + +/// The pixel shaders of the title's decoration bake (the title: +/// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the +/// frame listings print it. They draw into a 256x256 corner of 2048x2048 +/// targets and name no texture in a table. +const BAKE_PIXEL_SHADERS: [&str; 4] = + ["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"]; + +/// Where a pixel shader of the title's skin bake finds what it samples +/// (fork pull request #1264, head 4c14ca41): the root parameter of its one +/// table, and in that table the dwords of its buffer of decoration records +/// and of its constants. +/// +/// The bake names no texture in a table. Its constants hold the view heap +/// indices of up to five textures (bytes 0x20, 0x30, 0x40, 0x50 and 0x60) +/// and the records it walks (first at 0x78, the one past the last at 0x7c); +/// a record is 304 bytes and holds five more indices (bytes 0, 0x10, 0x20, +/// 0x30 and 0x40). The same in all 322 bake programs but for the two table +/// offsets (by that pull request); an index counts only if the slot it +/// names holds a texture view. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +struct BakeTables { + slot: u8, + records: u32, + constants: u32, +} + +/// The stride of the bake's records. +const BAKE_RECORD: u64 = 304; +/// Where its constants and each of its records hold view heap indices. +const BAKE_CONSTANT_INDICES: [usize; 5] = [0x20, 0x30, 0x40, 0x50, 0x60]; +const BAKE_RECORD_INDICES: [usize; 5] = [0, 0x10, 0x20, 0x30, 0x40]; + +/// [`BakeTables`] of pipeline `p`, if its pixel shader reads one table +/// with a buffer of 304-byte records and constants and nothing else +/// through tables. +fn bake_tables(p: &HostPipeline) -> Option<BakeTables> { + let stage = p.stages.iter().find(|s| s.shader.stage == "pixel")?; + let read = || { + let mut tabled = stage.translated().used.iter().filter(|u| u.root == RootType::Table); + let (a, b) = (tabled.next()?, tabled.next()?); + if tabled.next().is_some() { + return None; + } + let (records, constants) = if a.kind == ResourceType::Srv { (a, b) } else { (b, a) }; + (records.kind == ResourceType::Srv + && u64::from(records.stride) == BAKE_RECORD + && constants.kind == ResourceType::Cbv + && records.slot == constants.slot) + .then_some(BakeTables { + slot: records.slot, + records: records.table_offset_dwords, + constants: constants.table_offset_dwords, + }) + }; + BAKE_TABLES.with_borrow_mut(|known| match known.get(stage.shader.hash.as_str()) { + Some(&tables) => tables, + None => { + let tables = read(); + known.insert(stage.shader.hash.clone(), tables); + tables + } + }) +} + +/// The view heap indices a bake draw names, in order and each once, and +/// the records it walks with how many of them were read: from its +/// constants, and from the records `first..end` they give and the one +/// after them, which the program looks at as well; no more records than +/// the buffer holds (`held`), and no more than 256. `record` reads the +/// start of one. +fn bake_named( + constants: &[u8; 0x80], + held: u32, + mut record: impl FnMut(u32) -> Option<[u8; 0x44]>, +) -> (Vec<u32>, (u32, u32)) { + let word = |bytes: &[u8], at: usize| u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]); + let mut named: Vec<u32> = BAKE_CONSTANT_INDICES.iter().map(|&at| word(constants, at)).collect(); + let (first, end) = (word(constants, 0x78), word(constants, 0x7c)); + let mut read = 0; + // (No record is looked at where none is walked.) + let last = if end > first { end.saturating_add(1) } else { first }; + for i in first..last.min(held).min(first.saturating_add(256)) { + let Some(record) = record(i) else { + break; + }; + named.extend(BAKE_RECORD_INDICES.iter().map(|&at| word(&record, at))); + read += 1; + } + named.sort_unstable(); + named.dedup(); + (named, (end.saturating_sub(first), read)) +} + +/// What is done for a skin-bake draw's own textures +/// (`VICTORY_BAKE_SOURCES`): unset or anything else, nothing (no draw is +/// even looked at); `count`, the textures each such draw samples are +/// counted, and those it samples while they still wait for their upload +/// are logged; `1`, those are also uploaded before the draw, on the thread +/// that records it, up to `VICTORY_BAKE_SOURCES_MB` (64) megabytes a draw, +/// and only while the card has room for textures (`resource::room`). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum BakeMode { + Off, + Count, + Upload, + /// [`BakeMode::Upload`] also while the card has no room + /// (`VICTORY_BAKE_SOURCES=full`), as fork pull request #1264 had it: + /// at the boat save every such upload was skipped for room (run 316: 55 + /// of 55), the card being at its line through the whole world. Still + /// within `VICTORY_BAKE_SOURCES_MB` a draw. + Full, +} + +/// [`BakeMode`], and the bytes one draw may have uploaded. +fn bake_sources_mode() -> (BakeMode, u64) { + static MODE: std::sync::OnceLock<(BakeMode, u64)> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| { + let mode = match std::env::var("VICTORY_BAKE_SOURCES").ok().as_deref().map(str::trim) { + Some("count") => BakeMode::Count, + Some("1") => BakeMode::Upload, + Some("full") => BakeMode::Full, + _ => BakeMode::Off, + }; + let mb = std::env::var("VICTORY_BAKE_SOURCES_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(64); + if mode != BakeMode::Off { + tracing::info!(?mode, megabytes_a_draw = mb, "skin-bake draws' own textures (VICTORY_BAKE_SOURCES)"); + } + (mode, mb << 20) + }) +} + +/// What a bake draw samples ([`State::bake_sources`]). +#[derive(Default, Debug)] +struct BakeSources { + /// The records the draw walks, and how many of them were read. + records: (u32, u32), + /// Slots named that hold a texture view, and their handles. + textures: Vec<(u32, u64)>, + /// Of them: with their host texture made from that view and nothing + /// waiting. + ready: u32, + /// Waiting in the queue of textures picked by index. + queued: Vec<u32>, + /// Neither, and a texture the title placed in memory that is there: + /// the host slot shows nothing, and nothing would make it (the title + /// wrote a newer view of memory this one clashes with, which made this + /// one stale to the layer; the bake reads it all the same). + unmade: Vec<u32>, + /// Neither, and something else: a texture the host itself writes. + other: u32, +} + +/// Since the start: early runs of the texture pass, and those of them +/// made for a bake draw. +pub(crate) static EARLY_TEXTURE_PASSES: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + +/// Whether a buffer range a shader names through an unordered access view +/// is given to shaders as written (snapshot before the submission, compare +/// and write back after) only if that shader's code can store to buffers. +/// The title binds buffers its shaders only read through such views, and +/// every range declared costs a snapshot and a compare of its bytes: 3.97 +/// GB a frame in 31 submissions, 0.49 s of snapshots and 0.28 s of +/// comparing (run 28). On by default; `VICTORY_WRITE_SKIP=0` declares +/// every such range, as before. +fn write_skip() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WRITE_SKIP").is_none_or(|v| v != "0")) +} + +/// A run of indirect records clamped in one pass ([`windows`]): the host +/// copy they came from (its number), their kind and stride, the offset of +/// the first in that copy, how many, and the list's scratch buffer that +/// holds them clamped, record `i` at `i * step`. +#[derive(Clone)] +struct Window { + copy: u64, + kind: u32, + stride: u32, + /// How far apart the records are in the copy, and in the scratch + /// buffer: what the title walks them by ([`windows`]). + step: u32, + base: u64, + records: u32, + scratch: ID3D12Resource, +} + +/// The most records clamped in one pass ([`windows`]). +const WINDOW_MOST: u64 = 64; + +/// Whether indirect draws that read record after record of one argument +/// buffer are clamped a window at a time (`VICTORY_INDIRECT_WINDOW=1`; off +/// by default). +/// +/// The title issues its mesh draws one record per call, each from the next +/// slot of the same argument buffer: 3,460 a frame in gameplay, and before +/// each our clamp ran as a compute dispatch of its own between two waits, +/// so the card went from drawing to compute and back for every record. In +/// the timing run of the lit scene (run 79) a shadow draw of next to +/// nothing cost 14-16 microseconds, 4,126 records a frame. +/// +/// With the switch, when a draw asks for a record a short step after the +/// one drawn before, the clamp takes that record and the ones that step +/// apart after it (16, then twice as many each time, [`WINDOW_MOST`] at +/// most, never past the buffer) into +/// the list's scratch buffer in one pass, and the draws that follow read +/// their record there with no pass of ours and no barrier (the scratch +/// buffer stays readable as arguments until the next clamp), until one of +/// these: a compute +/// dispatch, a direct draw, an indirect call with a count buffer or more +/// than one record, a draw whose shaders can store to buffers, a record +/// outside the window, another host list. +/// +/// The step is the one the title is seen to take, not the stride its +/// command signature names: it draws one record a call, for which the +/// stride means nothing, and the title names 12 bytes (the three +/// words of a mesh dispatch) for records it keeps 32 bytes apart (2,173 of +/// a frame's 3,349 mesh records in run 87's listed frame; 283 are 16 +/// apart, which ends a window). Walked by the named stride the window +/// never opened: run 87, with the switch, still clamped 5,068 records a +/// frame one at a time. +/// +/// What it costs the guard against garbage records: nothing against a +/// hang (every record is bounded as before and charged to the list's +/// budget as before), but the budget is charged when a window is clamped, +/// so also for records of the window's tail that are never drawn. Those +/// hold garbage in this title (slots of all ones: run 93 spent lists' +/// budgets on them and emptied the draws after), so in a window a record +/// that asks for more than can run is left empty and charges nothing +/// (`crate::indirect::bound_ahead`); a tail record that looks real is +/// charged what it asks, a few thousand of 2^27. And arguments the title's CPU side changes are seen as +/// before, at the next submission. +/// +/// Off for the rest of the run from the first error the card's driver +/// reports to the system (`crate::drvwatch`): every loss of the card in a +/// run with windows was announced that way seconds ahead. +fn windows() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1")) && !crate::drvwatch::tripped() +} + +/// Whether a record that is not on the window's walk opens a window of its +/// own at once, with the step the title was last seen to walk that +/// argument buffer by (`VICTORY_WINDOW_JUMP=1`; `alt`: twenty seconds +/// with, twenty without, in turn, each change said in the log). Off by +/// default. Needs [`windows`]. +/// +/// Run 243 counted, per frame, 2,370 indirect commands read from a window +/// and 2,370 clamped by a pass of ours; 960 of those passes were for +/// records "off the window's walk": the title draws a few records one +/// after the other and then jumps to another place in the same argument +/// buffer, some 480 times a frame. The record after a jump was clamped +/// alone (its step is not known from one record), and the one after it +/// opened a window of sixteen: two passes a jump, each one a trip of the +/// card from drawing to compute and back (9 microseconds in the game). +/// +/// With the switch the step of the last window that draws did read from +/// is remembered with its argument buffer, kind and stride, and a record +/// that would be clamped alone on that buffer opens sixteen records at +/// that step instead: what the next record would have opened anyway, one +/// record earlier, so no more of the list's budget is spent than before. +/// If no draw reads from a window opened that way before the next pass, +/// the step is forgotten until a walk shows it again: a title that draws +/// lone records all over a buffer gets what it had. +fn jump_windows() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_WINDOW_JUMP").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a record off the window's walk opens a window at the remembered step from now (VICTORY_WINDOW_JUMP=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} -#[derive(Clone, Copy)] -struct DepthTarget { - resource: usize, - state: u32, +/// Whether a single record that misses its window is gathered: given a +/// slot that the list's prelude fills in one pass with the list's other +/// such records, in place of a pass of ours in front of its draw +/// (`crate::indirect::gather`; `VICTORY_INDIRECT_GATHER=1`; `alt`: twenty +/// seconds with, twenty without, in turn, each change said in the log). +/// Off by default. Needs [`windows`]. +fn gathers() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_INDIRECT_GATHER").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "single indirect records are gathered for their list's prelude from now (VICTORY_INDIRECT_GATHER=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// The records of a window opened at a remembered step ([`jump_windows`]): +/// what the record after a lone one opens. +const WINDOW_JUMP: u32 = 16; + +/// What a record that would be clamped alone opens instead, if the step +/// its argument buffer is walked by is remembered: that step and how many +/// records (never past the buffer, of which `left` bytes are left from +/// the record on). None if nothing is remembered for this buffer, kind +/// and stride, or no second record fits. +fn jump_window(remembered: Option<(u64, u32, u32, u32)>, (copy, kind, stride): (u64, u32, u32), left: u64) -> Option<(u32, u32)> { + let (c, k, s, step) = remembered?; + if (c, k, s) != (copy, kind, stride) || step == 0 { + return None; + } + let fit = (left / u64::from(step)).min(u64::from(WINDOW_JUMP)) as u32; + (fit > 1).then_some((step, fit)) } -/// A UAV clear's value, as the title's call gives it. -pub(crate) enum UavClear { - Uint([u32; 4]), - Float([f32; 4]), +/// Diagnostics of [`windows`]: indirect commands since the last line, by +/// what became of their clamp. In order: read from a window (no pass of +/// ours); then clamped by a pass of ours because: it is a dispatch; it +/// asks for more than one record; it has a count buffer; its shaders can +/// store to buffers; it is the list's first; there was no window on its +/// argument buffer (another buffer, kind or stride, or the window was +/// ended); its record does not continue the window's walk; it is past the +/// window's end (the next window: as meant). And the records those passes +/// clamped in all; the passes that opened a window at a remembered step +/// ([`jump_windows`]), and those of them no draw read from; the commands +/// that read a gathered record ([`gathers`]: no pass of ours either), and +/// those that asked for one and got none (the list no longer gathers, or +/// its set is full). +#[cfg(feature = "diagnostics")] +pub(crate) static WINDOW_WHY: [std::sync::atomic::AtomicU64; 14] = [const { std::sync::atomic::AtomicU64::new(0) }; 14]; + +/// The line of [`WINDOW_WHY`], per frame over `frames` frames. +#[cfg(feature = "diagnostics")] +pub(crate) fn window_line(frames: f64) { + let n: Vec<f64> = WINDOW_WHY.iter().map(|n| n.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames.max(1.0)).collect(); + let g: Vec<f64> = crate::indirect::GATHER_NONE.iter().map(|n| n.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames.max(1.0)).collect(); + tracing::info!( + "indirect commands per frame by their clamp: {:.0} read from a window (no pass of ours); a pass of ours for {:.0}: {:.0} dispatches, {:.0} of more than one record, {:.0} with a count \ + buffer, {:.0} whose shaders can store to buffers, {:.0} first on their list, {:.0} with no window on their argument buffer, {:.0} off the window's walk, {:.0} past the window's end; \ + {:.0} records clamped by those passes; {:.0} of the passes opened a window at a remembered step (VICTORY_WINDOW_JUMP=1), {:.0} of those windows were read by no draw; \ + {:.0} read a record gathered for their list's prelude (VICTORY_INDIRECT_GATHER=1), {:.0} asked for one and got none (no fit for the clamp {:.0}, the list had stopped gathering {:.0}, too many buffers {:.0}, the set full {:.0}, no buffer {:.0})", + n[0], + n[1..9].iter().sum::<f64>(), + n[1], + n[2], + n[3], + n[4], + n[5], + n[6], + n[7], + n[8], + n[9], + n[10], + n[11], + n[12], + n[13], + g[0], + g[1], + g[2], + g[3], + g[4], + ); } /// What one title list has set, and what its host list was last given. @@ -81,35 +508,432 @@ pub(crate) struct State { index: IndexView, /// Bound render target and depth resources, for their host states. targets: Vec<usize>, - depth: Option<DepthTarget>, - /// The current draw also samples its read-only depth target. - depth_sampled: bool, + depth: usize, + /// The host state the bound depth view needs ([`depth_state`]). + depth_state: u32, /// The title's primitive topology (the host's may differ). topology: u32, + /// What the title set that goes straight onto the host list, kept for + /// the host list that continues this one after a cut ([`State::replay`]): + /// whether a topology was set, the render target and depth handles, the + /// viewports, the scissors, the blend factor and the stencil reference. + topology_set: bool, + target_handles: Vec<u64>, + depth_handle: u64, + targets_set: bool, + /// The render target views and the depth view the host list has, once + /// it has any ([`State::set_targets`]): per view the host texture (0: + /// a null view) and what its descriptor says. + host_targets: Option<(Vec<TargetKey>, Option<TargetKey>)>, + /// The formats of the views [`State::set_targets`] bound on the host + /// list: a draw's pipeline is one for them + /// (`crate::pipeline::host_pipeline_for`). + target_formats: crate::pipeline::host::TargetFormats, + viewports: Vec<D3D12_VIEWPORT>, + scissors: Vec<RECT>, + blend: Option<[f32; 4]>, + stencil: Option<u32>, + /// The title's depth bounds (`OMSetDepthBounds`), set again after a cut. + depth_bounds: Option<[f32; 2]>, + /// The indirect records clamped last, if later draws may still read + /// them ([`windows`]). + window: Option<Window>, + /// With [`jump_windows`]: the argument buffer (its copy's number), kind + /// and stride of the last window of several records that a draw read + /// from, and that window's step. + walk_step: Option<(u64, u32, u32, u32)>, + /// Whether [`State::window`] was opened at the remembered step, and + /// whether a draw has read from it since. + window_jumped: bool, + window_read: bool, + /// A direct dispatch spread across z, for [`State::host_word`] at its + /// bind: `[row, asked x]` (`[0, 0]`: not spread; an indirect one gets + /// its words from the clamp through its command signature). + dispatch_spread: [u32; 2], + /// A `DispatchX` that counts threads, for [`State::host_word`] at its + /// bind: the count per axis where it is not a whole number of groups, + /// else 0 (`USER_DISPATCH_THREADS`; fork pull request #646). + dispatch_threads: [u32; 3], + /// Diagnostics: the argument buffer and the offset of the indirect + /// command before this one on the list. + #[cfg(feature = "diagnostics")] + last_indirect: (u64, u64), /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. host_roots: [usize; 2], host_heaps: [usize; 2], - /// Tables made afresh in this list: (table, what it holds) → first + /// Tables made afresh in this list: (table, slot count, contents) → first /// dynamic slot. - fresh_tables: std::collections::HashMap<(u64, u64), u32>, - /// Root SRV views made in this list: (title heap, title address) → - /// dynamic slot (see [`State::bind_root_srv`]). - root_srv_slots: std::collections::HashMap<(usize, u64), u32>, - /// The dynamic slots the list holds: title heap, first, count; given - /// back when the list is reset or released. - dynamic: Vec<(usize, u32, u32)>, + fresh_tables: std::collections::HashMap<(u64, u32, u64), u32>, + /// Constant data copied to upload memory in this list ([`share_constants`]): + /// (host list, its title epoch, title address, bytes) → GPU address. + constant_fills: std::collections::HashMap<(usize, u64, u64, u32), u64>, + /// The dynamic slots the list holds: title heap, that heap's identity + /// (`HostHeap::id`), first, count; given back when the list has run, is + /// reset or released. + dynamic: Vec<(usize, u64, u32, u32)>, + /// Root SRVs bound as one-view tables in this list: (title heap, title + /// address; 0 for none) → dynamic slot, and the host copy the slot + /// shows: later draws of the list bring that one up to date, whatever + /// copy the address would find by then (`shadow.rs` `tails`). + root_srv_slots: std::collections::HashMap<(usize, u64), RootSlot>, + /// Root UAVs bound as one-view tables in this list, likewise. + root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>, + /// The list ran and its dynamic slots were given back. + tables_gone: bool, + /// Diagnostics: the number of this recording of the list, by which the + /// tables it makes twice are told ([`table_asked`]); 0 until its first. + #[cfg(feature = "diagnostics")] + recording: u64, +} + +/// Whether constant data that several fresh tables of a list name is +/// copied to upload memory once (`VICTORY_SHARE_CONSTANTS=0`: once per +/// table, as before Try 4.2). Try 4.2, idea 4, reuse of what was already +/// made (as a replay of recorded command buffers reuses them): a frame of +/// the world makes some 12,500 tables, most of them naming the same few +/// constant buffers of the frame and the view, and each copied them into +/// upload memory of its own at submission. Two fills of the same title +/// bytes recorded between the same two title writes of the list copy the +/// same bytes, so the second table's view shows the first's copy. +fn share_constants() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SHARE_CONSTANTS").is_none_or(|v| v != "0")) } impl Drop for State { fn drop(&mut self) { - for &(heap, first, n) in &self.dynamic { - crate::descriptor::release_dynamic(heap, first, n); + for &(heap, id, first, n) in &self.dynamic { + crate::descriptor::release_dynamic(heap, id, first, n); } } } +impl State { + /// The list's submission has run (submissions are waited for): the + /// dynamic slots its tables were made in are given back, not kept + /// until the title resets the list. A frame of the opening cutscene + /// asks for 12,500 tables; held until the resets they ran the 131,072 + /// slots out, and up to 4,900 draws a frame went without their tables. + /// shortcut: a list the title runs a second time without a reset then + /// reads slots others may have taken (logged once). + pub(crate) fn tables_done(&mut self) { + if self.tables_gone && self.dynamic.is_empty() { + return; + } + if self.tables_gone { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("a list ran again after its descriptor tables were given back")); + } + for (heap, id, first, n) in self.dynamic.drain(..) { + crate::descriptor::release_dynamic(heap, id, first, n); + } + self.fresh_tables.clear(); + self.constant_fills.clear(); + self.root_srv_slots.clear(); + self.root_uav_slots.clear(); + self.tables_gone = true; + #[cfg(feature = "diagnostics")] + { + self.recording = 0; + } + } +} + +/// Diagnostics, since the last line ([`tables_line`]): the descriptor tables +/// draws and dispatches have made afresh ([`State::tables`]). +/// 0: tables asked of the list's own memory of them (`fresh_tables`); 1: of +/// them, found there (the same table holding the same records). The others +/// are made, and each is counted once in 2 to 7 or in none of them: +/// 2: its records are those of a table this recording of the list made +/// before, at another address; 6: not that, but they differ from such a +/// table's only in where the constants are; 3, 4, 5: neither, but its +/// records are those of a table some list made earlier in this frame, in +/// the frame before, 2 to 8 frames before; 7: none of those, but they +/// differ only in where the constants are from a table made in this frame +/// or the 8 before. +/// 8 to 11: the tables to make by their slots (1, 2 to 4, 5 to 16, more); +/// 12: those slots; 13 to 16: the slots made as a constant view, a texture +/// view, another view (buffers), a null view; 17: entries made readable in +/// tables made; 18: in tables found; 19: entries of tables that are not +/// made afresh ([`State::table_entry`]: the title's own slots). +/// 20: tables timed (one in 16 of each thread); their nanoseconds: 21 +/// finding the slots (`HostHeap::dynamic`), 22 looking the views up and +/// making them, 23 making entries readable, 24 the title's own slots of +/// texture views (`HostHeap::texture_slot_tabled`, `HostHeap::mirror`). +/// 25: tables to make that found no slots. +#[cfg(feature = "diagnostics")] +static TABLES: [AtomicU64; 26] = [const { AtomicU64::new(0) }; 26]; + +#[cfg(feature = "diagnostics")] +thread_local! { + /// This thread's counts for [`TABLES`] not yet added to it, and its + /// calls of [`State::tables`] since they last were. + static TALLY: std::cell::RefCell<([u64; 26], u32)> = const { std::cell::RefCell::new(([0; 26], 0)) }; + /// This thread's tables to make, for timing one in 16. + static TABLES_MADE: std::cell::Cell<u32> = const { std::cell::Cell::new(0) }; +} + +/// Diagnostics: `n` more of count `at` of [`TABLES`], kept by the thread +/// until [`tally_done`] (no shared memory is written here). +#[cfg(feature = "diagnostics")] +fn tally(at: usize, n: u64) { + TALLY.with(|t| t.borrow_mut().0[at] += n); +} + +/// Diagnostics: a call of [`State::tables`] ends; every 64th of a thread +/// adds the thread's counts to [`TABLES`]. +#[cfg(feature = "diagnostics")] +fn tally_done() { + TALLY.with(|t| { + let t = &mut *t.borrow_mut(); + t.1 += 1; + if t.1 < 64 { + return; + } + t.1 = 0; + for (total, sum) in TABLES.iter().zip(t.0.iter_mut()) { + if *sum != 0 { + total.fetch_add(std::mem::take(sum), Ordering::Relaxed); + } + } + }); +} + +/// Diagnostics: the clock of a timed table: each lap goes to a count of +/// [`TABLES`]. Without a clock (15 tables of 16) a lap does nothing. +#[cfg(feature = "diagnostics")] +struct Lap(Option<std::time::Instant>); + +#[cfg(feature = "diagnostics")] +impl Lap { + /// The time since the lap before (or the start) goes to count `at`. + fn lap(&mut self, at: usize) { + if let Some(last) = &mut self.0 { + let now = std::time::Instant::now(); + tally(at, now.duration_since(*last).as_nanos() as u64); + *last = now; + } + } +} + +/// Diagnostics: slots of each of the four parts of [`seen`]. +#[cfg(feature = "diagnostics")] +const SEEN_SLOTS: usize = 1 << 19; + +/// Diagnostics: where the fingerprints of the tables made are kept +/// ([`table_asked`]): four parts of [`SEEN_SLOTS`] slots, each slot the +/// last fingerprint that fell on it. Made at the first table (16 MB). +#[cfg(feature = "diagnostics")] +fn seen() -> &'static [AtomicU64] { + static SEEN: std::sync::OnceLock<Box<[AtomicU64]>> = std::sync::OnceLock::new(); + SEEN.get_or_init(|| (0..4 * SEEN_SLOTS).map(|_| AtomicU64::new(0)).collect()) +} + +/// Diagnostics: counts the table of `n` records at `table` that a list in +/// its recording number `recording` (given one here if it has none) is +/// about to make, by where the same records were seen before ([`TABLES`] 2 +/// to 12), and starts the clock of one table in 16. +/// +/// A table is told by a fingerprint of its records +/// (`crate::descriptor::host::table_prints`), and a fingerprint is found +/// again only while no other has fallen on its slot since: the counts of +/// tables seen before are lower bounds. With 30,000 tables a frame on +/// 524,288 slots, about 6% of the tables last made a whole frame ago are +/// missed, fewer of the nearer ones. +#[cfg(feature = "diagnostics")] +fn table_asked(recording: &mut u64, table: u64, n: u32) -> Lap { + const K: u64 = 0x9e37_79b9_7f4a_7c15; + static NEXT: AtomicU64 = AtomicU64::new(1); + if *recording == 0 { + *recording = NEXT.fetch_add(1, Ordering::Relaxed); + } + let (whole, shape) = crate::descriptor::host::table_prints(table, n); + let seen = seen(); + let mix = |v: u64| { + let v = v.wrapping_mul(K); + v ^ (v >> 31) + }; + // In this recording of this list: the slot holds the fingerprint mixed + // with the recording's number. + let own = recording.wrapping_mul(0xff51_afd7_ed55_8ccd); + let in_list = |part: usize, print: u64| { + let tag = mix(print ^ own) | (1 << 63); + let slot = &seen[part * SEEN_SLOTS + (tag as usize & (SEEN_SLOTS - 1))]; + slot.swap(tag, Ordering::Relaxed) == tag + }; + // By any list: the slot holds the fingerprint's high half and the frame + // it was last seen in. The frames since then, if it is there. + let frame = crate::frame::current() as u32; + let frames_ago = |part: usize, print: u64| { + let tag = mix(print); + let slot = &seen[part * SEEN_SLOTS + (tag as usize & (SEEN_SLOTS - 1))]; + let was = slot.swap((tag & !0xffff_ffff) | u64::from(frame), Ordering::Relaxed); + (was != 0 && was >> 32 == tag >> 32).then(|| frame.wrapping_sub(was as u32)) + }; + // All four are noted for every table, whichever it is counted as. + let (list_whole, list_shape) = (in_list(0, whole), in_list(1, shape)); + let (ago_whole, ago_shape) = (frames_ago(2, whole), frames_ago(3, shape)); + let class = if list_whole { + Some(2) + } else if list_shape { + Some(6) + } else { + match (ago_whole, ago_shape) { + (Some(0), _) => Some(3), + (Some(1), _) => Some(4), + (Some(2..=8), _) => Some(5), + (_, Some(0..=8)) => Some(7), + _ => None, + } + }; + if let Some(class) = class { + tally(class, 1); + } + tally( + match n { + 1 => 8, + 2..=4 => 9, + 5..=16 => 10, + _ => 11, + }, + 1, + ); + tally(12, u64::from(n)); + let timed = TABLES_MADE.with(|made| { + made.set(made.get().wrapping_add(1)); + made.get().is_multiple_of(16) + }); + if timed { + tally(20, 1); + } + Lap(timed.then(std::time::Instant::now)) +} + +/// Diagnostics, with the line of the recording: the tables made afresh +/// ([`TABLES`]) and the host heap's locks (`crate::descriptor::host::LOCKS`), +/// per frame over `frames` frames. +#[cfg(feature = "diagnostics")] +pub(crate) fn tables_line(frames: f64) { + let frames = frames.max(1.0); + let t: Vec<f64> = TABLES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let l: Vec<f64> = crate::descriptor::host::LOCKS.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let (asked, found) = (t[0], t[1]); + let to_make = asked - found; + let (in_list, in_list_but_constants) = (t[2], t[6]); + let (this_frame, frame_before, older, but_constants) = (t[3], t[4], t[5], t[7]); + let new = to_make - t[2..8].iter().sum::<f64>(); + let (one, to_4, to_16, more, slots) = (t[8], t[9], t[10], t[11], t[12]); + let (constants, textures, others, nulls) = (t[13], t[14], t[15], t[16]); + let (readable_made, readable_found, entries) = (t[17], t[18], t[19]); + // One table in 16 was timed: the milliseconds of all of them, at that rate. + let timed = t[20]; + let all = |ns: f64| if timed > 0.0 { ns / timed * to_make / 1e6 } else { 0.0 }; + let (finding, views, readable, title) = (all(t[21]), all(t[22]), all(t[23]), all(t[24])); + let refused = t[25]; + tracing::info!( + "descriptor tables per frame ({frames:.0} frames; counts of a thread join after 64 of its binds): {asked:.0} asked of their list's \ + memory, {found:.0} found there; of the {to_make:.0} to make: {in_list:.0} hold the records of a table made earlier in the same \ + recording of their list at another address (a table cache within a list would serve these), {in_list_but_constants:.0} more \ + differ from one only in where their constants are; of the rest {this_frame:.0} hold the records of a table another list made \ + earlier in the frame, {frame_before:.0} of one made the frame before, {older:.0} of one made 2 to 8 frames before, \ + {but_constants:.0} more differ from one of those only in where their constants are; {new:.0} are new (the counts of repeats \ + are lower bounds); {refused:.0} found no slots; tables of 1 slot {one:.0}, of 2 to 4 {to_4:.0}, of 5 to 16 {to_16:.0}, of more \ + {more:.0}; {slots:.0} slots: {constants:.0} constant views, {textures:.0} texture views, {others:.0} other views, {nulls:.0} null; \ + entries made readable {readable_made:.0} in tables made, {readable_found:.0} in tables found, {entries:.0} entries of tables \ + not made afresh; one table in 16 timed ({timed:.0}), all of them at that rate: {finding:.1} ms finding slots, {views:.1} ms \ + looking up and making views, {readable:.1} ms making entries readable, {title:.1} ms on the title's own slots of textures" + ); + let (mirrors_other, mirrors_draw) = (l[0], l[1]); + let (changed_other, changed_draw) = (l[2], l[3]); + let (made_waits, made_waited) = (l[4], l[5] / 1e6); + // One call in 16 was timed: the mean of those, and all calls at that mean. + let mean = |ns: f64, n: f64| if n > 0.0 { ns / n } else { 0.0 }; + let (same_ns, changed_ns) = (mean(l[6], l[8]), mean(l[7], l[9])); + let changed = changed_other + changed_draw; + let same_ms = same_ns * (mirrors_other + mirrors_draw - changed) / 1e6; + let changed_ms = changed_ns * changed / 1e6; + let (keeps, kept_waits, kept_waited) = (l[10], l[11], l[12] / 1e6); + let (next_waits, next_waited) = (l[13], l[14] / 1e6); + tracing::info!( + "the host heap's locks per frame, all threads: the slots' lock (HostHeap::mirror) taken {mirrors_draw:.0} times for draws \ + ({changed_draw:.0} found the slot's record changed) and {mirrors_other:.0} times for writes and the pass over copied records \ + ({changed_other:.0} changed); {made_waits:.0} takes found it held and waited {made_waited:.2} ms in all (every wait timed); it \ + was held {same_ns:.0} ns a call where the slot was as it was and {changed_ns:.0} ns where it had changed (one call in 16 timed), \ + {same_ms:.1} ms and {changed_ms:.1} ms for all calls at those means; the lock of the resources slots hold (HostHeap::keep) \ + taken {keeps:.0} times, {kept_waits:.0} found it held and waited {kept_waited:.2} ms; the lock of the dynamic slots \ + (HostHeap::dynamic; its takes are the line above's tables asked): {next_waits:.0} found it held and waited {next_waited:.2} ms" + ); + let why: Vec<f64> = + crate::descriptor::host::DYNAMIC_WHY.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let low = crate::descriptor::host::DYNAMIC_LOW.swap(u32::MAX, Ordering::Relaxed); + let low = if low == u32::MAX { "no table asked".to_string() } else { format!("{low}") }; + tracing::info!( + "dynamic slots per frame, tables refused by cause: {:.0} asked more slots than were free (the ring was full), {:.0} had room \ + but a search for a table no longer had failed since the last release (not searched), {:.0} were searched for and no run of \ + free slots was that long (the free slots lay apart); {:.0} tables got a run lying across the place the search starts from \ + (missed by the search as it was before); the fewest free slots seen since the last line: {low} of {}", + why[0], + why[1], + why[2], + why[3], + crate::descriptor::host::DYNAMIC, + ); +} + +/// An experiment on the title's scissor rectangles (`VICTORY_SCISSOR_TEST=full`): +/// they are all widened to the whole target. The title's room at +/// the start of the prologue lost its walls in five runs of seven, and in +/// those runs the player's body and the world outside were cut by one +/// rectangle around the window (run 85, frame 2046): one run with this on +/// says whether the walls are drawn and cut away by such a rectangle, or +/// not drawn at all. Off by default: a rectangle the title sets is part of +/// its picture. +fn scissor_test() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_SCISSOR_TEST").as_deref() == Ok("full")) +} + +/// An experiment on mesh draws (`VICTORY_MESH_TEST`): 1 for `skip` (none +/// is issued), 2 for `scissor` (each runs its shaders but rasterises one +/// pixel), 0 otherwise. It tells a card hung by a mesh shader from one hung +/// by what the shader's triangles cover. +fn mesh_test() -> u8 { + static ON: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("VICTORY_MESH_TEST").as_deref() { + Ok("skip") => 1, + Ok("scissor") => 2, + _ => 0, + }) +} + +/// `VICTORY_MESH_TEST=keep:<hex digits>[:<hex digits>]`: only the mesh +/// draws whose mesh shader's hash ends in one of the first digits (and +/// whose digit before it is one of the second, if given) are issued: a +/// search for the shaders that stop the card. +fn mesh_kept(pipeline: usize) -> bool { + static KEEP: std::sync::OnceLock<Option<(String, String)>> = std::sync::OnceLock::new(); + let Some((last, before)) = KEEP.get_or_init(|| { + let value = std::env::var("VICTORY_MESH_TEST").ok()?; + let mut parts = value.strip_prefix("keep:")?.split(':'); + Some((parts.next()?.to_owned(), parts.next().unwrap_or("").to_owned())) + }) else { + return true; + }; + let Some(p) = crate::pipeline::host_pipeline(pipeline as This) else { + return true; + }; + let Some(at) = p.name.find("mesh ") else { + return true; + }; + let hash = p.name[at + 5..].as_bytes(); + if hash.len() < 16 { + return true; + } + last.as_bytes().contains(&hash[15]) && (before.is_empty() || before.as_bytes().contains(&hash[14])) +} + /// Draws recorded on the host GPU since the last frame line. static DRAWN: AtomicU64 = AtomicU64::new(0); @@ -134,6 +958,349 @@ pub(crate) fn take_frame() -> Vec<String> { pub(crate) fn take_dropped() -> u64 { DROPPED.swap(0, Ordering::Relaxed) } +/// A root SRV's dynamic slot in a list, and the host copy it shows. +type RootSlot = (u32, Option<std::sync::Arc<crate::shadow::Shadow>>); + +/// Buffer views of the heap whose slot showed another host buffer than +/// the copy the pass brought up to date for them, since the start +/// (diagnostics; for the memory line). It stays 0 while the pass and the +/// slots agree; with `VICTORY_VIEW_EXTENT=0` it counts the views that were +/// read stale. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0); +/// Passes over the view heap's buffer views for shaders that pick them by +/// index ([`State::heap_buffers`]), and the microseconds they took. +pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); +/// Per host heap, for [`State::heap_buffers`]: its passes so far, and the +/// host copy and range each slot's buffer view reads. (At the module's +/// level so that the marked pass can have this one start anew: +/// [`State::heap_buffers_marked`].) +type Ranges = std::collections::HashMap<u32, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)>; +/// (By the heap and its table: a new heap where one was has another table +/// and none of its ranges; cool_fox 18bdf79.) +type ByHeap = std::collections::HashMap<(usize, u64), (u64, Ranges)>; +static RANGES: std::sync::Mutex<Option<ByHeap>> = std::sync::Mutex::new(None); +/// Per host heap, for [`State::heap_buffers_marked`]: what the marked pass +/// keeps (`VICTORY_HEAP_PASS_MARKED`; nothing while that is unset). +type Marked = crate::heap_pass::Picked<std::sync::Arc<crate::shadow::Shadow>>; +static MARKED: std::sync::Mutex<Option<std::collections::HashMap<usize, Marked>>> = std::sync::Mutex::new(None); +pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0); +/// Where the pass over textures picked by index records its uploads: into +/// a list of the title's, or into lists of the thread that runs it ahead. +pub(crate) enum Into<'a> { + List(&'a HostList), + Ahead(&'a mut crate::heap_worker::Batch), +} + +/// Of [`HEAP_BUFFER_MICROS`], the microseconds of the pass over textures +/// picked by index that runs inside it (`heap_textures`), and the buffer +/// slots the pass over buffer views looked at; since the last frame line. +pub(crate) static HEAP_PASS_PARTS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +/// Textures brought up to date for shaders that pick them by index +/// ([`State::heap_textures`]), the bytes of their memory, and the slots +/// still waiting. +pub(crate) static HEAP_TEXTURES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_TEXTURE_BYTES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_TEXTURES_WAITING: AtomicU64 = AtomicU64::new(0); +/// Host copies made on a card without room, level by level with only their +/// small levels given memory (`resource::squeeze_room`), since the start. +pub(crate) static HEAP_TEXTURES_SQUEEZED: AtomicU64 = AtomicU64::new(0); +/// Passes that made no texture because the card had no room +/// (`crate::resource::room`), for the memory line. +pub(crate) static HEAP_TEXTURES_FULL: AtomicU64 = AtomicU64::new(0); + +/// Frames after a whole upload of a texture picked by index at which its +/// memory is looked at again, each counted from the look before. +const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400]; + +/// Frames between looks at an uploaded texture picked by index once +/// [`RECHECK_FRAMES`] is through (`VICTORY_HEAP_RECHECK_EVERY=<frames>`; unset +/// or 0: it is not looked at again, as before). The title streams a +/// texture's memory in and rewrites it long after its view was written: +/// runs 338-339 logged changes found at the schedule's last look, and what +/// changes later stays as it was on the card for the rest of the run (skin +/// that turns black or red). After RyanCase94's 920423a9. +fn recheck_every() -> u64 { + static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| { + let every = std::env::var("VICTORY_HEAP_RECHECK_EVERY").ok().and_then(|v| v.parse().ok()).unwrap_or(0); + if every > 0 { + tracing::info!("uploaded textures picked by index are looked at again every {every} frames (VICTORY_HEAP_RECHECK_EVERY)"); + } + every + }) +} + +/// Looks at uploaded textures picked by index that found the memory as it +/// was, and that found it changed (uploaded again), since the start. +pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + +/// Uploads of textures already on the card made while it had no room for +/// new ones, since the start. +pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0); + +/// Whether a pass over the textures picked by index on a full card holds +/// back the slots that need a new host copy (`VICTORY_FULL_CARD_PASS=0`: +/// no, as before: they stay due, each pass looks at the same ones again +/// and stops at the 257th). Held back, such a slot is looked at again +/// after about four seconds or as soon as the card has room, and the pass +/// goes on to the slots behind it: the ones whose host copy exists and +/// only wants bringing up to date, and the ones whose memory went (letting +/// their host copies go is what makes room). What is uploaded while the +/// card has room is the same either way. +fn full_card_pass() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FULL_CARD_PASS").is_none_or(|v| v != "0")) +} + +/// Whether a texture that has its host copy is still brought up to date +/// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`: +/// no). +fn reupload_when_full() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_REUPLOAD_WHEN_FULL").is_none_or(|v| v != "0")) +} + +/// Whether textures picked by index are looked at again after their upload +/// (`VICTORY_HEAP_RECHECK=0`: no). +fn heap_recheck() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_RECHECK").is_none_or(|v| v != "0")) +} +/// Passes over textures picked by index that ran behind a loading screen +/// with its big budget (`loading_draws`), since the start. +pub(crate) static HEAP_TEXTURES_LOADING: AtomicU64 = AtomicU64::new(0); + +/// A frame with fewer draws than this is a loading screen to the texture +/// pass (`VICTORY_LOADING_DRAWS`; 400 unless set, 0: none is). +fn loading_draws() -> u64 { + static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_LOADING_DRAWS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(400)) +} + +/// Try 6.3: frames of few draws in a row before the texture pass takes a +/// loading screen's budget (`VICTORY_LOADING_FRAMES`, 30 unless set). One +/// such frame was enough in 6.1 and 6.2, and the world has some (a cut, a +/// fade, a frame the title split): the report of 6.2 had passes of 750 ms +/// to 2 s in the world, at 1 to 2 frames a second, from the loading budget +/// of 1.2 s. A loading screen runs 25 frames a second with 1 to 17 draws. +fn loading_frames() -> u64 { + static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_LOADING_FRAMES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(30)) +} + +/// Try 6.3: the milliseconds of each loading-screen frame given to the +/// texture pass (`VICTORY_LOADING_MS`, 200 unless set; 0: the 12 ms of any +/// frame). A loading screen draws nothing but its own few draws, and the +/// pass that runs there is the early one (`State::early_textures`), whose +/// budget was 12 ms and 64 MB: the 6.1 loading budget never reached it, and +/// the 6.2 report entered the world after 94 s of loading screen with +/// 5,771 textures still due. +fn loading_ms() -> u64 { + static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_LOADING_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(200)) +} + +/// Frames in a row, up to the last one the texture pass saw, with fewer +/// draws than [`loading_draws`]. +static LOW_DRAW_FRAMES: AtomicU64 = AtomicU64::new(0); + +/// Whether a loading screen (or a menu, or a long fade) is up now: the +/// last [`loading_frames`] frames all had fewer draws than +/// [`loading_draws`]. The texture pass then has a big budget, and the +/// texture rush (`crate::tiles::rush_levels`) is off: textures made behind +/// a loading screen keep their detail. +pub(crate) fn loading_now() -> bool { + loading_draws() > 0 && LOW_DRAW_FRAMES.load(Ordering::Relaxed) >= loading_frames() +} + +/// Try 6.4, the console's curtain: the Series S version keeps its loading +/// screen up until what the first shot needs has streamed in. Here the +/// first world frames after a loading screen are that curtain: for up to +/// `VICTORY_JOIN_HOLD_MS` (10,000 unless set; 0: none) after the loading +/// screen went, while 300 or more textures picked by index are due, each +/// pass of the world gets 1.5 s and the loading screen's bytes. The first +/// seconds of the world run at under a frame a second, and the world then +/// stands there whole instead of filling in over the first minute (the +/// 6.2 report entered it with 5,771 textures due). +fn join_hold_ms() -> u64 { + static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_JOIN_HOLD_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(10_000)) +} + +/// Try 6.5, the streaming budget of big games: the texture pass of the +/// world takes at most this share, in percent, of the frame before +/// (`VICTORY_TEXTURE_FRAME_SHARE`, 35 unless set; 0: its own budget alone), +/// never under 60 ms. Engines stream within a fixed slice of each frame; +/// here the catch-up budget let one pass take 750 ms of a 900 ms frame in +/// the 6.2 report. Not behind a loading screen or the world's curtain. +fn frame_share() -> u64 { + static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_FRAME_SHARE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(35).min(100) + }) +} + +/// Try 6.6: the most the world's texture pass takes in any frame, in +/// milliseconds (`VICTORY_TEXTURE_PASS_MS`, 120), whatever its share +/// ([`frame_share`]) gives: smooth frames before fast streaming. +fn pass_most_ms() -> u64 { + static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_TEXTURE_PASS_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(120)) +} + +/// When the texture pass last saw a new frame (`crate::host::now_ms`), and +/// how long the frame before took by it. +static FRAME_AT: AtomicU64 = AtomicU64::new(0); +static LAST_FRAME_MS: AtomicU64 = AtomicU64::new(0); + +/// Try 6.5, a profiler's view of the texture pass (big games are made fast +/// by measuring first): microseconds since the start in each part of it — +/// the looks at uploaded textures, the memory queries, making host +/// textures, recording their uploads, the rest — and the passes measured. +pub(crate) static PASS_PARTS_US: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +pub(crate) static PASS_PARTS_PASSES: AtomicU64 = AtomicU64::new(0); + +/// Adds the time since the last mark to the part being timed +/// ([`PASS_PARTS_US`]); the last part when dropped. +struct PassParts { + at: std::time::Instant, + part: usize, +} + +impl PassParts { + fn new() -> Self { + PassParts { at: std::time::Instant::now(), part: 0 } + } + + fn mark(&mut self, part: usize) { + let now = std::time::Instant::now(); + PASS_PARTS_US[self.part].fetch_add(now.duration_since(self.at).as_micros() as u64, Ordering::Relaxed); + self.at = now; + self.part = part; + } +} + +impl Drop for PassParts { + fn drop(&mut self) { + PASS_PARTS_US[self.part].fetch_add(self.at.elapsed().as_micros() as u64, Ordering::Relaxed); + } +} + +/// Whether the last frame the texture pass saw was behind a loading screen +/// ([`loading_now`]), and when the last loading screen went +/// (`crate::host::now_ms`, never 0; 0: the curtain is not up). +static WAS_LOADING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static JOINED_AT: AtomicU64 = AtomicU64::new(0); +/// Passes made behind the curtain ([`join_hold_ms`]), since the start. +pub(crate) static JOIN_HOLD_PASSES: AtomicU64 = AtomicU64::new(0); + +/// Whether the curtain is up now with `due` slots due: ends (with a line) +/// when they are under 300 or its time is up. +fn join_hold(due: usize) -> bool { + let at = JOINED_AT.load(Ordering::Relaxed); + if at == 0 { + return false; + } + let took = crate::host::now_ms().saturating_sub(at); + if due >= 300 && took < join_hold_ms() { + return true; + } + if JOINED_AT.compare_exchange(at, 0, Ordering::Relaxed, Ordering::Relaxed).is_ok() { + tracing::info!( + ms = took, + due, + passes = JOIN_HOLD_PASSES.load(Ordering::Relaxed), + uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), + "the world's curtain is down: its textures were uploaded before it went on (VICTORY_JOIN_HOLD_MS)" + ); + } + false +} + +/// Try 6.4, the order of a pass's due slots +/// (`VICTORY_TEXTURE_PRIORITY=0`: as the queue hands them out): +/// 1. the slots the queue looks at again (memory that has arrived since, +/// and the looks after an upload): cheap, and the newest streaming; +/// 2. then the others in the queue's order (newest write and oldest +/// write in turns: what the title streamed for the shot now, and first +/// come first served so that nothing waits for ever), three small +/// textures (up to 256 KiB) to one large: a small one costs little and +/// gives a whole surface its colour, as a console's streamer brings in +/// the small levels of everything before the large levels of anything. +fn prioritize( + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + due: Vec<(u32, u64)>, +) -> Vec<(u32, u64)> { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_PRIORITY").is_none_or(|v| v != "0")) || due.len() < 2 { + return due; + } + let mut first = Vec::new(); + let mut small = std::collections::VecDeque::new(); + let mut large = std::collections::VecDeque::new(); + for (index, write) in due { + if host.texture_slot_checked(index).is_some() || host.texture_slot_mapped(index) > 0 { + first.push((index, write)); + continue; + } + let bytes = match heap.handle(index).and_then(crate::descriptor::view) { + Some(View::Placed(false, resource, _)) => crate::resource::placed_bytes(&resource).unwrap_or(0), + _ => 0, + }; + if bytes > 256 << 10 { + large.push_back((index, write)); + } else { + small.push_back((index, write)); + } + } + let mut order = first; + order.reserve(small.len() + large.len()); + while !small.is_empty() || !large.is_empty() { + for _ in 0..3 { + if let Some(next) = small.pop_front() { + order.push(next); + } + } + if let Some(next) = large.pop_front() { + order.push(next); + } + } + order +} + +/// Whether a texture picked by index that a look found changed after its +/// upload is looked at again in the next frame, not after +/// `RECHECK_FRAMES[0]` (`VICTORY_RECHECK_SOON=1`; off by default). A +/// texture whose bytes land in several pieces, or that the title keeps +/// writing, was shown four frames behind at each change. (The AMD sibling +/// repository's switch of that name, on by default there.) +fn recheck_soon() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RECHECK_SOON").is_some_and(|v| v == "1")) +} + +/// Uploads of textures picked by index looked at again in the next frame +/// because a look had found them changed ([`recheck_soon`]), since the +/// start. +pub(crate) static HEAP_TEXTURES_SOON: AtomicU64 = AtomicU64::new(0); + +/// Times a placed texture's slot was passed over because its memory is not +/// mapped. +pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0); +/// Slots the pass found up to date already: their texture is uploaded by +/// the draws that read it through a table (it has a staging buffer). +pub(crate) static HEAP_TEXTURES_TABLED: AtomicU64 = AtomicU64::new(0); +/// The queue of textures picked by index at the last pass +/// (`TextureQueue::census`): slots in it, due, waiting for their memory, +/// uploaded in part, and the frames the oldest due one has waited. +pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +/// Since the start: looks at a slot uploaded in part that found no more of +/// its memory mapped; uploads of textures not all mapped; and of those, +/// the ones whose first page was not there (asked by the first page alone, +/// as before, they counted as not there at all). +pub(crate) static HEAP_TEXTURES_PARTLY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; static DROPPED: AtomicU64 = AtomicU64::new(0); /// Marks the last traced draw as not run on the host. @@ -152,32 +1319,44 @@ pub(crate) fn dispatched() -> u64 { DISPATCHED.load(Ordering::Relaxed) } +/// What a render target or depth view of the host is made from: the host +/// texture, and [`crate::descriptor::RtvRecord::key`]. +type TargetKey = (usize, (usize, [u32; 7])); + /// The host address of a root view: its buffer's host copy, or for a /// constant buffer not 256-byte aligned there (the console needs 16) a /// copy in upload memory. -/// shortcut: a root view has no size; constant buffers are taken as 64 KiB, -/// other views as 1 MiB (both cut at their buffer's end). +/// shortcut: a root view has no size; constant buffers are taken as 64 KiB +/// (cut at their buffer's end), other views as all that is left of their +/// buffer. (They were taken as 1 MiB: 1,452 of the 2,021 mesh vertex +/// streams of a cutscene frame reach further, and what lay past the first +/// megabyte was never brought up to date - meshes without bodies, exploded +/// triangles. `VICTORY_ROOT_VIEW_MB` sets a limit again.) fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> { + static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("VICTORY_ROOT_VIEW_MB") + .ok() + .and_then(|v| v.parse::<u64>().ok()) + .map_or(u64::MAX, |mb| mb << 20) + }); let shadow = crate::shadow::find(address, 1)?; - let len = root_view_len(&shadow, address, srv); + let len = shadow + .left(address) + .min(if srv { limit } else { 1 << 16 }); let gpu = shadow.gpu(address); if srv || gpu % 256 == 0 { shadow.refresh(list, address, len); return Some(gpu); } + if crate::host::list_reuse() { + return list.fill_scratch(address as *const u8, len); + } let (gpu, to) = list.scratch(len)?; list.defer_fill(to, address as *const u8, len as usize); Some(gpu) } -/// The bytes of title memory at `address` a root view binds (and shaders -/// may read: see [`State::root_view_bytes`]). -fn root_view_len(shadow: &crate::shadow::Shadow, address: u64, srv: bool) -> u64 { - shadow - .left(address) - .min(if srv { 1 << 20 } else { 1 << 16 }) -} - macro_rules! once { ($($arg:tt)*) => {{ static ONCE: std::sync::Once = std::sync::Once::new(); @@ -185,6 +1364,73 @@ macro_rules! once { }}; } +/// Whether the stages of one draw share a table they both need made afresh +/// (`VICTORY_TABLE_STAGES=1`; off by default: each stage makes its own, as +/// before). `alt`: twenty seconds with, twenty without, in turn, each +/// change said in the log; `alt40`: forty and forty, so that a run can +/// carry this switch and another one in turn and tell the two apart (the +/// four pairs of states each come up for twenty seconds). +/// +/// A draw's stages read the same root tables, and each asked for slots up +/// to the last entry it reads itself. The count is in the key of +/// `State::fresh_tables`, so a mesh stage and a pixel stage that read one +/// table to different depths made it twice, in dynamic slots of its own +/// each time. With this both ask for the larger count ([`stage_spans`]), +/// the second finds the first one's table, and one table is made. +fn table_stages() -> bool { + /// 0 off, 1 on, 2 in turn every 20 s, 3 in turn every 40 s. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_TABLE_STAGES").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + Ok("alt40") => 3, + _ => 0, + }) { + 0 => false, + 1 => true, + mode => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let period = if mode == 3 { 40 } else { 20 }; + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / period) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "the stages of a draw share the tables they need made afresh from now (VICTORY_TABLE_STAGES=alt): {}", + if on { "ON" } else { "off, each stage makes its own as usual" } + ); + } + on + } + } +} + +/// For [`table_stages`]: per root table the stages of `p` read, the slots +/// it has up to the last entry read by a stage that also reads a constant +/// view in it (0: no stage does), and up to the last entry any stage reads: +/// (root parameter, with constants, all). +fn stage_spans(p: &HostPipeline) -> Vec<(u8, u32, u32)> { + let mut spans: Vec<(u8, u32, u32)> = Vec::new(); + for stage in &p.stages { + let t = stage.translated(); + let mut constant = [false; 256]; + for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind == ResourceType::Cbv) { + constant[usize::from(u.slot)] = true; + } + for u in t.used.iter().filter(|u| u.root == RootType::Table) { + let n = u.table_offset_dwords / 8 + 1; + let with = if constant[usize::from(u.slot)] { n } else { 0 }; + match spans.iter_mut().find(|s| s.0 == u.slot) { + Some(s) => { + s.1 = s.1.max(with); + s.2 = s.2.max(n); + } + None => spans.push((u.slot, with, n)), + } + } + } + spans +} + fn set(roots: &mut Vec<Root>, slot: u32, root: Root) { let slot = slot as usize; if roots.len() <= slot { @@ -194,40 +1440,23 @@ fn set(roots: &mut Vec<Root>, slot: u32, root: Root) { } impl State { - #[cfg(test)] - pub(crate) fn current_pipeline(&self) -> This { - self.pipeline as This - } - pub(crate) fn reset(&mut self, pipeline: This) { *self = State::default(); self.pipeline = pipeline as usize; } - /// `ClearState`: every binding back to its default as at a reset, with - /// `pipeline` set. The list keeps its dynamic descriptor slots: draws - /// recorded before the clear still read them. - pub(crate) fn clear(&mut self, pipeline: This) { - let dynamic = std::mem::take(&mut self.dynamic); - *self = State::default(); - self.dynamic = dynamic; - self.pipeline = pipeline as usize; - } - - /// Takes the dynamic descriptor slots held by this recording, so a - /// pending host list can keep them alive until its submission finishes. - pub(crate) fn take_dynamic(&mut self) -> Vec<(usize, u32, u32)> { - std::mem::take(&mut self.dynamic) - } - /// The title's topology; console-only ones become host lists (see /// [`crate::primitive`]). pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) { self.topology = topology; + self.topology_set = true; let host = match topology { RECTANGLES => 4, - t => crate::primitive::ExpandedTopology::from_console(t) - .map_or(t, crate::primitive::ExpandedTopology::host_topology), + TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => { + once!(topology, "console topology drawn as a triangle list"); + 4 + } + t => t, }; // SAFETY: an open list. unsafe { @@ -290,12 +1519,7 @@ impl State { } pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { - for slot in self - .vertex - .iter_mut() - .skip(start as usize) - .take(count as usize) - { + for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) { *slot = VertexView::default(); } } @@ -304,13 +1528,24 @@ impl State { self.index = view.copied().unwrap_or_default(); } - /// Render targets and depth, set on the host list at once. + /// Render targets and depth, set on the host list at once, unless it has + /// the same ones already: the title sets the same targets again and + /// again, each time a host view per target and a call of the driver + /// (25,662 times in a frame of another fork). `VICTORY_BIND_CACHE=0` + /// sets them every time. pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) { let Some(host) = crate::host::host() else { return; }; + self.target_handles.clear(); + self.target_handles.extend_from_slice(handles); + self.depth_handle = depth; + self.targets_set = true; self.targets.clear(); - let mut rtvs = Vec::new(); + // The formats of the host views, for the draws' pipelines. + let mut formats = [0; 9]; + let mut views = Vec::with_capacity(handles.len()); + let mut keys = Vec::with_capacity(handles.len()); for &h in handles { let Some(record) = crate::descriptor::rtv_record(h) else { once!( @@ -319,34 +1554,62 @@ impl State { ); continue; }; - if record.resource.is_null() { - // A typed null RTV discards writes without changing the output slot. - if let Some(desc) = record.desc() { - rtvs.push(host.rtv(None, Some(&desc))); - } - continue; - } let Some(texture) = crate::resource::host_resource(record.resource) else { + // A typed null view (or a target without a host copy) still + // takes its slot: left out, the next live target would move + // into it and the pixel shader's outputs reach the wrong + // targets. + // shortcut: a view without a description or a format has no + // null view to stand for it and is left out, as before. + let null = record + .desc() + .filter(|d| d.Format.0 != 0 && d.ViewDimension.0 != 0); + if let Some(desc) = null { + if views.len() < 8 { + formats[views.len()] = desc.Format.0 as u32; + } + views.push((None, Some(desc))); + keys.push((0, record.key())); + } continue; }; self.targets.push(record.resource as usize); #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); - rtvs.push(host.rtv(Some(texture), record.desc().as_ref())); + let desc = record.desc(); + if views.len() < 8 { + formats[views.len()] = bound_format(texture, desc.as_ref().map(|d| d.Format)); + } + views.push((Some(texture), desc)); + keys.push((texture.as_raw() as usize, record.key())); } - self.depth = None; - self.depth_sampled = false; + self.depth = 0; + self.depth_state = DEPTH_WRITE; let dsv = crate::descriptor::dsv_record(depth).and_then(|record| { let texture = crate::resource::host_resource(record.resource)?; + self.depth = record.resource as usize; let desc = record.depth_desc(); - self.depth = Some(DepthTarget { - resource: record.resource as usize, - state: depth_state(texture, desc.as_ref()), - }); + self.depth_state = depth_state(texture, desc.as_ref()); + formats[8] = bound_format(texture, desc.as_ref().map(|d| d.Format)); + if crate::resource::depth_and_unordered(record.resource) { + crate::resource::DEPTH_UNORDERED[1].fetch_add(1, Ordering::Relaxed); + } #[cfg(feature = "diagnostics")] crate::capture::note_target(record.resource); - Some(host.dsv(texture, desc.as_ref())) + Some((texture, record)) }); + // (Before the cache: the draws' pipelines follow the formats bound.) + self.target_formats = formats; + let now = (keys, dsv.as_ref().map(|(texture, record)| (texture.as_raw() as usize, record.key()))); + static CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if *CACHE.get_or_init(|| std::env::var("VICTORY_BIND_CACHE").map_or(true, |v| v != "0")) + && self.host_targets.as_ref() == Some(&now) + { + return; + } + self.host_targets = Some(now); + let rtvs: Vec<_> = views.iter().map(|(texture, desc)| host.rtv(*texture, desc.as_ref())).collect(); + let dsv = dsv.map(|(texture, record)| host.dsv(texture, record.depth_desc().as_ref())); // SAFETY: an open list; the views were just made. unsafe { list.list.OMSetRenderTargets( @@ -358,27 +1621,169 @@ impl State { }; } - /// The user-data value of a root argument, as translated shaders read - /// it: a table's byte offset in its heap, a constant's value. - fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 { - match (self.roots_ref(compute).get(usize::from(slot)), root) { - (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) { - Some(heap) => (handle - heap.start) as u32, - None => { - once!( - handle = format_args!("{handle:#x}"), - "descriptor table outside the bound heaps" - ); - 0 - } - }, - (Some(Root::Constants(c)), RootType::Constants) => { - c.get(dword as usize).copied().unwrap_or(0) - } - _ => { - once!( - slot, - ?root, + /// Viewports, scissors, the blend factor and the stencil reference: set + /// on the host list at once, and kept for [`State::replay`]. + pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) { + self.viewports.clear(); + self.viewports.extend_from_slice(viewports); + crate::draw::viewports(list, viewports); + } + + pub(crate) fn set_scissors(&mut self, list: &HostList, rects: &[RECT]) { + self.scissors.clear(); + self.scissors.extend_from_slice(rects); + if scissor_test() { + // The experiment: every rectangle the title sets is widened to + // the largest target there is, so nothing is cut by one. What + // the listing shows (`op_text`) stays the title's own. + let full = RECT { + left: 0, + top: 0, + right: 16384, + bottom: 16384, + }; + crate::draw::scissors(list, &vec![full; rects.len()]); + return; + } + crate::draw::scissors(list, rects); + } + + pub(crate) fn set_blend_factor(&mut self, list: &HostList, factor: Option<&[f32; 4]>) { + self.blend = factor.copied(); + crate::draw::blend_factor(list, factor); + } + + pub(crate) fn set_stencil_ref(&mut self, list: &HostList, reference: u32) { + self.stencil = Some(reference); + crate::draw::stencil_ref(list, reference); + } + + pub(crate) fn set_depth_bounds(&mut self, list: &HostList, min: f32, max: f32) { + self.depth_bounds = Some([min, max]); + crate::draw::depth_bounds(list, min, max); + } + + /// `list` is a new host list that continues the title's list (it was + /// cut at a wait for a memory value, `crate::list::cut`): a new host + /// list has nothing set, so what the title set so far is set again. + /// The pipeline, the root signatures and the heaps are set by the next + /// draw or dispatch (`bind`, which is told here that the host list has + /// none); root arguments, vertex and index buffers are set by every + /// draw anyway. The dynamic descriptor slots and the tables made in + /// them stay: the parts before the cut have not run yet, and they are + /// given back when the title's list is reset. + /// shortcut: the render target views are made again from the handles' + /// descriptors as they are now, not as they were when the title set + /// the targets (a descriptor rewritten in between names another view). + pub(crate) fn replay(&mut self, list: &HostList) { + self.host_pipeline = 0; + self.host_roots = [0; 2]; + self.host_heaps = [0; 2]; + if self.topology_set { + self.set_topology(list, self.topology); + } + self.host_targets = None; + if self.targets_set { + let handles = std::mem::take(&mut self.target_handles); + self.set_targets(list, &handles, self.depth_handle); + } + if !self.viewports.is_empty() { + crate::draw::viewports(list, &self.viewports); + } + if !self.scissors.is_empty() { + let rects = std::mem::take(&mut self.scissors); + self.set_scissors(list, &rects); + } + if let Some(factor) = self.blend { + crate::draw::blend_factor(list, Some(&factor)); + } + if let Some(reference) = self.stencil { + crate::draw::stencil_ref(list, reference); + } + if let Some([min, max]) = self.depth_bounds { + crate::draw::depth_bounds(list, min, max); + } + } + + /// After a dispatch of `p`: the least indirect light, if it is the + /// program that resolves that (ported from Belobug/VIctory-Belobug-AMD, + /// beloooo). Whether it recorded anything: the compute pipeline, root + /// signature and heaps on the host list are then the ambient pass's. + fn ambient(&self, list: &HostList, p: &HostPipeline) -> bool { + let Some(stage) = p.stages.first().filter(|s| s.shader.resolves_light) else { + return false; + }; + let view = |kind: ResourceType, (slot, offset): (u8, u32)| { + let u = stage.translated().used.iter().find(|u| { + u.kind == kind + && u.root == RootType::Table + && (u.slot, u.table_offset_dwords) == (slot, offset) + })?; + let Some(Root::Table(table)) = self.roots_ref(true).get(usize::from(u.slot)) else { + return None; + }; + crate::descriptor::view(table + u64::from(u.table_offset_dwords) * 4) + }; + let light = match view(ResourceType::Uav, crate::ambient::LIGHT) { + Some(View::Unordered(r, ..)) => r, + _ => 0, + }; + if light == 0 { + once!("no ambient light: other tables"); + return false; + } + let depth = match view(ResourceType::Srv, crate::ambient::DEPTH) { + Some(View::Shader(r, _)) => Some(r as This), + _ => None, + }; + // Try 6.6: what else the resolve reads, for the lit scene whose + // brightness the light follows (`crate::ambient::follow`). + let roots = self.roots_ref(true); + let scenes: Vec<This> = stage + .translated() + .used + .iter() + .filter(|u| { + u.kind == ResourceType::Srv + && u.root == RootType::Table + && (u.slot, u.table_offset_dwords) != crate::ambient::DEPTH + }) + .filter_map(|u| { + let Some(Root::Table(table)) = roots.get(usize::from(u.slot)) else { + return None; + }; + match crate::descriptor::view(table + u64::from(u.table_offset_dwords) * 4) { + Some(View::Shader(r, _)) if r != 0 => Some(r as This), + _ => None, + } + }) + .collect(); + crate::ambient::raise(list, light as This, depth, &scenes) + } + + /// The user-data value of a root argument, as translated shaders read + /// it: a table's byte offset in its heap, a constant's value. + fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 { + match (self.roots_ref(compute).get(usize::from(slot)), root) { + (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) { + Some(heap) => (handle - heap.start) as u32, + None => { + once!( + handle = format_args!("{handle:#x}"), + "descriptor table outside the bound heaps" + ); + 0 + } + }, + (Some(Root::Constants(c)), RootType::Constants) => { + c.get(dword as usize).copied().unwrap_or(0) + } + // The host's own ([`Self::host_word`]): no root argument. + (_, RootType::Other(_)) => 0, + _ => { + once!( + slot, + ?root, "a shader reads a root argument the title did not set" ); 0 @@ -386,19 +1791,79 @@ impl State { } } - /// The bytes root view `slot` holds from its start, as [`root_view`] - /// binds it. Shaders check their accesses against it: a root view has - /// no bounds on the host, and an access past the memory it maps is a - /// GPU page fault, which some hosts stall on until the driver resets - /// the device. 0 for a root view the title did not set. - fn root_view_bytes(&self, compute: bool, slot: u8, srv: bool) -> u32 { - let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { - return 0; + /// A user-data dword the host computes for a translated shader + /// (`victory_shader::emit::USER_MEMORY_BASE`, `USER_VIEW_ADDRESS`). + fn host_word( + &self, + compute: bool, + kind: u32, + slot: u8, + dword: u32, + memory: Option<&crate::memory::Ready>, + ) -> u32 { + use victory_shader::emit::{ + USER_DISPATCH_SPREAD, USER_DISPATCH_THREADS, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, }; - let Some(shadow) = crate::shadow::find(address, 1) else { + if kind == USER_DISPATCH_SPREAD { + return self.dispatch_spread[usize::from(dword != 0)]; + } + if kind == USER_DISPATCH_THREADS { + return self.dispatch_threads.get(dword as usize).copied().unwrap_or(0); + } + if kind == USER_MEMORY_BASE { + return memory.map_or(0, |m| m.base); + } + if kind == USER_VIEW_BIAS { + // The view begins on 16 bytes of the copy the address finds + // (`root_uav`, `root_srv_table`). + // shortcut: found again here, not taken from the list's slot. + return match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::View(address)) => crate::shadow::find(address, 1).map_or(0, |s| { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + ((s.gpu(address) - base) & 15) as u32 + }), + _ => 0, + }; + } + if kind != USER_VIEW_ADDRESS && kind != USER_VIEW_ADDRESS + 1 { + once!(kind, "a shader reads a host value this build does not know"); return 0; + } + // The title address of the buffer view at that dword of the table. + let address = match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4) + .and_then(|view| crate::descriptor::host::buffer_range(&view)) + .map_or(0, |range| range.0), + _ => 0, }; - u32::try_from(root_view_len(&shadow, address, srv)).unwrap_or(u32::MAX) + if address == 0 { + once!(slot, dword, "a shader takes the address of a buffer view that is not there: it reads 0"); + } + if kind == USER_VIEW_ADDRESS { + address as u32 + } else { + (address >> 32) as u32 + } + } + + /// For a shader that reads title memory by address + /// ([`crate::memory`]): its directory, fault notes and view slots, + /// with the pages of the root views the list has set made ready. + fn memory_ready(&self, list: &HostList, compute: bool, writes: bool) -> Option<crate::memory::Ready> { + let heap = match self.heaps[0] { + 0 => None, + h => crate::descriptor::heap(h as This).host(), + }?; + let (mut addresses, mut constants) = (Vec::new(), Vec::new()); + for root in self.roots_ref(compute) { + match root { + Root::View(address) => addresses.push(*address), + Root::Constants(values) => constants.extend_from_slice(values), + _ => {} + } + } + crate::memory::ready(list, heap, &addresses, &constants, writes) } /// The bound heap holding `handle`. @@ -422,17 +1887,20 @@ impl State { if crate::pipeline::is_skipped(self.pipeline as This) { return false; } - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + let Some(p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) else { return false; }; if p.compute || p.mesh != mesh { - once!( - mesh, - "a draw or mesh dispatch with another kind of pipeline" - ); + once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); + return false; + } + if p.rects && self.topology != RECTANGLES { + // Its geometry stage would turn each triangle into a rectangle. + once!("a rectangle pipeline drawn with another topology"); + } + if !self.bind(list, p, false) { return false; } - self.bind(list, p, false); let l = &list.list; // Vertex buffers the input layout reads. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32]; @@ -445,7 +1913,7 @@ impl State { if v.address == 0 || v.size == 0 { continue; } - let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { continue; }; shadow.refresh(list, v.address, u64::from(v.size)); @@ -463,7 +1931,7 @@ impl State { } if indexed { let v = self.index; - let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { return false; }; shadow.refresh(list, v.address, u64::from(v.size)); @@ -479,31 +1947,43 @@ impl State { for &t in &self.targets { crate::list::ensure_state(list, t as This, RENDER_TARGET); } - self.ensure_depth_state(list); - true - } - - fn ensure_depth_state(&self, list: &HostList) { - if let Some(depth) = self.depth { - let state = depth.state - | if self.depth_sampled { - SHADER_RESOURCE + if self.depth != 0 { + // A depth texture shaders also write: what they wrote, first. + list.twin_use(self.depth as This, false, true); + // A view that writes neither plane keeps the texture readable: + // the depth read state, together with the shader read states + // if this draw's shaders read the same texture (the write state + // put it out of the state those views need, and a move to it + // and back for every such draw). + let state = if self.depth_state == DEPTH_READ { + let (tested, read) = TESTED_DEPTH.get(); + if read && tested == self.depth { + DEPTH_READ | SHADER_RESOURCE } else { - 0 - }; - crate::list::ensure_state(list, depth.resource as This, state); + DEPTH_READ + } + } else { + DEPTH_WRITE + }; + crate::list::ensure_state(list, self.depth as This, state); } + true } - fn read_only_depth(&self, compute: bool) -> Option<usize> { - self.depth - .filter(|depth| !compute && depth.state == DEPTH_READ) - .map(|depth| depth.resource) - } - - /// Binds the title's shader-visible heaps when they change. - fn bind_heaps(&mut self, list: &HostList) { + /// A descriptor a shader reads through a table: its host slot made if + /// it changed, constant data copied, textures made readable. + /// What draws and dispatches share: heaps, our root signature, the + /// pipeline, and per stage the user data, root views and the + /// descriptors its tables hold. + /// False if the draw or dispatch must not run: a root SRV it reads + /// could not be given a view. + pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { let l = &list.list; + // Textures picked by index, before anything asks for them. + self.early_textures(list, p, compute); + if crate::host::walls_trace() { + self.walls_census(p, compute); + } // Heaps first: a root signature with directly indexed heaps must be // set after them. if self.host_heaps != self.heaps { @@ -520,75 +2000,14 @@ impl State { self.host_heaps = self.heaps; self.host_roots = [0; 2]; } - } - - /// Records a clear of a resource-backed texture UAV in the bound heap. - pub(crate) fn clear_texture_uav( - &mut self, - list: &HostList, - gpu: u64, - cpu: u64, - resource: This, - value: UavClear, - rects: &[RECT], - ) { - let heap_id = self.heaps[0]; - if heap_id == 0 { - return; - } - let heap = crate::descriptor::heap(heap_id as This); - if heap.index(gpu).is_none() { - return; - } - let ( - Some(View::Unordered(cpu_resource, _, words)), - Some(View::Unordered(gpu_resource, _, _)), - ) = (crate::descriptor::view(cpu), crate::descriptor::view(gpu)) - else { - return; - }; - if cpu_resource != resource as usize || gpu_resource != cpu_resource { - return; - } - let (Some(texture), Some(native_heap)) = - (crate::resource::host_resource(resource), heap.host()) - else { - return; - }; - let Some((slot, gpu, cpu)) = native_heap.clear_texture_uav(list, texture, words.as_ref()) - else { - return; + // The depth target a draw only tests, for the views of it that the + // draw's shaders read (`readable`). + let tested = if !compute && self.depth_state == DEPTH_READ { + self.depth + } else { + 0 }; - self.dynamic.push((heap_id, slot, 1)); - self.bind_heaps(list); - crate::list::ensure_state( - list, - resource, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32, - ); - // SAFETY: matched views, a live texture in UAV state, and the - // shader-visible descriptor's heap is bound on this list. - unsafe { - match value { - UavClear::Uint(values) => { - list.list - .ClearUnorderedAccessViewUint(gpu, cpu, texture, &values, rects); - } - UavClear::Float(values) => { - list.list - .ClearUnorderedAccessViewFloat(gpu, cpu, texture, &values, rects); - } - } - } - } - - /// What draws and dispatches share: heaps, our root signature, the - /// pipeline, and per stage the user data, root views and the - /// descriptors its tables hold. - fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) { - self.depth_sampled = false; - let l = &list.list; - self.bind_heaps(list); + TESTED_DEPTH.set((tested, false)); let root = p.root.as_raw() as usize; if self.host_roots[usize::from(compute)] != root { // SAFETY: an open list and a live root signature. @@ -609,24 +2028,56 @@ impl State { self.host_pipeline = p.pso.as_raw() as usize; list.used_pipeline(&p.name); // The title may release the pipeline before it submits the list. - list.keep(&p.pso); - list.keep(&p.root); + // (`VICTORY_LIST_REUSE`: kept at the list's first bind of it only.) + if !crate::host::list_reuse() || list.first_bind(p.pso.as_raw() as usize) { + list.keep(&p.pso); + list.keep(&p.root); + } } + // With `table_stages`: what the stages of this draw read of each + // table, and the tables its earlier stages made afresh (address, + // slots). + let spans = if table_stages() { stage_spans(p) } else { Vec::new() }; + let mut staged: Vec<(u64, u32)> = Vec::new(); for stage in &p.stages { let t = stage.translated(); - let made = self.tables(list, &t.used, compute); + STORES.set(t.stores); + let made = self.tables(list, &t.used, &t.host.root_indexed_views, &t.host.half_views, compute, &spans, &mut staged); + STORES.set(true); + if made.iter().any(|m| m.1 == u32::MAX) { + once!("a draw whose descriptor table found no free slots is dropped"); + // Which draws those are, in the frame line's list of drops. + #[cfg(feature = "diagnostics")] + crate::pipeline::note_why(format!("no free dynamic slots for a table of {}", p.name)); + return false; + } + // What the shader stores through root views and raw addresses is + // copied back into title memory afterwards. + let writes = (t.stores || !write_skip()) + && !crate::pipeline::builder_quarantined(self.pipeline as This); + // Title memory by address: what the shader finds it by. + let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { + let Some(ready) = self.memory_ready(list, compute, writes) else { + once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); + return false; + }; + Some(ready) + } else { + None + }; if let Some((param, dwords)) = stage.user_data { let mut values = vec![0u32; dwords as usize]; for u in &t.host.user_data { + if let RootType::Other(kind) = u.root { + values[u.index as usize] = + self.host_word(compute, kind, u.slot, u.dword, memory.as_ref()); + continue; + } let fresh = made .iter() .find(|m| m.0 == u.slot && u.root == RootType::Table); values[u.index as usize] = match fresh { Some(&(_, offset)) => offset, - None if u.root == RootType::Descriptor => { - let srv = stage.root_srvs.iter().any(|r| r.0 == u.slot); - self.root_view_bytes(compute, u.slot, srv) - } None => self.user_value(compute, u.slot, u.root, u.dword), }; } @@ -662,20 +2113,89 @@ impl State { } for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { for &(slot, param) in views { - // Root SRVs are bounded one-view tables (see the host - // root signature). - if srv { - self.bind_root_srv(list, compute, slot, param); + if srv && slot == victory_shader::emit::SLOT_MEMORY { + // Ours: the directory of title memory by address. + if let Some(m) = &memory { + // SAFETY: an open list; the directory lives as + // long as the process and the list holds it. + unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, m.directory); + } else { + l.SetGraphicsRootShaderResourceView(param, m.directory); + } + } + } + continue; + } + if srv && slot == victory_shader::emit::SLOT_STRIDES { + // Ours, not the title's: the shader picks buffers + // from the view heap by an index it computes. + match self.heap_buffers(list) { + // SAFETY: an open list; the table lives as long + // as the heap the list holds. + Some(gpu) => unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + }, + None => once!("a shader picks buffers from a view heap that is not set"), + } continue; } - let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) + if srv && slot == victory_shader::emit::SLOT_TABLE_STRIDES { + // Ours: the kinds of the views of the shader's tables + // (its d16 typed accesses of integer views). + match self.heap_strides(list) { + // SAFETY: an open list; the table lives as long + // as the heap the list holds. + Some(gpu) => unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + }, + None => once!("a shader looks at its tables' view kinds without a view heap set"), + } + continue; + } + let tabled = srv && crate::pipeline::host::bounded_root_srvs(); + let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { once!(slot, "a shader reads a root view the title did not set"); + // A table left unset is undefined: a null view. + if tabled && !self.root_srv_table(list, None, param, compute, false) { + return false; + } continue; }; - let Some(gpu) = root_view(list, *address, srv) else { + // The shader adds the bytes a raw view begins early by. + let biased = srv + && t.host.user_data.iter().any(|u| { + u.slot == slot + && u.root == RootType::Other(victory_shader::emit::USER_VIEW_BIAS) + }); + if tabled { + if !self.root_srv_table(list, Some(address), param, compute, biased) { + return false; + } + continue; + } + let Some(mut gpu) = root_view(list, address, srv) else { continue; }; + if biased { + gpu -= u64::from(self.host_word( + compute, + victory_shader::emit::USER_VIEW_BIAS, + slot, + 0, + None, + )); + } // SAFETY: an open list; the address is in live memory. unsafe { match (compute, srv) { @@ -687,160 +2207,2049 @@ impl State { } } } + for &(slot, param) in &stage.root_uavs { + if slot == victory_shader::emit::SLOT_FAULTS { + // Ours: where shaders note the pages they found empty. + if let Some(m) = &memory { + // SAFETY: an open list; the buffer lives as long as + // the process and the list holds it. + unsafe { + if compute { + l.SetComputeRootUnorderedAccessView(param, m.faults); + } else { + l.SetGraphicsRootUnorderedAccessView(param, m.faults); + } + } + } + continue; + } + let address = match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::View(address)) => Some(address), + _ => { + once!(slot, "a shader writes through a root view the title did not set"); + None + } + }; + if !self.root_uav(list, address, param, compute, writes) { + return false; + } + } } + // Depth textures it writes through unordered access: their colour + // twins hold what they lack from here on. + list.twins_written(); + true } - /// Binds the title's root SRV `slot` as the one-view table `param` (see - /// the host root signature): a raw view of the rest of the title - /// buffer's host copy, in a dynamic slot of the bound view heap, so - /// reads past the copy return zeros rather than fault. Zeros (our null - /// buffer) if the title set none or it lies outside every buffer. - fn bind_root_srv(&mut self, list: &HostList, compute: bool, slot: u8, param: u32) { - let l = &list.list; - let heap = self.heaps[0]; - if heap == 0 { - once!("a root SRV with no view heap bound: left unset"); - return; - } - let title_heap = crate::descriptor::heap(heap as This); - let Some(host) = title_heap.host() else { return }; - let address = match self.roots_ref(compute).get(usize::from(slot)) { - Some(Root::View(address)) => *address, - _ => 0, + /// Binds a root UAV: a raw unordered access view of the title buffer's + /// host copy from `address` on, as a one-view table (a null view + /// without an address, without a host copy shaders can write, or at an + /// address not on 16 bytes), or as a root descriptor with + /// `VICTORY_ROOT_SRV_DIRECT=1` (the dispatch is dropped then if there + /// is nothing to bind). With `writes`, what the shader stored is copied + /// back into title memory when the list has run. False if the draw + /// must be dropped. + /// shortcut: a root view has no size: the view, the refresh and the + /// copy back cover all that is left of the title's buffer + /// (`VICTORY_ROOT_UAV_MB` sets a limit for all three). + fn root_uav( + &mut self, + list: &HostList, + address: Option<u64>, + param: u32, + compute: bool, + writes: bool, + ) -> bool { + const UNORDERED: i32 = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0; + static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("VICTORY_ROOT_UAV_MB") + .ok() + .and_then(|v| v.parse::<u64>().ok()) + .map_or(u64::MAX, |mb| mb << 20) + }); + let find = |a: u64| { + let s = crate::shadow::find(a, 1)?; + // SAFETY: a live buffer. + let flags = unsafe { s.buffer.GetDesc() }.Flags; + if flags.0 & UNORDERED == 0 { + once!("a root UAV of a buffer whose host copy shaders cannot write"); + return None; + } + Some(s) }; - let shadow = crate::shadow::find(address, 1).filter(|_| address != 0).map(|s| (s, address)); - // The same buffer again in this list: its slot, refreshed again. - if let Some(&index) = self.root_srv_slots.get(&(heap, address)) { - if let Some((shadow, address)) = &shadow { - shadow.refresh(list, *address, shadow.left(*address).min(1 << 20)); + let ready = |a: u64, s: &std::sync::Arc<crate::shadow::Shadow>| { + let len = s.left(a).min(limit); + s.refresh(list, a, len); + if writes { + s.gpu_writes(list, a, len); } - let table = host.gpu_handle(index); - // SAFETY: an open list; the slot is held by this list. + }; + if !crate::pipeline::host::bounded_root_srvs() { + let Some((a, s)) = address.and_then(|a| Some((a, find(a)?))) else { + once!("a root UAV with nothing to bind: the draw is dropped"); + return false; + }; + ready(a, &s); + // From the 16 bytes below: the shader adds the rest. + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let gpu = base + ((s.gpu(a) - base) & !15); + // SAFETY: an open list; the address is in a live buffer. unsafe { if compute { - l.SetComputeRootDescriptorTable(param, table); + list.list.SetComputeRootUnorderedAccessView(param, gpu); } else { - l.SetGraphicsRootDescriptorTable(param, table); + list.list.SetGraphicsRootUnorderedAccessView(param, gpu); } } - return; + return true; } - let Some(index) = host.dynamic(1) else { - once!("no free dynamic slot for a root SRV: left unset"); - return; + let heap = match self.heaps[0] { + 0 => None, + h => Some(crate::descriptor::heap(h as This)), + }; + let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else { + once!("a root UAV without a bound view heap: the draw is dropped"); + return false; + }; + let key = (std::ptr::from_ref(heap) as usize, address.unwrap_or(0)); + let (index, shadow) = match self.root_uav_slots.get(&key) { + Some((index, shadow)) => (*index, address.zip(shadow.clone())), + None => { + let shadow = address.and_then(|a| find(a).map(|s| (a, s))); + let Some(index) = host.dynamic(1).or_else(|| { + // out of slots: settle what has run, its slots come back + // (codec_d, cool_fox f4b48ad) + crate::host::settle_for_fence(); + host.dynamic(1) + }) else { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_why("no free dynamic slot for the one-view table of a root view".to_owned()); + return false; + }; + self.dynamic.push((key.0, host.id(), index, 1)); + if let Some((a, s)) = &shadow { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let offset = s.gpu(*a) - base; + // Raw views start on 16 bytes: from the 16 bytes + // below, and the shader adds the rest to its offsets + // (`victory_shader::emit::USER_VIEW_BIAS`). (An address + // not on 16 bytes got a null view at first: the + // builder's counters are at such addresses.) + let bias = offset & 15; + host.raw_uav_at(index, &s.buffer, offset - bias, s.left(*a).min(limit) + bias); + } + if shadow.is_none() { + host.null_raw_uav_at(index); + } + self.root_uav_slots + .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone()))); + (index, shadow) + } }; - self.dynamic.push((heap, index, 1)); - self.root_srv_slots.insert((heap, address), index); - match shadow { - Some((shadow, address)) => { - let len = shadow.left(address); - shadow.refresh(list, address, len.min(1 << 20)); - host.raw_srv_at(index, &shadow.buffer, shadow.offset(address), len); + if let Some((a, s)) = &shadow { + ready(*a, s); + } + let handle = host.gpu_handle(index); + // SAFETY: an open list; the slot is in the bound view heap. + unsafe { + if compute { + list.list.SetComputeRootDescriptorTable(param, handle); + } else { + list.list.SetGraphicsRootDescriptorTable(param, handle); } + } + true + } + + /// Binds a root SRV as a one-view table + /// ([`crate::pipeline::host::bounded_root_srvs`]): a raw view of the + /// title buffer's host copy from `address` to the copy's end, or a null + /// view (no address, no host copy, or an address not on 16 bytes). One + /// dynamic slot per address per list, given back with the list's + /// others. False if no slot could be had or no view heap is bound. + fn root_srv_table( + &mut self, + list: &HostList, + address: Option<u64>, + param: u32, + compute: bool, + biased: bool, + ) -> bool { + let heap = match self.heaps[0] { + 0 => None, + h => Some(crate::descriptor::heap(h as This)), + }; + let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else { + once!("a root SRV without a bound view heap: the draw is dropped"); + return false; + }; + // A view that begins early is another view than one that does not + // (title addresses stay below bit 63). + let key = ( + std::ptr::from_ref(heap) as usize, + address.unwrap_or(0) | u64::from(biased) << 63, + ); + let (index, shadow) = match self.root_srv_slots.get(&key) { + Some((index, shadow)) => (*index, address.zip(shadow.clone())), None => { - once!(slot, "a root SRV the title did not set, or outside every buffer: reads zeros"); - host.make_null(index); + let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s))); + let Some(index) = host.dynamic(1).or_else(|| { + // out of slots: settle what has run, its slots come back + // (codec_d, cool_fox f4b48ad) + crate::host::settle_for_fence(); + host.dynamic(1) + }) else { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_why("no free dynamic slot for the one-view table of a root view".to_owned()); + return false; + }; + self.dynamic.push((key.0, host.id(), index, 1)); + self.root_srv_slots + .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone()))); + match &shadow { + Some((a, s)) => { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let offset = s.gpu(*a) - base; + if biased { + // From the 16 bytes below; the shader adds the + // rest (`victory_shader::emit::USER_VIEW_BIAS`). + let bias = offset & 15; + host.raw_at(index, &s.buffer, offset - bias, s.left(*a) + bias); + } else if offset.is_multiple_of(16) { + host.raw_at(index, &s.buffer, offset, s.left(*a)); + } else { + // Raw views start on 16 bytes; one from the + // aligned start would shift every read. + once!( + address = format_args!("{a:#x}"), + "a root SRV not on 16 bytes reads zeros" + ); + host.null_raw_at(index); + } + } + None => host.null_raw_at(index), + } + (index, shadow) } + }; + // As for root descriptors (`root_view`): all that is left of the + // buffer is brought up to date. The first 1 MiB only left what lay + // past it stale (most mesh vertex streams reach further). + if let Some((a, s)) = &shadow { + s.refresh(list, *a, s.left(*a)); } - let table = host.gpu_handle(index); - // SAFETY: an open list; the slot is in the bound heap and held by - // this list until it is reset. + let handle = host.gpu_handle(index); + // SAFETY: an open list; the slot is in the bound view heap. unsafe { if compute { - l.SetComputeRootDescriptorTable(param, table); + list.list.SetComputeRootDescriptorTable(param, handle); } else { - l.SetGraphicsRootDescriptorTable(param, table); + list.list.SetGraphicsRootDescriptorTable(param, handle); } } + true } - /// Runs a dispatch on the host. - pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { - #[cfg(feature = "diagnostics")] - if crate::pipeline::is_skipped(self.pipeline as This) { - DROPPED.fetch_add(1, Ordering::Relaxed); - crate::pipeline::note_drop(self.pipeline as This); + /// For a shader that picks buffers from the view heap by an index it + /// computes (SM 6.6 dynamic resources): the GPU address of the heap's + /// table of element strides, with every buffer view of the heap given + /// its host slot and its memory brought up to date when `list` is + /// submitted. Tables tell us which views a draw reads; nothing tells + /// us which of the heap's a computed index names, so all of them are + /// made ready, once per list. + /// shortcut: the buffers are read, not written: what such a shader + /// writes through a picked unordered access view stays in the host + /// copy. A list refreshes them where it first runs such a shader; + /// title writes recorded later in the same list are not seen. + /// The table of strides and view kinds of the bound view heap, for a + /// shader that only looks at the views of its tables + /// (`victory_shader::emit::SLOT_TABLE_STRIDES`): bound without the pass + /// over the heap's buffers [`Self::heap_buffers`] makes (codec_d, + /// cool_fox f4b48ad). + fn heap_strides(&self, list: &HostList) -> Option<u64> { + let heap = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers())?; + let host = heap.host()?; + let gpu = host.strides_gpu()?; + // (its own key, apart from `heap_buffers`'s) + if list.first_use(gpu as usize | 2) + && let Some(buffer) = host.strides_buffer() + { + list.keep(buffer); + } + Some(gpu) + } + + fn heap_buffers(&self, list: &HostList) -> Option<u64> { + let heap = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers())?; + let host = heap.host()?; + let gpu = host.strides_gpu()?; + // Once per list and table (a list may bind two view heaps): the + // table's aligned address, tagged apart from title resources + // (codec_d, cool_fox 18bdf79). + if !list.first_use(gpu as usize | 1) { + return Some(gpu); + } + // The list may outlive the title's heap object, which owns the table. + if let Some(buffer) = host.strides_buffer() { + list.keep(buffer); + } + // The pass itself once per frame: per list it ran up to 51 times a + // frame over 81,000 views and 4,100 host copies, 18 s of every + // frame (2026-11-24, run 11). + // shortcut: what the title writes into such buffers between lists + // of one frame is seen a frame late. + // Per heap: with one stamp for all, a second view heap's buffers + // went without their pass for the frame (cool_fox 18bdf79). + let frame = crate::frame::current(); + if host.buffer_frame.swap(frame, Ordering::Relaxed) == frame { + return Some(gpu); + } + // `VICTORY_HEAP_PASS_MARKED` (off unless set): the pass that looks + // only at marked slots, in place of everything below. + if crate::heap_pass::marked() { + self.heap_buffers_marked(list, heap, host, frame); + return Some(gpu); + } + // (`alt`, the marked pass's turn just over: the host copies it + // kept are let go.) + if crate::heap_pass::marked_paused() { + *MARKED.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + let started = std::time::Instant::now(); + // Per host heap: the host copy and range each slot's buffer view + // reads, kept from pass to pass. Only the slots written since the + // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s + // at best); all of them every 16 passes, because a view of a + // released resource goes stale without a write, and a slot written + // before its memory had a host copy is only made then. + let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let (passes, ranges) = kept + .get_or_insert_with(Default::default) + .entry((std::ptr::from_ref(host) as usize, gpu)) + .or_insert_with(|| (0, Ranges::new())); + let changed = host.buffer_changes(); + let slots = if *passes % 16 == 0 { + ranges.clear(); + host.buffer_slots() + } else { + changed + }; + *passes += 1; + // Whether the device was there before the pass: a view that removes + // it is named below. + static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); + HEAP_PASS_PARTS[1].fetch_add(slots.len() as u64, Ordering::Relaxed); + for (n, &index) in slots.iter().enumerate() { + ranges.remove(&index); + let Some(handle) = heap.handle(index) else { + continue; + }; + let Some(view) = host.mirror(index, handle, true) else { + continue; + }; + // Every 64 views while the device lives (a cheap query). + if alive + && n % 64 == 63 + && let Some(why) = crate::descriptor::host::device_removed() + { + alive = false; + GONE.store(true, Ordering::Relaxed); + let last: Vec<String> = slots[n - 63..=n] + .iter() + .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}"))) + .map(|s| s.chars().take(200).collect()) + .collect(); + tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}"); + crate::host::log_removal_context(); + } + // The copy the slot shows (`buffer_copy`), not the one the + // view's range alone would find. + let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else { + continue; + }; + #[cfg(feature = "diagnostics")] + if host.shows(index, &shadow.buffer) == Some(false) { + HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); + } + ranges.insert(index, (shadow, address, address + len)); + } + let views = ranges.len() as u32; + // Per host copy, the span its picked views cover. + let mut spans: std::collections::HashMap<usize, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)> = + std::collections::HashMap::new(); + for (shadow, from, to) in ranges.values() { + let key = std::sync::Arc::as_ptr(shadow) as usize; + let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); + span.1 = span.1.min(*from); + span.2 = span.2.max(*to); + } + drop(kept); + let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); + // Memory that is not write-watched is copied whole by every refresh. + // It was once refreshed only every 120 frames (unmapped pages read + // one by one cost 14 GB a frame in run 11, before they were + // remembered): streamed geometry then drew from stale buffers, and + // the garbage ended runs (the card stopped answering 14-90 frames + // into the opening cutscene; with every frame it ran on). The pass + // costs some 30 ms a frame this way. + static WHOLE: std::sync::Mutex<Option<std::collections::HashMap<usize, u64>>> = std::sync::Mutex::new(None); + let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let whole = whole.get_or_insert_with(Default::default); + for (shadow, from, to) in spans.values() { + if shadow.unwatched() { + // By the copy's number: a copy made where one let go was + // (`shadow::let_go_idle`) has never been refreshed. + let key = shadow.id() as usize; + // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame). + static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let every = *EVERY.get_or_init(|| { + std::env::var("VICTORY_UNWATCHED_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1) + }); + match whole.get(&key) { + Some(&last) if frame < last + every => continue, + _ => { + whole.insert(key, frame); + } + } + } + shadow.refresh(list, *from, to - from); + } + let textures_began = std::time::Instant::now(); + if !crate::heap_worker::kick(heap) { + Self::heap_textures(Into::List(list), heap, host); + } + HEAP_PASS_PARTS[0].fetch_add(textures_began.elapsed().as_micros() as u64, Ordering::Relaxed); + HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); + HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + static LOGGED: AtomicU64 = AtomicU64::new(0); + // The first pass and every growth of the set by half. + let seen = LOGGED.load(Ordering::Relaxed); + if u64::from(views) > seen + seen / 2 { + LOGGED.store(u64::from(views), Ordering::Relaxed); + tracing::info!( + slots = slots.len(), + views, + copies = spans.len(), + mb = bytes >> 20, + ms = started.elapsed().as_millis(), + "buffer views of the heap made ready for shaders that pick them by index" + ); + } + Some(gpu) + } + + /// [`State::heap_buffers`]' pass with `VICTORY_HEAP_PASS_MARKED` + /// (`crate::heap_pass`, after fork pull request #523): a slot is looked + /// at again only when its view was written, the table entry its record + /// names was freed, its record in title memory is not the one seen at + /// its last look, or it found no host copy (every 16 passes); every slot + /// every 256 passes. A copy's span is worked out again only when one of + /// its slots went. What follows the slots (the refreshes, the textures, + /// the counts) is the other pass's, line for line. + fn heap_buffers_marked( + &self, + list: &HostList, + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + frame: u64, + ) { + let started = std::time::Instant::now(); + let mut kept = MARKED.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = kept.get_or_insert_with(Default::default); + // `alt`, back from the other pass's turn: what is kept here is from + // before it, and it took the heap's changes meanwhile. Both start + // anew: this one now, the other at its next turn (with no entry it + // begins at pass 0, which looks at every slot). + if crate::heap_pass::RESUMED.swap(false, Ordering::Relaxed) { + heaps.clear(); + *RANGES.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + // One list of freed table entries for all heaps: each heap's pass is told. + let forgotten = crate::descriptor::take_forgotten(); + for picked in heaps.values_mut() { + picked.note_forgotten(forgotten.as_deref()); + } + let ranges = heaps.entry(std::ptr::from_ref(host) as usize).or_insert_with(|| Marked::new(false)); + let changed = host.buffer_changes(); + let record = |index: u32| heap.handle(index).map(crate::descriptor::record_at); + let slots = ranges.plan(changed, || host.buffer_slots(), record, crate::descriptor::record_entry); + // Whether the device was there before the pass: a view that removes + // it is named below. + static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); + HEAP_PASS_PARTS[1].fetch_add(slots.len() as u64, Ordering::Relaxed); + // Of the slots looked at, those whose record is the one seen at + // their last look (a view written again as it was). + let mut same = 0u64; + for (n, &index) in slots.iter().enumerate() { + let Some(handle) = heap.handle(index) else { + ranges.forget(index); + continue; + }; + // Read before the slot is made: a write after it is seen next pass. + let record = crate::descriptor::record_at(handle); + let entry = crate::descriptor::record_entry(record); + same += u64::from(ranges.record_of(index) == Some(record)); + ranges.forget(index); + let Some(view) = host.mirror(index, handle, true) else { + continue; + }; + // Every 64 views while the device lives (a cheap query). + if alive + && n % 64 == 63 + && let Some(why) = crate::descriptor::host::device_removed() + { + alive = false; + GONE.store(true, Ordering::Relaxed); + let last: Vec<String> = slots[n - 63..=n] + .iter() + .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}"))) + .map(|s| s.chars().take(200).collect()) + .collect(); + tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}"); + crate::host::log_removal_context(); + } + // The copy the slot shows (`buffer_copy`), not the one the + // view's range alone would find. + let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else { + // A buffer view whose memory has no host copy (yet): tried + // again every 16 passes. (Other views: left out until + // written, as in the other pass.) + if crate::descriptor::host::buffer_range(&view).is_some_and(|(_, len)| len > 0) { + ranges.orphan(index, record, entry); + } + continue; + }; + #[cfg(feature = "diagnostics")] + if host.shows(index, &shadow.buffer) == Some(false) { + HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); + } + let key = std::sync::Arc::as_ptr(&shadow) as usize; + ranges.keep(index, key, &shadow, address, address + len, record, entry); + } + let views = ranges.views() as u32; + // Per host copy, the span its picked views cover. + let spans = ranges.spans(); + drop(kept); + let bytes: u64 = spans.iter().map(|s| s.2 - s.1).sum(); + // Memory that is not write-watched is copied whole by every refresh + // (see the other pass). + static WHOLE: std::sync::Mutex<Option<std::collections::HashMap<usize, u64>>> = std::sync::Mutex::new(None); + let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let whole = whole.get_or_insert_with(Default::default); + for (shadow, from, to) in &spans { + if shadow.unwatched() { + let key = shadow.id() as usize; + // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame). + static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let every = *EVERY.get_or_init(|| { + std::env::var("VICTORY_UNWATCHED_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1) + }); + match whole.get(&key) { + Some(&last) if frame < last + every => continue, + _ => { + whole.insert(key, frame); + } + } + } + shadow.refresh(list, *from, *to - *from); + } + let textures_began = std::time::Instant::now(); + if !crate::heap_worker::kick(heap) { + Self::heap_textures(Into::List(list), heap, host); + } + HEAP_PASS_PARTS[0].fetch_add(textures_began.elapsed().as_micros() as u64, Ordering::Relaxed); + HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); + HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + // Every 256 passes: how many of the slots looked at held the record + // of their last look (what a further cut could leave alone). + static SEEN: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + SEEN[1].fetch_add(slots.len() as u64, Ordering::Relaxed); + SEEN[2].fetch_add(same, Ordering::Relaxed); + if SEEN[0].fetch_add(1, Ordering::Relaxed) % 256 == 255 { + tracing::info!( + "the marked pass over the heap's buffer views (VICTORY_HEAP_PASS_MARKED), its last 256 passes: {} slots looked at, {} of them held the record seen at their last look; {} views kept now", + SEEN[1].swap(0, Ordering::Relaxed), + SEEN[2].swap(0, Ordering::Relaxed), + views, + ); + } + static LOGGED: AtomicU64 = AtomicU64::new(0); + // The first pass and every growth of the set by half. + let seen = LOGGED.load(Ordering::Relaxed); + if u64::from(views) > seen + seen / 2 { + LOGGED.store(u64::from(views), Ordering::Relaxed); + tracing::info!( + slots = slots.len(), + views, + copies = spans.len(), + mb = bytes >> 20, + ms = started.elapsed().as_millis(), + "buffer views of the heap made ready for shaders that pick them by index (the marked pass)" + ); + } + } + + /// Runs the pass that uploads textures picked by index + /// ([`State::heap_textures`]) where nothing has asked for it yet + /// ([`early_budgets`]): once a frame for a few milliseconds, at the + /// frame's first draw with a view heap set, and with a larger budget + /// of its own before every draw whose pixel shader is one of the + /// title's bake programs. The uploads are recorded into `list` ahead + /// of the draw being bound, as the world's pass records them. + /// Then, for a draw of the title's skin bake, what + /// `VICTORY_BAKE_SOURCES` asks for its own textures + /// ([`State::bake_sources_pass`]). + fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) { + if compute { + return; + } + self.early_textures_budgeted(list, p); + if bake_sources_mode().0 != BakeMode::Off { + self.bake_sources_pass(list, p); + } + } + + /// [`State::early_textures`]' runs within budgets of their own. + fn early_textures_budgeted(&self, list: &HostList, p: &HostPipeline) { + let (early_ms, bake_ms) = early_budgets(); + if early_ms == 0 && bake_ms == 0 { + return; + } + let bake = bake_ms > 0 + && p.stages.iter().any(|s| s.shader.bakes || BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str())); + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + // The milliseconds this frame's bake draws have taken so far: a + // frame has several, and together they get `bake_ms`. + static BAKED_MS: AtomicU64 = AtomicU64::new(0); + let frame = crate::frame::current(); + let first = FRAME.swap(frame, Ordering::Relaxed) != frame; + if first { + BAKED_MS.store(0, Ordering::Relaxed); + } + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + let budget = if bake && left > 0 { + // What a bake may read must be there now: up to 2 GiB. + (left, 2 << 30) + } else if first && loading_now() && loading_ms() > 0 { + // Try 6.3: behind a loading screen, the loading budget (the + // pass of the world does not run there). + let bytes: u64 = if crate::pressure::texture_pass_quarters().1 { 768 << 20 } else { 384 << 20 }; + (loading_ms().max(early_ms), bytes) + } else if first && early_ms > 0 { + (early_ms, 64 << 20) + } else { + return; + }; + let Some(heap) = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers()) + else { + return; + }; + let Some(host) = heap.host() else { + return; + }; + let bake = bake && left > 0; + // What can wait for a later list is the worker's. + if !bake && crate::heap_worker::kick(heap) { + return; + } + let _pass = crate::heap_worker::on().then(crate::heap_worker::urgent); + let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; + if bake && n.is_power_of_two() { + let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); + tracing::info!( + frame, + bakes = n, + queued_at_the_last_pass = slots, + due_at_the_last_pass = due, + uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), + "a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)" + ); + } + let began = std::time::Instant::now(); + PASS_BUDGET.set(Some(budget)); + Self::heap_textures(Into::List(list), heap, host); + PASS_BUDGET.set(None); + if bake { + BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); + } + } + + /// For a draw of the title's skin bake (any pixel shader with the + /// bake's tables, [`bake_tables`]): the textures it samples by index, + /// read from its own constants and records, after the budgeted runs + /// above. `VICTORY_BAKE_SOURCES=count`: counted and logged + /// ([`State::log_bake_sources`]). `=1`: those still waiting in the + /// queue are also uploaded now, into `list` ahead of the draw, while + /// the card has room, up to `VICTORY_BAKE_SOURCES_MB` a draw. That run + /// is this thread's: the worker, if it runs, stops and hands over what + /// it recorded first ([`crate::heap_worker::urgent`]), as for the + /// budgeted bake run. A source missing here is baked as nothing for the + /// rest of the run: black or blotched skin. + fn bake_sources_pass(&self, list: &HostList, p: &HostPipeline) { + let (mode, _) = bake_sources_mode(); + let Some(tables) = bake_tables(p) else { + return; + }; + let Some(heap) = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers()) + else { + return; + }; + let Some(host) = heap.host() else { + return; + }; + let Some(sources) = self.bake_sources(tables, heap, host) else { + return; + }; + let waiting = !sources.queued.is_empty() || !sources.unmade.is_empty(); + let mut done = [0u64; 4]; + let mut skipped = false; + if matches!(mode, BakeMode::Upload | BakeMode::Full) && waiting { + if mode == BakeMode::Full || crate::resource::room() { + let _pass = crate::heap_worker::on().then(crate::heap_worker::urgent); + host.texture_slots_requeue(&sources.unmade, crate::frame::current()); + PASS_SOURCES.set(Some(sources.queued.iter().chain(&sources.unmade).copied().collect())); + PASS_SOURCED.set([0; 4]); + // No budget of the frame's: the run serves the sources + // alone, within their own bytes. + PASS_BUDGET.set(Some((0, 0))); + Self::heap_textures(Into::List(list), heap, host); + PASS_BUDGET.set(None); + PASS_SOURCES.set(None); + done = PASS_SOURCED.get(); + } else { + skipped = true; + } + } + Self::log_bake_sources(p, &sources, done, Self::bake_missing(&sources, host), skipped); + } + + /// The textures a draw of the title's skin bake samples + /// ([`BakeTables`]), by what the queue of textures picked by index + /// holds of them. `None`: the draw's table does not hold what a bake's + /// does. + fn bake_sources( + &self, + tables: BakeTables, + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + ) -> Option<BakeSources> { + let Some(&Root::Table(table)) = self.roots_ref(false).get(usize::from(tables.slot)) else { + return None; + }; + let View::Constant(constants, size) = crate::descriptor::view(table + u64::from(tables.constants) * 4)? + else { + return None; + }; + let mut words = [0u8; 0x80]; + if (size as usize) < words.len() || !crate::host::read_into(constants as *const u8, &mut words) { + return None; + } + let (address, len) = crate::descriptor::view(table + u64::from(tables.records) * 4) + .and_then(|view| crate::descriptor::host::buffer_range(&view)) + .unwrap_or((0, 0)); + let held = u32::try_from(len / BAKE_RECORD).unwrap_or(u32::MAX); + let (named, records) = bake_named(&words, held, |i| { + let mut record = [0u8; 0x44]; + crate::host::read_into((address + u64::from(i) * BAKE_RECORD) as *const u8, &mut record).then_some(record) + }); + let mut sources = BakeSources { records, ..Default::default() }; + let mut textures = Vec::new(); + for index in named { + let Some(handle) = heap.handle(index) else { + continue; + }; + if crate::descriptor::view(handle).is_some_and(|view| crate::descriptor::host::is_texture_view(&view)) { + textures.push((index, handle)); + } + } + let indices: Vec<u32> = textures.iter().map(|t| t.0).collect(); + sources.queued = host.texture_slots_queued(&indices).into_iter().map(|q| q.0).collect(); + sources.textures = textures; + for &(index, handle) in &sources.textures { + if sources.queued.contains(&index) { + continue; + } + if host.texture_slot_made_from(index, handle) { + sources.ready += 1; + } else if let Some(View::Placed(false, resource, desc)) = crate::descriptor::view(handle) + && crate::texture::mapped_bytes( + (u64::from(desc[10]) | u64::from(desc[11]) << 32) as *const u8, + crate::resource::placed_bytes(&resource).unwrap_or(1) as usize, + ) > 0 + { + sources.unmade.push(index); + } else { + sources.other += 1; + } + } + Some(sources) + } + + /// Of a bake draw's textures, the ones the draw samples wrong: placed + /// by the title in memory that is there, with a host slot that shows + /// nothing of them. Counted when the runs before the draw are done. + fn bake_missing(sources: &BakeSources, host: &crate::descriptor::host::HostHeap) -> u64 { + let missing = |&&(index, handle): &&(u32, u64)| { + !host.texture_slot_made_from(index, handle) + && matches!( + crate::descriptor::view(handle), + Some(View::Placed(false, resource, desc)) if crate::texture::mapped_bytes( + (u64::from(desc[10]) | u64::from(desc[11]) << 32) as *const u8, + crate::resource::placed_bytes(&resource).unwrap_or(1) as usize, + ) > 0 + ) + }; + sources.textures.iter().filter(missing).count() as u64 + } + + /// The lines of `VICTORY_BAKE_SOURCES`: one for each of the first 64 + /// bake draws that sample a texture wrong ([`State::bake_missing`]), + /// and while bake draws come, one a second with the totals so far. + /// `skipped`: the upload was not made, the card having no room. + fn log_bake_sources(p: &HostPipeline, sources: &BakeSources, done: [u64; 4], missing: u64, skipped: bool) { + // Bake draws; of them sampling something wrong; sources waiting at + // the draw; made stale; sampled wrong; uploaded; their bytes; + // uploads not made for lack of room. + static TOTALS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + static LINES: AtomicU64 = AtomicU64::new(0); + static SAID_MS: AtomicU64 = AtomicU64::new(0); + let waiting = sources.queued.len() as u64; + let unmade = sources.unmade.len() as u64; + let [uploaded, bytes, unmapped, as_before] = done; + for (total, now) in TOTALS.iter().zip([ + 1, + u64::from(missing > 0), + waiting, + unmade, + missing, + uploaded, + bytes, + u64::from(skipped), + ]) { + total.fetch_add(now, Ordering::Relaxed); + } + let frame = crate::frame::current(); + if missing > 0 && LINES.fetch_add(1, Ordering::Relaxed) < 64 { + let pixel = p.stages.iter().find(|s| s.shader.stage == "pixel").map_or("", |s| s.shader.hash.as_str()); + tracing::warn!( + frame, + pixel, + records = sources.records.0, + records_read = sources.records.1, + textures = sources.textures.len(), + on_the_card = sources.ready, + waiting, + made_stale = unmade, + the_host_s_own = sources.other, + uploaded, + kilobytes = bytes >> 10, + as_far_as_mapped_already = as_before, + not_mapped = unmapped, + skipped_no_room = skipped, + sampled_wrong = missing, + "a skin-bake draw samples textures that are not on the card (VICTORY_BAKE_SOURCES)" + ); + } + let now = crate::host::now_ms(); + let said = SAID_MS.load(Ordering::Relaxed); + if now.saturating_sub(said) >= 1000 + && SAID_MS.compare_exchange(said, now, Ordering::Relaxed, Ordering::Relaxed).is_ok() + { + let [draws, short, waited, stale, wrong, ups, up_bytes, no_room] = + TOTALS.each_ref().map(|t| t.load(Ordering::Relaxed)); + tracing::info!( + frame, + bake_draws = draws, + draws_sampling_wrong = short, + sources_waiting = waited, + made_stale = stale, + sampled_wrong = wrong, + uploaded = ups, + megabytes = up_bytes >> 20, + skipped_no_room = no_room, + "skin-bake draws and their own textures, so far (VICTORY_BAKE_SOURCES)" + ); + } + } + + /// The queue's side of the card accounting line + /// (`crate::resource::card_accounting`, which says what the line + /// holds): the slots that are due, by what their texture has on the + /// card. Off unless `VICTORY_CARD_ACCOUNTING=1`; then at the first pass + /// that finds the card without room, and every five seconds after it. + /// Nothing is made, uploaded or counted as used here. For 18,000 due + /// slots: 18,000 looks at a title slot and at the texture it views, a + /// lock each, some milliseconds of the thread that records the frame. + fn card_accounting( + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + frame: u64, + room: bool, + ) { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ACCOUNTING").is_some_and(|v| v == "1")) { + return; + } + // When the next line is due (0: none yet, the card has had room). + static NEXT: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms().max(1); + let next = NEXT.load(Ordering::Relaxed); + // (With levels on demand the card may never be without room: the + // lines then start with the first texture made that way.) + let by_level = crate::tiles::STATS[4].load(Ordering::Relaxed) > 0; + let due_now = if next == 0 { !room || by_level } else { now >= next }; + if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + // Due slots; of them uploaded before; of them viewing nothing the + // title fills; and the textures (each once) whose host copy is + // alive, with their bytes on the card. + let mut due = [0u64; 5]; + // Textures (each once) that never had a host copy, and ones whose + // host copy was let go: where their memory is, and its bytes. + let (mut never, mut gone) = (Vec::new(), Vec::new()); + let mut seen = std::collections::BTreeSet::new(); + for (index, uploaded) in host.texture_slots_all_due(frame) { + due[0] += 1; + due[1] += u64::from(uploaded); + let state = match heap.handle(index).and_then(crate::descriptor::view) { + Some(View::Placed(false, resource, desc)) if resource[0] != 1 => { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + match crate::resource::placed_known(address, &resource) { + Some(texture) => crate::resource::copy_state(texture), + // No title texture was made for it: the pass never + // got as far as making one. + None => Some((0, crate::resource::placed_bytes(&resource).unwrap_or(0), address)), + } + } + Some(View::Shader(object, _)) if crate::resource::title_fills(object as This) => { + crate::resource::copy_state(object as This) + } + _ => None, + }; + let Some((state, bytes, memory)) = state else { + due[2] += 1; + continue; + }; + if !seen.insert(memory) { + continue; + } + match state { + 2 => { + due[3] += 1; + due[4] += bytes; + } + 1 => gone.push((memory, bytes)), + _ => never.push((memory, bytes)), + } + } + crate::resource::card_accounting(room, due, never, gone); + } + + /// The texture side of [`State::heap_buffers`]: textures the title fills + /// itself (streamed pages, layout-library copies) whose views sit in the + /// view heap are created (placed textures have no host texture until + /// something reads them) and uploaded, as a table read would do, for + /// shaders that pick them by a computed index. Within a budget of bytes + /// per frame and in all; the rest waits for later lists and frames. + /// The most recently written slots first (`TextureQueue::due`); slots + /// draws read through tables are not in the queue. + /// shortcut: uploaded once, and again only when the title rewrites the + /// slot. A placed texture not all mapped yet is uploaded with what is + /// there and looked at again (1, 2, 4, ... frames later, at most about + /// a second): uploaded again when more of it is mapped. Pages mapped + /// in place of others, and contents changed with no descriptor write, + /// are missed (hook the page-mapping events for those). + /// `VICTORY_HEAP_TEXTURES=0` turns it off. + /// On a thread of its own the pass records into lists of its own, and + /// the slots show what they upload from then on + /// (`crate::heap_worker`). + pub(crate) fn heap_textures( + mut into: Into<'_>, + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + ) { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) { + return; + } + /// Bytes of texture memory staged per frame. + // `VICTORY_TEXTURE_STAGE_MB` raises it: a backlog of tens of thousands of + // textures (a scene's first minutes) then drains in fewer frames. + static PER_FRAME_MB: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let per_frame: u64 = *PER_FRAME_MB.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_STAGE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(192) + }) << 20; + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + static SPENT: AtomicU64 = AtomicU64::new(0); + // The draws of the frame before (`list::DRAWS_EVER` at each new + // frame): few of them is a loading screen, a menu or a fade. + static DRAWS_AT: AtomicU64 = AtomicU64::new(0); + static LAST_DRAWS: AtomicU64 = AtomicU64::new(u64::MAX); + let frame = crate::frame::current(); + if FRAME.swap(frame, Ordering::Relaxed) != frame { + SPENT.store(0, Ordering::Relaxed); + let ever = crate::list::DRAWS_EVER.load(Ordering::Relaxed); + let last = ever.saturating_sub(DRAWS_AT.swap(ever, Ordering::Relaxed)); + let at = crate::host::now_ms(); + let before = FRAME_AT.swap(at, Ordering::Relaxed); + // Try 6.6: eased over frames, so one slow frame does not give + // the next pass a bigger budget and make it slow too (in the + // 6.5 report a 1.6 s frame let the pass take 240 ms). + let took = if before == 0 { 0 } else { at.saturating_sub(before).min(10_000) }; + let eased = LAST_FRAME_MS.load(Ordering::Relaxed); + LAST_FRAME_MS.store(if eased == 0 { took } else { (eased * 3 + took) / 4 }, Ordering::Relaxed); + LAST_DRAWS.store(last, Ordering::Relaxed); + if last < loading_draws() { + LOW_DRAW_FRAMES.fetch_add(1, Ordering::Relaxed); + } else { + LOW_DRAW_FRAMES.store(0, Ordering::Relaxed); + } + // A loading screen just went: the curtain goes up. + let loading = loading_now(); + if WAS_LOADING.swap(loading, Ordering::Relaxed) && !loading && join_hold_ms() > 0 { + JOINED_AT.store(crate::host::now_ms().max(1), Ordering::Relaxed); + tracing::info!( + hold_ms = join_hold_ms(), + due = HEAP_TEXTURES_QUEUE[1].load(Ordering::Relaxed), + "a loading screen went: the world's first frames upload its textures first (VICTORY_JOIN_HOLD_MS=0: not)" + ); + } + } + // No more of them are made while the card has no room + // (`resource::room`): by what is alive now, not by what was ever + // staged (4 GB in all, after which later textures stayed empty for + // the run). The ones nothing names any more are let go, which + // makes room again: so the slots are still looked at (the pass + // returned here, and a slot whose texture had been streamed out + // kept its host copy for as long as the card was full). + // A skin-bake draw's own textures (`State::bake_sources_pass`): a + // run for them alone, on the thread that records the draw. Nothing + // of the queue's upkeep is done in it, which a pass of this frame + // did or will do. + let sources = PASS_SOURCES.take(); + let only = sources.is_some(); + // A bake draw's own run with `VICTORY_BAKE_SOURCES=full` goes on + // as if the card had room, within its own bytes. + let forced = only && bake_sources_mode().0 == BakeMode::Full; + let mut room = forced || crate::resource::room(); + // Bytes uploaded by this pass since the card was last asked + // whether it has room: asked again every 32 MiB (a pass may upload + // 192 MB and more, and one asking a pass let the queue run some + // 400 MB past its line while the world loaded: run 193). + let mut since_asked = 0u64; + if !room && !only { + HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed); + once!("textures picked by index: the card has no room for more; they wait"); + } + let mut refused = 0; + let mut squeeze_ok = !room && crate::resource::squeeze_room(); + let mut squeezed_here = 0u32; + if !only { + // Room again: the slots held back while the card was full are due + // now (`full_card_pass`). + if room { + host.texture_slots_room(frame); + } + // Slots whose texture's memory the runtime mapped, unmapped or + // wrote since the last pass are due again. + host.texture_slots_remapped(frame); + // Levels on demand: the slots of textures whose first level with + // memory changed since the last pass are made again from it. + host.texture_views_remade(); + // And with room, the textures whose upload left a held level + // without the card's memory are uploaded again. + if room { + // Texture quality: blurred textures get their largest levels + // back while the card has memory to spare. + // (1,024 a pass, Try 6.0: 256 left a blurred backlog of + // thousands for a minute after the card had room again.) + crate::descriptor::host::sharpen(1024); + // Try 6.3: and the textures the rush made soft, once it is over, + // whatever texture quality says (it judges their levels again at + // the upload): `sharpen` waits for the card to be under its + // sharp line, and in the 6.2 report it stood above it for the + // whole world, so no rushed texture got its detail back. + crate::descriptor::host::unrush(1024); + host.texture_slots_waiting(frame); + } + // Slots that read zeros for good and nothing asks for again + // (`VICTORY_REASK_BLANK=1`; off by default; diagnostics builds). + #[cfg(feature = "diagnostics")] + host.texture_slots_blank(frame); + } + let due = match &sources { + // The bake draw's own, due or not, held or not. + Some(slots) => host.texture_slots_queued(slots), + None => { + let (due, census) = host.texture_slots_due(frame, 4096); + let due = prioritize(heap, host, due); + // What the slots shaders pick by index show, every five seconds. + #[cfg(feature = "diagnostics")] + host.placed_slot_census(); + HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); + for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { + count.store(now, Ordering::Relaxed); + } + // Where the card's memory is, and what the due slots would + // need (`VICTORY_CARD_ACCOUNTING=1`; a line when the card + // first has no room, and every five seconds after it). + Self::card_accounting(heap, host, frame, room); + due + } + }; + // What a run for a bake draw's own may upload. + let sourced_at_most = bake_sources_mode().1; + let mut sourced_bytes = 0u64; + // The frames in about four seconds, between 16 and 256: how long a + // slot with nothing to upload waits at most for its next look. In + // frames alone it was 120: four minutes at the opening cutscene's + // half a frame per second, while the title streams by the clock. + // (About a second before the runtime told of the memory it maps: + // the looks are now only for what that does not tell.) + static PASSED: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + // (A run for a bake draw's own leaves the time between passes as + // it is.) + let took = if only { 100 } else { now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1) }; + // The worker may run two passes in a frame: no shorter than that. + let took = if matches!(into, Into::Ahead(_)) { took.max(100) } else { took }; + let most = (4000 / took).clamp(16, 256); + // What a table entry of a texture a shader samples says. + let sampled = UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }; + // Also within a time per pass: the pass runs on a thread that + // records the frame, and making and staging 192 MB of textures took + // 1.6-2.2 s of each of the world's first twenty frames (run 20). + // The rest waits for the next frames, as it does past the bytes. + static SPAN_MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let span = std::time::Duration::from_millis(*SPAN_MS.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_STAGE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(250) + })); + // A backlog (a scene's first minutes: 22,000 slots due, 2-3 minutes of black + // surfaces at 192 MB a frame) gets three times the bytes and the time until it + // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget. + static CATCHUP: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); + // Nearly out of memory (`crate::pressure`): no catch-up (the share + // in quarters is kept for `VICTORY_PRESSURE` levels to come). + let (quarters, backlog_ok) = crate::pressure::texture_pass_quarters(); + let catchup = catchup && backlog_ok; + let per_frame = per_frame / 4 * quarters; + let (per_frame, span) = if catchup && due.len() >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; + // Try 6.0, the console's way: what the title streams in behind a + // loading screen is uploaded behind it too. A frame after one of + // few draws (`VICTORY_LOADING_DRAWS`, 400 unless set; 0: never; the + // world draws 2,000-4,600) gives the pass up to 1.2 s and 768 MB + // (384 MB when the PC is short of memory): nobody sees a loading + // screen take longer, and the world then opens with its textures + // there instead of coming in over the first minute. + let loading = !only && !due.is_empty() && loading_now(); + // The world's curtain (`join_hold_ms`): the world's own pass, right + // after a loading screen, with a loading screen's bytes and 1.5 s. + let holding = !only && PASS_BUDGET.get().is_none() && join_hold(due.len()); + // The world's pass in its share of the frame (`frame_share`). + let frame_ms = LAST_FRAME_MS.load(Ordering::Relaxed); + let span = if !holding && !loading && frame_share() > 0 && frame_ms > 0 { + span.min(std::time::Duration::from_millis((frame_ms * frame_share() / 100).clamp(60, pass_most_ms().max(60)))) + } else { + span + }; + let (per_frame, span) = if holding { + JOIN_HOLD_PASSES.fetch_add(1, Ordering::Relaxed); + let bytes: u64 = if backlog_ok { 768 << 20 } else { 384 << 20 }; + (per_frame.max(bytes), span.max(std::time::Duration::from_millis(1500))) + } else { + (per_frame, span) + }; + let (per_frame, span) = if loading { + let bytes: u64 = if backlog_ok { 768 << 20 } else { 384 << 20 }; + let n = HEAP_TEXTURES_LOADING.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(200) { + tracing::info!( + passes = n, + due = due.len(), + draws_last_frame = LAST_DRAWS.load(Ordering::Relaxed), + frames_of_few_draws = LOW_DRAW_FRAMES.load(Ordering::Relaxed), + early_pass_ms = PASS_BUDGET.get().map_or(0, |(ms, _)| ms), + mb = bytes >> 20, + "a loading screen: textures picked by index get a big budget behind it (VICTORY_LOADING_DRAWS=0: not)" + ); + } + (per_frame.max(bytes), span.max(std::time::Duration::from_millis(1200))) + } else { + (per_frame, span) + }; + // A run made early (`State::early_textures`) has a budget of its + // own: its bytes on top of what the frame has spent so far. + // (Not `most`: that is the longest wait between looks, used below.) + let (span, bytes_at_most) = match PASS_BUDGET.get() { + Some((ms, bytes)) => { + (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes / 4 * quarters)) + } + None => (span, per_frame), + }; + let began = std::time::Instant::now(); + let measured = PASS_PARTS_PASSES.fetch_add(1, Ordering::Relaxed) + 1; + if measured.is_multiple_of(100) { + let ms = |part: usize| PASS_PARTS_US[part].load(Ordering::Relaxed) as f64 / 1000.0 / measured as f64; + tracing::info!( + "texture pass, where its time goes (ms a pass, over {measured} passes): looks at uploaded textures {:.1}, memory queries {:.1}, host textures made {:.1}, uploads recorded {:.1}, the rest {:.1}; frame before {frame_ms} ms, the pass's share at most {}%", + ms(0), + ms(1), + ms(2), + ms(3), + ms(4), + frame_share() + ); + } + for (index, write) in due { + // A run for a bake draw's own ends at its own bytes, not at the + // frame's budget or time. + if only { + if sourced_bytes >= sourced_at_most { + once!("a skin-bake draw samples more than VICTORY_BAKE_SOURCES_MB of textures not on the card yet: the rest take their turn"); + break; + } + } else if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span { + break; + } + let ahead = matches!(into, Into::Ahead(_)); + if ahead && crate::heap_worker::make_way() { + break; + } + let mut parts = PassParts::new(); + // The record the slot has now, and the texture it names held + // while a thread of ours works on it. (Released meanwhile, or + // not a texture: nothing to upload.) + let record = heap.handle(index).and_then(crate::descriptor::view_and_key); + let _held = match &record { + Some((View::Shader(object, _), _)) if ahead => { + let held = crate::resource::hold(*object as This); + if held.is_none() { + host.texture_slot_done(index, write, None); + continue; + } + held + } + _ => None, + }; + // A placed texture whose memory is not mapped (not streamed in + // yet, or streamed out again: the heap keeps tens of thousands + // of such views) gets no host texture; looked at again soon (a + // title writes a texture's view before its pages are mapped, + // and the pass runs early in a frame). One of which some is + // mapped (a texture streaming in: its smaller mips lie at the + // start of its memory and arrive first) is uploaded with what + // is there, and again when more is. (It was uploaded again + // every 120 frames, changed or not; and asked by its first + // page alone, one whose first page is the one missing counted + // as not there.) + // A slot uploaded whole is looked at again a few times + // (`RECHECK_FRAMES`): the title writes a texture's view, and + // may fill the texture's memory itself only afterwards, with + // no descriptor write and nothing from the runtime to tell of + // it. The host copy then kept what the memory held at the + // first look for the rest of the run. The look reads 48 KiB; + // only a changed texture is uploaded again. + // `VICTORY_HEAP_RECHECK=0`: uploaded once, as before. + // One found changed by such a look is looked at again in the + // next frame with `VICTORY_RECHECK_SOON=1` ([`recheck_soon`]). + let mut again_in = RECHECK_FRAMES[0]; + if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) { + if crate::texture::fingerprint(at, len) == print { + HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed); + match RECHECK_FRAMES.get(usize::from(looks) + 1) { + Some(wait) => { + host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded) + } + // The schedule is over: looked at again every so many + // frames for as long as the slot shows it + // (`recheck_every`), or never again. + None => match recheck_every() { + 0 => host.texture_slot_done(index, write, None), + every => host.texture_slot_recheck(index, write, frame + every, (at, len), print, looks, uploaded), + }, + } + continue; + } + if recheck_soon() { + again_in = 1; + } + let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed); + // (Not a fault: the title fills such textures itself, and this + // is the look that catches it; told as information.) + if n < 200 || n.is_multiple_of(1000) { + tracing::info!( + slot = index, + address = format_args!("{at:#x}"), + bytes = len, + frames_after_upload = frame.saturating_sub(uploaded), + looks, + changed = n + 1, + looked_at_next_frame = HEAP_TEXTURES_SOON.load(Ordering::Relaxed), + "a texture picked by index changed after its upload with nothing to tell of it: uploaded again" + ); + } + } + parts.mark(1); + let mut partly = None; + if let Some((View::Placed(false, resource, desc), _)) = &record { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let len = crate::resource::placed_bytes(resource).unwrap_or(1); + let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize); + if mapped == 0 { + if only { + let [uploaded, bytes, unmapped, as_before] = PASS_SOURCED.get(); + PASS_SOURCED.set([uploaded, bytes, unmapped + 1, as_before]); + } + HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); + // Streamed out: what the slot showed is let go. + host.texture_slot_gone(index); + host.texture_slot_later(index, write, frame, most); + continue; + } + if mapped < len { + // (One of a bake draw's own is left so only if its host + // slot shows what was uploaded then.) + if mapped <= host.texture_slot_mapped(index) + && !(only + && !heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle))) + { + if only { + let [uploaded, bytes, unmapped, as_before] = PASS_SOURCED.get(); + PASS_SOURCED.set([uploaded, bytes, unmapped, as_before + 1]); + } + HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed); + host.texture_slot_later(index, write, frame, most); + continue; + } + if !crate::texture::committed(address as *const u8, 1) { + HEAP_TEXTURES_PARTLY[2].fetch_add(1, Ordering::Relaxed); + } + partly = Some(mapped); + } + } + // A texture object the host renders to or writes holds the + // host's own contents: nothing to bring up to date, and this + // pass is no use of it (its host copy is made when something + // uses it, and its slots then: `descriptor::make_waiting`). + if let Some((View::Shader(object, _), _)) = &record + && crate::resource::buffer_bytes(*object as This).is_none() + && !crate::resource::title_fills(*object as This) + { + host.texture_slot_done(index, write, None); + continue; + } + // From here on a host texture is made: not without room. The + // slot stays due. + // Not so a slot already made from this very view: its host + // texture exists, and uploading it again takes none of the + // card's memory. It was refused all the same, so a texture the + // title filled after its first upload kept its empty host copy + // from the moment the card reached the line, which is the first + // world frame in eight launches of nine: the same slots were + // found changed again at every pass and never uploaded (run + // 179: 33,000 such findings), and the main character's face + // had its colour only in the launches that entered the world + // under the line. `VICTORY_REUPLOAD_WHEN_FULL=0`: refused, as + // before. + // A card without room that still has some below its hard line + // (`resource::squeeze_room`, asked with `room`): the copy is made + // level by level and only its small levels get memory, so the + // texture is drawn blurred until there is room, not black. + let mut squeeze = false; + if !room { + let has_its_texture = reupload_when_full() + && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle)); + // (A few hundred a pass and 40 ms of it at most: a backlog of + // thousands drains over frames, not in one long stall.) + if !has_its_texture + && squeeze_ok + && squeezed_here < 384 + && began.elapsed() < std::time::Duration::from_millis(40) + { + squeeze = true; + squeezed_here += 1; + let n = HEAP_TEXTURES_SQUEEZED.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(2000) { + tracing::info!( + so_far = n, + "the card has no room for whole textures: a new one gets memory for its small levels only (VICTORY_SQUEEZE_TILES)" + ); + } + } else if !has_its_texture { + refused += 1; + if full_card_pass() { + // Held back for the frames of about four seconds + // (`most`), or until the card has room; the pass + // goes on, within a count that bounds one pass. + host.texture_slot_held(index, write, frame + most); + if refused > 1024 { + break; + } + } else if refused > 256 { + break; + } + continue; + } + let n = HEAP_TEXTURES_REUPLOADED_FULL.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(500) { + tracing::info!( + so_far = n, + slot = index, + "a texture already on the card is brought up to date although the card has no room for new ones" + ); + } + } + parts.mark(2); + // On the worker the slot shows the view when the upload is in + // the queue ([`crate::heap_worker::Batch::publish`]). + let view_now = || match &into { + Into::List(_) => heap.handle(index).and_then(|handle| host.mirror(index, handle, true)), + Into::Ahead(_) => record.as_ref().map(|(view, _)| view.clone()), + }; + let (view, placed, made) = if squeeze { + // (The host copy is made here, in the squeeze, not later on + // first use.) + crate::resource::squeezing(|| { + let view = view_now(); + let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); + let made = match &placed { + Some(View::Shader(resource, _)) => crate::resource::host_resource(*resource as This).is_some(), + _ => false, + }; + (view, placed, made) + }) + } else { + let view = view_now(); + let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); + (view, placed, true) + }; + if squeeze && (!made || !matches!(view, Some(View::Placed(..)))) { + // Not made now (too large to make level by level, or not a + // texture placed in memory, whose copy is made whole): waits. + host.texture_slot_held(index, write, frame + most); + continue; + } + let resource = match placed.as_ref().or(view.as_ref()) { + Some(&View::Shader(resource, _)) => resource as This, + _ => { + host.texture_slot_done(index, write, None); + continue; + } + }; + let title_fills = crate::resource::host_resource(resource).is_some_and(crate::texture::title_written); + if !title_fills { + // a render target, a depth or unordered access texture: the host's own + host.texture_slot_done(index, write, None); + continue; + } + // A texture that has a staging buffer now is one draws read + // through a table: they upload it, and check it at every + // submission that samples it. + let tabled = crate::texture::is_staged(resource); + parts.mark(3); + if let Some(view) = &view { + match &mut into { + Into::List(list) => readable(list, sampled.kind, view), + Into::Ahead(batch) => { + let Some(list) = batch.list() else { + return; + }; + readable(list, sampled.kind, view); + if let (Some(handle), Some((_, key))) = (heap.handle(index), &record) { + batch.publish(index, handle, *key); + } + } + } + } + parts.mark(4); + // A texture view the host refuses removes the device: name it. + static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !GONE.load(Ordering::Relaxed) + && let Some(why) = crate::descriptor::host::device_removed() + { + GONE.store(true, Ordering::Relaxed); + let text: String = format!("{view:?}").chars().take(300).collect(); + tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}"); + crate::host::log_removal_context(); + return; + } + let (bytes, whole) = crate::texture::staged(resource).unwrap_or((0, true)); + // Not all of it there: looked at again next frame, and from + // then on as a slot with nothing new (a placed texture: until + // more of it is mapped; a texture object at an address the + // title mapped: again in 120 frames, as before). + let again = match partly { + Some(mapped) => Some((frame + 1, mapped)), + None => (!whole).then_some((frame + 120, 0)), + }; + if again.is_some() { + HEAP_TEXTURES_PARTLY[1].fetch_add(1, Ordering::Relaxed); + } + if only { + let [uploaded, was, unmapped, as_before] = PASS_SOURCED.get(); + let staged = if tabled { 0 } else { bytes }; + PASS_SOURCED.set([uploaded + 1, was + staged, unmapped, as_before]); + sourced_bytes += staged; + } + if tabled { + // Nothing was staged here, so nothing is counted or spent, + // and the staging buffer stays: taking it away made the + // next draw that reads the texture through a table stage, + // detile and upload all of it once more. + HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed); + host.texture_slot_done(index, write, again); + continue; + } + // Uploaded: the list holds the staging buffer until it has run; + // a table read, or the next look at a texture not all mapped + // yet, makes it anew. (Kept for those until now: every partly + // streamed texture of the heap held a staging buffer of its full + // size for good.) + let memory = if again.is_none() && heap_recheck() { + crate::texture::staged_memory(resource) + } else { + None + }; + crate::texture::unstage(resource); + SPENT.fetch_add(bytes, Ordering::Relaxed); + if let Into::Ahead(batch) = &mut into { + batch.uploaded(bytes); + } + since_asked += bytes; + if since_asked >= 32 << 20 { + since_asked = 0; + if room { + room = forced || crate::resource::room(); + } + if !room { + squeeze_ok = crate::resource::squeeze_room(); + } + } + HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed); + HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed); + match memory { + // Whole and uploaded: looked at again (see above). + Some((at, len)) => { + let print = crate::texture::fingerprint(at, len); + if again_in != RECHECK_FRAMES[0] { + HEAP_TEXTURES_SOON.fetch_add(1, Ordering::Relaxed); + } + host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame); + } + None => host.texture_slot_done(index, write, again), + } + } + } + + /// For the frame listing, after a dropped dispatch's line: its group + /// counts and the compute root arguments it was recorded with (root + /// constants as hex dwords, root views with the title buffer they + /// point into). A program that does not translate has no bindings to + /// list; these say which memory it would have read and written (the + /// ray-tracing structure builder passes its buffers this way). + #[cfg(feature = "diagnostics")] + fn list_dropped_roots(&self, groups: [u32; 3]) { + crate::capture::op(0, || { + use std::fmt::Write; + let [x, y, z] = groups; + let mut text = format!(" its roots ({x}x{y}x{z}):"); + for (slot, root) in self.compute.iter().enumerate() { + match root { + Root::None => {} + Root::Table(a) => { + let _ = write!(text, " {slot}=table {a:#x}"); + } + Root::Constants(v) => { + let _ = write!(text, " {slot}=constants {:x?}", &v[..v.len().min(48)]); + } + Root::View(a) => { + let _ = write!(text, " {slot}=view {a:#x}"); + match crate::shadow::extent(*a) { + Some((start, len)) => { + let _ = write!(text, " in buffer {start:#x}+{len:#x}"); + } + None => text.push_str(" in no buffer"), + } + } + } + } + text + }); + } + + /// Whether the shaders of the pipeline bound now can store to buffers + /// (or the pipeline is not known): a draw with them may write the + /// arguments of draws after it, which ends a list's gathering + /// (`crate::indirect::gather`). The same test keeps such a draw out of + /// a window ([`windows`]). + fn may_store(&self) -> bool { + crate::pipeline::host_pipeline(self.pipeline as This).is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) + } + + /// What is about to be recorded may write arguments (`stores`: a + /// dispatch, or shaders that can store to buffers): the list's + /// gathering ends, whole, or with `crate::indirect::gather_by_copy` + /// only for the copies the shaders are declared to write as they are + /// prepared (`HostList::gather_wrote`), and whole only for a pipeline + /// the layer does not know. + fn gather_ends(&self, list: &HostList, stores: bool) { + if !stores { + return; + } + // The open segment of gathered records ends whatever the prelude's gathering does + // (`crate::indirect::gather_segments`). + list.segments_end(); + // Whole, as before: without the switch, for a pipeline the layer + // does not know, and for shaders that can store through a view + // that is NOT declared where they are prepared: a buffer picked + // from the view heap by an index the shader computes + // (`State::heap_buffers`: what such a shader writes through a + // picked unordered access view is declared nowhere), and title + // memory by address (`crate::memory::ready` declares the numbered + // copies once per list; a copy another list numbers after that is + // reached through the directory and not declared in this list). + let whole = !crate::indirect::gather_by_copy() + || crate::pipeline::host_pipeline(self.pipeline as This).is_none_or(|p| { + p.stages.iter().any(|stage| { + let t = stage.translated(); + t.stores + && (t.host.root_srvs.contains(&victory_shader::emit::SLOT_STRIDES) + || t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY)) + }) + }); + if whole { + list.gather_close(); + } + } + + /// Runs a dispatch on the host. + pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { + self.dispatch_x(list, x, y, z, 0); + } + + /// Runs a console `DispatchX(x, y, z, flags)` on the host: with + /// `USE_THREAD_DIMENSIONS` (flags bit 5) the counts are threads, made + /// groups here, and the program leaves out the threads past them + /// ([`dispatch_dimensions`]; fork pull request #646). + pub(crate) fn dispatch_x(&mut self, list: &HostList, x: u32, y: u32, z: u32, flags: u32) { + // It may write the arguments a window holds clamped. + self.window = None; + crate::indirect::end_window(list); + self.gather_ends(list, true); + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + DROPPED.fetch_add(1, Ordering::Relaxed); + crate::pipeline::note_drop(self.pipeline as This); + return; + } + // A program that walks ray-tracing structures nothing has built. + if crate::pipeline::walk_held(self.pipeline as This) { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_why("a walk of ray-tracing structures that are not built (VICTORY_BVH_HOLD=1)".to_owned()); + return; + } + // Try 6.12 (edsuuu/VI-BR-PORT): passes that only serve rays, with + // every ray a miss and the builder off. + if crate::pipeline::only_for_rays(self.pipeline as This) { + once!("passes that only serve rays are left out (VICTORY_SKIP_RT=1, builder off; VICTORY_RT_SKIN, VICTORY_RT_RESOLVE, VICTORY_RT_TRACE, VICTORY_ACTIVATE_RAYS =1 run them)"); + return; + } + // The ray-tracing structure builder's stages run all or none. + if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() { + DROPPED.fetch_add(1, Ordering::Relaxed); + crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned()); + #[cfg(feature = "diagnostics")] + self.list_dropped_roots([x, y, z]); + return; + } + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + once!( + pipeline = format_args!("{:#x}", self.pipeline), + "a dispatch without a host pipeline dropped" + ); + DROPPED.fetch_add(1, Ordering::Relaxed); + crate::pipeline::note_drop(self.pipeline as This); + #[cfg(feature = "diagnostics")] + self.list_dropped_roots([x, y, z]); + return; + }; + if !p.compute { + once!("a dispatch with a graphics pipeline"); + return; + } + // Counts of threads: the groups that hold them, and the counts the + // program needs where the last group is cut (fork pull request #646: + // taken as groups, the structure builder's box stages ran up to 64 + // times the threads asked and wrote past their structures). + let translated = p.stages[0].translated(); + let Some(([x, y, z], partial)) = dispatch_dimensions([x, y, z], translated.threads, flags) else { + return; + }; + if partial != [0; 3] + && !translated + .host + .user_data + .iter() + .any(|u| u.root == RootType::Other(victory_shader::emit::USER_DISPATCH_THREADS)) + { + once!( + pipeline = %p.name, + threads = ?partial, + group = ?translated.threads, + "a DispatchX counting threads cuts its last group, and its program does not take the count: \ + the threads past it run" + ); + } + // More than 65,535 groups in x: spread across z for a program that + // takes the spread words (`USER_DISPATCH_SPREAD`). + let (row, asked, gx, gy, gz) = victory_shader::emit::spread_groups(x, y, z, spreads(p).is_some()); + if row != 0 { + SPREAD[0].fetch_add(1, Ordering::Relaxed); + } else if gx > 65_535 || gy > 65_535 || gz > 65_535 { + once!(gx, gy, gz, "a dispatch asks for more than 65,535 groups in a dimension and is not spread"); + } + self.dispatch_spread = [row, asked]; + self.dispatch_threads = partial; + let bound = self.bind(list, p, true); + self.dispatch_spread = [0, 0]; + self.dispatch_threads = [0; 3]; + if !bound { + DROPPED.fetch_add(1, Ordering::Relaxed); + crate::pipeline::note_drop(self.pipeline as This); + // A stage of the structure builder that cannot be bound is a + // dropped stage: the others stop too. + if crate::pipeline::is_builder(self.pipeline as This) { + crate::pipeline::builder_off("one of its dispatches could not be bound"); + } + return; + } + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); + // SAFETY: an open list with everything set. + unsafe { list.list.Dispatch(gx, gy, gz) }; + DISPATCHED.fetch_add(1, Ordering::Relaxed); + // The light resolve's output gets the least indirect light; the + // next draw or dispatch then sets the title's state again. + if self.ambient(list, p) { + self.host_pipeline = 0; + self.host_roots = [0; 2]; + self.host_heaps = [0; 2]; + } + } + + /// What a draw or dispatch runs, for the device-removed report + /// (diagnostics): the pipeline, then per stage the user data it gets + /// (with the view at that heap index, if one is), the host addresses + /// of its root views and the views its tables name. + #[cfg(feature = "diagnostics")] + fn op_text(&self, kind: String, compute: bool) -> String { + use std::fmt::Write; + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return kind; + }; + let mut text = format!("{kind} {}", p.name); + // What it draws into (a dispatch writes through its views below). + if !compute { + let described = |t: usize| { + crate::resource::host_made(t as This).map(|r| { + // SAFETY: a live resource. + let d = unsafe { r.GetDesc() }; + format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0) + }) + }; + let targets: Vec<String> = self.targets.iter().filter_map(|&t| described(t)).collect(); + let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state); + // The title's scissor and viewport at this draw (the first of + // each): the title draws what it sees through a + // portal (a window, from inside a room) under the portal's + // rectangle, and the listing did not say which draws those are. + if let Some(r) = self.scissors.first() { + let _ = write!(text, " scissor [{} {} {} {}]", r.left, r.top, r.right, r.bottom); + } + if let Some(v) = self.viewports.first() { + let _ = write!( + text, + " viewport [{} {} {} {} depth {}..{}]", + v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth + ); + } + } + let views = (self.heaps[0] != 0) + .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) + .flatten(); + for stage in &p.stages { + let t = stage.translated(); + let _ = write!(text, " | {}:", stage.shader.hash); + for u in &t.host.user_data { + let v = match u.root { + RootType::Other(kind) => self.host_word(compute, kind, u.slot, u.dword, None), + _ => self.user_value(compute, u.slot, u.root, u.dword), + }; + let _ = write!(text, " u{}={v:#x}", u.index); + let index = if u.root == RootType::Table { v / 32 } else { v }; + if let Some(slot) = views.and_then(|h| h.describe_slot(index)) { + let _ = write!(text, " [heap {index}: {slot}]"); + } + } + for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs).chain(&stage.root_uavs) { + if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) { + let host = crate::shadow::find(*address, 1) + .map(|s| (s.gpu(*address), s.left(*address))); + let _ = write!(text, " root{slot}={address:#x} host {host:#x?}"); + } + } + } + let _ = write!(text, " tables {:?}", self.reads(compute)); + if !compute && !list_slots().is_empty() { + text.push_str(&self.slots_text()); + } + text + } + + /// For the frame listing, after a draw whose shader `VICTORY_LIST_SLOTS` + /// names: the heap slots it will pick textures from by index, and what + /// the title and the host hold there (one `~slot` line each), with the + /// words they were read from (`~raw` lines, to decode offline what is + /// not decoded here). + /// + /// Where the slots are, for the title's character shaders + /// (`PS_DeferredPedTexturedNC`, from their native code): in the small + /// buffers and constants of the draw's own table (every word of those + /// that names a texture view gets a line); in the material record, at + /// the byte offset the draw's constants (table 1, dword 56) hold at + /// 0x1c, of the buffer at table 0, dword 160; and in the record at the + /// byte offset the second root constant holds of the buffer at table 0, + /// dword 688. A word that is a small number by chance and names a + /// texture gets a line too. + #[cfg(feature = "diagnostics")] + fn slots_text(&self) -> String { + use std::fmt::Write; + const MATERIALS: u32 = 160; + const GLOBAL: u32 = 688; + const DRAW_CONSTANTS: u32 = 56; + let wanted = list_slots(); + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return String::new(); + }; + let Some(stage) = p.stages.iter().find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str()))) + else { + return String::new(); + }; + let Some(heap) = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers()) + else { + return String::new(); + }; + let t = stage.translated(); + let mut text = String::new(); + let entry = |slot: u8, dwords: u32| -> Option<View> { + let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(slot)) else { + return None; + }; + crate::descriptor::view(table + u64::from(dwords) * 4) + }; + let mut material = None; + for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) { + let label = format!("s{}+{}", u.slot, u.table_offset_dwords); + let Some(view) = entry(u.slot, u.table_offset_dwords) else { + let _ = write!(text, "\n ~table {label} no view"); + continue; + }; + let range = match &view { + View::Constant(address, size) => Some((*address, u64::from(*size))), + other => crate::descriptor::host::buffer_range(other), + }; + match range { + // A small buffer or constants: its words. + Some((address, len)) if len <= 2048 => { + Self::slot_words(&mut text, heap, &label, address, len as usize); + if u.slot == 1 && u.table_offset_dwords == DRAW_CONSTANTS && len >= 0x20 { + let mut word = [0u8; 4]; + if crate::host::read_into((address + 0x1c) as *const u8, &mut word) { + material = Some(u32::from_le_bytes(word)); + } + } + } + Some(_) => {} + // A texture read through the table: the title slot it sits in. + None => { + let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(u.slot)) else { + continue; + }; + match heap.index(table + u64::from(u.table_offset_dwords) * 4) { + Some(index) => text.push_str(&Self::slot_line(heap, &format!("table:{label}"), 0, index)), + None => { + let _ = write!(text, "\n ~table {label} title=[{}]", view_state(Some(&view))); + } + } + } + } + } + let uses = |slot: u8, dwords: u32| { + t.used.iter().any(|u| u.root == RootType::Table && u.slot == slot && u.table_offset_dwords == dwords) + }; + if let Some(at) = material + && uses(0, MATERIALS) + && let Some((base, len)) = entry(0, MATERIALS).as_ref().and_then(crate::descriptor::host::buffer_range) + { + let at = u64::from(at); + let _ = write!(text, "\n ~material record at {at:#x} of the buffer at {base:#x} bytes {len}"); + if at + 64 <= len { + Self::slot_words(&mut text, heap, "M", base + at, 64); + } + if at + 1936 + 512 <= len { + Self::slot_words(&mut text, heap, "M+1936", base + at + 1936, 512); + } + } + if uses(0, GLOBAL) + && let Some(slot) = t.used.iter().find(|u| u.root == RootType::Constants).map(|u| u.slot) + && let Some(Root::Constants(words)) = self.roots_ref(false).get(usize::from(slot)) + && let Some(&at) = words.get(1) + && let Some((base, len)) = entry(0, GLOBAL).as_ref().and_then(crate::descriptor::host::buffer_range) + { + let at = u64::from(at); + let _ = write!(text, "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}"); + if at + 64 <= len { + Self::slot_words(&mut text, heap, "G", base + at, 64); + } + } + text + } + + /// Up to 512 bytes of title memory at `address` as hex words (a `~raw` + /// line), and a `~slot` line for every word of them that names a + /// texture view in `heap`. + #[cfg(feature = "diagnostics")] + fn slot_words(text: &mut String, heap: &crate::descriptor::Heap, label: &str, address: u64, len: usize) { + use std::fmt::Write; + let mut bytes = vec![0u8; len.min(512) & !3]; + if bytes.is_empty() || !crate::host::read_into(address as *const u8, &mut bytes) { + let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}: unreadable"); return; } - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { - once!( - pipeline = format_args!("{:#x}", self.pipeline), - "a dispatch without a host pipeline dropped" - ); - DROPPED.fetch_add(1, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] - crate::pipeline::note_drop(self.pipeline as This); - return; - }; - if !p.compute { - once!("a dispatch with a graphics pipeline"); - return; + let words: Vec<u32> = + bytes.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect(); + let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}:"); + for w in &words { + let _ = write!(text, " {w:08x}"); + } + for (i, &index) in words.iter().enumerate() { + let names = index != 0 + && heap + .handle(index) + .and_then(crate::descriptor::view) + .as_ref() + .is_some_and(crate::descriptor::host::is_texture_view); + if names { + text.push_str(&Self::slot_line(heap, label, i * 4, index)); + } } - self.bind(list, p, true); - #[cfg(feature = "diagnostics")] - list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); - // SAFETY: an open list with everything set. - unsafe { list.list.Dispatch(x, y, z) }; - DISPATCHED.fetch_add(1, Ordering::Relaxed); } - /// What a draw or dispatch runs, for the device-removed report - /// (diagnostics): the pipeline, then per stage the user data it gets - /// (`table` values with the view the table starts at; `const` values - /// with the view at that heap index, if one is, since dynamic resources - /// may index the heap with one, though most are plain numbers), the - /// host addresses of its root views and the views its tables name. + /// One `~slot` line: where the slot number was read (`from`, byte + /// `at`), what the title's heap holds in slot `index` with the state + /// of that texture ([`view_state`]), what the host slot was made from, + /// and what the queue of textures picked by index knows of it. #[cfg(feature = "diagnostics")] - fn op_text(&self, kind: String, compute: bool) -> String { - use std::fmt::Write; - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { - return kind; + fn slot_line(heap: &crate::descriptor::Heap, from: &str, at: usize, index: u32) -> String { + let title = heap.handle(index).and_then(crate::descriptor::view); + let host: String = heap + .host() + .and_then(|h| h.describe_slot(index)) + .unwrap_or_else(|| "none".into()) + .chars() + .take(90) + .collect(); + let queue = match heap.host() { + Some(h) => h.texture_slot_state(index, crate::frame::current()), + None => "no host heap".into(), }; - let mut text = format!("{kind} {}", p.name); - let views = (self.heaps[0] != 0) - .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) - .flatten(); - for stage in &p.stages { - let t = stage.translated(); - let _ = write!(text, " | {}:", stage.shader.hash); - for u in &t.host.user_data { - let v = self.user_value(compute, u.slot, u.root, u.dword); - let table = u.root == RootType::Table; - let (kind, index) = if table { - ("table", v / 32) - } else { - ("const", v) - }; - let _ = write!(text, " u{}={v:#x} {kind}", u.index); - if let Some(slot) = views.and_then(|h| h.describe_slot(index)) { - let at = if table { "heap" } else { "as heap index" }; - let _ = write!(text, " [{at} {index}: {slot}]"); - } - } - for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) { - if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) { - let host = crate::shadow::find(*address, 1) - .map(|s| (s.gpu(*address), s.left(*address))); - let _ = write!(text, " root{slot}={address:#x} host {host:#x?}"); - } - } + format!( + "\n ~slot from={from}+{at:#x} slot={index} title=[{}] host=[{host}] queue=[{queue}]", + view_state(title.as_ref()) + ) + } + + /// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel: + /// the scissors before it (`on`), the title's after it. + fn mesh_scissor(&self, list: &HostList, on: bool) { + if mesh_test() != 2 { + return; + } + if on { + let one = RECT { left: 0, top: 0, right: 1, bottom: 1 }; + crate::draw::scissors(list, &vec![one; self.scissors.len().max(1)]); + } else if !self.scissors.is_empty() { + crate::draw::scissors(list, &self.scissors); } - let _ = write!(text, " tables {:?}", self.reads(compute)); - text } /// Runs a mesh dispatch of `x` groups on the host (the title's mesh /// programs are one-dimensional). pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) { + self.window = None; + crate::indirect::end_window(list); + self.gather_ends(list, self.may_store()); #[cfg(feature = "diagnostics")] self.trace("mesh", x, 0); - let ran = self.prepare_for(list, false, true) + let ran = mesh_test() != 1 + && mesh_kept(self.pipeline) + && self.prepare_for(list, false, true) && match list.list.cast::<ID3D12GraphicsCommandList6>() { Ok(l6) => { #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("mesh {x}"), false)); + self.mesh_scissor(list, true); // SAFETY: an open list with everything set. unsafe { l6.DispatchMesh(x, 1, 1) }; + self.mesh_scissor(list, false); DRAWN.fetch_add(1, Ordering::Relaxed); true } @@ -850,6 +4259,76 @@ impl State { DROPPED.fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] dropped(self.pipeline); + #[cfg(not(feature = "diagnostics"))] + crate::pipeline::note_drop(self.pipeline as This); + } + } + + /// The walls trace (`crate::host::walls_trace`): one log line per + /// frame with the draws of its main pass (four or more colour targets) + /// by scissor rectangle, and how often each of the title's culling + /// programs was dispatched. The title clips what it draws + /// through a window or door to that opening's rectangle while it holds + /// the camera to be in a room (run 182, frame 1529: 1,386 draws under + /// `531 0 1789 1337`); in a launch without the room's walls the same + /// shot has no such rectangle (run 187, frame 1414). The line shows + /// the frame in which that changes. + fn walls_census(&self, p: &HostPipeline, compute: bool) { + const CULL: [(&str, &str); 9] = [ + ("55679a0547649d0b", "tree"), + ("89d08e561897d4e5", "tree_imposter"), + ("9209777e8face9dd", "grass"), + ("17af15c4015cb4b6", "prop"), + ("fdd56d97a806bcca", "prop_nocull"), + ("42f717f1b4d18e94", "simple"), + ("1c4b3c0547e3e6fa", "slod"), + ("9146291b38ea9ce1", "meshlet_args"), + ("42683eebec081520", "depth_pyramid_cpu_occlusion"), + ]; + type Census = (u64, std::collections::BTreeMap<[i32; 4], u32>, [u32; 9]); + static CENSUS: std::sync::Mutex<Census> = + std::sync::Mutex::new((u64::MAX, std::collections::BTreeMap::new(), [0; 9])); + let frame = crate::frame::current(); + let mut census = CENSUS.lock().unwrap_or_else(|e| e.into_inner()); + if census.0 != frame { + let draws: u32 = census.1.values().sum(); + if draws > 0 { + let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); + rects.sort_unstable_by_key(|r| std::cmp::Reverse(r.1)); + let scissors: Vec<String> = rects + .iter() + .take(5) + .map(|(r, n)| format!("{} {} {} {} x{n}", r[0], r[1], r[2], r[3])) + .collect(); + let counts = census.2; + let culling: Vec<String> = CULL + .iter() + .zip(counts) + .filter(|(_, n)| *n > 0) + .map(|(c, n)| format!("{}={n}", c.1)) + .collect(); + tracing::info!( + frame = census.0, + main_pass_draws = draws, + rectangles = rects.len(), + scissors = ?scissors, + culling = ?culling, + "walls trace: the frame's main pass by scissor rectangle, and its culling dispatches" + ); + } + census.0 = frame; + census.1.clear(); + census.2 = [0; 9]; + } + if compute { + for (i, c) in CULL.iter().enumerate() { + if p.stages.iter().any(|s| s.shader.hash.as_str() == c.0) { + census.2[i] += 1; + } + } + } else if self.targets.iter().filter(|&&t| t != 0).count() >= 4 { + let r = self.scissors.first().map_or([0; 4], |r| [r.left, r.top, r.right, r.bottom]); + *census.1.entry(r).or_insert(0) += 1; } } @@ -861,7 +4340,7 @@ impl State { } } - fn table_entry(&mut self, list: &HostList, u: &UsedResource, compute: bool) { + fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) { let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { return; }; @@ -872,28 +4351,86 @@ impl State { let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else { return; }; + #[cfg(feature = "diagnostics")] + tally(19, 1); if let Some(view) = host.mirror(index, handle, true) { - self.depth_sampled |= readable(list, u, &view, self.read_only_depth(compute)); + readable(list, u.kind, &view); + // Up to date by this draw: not the texture pass's to make. + if crate::descriptor::host::is_texture_view(&view) { + host.texture_slot_tabled(index, true); + } } } - /// Gives tables with shader resources or constants slots owned by the - /// command list. Later title descriptor writes cannot change what a - /// recorded draw samples. Constants also get 256-byte-aligned storage, - /// filled at submission. Identical descriptors share slots within a list. - fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> { - let read_only_depth = self.read_only_depth(compute); + /// The descriptors a shader reads through tables. Tables holding a + /// constant buffer are made afresh for the draw in dynamic slots, with + /// the constant data copied to upload memory when the list is + /// submitted: the host wants constant buffers 256-byte aligned, the + /// console only 16. Returns those tables' new byte offsets by root + /// parameter; the other tables' slots are made from the title's. + /// + /// Within a list, the same table holding the same descriptors is made + /// once: its constant data is copied at submission either way, and the + /// big tables the world binds would otherwise take hundreds of slots per + /// draw, wrapping the dynamic slots onto lists not yet submitted. + /// + /// `half`: the table descriptors the shader moves sixteen bits a + /// channel as unsigned integers (`HostShader::half_views`). A table + /// with a 16-bit float or signed buffer view at one of them is made + /// afresh as well, with that view in the unsigned format of the same + /// layout (`descriptor::host::half_view`): the title's own slot keeps + /// the title's format for the shaders that read it as floats. + #[allow(clippy::too_many_arguments)] + pub(crate) fn tables( + &mut self, + list: &HostList, + used: &[UsedResource], + indexed: &[RootIndexedView], + half: &[(u8, u32)], + compute: bool, + spans: &[(u8, u32, u32)], + staged: &mut Vec<(u64, u32)>, + ) -> Vec<(u8, u32)> { let tables = |u: &&UsedResource| u.root == RootType::Table; let mut fresh: Vec<u8> = used .iter() .filter(tables) - .filter(|u| matches!(u.kind, ResourceType::Cbv | ResourceType::Srv)) + .filter(|u| u.kind == ResourceType::Cbv) .map(|u| u.slot) .collect(); + // The view shown in place of the title's at dword `at` of the table + // in root parameter `slot`, if the shader moves halves there and + // the title's view is a 16-bit float or signed buffer view. + let halved = |state: &Self, slot: u8, at: u32| -> Option<View> { + if !half.contains(&(slot, at)) { + return None; + } + let Some(&Root::Table(table)) = state.roots_ref(compute).get(usize::from(slot)) else { + return None; + }; + crate::descriptor::host::half_view(&crate::descriptor::view(table + u64::from(at) * 4)?) + }; + for &(slot, at) in half { + let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { + continue; + }; + let Some(view) = crate::descriptor::view(table + u64::from(at) * 4) else { + continue; + }; + if crate::descriptor::host::half_view(&view).is_some() { + if !fresh.contains(&slot) { + fresh.push(slot); + } + } else if let Some(format) = crate::descriptor::host::half_inexact(&view) { + once!( + format, + "a shader moves a buffer's 16-bit channels as integers through a view whose values the console converts: they are read and written unconverted" + ); + } + } // Tables reaching past a host heap smaller than the title's (the - // host's limit, 1,000,000 views on NVIDIA, 2,048 samplers anywhere) - // are made afresh too: the title's slots there have no host slot of - // their own. + // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the + // title's slots there have no host slot of their own. for u in used.iter().filter(tables) { if fresh.contains(&u.slot) { continue; @@ -932,19 +4469,63 @@ impl State { let Some(heap) = self.heap_of(table) else { continue; }; + if heap.samplers() || (table - heap.start) % 32 != 0 { + continue; + } let Some(host) = heap.host() else { continue; }; + let mut selected: Vec<u32> = indexed + .iter() + .filter(|index| index.table_slot == slot) + .map(|index| { + let constant = self.user_value( + compute, + index.constant_slot, + RootType::Constants, + index.constant_dword, + ); + // The shader adds i32 byte offsets and shifts by 5. + index.byte_offset.wrapping_add(constant << index.shift) / 32 + }) + .collect(); + // The descriptors the shader moves halves through are made too, + // and the table reaches them: they may lie past the range starts + // the entries give (a range of several views names only its + // first; review on #927). + selected.extend( + half.iter() + .filter(|&&(s, _)| s == slot) + .map(|&(_, at)| at / 8), + ); + selected.sort_unstable(); + selected.dedup(); let n = entries .iter() - .map(|u| u.table_offset_dwords / 8 + 1) + .map(|u| u.table_offset_dwords / 8) + .chain(selected.last().copied()) .max() - .unwrap_or(1); - let last = table + u64::from(n - 1) * 32; - if heap.index(last).is_none() { - for u in entries { - self.table_entry(list, u, compute); + .unwrap_or(0) + + 1; + // With `table_stages`: as many slots as the stage of this draw + // that reads furthest into the table needs among those that + // make it afresh too: the ones reading a constant view in it, + // or every stage where the table reaches past the host heap's + // slots (`spans` is empty with the switch off). + let n = match spans.iter().find(|s| s.0 == slot) { + Some(&(_, with_constants, all)) => { + let past = heap + .index(table) + .is_some_and(|at| u64::from(at) + u64::from(all) > u64::from(host.count())); + n.max(if past { all } else { with_constants }) } + None => n, + }; + let last = table.checked_add(u64::from(n - 1) * 32); + if n > crate::descriptor::host::DYNAMIC + || last.and_then(|handle| heap.index(handle)).is_none() + { + once!(slot, n, "fresh descriptor table exceeds the available span"); continue; } // The table and what its entries hold (record words). @@ -955,29 +4536,80 @@ impl State { let at = table + u64::from(k) * 32; // SAFETY: a descriptor slot in title memory. unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h); + // (Another table than the same slots made for a shader + // that reads them in the title's formats.) + half.contains(&(slot, k * 8)).hash(&mut h); } - (table, h.finish()) + (table, n, h.finish()) }; + #[cfg(feature = "diagnostics")] + tally(0, 1); if let Some(&first) = self.fresh_tables.get(&key) { + #[cfg(feature = "diagnostics")] + tally(1, 1); + // Found in the table an earlier stage of this draw made + // ([`table_stages`]): the title's own slots of the texture + // views this stage reads are stamped and made as the + // making of a table of its own did it (below). + let staged_title = staged + .contains(&(table, n)) + .then(|| heap.index(table).filter(|at| at + n <= host.count())) + .flatten(); for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { - self.depth_sampled |= readable(list, u, &view, read_only_depth); + readable(list, u.kind, &view); + if let Some(title) = staged_title + && crate::descriptor::host::is_texture_view(&view) + { + let k = u.table_offset_dwords / 8; + host.texture_slot_tabled(title + k, true); + host.mirror(title + k, handle, true); + } + #[cfg(feature = "diagnostics")] + tally(18, 1); + } + } + for k in selected { + if entries.iter().any(|u| u.table_offset_dwords / 8 == k) { + continue; + } + let handle = table + u64::from(k) * 32; + if let Some(view) = crate::descriptor::view(handle) + && let Some(kind) = view_kind(&view) + { + readable(list, kind, &view); + #[cfg(feature = "diagnostics")] + tally(18, 1); } } made.push((slot, first * 32)); continue; } - let Some(first) = host.dynamic(n) else { - once!(n, "descriptor table did not fit in command-list slots"); - for u in entries { - self.table_entry(list, u, compute); - } + #[cfg(feature = "diagnostics")] + let mut clock = table_asked(&mut self.recording, table, n); + let Some(first) = host.dynamic(n).or_else(|| { + crate::host::settle_for_fence(); + host.dynamic(n) + }) else { + // No room: the draw must not run with the title's own + // offsets (slots never made for it); `bind` drops it. + made.push((slot, u32::MAX)); + #[cfg(feature = "diagnostics")] + tally(25, 1); continue; }; + #[cfg(feature = "diagnostics")] + clock.lap(21); self.fresh_tables.insert(key, first); + if !spans.is_empty() { + staged.push((table, n)); + } self.dynamic - .push((std::ptr::from_ref(heap) as usize, first, n)); + .push((std::ptr::from_ref(heap) as usize, host.id(), first, n)); + // The title's own slots of this table: what the draw reads of + // them it brings up to date here, in the dynamic slots. + let title_first = heap.index(table).filter(|first| first + n <= host.count()); // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { @@ -985,21 +4617,75 @@ impl State { let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { - let Some((gpu, to)) = list.scratch(u64::from(size)) else { - host.make_null(index); - continue; + // The same constant buffer for many draws (the + // frame's and the view's constants): copied once + // between two title writes of the list. + let key = (std::ptr::from_ref(list) as usize, list.title_epoch(), address, size); + let gpu = match self.constant_fills.get(&key) { + Some(&gpu) => gpu, + None => { + let Some((gpu, to)) = list.scratch(u64::from(size)) else { + host.make_null(index); + continue; + }; + list.defer_fill(to, address as *const u8, size as usize); + if share_constants() { + self.constant_fills.insert(key, gpu); + } + gpu + } }; - list.defer_fill(to, address as *const u8, size as usize); host.constant_at(index, gpu, size); + #[cfg(feature = "diagnostics")] + { + tally(13, 1); + clock.lap(22); + } } Some(view) => { - host.make_at(index, &view); - if let Some(u) = used { - self.depth_sampled |= readable(list, u, &view, read_only_depth); + match halved(self, slot, k * 8) { + Some(shown) => host.make_at(index, &shown), + None => host.make_at(index, &view), + } + #[cfg(feature = "diagnostics")] + { + tally(if crate::descriptor::host::is_texture_view(&view) { 14 } else { 15 }, 1); + clock.lap(22); + } + let kind = used.map(|u| u.kind).or_else(|| { + selected.binary_search(&k).ok().and_then(|_| view_kind(&view)) + }); + if let Some(kind) = kind { + readable(list, kind, &view); + #[cfg(feature = "diagnostics")] + { + tally(17, 1); + clock.lap(23); + } + } + // The title's slot is a table's: out of the queue + // of textures picked by index if the draw read it + // (its texture is up to date now), and made in + // place as the texture pass would have made it, + // for a shader that picks it by index all the same. + if let Some(title) = title_first + && crate::descriptor::host::is_texture_view(&view) + { + host.texture_slot_tabled(title + k, kind.is_some()); + if kind.is_some() { + host.mirror(title + k, table + u64::from(k) * 32, true); + } + #[cfg(feature = "diagnostics")] + clock.lap(24); } } None => { host.make_null(index); + #[cfg(feature = "diagnostics")] + { + tally(16, 1); + clock.lap(22); + } if used.is_some() { once!(slot, "a table entry without a view"); } @@ -1008,6 +4694,8 @@ impl State { } made.push((slot, first * 32)); } + #[cfg(feature = "diagnostics")] + tally_done(); made } @@ -1024,7 +4712,7 @@ impl State { let targets: Vec<String> = self .targets .iter() - .filter_map(|&t| crate::resource::host_resource(t as This)) + .filter_map(|&t| crate::resource::host_made(t as This)) .map(|t| { // SAFETY: a live resource. let d = unsafe { t.GetDesc() }; @@ -1086,198 +4774,45 @@ impl State { first: u32, first_instance: u32, ) { + self.window = None; + crate::indirect::end_window(list); + self.gather_ends(list, self.may_store()); #[cfg(feature = "diagnostics")] self.trace("draw", vertices, first); - let rects = self.topology == RECTANGLES; - let expanded = crate::primitive::ExpandedTopology::from_console(self.topology); - let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first)); + let ready = self.prepare(list, false); + // A pipeline with the rectangle geometry stage draws the title's + // vertices as they are; any other gets its rectangles expanded. + let rects = self.topology == RECTANGLES && !self.completes_rects(); + let ran = ready && (!rects || self.rectangles(list, vertices, first)); if ran { - if let Some(kind) = expanded { - if let Some((count, base)) = self.expand_non_indexed(list, kind, vertices, first) { - if count > 0 { - #[cfg(feature = "diagnostics")] - list.note_op(|| { - self.op_text(format!("draw {kind:?} {count}x{instances}"), false) - }); - // SAFETY: an open list with expanded scratch index buffer bound. - unsafe { - list.list - .DrawIndexedInstanced(count, instances, 0, base, first_instance) - }; - DRAWN.fetch_add(1, Ordering::Relaxed); - } - return; - } + // Rectangles were expanded into their own vertex buffers. + let (count, from) = if rects { + (vertices / 3 * 6, 0) } else { - // Rectangles were expanded into their own vertex buffers. - let (count, from) = if rects { - (vertices / 3 * 6, 0) - } else { - (vertices, first) - }; - #[cfg(feature = "diagnostics")] - list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false)); - // SAFETY: an open list with everything set. - unsafe { - list.list - .DrawInstanced(count, instances, from, first_instance) - }; - DRAWN.fetch_add(1, Ordering::Relaxed); - return; - } - } - DROPPED.fetch_add(1, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] - dropped(self.pipeline); - } - - /// Binds a synthesized scratch index buffer expanding a non-indexed - /// console-only topology draw into a host triangle or line list. - fn expand_non_indexed( - &self, - list: &HostList, - kind: crate::primitive::ExpandedTopology, - vertices: u32, - first: u32, - ) -> Option<(u32, i32)> { - let out_count = kind.max_output_indices(vertices); - if out_count == 0 { - return Some((0, 0)); - } - let strip_cut = crate::pipeline::host_pipeline(self.pipeline as This) - .map_or(D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, |p| p.strip_cut); - let use_u16 = strip_cut == D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF; - if use_u16 { - if vertices > u32::from(u16::MAX) { - once!( - vertices, - "non-indexed console topology exceeds 16-bit strip-cut index range" - ); - return None; - } - let base = i32::try_from(first).ok()?; - let bytes = u64::from(out_count).checked_mul(2)?; - let size_bytes = u32::try_from(bytes).ok()?; - let (gpu, to) = list.scratch(bytes)?; - // SAFETY: `to` points to `out_count` writable `u16` elements in scratch upload memory. - let dst = unsafe { std::slice::from_raw_parts_mut(to.cast::<u16>(), out_count as usize) }; - kind.expand_non_indexed_u16(vertices, 0, dst); - let view = D3D12_INDEX_BUFFER_VIEW { - BufferLocation: gpu, - SizeInBytes: size_bytes, - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT, + (vertices, first) }; - // SAFETY: an open list; the view names live scratch upload memory. - unsafe { list.list.IASetIndexBuffer(Some(&view)) }; - return Some((out_count, base)); - } - let (start, base) = match i32::try_from(first) { - Ok(base) => (0u32, base), - Err(_) => { - first.checked_add(vertices)?; - (first, 0) - } - }; - let bytes = u64::from(out_count).checked_mul(4)?; - let size_bytes = u32::try_from(bytes).ok()?; - let (gpu, to) = list.scratch(bytes)?; - // SAFETY: `to` points to `out_count` writable `u32` elements in scratch upload memory. - let dst = unsafe { std::slice::from_raw_parts_mut(to.cast::<u32>(), out_count as usize) }; - kind.expand_non_indexed_u32(vertices, start, dst); - let view = D3D12_INDEX_BUFFER_VIEW { - BufferLocation: gpu, - SizeInBytes: size_bytes, - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, - }; - // SAFETY: an open list; the view names live scratch upload memory. - unsafe { list.list.IASetIndexBuffer(Some(&view)) }; - Some((out_count, base)) - } - - /// Binds a submission-filled scratch index buffer expanding an indexed - /// console-only topology draw into a host triangle or line list, preserving - /// index format (`R16_UINT`/`R32_UINT`) and strip-cut semantics. - fn expand_indexed( - &self, - list: &HostList, - kind: crate::primitive::ExpandedTopology, - indices: u32, - first: u32, - base: i32, - ) -> Option<u32> { - const R32_UINT: u32 = 42; - const R16_UINT: u32 = 57; - let v = self.index; - let is_u16 = match v.format { - R16_UINT => true, - R32_UINT => false, - _ => { - once!(format = v.format, "unsupported index format for console topology"); - return None; - } - }; - if v.address == 0 || v.size == 0 { - return None; + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false)); + // SAFETY: an open list with everything set. + unsafe { + list.list + .DrawInstanced(count, instances, from, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); } - let elem_bytes: u64 = if is_u16 { 2 } else { 4 }; - let avail = (u64::from(v.size) / elem_bytes).saturating_sub(u64::from(first)); - let count = u64::from(indices).min(avail) as u32; - let max_out = kind.max_output_indices(count); - if max_out == 0 { - return Some(0); - } - let src_addr = v.address.checked_add(u64::from(first).checked_mul(elem_bytes)?)?; - let src_bytes = usize::try_from(u64::from(count).checked_mul(elem_bytes)?).ok()?; - let out_bytes = u64::from(max_out).checked_mul(elem_bytes)?; - let out_bytes_u32 = u32::try_from(out_bytes).ok()?; - let (gpu, to) = list.scratch(out_bytes)?; - let strip_cut = crate::pipeline::host_pipeline(self.pipeline as This) - .map_or(D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, |p| p.strip_cut); - let to_addr = to as usize; - let fallback_pad = (-i64::from(base)).max(0) as u32; - if is_u16 { - let cut = (strip_cut == D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF).then_some(u16::MAX); - let pad = fallback_pad.min(u32::from(u16::MAX)) as u16; - list.defer_host(move || { - let mut src = vec![0u16; count as usize]; - crate::host::copy_mapped( - src.as_mut_ptr().cast::<u8>(), - src_addr as *const u8, - src_bytes, - false, - ); - // SAFETY: `to_addr` points to `max_out` writable `u16` slots owned by this list. - let dst = unsafe { - std::slice::from_raw_parts_mut(to_addr as *mut u16, max_out as usize) - }; - kind.expand_indexed_u16(&src, cut, pad, dst); - }); - } else { - let cut = - (strip_cut == D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF).then_some(u32::MAX); - list.defer_host(move || { - let mut src = vec![0u32; count as usize]; - crate::host::copy_mapped( - src.as_mut_ptr().cast::<u8>(), - src_addr as *const u8, - src_bytes, - false, - ); - // SAFETY: `to_addr` points to `max_out` writable `u32` slots owned by this list. - let dst = unsafe { - std::slice::from_raw_parts_mut(to_addr as *mut u32, max_out as usize) - }; - kind.expand_indexed_u32(&src, cut, fallback_pad, dst); - }); + if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); + #[cfg(not(feature = "diagnostics"))] + crate::pipeline::note_drop(self.pipeline as This); } - let view = D3D12_INDEX_BUFFER_VIEW { - BufferLocation: gpu, - SizeInBytes: out_bytes_u32, - Format: DXGI_FORMAT(v.format as i32), - }; - // SAFETY: an open list; the view names live scratch upload memory. - unsafe { list.list.IASetIndexBuffer(Some(&view)) }; - Some(max_out) + } + + /// Whether the bound pipeline completes rectangles itself, in the + /// geometry stage rectangle pipelines get (`HostPipeline::rects`). + fn completes_rects(&self) -> bool { + crate::pipeline::host_pipeline(self.pipeline as This).is_some_and(|p| p.rects) } /// Binds vertex buffers holding the rectangles of vertices `first..first @@ -1314,6 +4849,10 @@ impl State { let (from, to, stride) = (from as usize, to as usize, stride as usize); let n = rects as usize; list.defer_host(move || { + // The vertices are read in place, at submission: no change + // of mapping under the read (see + // `crate::watch::title_memory_reading`). + let _mapped = crate::watch::title_memory_reading(); // SAFETY: the vertices lie in a title buffer (checked when // recorded) and the scratch memory is the list's. let (src, dst) = unsafe { @@ -1344,52 +4883,41 @@ impl State { base: i32, first_instance: u32, ) { + self.window = None; + crate::indirect::end_window(list); + self.gather_ends(list, self.may_store()); #[cfg(feature = "diagnostics")] self.trace("indexed", indices, first); - if self.topology == RECTANGLES { + // Indexed rectangles are drawn by the rectangle geometry stage + // alone (nothing expands them on the CPU). + let lost = self.topology == RECTANGLES && !self.completes_rects(); + if lost { once!("indexed rectangles not drawn"); } - let expanded = crate::primitive::ExpandedTopology::from_console(self.topology); - let ran = self.topology != RECTANGLES && self.prepare(list, expanded.is_none()); + let ran = !lost && self.prepare(list, true); if ran { - if let Some(kind) = expanded { - if let Some(count) = self.expand_indexed(list, kind, indices, first, base) { - if count > 0 { - #[cfg(feature = "diagnostics")] - list.note_op(|| { - self.op_text(format!("indexed {kind:?} {count}x{instances}"), false) - }); - // SAFETY: an open list with expanded scratch index buffer bound. - unsafe { - list.list - .DrawIndexedInstanced(count, instances, 0, base, first_instance) - }; - DRAWN.fetch_add(1, Ordering::Relaxed); - } - return; - } - } else { - #[cfg(feature = "diagnostics")] - list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); - // SAFETY: an open list with everything set. - unsafe { - list.list - .DrawIndexedInstanced(indices, instances, first, base, first_instance) - }; - DRAWN.fetch_add(1, Ordering::Relaxed); - return; - } + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); + // SAFETY: an open list with everything set. + unsafe { + list.list + .DrawIndexedInstanced(indices, instances, first, base, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + } + if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); + #[cfg(not(feature = "diagnostics"))] + crate::pipeline::note_drop(self.pipeline as This); } - DROPPED.fetch_add(1, Ordering::Relaxed); - #[cfg(feature = "diagnostics")] - dropped(self.pipeline); } } impl State { - /// Indirect execution of the title command signature `title_args` - /// (PC numbering of the last argument: 0 draw, 1 indexed draw, 2 - /// dispatch, 10 mesh dispatch; root constants may come before it) with + /// Indirect execution of a one-argument signature of `kind` (PC + /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with /// records `stride` bytes apart at title address `arguments`, and the /// record count at `count` if the title gives one: the GPU reads them /// from the buffer's host copy, where earlier dispatches may have @@ -1397,9 +4925,7 @@ impl State { pub(crate) fn execute_indirect( &mut self, list: &HostList, - stride: u32, - title_args: &[[u32; 4]], - max: u32, + (kind, stride, max): (u32, u32, u32), arguments: u64, count: Option<u64>, ) -> bool { @@ -1409,48 +4935,64 @@ impl State { crate::pipeline::note_drop(self.pipeline as This); return false; } + if crate::pipeline::only_for_rays(self.pipeline as This) + || (crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs()) + { + return false; + } + // A program that walks ray-tracing structures nothing has built: + // dropped before the argument clamp, like a skipped one. + if crate::pipeline::walk_held(self.pipeline as This) { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_why("a walk of ray-tracing structures that are not built (VICTORY_BVH_HOLD=1)".to_owned()); + return false; + } const DRAW: u32 = 0; const INDEXED: u32 = 1; const DISPATCH: u32 = 2; const MESH: u32 = 10; - let pipeline = crate::pipeline::host_pipeline(self.pipeline as This); - // Root constants land in the user data of the stage that reads - // them; a spilled stage's user data is a root view (no dwords). - let stages: Vec<crate::indirect_plan::StageUserData<'_>> = pipeline - .map(|p| { - p.stages - .iter() - .filter_map(|s| { - let (param, dwords) = s.user_data?; - Some(crate::indirect_plan::StageUserData { - param, - dwords: if s.user_data_cbv { 0 } else { dwords }, - entries: &s.translated().host.user_data, - }) - }) - .collect() - }) - .unwrap_or_default(); - let Some(plan) = crate::indirect_plan::plan_indirect(stride, title_args, &stages) else { - #[cfg(feature = "diagnostics")] - crate::pipeline::note_why(format!( - "indirect signature {title_args:?}: cannot map onto the host pipeline" - )); + let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + crate::pipeline::note_drop(self.pipeline as This); return false; }; - let kind = plan.kind; - let multi = plan.args.len() > 1; - #[cfg(feature = "diagnostics")] - let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); - #[cfg(not(feature = "diagnostics"))] - let why = |_: &str| {}; + // Indirect rectangles (the title's tiled lighting, 256 + // indirect draws a frame, makes their corners from the vertex + // number) are completed by the pipeline's geometry stage: the + // arguments stay the title's, three vertices a rectangle. They + // cannot be expanded on the CPU, which does not know their count. + // shortcut: in a pipeline without that stage, a rectangle with no + // per-vertex inputs is drawn as its first triangle (three vertices, + // half of it), and one with vertex buffers is not drawn. + let made_rects = !p.rects + && kind == DRAW + && self.topology == RECTANGLES + && !p.inputs.iter().any(|e| !e.per_instance); + if made_rects { + once!("indirect rectangles without vertex inputs drawn as their first triangle"); + } + let matches_kind = match kind { + DRAW | INDEXED => { + (self.topology != RECTANGLES || made_rects || p.rects) && !p.compute && !p.mesh + } + MESH => !p.compute && p.mesh, + DISPATCH => p.compute, + _ => false, + }; + if !matches_kind { + why(&format!( + "pipeline mismatch (compute {}, mesh {}, topology {})", + p.compute, p.mesh, self.topology + )); + return false; + } let len = u64::from(stride) * u64::from(max.max(1)); - let Some(args) = crate::shadow::find(arguments, len) else { + let Some(args) = crate::shadow::find_any(arguments, len) else { why("arguments outside title buffers"); return false; }; let counter = match count { - Some(at) => match crate::shadow::find(at, 4) { + Some(at) => match crate::shadow::find_any(at, 4) { Some(s) => Some((s, at)), None => { why("count outside title buffers"); @@ -1459,161 +5001,317 @@ impl State { }, None => None, }; - if multi && self.topology == RECTANGLES { - once!("indirect rectangles with root constants not drawn"); - why("rectangles with root constants not supported"); + // A dispatch of a program that takes the spread words: the clamp + // writes [row, asked x, x, y, z] records, run through a signature + // that sets the two words, then dispatches. + let spread = (kind == DISPATCH && p.compute) + .then(|| spreads(p)) + .flatten() + .and_then(|(param, index)| host_spread_signature(&p.root, param, index)); + let is_spread = spread.is_some(); + let Some(signature) = spread.or_else(|| { + matches!(kind, DRAW | INDEXED | DISPATCH | MESH) + .then(|| host_signature(kind, stride)) + .flatten() + }) else { + why("no host signature"); + return false; + }; + if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) { + why("mesh draws are switched off (VICTORY_MESH_TEST=skip)"); return false; } - if kind == INDEXED && self.topology == RECTANGLES { - once!("indirect indexed rectangles not drawn"); - why("indexed rectangles not supported"); - return false; + // A window of records clamped in one pass (`windows`): for single + // records without a count buffer, drawn by shaders that store to no + // buffer. Anything else ends the window: it uses the scratch buffer + // or may write the arguments. + const WINDOW_USE: usize = usize::MAX - 0x77; + let offset = args.offset(arguments); + let windowed = windows() + && kind != DISPATCH + && max == 1 + && count.is_none() + && !p.stages.iter().any(|stage| stage.translated().stores); + // Another host list (a new one after a cut, or this one after its + // reset) has another scratch buffer, or this one's with old bytes. + let first_on_list = list.first_use(WINDOW_USE); + if !windowed || first_on_list { + self.window = None; + } + // An indirect dispatch's own record may take a gathered slot as a draw's does + // (`crate::indirect::gather_dispatches`); the dispatch ends the gathering right after that, below. + let joins = kind == DISPATCH + && max == 1 + && count.is_none() + && !is_spread + && gathers() + && crate::indirect::gather_dispatches(); + if !windowed && !joins { + // A dispatch, or shaders that store to buffers: arguments may + // be written from here on. + self.gather_ends(list, true); + } + // Diagnostics: why this command gets a pass of ours, if it does. + #[cfg(feature = "diagnostics")] + let why_not = if !windows() { + usize::MAX + } else if kind == DISPATCH { + 1 + } else if max != 1 { + 2 + } else if count.is_some() { + 3 + } else if !windowed { + 4 + } else if first_on_list { + 5 + } else { + match &self.window { + None => 6, + Some(w) if !(w.copy == args.id() && w.kind == kind && w.stride == stride) => 6, + Some(w) if offset >= w.base && (offset - w.base) % u64::from(w.step) == 0 => 8, + Some(_) => 7, + } + }; + let same = |w: &Window| w.copy == args.id() && w.kind == kind && w.stride == stride; + let hit = self + .window + .as_ref() + .filter(|w| same(w) && offset >= w.base) + .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records)) + .map(|w| (w.scratch.clone(), offset - w.base, w.step)); + // A record that misses its window: a slot the list's prelude fills, + // if the list still gathers ([`gathers`]). + let gathered = if hit.is_none() && (windowed || joins) && gathers() { + let slot = crate::indirect::gather(list, (&args.buffer, args.id()), offset, (kind, stride)); + #[cfg(feature = "diagnostics")] + WINDOW_WHY[if slot.is_some() { 12 } else { 13 }].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + slot + } else { + None + }; + if joins { + // The dispatch's record is taken (or clamped alone below): what the dispatch writes, from here on. + self.gather_ends(list, true); } - if kind == DRAW && self.topology == RECTANGLES { - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + let (bounded, at) = match (hit, gathered) { + (Some((scratch, at, step)), _) => { + // Diagnostics of windows: the record clamped again and + // compared (`crate::indirect::window_check`). + if crate::indirect::window_check() + && crate::indirect::check_hit( + list, + (&args.buffer, offset), + (kind, step), + &scratch, + at, + ) + { + self.host_pipeline = 0; + self.host_roots[1] = 0; + } #[cfg(feature = "diagnostics")] - crate::pipeline::note_drop(self.pipeline as This); - return false; - }; - if p.compute || p.mesh { - why(&format!( - "pipeline mismatch (compute {}, mesh {}, topology {})", - p.compute, p.mesh, self.topology - )); - return false; + WINDOW_WHY[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if !self.window_read { + self.window_read = true; + if let Some(w) = self.window.as_ref().filter(|w| w.records > 1) { + self.walk_step = Some((w.copy, w.kind, w.stride, w.step)); + } + } + (scratch, at) } - let Some(signature) = host_signature(DRAW, 16) else { - why("no host signature"); - return false; - }; - if max == 0 { - DRAWN.fetch_add(1, Ordering::Relaxed); - return true; - } - let prepared = match crate::rectangles::expand( - list, - p, - &self.vertex, - (&args, arguments, stride, max), - counter.as_ref().map(|(s, at)| (s, *at)), - ) { - Ok(p) => p, - Err(reason) => { - why(reason); + (None, Some((scratch, at, recorded))) => { + // A segment's pass recorded here bound our pipeline (`crate::indirect::gather_segments`). + if recorded { + self.host_pipeline = 0; + self.host_roots[1] = 0; + } + // The record's bytes are up to date when the list is + // submitted, as for a record clamped in the list. + args.refresh(list, arguments, len); + // Diagnostics of windows, for gathered records too: the + // record clamped again here and compared. + if crate::indirect::window_check() && crate::indirect::check_hit(list, (&args.buffer, offset), (kind, stride), &scratch, at) { + self.host_pipeline = 0; + self.host_roots[1] = 0; + } + (scratch, at) + } + (None, None) => { + // A window opened at the remembered step that no draw read + // from: the title does not walk here by that step. + if self.window_jumped && !self.window_read { + self.walk_step = None; + #[cfg(feature = "diagnostics")] + WINDOW_WHY[11].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + self.window_jumped = false; + // A record a short step after the last window's last one + // (the same step as that window's, if it had one): the + // title walks the buffer, so the ones that step apart + // after it are clamped with it. + let (step, records) = match &self.window { + Some(w) if windowed && same(w) => { + let last = w.base + u64::from(w.records - 1) * u64::from(w.step); + let step = offset.saturating_sub(last); + let walks = step >= u64::from(stride) + && step <= 256 + && step % 4 == 0 + && (w.records == 1 || step == u64::from(w.step)); + if walks { + let fit = (args.left(arguments) / step).min(WINDOW_MOST) as u32; + (step as u32, (if w.records == 1 { 16 } else { w.records * 2 }).min(fit).max(1)) + } else { + (stride, max) + } + } + _ => (stride, max), + }; + // A record that would be clamped alone, on a buffer whose + // step is remembered: the window the next record would + // open, opened here ([`jump_windows`]). + let (step, records) = match (windowed && records == 1 && jump_windows()) + .then(|| jump_window(self.walk_step, (args.id(), kind, stride), args.left(arguments))) + .flatten() + { + Some(jumped) => { + self.window_jumped = true; + #[cfg(feature = "diagnostics")] + WINDOW_WHY[10].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + jumped + } + None => (step, records), + }; + self.window_read = false; + args.refresh(list, arguments, len.max(u64::from(step) * u64::from(records))); + if let Some((s, at)) = &counter { + s.refresh(list, *at, 4); + } + // Bounded first: the clamp binds a compute pipeline of its + // own and copies clamped active records into a scratch + // buffer at offset 0. + let count_arg = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); + // More than the record asked for: a window clamped ahead, + // whose unfilled slots must not spend the list's budget. + // With `VICTORY_CLAMP_WINDOW`: the record clamped in the list's window of indirect draws (a draw with no + // count buffer whose shaders cannot store), at `window_at` in the window's buffer. + let mut window_at = None; + let bounded = if windowed && records > 1 { + crate::indirect::bound_ahead(list, (&args.buffer, offset), (kind, step, records)) + } else if let Some((dst, at, opened)) = (crate::indirect::clamp_window() + && count_arg.is_none() + && !is_spread + && kind != DISPATCH + && !self.may_store()) + .then(|| crate::indirect::windowed(list, (&args.buffer, offset), (kind, step, records))) + .flatten() + { + window_at = Some((at, opened)); + Some(dst) + } else { + // (A spread dispatch is never windowed: `windowed` is + // false for dispatches.) + crate::indirect::bound(list, (&args.buffer, offset), count_arg, (kind, step, records), is_spread) + }; + let Some(bounded) = bounded else { + self.window = None; + why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; + }; + #[cfg(feature = "diagnostics")] + if why_not < WINDOW_WHY.len() { + WINDOW_WHY[why_not].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + WINDOW_WHY[9].fetch_add(u64::from(records), std::sync::atomic::Ordering::Relaxed); + // One in 256 of the draws that miss their window, said: + // where the record lies against the window and against + // the record drawn before it. + if (6..=8).contains(&why_not) { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(256) { + let (last_copy, last_offset) = self.last_indirect; + tracing::info!( + "a window miss (one in 256): cause {why_not}, kind {kind}, stride {stride}, buffer {} offset {offset:#x} ({} left); the command before it on the list: buffer {last_copy} offset \ + {last_offset:#x} (this one is {} bytes on); the window it missed: {}; clamped now: {records} records at step {step}", + args.id(), + args.left(arguments), + offset as i64 - last_offset as i64, + match &self.window { + Some(w) => format!("buffer {} kind {} stride {} base {:#x} step {} records {} (this record is {} bytes from its base)", w.copy, w.kind, w.stride, w.base, w.step, w.records, offset as i64 - w.base as i64), + None => "none".to_string(), + } + ); + } + } + } + if let Some((at, opened)) = window_at { + // A draw that joined a window recorded no pass: the graphics state stands. + if opened { + self.host_pipeline = 0; + self.host_roots[1] = 0; + } + // The records sit at `at` of the window's buffer: no ahead-window state is kept over them. + self.window = None; + (bounded, at) + } else { + self.host_pipeline = 0; + self.host_roots[1] = 0; + self.window = windowed.then(|| Window { + copy: args.id(), + kind, + stride, + step, + base: offset, + records, + scratch: bounded.clone(), + }); + (bounded, 0) } - }; - self.host_pipeline = 0; - self.host_roots[1] = 0; - if !self.prepare(list, false) { - why("prepare failed for indirect rectangles"); - return false; } - prepared.before_draw(list); - #[cfg(feature = "diagnostics")] - list.note_op(|| { - self.op_text( - format!("indirect rect draw max {max} at {arguments:#x}"), - false, - ) - }); - // SAFETY: an open list with everything set; `prepared.args_buf` is - // list-owned, `counter` is kept alive by refresh, signature cached. - unsafe { - list.list.ExecuteIndirect( - &signature, - max, - &prepared.args_buf, - 0, - counter.as_ref().map(|(s, _)| &s.buffer), - counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), - ) - }; - prepared.after_draw(list); - DRAWN.fetch_add(1, Ordering::Relaxed); - return true; - } - let signature = if multi { - pipeline.and_then(|p| pipeline_signature(p, &plan.args, stride)) - } else { - matches!(kind, DRAW | INDEXED | DISPATCH | MESH) - .then(|| host_signature(kind, stride)) - .flatten() - }; - let Some(signature) = signature else { - why("no host signature"); - return false; }; - args.refresh(list, arguments, len); - if let Some((s, at)) = &counter { - s.refresh(list, *at, 4); - } - // Bounded first: the clamp binds a compute pipeline of its own. - // The clamp's view starts at the draw or dispatch argument of the - // first record (a root view has no bounds to shift). - let at = args.gpu(arguments) + u64::from(plan.arg_offset); - if !crate::indirect::bound(list, &args.buffer, at, (kind, stride, max)) { - why("not bounded (no clamp, or arguments not 4-byte aligned)"); - return false; + #[cfg(feature = "diagnostics")] + { + self.last_indirect = (args.id(), offset); } - self.host_pipeline = 0; - self.host_roots[1] = 0; let ran = match kind { DRAW | INDEXED => self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), - DISPATCH => match pipeline { - Some(p) if p.compute => { - self.bind(list, p, true); - true - } - _ => false, - }, + DISPATCH => self.bind(list, p, true), _ => false, }; - // A signature with root arguments needs the root signature it was - // made for bound. - let ran = ran - && (!multi - || pipeline.is_some_and(|p| { - self.host_roots[usize::from(kind == DISPATCH)] == p.root.as_raw() as usize - })); if !ran { - crate::indirect::done(list, &args.buffer); - #[cfg(feature = "diagnostics")] - match crate::pipeline::host_pipeline(self.pipeline as This) { - None => crate::pipeline::note_drop(self.pipeline as This), - Some(p) => why(&format!( - "prepare failed (compute {}, mesh {})", - p.compute, p.mesh - )), - } + why("prepare failed"); return false; } - if multi { - list.keep(&signature); - } #[cfg(feature = "diagnostics")] list.note_op(|| { - self.op_text( - format!("indirect kind {kind} max {max} at {arguments:#x}"), - kind == DISPATCH, - ) + self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) }); - // SAFETY: an open list with everything set; the buffers are host - // copies the list keeps alive (refresh), the signature is cached. + if kind == MESH { + self.mesh_scissor(list, true); + } + // SAFETY: an open list with everything set; the scratch buffer and + // host copies are kept alive by the list, and the signature is cached. unsafe { list.list.ExecuteIndirect( &signature, max, - &args.buffer, - args.offset(arguments), + &bounded, + at, counter.as_ref().map(|(s, _)| &s.buffer), counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; - crate::indirect::done(list, &args.buffer); + if kind == MESH { + self.mesh_scissor(list, false); + } + // The scratch buffer stays readable as arguments: the next draw of + // the window reads it with no barrier, and the next clamp moves it + // back (`crate::indirect`). if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); + if is_spread { + SPREAD[1].fetch_add(1, Ordering::Relaxed); + } } else { DRAWN.fetch_add(1, Ordering::Relaxed); } @@ -1621,43 +5319,136 @@ impl State { } } -/// A multi-argument host command signature for `p`'s root signature, -/// made once per argument layout and stride. -fn pipeline_signature( - p: &HostPipeline, - args: &[crate::indirect_plan::HostIndirectArg], - stride: u32, -) -> Option<ID3D12CommandSignature> { - let mut cache = p.signatures.lock().unwrap_or_else(|e| e.into_inner()); - if let Some((_, _, s)) = cache.iter().find(|(a, st, _)| *st == stride && a == args) { +/// The host command signature for one argument of `kind` with records +/// `stride` bytes apart (no root arguments, so no root signature), made +/// once. +/// Dispatches spread across z since the frame line last took them: direct, +/// indirect ([`victory_shader::emit::USER_DISPATCH_SPREAD`]). +pub(crate) static SPREAD: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// `COMPUTE_DISPATCH_INITIATOR` bit 5, `USE_THREAD_DIMENSIONS`: a +/// `DispatchX` whose `x`, `y`, `z` count threads, not groups; in the last +/// group of an axis the threads at or past the count are not in EXEC. +const DISPATCH_THREAD_COUNTS: u32 = 0x20; + +/// A console dispatch `(x, y, z)` with `DispatchX` flags `flags`, as host +/// groups and the thread counts the program is to keep to: per axis the +/// count where it is not a whole number of `group`-thread groups, else 0 +/// (`USER_DISPATCH_THREADS`). Without [`DISPATCH_THREAD_COUNTS`] the counts +/// are groups and go as they are. `None`: no thread along some axis, so +/// nothing to run. (Fork pull request #646, mynzjerko.) +fn dispatch_dimensions(dims: [u32; 3], group: [u32; 3], flags: u32) -> Option<([u32; 3], [u32; 3])> { + if flags & DISPATCH_THREAD_COUNTS == 0 { + return Some((dims, [0; 3])); + } + if dims.contains(&0) { + return None; + } + let groups = std::array::from_fn(|c| dims[c].div_ceil(group[c].max(1))); + let partial = std::array::from_fn(|c| { + let g = group[c].max(1); + if g > 1 && !dims[c].is_multiple_of(g) { dims[c] } else { 0 } + }); + Some((groups, partial)) +} + +/// The user-data root parameter of compute pipeline `p` whose program takes +/// the spread words, and the index of the first in it (the second follows: +/// one root-constant argument sets both); `None` for any other pipeline. +fn spreads(p: &crate::pipeline::host::HostPipeline) -> Option<(u32, u32)> { + if !spread_on() { + return None; + } + let stage = p.stages.first()?; + let (param, _) = stage.user_data?; + let kind = RootType::Other(victory_shader::emit::USER_DISPATCH_SPREAD); + let words = &stage.translated().host.user_data; + let first = words.iter().find(|u| u.root == kind && u.dword == 0)?.index; + words + .iter() + .any(|u| u.root == kind && u.dword == 1 && u.index == first + 1) + .then_some((param, first)) +} + +/// Whether dispatches past 65,535 groups in x are spread across z +/// (`VICTORY_DISPATCH_SPREAD`: on by default; `0` off, as before f93: clamped to +/// 65,535; `alt`: twenty seconds with, twenty without, in turn, each change +/// said in the log), to measure what the spread costs and shows within one +/// run. Off, a translated program's words stay 0: it runs as dispatched. +fn spread_on() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + // (Not `VICTORY_SPREAD`: `crate::spread` reads that one, for the title's + // pinned threads; run 326 alternated both under it.) + match *MODE.get_or_init(|| match std::env::var("VICTORY_DISPATCH_SPREAD").as_deref() { + Ok("0") => 0, + Ok("alt") => 2, + _ => 1, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "dispatches past 65,535 groups are spread across z from now (VICTORY_DISPATCH_SPREAD=alt): {}", + if on { "ON" } else { "off, clamped to 65,535 as before" } + ); + } + on + } + } +} + +/// The command signature of a spread dispatch: two root constants (row, +/// asked x) at `index` of root parameter `param`, then the dispatch; 20 +/// bytes a record (the clamp's spread layout). Made once per root +/// signature, parameter and index. (After upstream VIctory pull request +/// #2312.) +fn host_spread_signature(root: &ID3D12RootSignature, param: u32, index: u32) -> Option<ID3D12CommandSignature> { + type Key = (usize, u32, u32); + static MADE: std::sync::Mutex<Vec<(Key, ID3D12CommandSignature)>> = std::sync::Mutex::new(Vec::new()); + let key = (root.as_raw() as usize, param, index); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, s)) = made.iter().find(|(k, _)| *k == key) { return Some(s.clone()); } - let descs = crate::indirect::to_d3d12_descs(args); + let args = [ + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, + Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { + Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { + RootParameterIndex: param, + DestOffsetIn32BitValues: index, + Num32BitValuesToSet: 2, + }, + }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + ..Default::default() + }, + ]; let desc = D3D12_COMMAND_SIGNATURE_DESC { - ByteStride: stride, - NumArgumentDescs: descs.len() as u32, - pArgumentDescs: descs.as_ptr(), + ByteStride: 20, + NumArgumentDescs: args.len() as u32, + pArgumentDescs: args.as_ptr(), NodeMask: 0, }; let mut signature: Option<ID3D12CommandSignature> = None; - // SAFETY: `descs` lives through the call; `p.root` is a live root signature. - let result = unsafe { - crate::host::host()? - .device - .CreateCommandSignature(&desc, Some(&p.root), &mut signature) - }; + // SAFETY: two valid argument descriptions and a live root signature. + let result = unsafe { crate::host::host()?.device.CreateCommandSignature(&desc, Some(root), &mut signature) }; if let Err(e) = result { - once!(error = %e, ?args, stride, "host multi-argument command signature refused"); + once!(error = %e, param, index, "spread command signature refused"); return None; } let signature = signature?; - cache.push((args.to_vec(), stride, signature.clone())); + made.push((key, signature.clone())); Some(signature) } -/// The host command signature for one argument of `kind` with records -/// `stride` bytes apart (no root arguments, so no root signature), made -/// once. fn host_signature(kind: u32, stride: u32) -> Option<ID3D12CommandSignature> { static MADE: std::sync::Mutex<Vec<((u32, u32), ID3D12CommandSignature)>> = std::sync::Mutex::new(Vec::new()); @@ -1693,62 +5484,97 @@ fn host_signature(kind: u32, stride: u32) -> Option<ID3D12CommandSignature> { Some(signature) } -/// The tracker uses whole resources, so both planes must be read-only -/// when the depth format carries stencil. +/// Gets what a shader reads or writes through a view ready: buffer data +/// copied, textures moved to the state they need. +fn view_kind(view: &View) -> Option<ResourceType> { + match view { + View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv), + View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav), + _ => None, + } +} + +/// The format of a host view of `texture` whose description names +/// `described` (none without a description): that one, or the texture's +/// own, which is what the host gives a view without a format. +fn bound_format(texture: &ID3D12Resource, described: Option<DXGI_FORMAT>) -> u32 { + match described { + Some(format) if format.0 != 0 => format.0 as u32, + // SAFETY: a live texture. + _ => unsafe { texture.GetDesc() }.Format.0 as u32, + } +} + +/// The host state a depth view needs of its texture: the read state if the +/// view writes no plane the format has (the title's read-only flags), else +/// the write state. +/// shortcut: whole textures have one state, so a view that writes one of +/// two planes counts as writing. fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>) -> u32 { + // D16_UNORM and D32_FLOAT: depth formats without a stencil plane. + const ONE_PLANE: [i32; 2] = [55, 40]; let Some(desc) = desc else { return DEPTH_WRITE; }; - let format = if desc.Format == DXGI_FORMAT_UNKNOWN { - // SAFETY: a live texture; a default format inherits its format. - unsafe { texture.GetDesc() }.Format + let format = if desc.Format.0 == 0 { + // SAFETY: a live texture; a view without a format has its own. + unsafe { texture.GetDesc() }.Format.0 } else { - desc.Format + desc.Format.0 }; - let mut required = D3D12_DSV_FLAG_READ_ONLY_DEPTH.0; - if format != DXGI_FORMAT_D16_UNORM && format != DXGI_FORMAT_D32_FLOAT { - required |= D3D12_DSV_FLAG_READ_ONLY_STENCIL.0; + let mut needed = D3D12_DSV_FLAG_READ_ONLY_DEPTH.0; + if !ONE_PLANE.contains(&format) { + needed |= D3D12_DSV_FLAG_READ_ONLY_STENCIL.0; } - if desc.Flags.0 & required == required { + if desc.Flags.0 & needed == needed { DEPTH_READ } else { DEPTH_WRITE } } -/// Gets what a shader reads or writes through a view ready: buffer data -/// copied, textures moved to the state they need. Returns whether the view -/// also reads the draw's bound depth target. -fn readable( - list: &HostList, - u: &UsedResource, - view: &View, - read_only_depth: Option<usize>, -) -> bool { +fn readable(list: &HostList, kind: ResourceType, view: &View) { const UNORDERED_ACCESS: u32 = 0x8; let placed = crate::descriptor::host::placed_texture(view); let view = placed.as_ref().unwrap_or(view); // Buffer views read title memory: their range is copied at submission; // what shaders write through unordered access goes back to it after. - if let Some((address, len)) = crate::descriptor::host::buffer_range(view) - && len > 0 - && let Some(shadow) = crate::shadow::find(address, len) - { + if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) { shadow.refresh(list, address, len); - if u.kind == ResourceType::Uav { - shadow.gpu_writes(list, address, len); + if kind == ResourceType::Uav { + // A shader that cannot store to buffers leaves the range as + // the title has it: nothing to find afterwards. + if STORES.get() || !write_skip() { + shadow.gpu_writes(list, address, len); + } else { + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1); + crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len); + } + } } } - match (view, u.kind) { + match (view, kind) { (View::Shader(resource, _), ResourceType::Srv) => { - if let Some(t) = crate::resource::host_resource(*resource as This) + // A view the title placed, in another format, in the memory of + // a texture the host writes: that texture's texels, copied on + // the host (title memory does not have them). + let aliased = crate::resource::alias_of(*resource as This) + .is_some_and(|source| crate::texture::alias(list, *resource as This, source.get())); + if !aliased + && let Some(t) = crate::resource::host_resource(*resource as This) && crate::texture::title_written(t) { crate::texture::upload(list, *resource as This, t); } - // Keep the same read bits the depth target will request at draw time. - let samples_depth = read_only_depth == Some(*resource); - let state = if samples_depth { + // A depth texture shaders also write: what they wrote, first. + list.twin_use(*resource as This, false, false); + // The depth target the draw only tests is read in both ways at + // once: both read states, which its preparation asks for too. + let (tested, _) = TESTED_DEPTH.get(); + let state = if tested != 0 && tested == *resource { + TESTED_DEPTH.set((tested, true)); DEPTH_READ | SHADER_RESOURCE } else { SHADER_RESOURCE @@ -1766,15 +5592,124 @@ fn readable( ); } } - samples_depth } (View::Unordered(resource, _, _), ResourceType::Uav) => { #[cfg(feature = "diagnostics")] crate::capture::note_target(*resource as This); - crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); - false + // Some compute-written textures are also read by the title CPU. + list.texture_written(*resource as This); + // Unordered access to a depth texture is its colour twin's. + if !list.twin_use(*resource as This, true, true) { + crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); + } + } + _ => {} + } +} + +/// The pixel shaders whose draws get their slots listed +/// ([`State::slots_text`]): `VICTORY_LIST_SLOTS`, hash prefixes separated +/// by commas. None by default. +#[cfg(feature = "diagnostics")] +fn list_slots() -> &'static [String] { + static LIST: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new(); + LIST.get_or_init(|| { + std::env::var("VICTORY_LIST_SLOTS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_ascii_lowercase()) + .filter(|s| !s.is_empty()) + .collect() + }) +} + +/// A fingerprint of the 4 KiB of title memory at `at` (FNV-1a, 64 bits; of +/// 4 KiB of zeros it is always the same value, which `slots.py` knows), or +/// "unreadable". +#[cfg(feature = "diagnostics")] +fn print_4k(at: u64) -> String { + let mut bytes = [0u8; 4096]; + if at == 0 || !crate::host::read_into(at as *const u8, &mut bytes) { + return "unreadable".into(); + } + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + for b in bytes { + hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); + } + format!("{hash:016x}") +} + +/// The `bytes` of title memory at `at`: how many are mapped, and the +/// fingerprints of the first and the last 4 KiB (a texture's smallest +/// levels lie first, its largest last). +#[cfg(feature = "diagnostics")] +fn memory_state(at: u64, bytes: u64) -> String { + let mapped = crate::texture::mapped_bytes(at as *const u8, bytes as usize); + let last = at + bytes.saturating_sub(4096); + format!("memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", print_4k(at), print_4k(last)) +} + +/// Title texture `this` for the frame listing: its size, whether it has a +/// host copy (not made here), its staging buffer's state, whether the host +/// copied into it, and its memory ([`memory_state`]). +#[cfg(feature = "diagnostics")] +fn texture_state(this: This) -> String { + let Some((at, desc)) = crate::resource::texture_memory(this) else { + return "not a texture".into(); + }; + // SAFETY: 56 bytes in the description's layout. + let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() }; + let bytes = crate::resource::placed_bytes(&words).unwrap_or(0); + let staged = match crate::texture::staged_state(this) { + Some((uploaded, dirty)) => format!("staged=yes uploaded={uploaded} dirty={dirty}"), + None => "staged=no".into(), + }; + format!( + "{}x{} f{} levels={} host_copy={} {staged} host_written={} title_fills={} {}", + u64::from(words[4]) | u64::from(words[5]) << 32, + words[6], + words[8], + words[7] >> 16, + crate::resource::host_made(this).is_some(), + crate::texture::host_wrote(this as usize), + crate::resource::title_fills(this), + memory_state(at as u64, bytes) + ) +} + +/// A view of the title's heap for the frame listing: a texture with its +/// state ([`texture_state`]; a placed one that has no resource yet with +/// its memory alone), anything else in a few words. +#[cfg(feature = "diagnostics")] +fn view_state(view: Option<&View>) -> String { + match view { + None => "no view".into(), + Some(View::Placed(false, r, d)) if r[0] != 1 => { + let address = u64::from(d[10]) | u64::from(d[11]) << 32; + let state = match crate::resource::texture_at_made(address, r) { + Some(this) => texture_state(this), + None => format!( + "{}x{} f{} levels={} resource=none {}", + u64::from(r[4]) | u64::from(r[5]) << 32, + r[6], + r[8], + r[7] >> 16, + memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0)) + ), + }; + // (Last, so that readers of the older lines still find + // theirs: the level the view starts at, and how many it shows.) + format!("placed texture view_format={} {state} view_levels={}+{}", d[0], d[4], d[5] as i32) + } + Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => { + format!( + "texture object {r:#x} view_format={} {} view_levels={}", + d.as_ref().map_or(0, |d| d[0]), + texture_state(*r as This), + d.as_ref().map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32)) + ) } - _ => false, + Some(v) => format!("{v:?}").chars().take(80).collect(), } } @@ -1782,24 +5717,23 @@ fn readable( #[cfg(feature = "diagnostics")] fn describe(view: Option<&View>) -> String { let texture = |r: This| { - crate::resource::host_resource(r).map(|t| { + crate::resource::host_made(r).map(|t| { // SAFETY: a live resource. let d = unsafe { t.GetDesc() }; - format!( - "{}x{} f{} flags {:#x}", - d.Width, d.Height, d.Format.0, d.Flags.0 - ) + format!("{}x{} f{} flags {:#x} of {r:?}", d.Width, d.Height, d.Format.0, d.Flags.0) }) }; match view { None => "no view".into(), Some(v @ View::Shader(r, _)) => texture(*r as This) .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))), - // A buffer has no host texture: its title range, as for a shader view. - Some(v @ View::Unordered(r, ..)) => texture(*r as This).map_or_else( - || format!("uav buffer {:?}", crate::descriptor::host::buffer_range(v)), - |t| format!("uav {t}"), - ), + Some(v @ View::Unordered(r, ..)) => match texture(*r as This) { + Some(t) => format!("uav texture {t}"), + None => format!( + "uav resource {r:#x} buffer {:?}", + crate::descriptor::host::buffer_range(v) + ), + }, Some(View::Placed(u, r, d)) => format!( "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}", r[0], @@ -1859,8 +5793,12 @@ mod trace_tests { } } -/// Console rectangle list topology (expanded on vertex inputs in [`crate::primitive`]). +/// The console's own primitive topologies. +const TRIANGLE_FAN: u32 = 6; const RECTANGLES: u32 = 17; +const LINE_LOOP: u32 = 18; +const QUADS: u32 = 19; +const QUAD_STRIP: u32 = 20; /// Fixed-function state, straight onto the host list. pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) { @@ -1878,205 +5816,38 @@ pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) { unsafe { list.list.OMSetBlendFactor(factor) }; } -pub(crate) fn stencil_ref(list: &HostList, reference: u32) { - // SAFETY: an open list. - unsafe { list.list.OMSetStencilRef(reference) }; -} - -#[cfg(test)] -mod depth_tests { - use super::*; - - #[test] - fn shader_table_keeps_read_only_depth_state() { - use windows::Win32::Graphics::Dxgi::Common::{ - DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R32_FLOAT, DXGI_SAMPLE_DESC, - }; - - let Some(host) = crate::host::host() else { - return; // no host GPU here - }; - let null = std::ptr::null(); - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: 4, - Height: 4, - DepthOrArraySize: 1, - MipLevels: 1, - Format: DXGI_FORMAT_D32_FLOAT, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, - ..Default::default() - }; - let resource_iid = ID3D12Resource::IID; - let mut depth = null; - assert_eq!( - crate::resource::create_committed( - null, - (&raw const heap).cast(), - 0, - (&raw const desc).cast(), - D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32, - null.cast(), - (&raw const resource_iid).cast(), - &mut depth, - ), - crate::object::S_OK - ); - #[repr(C)] - struct ViewHeap { - desc: D3D12_DESCRIPTOR_HEAP_DESC, - placement: [u64; 2], - } - let desc = ViewHeap { - desc: D3D12_DESCRIPTOR_HEAP_DESC { - Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - NumDescriptors: 1, - Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - NodeMask: 0, - }, - placement: [0; 2], - }; - let heap_iid = ID3D12DescriptorHeap::IID; - let mut views = null; - assert_eq!( - crate::descriptor::create_heap( - null, - (&raw const desc).cast(), - (&raw const heap_iid).cast(), - &mut views, - ), - crate::object::S_OK - ); - let srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { - Format: DXGI_FORMAT_R32_FLOAT, - ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, - Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { - Texture2D: D3D12_TEX2D_SRV { - MipLevels: 1, - ..Default::default() - }, - }, - }; - let srv = crate::descriptor::heap(views).start; - crate::descriptor::create_srv(null, depth, (&raw const srv_desc).cast(), srv); - let used = UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 8, - user_data: 0, - slot: 0, - }; - - let shader_resource = (D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE - | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE) - .0 as u32; - let combined = D3D12_RESOURCE_STATE_DEPTH_READ.0 as u32 | shader_resource; - for (flags, unsampled_state, shader_state, draw_state) in [ - ( - D3D12_DSV_FLAG_READ_ONLY_DEPTH, - DEPTH_READ, - combined, - combined, - ), - ( - D3D12_DSV_FLAG_NONE, - DEPTH_WRITE, - shader_resource, - DEPTH_WRITE, - ), - ] { - let list = host.new_list().expect("host list"); - let desc = [ - DXGI_FORMAT_D32_FLOAT.0 as u32, - D3D12_DSV_DIMENSION_TEXTURE2D.0 as u32, - flags.0 as u32, - 0, - 0, - 0, - ]; - let mut slot = [0u64; 16]; - let dsv = slot.as_mut_ptr() as u64; - crate::descriptor::create_dsv(null, depth, &desc, dsv); - let mut state = State::default(); - state.set_targets(&list, &[], dsv); - state.set_heaps(&[views]); - state.set_table(false, 0, srv); - crate::list::ensure_state(&list, depth, D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32); - state.ensure_depth_state(&list); - assert!( - list.transition(depth, unsampled_state).is_none(), - "unsampled depth state for {flags:?}" - ); - state.tables(&list, &[used], false); - assert!( - list.transition(depth, shader_state).is_none(), - "shader-table state for {flags:?}" - ); - state.ensure_depth_state(&list); - assert!( - list.transition(depth, draw_state).is_none(), - "depth state for {flags:?}" - ); - list.close(); - host.execute(&[&list]); - } - let release = |object: This| { - crate::object::slot::<extern "system" fn(This) -> u32>(object, 0x10)(object) - }; - assert_eq!(release(views), 0); - assert_eq!(release(depth), 0); +/// `OMSetDepthBounds`, if the host has the test: bounds in 0..=1, the low +/// one first, as the host requires (its debug layer refuses others). +/// Ideas from upstream #849 (Xvania7 c47632fc, Raxstreams 520d629e). +pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) { + if !crate::pipeline::host::depth_bounds_supported() { + return; + } + let (min, max) = depth_range(min, max); + if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() { + // SAFETY: an open list. + unsafe { list1.OMSetDepthBounds(min, max) }; } } -#[cfg(test)] -mod clear_state_tests { - use super::*; +/// Depth bounds the host takes: NaN as the full range, each in 0..=1, in +/// order. +fn depth_range(min: f32, max: f32) -> (f32, f32) { + let unit = |x: f32, nan: f32| if x.is_nan() { nan } else { x.clamp(0.0, 1.0) }; + let (min, max) = (unit(min, 0.0), unit(max, 1.0)); + (min.min(max), max) +} - #[test] - fn clear_resets_bindings_but_keeps_dynamic_slots() { - // A synthetic slot record: no registered heap, so giving it back - // does nothing. - let dynamic = (0, 64, 3); - let mut state = State::default(); - state.pipeline = 1; - state.heaps = [2, 3]; - state.targets = vec![8]; - state.topology = 4; - state.host_pipeline = 10; - state.host_roots = [11, 12]; - state.host_heaps = [13, 14]; - state.fresh_tables = [((4, 15), dynamic.1)].into(); - state.dynamic = vec![dynamic]; - let pipeline: This = std::ptr::dangling(); - state.clear(pipeline); - assert_eq!(state.pipeline, pipeline as usize); - assert_eq!(state.heaps, [0; 2]); - assert!(state.targets.is_empty()); - assert_eq!(state.topology, 0); - assert_eq!(state.host_pipeline, 0); - assert_eq!(state.host_roots, [0; 2]); - assert_eq!(state.host_heaps, [0; 2]); - assert!(state.fresh_tables.is_empty()); - assert_eq!(state.dynamic, [dynamic]); - state.reset(std::ptr::null()); - assert!(state.dynamic.is_empty()); - } +pub(crate) fn stencil_ref(list: &HostList, reference: u32) { + #[cfg(feature = "diagnostics")] + crate::capture::op(std::ptr::from_ref(list) as usize, || format!("STENCIL REF {reference:#x}")); + // SAFETY: an open list. + unsafe { list.list.OMSetStencilRef(reference) }; } -#[cfg(all(test, feature = "diagnostics"))] -mod tests { +#[cfg(test)] +mod depth_bounds_tests { + use super::depth_range; /// Depth bounds reach the host in 0..=1 and in order. #[test] @@ -2086,232 +5857,87 @@ mod tests { assert_eq!(depth_range(f32::NAN, f32::NAN), (0.0, 1.0)); assert_eq!(depth_range(0.9, 0.1), (0.1, 0.1)); } +} + +#[cfg(test)] +mod tests { use super::*; #[test] - fn typed_null_rtv_keeps_the_next_color_slot() { - use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; - use windows::Win32::Graphics::Direct3D::{D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob}; - use windows::Win32::Graphics::Dxgi::Common::{ - DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC, - }; - use windows::core::s; - - struct Texture(This); + fn a_lone_record_opens_a_window_at_the_remembered_step() { + // (a mesh dispatch is kind 10, a draw kind 0) + let remembered = Some((7u64, 10u32, 12u32, 32u32)); + // the same buffer, kind and stride: sixteen records at the title's step + assert_eq!(jump_window(remembered, (7, 10, 12), 1 << 20), Some((32, 16))); + // never past the buffer: 100 bytes left hold three records 32 apart + assert_eq!(jump_window(remembered, (7, 10, 12), 100), Some((32, 3))); + // one record fits: nothing to open + assert_eq!(jump_window(remembered, (7, 10, 12), 40), None); + // another buffer, kind or stride, or nothing remembered: alone, as before + assert_eq!(jump_window(remembered, (8, 10, 12), 1 << 20), None); + assert_eq!(jump_window(remembered, (7, 0, 12), 1 << 20), None); + assert_eq!(jump_window(remembered, (7, 10, 16), 1 << 20), None); + assert_eq!(jump_window(None, (7, 10, 12), 1 << 20), None); + } - impl Drop for Texture { - fn drop(&mut self) { - let release = crate::object::slot::<extern "system" fn(This) -> u32>(self.0, 0x10); - release(self.0); - } + /// A bake draw names the indices in its constants, and those in the + /// records its constants give and in the one after them; not those of + /// records past the buffer, nor of one that cannot be read. + #[test] + fn a_bake_draw_names_the_indices_of_its_constants_and_records() { + let mut constants = [0u8; 0x80]; + let put = |bytes: &mut [u8], at: usize, value: u32| bytes[at..at + 4].copy_from_slice(&value.to_le_bytes()); + for (n, at) in BAKE_CONSTANT_INDICES.into_iter().enumerate() { + put(&mut constants, at, 100 + n as u32); } - - let Some(host) = crate::host::host() else { - return; // no host GPU here - }; - let device = &host.device; - let list = host.new_list().expect("host command list"); - let l = &list.list; - let format = DXGI_FORMAT_R8G8B8A8_UNORM; - let source = r#" - [RootSignature("RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)")] - float4 vs(uint id : SV_VertexID) : SV_Position { - return float4(id == 2 ? 3 : -1, id == 1 ? -3 : 1, 0, 1); - } - struct Colors { float4 red : SV_Target0; float4 green : SV_Target1; }; - Colors ps() { - Colors c; - c.red = float4(1, 0, 0, 1); - c.green = float4(0, 1, 0, 1); - return c; - } - "#; - let compile = |entry, target| { - let mut code = None; - // SAFETY: source and shader names are live, and code is our output pointer. - unsafe { - D3DCompile( - source.as_ptr().cast(), - source.len(), - s!("rtv-slot-test"), - None, - None, - entry, - target, - 0, - 0, - &mut code, - None, - ) - .expect("compile fixture shader"); + // Records 2 and 3, of 9 in all. + put(&mut constants, 0, 9); + put(&mut constants, 0x78, 2); + put(&mut constants, 0x7c, 4); + // Record `i` names 1000 + 10 i + n at its n-th place; record 3 the + // index of the constants' first once more. + let record = |i: u32| { + let mut record = [0xffu8; 0x44]; + for (n, at) in BAKE_RECORD_INDICES.into_iter().enumerate() { + put(&mut record, at, 1000 + 10 * i + n as u32); } - code.expect("fixture bytecode") - }; - let vs = compile(s!("vs"), s!("vs_5_1")); - let ps = compile(s!("ps"), s!("ps_5_1")); - // SAFETY: compiled fixture shaders and their embedded root signature are live. - let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { - let bytecode = |blob: &ID3DBlob| D3D12_SHADER_BYTECODE { - pShaderBytecode: blob.GetBufferPointer(), - BytecodeLength: blob.GetBufferSize(), - }; - let code = bytecode(&vs); - let root = device - .CreateRootSignature( - 0, - std::slice::from_raw_parts(code.pShaderBytecode.cast(), code.BytecodeLength), - ) - .expect("graphics root signature"); - let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - VS: code, - PS: bytecode(&ps), - SampleMask: u32::MAX, - RasterizerState: D3D12_RASTERIZER_DESC { - FillMode: D3D12_FILL_MODE_SOLID, - CullMode: D3D12_CULL_MODE_NONE, - DepthClipEnable: true.into(), - ..Default::default() - }, - PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - NumRenderTargets: 2, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - ..Default::default() - }; - // D3D12 requires UNKNOWN in the PSO slot that binds a null RTV. - desc.RTVFormats[1] = format; - desc.BlendState.RenderTarget[0].RenderTargetWriteMask = - D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; - let pso = device - .CreateGraphicsPipelineState(&desc) - .expect("graphics pipeline"); - (root, pso) - }; - - const SIDE: u32 = 4; - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: u64::from(SIDE), - Height: SIDE, - DepthOrArraySize: 1, - MipLevels: 1, - Format: format, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, - ..Default::default() - }; - let mut target = std::ptr::null(); - let null = std::ptr::null(); - let iid = ID3D12Resource::IID; - assert_eq!( - crate::resource::create_committed( - null, - (&raw const heap).cast(), - 0, - (&raw const desc).cast(), - D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, - null.cast(), - (&raw const iid).cast(), - &mut target, - ), - crate::object::S_OK - ); - let _target = Texture(target); - let color = crate::resource::host_resource(target).expect("color target"); - let mut slots = [[0u64; 16]; 2]; - let handles = slots.each_mut().map(|slot| slot.as_mut_ptr() as u64); - let null_desc = [ - format.0 as u32, - D3D12_RTV_DIMENSION_TEXTURE2D.0 as u32, - 0, - 0, - 0, - 0, - ]; - crate::descriptor::create_rtv(null, null, &null_desc, handles[0]); - crate::descriptor::create_rtv(null, target, null.cast(), handles[1]); - crate::list::ensure_state(&list, target, D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32); - // SAFETY: open list, live target and graphics pipeline. - unsafe { - l.ClearRenderTargetView(host.rtv(Some(color), None), &[0.0, 0.0, 1.0, 1.0], None); - l.SetGraphicsRootSignature(&root); - l.SetPipelineState(&pso); - l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - } - viewports( - &list, - &[D3D12_VIEWPORT { - Width: SIDE as f32, - Height: SIDE as f32, - MaxDepth: 1.0, - ..Default::default() - }], - ); - scissors( - &list, - &[RECT { - right: SIDE as i32, - bottom: SIDE as i32, - ..Default::default() - }], - ); - State::default().set_targets(&list, &handles, 0); - // SAFETY: complete graphics state on the open list. - unsafe { l.DrawInstanced(3, 1, 0, 0) }; - - crate::list::ensure_state(&list, target, D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32); - let (readback, footprint) = - crate::capture::read_back(device, l, color).expect("color readback"); - list.close(); - host.execute(&[&list]); - let mut mapped = std::ptr::null_mut(); - let mut pixels = Vec::new(); - // SAFETY: execution has completed and all pixels lie in the mapped footprint. - unsafe { - readback - .Map(0, None, Some(&mut mapped)) - .expect("map readback"); - for y in 0..SIDE { - for x in 0..SIDE { - let at = footprint.Offset as usize - + (y * footprint.Footprint.RowPitch + x * 4) as usize; - pixels.push(mapped.cast::<u8>().add(at).cast::<[u8; 4]>().read()); - } + if i == 3 { + put(&mut record, 0, 100); } - readback.Unmap(0, None); - } - assert_eq!(pixels, [[0, 255, 0, 255]; (SIDE * SIDE) as usize]); + Some(record) + }; + let (named, records) = bake_named(&constants, 9, record); + assert_eq!(records, (2, 3), "two records walked, and the one after them looked at"); + let mut expected: Vec<u32> = (100..105).collect(); + expected.extend((1020..1025).chain(1031..1035).chain(1040..1045)); + assert_eq!(named, expected); + // The buffer ends with record 3: the one after is not there. + assert_eq!(bake_named(&constants, 4, record).1, (2, 2)); + // A record that cannot be read ends the walk. + let (named, records) = bake_named(&constants, 9, |i| if i == 3 { None } else { record(i) }); + assert_eq!(records, (2, 1)); + assert!(named.contains(&1024) && !named.contains(&1040)); + // No records at all: the constants' own. + put(&mut constants, 0x7c, 2); + assert_eq!(bake_named(&constants, 0, record), ((100..105).collect(), (0, 0))); } -} -/// `OMSetDepthBounds`, if the host has the test: bounds in 0..=1, the low -/// one first, as the host requires (its debug layer refuses others). -pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) { - if !crate::pipeline::host::depth_bounds_supported() { - return; - } - let (min, max) = depth_range(min, max); - if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() { - // SAFETY: an open list. - unsafe { list1.OMSetDepthBounds(min, max) }; + /// Fork pull request #646: a `DispatchX` with bit 5 counts threads. + #[test] + fn a_dispatch_counting_threads_runs_the_groups_that_hold_them() { + // Without bit 5 (plain Dispatch, or only the 32-lane bit 0x8000): groups. + assert_eq!(dispatch_dimensions([48, 1, 1], [64, 1, 1], 0), Some(([48, 1, 1], [0; 3]))); + assert_eq!(dispatch_dimensions([48, 1, 1], [64, 1, 1], 0x8000), Some(([48, 1, 1], [0; 3]))); + // Threads: the groups that hold them, and the count where the last is cut. + assert_eq!(dispatch_dimensions([48, 1, 1], [64, 1, 1], 0x20), Some(([1, 1, 1], [48, 0, 0]))); + assert_eq!(dispatch_dimensions([1, 1, 1], [64, 1, 1], 0x8020), Some(([1, 1, 1], [1, 0, 0]))); + assert_eq!(dispatch_dimensions([65, 1, 1], [64, 1, 1], 0x20), Some(([2, 1, 1], [65, 0, 0]))); + // The builder's box stage: 5,348 nodes of one thread each in groups of 64. + assert_eq!(dispatch_dimensions([5348, 1, 1], [64, 1, 1], 0x20), Some(([84, 1, 1], [5348, 0, 0]))); + // A whole number of groups needs no count. + assert_eq!(dispatch_dimensions([128, 1, 1], [64, 1, 1], 0x20), Some(([2, 1, 1], [0; 3]))); + assert_eq!(dispatch_dimensions([10, 16, 5], [8, 8, 4], 0x20), Some(([2, 2, 2], [10, 0, 5]))); + // No thread along an axis: nothing runs. + assert_eq!(dispatch_dimensions([0, 1, 1], [64, 1, 1], 0x20), None); } } - -/// Depth bounds the host takes: NaN as the full range, each in 0..=1, in -/// order. -fn depth_range(min: f32, max: f32) -> (f32, f32) { - let unit = |x: f32, nan: f32| if x.is_nan() { nan } else { x.clamp(0.0, 1.0) }; - let (min, max) = (unit(min, 0.0), unit(max, 1.0)); - (min.min(max), max) -} - diff --git a/crates/victory-gpu/src/drvwatch.rs b/crates/victory-gpu/src/drvwatch.rs new file mode 100644 index 0000000000..c8530f05cb --- /dev/null +++ b/crates/victory-gpu/src/drvwatch.rs @@ -0,0 +1,196 @@ +//! The graphics driver's errors, seen as the system records them. +//! +//! A card is not lost out of nothing. Every loss of runs 201, 204, 208 and +//! 224 has entries of the card's driver in the system's event log (NVIDIA: +//! provider `nvlddmkm`, event 153, "Error occurred on GPUID") from 2.7 to +//! 6.3 seconds BEFORE the device was removed, several of them; run 210 has +//! three and kept its device; the runs with no such entry lost nothing. +//! Nothing in the layer saw them: the first it knew was the device gone. +//! +//! Here the layer subscribes to that log. Each entry of a display driver +//! is written to our log when the system records it, with our own clock, +//! so it can be laid beside what the layer did in that moment; it is +//! counted; and the first one trips a switch ([`tripped`]) that the paths +//! under suspicion ask before they run (the draw windows of `crate::draw` +//! turn themselves off for the rest of the run). So a driver error costs a +//! slower frame from then on, and not the card. +//! +//! On by default; `VICTORY_DRIVER_WATCH=0` subscribes to nothing. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; + +use windows_sys::Win32::System::EventLog::{ + EVT_HANDLE, EVT_SUBSCRIBE_NOTIFY_ACTION, EvtSubscribe, EvtSubscribeActionDeliver, EvtSubscribeToFutureEvents, +}; + +/// Entries of a display driver seen since the start. +static ERRORS: AtomicU64 = AtomicU64::new(0); +/// Whether one was seen ([`tripped`]). +static TRIPPED: AtomicBool = AtomicBool::new(false); + +/// Whether the card's driver has reported an error in this run: what could +/// have caused it stops for the rest of the run. +pub(crate) fn tripped() -> bool { + TRIPPED.load(Relaxed) +} + +/// Driver errors seen since the start. +pub(crate) fn errors() -> u64 { + ERRORS.load(Relaxed) +} + +/// An entry of a display driver was recorded. +fn seen() { + let n = ERRORS.fetch_add(1, Relaxed) + 1; + let first = !TRIPPED.swap(true, Relaxed); + tracing::error!( + n, + "the graphics driver reported an error to the system's event log{}", + if first { + ": from now on the paths under suspicion are off for this run (draw windows clamp each record again)" + } else { + "" + } + ); +} + +unsafe extern "system" fn on_event(action: EVT_SUBSCRIBE_NOTIFY_ACTION, _context: *const core::ffi::c_void, _event: EVT_HANDLE) -> u32 { + if action == EvtSubscribeActionDeliver { + seen(); + } + 0 +} + +/// The entries [`start`] subscribes to: the display drivers' and the +/// `Display` source's, at levels 1-3 (critical, error, warning). +const QUERY: &str = "*[System[Provider[@Name='nvlddmkm' or @Name='amdkmdag' or @Name='amdwddmg' or @Name='igfx' \ + or @Name='igfxn' or @Name='Display'] and (Level=1 or Level=2 or Level=3)]]"; + +/// Subscribes to the display drivers' entries in the system's event log, +/// once. Entries from before the call are not delivered. +pub(crate) fn start() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + if std::env::var_os("VICTORY_DRIVER_WATCH").is_some_and(|v| v == "0") { + return; + } + let wide = |s: &str| -> Vec<u16> { s.encode_utf16().chain(std::iter::once(0)).collect() }; + let channel = wide("System"); + // The kernel drivers of the three vendors, and the system's own + // "display driver stopped responding" source (4101, a warning). + // Critical, error and warning entries only: the `Display` source + // also writes information entries that are no fault, among them + // 4125, the Auto HDR notice ("Good news-… has been enhanced"), + // which Windows 11 writes when a game's window first shows. On a + // machine with Auto HDR on it tripped the switch a second into + // every run, and the draw windows were off from the start. + let query = wide(QUERY); + // SAFETY: valid strings for the call's length; the callback is a + // plain function that touches only statics; the subscription is + // kept for the life of the process. + let subscription = unsafe { + EvtSubscribe( + 0, + std::ptr::null_mut(), + channel.as_ptr(), + query.as_ptr(), + 0, + std::ptr::null(), + Some(on_event), + EvtSubscribeToFutureEvents, + ) + }; + if subscription == 0 { + tracing::warn!( + error = %std::io::Error::last_os_error(), + "no subscription to the system's event log: the graphics driver's errors are not seen as they happen" + ); + } else { + tracing::info!( + "the graphics driver's errors in the system's event log are watched: each is logged here as it is recorded, and \ + the first turns the paths under suspicion off (VICTORY_DRIVER_WATCH=0: not watched)" + ); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_first_error_trips_the_switch_and_every_one_is_counted() { + // (Other tests do not touch these statics.) + assert!(!tripped()); + assert_eq!(errors(), 0); + seen(); + assert!(tripped()); + seen(); + assert_eq!(errors(), 2); + assert!(tripped()); + } + + /// End to end, by hand (`--ignored`): an entry written to the + /// Application log under a name of our own reaches a subscription made + /// the same way as [`start`]'s, within a second. It leaves one + /// information entry in that log. + #[test] + #[ignore = "writes one entry to the Application event log: run it by name with --ignored"] + fn an_entry_written_reaches_a_subscription() { + use windows_sys::Win32::System::EventLog::{ + DeregisterEventSource, EVENTLOG_INFORMATION_TYPE, EvtClose, RegisterEventSourceW, ReportEventW, + }; + static GOT: AtomicU64 = AtomicU64::new(0); + unsafe extern "system" fn got(action: EVT_SUBSCRIBE_NOTIFY_ACTION, _: *const core::ffi::c_void, _: EVT_HANDLE) -> u32 { + if action == EvtSubscribeActionDeliver { + GOT.fetch_add(1, Relaxed); + } + 0 + } + let wide = |s: &str| -> Vec<u16> { s.encode_utf16().chain(std::iter::once(0)).collect() }; + let (channel, query) = (wide("Application"), wide("*[System[Provider[@Name='victory-drvwatch-test']]]")); + // SAFETY: as in `start`. + let subscription = unsafe { + EvtSubscribe(0, std::ptr::null_mut(), channel.as_ptr(), query.as_ptr(), 0, std::ptr::null(), Some(got), EvtSubscribeToFutureEvents) + }; + assert_ne!(subscription, 0, "{}", std::io::Error::last_os_error()); + let (name, text) = (wide("victory-drvwatch-test"), wide("a test entry of the VIctory layer's driver watch")); + // SAFETY: a source of our own name, one string, no data. + unsafe { + let source = RegisterEventSourceW(std::ptr::null(), name.as_ptr()); + assert!(!source.is_null(), "{}", std::io::Error::last_os_error()); + let strings = [text.as_ptr()]; + assert_ne!( + ReportEventW(source, EVENTLOG_INFORMATION_TYPE, 0, 1, std::ptr::null_mut(), 1, 0, strings.as_ptr(), std::ptr::null()), + 0, + "{}", + std::io::Error::last_os_error() + ); + DeregisterEventSource(source); + } + let started = std::time::Instant::now(); + while GOT.load(Relaxed) == 0 && started.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let after = started.elapsed(); + // SAFETY: our own subscription. + unsafe { EvtClose(subscription) }; + assert_eq!(GOT.load(Relaxed), 1, "the entry was not delivered in 5 s"); + eprintln!("delivered after {} ms", after.as_millis()); + } + + /// The subscription itself: the system accepts the channel and the + /// query (a query it cannot read is refused at once). + #[test] + fn the_system_takes_the_subscription() { + let wide = |s: &str| -> Vec<u16> { s.encode_utf16().chain(std::iter::once(0)).collect() }; + let (channel, query) = (wide("System"), wide(QUERY)); + // SAFETY: as in `start`. + let subscription = unsafe { + EvtSubscribe(0, std::ptr::null_mut(), channel.as_ptr(), query.as_ptr(), 0, std::ptr::null(), Some(on_event), EvtSubscribeToFutureEvents) + }; + assert_ne!(subscription, 0, "{}", std::io::Error::last_os_error()); + // SAFETY: our own subscription. + unsafe { windows_sys::Win32::System::EventLog::EvtClose(subscription) }; + } +} diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs index c7f7c45f27..b0abf4d4cc 100644 --- a/crates/victory-gpu/src/dxgi.rs +++ b/crates/victory-gpu/src/dxgi.rs @@ -219,7 +219,66 @@ struct Mode { } const _: () = assert!(size_of::<Mode>() == 32); -/// The console's mode list: one 4K mode at 60 Hz (Grand Theft Auto VI looks +/// The size of the display the console reports: `VICTORY_DISPLAY_MODE=WxH` +/// if set (as a console reports the television it is plugged into: a +/// Series X on a 1080p set lists a 1080p mode), else 3840x2160; times +/// [`render_scale`]. +/// shortcut: not yet the host display's own size by default; make it so +/// once a title is seen to render for the mode it is given. +fn display_size() -> (u32, u32) { + static SIZE: std::sync::OnceLock<(u32, u32)> = std::sync::OnceLock::new(); + *SIZE.get_or_init(|| { + let (w, h) = asked_size(); + let scale = render_scale(); + // Even sizes, and never below the smallest mode a title expects. + let size = (((w * scale / 100) & !1).max(640), ((h * scale / 100) & !1).max(360)); + tracing::info!( + width = size.0, + height = size.1, + scale, + "display mode reported to the title (VICTORY_RENDER_SCALE: percent of the screen it renders at)" + ); + size + }) +} + +/// `VICTORY_DISPLAY_MODE`'s size, else 3840x2160: the size frames are shown at. +fn asked_size() -> (u32, u32) { + let asked = std::env::var("VICTORY_DISPLAY_MODE").ok().and_then(|v| { + let (w, h) = v.trim().split_once(['x', 'X'])?; + Some((w.trim().parse::<u32>().ok()?, h.trim().parse::<u32>().ok()?)) + }); + match asked { + Some((w, h)) if (640..=7680).contains(&w) && (360..=4320).contains(&h) => (w, h), + _ => (3840, 2160), + } +} + +/// Render scale (Try 4.2, idea 6, after the DLSS/FSR enabler mods): the +/// percent of the screen's size the title is told its display has +/// (`VICTORY_RENDER_SCALE`, 50 to 100; 100, the whole size, by default). +/// The title renders everything at that smaller size, and the present +/// scales its frames up to the screen with a sharp filter (Catmull-Rom +/// with FSR's ring clamp, and a little sharpening): 67 renders 44% of the +/// pixels, 50 a quarter. +pub(crate) fn render_scale() -> u32 { + static SCALE: std::sync::OnceLock<u32> = std::sync::OnceLock::new(); + *SCALE.get_or_init(|| { + std::env::var("VICTORY_RENDER_SCALE") + .ok() + .and_then(|v| v.trim().trim_end_matches('%').parse::<u32>().ok()) + .map_or(100, |s| s.clamp(50, 100)) + }) +} + +/// The size frames are shown at when the title renders smaller than the +/// screen ([`render_scale`] below 100); `None` when it renders at it. +#[cfg(windows)] +pub(crate) fn output_size() -> Option<(u32, u32)> { + (render_scale() < 100).then(asked_size) +} + +/// The console's mode list: one 4K mode at 60 Hz (the title looks /// for a 120 Hz one to allow 120 Hz frame intervals). /// shortcut: fixed mode, not the host display's; report the host's rates if /// a title paces by them. @@ -242,9 +301,10 @@ extern "system" fn modes( return MORE_DATA; } *count = 1; + let (width, height) = display_size(); let mode = Mode { - width: 3840, - height: 2160, + width, + height, refresh: [60, 1], format: 0, scanlines: 1, // progressive diff --git a/crates/victory-gpu/src/external.rs b/crates/victory-gpu/src/external.rs new file mode 100644 index 0000000000..91d85c0499 --- /dev/null +++ b/crates/victory-gpu/src/external.rs @@ -0,0 +1,76 @@ +//! Host work that a host library records into a title's command list in +//! place of a console one (the host's FidelityFX upscaler, say): the host +//! device, a title texture's host copy in the state the library is told, +//! and the host list itself. +//! +//! From Belobug/VIctory cd8dfc06 (ported there from DexNom/VIctory +//! ab34a8b2); here on the plain host list of each title list (Try 6.10). + +use windows::Win32::Graphics::Direct3D12::{ID3D12Device, ID3D12GraphicsCommandList, ID3D12Resource}; + +use crate::object::Object; + +/// The host D3D12 device, created on first use; `None` without a host GPU. +pub fn host_device() -> Option<ID3D12Device> { + crate::host::host().map(|h| h.device.clone()) +} + +/// The active host list for one synchronous external recording call. +pub struct Recording<'a>(&'a crate::host::HostList); + +impl Recording<'_> { + /// Move a title texture to the state the provider will see. The list + /// holds the backing resource through submission. + pub fn texture(&self, resource: *const Object, state: u32) -> Option<(ID3D12Resource, u32)> { + let texture = crate::resource::host_resource(resource)?.clone(); + crate::list::ensure_state(self.0, resource, state); + let state = crate::host::legal_state(&texture, state); + Some((texture, state)) + } + + /// Prepare aliases, uploads and depth twins as for a compute read. + pub fn prepare_input(&self, resource: *const Object) -> Option<()> { + let texture = crate::resource::host_resource(resource)?.clone(); + let aliased = crate::resource::alias_of(resource) + .is_some_and(|source| crate::texture::alias(self.0, resource, source.get())); + if !aliased && crate::texture::title_written(&texture) { + crate::texture::upload(self.0, resource, &texture); + } + let _ = self.0.twin_use(resource, false, false); + Some(()) + } + + /// The host command list the provider records into. + pub fn commands(&self) -> &ID3D12GraphicsCommandList { + &self.0.list + } +} + +/// The producer recorded its output on the host's command list. +pub fn output_written(resource: *const Object) { + crate::texture::host_written(resource); +} + +/// Settle submitted title work before releasing a provider's private GPU +/// resources. +pub fn finish_submitted() { + crate::queue::before_sync(); + crate::host::settle_for_fence(); +} + +/// Runs `f` with the host list behind the title list `list` (open for +/// recording); `None` without one. What `f` binds (descriptor heaps, root +/// signatures, pipeline) is replaced before the list's next draw or +/// dispatch: the draw state is replayed afterwards, as after our own +/// upscale passes (`list::upscale_temporal`). +pub fn record<R>(list: *const Object, f: impl FnOnce(&Recording<'_>) -> R) -> Option<R> { + if list.is_null() { + return None; + } + let mut out = None; + crate::list::with_state(list, |host, state| { + out = Some(f(&Recording(host))); + state.replay(host); + }); + out +} diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 134f4b43a3..b820335502 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -1,21 +1,13 @@ -//! Fences: a 64-bit value and the events and queues waiting for it. Three -//! things move a value: the title's CPU signals, our queues' signals (a -//! queue's work runs to completion before its signal, so a queue not held -//! back by a wait signals at once) and bottom-of-pipe writes a command list -//! makes at the fence's GPU address. All three wake the waits, so an -//! event, a blocking wait or a queue's wait ends once the value it asked -//! for is reached, whichever moved it. +//! Fences: a 64-bit value and the events waiting for it. Nothing runs on a +//! GPU yet, so only signals (the title's, later our queues') move one. #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::collections::BTreeMap; use std::ffi::c_void; +use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex, MutexGuard, Weak}; -use std::time::{Duration, Instant}; -use crate::object::{self, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid}; +use crate::object::{self, E_NOTIMPL, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; -use crate::timeline::Timeline; pub(crate) const FENCE_IIDS: [Iid; 4] = [ guid( @@ -38,113 +30,9 @@ struct Fence { flags: u32, /// Events to set once the value reaches theirs (handles as integers). waiters: Mutex<Vec<(u64, usize)>>, - /// Wakes blocking waits (`SetEventOnCompletion` with a null event) - /// whenever the value moves. - moved: Condvar, - /// Queues holding work back until the value reaches theirs - /// (`ID3D12CommandQueue::Wait`). Locked after `waiters`, never before. - queues: Mutex<Vec<(u64, Weak<Timeline>)>>, -} - -impl Drop for Fence { - fn drop(&mut self) { - live().remove(&((&raw const self.value) as usize)); - } -} - -/// Live fences by the address of their value (their GPU address), for -/// bottom-of-pipe writes that land on one. Locked before a fence's -/// `waiters`, never after. -static LIVE: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); - -fn live() -> MutexGuard<'static, BTreeMap<usize, usize>> { - LIVE.lock().unwrap_or_else(|e| e.into_inner()) -} - -/// How often a blocking wait looks at the value without being woken (a -/// value moved by a path we do not see), and how long it waits before -/// saying it is stuck. -const RECHECK: Duration = Duration::from_millis(100); -const STALL: Duration = Duration::from_secs(5); -/// How often the background watcher re-checks live fences while at least one -/// event or queue wait is pending (for direct CPU/shader memory writes). -const WATCH_POLL: Duration = Duration::from_millis(10); - -struct Watcher { - /// Incremented whenever an event or queue wait is added. Pure leaf lock: - /// never held while acquiring `LIVE`, fence locks, or a timeline lock. - generation: Mutex<u64>, - added: Condvar, -} - -static WATCHER: Watcher = Watcher { - generation: Mutex::new(0), - added: Condvar::new(), -}; - -fn watch_notify() { - static THREAD: std::sync::Once = std::sync::Once::new(); - { - let mut g = WATCHER.generation.lock().unwrap_or_else(|e| e.into_inner()); - *g = g.wrapping_add(1); - WATCHER.added.notify_one(); - } - THREAD.call_once(|| { - let _ = std::thread::Builder::new() - .name("victory-fence-watch".into()) - .spawn(watch_loop); - }); -} - -fn watch_loop() { - loop { - let seen = *WATCHER.generation.lock().unwrap_or_else(|e| e.into_inner()); - let (woken, any_waiting) = scan_live_fences(); - if !woken.is_empty() { - run_held(woken); - continue; - } - let g = WATCHER.generation.lock().unwrap_or_else(|e| e.into_inner()); - if *g != seen { - continue; - } - if any_waiting { - drop( - WATCHER - .added - .wait_timeout(g, WATCH_POLL) - .unwrap_or_else(|e| e.into_inner()), - ); - } else { - drop(WATCHER.added.wait(g).unwrap_or_else(|e| e.into_inner())); - } - } -} - -/// Checks every live fence for event or queue waits whose value has been -/// reached outside `Signal` / bottom-of-pipe writes (for example a CPU write -/// to the fence's memory). -fn scan_live_fences() -> (Vec<Arc<Timeline>>, bool) { - let live = live(); - let mut woken = Vec::new(); - let mut any_waiting = false; - for &ptr in live.values() { - // SAFETY: registered fences stay alive until `Fence::drop`, which - // takes the `LIVE` lock we hold here. - let fence = unsafe { &*(ptr as *const Fence) }; - let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); - let mut queues = fence.queues.lock().unwrap_or_else(|e| e.into_inner()); - if waiters.is_empty() && queues.is_empty() { - continue; - } - let (more, moved) = wake_locked(fence, &mut waiters, &mut queues); - if moved { - fence.moved.notify_all(); - } - woken.extend(more); - any_waiting |= !waiters.is_empty() || !queues.is_empty(); - } - (woken, any_waiting) + /// For [`pace`]: when each wait above was asked for. + #[cfg(all(windows, feature = "diagnostics"))] + asked: Mutex<Vec<pace::Asked>>, } fn fence<'a>(this: This) -> &'a Fence { @@ -165,13 +53,9 @@ pub(crate) extern "system" fn create( value: AtomicU64::new(initial), flags, waiters: Mutex::new(Vec::new()), - moved: Condvar::new(), - queues: Mutex::new(Vec::new()), + #[cfg(all(windows, feature = "diagnostics"))] + asked: Mutex::new(Vec::new()), }); - let at = (&raw const fence.value) as usize; - live().insert(at, (&raw const *fence) as usize); - // Dropped (and so unregistered) here if the title asked for an - // interface a fence does not have. object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out) } @@ -196,7 +80,7 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT extern "system" fn release(this: This) -> u32 { object::release_boxed::<Fence>(this) } -extern "system" fn completed(this: This) -> u64 { +pub(crate) extern "system" fn completed(this: This) -> u64 { fence(this).value.load(Ordering::Acquire) } extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT { @@ -206,174 +90,217 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c if !event.is_null() { set_event(event as usize); } + #[cfg(all(windows, feature = "diagnostics"))] + pace::ready(); return S_OK; } - if !event.is_null() { - waiters.push((value, event as usize)); - drop(waiters); - watch_notify(); - return S_OK; - } - // A null event: block until the value is reached, as D3D12 does. - let started = Instant::now(); - let mut warned = Duration::ZERO; - while fence.value.load(Ordering::Acquire) < value { - waiters = fence - .moved - .wait_timeout(waiters, RECHECK) - .unwrap_or_else(|e| e.into_inner()) - .0; - let waited = started.elapsed(); - if waited >= warned + STALL { - warned = waited; - tracing::warn!( - value, - completed = fence.value.load(Ordering::Acquire), - seconds = waited.as_secs(), - "blocking fence wait still waiting" - ); + #[cfg(all(windows, feature = "diagnostics"))] + pace::waits(this, &fence.asked, value, fence.value.load(Ordering::Acquire)); + if event.is_null() { + // With submissions sent to the card and not waited for + // (`crate::host::late`) the signal may be behind them: they are + // settled, which sets it. + #[cfg(windows)] + if crate::host::late() { + drop(waiters); + crate::host::settle_for_fence(); + if fence.value.load(Ordering::Acquire) >= value { + return S_OK; + } + tracing::warn!(value, "blocking fence wait not implemented"); + return E_NOTIMPL; } + // shortcut: a null event means "block until reached"; nothing can + // reach it while no GPU work runs, so fail instead of hanging. + tracing::warn!(value, "blocking fence wait not implemented"); + return E_NOTIMPL; } + waiters.push((value, event as usize)); S_OK } -pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { +/// Moves the fence to `value` and sets the events that waited for it. +pub(crate) fn set(this: This, value: u64) { let fence = fence(this); - let waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); + let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); fence.value.store(value, Ordering::Release); - let queues = wake(fence, waiters); - run_held(queues); - S_OK -} - -/// Wakes any events and queues on `fence` whose value has been reached; -/// returns the timelines to resume once locks are dropped and whether -/// anything changed. -#[must_use] -fn wake_locked( - fence: &Fence, - waiters: &mut Vec<(u64, usize)>, - queues: &mut Vec<(u64, Weak<Timeline>)>, -) -> (Vec<Arc<Timeline>>, bool) { - let value = fence.value.load(Ordering::Acquire); - let mut moved = false; + #[cfg(all(windows, feature = "diagnostics"))] + pace::reached(this, &fence.asked, value); waiters.retain(|&(wanted, event)| { let reached = wanted <= value; if reached { set_event(event); - moved = true; } !reached }); - let mut woken = Vec::new(); - queues.retain(|(wanted, queue)| { - if *wanted <= value { - woken.extend(queue.upgrade()); - moved = true; - false - } else { - queue.strong_count() > 0 - } - }); - (woken, moved) } - -/// Sets the events whose value the fence has reached, wakes the blocking -/// waits and returns the queues to wake, for [`run_held`] once no fence -/// lock is held. -#[must_use] -fn wake(fence: &Fence, mut waiters: MutexGuard<'_, Vec<(u64, usize)>>) -> Vec<Arc<Timeline>> { - let mut queues = fence.queues.lock().unwrap_or_else(|e| e.into_inner()); - let (woken, _) = wake_locked(fence, &mut waiters, &mut queues); - fence.moved.notify_all(); - woken +pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { + set(this, value); + // A queue may have waited for it: what it held runs now. + #[cfg(windows)] + crate::queue::release_held(false); + S_OK } -/// Runs the work queues held back until a value now reached. With no fence -/// lock held: the work may move fences itself. -fn run_held(queues: Vec<Arc<Timeline>>) { - for queue in queues { - queue.wake(); - } +extern "system" fn creation_flags(this: This) -> u32 { + fence(this).flags +} +/// Where the value lives (GPU addresses are CPU addresses). +extern "system" fn gpu_address(this: This) -> u64 { + (&raw const fence(this).value) as u64 } -/// Queues a bottom-of-pipe write woke, to run once the writer holds no -/// lock: their work submits lists itself (`Host::execute`'s lock). -#[derive(Default)] -#[must_use = "run the woken queues once no lock is held"] -pub(crate) struct Woken(Vec<Arc<Timeline>>); - -impl Woken { - pub(crate) fn add(&mut self, other: Woken) { - self.0.extend(other.0); +/// How the title paces itself on its fences, measured (diagnostics +/// builds): which value it waits for, how long until our line gets the +/// fence there, and how many frames lie between the title's `Signal` on +/// its queue and the fence being set. Run 233 put presents behind the +/// line and the frame did not get shorter: the title waited somewhere +/// else, and this says for what. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) mod pace { + use std::sync::Mutex; + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + use std::time::Instant; + + use crate::object::This; + + pub(crate) struct Asked { + value: u64, + at: Instant, + frame: u64, + thread: u32, } - pub(crate) fn run(self) { - run_held(self.0); + /// The title's `Signal` calls on a queue not yet at the fence: + /// fence, value, when, frame. + static QUEUED: Mutex<Vec<(usize, u64, Instant, u64)>> = Mutex::new(Vec::new()); + /// The thread that presents. + static RENDER: AtomicU32 = AtomicU32::new(0); + /// Since the last line: waits already met; waits not met; of those, + /// the render thread's; reached waits, their microseconds, their + /// frames between; the render thread's reached waits and microseconds; + /// signals set, their microseconds since the title's call, their + /// frames between. + static N: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11]; + static SAID: AtomicU64 = AtomicU64::new(0); + static LINE_AT: AtomicU64 = AtomicU64::new(0); + + /// Whether events are said one by one now: four seconds of every two + /// minutes of the wall clock, the same seconds in which the loader says + /// the title's `mwaitx` waits (`console_insn`), to lay the two side by side. + fn detail_now() -> bool { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).is_ok_and(|d| d.as_secs() % 120 < 4) } -} -/// A reference to a fence held by a queue's work, given back on drop. -pub(crate) struct Held(object::Held); - -impl Held { - pub(crate) fn new(this: This) -> Held { - Held(object::Held::new(this)) + fn thread() -> u32 { + // SAFETY: a plain query. + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } } - pub(crate) fn reached(&self, value: u64) -> bool { - fence(self.0.get()).value.load(Ordering::Acquire) >= value + pub(super) fn ready() { + N[0].fetch_add(1, Ordering::Relaxed); } - pub(crate) fn signal(&self, value: u64) { - signal(self.0.get(), value); + pub(super) fn waits(fence: This, asked: &Mutex<Vec<Asked>>, value: u64, now: u64) { + let thread = thread(); + let render = thread == RENDER.load(Ordering::Relaxed); + N[1].fetch_add(1, Ordering::Relaxed); + if render { + N[2].fetch_add(1, Ordering::Relaxed); + } + let frame = crate::queue::presented(); + if detail_now() || SAID.fetch_add(1, Ordering::Relaxed) < 48 { + tracing::info!( + "pace: the title waits for fence {fence:?} value {value} (it is at {now}) in frame {frame}, on {}", + if render { "the render thread".to_string() } else { format!("thread {thread}") } + ); + } + let mut asked = asked.lock().unwrap_or_else(|e| e.into_inner()); + if asked.len() < 4096 { + asked.push(Asked { value, at: Instant::now(), frame, thread }); + } } - /// Whether the value is reached; if not, `queue` is woken once it is. - /// Checked under the lock a signal takes, so no signal is missed. - pub(crate) fn wait_on_gpu(&self, value: u64, queue: &Arc<Timeline>) -> bool { - let fence = fence(self.0.get()); - let mut queues = fence.queues.lock().unwrap_or_else(|e| e.into_inner()); - if fence.value.load(Ordering::Acquire) >= value { - return true; - } - let queue = Arc::downgrade(queue); - if !queues.iter().any(|(v, q)| *v == value && q.ptr_eq(&queue)) { - queues.push((value, queue)); + /// The title called `Signal` for `fence` on a queue. + pub(crate) fn signal_called(fence: usize, value: u64) { + let mut queued = QUEUED.lock().unwrap_or_else(|e| e.into_inner()); + if queued.len() < 4096 { + queued.push((fence, value, Instant::now(), crate::queue::presented())); } - drop(queues); - watch_notify(); - false } -} -/// After a bottom-of-pipe write of `bytes` at `at`: wakes the waits of a -/// fence whose value the write touched, and returns its held queues. -pub(crate) fn written(at: usize, bytes: usize) -> Woken { - let end = at.saturating_add(bytes); - let live = live(); - let Some((&value_at, &fence)) = live.range(..end).next_back() else { - return Woken::default(); - }; - if value_at + size_of::<u64>() <= at { - return Woken::default(); + pub(super) fn reached(fence: This, asked: &Mutex<Vec<Asked>>, value: u64) { + let frame = crate::queue::presented(); + let render = RENDER.load(Ordering::Relaxed); + { + let mut queued = QUEUED.lock().unwrap_or_else(|e| e.into_inner()); + queued.retain(|&(f, v, at, called)| { + let done = f == fence as usize && v <= value; + if done { + N[8].fetch_add(1, Ordering::Relaxed); + N[9].fetch_add(at.elapsed().as_micros() as u64, Ordering::Relaxed); + N[10].fetch_add(frame.saturating_sub(called), Ordering::Relaxed); + if detail_now() || SAID.fetch_add(1, Ordering::Relaxed) < 48 { + tracing::info!( + "pace: fence {fence:?} is set to {v}, {:.1} ms after the title's Signal for it (called in frame {called}, set in frame {frame})", + at.elapsed().as_micros() as f64 / 1e3 + ); + } + } + !done + }); + } + let mut asked = asked.lock().unwrap_or_else(|e| e.into_inner()); + asked.retain(|a| { + let done = a.value <= value; + if done { + let us = a.at.elapsed().as_micros() as u64; + N[3].fetch_add(1, Ordering::Relaxed); + N[4].fetch_add(us, Ordering::Relaxed); + N[5].fetch_add(frame.saturating_sub(a.frame), Ordering::Relaxed); + if a.thread == render { + N[6].fetch_add(1, Ordering::Relaxed); + N[7].fetch_add(us, Ordering::Relaxed); + } + if detail_now() || SAID.fetch_add(1, Ordering::Relaxed) < 48 { + tracing::info!( + "pace: fence {fence:?} reached {} {:.1} ms after the wait for it (asked in frame {}, reached in frame {frame})", + a.value, + us as f64 / 1e3, + a.frame + ); + } + } + !done + }); } - // SAFETY: registered fences are alive until their drop, which takes - // the registry lock we hold. - let fence = unsafe { &*(fence as *const Fence) }; - let queues = wake( - fence, - fence.waiters.lock().unwrap_or_else(|e| e.into_inner()), - ); - drop(live); - Woken(queues) -} -extern "system" fn creation_flags(this: This) -> u32 { - fence(this).flags -} -/// Where the value lives (GPU addresses are CPU addresses). -extern "system" fn gpu_address(this: This) -> u64 { - (&raw const fence(this).value) as u64 + /// Once a frame, on the thread that presents: a line every 256 frames. + pub(crate) fn frame() { + RENDER.store(thread(), Ordering::Relaxed); + let frame = crate::queue::presented(); + let last = LINE_AT.load(Ordering::Relaxed); + if frame < last + 256 { + return; + } + LINE_AT.store(frame, Ordering::Relaxed); + let n: Vec<f64> = N.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64).collect(); + let frames = (frame - last).max(1) as f64; + let per = |a: f64, b: f64| if b > 0.0 { a / b } else { 0.0 }; + tracing::info!( + "pace, per frame: fence waits already met {:.2}, not met {:.2} (the render thread's {:.2}); a wait is met {:.1} ms and {:.2} frames after it was asked \ + (the render thread's: {:.1} ms, {:.1} ms a frame); the title's queue signals: {:.2} a frame, a fence is set {:.1} ms and {:.2} frames after the title's Signal call", + n[0] / frames, + n[1] / frames, + n[2] / frames, + per(n[4], n[3]) / 1e3, + per(n[5], n[3]), + per(n[7], n[6]) / 1e3, + n[7] / frames / 1e3, + n[8] / frames, + per(n[9], n[8]) / 1e3, + per(n[10], n[8]), + ); + } } /// IUnknown 3, object 4, device child 1, fence 3, fence 1 (2, a console @@ -396,58 +323,20 @@ mod tests { use super::*; use crate::object::slot; - type Wait = extern "system" fn(This, u64, *mut c_void) -> HRESULT; - type Signal = extern "system" fn(This, u64) -> HRESULT; - - fn new_fence(initial: u64) -> This { - let mut f = std::ptr::null(); - assert_eq!( - create(std::ptr::null(), initial, 0, &FENCE_IIDS[0], &mut f), - S_OK - ); - f - } - - fn release_fence(f: This) { - assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0); - } - - fn address(f: This) -> usize { - slot::<extern "system" fn(This) -> u64>(f, 0x60)(f) as usize - } - - /// A fence pointer that may cross threads (the fence is `Sync`). - #[derive(Clone, Copy)] - struct Shared(This); - // SAFETY: fences are made for use from many threads. - unsafe impl Send for Shared {} - - /// Runs a blocking wait for `value` on another thread; the receiver - /// gets its result once it returns. - fn blocking_wait(f: This, value: u64) -> std::sync::mpsc::Receiver<HRESULT> { - let (done, result) = std::sync::mpsc::channel(); - let f = Shared(f); - std::thread::spawn(move || { - let f = f; - let wait = slot::<Wait>(f.0, 0x48); - let _ = done.send(wait(f.0, value, std::ptr::null_mut())); - }); - result - } - #[cfg(windows)] #[test] fn signals_set_waiting_events() { use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; - let f = new_fence(1); + let mut f = std::ptr::null(); + assert_eq!(create(std::ptr::null(), 1, 0, &FENCE_IIDS[0], &mut f), S_OK); assert_eq!(slot::<extern "system" fn(This) -> u64>(f, 0x40)(f), 1); // SAFETY: plain auto-reset event. let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; assert!(!event.is_null()); - let wait = slot::<Wait>(f, 0x48); - let signal = slot::<Signal>(f, 0x50); + let wait = slot::<extern "system" fn(This, u64, *mut c_void) -> HRESULT>(f, 0x48); + let signal = slot::<extern "system" fn(This, u64) -> HRESULT>(f, 0x50); assert_eq!(wait(f, 5, event), S_OK); // SAFETY: a valid event. assert_ne!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); @@ -457,146 +346,13 @@ mod tests { assert_eq!(wait(f, 5, event), S_OK, "already reached"); // SAFETY: as above. assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); - // Grand Theft Auto VI reads the value at the fence's address. + assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL); + // The title reads the value at the fence's address. + let at = slot::<extern "system" fn(This) -> u64>(f, 0x60)(f); // SAFETY: the fence's value. - assert_eq!(unsafe { *(address(f) as *const u64) }, 5); - // SAFETY: ours. - unsafe { CloseHandle(event) }; - release_fence(f); - } - - #[test] - fn blocking_wait_returns_at_once_when_reached() { - let f = new_fence(7); - let wait = slot::<Wait>(f, 0x48); - assert_eq!(wait(f, 7, std::ptr::null_mut()), S_OK); - assert_eq!(wait(f, 3, std::ptr::null_mut()), S_OK); - release_fence(f); - } - - /// Used to answer `E_NOTIMPL` at once, so the title went on before the - /// value was reached. - #[test] - fn blocking_wait_blocks_until_signalled() { - let f = new_fence(0); - let result = blocking_wait(f, 2); - let short = Duration::from_millis(200); - assert!( - result.recv_timeout(short).is_err(), - "returned before any signal" - ); - let signal = slot::<Signal>(f, 0x50); - assert_eq!(signal(f, 1), S_OK); - assert!( - result.recv_timeout(short).is_err(), - "returned below its value" - ); - assert_eq!(signal(f, 2), S_OK); - assert_eq!(result.recv_timeout(Duration::from_secs(5)), Ok(S_OK)); - release_fence(f); - } - - #[test] - fn bottom_of_pipe_write_releases_blocking_wait() { - let f = new_fence(0); - let result = blocking_wait(f, 0x1_0000_0003); - std::thread::sleep(Duration::from_millis(50)); - // The low half alone does not reach the value. - crate::queue::Written::Value(3) - .write(address(f) as *mut u8, 4) - .run(); - assert!(result.recv_timeout(Duration::from_millis(200)).is_err()); - crate::queue::Written::Value(0x1_0000_0003) - .write(address(f) as *mut u8, 8) - .run(); - assert_eq!(result.recv_timeout(Duration::from_secs(5)), Ok(S_OK)); - release_fence(f); - } - - #[cfg(windows)] - #[test] - fn bottom_of_pipe_write_sets_waiting_event() { - use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; - use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; - - let f = new_fence(0); - // SAFETY: plain manual-reset event. - let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }; - assert!(!event.is_null()); - assert_eq!(slot::<Wait>(f, 0x48)(f, 9, event), S_OK); - crate::queue::Written::Value(9) - .write(address(f) as *mut u8, 8) - .run(); - // SAFETY: a valid event. - assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); - // SAFETY: ours. - unsafe { CloseHandle(event) }; - release_fence(f); - } - - #[cfg(windows)] - #[test] - fn direct_memory_write_sets_waiting_event() { - use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; - use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; - - let f = new_fence(0); - // SAFETY: plain manual-reset event. - let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }; - assert!(!event.is_null()); - assert_eq!(slot::<Wait>(f, 0x48)(f, 11, event), S_OK); - // SAFETY: a valid event. - assert_ne!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); - // Direct write to the fence's GPU address, bypassing `Signal` and - // `Written::write`. - // SAFETY: `address(f)` is `Fence::value`, an `AtomicU64`. - unsafe { (*(address(f) as *const AtomicU64)).store(11, Ordering::Release) }; - // SAFETY: a valid event. - assert_eq!(unsafe { WaitForSingleObject(event, 2_000) }, WAIT_OBJECT_0); + assert_eq!(unsafe { *(at as *const u64) }, 5); // SAFETY: ours. unsafe { CloseHandle(event) }; - release_fence(f); - } - - #[test] - fn released_fences_leave_the_registry() { - let f = new_fence(0); - let at = address(f); - assert!(live().contains_key(&at)); - release_fence(f); - assert!(!live().contains_key(&at)); - // A write next to (not on) a live fence's value wakes nothing and - // does not fault. - let g = new_fence(0); - let mut other = [0u64; 2]; - written(other.as_mut_ptr() as usize, 16).run(); - written(address(g) + 8, 8).run(); - release_fence(g); - } - - /// A bottom-of-pipe write at a fence a held queue waits for does not - /// run that queue's work inside the write: the writer (`Host::execute`) - /// still holds its submission lock, which the work takes again. The old - /// code ran it there (a deadlock on the real lock). - #[test] - fn bottom_of_pipe_writes_leave_woken_work_to_the_writer() { - use crate::timeline::{Op, Timeline}; - let f = new_fence(0); - let submission = Arc::new(Mutex::new(())); - let ran = Arc::new(std::sync::atomic::AtomicU32::new(0)); - let queue = Arc::new(Timeline::default()); - queue.submit(Op::Wait(Held::new(f), 1)); - let (lock, seen) = (submission.clone(), ran.clone()); - queue.submit(Op::Run(Box::new(move || { - let free = lock.try_lock().is_ok(); - seen.store(if free { 1 } else { 2 }, Ordering::SeqCst); - }))); - let held = submission.lock().unwrap(); - let woken = crate::queue::Written::Value(1).write(address(f) as *mut u8, 8); - assert_eq!(ran.load(Ordering::SeqCst), 0, "ran inside the write"); - drop(held); - woken.run(); - assert_eq!(ran.load(Ordering::SeqCst), 1); - release_fence(f); + assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0); } } diff --git a/crates/victory-gpu/src/fpsbox.rs b/crates/victory-gpu/src/fpsbox.rs new file mode 100644 index 0000000000..7f48daab8a --- /dev/null +++ b/crates/victory-gpu/src/fpsbox.rs @@ -0,0 +1,456 @@ +//! The frame rate and the machine's load, drawn into the top left corner of +//! every frame shown. +//! +//! The window's caption has the frame rate, but a capture of the window's +//! picture (a stream) does not carry the caption. Here the numbers are part +//! of the picture: a small box of text copied onto the swap chain's back +//! buffer right after the title's frame, before it is presented. The +//! title's own frame is not touched, so saved frames and everything read +//! back from it are as before. +//! +//! The box has six lines, new once a second: +//! +//! ```text +//! 5.8 FPS 172 MS the frames shown a second and a frame's time +//! CPU 31% GAME 5.2 CORES all processors, all programs; this process +//! TOP THREAD 97% this process's busiest thread, of one processor +//! GPU 41% GAME 38% the card's busiest engine: all programs; this one +//! VRAM 9.0/10.0 GB the card's memory this process uses / its budget +//! RAM 15.4 GB FREE 3.1 GB this process's committed memory; the PC's free +//! ``` +//! +//! A thread near 100 % beside a card far from it is a frame held by that +//! thread; a card near 100 % holds it itself; neither busy is waiting (for +//! memory to cross between the two, mostly). The load comes from +//! `crate::stats`, the card's memory from the host. +//! +//! The text is drawn on the CPU with a font of its own (5 by 7 dots a +//! glyph) into one of four buffers the card copies from, taken in turn: a +//! buffer is written again only three texts (three seconds) after it was +//! last recorded, so a present still in the air reads what it was recorded +//! with. On by default; `VICTORY_FPS_COUNTER=fps` shows the frame rate +//! alone, `VICTORY_FPS_COUNTER=0` leaves the frame as the title drew it. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, Ordering}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// The frame rate in tenths of a frame a second, as last measured (once a +/// second, by the presenter's meter); `u32::MAX` before the first. +static TENTHS: AtomicU32 = AtomicU32::new(u32::MAX); + +/// What is drawn: nothing, the frame rate alone, or the whole box. +#[derive(Clone, Copy, PartialEq)] +enum Mode { + Off, + Rate, + All, +} + +fn mode() -> Mode { + static MODE: std::sync::OnceLock<Mode> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_FPS_COUNTER").as_deref() { + Ok("0") => Mode::Off, + Ok("fps") => Mode::Rate, + _ => Mode::All, + }) +} + +/// The frame rate just measured. +pub(crate) fn set(fps: f64) { + if fps.is_finite() && fps >= 0.0 { + TENTHS.store((fps * 10.0).round().min(99_999.0) as u32, Ordering::Relaxed); + } +} + +/// A glyph's seven rows, five dots each (bit 4 is the left one). +fn glyph(c: char) -> [u8; 7] { + match c { + '0' => [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110], + '1' => [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110], + '2' => [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111], + '3' => [0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110], + '4' => [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010], + '5' => [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110], + '6' => [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110], + '7' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000], + '8' => [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110], + '9' => [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100], + '.' => [0, 0, 0, 0, 0, 0b01100, 0b01100], + '%' => [0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011], + '/' => [0b00001, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b10000], + 'A' => [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001], + 'B' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110], + 'C' => [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110], + 'D' => [0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110], + 'E' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111], + 'F' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000], + 'G' => [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01111], + 'H' => [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001], + 'I' => [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110], + 'K' => [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001], + 'M' => [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001], + 'N' => [0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001], + 'O' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110], + 'P' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000], + 'R' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001], + 'S' => [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110], + 'T' => [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100], + 'U' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110], + 'V' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100], + 'W' => [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001], + _ => [0; 7], + } +} + +/// The text for a frame rate in tenths. +fn text(tenths: u32) -> String { + format!("{}.{} FPS", tenths / 10, tenths % 10) +} + +/// The glyphs a line of the whole box has room for. +const COLUMNS: usize = 26; + +/// The glyphs of the frame rate alone ("9999.9 FPS"). +const RATE_COLUMNS: usize = 10; + +/// The six lines of the whole box (see the module's notes), each exactly +/// [`COLUMNS`] glyphs: for a frame rate in tenths, the machine's load if a +/// look was taken, and the card's memory in bytes (budget, used) if the +/// host answered. A line whose figures are not there yet is blank. +fn lines(tenths: u32, stats: Option<crate::stats::Stats>, card: Option<(u64, u64)>) -> Vec<String> { + let gb = |mb: f64| mb / 1024.0; + let mut out = Vec::with_capacity(6); + out.push(if tenths > 0 { format!("{} {:.0} MS", text(tenths), 10_000.0 / f64::from(tenths)) } else { text(tenths) }); + match stats { + Some(s) => { + out.push(format!("CPU {:.0}% GAME {:.1} CORES", s.cpu_all, s.cores)); + out.push(format!("TOP THREAD {:.0}%", s.top_thread)); + out.push(match (s.gpu_all, s.gpu_ours) { + (Some(all), Some(ours)) => format!("GPU {all:.0}% GAME {ours:.0}%"), + _ => "GPU NOT KNOWN".to_owned(), + }); + } + None => out.extend([String::new(), String::new(), String::new()]), + } + out.push(match card { + Some((budget, used)) => format!("VRAM {:.1}/{:.1} GB", gb((used >> 20) as f64), gb((budget >> 20) as f64)), + None => String::new(), + }); + out.push(match stats { + Some(s) => format!("RAM {:.1} GB FREE {:.1} GB", gb(f64::from(s.ram_ours_mb)), gb(f64::from(s.ram_free_mb))), + None => String::new(), + }); + out.into_iter().map(|line| fit(&line, COLUMNS)).collect() +} + +/// `line` in exactly `columns` glyphs: cut, or filled with spaces. +fn fit(line: &str, columns: usize) -> String { + let mut out: String = line.chars().take(columns).collect(); + out.extend(std::iter::repeat_n(' ', columns - out.chars().count())); + out +} + +/// Bytes a pixel of a swap chain format this layer presents in, or none. +fn pixel_bytes(format: DXGI_FORMAT) -> Option<usize> { + match format { + DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_R10G10B10A2_UNORM => Some(4), + DXGI_FORMAT_R16G16B16A16_FLOAT => Some(8), + _ => None, + } +} + +/// One pixel of `format`: of the text (`lit`) or of the box behind it. +fn pixel(format: DXGI_FORMAT, lit: bool, out: &mut [u8]) { + // The text: a bright yellow. The box: nearly black. + let (r, g, b): (f32, f32, f32) = if lit { (1.0, 0.92, 0.16) } else { (0.03, 0.03, 0.03) }; + let byte = |v: f32| (v * 255.0).round() as u8; + match format { + DXGI_FORMAT_R8G8B8A8_UNORM => out.copy_from_slice(&[byte(r), byte(g), byte(b), 255]), + DXGI_FORMAT_B8G8R8A8_UNORM => out.copy_from_slice(&[byte(b), byte(g), byte(r), 255]), + DXGI_FORMAT_R10G10B10A2_UNORM => { + let ten = |v: f32| (v * 1023.0).round() as u32; + out.copy_from_slice(&(ten(r) | ten(g) << 10 | ten(b) << 20 | 3 << 30).to_le_bytes()); + } + _ => { + for (i, v) in [r, g, b, 1.0].into_iter().enumerate() { + out[i * 2..i * 2 + 2].copy_from_slice(&half(v).to_le_bytes()); + } + } + } +} + +/// A value from 0 to 1 as a 16-bit float. +fn half(v: f32) -> u16 { + let bits = v.clamp(0.0, 1.0).to_bits(); + if v <= 0.0 { + return 0; + } + // Sign 0; the exponent moves from a bias of 127 to one of 15; the top + // ten bits of the fraction stay. Values under 2^-14 (none of ours) are 0. + let exponent = ((bits >> 23) & 0xFF) as i32 - 127 + 15; + if exponent <= 0 { + return 0; + } + ((exponent as u32) << 10 | (bits >> 13) & 0x3FF) as u16 +} + +/// The box for `text` (lines parted by `\n`) at `scale` dots a pixel: its +/// width and height in pixels and, row by row from the top, whether each +/// pixel is text. A glyph takes six dots across with its gap and a line +/// nine down with its gap; a pad of two dots lies all round. +fn bitmap(text: &str, scale: u32) -> (u32, u32, Vec<bool>) { + let lines: Vec<Vec<char>> = text.split('\n').map(|l| l.chars().collect()).collect(); + let longest = lines.iter().map(Vec::len).max().unwrap_or(0).max(1) as u32; + let pad = 2 * scale; + let width = 2 * pad + longest * 6 * scale - scale; + let height = 2 * pad + lines.len() as u32 * 9 * scale - 2 * scale; + let mut lit = vec![false; (width * height) as usize]; + for (line, chars) in lines.iter().enumerate() { + for (i, &c) in chars.iter().enumerate() { + let rows = glyph(c); + for (row, bits) in rows.into_iter().enumerate() { + for column in 0..5u32 { + if bits >> (4 - column) & 1 == 0 { + continue; + } + let x0 = pad + (i as u32 * 6 + column) * scale; + let y0 = pad + (line as u32 * 9 + row as u32) * scale; + for y in y0..y0 + scale { + for x in x0..x0 + scale { + lit[(y * width + x) as usize] = true; + } + } + } + } + } + } + (width, height, lit) +} + +/// A buffer the card copies a box from, with its footprint and where its +/// bytes are mapped. +struct Made { + buffer: ID3D12Resource, + data: *mut u8, + width: u32, + height: u32, + pitch: u32, +} + +// SAFETY: a free-threaded D3D12 object, its mapping (written under +// `PANEL`'s lock only) and plain numbers. +unsafe impl Send for Made {} + +/// The buffers a text is drawn into, in turn. +const RING: usize = 4; + +/// The box as last drawn. +#[derive(Default)] +struct Panel { + /// What the buffers were made for: the format, the scale, the glyphs + /// across and the lines. + made_for: Option<(i32, u32, usize, usize)>, + /// The text in `ring[at]`: the frame rate and the number of the look at + /// the machine's load. + shown: Option<(u32, u64)>, + ring: Vec<Made>, + at: usize, +} + +static PANEL: Mutex<Option<Panel>> = Mutex::new(None); + +/// Copies the box onto `back`, a back buffer of `width` by `height` pixels +/// of `format` that `list` holds as a copy's destination. Nothing if the +/// box is off, no rate was measured yet, the format is not one of ours or +/// the frame is too small for the box. +pub(crate) fn draw(host: &crate::host::Host, list: &ID3D12GraphicsCommandList, back: &ID3D12Resource, (width, height, format): (u32, u32, DXGI_FORMAT)) { + let mode = mode(); + if mode == Mode::Off { + return; + } + let tenths = TENTHS.load(Ordering::Relaxed); + let Some(bytes) = pixel_bytes(format).filter(|_| tenths != u32::MAX) else { + return; + }; + // About a fortieth of the frame's height a glyph: 6 dots a pixel at + // 2160 lines, 3 at 1080. + let scale = (height / 360).clamp(2, 12); + let stats = (mode == Mode::All).then(|| { + crate::stats::start(); + crate::stats::now() + }); + let look = stats.flatten(); + let (columns, rows) = if mode == Mode::All { (COLUMNS, 6) } else { (RATE_COLUMNS, 1) }; + let mut panel = PANEL.lock().unwrap_or_else(|e| e.into_inner()); + let panel = panel.get_or_insert_with(Panel::default); + let made_for = Some((format.0, scale, columns, rows)); + if panel.made_for != made_for { + // Another size of frame or another format: new buffers. A present + // still in the air may read the old ones, so they are never let go + // (a few hundred KiB each; this happens when the window changes). + std::mem::forget(std::mem::take(&mut panel.ring)); + *panel = Panel { made_for, ..Default::default() }; + } + let key = (tenths, look.map_or(0, |(number, _)| number)); + if panel.shown != Some(key) { + let text = if mode == Mode::All { + let card = host.video_memory().map(|m| (m[0], m[1])); + lines(tenths, look.map(|(_, s)| s), card).join("\n") + } else { + fit(&text(tenths), RATE_COLUMNS) + }; + let (w, h, lit) = bitmap(&text, scale); + let pitch = (w as usize * bytes).next_multiple_of(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT as usize); + // The next buffer in turn, made at its first use. + let at = if panel.ring.len() < RING { + let Some((buffer, data)) = host.shared_buffer((pitch * h as usize) as u64) else { + return; + }; + panel.ring.push(Made { buffer, data, width: w, height: h, pitch: pitch as u32 }); + panel.ring.len() - 1 + } else { + (panel.at + 1) % RING + }; + let m = &panel.ring[at]; + if (m.width, m.height, m.pitch) != (w, h, pitch as u32) { + // (Every text of one `made_for` has one size: not reached.) + return; + } + // SAFETY: the buffer's own mapped bytes, `pitch * h` of them; the + // card last read them at least `RING - 1` texts ago. + let out = unsafe { std::slice::from_raw_parts_mut(m.data, pitch * h as usize) }; + for y in 0..h as usize { + for x in 0..w as usize { + let to = y * pitch + x * bytes; + pixel(format, lit[y * w as usize + x], &mut out[to..to + bytes]); + } + } + panel.at = at; + panel.shown = Some(key); + } + let Some(m) = panel.ring.get(panel.at) else { + return; + }; + let margin = 4 * scale; + if m.width + 2 * margin > width || m.height + 2 * margin > height { + return; + } + // SAFETY: an open list; the back buffer is a copy's destination in it + // and the box lies inside it; our buffer holds `pitch * height` bytes + // and is kept for as long as the process runs. + unsafe { + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&m.buffer), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: format, Width: m.width, Height: m.height, Depth: 1, RowPitch: m.pitch }, + }, + }, + }; + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(back), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + list.CopyTextureRegion(&to, margin, margin, 0, &from, None); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_text_is_the_rate_to_a_tenth() { + assert_eq!(text(103), "10.3 FPS"); + assert_eq!(text(7), "0.7 FPS"); + assert_eq!(text(300), "30.0 FPS"); + } + + #[test] + fn the_box_holds_every_glyph_with_a_margin() { + let (w, h, lit) = bitmap("10.3 FPS", 3); + // Eight glyphs of five dots and seven gaps of one, a pad of two dots all round. + assert_eq!((w, h), ((8 * 5 + 7 + 4) * 3, (7 + 4) * 3)); + assert_eq!(lit.len(), (w * h) as usize); + // The pad is box, not text; the "1" has its stem lit. + assert!(lit[..(w * 6) as usize].iter().all(|&l| !l), "the top pad"); + assert!((0..h).all(|y| !lit[(y * w) as usize] && !lit[(y * w + w - 1) as usize]), "the side pads"); + let at = |x: u32, y: u32| lit[(y * w + x) as usize]; + // Glyph 0 ("1"): dot column 2 of row 0 is lit, column 0 is not. + assert!(at(6 + 2 * 3, 6) && !at(6, 6)); + // A space lights nothing: glyph 4. + assert!((0..7 * 3).all(|y| (0..5 * 3).all(|x| !at(6 + 4 * 18 + x, 6 + y)))); + // Every glyph used has at least one dot, but the space. + for c in "0123456789.FPS".chars() { + assert!(glyph(c).iter().any(|&r| r != 0), "{c}"); + } + } + + #[test] + fn the_whole_box_has_six_lines_of_one_length_and_a_glyph_for_every_letter() { + let stats = crate::stats::Stats { + cpu_all: 100.0, + cores: 28.0, + top_thread: 100.0, + gpu_all: Some(100.0), + gpu_ours: Some(100.0), + ram_ours_mb: 31 * 1024 + 512, + ram_free_mb: 12 * 1024 + 100, + }; + // The longest figures there can be, the usual ones, and none. + let texts = [ + lines(99_999, Some(stats), Some((12_282 << 20, 11_900 << 20))), + lines(58, Some(crate::stats::Stats { gpu_all: None, gpu_ours: None, ..stats }), Some((10_048 << 20, 9_039 << 20))), + lines(0, None, None), + ]; + assert_eq!(texts[0][0].trim_end(), "9999.9 FPS 0 MS"); + assert_eq!(texts[0][1].trim_end(), "CPU 100% GAME 28.0 CORES"); + assert_eq!(texts[0][5].trim_end(), "RAM 31.5 GB FREE 12.1 GB"); + assert_eq!(texts[1][0].trim_end(), "5.8 FPS 172 MS"); + assert_eq!(texts[1][2].trim_end(), "TOP THREAD 100%"); + assert_eq!(texts[1][3].trim_end(), "GPU NOT KNOWN"); + assert_eq!(texts[1][4].trim_end(), "VRAM 8.8/9.8 GB"); + assert_eq!(texts[2][0].trim_end(), "0.0 FPS"); + for lines in &texts { + assert_eq!(lines.len(), 6); + for line in lines { + assert_eq!(line.chars().count(), COLUMNS, "{line:?}"); + for c in line.chars().filter(|c| *c != ' ') { + assert!(glyph(c).iter().any(|&r| r != 0), "no glyph for {c:?} in {line:?}"); + } + } + } + // Six lines: nine dots a line, less the last gap, and the pad. + let (w, h, lit) = bitmap(&texts[0].join("\n"), 3); + assert_eq!((w, h), ((COLUMNS as u32 * 6 - 1 + 4) * 3, (6 * 9 - 2 + 4) * 3)); + assert_eq!(lit.len(), (w * h) as usize); + // The frame rate alone keeps its length whatever the rate. + assert_eq!(fit(&text(7), RATE_COLUMNS).len(), fit(&text(99_999), RATE_COLUMNS).len()); + } + + #[test] + fn pixels_are_in_the_formats_the_layer_presents_in() { + let mut four = [0u8; 4]; + pixel(DXGI_FORMAT_R8G8B8A8_UNORM, true, &mut four); + assert_eq!(four, [255, 235, 41, 255]); + pixel(DXGI_FORMAT_B8G8R8A8_UNORM, true, &mut four); + assert_eq!(four, [41, 235, 255, 255]); + pixel(DXGI_FORMAT_R10G10B10A2_UNORM, true, &mut four); + let v = u32::from_le_bytes(four); + assert_eq!((v & 1023, v >> 10 & 1023, v >> 20 & 1023, v >> 30), (1023, 941, 164, 3)); + let mut eight = [0u8; 8]; + pixel(DXGI_FORMAT_R16G16B16A16_FLOAT, true, &mut eight); + assert_eq!(u16::from_le_bytes([eight[0], eight[1]]), 0x3C00, "1.0 as a half"); + assert_eq!(u16::from_le_bytes([eight[6], eight[7]]), 0x3C00); + assert_eq!(half(0.5), 0x3800); + assert_eq!(half(0.0), 0); + assert_eq!(pixel_bytes(DXGI_FORMAT_R16G16B16A16_FLOAT), Some(8)); + assert_eq!(pixel_bytes(DXGI_FORMAT_D32_FLOAT), None); + } +} diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index d172d5b8d0..23544f8e0c 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -2,7 +2,7 @@ //! to begin. Ours is a clock started by the first interval set, ticking //! once per interval; the token is the frame number. Each event kind //! (origin, vblank, flip) happens once per tick, so two waits for the same -//! kind never end on the same tick: Grand Theft Auto VI polls the origin +//! kind never end on the same tick: the title polls the origin //! with "token on time-out" (starting its next frame at once) and is paced //! by a blocking wait for the flip before each present. //! @@ -92,12 +92,10 @@ fn last(kind: u32) -> &'static AtomicU64 { &LAST[(kind as usize).min(LAST.len() - 1)] } -/// The next tick after now and after the last one a wait for `kind` took -/// (an event happens once per tick: a wait woken a little early must not -/// let the next one end on the same tick), and how long until it. A wait -/// that comes within `limit` takes the tick here, under the clock's lock, -/// so two threads waiting for one kind never take the same tick. -fn next_tick(kind: u32, limit: Duration) -> (u64, Duration) { +/// The next tick after now and after the last one a wait for `kind` ended +/// on (an event happens once per tick: a wait woken a little early must not +/// let the next one end on the same tick), and how long until it. +fn next_tick(kind: u32) -> (u64, Duration) { let mut clock = clock(); let c = clock.get_or_insert_with(|| Clock { start: Instant::now(), @@ -106,25 +104,13 @@ fn next_tick(kind: u32, limit: Duration) -> (u64, Duration) { }); let elapsed = c.start.elapsed().as_nanos(); let interval = c.interval.as_nanos().max(1); - let last_tick = last(kind).load(Ordering::Relaxed); - // The tick most recently passed. A flip (or vblank) wait that begins - // after a tick nobody has taken yet is late: the frame took longer than - // an interval. It ends at once on that tick instead of waiting for the - // following one, so a frame a little over budget costs that much more, - // not a whole extra interval (30 fps falling straight to 15). - let passed = c.first + (elapsed / interval) as u64; - if kind != ORIGIN && passed > last_tick && passed > c.first { - // Take it here like any other tick, so the next wait cannot end on it. - last(kind).fetch_max(passed, Ordering::Relaxed); - return (passed, Duration::ZERO); - } - let tick = (c.first + (elapsed / interval + 1) as u64).max(last_tick + 1); + let tick = + (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1); let at = u128::from(tick - c.first) * interval; - let wait = Duration::from_nanos(at.saturating_sub(elapsed) as u64); - if wait <= limit { - last(kind).fetch_max(tick, Ordering::Relaxed); - } - (tick, wait) + ( + tick, + Duration::from_nanos(at.saturating_sub(elapsed) as u64), + ) } /// Device method: blocks until the next tick (or the time-out); an origin @@ -140,15 +126,42 @@ pub(crate) extern "system" fn wait( token: *mut u64, ) -> HRESULT { let origin = kind == ORIGIN; + let (mut tick, mut wait) = next_tick(kind); let limit = Duration::from_millis(u64::from(timeout_ms)); - let (_tick, wait) = next_tick(kind, limit); + // A blocking wait for an event that has happened since the last wait + // for it ended (a frame took longer than a tick) ends at once, on the + // tick that passed: sleeping on to the next one cost 17 ms of every + // 730 ms frame (run 58: "2.0 frame waits sleeping 16.8 ms"). Polls (a + // time-out shorter than a tick) answer as before. + // `VICTORY_LATE_WAITS=1` sleeps to the next tick, as before. + static SLEEP: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*SLEEP.get_or_init(|| std::env::var_os("VICTORY_LATE_WAITS").is_some_and(|v| v == "1")) + && limit >= wait + && tick > last(kind).load(Ordering::Relaxed) + 1 + { + tick -= 1; + wait = Duration::ZERO; + } let hr = if wait > limit { std::thread::sleep(limit); TIMEOUT } else { std::thread::sleep(wait); + last(kind).fetch_max(tick, Ordering::Relaxed); S_OK }; + #[cfg(windows)] + { + let us = wait.min(limit).as_micros() as u64; + crate::framelog::add(crate::framelog::T::PaceUs, us); + crate::framelog::here(crate::framelog::H::PaceUs, us); + } + #[cfg(all(windows, feature = "diagnostics"))] + { + use crate::copystat::{C, add}; + add(C::PaceWaits, 1); + add(C::PaceUs, wait.min(limit).as_micros() as u64); + } // A frame begun on a time-out takes no tick: its flip still does. if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) { // Tokens count frames (consecutive), not ticks. @@ -164,7 +177,7 @@ pub(crate) extern "system" fn wait( timeout_ms, flags, hr, - tick = _tick, + tick, wait_us = wait.as_micros() as u64, frame = current(), "frame wait" @@ -221,7 +234,11 @@ mod tests { // origin poll that times out (and starts the frame), then a // blocking flip wait. Each flip ends on a tick of its own. const FLIP: u32 = 2; - assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); + const INTERVAL: Duration = Duration::from_millis(5); + assert_eq!( + set_interval(null, null, INTERVAL.as_micros() as u32, 3, 0), + S_OK + ); let mut token = 0; let flips: Vec<u64> = (0..4) .map(|_| { @@ -236,38 +253,7 @@ mod tests { // Strictly rising: a late wake may skip ticks, but never repeats one. assert!(flips.windows(2).all(|w| w[1] > w[0]), "{flips:?}"); // Even when a flip wait begins on the tick another just ended on. - let (tick, _) = next_tick(FLIP, Duration::ZERO); + let (tick, _) = next_tick(FLIP); assert!(tick > flips[3]); - - // A frame over budget: its flip wait begins after a tick nobody - // took and ends at once on it, not on the tick after. - assert_eq!(set_interval(null, null, 20_000, 1, 0), S_OK); - assert_eq!( - wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), - S_OK - ); - let flipped = LAST[2].load(Ordering::Relaxed); - std::thread::sleep(Duration::from_millis(25)); - let late = Instant::now(); - assert_eq!( - wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), - S_OK - ); - assert!(late.elapsed() < Duration::from_millis(10)); - assert_eq!(LAST[2].load(Ordering::Relaxed), flipped + 1); - } - - /// Two waits for one kind that begin together (two threads) take two - /// ticks: the first takes its tick before it sleeps. A time-out takes - /// none. The old code marked the tick after the sleep, so both got it. - #[test] - fn waits_begun_together_take_different_ticks() { - const VBLANK: u32 = 1; - let long = Duration::from_secs(1); - let (first, _) = next_tick(VBLANK, long); - let (second, _) = next_tick(VBLANK, long); - assert!(second > first, "{second} after {first}"); - next_tick(VBLANK, Duration::ZERO); - assert_eq!(last(VBLANK).load(Ordering::Relaxed), second); } } diff --git a/crates/victory-gpu/src/framelog.rs b/crates/victory-gpu/src/framelog.rs new file mode 100644 index 0000000000..0ee47b205d --- /dev/null +++ b/crates/victory-gpu/src/framelog.rs @@ -0,0 +1,839 @@ +//! Every frame's length, and what the long ones were made of. +//! +//! The frame-rate line averages over a second or more, and its counters +//! are reset at each line: a single long frame is lost in it, and so is +//! what that frame was made of. Run 222's dips (150 ms frames with some of +//! 250 to 500 ms among them) could not be placed from those lines. +//! +//! Here every counter runs from the start and is never reset. At the end +//! of each present call the totals are read, and their differences since +//! the present before are that frame's. Every five seconds one line gives +//! the frame times (each one, the shortest, the median, the longest), one +//! gives the usual frame's make-up (the mean of the frames that were not +//! long), and each long frame gets a line of its own in the same form, so +//! a long frame is read against a usual one column by column. +//! +//! On by default in diagnostics builds, off in others; +//! `VICTORY_FRAME_LOG=1` or `0` says otherwise. The counters themselves +//! are plain atomic adds in every build. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// Totals since the start (microseconds unless said otherwise). +#[derive(Clone, Copy)] +#[repr(usize)] +pub enum T { + /// The title's present call, all of it; of it, running the queues' + /// lines and settling submissions before our copy; and our copy to the + /// window with the host's present. + PresentUs, + PresentLineUs, + PresentShowUs, + /// The title's submit calls (`queue::execute`), on every thread. + ExecuteUs, + /// The submit thread of ours (`VICTORY_ASYNC_SUBMIT=1`) at work: wall + /// time running the queues' lines, and its processor time doing so. + WorkerUs, + WorkerUserUs, + WorkerKernelUs, + /// Submissions sent; preparing them and waiting for the card, on + /// whichever thread (the frame-rate line's "preparing" and "on the + /// GPU"). + Submissions, + PrepareUs, + CardWaitUs, + /// The card with nothing of ours queued, and how much of that while + /// the submitting thread was working. + CardIdleUs, + CardIdleBehindUs, + /// Copies of title memory for submissions (time, bytes), and what + /// shaders wrote copied back (time, bytes). + CopyUs, + CopyBytes, + CopyBackUs, + CopyBackBytes, + /// List calls that record into host lists, on every thread + /// (nanoseconds, calls). Diagnostics builds only. + RecordNs, + RecordCalls, + /// The runtime changing what title memory shows: calls, the time from + /// asking for the lock to letting it go, and of that the wait for + /// readers. + Remaps, + RemapUs, + RemapWaitUs, + /// Texture refreshes on every thread, and of them the wait for title + /// memory to hold still; uploads recorded. + RefreshUs, + RefreshStillUs, + Uploads, + /// Waiting for host pipelines being made. + PipelineWaitUs, + /// Writes taken by the guards on view memory. + GuardFaults, + /// The title's frame waits: time slept, on every thread. + PaceUs, + /// DirectStorage requests finished, their destination bytes, and the + /// workers' time in them. + DiskReads, + DiskBytes, + DiskUs, + /// The card's time by kind of list (`crate::cardmeter`), as read a + /// second and a half after the lists were recorded: our lists that + /// bring copies in the card's memory up to date and hash their pieces, + /// our compare lists, and every other list; and how many of each. + CardSyncUs, + CardSyncLists, + CardCheckUs, + CardCheckLists, + CardListsUs, + CardLists, + /// Looks at which processor a thread is on ([`on_slow_core`]), and how + /// many found a slow one (an efficiency core of a hybrid processor): + /// the thread that presents (one look a present), our submit thread + /// (one a turn), and the recording threads (one every couple of + /// milliseconds of list calls). + RenderLooks, + RenderSlow, + WorkerLooks, + WorkerSlow, + RecordLooks, + RecordSlow, + /// The runtime's changes of what title memory shows, by part + /// (`victory-hle` `xmem.rs`): microseconds in the system's unmapping + /// calls, in its mapping calls (the split of the placeholder and the + /// mapping itself), in committing, and in the layer's own notes of the + /// change (`title_memory_remapped`, `title_memory_view`); then the views + /// that reached outside the range asked for and were mapped again there, + /// and those bytes. + RemapUnmapUs, + RemapMapUs, + RemapCommitUs, + RemapNotesUs, + RemapCuts, + RemapCutBytes, + /// The remapping meter (`victory-hle` `xmem.rs`, `Meter`): the system's + /// unmapping and mapping calls counted (a remapping call of the title + /// makes none, one or many of each); the processor cycles the calling + /// thread used inside them and the processor's clock over the same + /// calls (their ratio is the share of the calls' time the thread was + /// on a processor: the rest it stood blocked in the kernel); and the + /// calls by length (under 50 us, to 200 us, to 1 ms, longer): how many + /// and their microseconds. + RemapUnmapCalls, + RemapUnmapCycles, + RemapUnmapTsc, + RemapUnmapC0, + RemapUnmapC1, + RemapUnmapC2, + RemapUnmapC3, + RemapUnmapU0, + RemapUnmapU1, + RemapUnmapU2, + RemapUnmapU3, + RemapMapCalls, + RemapMapCycles, + RemapMapTsc, + RemapMapC0, + RemapMapC1, + RemapMapC2, + RemapMapC3, + RemapMapU0, + RemapMapU1, + RemapMapU2, + RemapMapU3, + /// Mappings tried a second time after the placeholder was split + /// (`VICTORY_REMAP_SPLIT`); splits of a placeholder tried, those that + /// split one, and their microseconds. + RemapMapRetries, + RemapSplits, + RemapSplitsDone, + RemapSplitUs, + /// The queue's page-mapping copies as the runtime sees them + /// (`map_alias`): calls and their microseconds from entry to return + /// (the wait for the page table's lock included, which `RemapUs` leaves + /// out); pages mapped, those that were the next page of the same + /// section after the page mapped just before at the address just + /// before (one view could show both), and those that were the same + /// page as it (no view can). + RemapAliasCalls, + RemapAliasUs, + RemapAliasPages, + RemapAliasRunPages, + RemapAliasSamePages, + /// The title's own mapping calls (`XMemMapPhysicalPages`, and each page + /// of `XMemMapPhysicalPagesScatter`): calls, microseconds, pages. + RemapDirectCalls, + RemapDirectUs, + RemapDirectPages, + /// The queue's page-mapping copies as the title asks for them + /// (`queue.rs` `copy_page_mappings`): calls, and ranges and pages by + /// kind (0 pool pages in a row, 1 one pool page each, 2 unmapped). + PageMapCalls, + PageMapRanges0, + PageMapPages0, + PageMapRanges1, + PageMapPages1, + PageMapRanges2, + PageMapPages2, + /// Views of our own on physical pages for DirectStorage's writes + /// (`xmem.rs` `View`): how many, and the microseconds mapping, + /// committing and unmapping them. + DiskViews, + DiskViewUs, + Count, +} + +const N: usize = T::Count as usize; +static TOTAL: [AtomicU64; N] = [const { AtomicU64::new(0) }; N]; + +/// Adds to a total. +pub fn add(t: T, n: u64) { + TOTAL[t as usize].fetch_add(n, Relaxed); +} + +/// Takes from a total (a time that was summed over threads is corrected +/// to the time it took). +pub fn sub(t: T, n: u64) { + TOTAL[t as usize].fetch_sub(n, Relaxed); +} + +/// What a thread did inside our calls since its last present: for the +/// thread that presents (the title's render thread). +#[derive(Clone, Copy)] +#[repr(usize)] +pub enum H { + /// List calls, nanoseconds. + RecordNs, + /// Submit calls, microseconds. + ExecuteUs, + /// Frame waits, microseconds slept. + PaceUs, + Count, +} + +const HN: usize = H::Count as usize; + +thread_local! { + static HERE: std::cell::Cell<[u64; HN]> = const { std::cell::Cell::new([0; HN]) }; +} + +/// Adds to this thread's own count. +pub fn here(h: H, n: u64) { + HERE.with(|c| { + let mut v = c.get(); + v[h as usize] += n; + c.set(v); + }); +} + +/// Whether the processor this thread runs on right now is a slow one: on a +/// processor with two kinds of cores (the console has eight alike; an Intel +/// hybrid has fast cores and efficiency cores at about half their speed), +/// one of a lower efficiency class than the best. Always false where all +/// cores are alike. +pub fn on_slow_core() -> bool { + use windows_sys::Win32::System::Threading::GetCurrentProcessorNumber; + /// By logical processor (of group 0): whether it is slow. + static SLOW: std::sync::OnceLock<Vec<bool>> = std::sync::OnceLock::new(); + let slow = SLOW.get_or_init(|| { + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + let mut slow = vec![false; sets.iter().map(|c| c.1 as usize + 1).max().unwrap_or(0)]; + for (_, processor, class) in &sets { + slow[*processor as usize] = *class < best; + } + tracing::info!( + "processors: {} logical, {} of them slow ones (a lower efficiency class than the best); the frame log counts how \ + often the render, submit and recording threads are found on a slow one", + slow.len(), + slow.iter().filter(|&&s| s).count() + ); + slow + }); + // SAFETY: a plain query. + let processor = unsafe { GetCurrentProcessorNumber() } as usize; + slow.get(processor).copied().unwrap_or(false) +} + +/// The system's processor sets of group 0: each one's id, its logical +/// processor and its efficiency class (higher is faster). +fn cpu_sets() -> Vec<(u32, u8, u8)> { + use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut bytes = 0u32; + // SAFETY: a size query, then the call into a buffer of that size. + unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) }; + let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)]; + // SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records. + let ok = unsafe { GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) }; + let mut sets = Vec::new(); + let mut at = 0usize; + while ok != 0 && at + size_of::<SYSTEM_CPU_SET_INFORMATION>() <= bytes as usize { + // SAFETY: a record inside the buffer; each says its own size. + let info = unsafe { &*(buffer.as_ptr().cast::<u8>().add(at).cast::<SYSTEM_CPU_SET_INFORMATION>()) }; + if info.Size == 0 { + break; + } + // SAFETY: the record's type is CpuSet (the only one there is). + let set = unsafe { &info.Anonymous.CpuSet }; + if set.Group == 0 { + sets.push((set.Id, set.LogicalProcessorIndex, set.EfficiencyClass)); + } + at += info.Size as usize; + } + sets +} + +/// The slow logical processors of group 0 as a mask (a lower efficiency +/// class than the best): 0 where all cores are alike. +pub fn slow_processors() -> usize { + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + sets.iter().filter(|c| c.2 < best && c.1 < usize::BITS as u8).fold(0, |mask, c| mask | 1usize << c.1) +} + +/// Asks the system to run the calling thread on the fast cores only, where +/// the processor has two kinds (`VICTORY_FAST_CORES=0`: not asked). +/// +/// The title keeps its own threads on fast cores (run 229: its render +/// thread in 3,484 looks of 3,484, its recording threads in 104,254 of +/// 104,254), as on the console, whose eight cores are alike. The layer's +/// submit thread was found on a slow one in 1,529 looks of 24,021, and the +/// frame waits for that thread. A set of processors selected for a thread +/// is a preference the scheduler keeps unless nothing of it is free. +pub fn keep_on_fast_cores(what: &str) { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets}; + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_FAST_CORES").is_none_or(|v| v != "0")) { + return; + } + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + let fast: Vec<u32> = sets.iter().filter(|c| c.2 == best).map(|c| c.0).collect(); + // All alike (or nothing known): nothing to ask for. + if fast.is_empty() || fast.len() == sets.len() { + return; + } + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) }; + if ok == 0 { + tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores"); + } else { + tracing::info!(what, fast = fast.len(), of = sets.len(), "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)"); + } +} + +/// Asks the system to run the calling thread on the slow cores only, where +/// the processor has two kinds and at least eight slow logical processors +/// (a helper that must not take a fast core from the title's threads). +/// True if it was asked. +/// +/// The title pins its threads as on the console, where disk decompression +/// is the hardware's: measured on a 14700KF, 31 of its threads are tied to +/// logical processors 0-13, the fast cores. The layer decompresses on as +/// many worker threads as there are logical processors (28), free to run +/// anywhere: in the opening cutscene's streaming stretch about ten of them +/// were busy while the title's recording calls took three times as long. +pub fn keep_on_slow_cores(what: &str) -> bool { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets}; + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + let slow: Vec<u32> = sets.iter().filter(|c| c.2 < best).map(|c| c.0).collect(); + if slow.len() < 8 { + return false; + } + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), slow.as_ptr(), slow.len() as u32) } != 0; + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!(what, slow = slow.len(), of = sets.len(), ok, "helper threads are kept on the slow cores: the first one"); + }); + ok +} + +/// Whether frames are logged. +pub fn on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var_os("VICTORY_FRAME_LOG") { + Some(v) => v != "0", + None => cfg!(feature = "diagnostics"), + }) +} + +fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 { + (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10 +} + +/// This thread's processor time so far (user, kernel), in microseconds. +pub fn thread_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own thread and four valid out pointers. + unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +/// The process's processor time so far (user, kernel), in microseconds. +fn process_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own process and four valid out pointers. + unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +/// The process's page faults so far (soft and hard). +fn page_faults() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: plain data the call fills in. + let mut c: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() }; + c.cb = size_of::<PROCESS_MEMORY_COUNTERS>() as u32; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + u64::from(c.PageFaultCount) +} + +/// The PC's free physical memory, in MiB. +pub(crate) fn free_mb() -> u64 { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = size_of::<MEMORYSTATUSEX>() as u32; + // SAFETY: a sized structure. + unsafe { GlobalMemoryStatusEx(&mut m) }; + m.ullAvailPhys >> 20 +} + +/// Values read when a frame ends, all running totals but the last. +const S: usize = 11; +const S_THREAD_USER: usize = 0; +const S_THREAD_KERNEL: usize = 1; +const S_PROCESS_USER: usize = 2; +const S_PROCESS_KERNEL: usize = 3; +const S_PAGE_FAULTS: usize = 4; +const S_DRAWS: usize = 5; +const S_PIPELINES_MADE: usize = 6; +const S_PIPELINES_LOADED: usize = 7; +const S_STAGING_REUSED: usize = 8; +const S_STAGING_MADE: usize = 9; +/// Not a total: the free memory then. +const S_FREE_MB: usize = 10; + +fn sample() -> [u64; S] { + let (tu, tk) = thread_times(); + let (pu, pk) = process_times(); + [ + tu, + tk, + pu, + pk, + page_faults(), + crate::draw::drawn(), + crate::pipeline::frame_log_counts().0, + crate::pipeline::frame_log_counts().1, + crate::host::STAGING_REUSE[0].load(Relaxed), + crate::host::STAGING_REUSE[1].load(Relaxed), + free_mb(), + ] +} + +/// One frame: its number, when it ended (seconds since the first), its +/// length in microseconds, and the differences of the totals, the sampled +/// values and the presenting thread's own counts over it. +#[derive(Clone)] +struct Frame { + number: u64, + at: f64, + us: f64, + t: [f64; N], + s: [f64; S], + h: [f64; HN], +} + +struct State { + first: std::time::Instant, + /// The last frame's end: when, the totals and samples then, and the + /// thread that presented. + last: Option<(std::time::Instant, [u64; N], [u64; S], u32)>, + number: u64, + frames: Vec<Frame>, + since: std::time::Instant, + /// The lengths of the last frames (microseconds), for the usual one. + recent: std::collections::VecDeque<f64>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); + +fn median(values: impl Iterator<Item = f64>) -> f64 { + let mut v: Vec<f64> = values.collect(); + if v.is_empty() { + return 0.0; + } + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// A frame's make-up as text (`f` may be a mean of frames). +fn text(f: &Frame) -> String { + let t = |x: T| f.t[x as usize]; + let ms = |x: T| f.t[x as usize] / 1e3; + let s = |i: usize| f.s[i]; + let h = |x: H| f.h[x as usize]; + let line = format!( + "{:.0} ms | render thread: ran {:.0} ms (user {:.0}, kernel {:.0}); in the present call {:.1} (lines and settling \ + {:.1}, copy and show {:.1}), in submit calls {:.1}, in list calls {:.1}, paced {:.1} | submit thread: at work \ + {:.1} ms (user {:.1}, kernel {:.1}); {:.0} submissions, preparing {:.1}, waiting for the card {:.1}; copies {:.1} \ + ms {:.1} MB; copy-back {:.1} ms {:.2} MB | card: idle {:.1} ms ({:.1} behind us); by its own clock, of the lists of a moment ago: our \ + send-and-hash lists {:.1} ms in {:.0}, our compare lists {:.1} ms in {:.0}, all other lists {:.1} ms in {:.0} | \ + recording, all threads: {:.1} ms in {:.0} calls; all submit calls {:.1} ms | textures: refresh {:.1} ms ({:.1} waiting for memory to hold \ + still), {:.0} uploads, staging {:.0} made {:.0} reused | remapping: {:.0} calls {:.1} ms ({:.1} waiting for \ + readers; of it the system's unmapping {:.1}, its mapping {:.1}, committing {:.1}, our own notes of the change \ + {:.1}; {:.0} views cut, {:.1} MB of them mapped again) | pipelines: {:.0} made, {:.0} loaded, {:.1} ms waited | disk: {:.0} reads {:.1} MB {:.1} worker ms | \ + faults: {:.0} page, {:.0} guard | process: {:.0} user {:.0} kernel ms | pacing, all threads {:.1} ms | {:.0} \ + draws | {:.0} MB free | found on a slow core: the render thread {:.0} of {:.0} looks, the submit thread {:.0} of {:.0}, recording threads {:.0} of {:.0}", + f.us / 1e3, + (s(S_THREAD_USER) + s(S_THREAD_KERNEL)) / 1e3, + s(S_THREAD_USER) / 1e3, + s(S_THREAD_KERNEL) / 1e3, + ms(T::PresentUs), + ms(T::PresentLineUs), + ms(T::PresentShowUs), + h(H::ExecuteUs) / 1e3, + h(H::RecordNs) / 1e6, + h(H::PaceUs) / 1e3, + ms(T::WorkerUs), + ms(T::WorkerUserUs), + ms(T::WorkerKernelUs), + t(T::Submissions), + ms(T::PrepareUs), + ms(T::CardWaitUs), + ms(T::CopyUs), + t(T::CopyBytes) / 1e6, + ms(T::CopyBackUs), + t(T::CopyBackBytes) / 1e6, + ms(T::CardIdleUs), + ms(T::CardIdleBehindUs), + ms(T::CardSyncUs), + t(T::CardSyncLists), + ms(T::CardCheckUs), + t(T::CardCheckLists), + ms(T::CardListsUs), + t(T::CardLists), + t(T::RecordNs) / 1e6, + t(T::RecordCalls), + ms(T::ExecuteUs), + ms(T::RefreshUs), + ms(T::RefreshStillUs), + t(T::Uploads), + s(S_STAGING_MADE), + s(S_STAGING_REUSED), + t(T::Remaps), + ms(T::RemapUs), + ms(T::RemapWaitUs), + ms(T::RemapUnmapUs), + ms(T::RemapMapUs), + ms(T::RemapCommitUs), + ms(T::RemapNotesUs), + t(T::RemapCuts), + t(T::RemapCutBytes) / (1 << 20) as f64, + s(S_PIPELINES_MADE), + s(S_PIPELINES_LOADED), + ms(T::PipelineWaitUs), + t(T::DiskReads), + t(T::DiskBytes) / 1e6, + ms(T::DiskUs), + s(S_PAGE_FAULTS), + t(T::GuardFaults), + s(S_PROCESS_USER) / 1e3, + s(S_PROCESS_KERNEL) / 1e3, + ms(T::PaceUs), + s(S_DRAWS), + s(S_FREE_MB), + t(T::RenderSlow), + t(T::RenderLooks), + t(T::WorkerSlow), + t(T::WorkerLooks), + t(T::RecordSlow), + t(T::RecordLooks), + ); + line + &remap_meter(f) +} + +/// The remapping meter's part of a frame's line (the totals are described +/// at [`T::RemapUnmapCalls`] and after it). +fn remap_meter(f: &Frame) -> String { + let t = |x: T| f.t[x as usize]; + let ms = |x: T| f.t[x as usize] / 1e3; + // The share of the calls' time their thread was on a processor. The + // cycles are read just outside the clock's two readings, so a short + // call can come out a little over the whole. + let on = |cycles: T, tsc: T| if t(tsc) > 0.0 { (100.0 * t(cycles) / t(tsc)).min(100.0) } else { 0.0 }; + format!( + " | remapping, metered: {:.0} system unmaps (on a processor {:.0} % of their time; under 50 us {:.0} = {:.1} ms, \ + to 200 us {:.0} = {:.1}, to 1 ms {:.0} = {:.1}, longer {:.0} = {:.1}), {:.0} system maps (on a processor {:.0} %; \ + under 50 us {:.0} = {:.1} ms, to 200 us {:.0} = {:.1}, to 1 ms {:.0} = {:.1}, longer {:.0} = {:.1}; {:.0} tried again \ + after a split); splits tried {:.0}, needed {:.0}, {:.1} ms; through the queue's page-mapping copies {:.0} calls \ + {:.1} ms with the wait for the page table ({:.0} copies: {:.0} ranges {:.0} pages of pool pages in a row, {:.0} \ + ranges {:.0} pages of one pool page each, {:.0} ranges {:.0} pages unmapped), {:.0} pages mapped, {:.0} the next \ + page after the one before, {:.0} the same page as the one before; the title's own mapping calls {:.0}, {:.1} \ + ms, {:.0} pages; views for disk writes {:.0}, {:.1} ms", + t(T::RemapUnmapCalls), + on(T::RemapUnmapCycles, T::RemapUnmapTsc), + t(T::RemapUnmapC0), + ms(T::RemapUnmapU0), + t(T::RemapUnmapC1), + ms(T::RemapUnmapU1), + t(T::RemapUnmapC2), + ms(T::RemapUnmapU2), + t(T::RemapUnmapC3), + ms(T::RemapUnmapU3), + t(T::RemapMapCalls), + on(T::RemapMapCycles, T::RemapMapTsc), + t(T::RemapMapC0), + ms(T::RemapMapU0), + t(T::RemapMapC1), + ms(T::RemapMapU1), + t(T::RemapMapC2), + ms(T::RemapMapU2), + t(T::RemapMapC3), + ms(T::RemapMapU3), + t(T::RemapMapRetries), + t(T::RemapSplits), + t(T::RemapSplitsDone), + ms(T::RemapSplitUs), + t(T::RemapAliasCalls), + ms(T::RemapAliasUs), + t(T::PageMapCalls), + t(T::PageMapRanges0), + t(T::PageMapPages0), + t(T::PageMapRanges1), + t(T::PageMapPages1), + t(T::PageMapRanges2), + t(T::PageMapPages2), + t(T::RemapAliasPages), + t(T::RemapAliasRunPages), + t(T::RemapAliasSamePages), + t(T::RemapDirectCalls), + ms(T::RemapDirectUs), + t(T::RemapDirectPages), + t(T::DiskViews), + ms(T::DiskViewUs), + ) +} + +/// The mean of `frames` (not empty). +fn mean(frames: &[&Frame]) -> Frame { + let n = frames.len() as f64; + let mut out = Frame { number: 0, at: 0.0, us: 0.0, t: [0.0; N], s: [0.0; S], h: [0.0; HN] }; + for f in frames { + out.us += f.us / n; + for i in 0..N { + out.t[i] += f.t[i] / n; + } + for i in 0..S { + out.s[i] += f.s[i] / n; + } + for i in 0..HN { + out.h[i] += f.h[i] / n; + } + } + out +} + +/// Over how many microseconds a frame is long, the usual one being +/// `usual`: half as long again, and at least 40 ms more. +fn long_over(usual: f64) -> f64 { + (usual * 1.5).max(usual + 40_000.0) +} + +/// The lines of a reading: the frame times, the usual frame, the long ones. +fn lines(frames: &[Frame], usual: f64, seconds: f64) -> Vec<String> { + let over = long_over(usual); + let (long, plain): (Vec<&Frame>, Vec<&Frame>) = frames.iter().partition(|f| f.us > over); + let each: Vec<String> = frames.iter().map(|f| format!("{:.0}", f.us / 1e3)).collect(); + let shortest = frames.iter().map(|f| f.us).fold(f64::INFINITY, f64::min); + let longest = frames.iter().map(|f| f.us).fold(0.0, f64::max); + let mut out = vec![format!( + "frame times: {} frames in {seconds:.1} s: shortest {:.0} ms, median {:.0}, longest {:.0}; {} long (over {:.0} ms, \ + the usual frame of the last {RECENT} being {:.0}); each: {}", + frames.len(), + shortest / 1e3, + median(frames.iter().map(|f| f.us)) / 1e3, + longest / 1e3, + long.len(), + over / 1e3, + usual / 1e3, + each.join(" ") + )]; + if !plain.is_empty() { + out.push(format!("usual frame (the mean of {} not long): {}", plain.len(), text(&mean(&plain)))); + } + for f in long.iter().take(LONG_MOST) { + out.push(format!("long frame {} at {:.1} s: {}", f.number, f.at, text(f))); + } + if long.len() > LONG_MOST { + out.push(format!("long frames: {} more in this reading are not listed", long.len() - LONG_MOST)); + } + out +} + +/// Frames whose lengths give the usual one, and the long frames listed in +/// a reading at most. +const RECENT: usize = 64; +const LONG_MOST: usize = 8; + +/// A frame ends: called at the end of the title's present call, on the +/// thread that made it. +pub fn frame() { + // Try 6.16: the card meter's lines also without the frame log (Try's + // builds have neither by default; VICTORY_CARD_METER=1 alone gave no + // line, its pairs were never read). + crate::cardmeter::collect(); + if !on() { + return; + } + add(T::RenderLooks, 1); + if on_slow_core() { + add(T::RenderSlow, 1); + } + let now = std::time::Instant::now(); + let totals: [u64; N] = std::array::from_fn(|i| TOTAL[i].load(Relaxed)); + let sampled = sample(); + let here = HERE.with(|c| c.replace([0; HN])); + // SAFETY: a plain query. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let state = state.get_or_insert_with(|| State { + first: now, + last: None, + number: 0, + frames: Vec::new(), + since: now, + recent: std::collections::VecDeque::new(), + }); + state.number += 1; + if let Some((then, t0, s0, thread0)) = state.last.replace((now, totals, sampled, thread)) { + let mut f = Frame { + number: state.number, + at: (now - state.first).as_secs_f64(), + us: (now - then).as_micros() as f64, + t: std::array::from_fn(|i| totals[i].wrapping_sub(t0[i]) as i64 as f64), + s: std::array::from_fn(|i| sampled[i].wrapping_sub(s0[i]) as i64 as f64), + h: here.map(|v| v as f64), + }; + f.s[S_FREE_MB] = sampled[S_FREE_MB] as f64; + if thread != thread0 { + // Another thread presented: its processor time is not this frame's. + (f.s[S_THREAD_USER], f.s[S_THREAD_KERNEL]) = (0.0, 0.0); + } + state.frames.push(f); + } + let elapsed = state.since.elapsed(); + if elapsed < std::time::Duration::from_secs(5) || state.frames.is_empty() { + return; + } + let frames = std::mem::take(&mut state.frames); + state.since = now; + // The usual frame: the median of the last frames, this reading's with + // those before it. + for f in &frames { + if state.recent.len() == RECENT { + state.recent.pop_front(); + } + state.recent.push_back(f.us); + } + let usual = median(state.recent.iter().copied()); + for line in lines(&frames, usual, elapsed.as_secs_f64()) { + tracing::info!("{line}"); + } + tracing::info!("{}", kinds(&frames)); +} + +/// Host submissions a frame from which a frame counts as one of the world: +/// the title's frame there is a burst (9 to 12 host submissions at the boat +/// save, 29 in the first rooms); its menus, fades and loading screens send +/// two or three and run at the title's own 30 a second. +const WORLD_SUBMISSIONS: f64 = 6.0; + +/// One more line of a reading: the frames of the world apart from the +/// others, each kind with its own time. A run's frames a second over "the +/// world phase" counted both: runs 306 and 308 (the boat save) read 9.1 and +/// 9.6 a second with 6.7 and 6.2 in the world's own frames, and run 309 +/// read 9.3 with 8.7 there, so a gain of a third looked like none. +fn kinds(frames: &[Frame]) -> String { + let (world, other): (Vec<&Frame>, Vec<&Frame>) = + frames.iter().partition(|f| f.t[T::Submissions as usize] >= WORLD_SUBMISSIONS); + let sum = |v: &[&Frame]| v.iter().map(|f| f.us).sum::<f64>(); + let (w, o) = (sum(&world), sum(&other)); + format!( + "frames by kind: {} of the world ({WORLD_SUBMISSIONS:.0} or more host submissions) in {:.1} s: mean {:.0} ms, {:.2} a second while they ran; {} menu or loading frames (fewer submissions) in {:.1} s: mean {:.0} ms", + world.len(), + w / 1e6, + w / 1e3 / world.len().max(1) as f64, + world.len() as f64 * 1e6 / w.max(1.0), + other.len(), + o / 1e6, + o / 1e3 / other.len().max(1) as f64 + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frame(number: u64, ms: f64) -> Frame { + let mut f = Frame { number, at: number as f64, us: ms * 1e3, t: [0.0; N], s: [0.0; S], h: [0.0; HN] }; + f.t[T::PresentUs as usize] = ms * 100.0; + f.t[T::Uploads as usize] = ms; + f + } + + #[test] + fn a_long_frame_is_listed_beside_the_usual_one() { + let frames: Vec<Frame> = [150.0, 160.0, 140.0, 400.0, 150.0].iter().enumerate().map(|(i, &ms)| frame(i as u64, ms)).collect(); + let out = lines(&frames, 150_000.0, 1.0); + assert_eq!(out.len(), 3, "{out:#?}"); + assert!(out[0].starts_with("frame times: 5 frames in 1.0 s: shortest 140 ms, median 150, longest 400; 1 long (over 225 ms"), "{}", out[0]); + assert!(out[0].ends_with("each: 150 160 140 400 150"), "{}", out[0]); + // The usual frame is the mean of the four that are not long. + assert!(out[1].starts_with("usual frame (the mean of 4 not long): 150 ms |"), "{}", out[1]); + assert!(out[1].contains("in the present call 15.0 "), "{}", out[1]); + assert!(out[1].contains(" 150 uploads"), "{}", out[1]); + assert!(out[2].starts_with("long frame 3 at 3.0 s: 400 ms |"), "{}", out[2]); + assert!(out[2].contains("in the present call 40.0 "), "{}", out[2]); + assert!(out[2].contains(" 400 uploads"), "{}", out[2]); + } + + #[test] + fn long_is_half_as_long_again_and_at_least_40_ms_more() { + assert_eq!(long_over(150_000.0), 225_000.0); + assert_eq!(long_over(30_000.0), 70_000.0); + } + + #[test] + fn more_long_frames_than_are_listed_are_counted() { + let mut frames: Vec<Frame> = (0..12).map(|i| frame(i, 500.0)).collect(); + frames.push(frame(12, 100.0)); + let out = lines(&frames, 100_000.0, 5.0); + assert_eq!(out.iter().filter(|l| l.starts_with("long frame ")).count(), LONG_MOST); + assert!(out.last().unwrap().starts_with("long frames: 4 more"), "{out:#?}"); + } + + #[test] + fn totals_and_a_threads_own_counts_add_up() { + let before = TOTAL[T::DiskReads as usize].load(Relaxed); + add(T::DiskReads, 3); + sub(T::DiskReads, 1); + assert_eq!(TOTAL[T::DiskReads as usize].load(Relaxed) - before, 2); + here(H::PaceUs, 5); + here(H::PaceUs, 6); + assert_eq!(HERE.with(|c| c.get())[H::PaceUs as usize], 11); + } +} diff --git a/crates/victory-gpu/src/heap_pass.rs b/crates/victory-gpu/src/heap_pass.rs new file mode 100644 index 0000000000..59cbdec5f5 --- /dev/null +++ b/crates/victory-gpu/src/heap_pass.rs @@ -0,0 +1,439 @@ +//! Bookkeeping of the pass over the view heap's buffer views for shaders +//! that pick them by a computed index (`draw::State::heap_buffers`): which +//! slots it looks at again, and the span of each host copy their views +//! read. Kept apart from D3D12 so that it can be tested alone. +//! +//! The pass used to look again at every buffer view of the heap (81,000 in +//! the world) every 16 passes, and to rebuild the spans of all host copies +//! from all views every pass. Now a slot is looked at again only when +//! - its buffer view was written or went (the heap's own set of changes); +//! - the view table entry its record names was freed (the title released +//! the resource: `descriptor::forget`), which leaves the record as it was; +//! - its record in title memory is not the one seen at the last look (a +//! record copied by the title itself, past the API); a compare of 12 +//! bytes per slot in slot order, no lock and no lookup; +//! - it found no host copy at its last look: every 16 passes, as before; +//! - every [`FULL_EVERY`] passes, all of them, as a safety net. +//! +//! The span of a copy is worked out again only when one of its slots went. +//! +//! From fork pull request #523, as darkworldhm's snapshot carries it. Here +//! the pass is taken only with `VICTORY_HEAP_PASS_MARKED` ([`marked`]); +//! unset, `draw::State::heap_buffers` runs as it always did. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +/// Passes between two looks at every slot, besides those marked. +pub(crate) const FULL_EVERY: u64 = 256; +/// Passes between two looks at slots that found no host copy (and between +/// two looks at every slot with the old pass). +pub(crate) const ORPHANS_EVERY: u64 = 16; + +/// What `VICTORY_HEAP_PASS_MARKED` says: 0 unset (off), 1 on, 2 in turn. +fn mode() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_HEAP_PASS_MARKED").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) +} + +/// Whether the switch is set at all (`1` or `alt`): the table entries freed +/// are then noted for the pass (`descriptor::forget`), in both phases of +/// `alt`. +pub(crate) fn marked_set() -> bool { + mode() != 0 +} + +/// Set when `alt` turns the marked pass on again: what it kept is from +/// before the other pass's turn, and the other pass took the heap's changes +/// meanwhile. The marked pass then starts anew (every slot), and has the +/// other pass start anew at its next turn. +pub(crate) static RESUMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Set when `alt` turns the marked pass off: see [`marked_paused`]. +static PAUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// With `alt` only: whether the marked pass's turn has just ended (true +/// once for each end), so that what it kept can be let go for the other +/// pass's turn. False, with nothing but the switch read, when the switch +/// is unset or `1`. +pub(crate) fn marked_paused() -> bool { + mode() == 2 && PAUSED.swap(false, std::sync::atomic::Ordering::Relaxed) +} + +/// Whether the pass over the heap's buffer views looks only at marked +/// slots now (`VICTORY_HEAP_PASS_MARKED=1`; off by default: every slot +/// every 16 passes, as before). `alt`: twenty seconds with, twenty without, +/// in turn, each change said in the log; the first pass of each turn looks +/// at every slot. +pub(crate) fn marked() -> bool { + match mode() { + 0 => false, + 1 => true, + _ => { + use std::sync::atomic::Ordering::Relaxed; + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Relaxed) != u8::from(on) { + if on { + RESUMED.store(true, Relaxed); + } else { + PAUSED.store(true, Relaxed); + } + tracing::info!( + "the pass over the heap's buffer views looks only at marked slots from now (VICTORY_HEAP_PASS_MARKED=alt): {}", + if on { "ON" } else { "off, every slot every 16 passes as usual" } + ); + } + on + } + } +} + +/// A slot's record in title memory: the tag and two words +/// (`descriptor::record_at`). +pub(crate) type Record = [u32; 3]; + +struct Slot { + copy: usize, + from: u64, + to: u64, + record: Record, +} + +struct Copy<C> { + copy: C, + slots: HashSet<u32>, + from: u64, + to: u64, + /// A slot went: the span is worked out again from those left. + stale: bool, +} + +/// What a pass looks at (see the module). +pub(crate) struct Picked<C> { + passes: u64, + /// In slot order: every pass reads the record of each of them from + /// title memory ([`Picked::plan`]), and in the order of a hash table + /// those reads fall all over the heap. With 163,000 views kept the + /// plan took 1,195 ms of the 10 s profiled that way (run st-x-play, + /// 9 ms a frame) and 262 ms in slot order (run st-y-play, 2 ms). + slots: BTreeMap<u32, Slot>, + copies: HashMap<usize, Copy<C>>, + /// Slots that found no host copy, with the record seen. In slot order + /// as `slots` is. + orphans: BTreeMap<u32, Record>, + /// View table entry -> slots whose record named it at their last look + /// (some may name another by now: checked when used). + by_entry: HashMap<u32, Vec<u32>>, + /// Table entries freed since the last pass; `None`: not known. + forgotten: Option<Vec<u32>>, + /// The old pass's rules, kept for the tests. + full: bool, +} + +impl<C: Clone> Picked<C> { + pub(crate) fn new(full: bool) -> Self { + Picked { + passes: 0, + slots: BTreeMap::new(), + copies: HashMap::new(), + orphans: BTreeMap::new(), + by_entry: HashMap::new(), + forgotten: None, + full, + } + } + + /// View table entries were freed (`None`: some were, which is not + /// known): their slots are looked at next pass. Every heap's pass is + /// told, though one of them asks. + pub(crate) fn note_forgotten(&mut self, entries: Option<&[u32]>) { + match (entries, &mut self.forgotten) { + (Some(new), Some(kept)) => kept.extend_from_slice(new), + _ => self.forgotten = None, + } + } + + /// The slots this pass looks at again, in order. `changed`: the slots + /// whose buffer view was written or went since the last pass (and the + /// entries [`Picked::note_forgotten`] was told of: if it was told it + /// does not know, all slots are looked at); `all`: every slot that holds a + /// buffer view; `record`: a slot's record now; `entry`: the table + /// entry a record names, if it names one. + pub(crate) fn plan( + &mut self, + changed: Vec<u32>, + all: impl FnOnce() -> Vec<u32>, + record: impl Fn(u32) -> Option<Record>, + entry: impl Fn(Record) -> Option<u32>, + ) -> Vec<u32> { + let pass = self.passes; + self.passes += 1; + let forgotten = self.forgotten.replace(Vec::new()); + if self.full { + if pass.is_multiple_of(ORPHANS_EVERY) { + self.clear(); + return all(); + } + return changed; + } + let Some(forgotten) = forgotten else { + self.clear(); + return all(); + }; + if pass.is_multiple_of(FULL_EVERY) { + self.clear(); + return all(); + } + let mut due = changed; + for e in forgotten { + if let Some(slots) = self.by_entry.remove(&e) { + // Only those whose record still names the entry. + due.extend( + slots + .into_iter() + .filter(|s| self.record_of(*s).is_some_and(|r| entry(r) == Some(e))), + ); + } + } + due.extend(self.slots.iter().filter(|&(&slot, kept)| record(slot) != Some(kept.record)).map(|(&slot, _)| slot)); + let orphans_too = pass.is_multiple_of(ORPHANS_EVERY); + due.extend( + self.orphans.iter().filter(|&(&slot, &seen)| orphans_too || record(slot) != Some(seen)).map(|(&slot, _)| slot), + ); + due.sort_unstable(); + due.dedup(); + due + } + + /// The record seen at slot `slot`'s last look, if it is kept. + pub(crate) fn record_of(&self, slot: u32) -> Option<Record> { + self.slots + .get(&slot) + .map(|s| s.record) + .or_else(|| self.orphans.get(&slot).copied()) + } + + fn clear(&mut self) { + self.slots.clear(); + self.copies.clear(); + self.orphans.clear(); + self.by_entry.clear(); + } + + /// What slot `slot` held is let go (it is looked at now). + pub(crate) fn forget(&mut self, slot: u32) { + self.orphans.remove(&slot); + let Some(old) = self.slots.remove(&slot) else { + return; + }; + if let Some(copy) = self.copies.get_mut(&old.copy) { + copy.slots.remove(&slot); + if copy.slots.is_empty() { + self.copies.remove(&old.copy); + } else if old.from <= copy.from || old.to >= copy.to { + copy.stale = true; + } + } + } + + /// Slot `slot` (with `record`, naming table entry `entry`) reads title + /// memory `[from, to)` through host copy `copy` (`key`: its identity). + #[allow(clippy::too_many_arguments)] + pub(crate) fn keep(&mut self, slot: u32, key: usize, copy: &C, from: u64, to: u64, record: Record, entry: Option<u32>) { + self.forget(slot); + self.note_entry(slot, entry); + self.slots.insert(slot, Slot { copy: key, from, to, record }); + let c = self.copies.entry(key).or_insert_with(|| Copy { + copy: copy.clone(), + slots: HashSet::new(), + from, + to, + stale: false, + }); + c.slots.insert(slot); + c.from = c.from.min(from); + c.to = c.to.max(to); + } + + /// Slot `slot` holds a buffer view whose memory has no host copy yet. + pub(crate) fn orphan(&mut self, slot: u32, record: Record, entry: Option<u32>) { + self.forget(slot); + self.note_entry(slot, entry); + self.orphans.insert(slot, record); + } + + fn note_entry(&mut self, slot: u32, entry: Option<u32>) { + // Only kept with the incremental pass (the old one does not use it). + if let Some(e) = entry + && !self.full + { + // (Maybe twice: the pass's set of due slots takes it once.) + self.by_entry.entry(e).or_default().push(slot); + } + } + + /// The views kept. + pub(crate) fn views(&self) -> usize { + self.slots.len() + } + + /// Per host copy, the span its views read: `(copy, from, to)`. + pub(crate) fn spans(&mut self) -> Vec<(C, u64, u64)> { + if self.full { + // As the old pass did: from every view, every pass. + let mut spans: HashMap<usize, (u64, u64)> = HashMap::new(); + for s in self.slots.values() { + let span = spans.entry(s.copy).or_insert((s.from, s.to)); + span.0 = span.0.min(s.from); + span.1 = span.1.max(s.to); + } + return spans + .into_iter() + .filter_map(|(key, (from, to))| Some((self.copies.get(&key)?.copy.clone(), from, to))) + .collect(); + } + let slots = &self.slots; + self.copies + .values_mut() + .map(|c| { + if c.stale { + c.stale = false; + let (mut from, mut to) = (u64::MAX, 0); + for s in c.slots.iter().filter_map(|s| slots.get(s)) { + from = from.min(s.from); + to = to.max(s.to); + } + (c.from, c.to) = (from, to); + } + (c.copy.clone(), c.from, c.to) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A heap of slots with records, as title memory holds them. + struct Heap { + records: HashMap<u32, Record>, + } + + impl Heap { + fn record(&self, slot: u32) -> Option<Record> { + self.records.get(&slot).copied() + } + } + + fn entry(r: Record) -> Option<u32> { + Some(r[1]) + } + + /// One pass: plans, then "looks" at each due slot: a slot reads 16 + /// bytes from `slot * 16` of copy `slot / 4`. + fn pass(p: &mut Picked<u32>, heap: &Heap, changed: Vec<u32>, forgotten: Vec<u32>) -> Vec<u32> { + p.note_forgotten(Some(&forgotten)); + let due = p.plan( + changed, + || { + let mut all: Vec<u32> = heap.records.keys().copied().collect(); + all.sort_unstable(); + all + }, + |s| heap.record(s), + entry, + ); + for &slot in &due { + let Some(record) = heap.record(slot) else { + p.forget(slot); + continue; + }; + let copy = slot / 4; + let from = u64::from(slot) * 16; + p.keep(slot, copy as usize, ©, from, from + 16, record, entry(record)); + } + due + } + + fn heap(n: u32) -> Heap { + Heap { + records: (0..n).map(|s| (s, [1, 100 + s, 1])).collect(), + } + } + + #[test] + fn only_slots_changed_since_the_last_pass_are_looked_at_again() { + let mut heap = heap(64); + let mut p = Picked::new(false); + // The first pass looks at all of them. + assert_eq!(pass(&mut p, &heap, vec![], vec![]).len(), 64); + assert_eq!(p.views(), 64); + // Nothing changed: nothing is looked at. + assert!(pass(&mut p, &heap, vec![], vec![]).is_empty()); + // A view written through the API. + heap.records.insert(5, [1, 500, 1]); + assert_eq!(pass(&mut p, &heap, vec![5], vec![]), vec![5]); + // A record copied past the API: found by its words alone. + heap.records.insert(9, [1, 900, 1]); + assert_eq!(pass(&mut p, &heap, vec![], vec![]), vec![9]); + // The resource of entry 117 (slot 17) released: the record is as + // it was, the slot is looked at all the same; slot 5 no longer + // names its old entry 105 and is not. + assert_eq!(pass(&mut p, &heap, vec![], vec![117, 105]), vec![17]); + // And the next pass leaves them alone again. + assert!(pass(&mut p, &heap, vec![], vec![]).is_empty()); + } + + #[test] + fn a_slot_that_went_shrinks_its_copy_span() { + let mut heap = heap(8); + let mut p = Picked::new(false); + pass(&mut p, &heap, vec![], vec![]); + let span = |p: &mut Picked<u32>, copy: u32| p.spans().into_iter().find(|s| s.0 == copy).map(|s| (s.1, s.2)); + assert_eq!(span(&mut p, 1), Some((64, 128))); + heap.records.remove(&7); + pass(&mut p, &heap, vec![7], vec![]); + assert_eq!(span(&mut p, 1), Some((64, 112))); + for s in 4..7 { + heap.records.remove(&s); + } + pass(&mut p, &heap, vec![4, 5, 6], vec![]); + assert_eq!(span(&mut p, 1), None); + assert_eq!(span(&mut p, 0), Some((0, 64))); + } + + #[test] + fn orphans_are_tried_again_every_16_passes_and_all_slots_now_and_then() { + let heap = heap(4); + let mut p: Picked<u32> = Picked::new(false); + let _ = p.plan(vec![], || vec![0, 1, 2, 3], |s| heap.record(s), entry); + for s in 0..3 { + p.keep(s, 0, &0, 0, 16, heap.record(s).unwrap(), None); + } + p.orphan(3, heap.record(3).unwrap(), None); + for n in 1..FULL_EVERY { + let due = p.plan(vec![], || vec![0, 1, 2, 3], |s| heap.record(s), entry); + let want: Vec<u32> = if n.is_multiple_of(ORPHANS_EVERY) { vec![3] } else { vec![] }; + assert_eq!(due, want, "pass {n}"); + } + let due = p.plan(vec![], || vec![0, 1, 2, 3], |s| heap.record(s), entry); + assert_eq!(due, vec![0, 1, 2, 3]); + } + + #[test] + fn the_old_pass_looks_at_all_every_16_passes() { + let heap = heap(4); + let mut p: Picked<u32> = Picked::new(true); + for n in 0..40u64 { + let due = p.plan(vec![2], || vec![0, 1, 2, 3], |s| heap.record(s), entry); + let want: Vec<u32> = if n.is_multiple_of(ORPHANS_EVERY) { vec![0, 1, 2, 3] } else { vec![2] }; + assert_eq!(due, want, "pass {n}"); + } + } +} diff --git a/crates/victory-gpu/src/heap_worker.rs b/crates/victory-gpu/src/heap_worker.rs new file mode 100644 index 0000000000..7ad742f840 --- /dev/null +++ b/crates/victory-gpu/src/heap_worker.rs @@ -0,0 +1,288 @@ +//! The pass that uploads textures picked by index, on a thread of its own +//! (`VICTORY_HEAP_WORKER=1`; off by default; needs `VICTORY_LATE_WAIT`). +//! +//! [`crate::draw::State::heap_textures`] runs on whichever thread of the +//! title records the frame's first shader that picks textures by index: it +//! asks what of each due texture is mapped, makes the host texture, makes a +//! staging buffer and records the copy, up to 250 ms of every frame while a +//! backlog waits, and the threads waiting for that list wait with it. The +//! detiling of what it recorded then runs on the thread that submits. With +//! the switch the pass runs here, and the recording thread only wakes it. +//! +//! What keeps the picture as it was: +//! - the uploads are recorded into host lists of ours ([`Batch`]), which the +//! next submission of the title's runs ahead of its own lists +//! ([`take_ready`]): texture states are settled by submission order, as +//! between any two lists; +//! - a texture's host slot is given its view at that submission, not before +//! ([`Publish`]): until then shaders see what the slot showed, never a +//! texture without its contents. (A host texture may be placed in memory +//! another texture had: `crate::placed`.) A slot the title wrote again +//! meanwhile is left to the write's own turn in the queue; +//! - the detiling done here is checked at submission as any texture's is: +//! memory the title wrote in between is read again; +//! - a title texture the pass works on is held ([`crate::resource::hold`]), +//! and so is the title's heap; +//! - the uploads before the title's decoration bake, which must be there +//! for that draw, still run on the recording thread; the worker makes way +//! for them ([`urgent`]). +// shortcut: what a submission shows for a texture is up to a frame later +// than when the recording thread did it all; with a backlog it is earlier, +// since the pass has the whole frame instead of a slice of it. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; + +use crate::descriptor::Heap; +use crate::host::HostList; +use crate::object::This; + +/// Whether the pass runs on its own thread now. +pub(crate) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_WORKER").is_some_and(|v| v == "1")) && crate::host::late() +} + +/// For the frame line, since the last one: nanoseconds the worker was at +/// work, of them detiling, lists given to submissions, textures published, +/// slots the title had written again, and textures in those lists whose +/// detiling was not done here. +pub(crate) static STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +/// One upload list holds at most this much texture memory, or this many +/// milliseconds of work, so that its textures show soon. +const LIST_BYTES: u64 = 48 << 20; +const LIST_MS: u128 = 40; + +/// A view to give a host slot once its texture's upload is in the queue: +/// the title's heap, the slot, the record's handle, and the record's key as +/// it was when the upload was recorded. +pub(crate) struct Publish { + heap: usize, + index: u32, + handle: u64, + key: u64, +} + +/// Holds a reference to a title heap. +struct HeldHeap(This); +// SAFETY: a reference counted title object, of which only the count and the +// parts behind locks are touched. +unsafe impl Send for HeldHeap {} + +impl HeldHeap { + fn new(heap: &Heap) -> Self { + let this = std::ptr::from_ref(heap).cast(); + crate::object::add_ref(this); + HeldHeap(this) + } + + fn heap(&self) -> &Heap { + crate::descriptor::heap(self.0) + } +} + +impl Drop for HeldHeap { + fn drop(&mut self) { + crate::object::release_boxed::<Heap>(self.0); + } +} + +/// A closed upload list, and what is published when it is submitted. +struct Ready { + list: HostList, + publish: Vec<Publish>, + _heap: HeldHeap, +} +// SAFETY: D3D12 objects are free-threaded; the list is closed and touched +// by nobody until it is taken out. +unsafe impl Send for Ready {} + +static READY: Mutex<Vec<Ready>> = Mutex::new(Vec::new()); + +fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// What a pass on the worker's thread records into: one upload list after +/// the other, made when first needed. +pub(crate) struct Batch { + heap: This, + list: Option<HostList>, + publish: Vec<Publish>, + bytes: u64, + began: std::time::Instant, +} + +impl Batch { + fn new(heap: &Heap) -> Self { + Batch { + heap: std::ptr::from_ref(heap).cast(), + list: None, + publish: Vec::new(), + bytes: 0, + began: std::time::Instant::now(), + } + } + + /// The open upload list. + pub(crate) fn list(&mut self) -> Option<&HostList> { + if self.list.is_none() { + self.list = crate::list::fresh_list(); + self.began = std::time::Instant::now(); + } + self.list.as_ref() + } + + /// Slot `index` (its record at `handle`, then with `key`) shows its + /// texture when the open list is submitted. `bytes` were uploaded. + pub(crate) fn publish(&mut self, index: u32, handle: u64, key: u64) { + self.publish.push(Publish { heap: self.heap as usize, index, handle, key }); + } + + /// `bytes` more of texture memory in the open list, which is closed + /// and handed over when it holds enough. + pub(crate) fn uploaded(&mut self, bytes: u64) { + self.bytes += bytes; + if self.bytes >= LIST_BYTES || self.began.elapsed().as_millis() >= LIST_MS { + self.flush(); + } + } + + /// Detiles what the open list uploads, closes it and hands it to the + /// next submission. + fn flush(&mut self) { + self.bytes = 0; + let publish = std::mem::take(&mut self.publish); + let Some(list) = self.list.take() else { + return; + }; + let started = std::time::Instant::now(); + let left = list.refresh_textures_ahead(); + STATS[1].fetch_add(started.elapsed().as_nanos() as u64, Relaxed); + STATS[5].fetch_add(left, Relaxed); + list.close(); + let heap = HeldHeap::new(crate::descriptor::heap(self.heap)); + lock(&READY).push(Ready { list, publish, _heap: heap }); + } +} + +impl Drop for Batch { + fn drop(&mut self) { + self.flush(); + } +} + +/// The upload lists ready now, for the submission about to be made, which +/// runs them ahead of its own lists; their host slots are given their views. +/// Called by the thread that submits. +pub(crate) fn take_ready() -> Vec<HostList> { + // (Asked without the lock by every submission of a run without it.) + if JOB.get().is_none() { + return Vec::new(); + } + let ready = std::mem::take(&mut *lock(&READY)); + STATS[2].fetch_add(ready.len() as u64, Relaxed); + ready + .into_iter() + .map(|r| { + for p in &r.publish { + let Some(host) = crate::descriptor::heap(p.heap as This).host() else { + continue; + }; + let shown = host.publish(p.index, p.handle, p.key); + STATS[if shown { 3 } else { 4 }].fetch_add(1, Relaxed); + } + r.list + }) + .collect() +} + +/// The heap the next pass is over, and what wakes the worker. +struct Job { + heap: Mutex<Option<HeldHeap>>, + wake: Condvar, +} + +static JOB: OnceLock<Job> = OnceLock::new(); +/// Held by whoever runs the pass. +static PASS: Mutex<()> = Mutex::new(()); +/// A recording thread waits for [`PASS`]. +static URGENT: AtomicBool = AtomicBool::new(false); + +/// A pass over `heap` is due (once a frame). False if there is no worker: +/// the caller runs the pass itself. +pub(crate) fn kick(heap: &Heap) -> bool { + if !on() { + return false; + } + static STARTED: OnceLock<bool> = OnceLock::new(); + let started = *STARTED.get_or_init(|| { + JOB.get_or_init(|| Job { heap: Mutex::new(None), wake: Condvar::new() }); + match std::thread::Builder::new().name("victory-heap".into()).spawn(worker) { + Ok(_) => { + tracing::info!("textures picked by index are uploaded by a thread of their own (VICTORY_HEAP_WORKER)"); + true + } + Err(e) => { + tracing::warn!(error = %e, "no thread for textures picked by index"); + false + } + } + }); + let Some(job) = JOB.get().filter(|_| started) else { + return false; + }; + *lock(&job.heap) = Some(HeldHeap::new(heap)); + job.wake.notify_one(); + true +} + +/// Takes the pass from the worker for the caller, which cannot wait for a +/// later submission: what the worker has recorded so far is handed over +/// first, so the caller's list runs behind it. +pub(crate) fn urgent() -> MutexGuard<'static, ()> { + if let Ok(pass) = PASS.try_lock() { + return pass; + } + URGENT.store(true, Relaxed); + let pass = lock(&PASS); + URGENT.store(false, Relaxed); + pass +} + +/// Whether the worker is to stop where it is ([`urgent`]). +pub(crate) fn make_way() -> bool { + URGENT.load(Relaxed) +} + +fn worker() { + let Some(job) = JOB.get() else { + return; + }; + loop { + let heap = { + let mut next = lock(&job.heap); + loop { + match next.take() { + Some(heap) => break heap, + None => next = job.wake.wait(next).unwrap_or_else(|e| e.into_inner()), + } + } + }; + let started = std::time::Instant::now(); + { + let _pass = lock(&PASS); + let heap = heap.heap(); + if let Some(host) = heap.host() { + let mut batch = Batch::new(heap); + crate::draw::State::heap_textures(crate::draw::Into::Ahead(&mut batch), heap, host); + } + } + STATS[0].fetch_add(started.elapsed().as_nanos() as u64, Relaxed); + // Whoever wants the pass now has it first. + while make_way() { + std::thread::yield_now(); + } + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4a23d32bfb..d54be651e6 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1,7 +1,8 @@ //! The host GPU: one D3D12 device and direct queue (decision 0007), and a //! window to present on. //! -//! shortcut: every submission is waited for, so CPU and GPU never overlap; +//! shortcut: every submission is waited for, so CPU and GPU never overlap +//! (unless `VICTORY_LATE_WAIT=1`, see [`late`]); //! overlap them with per-submission fences once more than clears run. use std::sync::atomic::{AtomicU32, Ordering}; @@ -34,8 +35,9 @@ pub(crate) fn texture_state(state: u32) -> u32 { /// Render target views live only until their command is recorded, so a /// ring of host descriptors is enough. const RTV_RING: u32 = 1024; -/// Maximum number of detached host lists kept for reuse after pending resets. -const LIST_POOL_CAP: usize = 64; + +/// Whether the host device has GPU upload heaps (asked when it is made). +static GPU_UPLOAD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); pub(crate) struct Host { pub(crate) device: ID3D12Device, @@ -55,10 +57,9 @@ pub(crate) struct Host { messages: Option<ID3D12InfoQueue>, next_rtv: AtomicU32, presenter: Mutex<Option<Presenter>>, - /// Detached host lists whose submissions finished, ready to reuse. - free_lists: Mutex<Vec<HostList>>, - #[cfg(test)] - reused_lists: std::sync::atomic::AtomicU64, + /// The adapter the device is on, for its memory budget + /// ([`Host::video_memory`]); `None` if the system does not name it. + adapter: Option<IDXGIAdapter3>, } // SAFETY: D3D12 devices, queues, fences and descriptor heaps are @@ -67,43 +68,284 @@ unsafe impl Send for Host {} // SAFETY: as above. unsafe impl Sync for Host {} -/// Time spent in submissions since the last frame-rate line, in -/// microseconds: preparing them on the CPU (title memory copies, texture -/// detiling), then waiting for the GPU. /// Host objects the title let go of while a submission may still use them /// (a texture its descriptors name, a descriptor slot's old resource), by /// the submission count they wait for. The title's descriptor writes and /// releases reach the host at once, from its own threads, while the host -/// runs a submission for most of a second in the world: freeing there was -/// a GPU page fault on the freed texture (DXGI_ERROR_DEVICE_HUNG, -/// 2026-11-24, RX 7600). +/// runs a submission: freeing there is a GPU page fault on the freed +/// texture (a device hang). static RETIRED: Mutex<Vec<(u64, Retired)>> = Mutex::new(Vec::new()); /// Submissions started and finished (waited for). static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +/// Microseconds of a submission's preparing by part, since the frame-rate +/// line last took them: the asking and the look under flights, the lists' +/// steps, the flush of refreshes, the snapshots and the wait for card +/// results, `card_before`, the hand-over to the card. An instrument: the +/// frame line's "preparing" had 19 to 23 ms a frame no line split (run 282). +static PREP_PARTS: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + +/// Adds the time since `since` to part `i` of [`PREP_PARTS`]; now. +fn prep_part(i: usize, since: std::time::Instant) -> std::time::Instant { + let now = std::time::Instant::now(); + PREP_PARTS[i].fetch_add((now - since).as_micros() as u64, Ordering::Relaxed); + now +} + +/// Submissions started and not finished yet: lists the card may still be +/// running, which read the view heap's slots as they run. +pub(crate) fn submissions_in_flight() -> u64 { + STARTED.load(Ordering::Relaxed).saturating_sub(FINISHED.load(Ordering::Relaxed)) +} + /// A retired object, dropped on whatever thread finishes the submission. struct Retired(#[allow(dead_code)] Box<dyn std::any::Any>); // SAFETY: what is retired is D3D12 objects (free-threaded) and the // reference-counted wrappers holding them, dropped once. unsafe impl Send for Retired {} +/// Milliseconds since the first call. +pub(crate) fn now_ms() -> u64 { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// This moment, for telling later how long ago it was ([`long_ago`]): the +/// frames begun so far (high half, `crate::frame::current`) and tenths of a +/// second since the start. Host copies of title memory, staging buffers and +/// host textures note when they were last used with it. +pub(crate) fn moment() -> u64 { + (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff) +} + +/// Whether `moment` lies at least `ms` milliseconds and `frames` frames +/// back. Both: at seconds per frame, what every frame uses is not touched +/// for seconds, and at many frames per second not for many frames. (A title +/// that never waits for frames has no frame count: nothing is then idle.) +pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool { + let now = self::moment(); + let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff); + (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms +} + +/// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`. +pub(crate) fn available_physical_ram() -> Option<u64> { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32; + // SAFETY: a sized structure. + let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0; + ok.then_some(m.ullAvailPhys) +} + +/// Effective idle timeout (in milliseconds) for VRAM-backed host textures, +/// scaled down under VRAM pressure. Never returns less than 1,000 ms so +/// handles not yet recorded into a list or slot remain protected. +pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 { + const NORMAL_MS: u64 = 5_000; + const MODERATE_MS: u64 = 2_500; + const HIGH_MS: u64 = 1_000; + let Some([budget, used, ..]) = video_memory else { + return NORMAL_MS; + }; + if budget == 0 { + return NORMAL_MS; + } + let used_pct = (u128::from(used) * 100) / u128::from(budget); + if used_pct >= 85 { + HIGH_MS + } else if used_pct >= 75 { + MODERATE_MS + } else { + NORMAL_MS + } +} + +/// Effective idle timeout (in milliseconds) for system-RAM caches (staging +/// buffers, loose shadows, and the mapped pipeline library), scaled down +/// when free physical RAM is low. Never returns less than 2,000 ms. +pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 { + const GIB: u64 = 1024 * 1024 * 1024; + const NORMAL_MS: u64 = 10_000; + const MODERATE_MS: u64 = 5_000; + const HIGH_MS: u64 = 2_000; + let Some(avail) = avail_phys else { + return NORMAL_MS; + }; + if avail < 2 * GIB { + HIGH_MS + } else if avail < 4 * GIB { + MODERATE_MS + } else { + NORMAL_MS + } +} + +/// How many references are held on a host object (its COM count): ours +/// all, since the host's views and commands hold none. A buffer or texture +/// with one is held by its owner alone: no descriptor slot keeps it +/// (`HostHeap::kept`) and no list (`HostList::keep`). +pub(crate) fn references(object: &impl Interface) -> u32 { + type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32; + let raw = object.as_raw(); + // SAFETY: a live COM object, whose first three methods are those of + // `IUnknown` (query, add a reference, release one); the pair leaves the + // count as it was, and the release returns it. The first is not called. + unsafe { + let methods = *raw.cast::<*const [Method; 3]>(); + ((*methods)[1])(raw); + ((*methods)[2])(raw) + } +} + +/// When [`sweep`] last ran ([`now_ms`]). +static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The next [`sweep`] runs at the next submission, not a second after the +/// last (an allocation was refused: `crate::pressure::refused`). +pub(crate) fn sweep_soon() { + SWEPT.store(0, Ordering::Relaxed); +} + +/// Once a second, before a submission starts: lets go of what nothing +/// names any more (copies of windows of title memory, staging buffers, +/// host copies of textures the title fills). +/// `VICTORY_SWEEP=0` keeps everything, as before. +fn sweep() { + // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`). + crate::inplace::tick(); + static ON: OnceLock<bool> = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) { + return; + } + let now = now_ms(); + let last = SWEPT.load(Ordering::Relaxed); + if now < last + 1000 + || SWEPT + .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed) + .is_err() + { + return; + } + // (Short of memory: kept upload buffers no list holds go first.) + if crate::pressure::level() != crate::pressure::Level::Normal { + trim_upload_spare(); + } + crate::pipeline::trim_library(); + crate::shadow::let_go_idle(); + crate::texture::let_go_idle(); + crate::resource::let_go_idle(); +} + /// Drops `object` once every submission running now has finished: at once /// if none is. pub(crate) fn retire<T: 'static>(object: T) { let started = STARTED.load(Ordering::Acquire); if started <= FINISHED.load(Ordering::Acquire) { - drop(object); + RETIREMENTS[0].fetch_add(1, Ordering::Relaxed); + if retire_lean() && !reaper_on() { + // Dropped here, as `reap` would, without a list made for it. + drop(object); + return; + } + reap(vec![Retired(Box::new(object))]); return; } + RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); RETIRED .lock() .unwrap_or_else(|e| e.into_inner()) .push((started, Retired(Box::new(object)))); } +/// Whether descriptor slots written again with the object they already +/// held let the old reference go at once instead of retiring it, and +/// [`bury`] sorts what it drops outside the lock (`VICTORY_RETIRE_LEAN=1`; +/// `alt`: twenty seconds with, twenty without, in turn, each change said in +/// the log). Off by default. +/// +/// Why: run 313 retired 36.8 million host objects in about 240 s (some +/// 150,000 a second, about ten a draw at the boat save): every write of a +/// descriptor slot of ours retires the reference it held +/// (`HostHeap::keep`), each a boxed object pushed under one lock that the +/// recording threads, the submitting thread (`sync_heaps`) and the thread +/// that lands flights share, and [`bury`] held that lock while it sorted +/// the whole list at every landing. A slot written again with the same +/// object keeps that object alive through the new reference: its old one +/// can go at once (a reference count that cannot reach zero). +pub(crate) fn retire_lean() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock<u8> = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_RETIRE_LEAN").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "descriptor slots written again with the same object let the old reference go at once from now (VICTORY_RETIRE_LEAN=alt): {}", + if on { "ON" } else { "off, retired as usual" } + ); + } + on + } + } +} + +/// Descriptor slots written since the start (`HostHeap::keep`): with an +/// object where they held one, and of those the ones that held the same +/// object; and the old references let go at once for that +/// ([`retire_lean`]). Said every 2^20 writes of the first kind. +pub(crate) static SLOT_REWRITES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Counts a slot write that replaced `old` by `new` and says whether the +/// old reference may go at once (the same object, [`retire_lean`] on). +pub(crate) fn slot_rewritten(old: &ID3D12Resource, new: Option<&ID3D12Resource>) -> bool { + let same = new.is_some_and(|new| new.as_raw() == old.as_raw()); + let before = SLOT_REWRITES[0].fetch_add(1, Ordering::Relaxed); + if same { + SLOT_REWRITES[1].fetch_add(1, Ordering::Relaxed); + } + let lean = same && retire_lean(); + if lean { + SLOT_REWRITES[2].fetch_add(1, Ordering::Relaxed); + } + if (before + 1).is_multiple_of(1 << 20) { + tracing::info!( + "descriptor slots written over an object they held: {} so far, {} of them with the same object; {} old references let go at once (VICTORY_RETIRE_LEAN), the rest retired", + before + 1, + SLOT_REWRITES[1].load(Ordering::Relaxed), + SLOT_REWRITES[2].load(Ordering::Relaxed) + ); + } + lean +} + /// Drops what waited for submissions up to `finished`. fn bury(finished: u64) { + if retire_lean() { + // Taken out whole, sorted with no lock held, what still waits put + // back (beside what was retired meanwhile; the order means nothing). + let all = std::mem::take(&mut *RETIRED.lock().unwrap_or_else(|e| e.into_inner())); + if all.is_empty() { + return; + } + let (done, keep): (Vec<(u64, Retired)>, Vec<(u64, Retired)>) = + all.into_iter().partition(|(at, _)| *at <= finished); + if !keep.is_empty() { + RETIRED.lock().unwrap_or_else(|e| e.into_inner()).extend(keep); + } + reap(done.into_iter().map(|(_, object)| object).collect()); + return; + } let done: Vec<(u64, Retired)> = { let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); if retired.is_empty() { @@ -115,21 +357,762 @@ fn bury(finished: u64) { *retired = keep; done }; - drop(done); + reap(done.into_iter().map(|(_, object)| object).collect()); +} + +/// Whether host objects that are let go are dropped by a thread of their +/// own (`VICTORY_REAPER=1`; `alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log). Off by default. +/// +/// Why: dropping a host texture or buffer is a call into Direct3D and the +/// driver (the allocation destroyed, its card address freed), and it ran on +/// whichever thread let the object go. Profile 307 (the boat save, 169 ms +/// a frame): the submitting thread is 7.8 ms of every frame inside +/// `resource::let_go_idle`, all of it those calls: the once-a-second sweep +/// drops what it lets go at once when nothing is in the air, about 46 ms in +/// one submission's preparing, with the title's present standing behind +/// it. The thread that lands flights does the same for what [`bury`] hands +/// it. +/// +/// With the switch the object goes to a list and a thread of ours drops +/// it. Nothing else changes: an object is handed over at the moment it was +/// dropped before (never earlier: [`retire`] still keeps it while a +/// submission that may use it is running), and it was already dropped on +/// "whatever thread finishes the submission" ([`Retired`]). The card's +/// memory comes back some milliseconds later than before. +fn reaper_on() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock<u8> = OnceLock::new(); + let mode = *MODE.get_or_init(|| { + let asked = match std::env::var("VICTORY_REAPER").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }; + if asked == 0 || std::thread::Builder::new().name("victory-reaper".into()).spawn(reaper).is_err() { + return 0; + } + tracing::info!("host objects that are let go are dropped by a thread of their own (VICTORY_REAPER=1; alt: in turn)"); + asked + }); + match mode { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "host objects let go are dropped by their own thread from now (VICTORY_REAPER=alt): {}", + if on { "ON" } else { "off, by the thread that lets them go as usual" } + ); + } + on + } + } +} + +/// What waits for [`reaper`]. +static REAP: (Mutex<Vec<Retired>>, std::sync::Condvar) = (Mutex::new(Vec::new()), std::sync::Condvar::new()); + +/// Objects [`reaper`] dropped since the start, and the microseconds that took. +static REAPED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Drops `objects`: here, or with [`reaper_on`] on the thread of that name. +fn reap(objects: Vec<Retired>) { + if objects.is_empty() { + return; + } + if !reaper_on() { + drop(objects); + return; + } + REAP.0.lock().unwrap_or_else(|e| e.into_inner()).extend(objects); + REAP.1.notify_one(); +} + +/// The thread of [`reaper_on`]: drops what [`reap`] hands it, with no lock +/// of ours held, and says every 4,096 objects how long the drops took. +fn reaper() { + loop { + let objects = { + let mut waiting = REAP.0.lock().unwrap_or_else(|e| e.into_inner()); + while waiting.is_empty() { + waiting = REAP.1.wait(waiting).unwrap_or_else(|e| e.into_inner()); + } + std::mem::take(&mut *waiting) + }; + let began = std::time::Instant::now(); + let count = objects.len() as u64; + drop(objects); + let us = began.elapsed().as_micros() as u64; + let before = REAPED[0].fetch_add(count, Ordering::Relaxed); + let spent = REAPED[1].fetch_add(us, Ordering::Relaxed) + us; + if (before + count) / 4096 != before / 4096 { + tracing::info!( + "host objects dropped by their own thread (VICTORY_REAPER): {} so far in {:.1} ms of that thread ({:.0} us each); the last batch {count} in {:.1} ms", + before + count, + spent as f64 / 1e3, + spent as f64 / (before + count) as f64, + us as f64 / 1e3 + ); + } + } +} + +/// Objects [`retire`] dropped at once (no submission was running) and +/// kept until a running submission finished, since the start. +static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// What the layer did to the host's objects lately, newest last (sweeps +/// that let host copies go, pipeline library calls, saves and trims): said +/// once when the host device is removed ([`log_removal_context`]), with +/// what the submitting thread and the pipeline workers were doing at that +/// moment. A device the driver removes "internally" names no command, and +/// the pass that happens to notice first names only the view it was at: +/// the three such losses of runs 72, 73 and 82 each came within 5 ms of a +/// pipeline library call that no line of the log tied to them. +/// `VICTORY_TRAIL=0`: nothing is kept and nothing is said. +static TRAIL: Mutex<std::collections::VecDeque<(u64, u32, String)>> = Mutex::new(std::collections::VecDeque::new()); +/// The entries kept. +const TRAIL_MOST: usize = 96; + +fn trail_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0")) +} + +/// Microseconds since the first call. +pub(crate) fn now_us() -> u64 { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 +} + +/// The calling thread, as the log's other lines name threads. +pub(crate) fn thread_id() -> u32 { + // SAFETY: a plain query. + unsafe { windows::Win32::System::Threading::GetCurrentThreadId() } +} + +/// Notes something done to the host's objects ([`TRAIL`]); `what` is only +/// run when the trail is kept. +pub(crate) fn trail(what: impl FnOnce() -> String) { + if !trail_on() { + return; + } + let entry = (now_us(), thread_id(), what()); + // Sweeps also go to the log as they happen: the trail is only said at + // a loss, and the driver's errors in the system's event log (run 224's + // first fell inside a sweep of 4,711 host textures) need the sweeps of + // clean runs beside them. + if entry.2.starts_with("sweep:") { + tracing::info!("{}", entry.2); + } + let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); + if trail.len() >= TRAIL_MOST { + trail.pop_front(); + } + trail.push_back(entry); +} + +/// What the submitting thread is doing (0 nothing: between submissions, +/// 1 preparing one, 2 waiting for the card to run it, 3 copying back what +/// it wrote), the lists of that submission, and since when ([`now_us`]). +static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +fn submitting(phase: u64, lists: usize) { + SUBMITTING[1].store(lists as u64, Ordering::Relaxed); + SUBMITTING[2].store(now_us(), Ordering::Relaxed); + SUBMITTING[0].store(phase, Ordering::Relaxed); +} + +/// What was going on when the host device went: whether a submission was +/// on the card, the pipeline library's state and the calls running in it, +/// and the trail. +pub(crate) fn removal_context() -> String { + use std::fmt::Write; + let now = now_us(); + let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0; + let phase = match SUBMITTING[0].load(Ordering::Relaxed) { + 0 => "between submissions (nothing of ours was running on the card)", + 1 => "preparing a submission (nothing of ours was running on the card)", + 2 => "waiting for the card to run a submission", + _ => "copying back what a submission wrote (nothing of ours was running on the card)", + }; + let mut text = format!( + "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}", + SUBMITTING[1].load(Ordering::Relaxed), + ms(SUBMITTING[2].load(Ordering::Relaxed)), + crate::pipeline::library_removal_note(), + RETIREMENTS[0].load(Ordering::Relaxed), + RETIREMENTS[1].load(Ordering::Relaxed), + STARTED.load(Ordering::Relaxed), + FINISHED.load(Ordering::Relaxed), + ); + let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); + let _ = write!(text, "; the last {} things done, newest last:", trail.len()); + for (at, thread, what) in trail.iter() { + let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at)); + } + text } -static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = [ +/// The card's memory at every look since [`video_memory_line`] last took +/// them: the most of the card's own in use, the least its budget was, the +/// most of the PC's shared memory in use, and the looks. A look is every +/// asking of [`Host::video_memory`] (the texture queue's, the card copies') +/// and one of our own at most every tenth of a second +/// ([`Host::video_memory_look`]). The memory line is one look in five +/// seconds: what the card held between two of them was not known (runs 277 +/// and 279 lost the device at 90 and 92 hundredths of the budget by it). +static VIDEO_PEAK: [std::sync::atomic::AtomicU64; 4] = [ + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(u64::MAX), std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0), ]; +/// [`memory_counts`] as they were when [`video_memory_line`] was last said, +/// and when that was ([`now_ms`]). +static MEMORY_MARK: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; + +/// Running totals for [`video_memory_line`] and [`removal_memory`]: the +/// bytes of upload, shared and card buffers made since the start +/// ([`MADE`]), the bytes of host textures alive, the bytes of host copies +/// of textures let go since the start, and host copies of textures made +/// since the start. +fn memory_counts() -> [u64; 6] { + [ + MADE[1].load(Ordering::Relaxed), + MADE[3].load(Ordering::Relaxed), + MADE[5].load(Ordering::Relaxed), + crate::resource::HOST_TEXTURES[1].load(Ordering::Relaxed), + crate::resource::KINDS[3].load(Ordering::Relaxed), + crate::resource::KINDS[6].load(Ordering::Relaxed), + ] +} + +/// With the frame-rate line, about once a second: what the looks at the +/// card's memory saw since the last such line ([`VIDEO_PEAK`], taken), and +/// what was made in that time ([`memory_counts`], noted for the next line +/// and for a removal). `VICTORY_VIDEO_LOOK=0`: no line. +fn video_memory_line() { + if !video_look_on() { + return; + } + let most = VIDEO_PEAK[0].swap(0, Ordering::Relaxed); + let least = VIDEO_PEAK[1].swap(u64::MAX, Ordering::Relaxed); + let shared = VIDEO_PEAK[2].swap(0, Ordering::Relaxed); + let looks = VIDEO_PEAK[3].swap(0, Ordering::Relaxed); + let now = memory_counts(); + let then = [0, 1, 2, 3, 4, 5].map(|i| MEMORY_MARK[i].swap(now[i], Ordering::Relaxed)); + let at = now_ms(); + let before = MEMORY_MARK[6].swap(at, Ordering::Relaxed); + if looks == 0 { + return; + } + tracing::info!( + "video memory in the {} ms since the last such line, at {looks} looks: the card's own in use at most {} MB, its budget at least {} MB, \ + the PC's shared in use at most {} MB; made in that time: upload buffers {} MB, shared buffers {} MB, card buffers {} MB, \ + {} host copies of textures; host textures alive {} MB (then {} MB), {} MB of filled ones let go", + at.saturating_sub(before), + most >> 20, + least >> 20, + shared >> 20, + now[0].saturating_sub(then[0]) >> 20, + now[1].saturating_sub(then[1]) >> 20, + now[2].saturating_sub(then[2]) >> 20, + now[5].saturating_sub(then[5]), + now[3] >> 20, + then[3] >> 20, + now[4].saturating_sub(then[4]) >> 20, + ); +} + +/// Whether the card's memory is looked at between the memory lines +/// (`VICTORY_VIDEO_LOOK=0`: not; on by default). +fn video_look_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIDEO_LOOK").is_none_or(|v| v != "0")) +} + +/// Rows of [`SECOND_ROWS`]: the last seconds a removal's report can say. +const SECONDS: usize = 16; +/// Values a row. +const SECOND_FIELDS: usize = 26; +/// One row a second of the run (the second modulo [`SECONDS`]), kept at +/// every look at the card's memory ([`Host::video_memory`]: ten or more a +/// second) and said only when the host device is removed +/// ([`seconds_text`]). The memory line is one look in five seconds; the +/// five device removals of 2026-11-25 each have at most two lines of it +/// in their last ten seconds. Per row: 0 the second (0: never written); +/// 1-2 the card's own memory in use, most and least; 3-4 its budget, least +/// and most; 5 the PC's shared in use, most; 6 looks; then as they stood +/// at the second's first look: 7 submissions started, 8-10 bytes of +/// upload, shared and card buffers made, 11 host copies of textures made, +/// 12 bytes of filled ones let go, 13 bytes of host textures alive, 14 +/// levels given tiles, 15 calls of `UpdateTileMappings`, 16 tile heaps +/// given back, 17 view slots made again, 18 those made again under a +/// flight, 19 pipelines first handed to a draw; 20-25 the PC: MB free, MB +/// committed, the kernel's MB paged and not paged, handles, this +/// process's private MB. Logging only: a row torn by two threads costs one +/// wrong line of a report. +static SECOND_ROWS: [[std::sync::atomic::AtomicU64; SECOND_FIELDS]; SECONDS] = + [const { [const { std::sync::atomic::AtomicU64::new(0) }; SECOND_FIELDS] }; SECONDS]; + +/// The PC's memory for [`second_look`], once a second: two plain questions +/// to the system (as [`removal_memory`] asks them). +fn pc_memory() -> [u64; 6] { + use windows_sys::Win32::System::ProcessStatus::{ + K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION, PROCESS_MEMORY_COUNTERS, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: plain data the call fills in. + let mut c: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() }; + c.cb = size_of::<PROCESS_MEMORY_COUNTERS>() as u32; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + // SAFETY: plain data the call fills in. + let mut p: PERFORMANCE_INFORMATION = unsafe { std::mem::zeroed() }; + p.cb = size_of::<PERFORMANCE_INFORMATION>() as u32; + // SAFETY: a sized structure. + unsafe { K32GetPerformanceInfo(&mut p, p.cb) }; + let pages = |n: usize| (n as u64 * p.PageSize as u64) >> 20; + [ + pages(p.PhysicalAvailable), + pages(p.CommitTotal), + pages(p.KernelPaged), + pages(p.KernelNonpaged), + u64::from(p.HandleCount), + c.PagefileUsage as u64 >> 20, + ] +} + +/// Notes one look at the card's memory in its second's row +/// ([`SECOND_ROWS`]). The second's first look also notes the counters and +/// asks the system for the PC's memory (once a second). +fn second_look(budget: u64, used: u64, shared: u64) { + use std::sync::atomic::Ordering::Relaxed; + let second = now_ms() / 1000 + 1; + let row = &SECOND_ROWS[second as usize % SECONDS]; + if row[0].swap(second, Relaxed) == second { + row[1].fetch_max(used, Relaxed); + row[2].fetch_min(used, Relaxed); + row[3].fetch_min(budget, Relaxed); + row[4].fetch_max(budget, Relaxed); + row[5].fetch_max(shared, Relaxed); + row[6].fetch_add(1, Relaxed); + return; + } + let counts = memory_counts(); + let remade = crate::descriptor::host::views_remade(); + let tiles = &crate::tiles::STATS; + let values = [ + used, + used, + budget, + budget, + shared, + 1, + STARTED.load(Relaxed), + counts[0], + counts[1], + counts[2], + counts[5], + counts[4], + counts[3], + tiles[5].load(Relaxed), + tiles[6].load(Relaxed), + tiles[8].load(Relaxed), + remade[0], + remade[1], + FIRST_USED.load(Relaxed), + ]; + let pc = pc_memory(); + for (i, v) in values.into_iter().chain(pc).enumerate() { + row[1 + i].store(v, Relaxed); + } + // Once a minute in the log too: what grows over a session (the kernel's + // pools and the handles were read once so far, at run 282's removal). + if second.is_multiple_of(60) { + tracing::info!( + "the PC by the minute: {} MB free, {} MB committed, the kernel's own {} MB paged and {} MB not paged, {} handles, the process {} MB private; {} pipelines first handed to a draw so far", + pc[0], + pc[1], + pc[2], + pc[3], + pc[4], + pc[5], + values[18], + ); + } +} + +/// The rows of [`SECOND_ROWS`] that are of the last [`SECONDS`] seconds, +/// oldest first, each with what its counters gained since the row before. +fn seconds_text() -> String { + use std::fmt::Write; + use std::sync::atomic::Ordering::Relaxed; + let now = now_ms() / 1000 + 1; + let mut rows: Vec<[u64; SECOND_FIELDS]> = SECOND_ROWS + .iter() + .map(|r| std::array::from_fn(|i| r[i].load(Relaxed))) + .filter(|r: &[u64; SECOND_FIELDS]| r[0] != 0 && r[0] + SECONDS as u64 > now) + .collect(); + rows.sort_by_key(|r| r[0]); + let mut text = format!("{} seconds kept, oldest first", rows.len()); + let mut before: Option<[u64; SECOND_FIELDS]> = None; + for r in rows { + let mb = |i: usize| r[i] >> 20; + let _ = write!( + text, + "\n {} s before: the card's own in use {}-{} MB of a budget of {}-{} MB, the PC's shared in use at most {} MB, {} looks; \ + the PC {} MB free, {} MB committed, the kernel's own {} MB paged and {} MB not paged, {} handles, the process {} MB private; \ + host textures alive {} MB", + now.saturating_sub(r[0]), + mb(2), + mb(1), + mb(3), + mb(4), + mb(5), + r[6], + r[20], + r[21], + r[22], + r[23], + r[24], + r[25], + mb(13), + ); + if let Some(b) = before { + let d = |i: usize| r[i].saturating_sub(b[i]); + let _ = write!( + text, + "; since the row before ({} s): {} submissions, buffers made upload {} MB, shared {} MB, card {} MB, {} host copies of textures \ + made, {} MB of filled ones let go, {} levels given tiles in {} calls of UpdateTileMappings, {} tile heaps given back, \ + {} view slots made again ({} under a flight), {} pipelines first handed to a draw", + d(0), + d(7), + d(8) >> 20, + d(9) >> 20, + d(10) >> 20, + d(11), + d(12) >> 20, + d(14), + d(15), + d(16), + d(17), + d(18), + d(19), + ); + } + before = Some(r); + } + text +} + +/// Host pipelines handed to a draw or dispatch for the first time +/// ([`first_use`]), since the start. +static FIRST_USED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +/// The last of them: when ([`now_us`]), the submissions started by then, +/// the frame, the pipeline's shaders. In each of the four removals of +/// 2026-11-25 with reason 0x887A0005 (runs 277, 279, 281, 282) a pipeline +/// was first bound or had just been made 31 to 96 ms before the first +/// call that failed; nothing said which submission carried its first draw. +static FIRST_USES: Mutex<std::collections::VecDeque<(u64, u64, u64, String)>> = Mutex::new(std::collections::VecDeque::new()); + +/// Notes that the made host pipeline `name` goes to a draw or dispatch +/// for the first time in this run (`pipeline::make::ready`). Once per +/// pipeline: a few thousand times a run. +pub(crate) fn first_use(name: &str) { + FIRST_USED.fetch_add(1, Ordering::Relaxed); + let entry = (now_us(), STARTED.load(Ordering::Relaxed), crate::frame::current(), name.to_owned()); + let mut uses = FIRST_USES.lock().unwrap_or_else(|e| e.into_inner()); + if uses.len() >= 48 { + uses.pop_front(); + } + uses.push_back(entry); +} + +/// For a removal's report: the last pipelines first handed to a draw +/// ([`FIRST_USES`]) and, of the lists `runs` (those in the air), which +/// bind each. `bound`: only those a list of `runs` binds. +fn first_uses_text(runs: &[&HostList], bound: bool) -> String { + use std::fmt::Write; + let now = now_us(); + let uses = FIRST_USES.lock().unwrap_or_else(|e| e.into_inner()); + let mut text = format!( + "; pipelines first handed to a draw or dispatch: {} since the start; submissions started {} finished {}; of the last {}{}:", + FIRST_USED.load(Ordering::Relaxed), + STARTED.load(Ordering::Relaxed), + FINISHED.load(Ordering::Relaxed), + uses.len(), + if bound { ", those a list in the air binds" } else { "" } + ); + for (at, started, frame, name) in uses.iter() { + let lists: Vec<usize> = runs + .iter() + .enumerate() + .filter(|(_, r)| r.pipelines.lock().unwrap_or_else(|e| e.into_inner()).contains(name.as_str())) + .map(|(i, _)| i) + .collect(); + if bound && lists.is_empty() { + continue; + } + let _ = write!( + text, + "\n {:.1} ms before, frame {frame}, with {started} submissions started: {name}", + now.saturating_sub(*at) as f64 / 1000.0 + ); + if !lists.is_empty() { + let _ = write!(text, " (bound by lists {lists:?} of the {} in the air)", runs.len()); + } + } + text +} + +/// The memory side of a removal, for [`log_removal_context`]: the process's +/// and the PC's memory at this moment, what the looks at the card's memory +/// saw since the last [`video_memory_line`] ([`VIDEO_PEAK`], not taken), +/// and what was made since that line. Atomics and two plain questions to +/// the system: no lock of ours. +fn removal_memory() -> String { + use windows_sys::Win32::System::ProcessStatus::{ + K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION, PROCESS_MEMORY_COUNTERS, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: plain data the call fills in. + let mut c: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() }; + c.cb = size_of::<PROCESS_MEMORY_COUNTERS>() as u32; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + // SAFETY: plain data the call fills in. + let mut p: PERFORMANCE_INFORMATION = unsafe { std::mem::zeroed() }; + p.cb = size_of::<PERFORMANCE_INFORMATION>() as u32; + // SAFETY: a sized structure. + unsafe { K32GetPerformanceInfo(&mut p, p.cb) }; + // The system counts in pages. + let pages = |n: usize| (n as u64 * p.PageSize as u64) >> 20; + let peak = [0, 1, 2, 3].map(|i| VIDEO_PEAK[i].load(Ordering::Relaxed)); + let then = [0, 1, 2, 3, 4, 5, 6].map(|i| MEMORY_MARK[i].load(Ordering::Relaxed)); + let now = memory_counts(); + format!( + "the process: {} MB private (at most {} MB), {} MB of it in memory (at most {} MB); the PC: {} MB free of {} MB, {} MB committed of a limit of {} MB \ + (at most {} MB), the kernel's own {} MB paged and {} MB not paged, {} handles; the card's memory at the {} looks since the last line of it: \ + in use at most {} MB, the budget at least {} MB, the PC's shared in use at most {} MB; made in the {} ms since that line: upload buffers {} MB, \ + shared buffers {} MB, card buffers {} MB, {} host copies of textures; host textures alive {} MB (then {} MB), {} MB of filled ones let go", + c.PagefileUsage as u64 >> 20, + c.PeakPagefileUsage as u64 >> 20, + c.WorkingSetSize as u64 >> 20, + c.PeakWorkingSetSize as u64 >> 20, + pages(p.PhysicalAvailable), + pages(p.PhysicalTotal), + pages(p.CommitTotal), + pages(p.CommitLimit), + pages(p.CommitPeak), + pages(p.KernelPaged), + pages(p.KernelNonpaged), + p.HandleCount, + peak[3], + peak[0] >> 20, + if peak[1] == u64::MAX { 0 } else { peak[1] >> 20 }, + peak[2] >> 20, + now_ms().saturating_sub(then[6]), + now[0].saturating_sub(then[0]) >> 20, + now[1].saturating_sub(then[1]) >> 20, + now[2].saturating_sub(then[2]) >> 20, + now[5].saturating_sub(then[5]), + now[3] >> 20, + then[3] >> 20, + now[4].saturating_sub(then[4]) >> 20, + ) +} + +/// Says [`removal_context`] in the log, once: called by whoever finds the +/// host device removed. +pub(crate) fn log_removal_context() { + static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !(trail_on() || dred_any()) || SAID.swap(true, Ordering::Relaxed) { + return; + } + if trail_on() { + tracing::error!("when the host device went: {}", removal_context()); + } + // The memory at this moment: the memory line is up to five seconds + // old, and a card or a PC out of memory would not be in it. + tracing::error!("memory when the host device went: {}", removal_memory()); + // The seconds before it, and the pipelines first drawn with lately + // (the lists in the air are named by the submission's own report). + tracing::error!("the seconds before the host device went: {}", seconds_text()); + tracing::error!("when the host device went{}", first_uses_text(&[], false)); + if let Some(host) = host() { + match host.video_memory_groups() { + Some(_) => host.log_video_memory("where the removal was found"), + None => tracing::error!("video memory where the removal was found: the system gives no numbers (the adapter does not answer)"), + } + } + // With device-removed data on (any form of `VICTORY_D3D12_DRED`): the + // runtime's data too, unless a submission's own report has just asked + // for it. Such a report came only from the three places that wait for + // a submission; a removal found anywhere else (a view being made, a + // tile mapped) printed none of it. Without the lookups in our own + // tables: whoever calls may hold their locks. + if dred_any() + && !DATA_SAID.load(Ordering::Relaxed) + && let Some(host) = host() + { + tracing::error!( + "device-removed data, asked where the removal was found{}", + host.removal_data_of(&[], false) + ); + } +} + +/// Whether [`Host::removal_data`] was asked for (once is enough for +/// [`log_removal_context`]). +static DATA_SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Time spent in submissions since the last frame-rate line, in +/// microseconds: preparing them on the CPU (title memory copies, texture +/// detiling), then waiting for the GPU. +static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = + [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; + +/// Adds to [`SUBMISSION_US`] and to the frame log's totals. +fn submission_us(i: usize, us: u64) { + SUBMISSION_US[i].fetch_add(us, Ordering::Relaxed); + crate::framelog::add([crate::framelog::T::PrepareUs, crate::framelog::T::CardWaitUs][i], us); + if i == 0 { + crate::framelog::add(crate::framelog::T::Submissions, 1); + } +} + +/// Adds to [`PREPARING`]'s copies (time, bytes) and to the frame log's totals. +fn preparing(i: usize, n: u64) { + PREPARING[i].fetch_add(n, Ordering::Relaxed); + crate::framelog::add([crate::framelog::T::CopyUs, crate::framelog::T::CopyBytes][i], n); +} + +/// Adds to [`COPY_BACK`] and to the frame log's totals. +fn copy_back(i: usize, n: u64) { + COPY_BACK[i].fetch_add(n, Ordering::Relaxed); + crate::framelog::add([crate::framelog::T::CopyBackUs, crate::framelog::T::CopyBackBytes][i], n); +} + +/// Adds to [`CARD_CLOCK_US`] and, for the card's idle times, to the frame +/// log's totals. +fn card_clock_us(i: usize, us: u64) { + CARD_CLOCK_US[i].fetch_add(us, Ordering::Relaxed); + match i { + 0 => crate::framelog::add(crate::framelog::T::CardIdleUs, us), + 1 => crate::framelog::add(crate::framelog::T::CardIdleBehindUs, us), + _ => {} + } +} + /// After submissions: shader-written ranges compared and copied back into /// title memory (microseconds, bytes that differed), since the last /// frame-rate line. -static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = [ - std::sync::atomic::AtomicU64::new(0), - std::sync::atomic::AtomicU64::new(0), -]; +static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = + [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; + +/// The card's clock, for the frame line of every run, in microseconds since +/// the last one: how long the card had nothing of ours queued; how much of +/// that while the thread that holds the submission lock was working (the +/// card idle behind us: preparing and copying back are done with the card +/// standing); and how long that thread stood waiting for the card. +/// +/// Every send of lists to the queue is followed by a signal on a fence of +/// the clock's own ([`Host::card_sent`]). A thread of the clock waits for +/// the newest signal and notes the moment the card reached it with nothing +/// newer sent; the next send ends that idle stretch. +static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Of the thread that holds the submission lock: the microseconds it has +/// worked so far (preparing, copying back; not its waits for the card), and +/// since when it works now ([`now_us`] plus one; 0: it does not). +static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The thread that holds the submission lock starts (`on`) or stops +/// working; whether it worked until now. +fn working(on: bool) -> bool { + let now = now_us() + 1; + let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed); + if since != 0 { + WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed); + } + since != 0 +} + +/// [`WORKING`] as of now: microseconds worked so far. +fn worked() -> u64 { + let since = WORKING[1].load(Ordering::Relaxed); + let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 }; + WORKING[0].load(Ordering::Relaxed) + now +} + +/// The thread that holds the submission lock stood waiting for the card +/// from `since` until now ([`CARD_CLOCK_US`]). +fn stood(since: std::time::Instant) { + card_clock_us(2, since.elapsed().as_micros() as u64); +} + +/// What [`CARD_CLOCK_US`] is measured with. +struct CardClock { + fence: ID3D12Fence, + /// Signals sent so far; and, while the card has reached the last of + /// them, since when and what [`worked`] said then. + state: Mutex<(u64, Option<(std::time::Instant, u64)>)>, + sent: std::sync::Condvar, +} + +// SAFETY: a fence (free-threaded) behind a lock. +unsafe impl Send for CardClock {} +// SAFETY: as above. +unsafe impl Sync for CardClock {} + +/// The clock's thread: waits for the newest signal sent and notes when the +/// card got there with nothing newer behind it. +fn card_clock_watch(clock: &'static CardClock) { + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + return; + }; + let mut seen = 0; + loop { + let target = { + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + while state.0 == seen { + state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner()); + } + state.0 + }; + // SAFETY: the clock's fence and this thread's event. + unsafe { + if clock.fence.SetEventOnCompletion(target, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + } + seen = target; + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.0 == target && state.1.is_none() { + state.1 = Some((std::time::Instant::now(), worked())); + } + } +} + +/// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the +/// frame's time. +fn card_clock_line(frames: f64, ms: f64) { + let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + tracing::info!( + "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \ + {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \ + had not submitted; the submitting thread stood waiting for the card {stood:.1} ms", + if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 } + ); +} /// Of the preparing: title memory copies (microseconds, bytes) and texture /// refreshes (microseconds, bytes hashed), since the last frame-rate line. @@ -140,6 +1123,48 @@ pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ std::sync::atomic::AtomicU64::new(0), ]; +/// Host buffers made since the start, as (count, bytes): in the upload heap +/// (staging, list scratch), shared with the processor (host copies of title +/// memory) and the graphics card's own (indirect arguments, twins' copies). +/// For the memory line: against what is alive, they show what was let go. +pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + +/// What of that is alive now, for the memory line (`MADE` counts what was +/// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60, +/// and nothing said how many were alive): host lists; the lists' scratch +/// chunks and their bytes; of those, the chunks no list holds (kept for the +/// next list, [`Spare`]) and their bytes; chunks taken from those kept +/// instead of made, since the start; and the lists' other upload buffers +/// (texture data copied from buffers, scratch too big for a chunk) and +/// their bytes. +pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; + +/// About host lists, for the memory line: lists made by the host since the +/// start; preludes made (a list's second allocator and list, made when it +/// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the +/// bytes the process's private memory grew by while lists were being made +/// (what a list costs: host objects with the driver's command memory; 631 +/// lists were alive in run 65, each with a prelude it may never use). +/// Then the lists alive that were never reset since they were made: the +/// host sides of title lists the title made and has not used (a host list +/// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title +/// makes at its start). +pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// The process's private bytes (diagnostics: around the making of lists). +#[cfg(feature = "diagnostics")] +fn private_bytes() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + c.PagefileUsage as u64 +} + /// What the runtime does when the host GPU fails for good: report it like a /// crash and end the run. The console has no such state, and carrying on /// draws nothing at seconds per frame. @@ -159,16 +1184,20 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! { // SAFETY: a plain query. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } { text.push_str(&format!("; device removed: {e}")); + log_removal_context(); } match host.log_messages() { Some(first) => text.push_str(&format!("; debug layer: {first}")), - None if host.messages.is_none() => { - text.push_str("; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command") - } + None if host.messages.is_none() => text.push_str( + "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command", + ), None => {} } } tracing::error!("{text}"); + // Tests have no log: the reason goes to their output. + #[cfg(test)] + eprintln!("host GPU failure: {text}"); match ON_FAILURE.get() { Some(report) => report(&text), None => std::process::abort(), @@ -190,6 +1219,12 @@ pub(crate) fn host() -> Option<&'static Host> { } fn create() -> windows::core::Result<Host> { + crate::drvwatch::start(); + crate::spread::start(); + // Diagnostics: RenderDoc, if asked for, before any graphics interface + // is made (`VICTORY_RENDERDOC`). + #[cfg(feature = "diagnostics")] + crate::renderdoc::load(); // SAFETY: plain D3D12 object creation with valid descriptions. unsafe { // The debug layer only in builds with diagnostics. @@ -221,68 +1256,119 @@ fn create() -> windows::core::Result<Host> { } // Diagnostics: device-removed data (the command that faulted, the // faulting address), read when the device is removed. - if dred_on() { + if dred_any() { + let mode = dred_mode(); let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None; if D3D12GetDebugInterface(&mut dred).is_ok() && let Some(dred) = dred { - dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + // `faults`: no breadcrumbs (the runtime then adds nothing + // to the commands), only the faulting address. + if mode != Dred::Faults { + dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + } dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + tracing::info!("device-removed data on: {}", mode.text()); + } else { + tracing::warn!( + "device-removed data was asked for ({}) and the runtime gave no settings for it: none will be kept", + mode.text() + ); } } let mut device: Option<ID3D12Device> = None; - let mut chosen: Option<DXGI_ADAPTER_DESC1> = None; // Diagnostics: the software adapter, on which a shader's wild access // is an access violation in this process (a crash report with the // address and instruction) instead of a GPU fault and driver reset. - if warp_on() { + if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); } else { - let filter = std::env::var("VICTORY_ADAPTER") - .ok() - .filter(|s| !s.trim().is_empty()); - match pick_hardware_adapter(filter.as_deref()) { - Ok((adapter, desc)) => { - D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; - chosen = Some(desc); - } - Err(e) if filter.is_some() => return Err(e), - Err(_) => { - D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; + // Try 6.0: on the adapter Windows ranks fastest (the NVIDIA card, + // not the CPU's own graphics on a laptop); the default pick if + // that fails. + crate::console::log_adapters(); + let fast = crate::console::fast_adapter(); + let made = fast.as_ref().is_some_and(|adapter| { + D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_ok() && device.is_some() + }); + if made { + if let Some(Ok(desc)) = fast.as_ref().map(|a| a.GetDesc1()) { + let end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + tracing::info!( + name = String::from_utf16_lossy(&desc.Description[..end]).as_str(), + own_mb = desc.DedicatedVideoMemory as u64 >> 20, + "host device on the high-performance adapter (VICTORY_ADAPTER=first: the first one)" + ); } + } else { + device = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; } } let device = device.ok_or_else(windows::core::Error::empty)?; - // Lane counts: without 64-lane waves (NVIDIA, Intel) the translation - // runs the console's 64-lane waves through group-shared memory where - // it can (victory_shader::emit::host_wave64). Set before the first - // translation, which the shader cache's key includes. - let mut lanes = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the + // driver compiling shaders again on the "D3D Background Thread"s, + // for minutes after pipelines were made or loaded) is switched off. + // An experiment: while those threads ran, the same shot took + // 1,000-1,200 ms a frame, and 830-950 ms from the moment they + // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default: + // whether the card is slower with the shaders it then keeps is not + // known. + if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0") + && let Ok(device6) = device.cast::<ID3D12Device6>() + { + let set = device6.SetBackgroundProcessingMode( + D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK, + D3D12_MEASUREMENTS_ACTION_KEEP_ALL, + None, + None, + ); + tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)"); + } + // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose + // cross-lane code stays in 32-lane halves translated for waves of 32 + let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); if device - .CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS1, - (&raw mut lanes).cast(), - size_of_val(&lanes) as u32, - ) + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32) .is_ok() { - victory_shader::emit::set_host_wave64(lanes.WaveLaneCountMin, lanes.WaveLaneCountMax); - tracing::info!( - min = lanes.WaveLaneCountMin, - max = lanes.WaveLaneCountMax, - wave64 = victory_shader::emit::host_wave64(), - "host wave lanes" - ); + tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes"); + victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax); } + // Whether the card's own memory can be mapped by the CPU ("GPU + // upload heaps": the card's memory through a resizable BAR). With + // it a host copy the CPU fills and shaders read needs one buffer, + // in the card's memory, and nothing sends it there. + let mut o16 = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + let upload = device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS16, (&raw mut o16).cast(), size_of_val(&o16) as u32) + .is_ok() + && o16.GPUUploadHeapSupported.as_bool(); + GPU_UPLOAD.store(upload, Ordering::Relaxed); + tracing::info!( + supported = upload, + "GPU upload heaps (the card's memory written by the CPU through a resizable BAR; VICTORY_WINDOW_UPLOAD=1 puts windows outside buffers there)" + ); let messages = debug .then(|| device.cast::<ID3D12InfoQueue>().ok()) .flatten(); - let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + // Try 6.0: the queue the title's work runs on asks the card's + // scheduler for high priority (`VICTORY_QUEUE_HIGH=0`: normal, as + // before): it is ahead of the desktop's and other programs' work on + // the card, and of our own keep-awake queue (`awake.rs`). + let queue: ID3D12CommandQueue = match device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + Priority: queue_priority(), ..Default::default() - })?; + }) { + Ok(queue) => queue, + Err(_) => device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?, + }; let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; let event = CreateEventW(None, false, false, None)?; let rtvs: ID3D12DescriptorHeap = @@ -299,18 +1385,10 @@ fn create() -> windows::core::Result<Host> { ..Default::default() })?; let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); - if let Some(desc) = chosen { - let name = adapter_name(&desc.Description); - tracing::info!( - adapter = %name, - vendor = format_args!("{:#06x}", desc.VendorId), - device = format_args!("{:#06x}", desc.DeviceId), - vram_mb = desc.DedicatedVideoMemory >> 20, - "host D3D12 device ready" - ); - } else { - tracing::info!("host D3D12 device ready"); - } + let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid())) + .ok(); + tracing::info!("host D3D12 device ready"); Ok(Host { device, queue, @@ -325,17 +1403,26 @@ fn create() -> windows::core::Result<Host> { messages, next_rtv: AtomicU32::new(0), presenter: Mutex::new(None), - free_lists: Mutex::default(), - #[cfg(test)] - reused_lists: std::sync::atomic::AtomicU64::new(0), + adapter, }) } } -/// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). -/// Reject it before creating a device in diagnostics' software-only mode. -fn warp_adapter() -> windows::core::Result<IDXGIAdapter> { - // SAFETY: plain DXGI adapter queries. +/// The priority of our queues on the card (Try 6.0): high unless +/// `VICTORY_QUEUE_HIGH=0`. +pub(crate) fn queue_priority() -> i32 { + static HIGH: OnceLock<bool> = OnceLock::new(); + if *HIGH.get_or_init(|| std::env::var_os("VICTORY_QUEUE_HIGH").is_none_or(|v| v != "0")) { + D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0 + } else { + D3D12_COMMAND_QUEUE_PRIORITY_NORMAL.0 + } +} + +/// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). +/// Reject it before creating a device in diagnostics' software-only mode. +pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> { + // SAFETY: plain DXGI adapter queries. unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?; @@ -354,6 +1441,154 @@ fn warp_adapter() -> windows::core::Result<IDXGIAdapter> { } } +#[cfg(test)] +mod tests { + /// Run once with VICTORY_CARD_SYNC_BATCH=0 and once with it set to 1. + #[test] + #[ignore = "requires a D3D12 adapter and the card hash pipeline; run alone"] + fn two_dirty_card_buffers_reach_readback_in_the_same_submission() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + const MIB: usize = 1 << 20; + const PIECE: usize = 64 << 10; + let host = super::host().expect("a D3D12 device"); + assert!(host.card_ready(), "the card hash pipeline must be available"); + // SAFETY: a private allocation held through the fenced submissions. + let allocation = unsafe { + VirtualAlloc(std::ptr::null(), 2 * MIB, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + }; + assert!(!allocation.is_null()); + let bases = [allocation as usize, allocation as usize + MIB]; + let shadows = bases.map(|base| { + crate::shadow::register(base, base as u64, MIB as u64); + let copy = crate::shadow::find(base as u64, MIB as u64).unwrap(); + assert!(copy.carded(), "both title buffers must have a card copy"); + copy + }); + let readback = host.read_back_buffer(16).unwrap(); + let hash_readback = host.read_back_buffer(64).unwrap(); + let mut previous = [0u128; 4]; + for round in [0x11u32, 0x55] { + let list = host.new_list().unwrap(); + let mut expected = [0u32; 4]; + for (i, (shadow, &base)) in shadows.iter().zip(&bases).enumerate() { + for (j, offset) in [32, PIECE + 20].into_iter().enumerate() { + let k = 2 * i + j; + expected[k] = round * 0x0101_0101 + k as u32; + // SAFETY: aligned dword in the private allocation. + unsafe { ((base + offset) as *mut u32).write_volatile(expected[k]); } + shadow.refresh(&list, (base + offset) as u64, 4); + // Request the before-hash for each of the two distinct pieces. + shadow.gpu_writes(&list, (base + offset) as u64, 4); + // SAFETY: the readback and the copy outlive this fenced list. + unsafe { list.list.CopyBufferRegion(&readback, (k * 4) as u64, &shadow.buffer, offset as u64, 4); } + } + } + list.close(); + host.execute(&[&list]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: execute waited for all four writes, and the buffer holds 16 bytes. + let got = unsafe { + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let got = mapped.cast::<[u32; 4]>().read_unaligned(); + readback.Unmap(0, None); + got + }; + assert_eq!(got, expected, "both copied pieces of each buffer"); + let hash_list = host.new_list().unwrap(); + for (i, shadow) in shadows.iter().enumerate() { + let hashes = shadow.card_sides().unwrap().1.expect("before-hashes were made"); + // SAFETY: two consecutive 16-byte piece hashes from each live buffer. + unsafe { hash_list.list.CopyBufferRegion(&hash_readback, (32 * i) as u64, &hashes, 0, 32); } + } + hash_list.close(); + host.execute(&[&hash_list]); + // SAFETY: all 64 bytes of the readback were written and fenced. + let current = unsafe { + hash_readback.Map(0, None, Some(&mut mapped)).unwrap(); + let words = mapped.cast::<[u128; 4]>().read_unaligned(); + hash_readback.Unmap(0, None); + words + }; + for (i, hash) in current.iter().enumerate() { + assert_ne!(*hash, previous[i], "piece {i} must be rehashed"); + assert!(!current[..i].contains(hash), "each piece has different input"); + } + previous = current; + } + for base in bases { + crate::shadow::unregister(base, base as u64); + } + drop(shadows); + // SAFETY: the lists completed and the copies were unregistered. + unsafe { VirtualFree(allocation, 0, MEM_RELEASE); } + } + + #[test] + fn sparse_copies_preserve_islands_and_observe_remaps() { + use windows_sys::Win32::System::Memory::*; + const N: usize = 5 << 16; + // SAFETY: we reserve a private region, commit selected pages inside it, + // and only directly access the pages while they are writable. + unsafe { + let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>(); + assert!(!base.is_null()); + let mut expected = vec![0; N]; + for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] { + let at = base.add(offset); + assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + at.write_bytes(value, 4096); + expected[offset..offset + 4096].fill(value); + } + for remap in [false, true] { + if remap { + let mut old = 0; + assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0); + expected[..4096].fill(0); + let at = base.add(1 << 16); + assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + at.write_bytes(0xc7, 4096); + expected[1 << 16..(1 << 16) + 4096].fill(0xc7); + } + let mut out = vec![0xee; N]; + super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false); + assert_eq!(out[27..N - 27], expected[27..N - 27]); + assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee)); + } + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); + } + } + + use super::*; + + #[test] + fn warp_adapter_accepts_only_software() { + // This probes DXGI without creating a D3D12 device or running a title. + // SAFETY: plain DXGI adapter queries. + let raw = unsafe { + let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)) + else { + return; + }; + factory.EnumWarpAdapter::<IDXGIAdapter>() + }; + let Ok(raw) = raw else { return }; + // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements + // IDXGIAdapter1; `raw` owns that interface. + let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() }; + eprintln!( + "EnumWarpAdapter: vendor={:#x}, flags={:#x}", + desc.VendorId, desc.Flags + ); + assert_eq!( + warp_adapter().is_ok(), + desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, + ); + } +} + /// A host command list and its allocator, always used together. pub(crate) struct HostList { allocator: ID3D12CommandAllocator, @@ -370,27 +1605,43 @@ pub(crate) struct HostList { /// list names alive until it is reset, even if the title releases the /// resource first. states: Mutex<States>, - /// The list that runs those transitions just before this one. - prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), - /// Memory handed out for the list's recording, kept until it is finished - /// when the title reset or dropped the list while a submission of it was - /// still to run. - kept_uploads: Mutex<Vec<Vec<u8>>>, - /// Dynamic descriptor slots kept alongside `kept_uploads` until the pending - /// submission completes. - kept_dynamic: Mutex<Vec<(usize, u32, u32)>>, + /// What the list does with depth textures that have a colour twin, by + /// twin ([`TwinUse`]). + twins: Mutex<std::collections::HashMap<usize, TwinUse>>, + /// The list that runs those transitions just before this one, made + /// when the list first has such transitions ([`lazy_prelude`]). + prelude: OnceLock<Option<Prelude>>, /// The pipelines the list binds, for reports of slow submissions. pipelines: Mutex<std::collections::BTreeSet<String>>, /// The work its indirect executions may still do (`indirect`): a - /// shader-writable word, zeroed when the list is submitted. + /// shader-writable word, zeroed when the list is submitted, and after + /// it what the clamp notes about mesh records. In memory the CPU maps. budget: OnceLock<Option<(ID3D12Resource, usize)>>, - /// GPU-writable scratch for indirect rectangle expansion (`rectangles`): - /// expanded vertices, rewritten draw arguments and per-draw atomic - /// counters, reused across draws and across resets. - rect_scratch: Mutex<RectScratch>, - /// A CPU-only heap of one UAV slot, for the CPU descriptor of a UAV - /// clear, made on first use. - clear_uav_cpu: OnceLock<Option<ID3D12DescriptorHeap>>, + /// The same words in the card's own memory ([`card_budget`]), which the + /// clamp uses instead when there is one: zeroed in the list before its + /// first clamp, its notes copied to `budget` when the list closes. + card_budget: OnceLock<Option<ID3D12Resource>>, + /// Device-local scratch buffer for clamped indirect arguments (`indirect`), + /// grown to the largest indirect execution recorded on the list. + indirect_args: Mutex<Option<(ID3D12Resource, u64)>>, + /// The buffers of `crate::indirect::window_check`, made at its first use. + window_check: OnceLock<Option<crate::indirect::WindowCheck>>, + /// The window of indirect draws clamped together (`crate::indirect::clamp_window`), if one is open. + clamp_window: Mutex<Option<crate::indirect::Window>>, + /// Occlusion queries begun on the host in this list and not ended in it (`crate::query`, `VICTORY_OCCLUSION`): + /// host heap, console kind, index, console heap. + open_queries: Mutex<Vec<(ID3D12QueryHeap, u32, u32, usize)>>, + /// Counts the list in [`ALIVE`] while it lives. + _alive: Counted, + /// The pair of timestamps its run is timed with since its last reset + /// (`crate::cardmeter`), or none. + meter: AtomicU32, + /// With `crate::cardmeter::pipelines`: the pair of the pipeline bound + /// last, open until the next one is bound or the list closes. + pipeline_meter: AtomicU32, + /// The records its draws read from slots that its prelude fills + /// (`crate::indirect::gather`). + gather: Mutex<Gather>, /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] @@ -399,21 +1650,82 @@ pub(crate) struct HostList { /// and at the end, and where they are read back. #[cfg(feature = "diagnostics")] stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>, + /// While a frame shot records (`crate::shot`): the block of its + /// timestamps the list fills (first place, places used, the shot's + /// number), or zeros. + #[cfg(feature = "diagnostics")] + pub(crate) shot_block: Mutex<(u32, u32, u32)>, + /// The frame of a shot the list was recorded in (the shot's number) and + /// the line its recording began at, or zeros. + #[cfg(feature = "diagnostics")] + pub(crate) shot_mark: Mutex<(u32, u32)>, } -impl Drop for HostList { - fn drop(&mut self) { - self.release_kept(); - } +/// A list's prelude: an allocator and a closed list. +type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); + +/// What a list gathers for its prelude to clamp (`crate::indirect::gather`). +#[derive(Default)] +struct Gather { + /// Something recorded in the list may write arguments: no record is + /// gathered from here on (the ones gathered before are read before + /// the list runs, which is before that). + closed: bool, + /// With `crate::indirect::gather_by_copy`: the host copies (their + /// numbers) the list's shaders were declared to write so far + /// (`Shadow::gpu_writes`): no record of those is gathered from then on. + written: std::collections::HashSet<u64>, + /// One set per argument buffer, kind and stride. + sets: Vec<crate::indirect::GatherSet>, + /// The budget words the gathered records are charged to. + budget: Option<ID3D12Resource>, + /// Scratch buffers of earlier recordings, kept for the next sets. + spare: Vec<ID3D12Resource>, + /// The passes recorded in the list for records taken after it stopped gathering for its prelude + /// (`crate::indirect::gather_segments`). + segments: Segments, } -// SAFETY: D3D12 lists and allocators may be used from any thread, one at -// a time: the title records a list on one thread at a time, and a -// submission runs it after its recording ended (a reset while one is to -// run moves recording to a new list). The rest is locked. -unsafe impl Send for HostList {} -// SAFETY: as above. -unsafe impl Sync for HostList {} +/// A list's segments' passes (`crate::indirect::gather_segments`). +#[derive(Default)] +struct Segments { + /// The list's buffer of slots, `SEGMENT_PASSES` passes of `SEGMENT_PASS` records of `GATHER_STRIDE` bytes: made at + /// the first pass and kept across recordings. + buffer: Option<ID3D12Resource>, + /// Whether a pass of this recording used the buffer: it is in `INDIRECT_ARGUMENT` from the first pass to the + /// list's end, else common. + used: bool, + /// The passes recorded in this recording. + passes: u32, + /// The passes of the segment open now that take records: none once something that may write arguments ends it. + open: Vec<SegmentPass>, +} + +/// A pass of the open segment: its argument buffer (a host copy, its number), kind and stride, its number in the +/// recording, the records it has, and its table (upload memory of the list: the count, then the records' offsets). +struct SegmentPass { + src: ID3D12Resource, + src_id: u64, + kind: u32, + stride: u32, + pass: u32, + records: u32, + table: usize, +} + +/// The most argument buffers a list gathers from. +const GATHER_SETS: usize = 8; + +/// Whether a host list's prelude is made when the list first needs one. A +/// prelude runs the texture transitions and twin copies a list needs before +/// it; lists that name no texture never have one, and every host list was +/// made with one all the same: twice the host objects per list, for the +/// title's 630 lists and for every list made anew. +/// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before. +fn lazy_prelude() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0")) +} /// Timestamps per list (diagnostics); commands past them are not timed. #[cfg(feature = "diagnostics")] @@ -423,31 +1735,530 @@ const STAMPS: u32 = 4096; #[cfg(feature = "diagnostics")] type Note = (String, Option<(u64, u64)>); -type States = - std::collections::HashMap<usize, (u32, u32, std::sync::Arc<crate::resource::HostTexture>)>; +type States = std::collections::HashMap< + usize, + (u32, u32, std::sync::Arc<crate::resource::HostTexture>), +>; + +/// What a list does with a depth texture that has a colour twin +/// ([`crate::resource::Twin`]). Lists are recorded on many threads and run +/// in submission order, so a list cannot know which side an earlier list +/// leaves behind: it notes which sides it uses as it finds them, and its +/// prelude copies one side into the other at submission if that side is +/// behind then. From its first use of a side on, the list knows. +struct TwinUse { + /// The depth texture (the title resource's host copy) and its twin. + depth: std::sync::Arc<crate::resource::HostTexture>, + twin: std::sync::Arc<crate::resource::Twin>, + /// The sides (depth texture, twin) the list uses as it finds them. + needs: [bool; 2], + /// Whether each side lacks what the other was written last, where the + /// list is now; `None`: as the list found it. + behind: [Option<bool>; 2], + /// The draw or dispatch being prepared writes the twin. + writing: bool, + /// The depth plane's twin holds what the plane lacks although the list + /// copied the twins since: the plane's pass waits for the list's close. + late: bool, +} + +/// The pass that draws the twin of a depth plane into the plane: one +/// triangle over each mip of each slice, its pixel shader writing the +/// twin's texel as the depth, with the depth test "always" and no stencil +/// (the stencil plane is copied through a buffer and not touched here). +/// +/// A 16-bit twin holds whole steps of 1/65535, and the depth written is +/// the step times the float nearest 1/65535 (0x37800080). That is how +/// The title's tiled lighting computes the depth of the +/// rectangles it then draws with the test "equal", one class of materials +/// a draw (all six of its vertex shaders multiply the class number by that +/// constant), so the pass and the draw give the host the same float, and +/// the host turns the same float into the same 24 bits. The step divided +/// by 65535 is another float for 512 of the 65,536 steps (none under 257), +/// and lands in another 24-bit step for 127 of them (none under 385). +const PLANE_CORNERS: &str = r#" +float4 corner(uint i : SV_VertexID) : SV_Position { + return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0); +} +"#; +const PLANE_STEPS: &str = r#" +#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)" +Texture2DArray<uint> twin : register(t0); +[RootSignature(RS)] +float plane(float4 p : SV_Position) : SV_Depth { + return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080); +} +"#; +const PLANE_FLOATS: &str = r#" +#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)" +Texture2DArray<float> twin : register(t0); +[RootSignature(RS)] +float plane(float4 p : SV_Position) : SV_Depth { + return twin.Load(int4(int2(p.xy), 0, 0)); +} +"#; + +/// Views of twins the pass reads, in a heap of ours used as a ring. +/// shortcut: a view must last until its list has run; with one or two +/// passes a frame the ring is far from coming round. +const PLANE_VIEWS: u32 = 256; + +/// What the pass draws with: the heap of its views of twins, and per kind +/// of twin (16-bit steps or floats) and depth format the root signature +/// and pipeline, made when first needed (`None`: the host refused). +struct PlanePass { + views: ID3D12DescriptorHeap, + cpu: usize, + gpu: u64, + step: u32, + next: AtomicU32, + made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>, +} + +/// The pass's root signature and pipeline for one kind of twin and one +/// depth format. +type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState); + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for PlanePass {} +// SAFETY: as above. +unsafe impl Sync for PlanePass {} + +fn plane_pass() -> Option<&'static PlanePass> { + static PASS: OnceLock<Option<PlanePass>> = OnceLock::new(); + PASS.get_or_init(|| { + let host = host()?; + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + // SAFETY: plain heap creation and queries. + unsafe { + let views: ID3D12DescriptorHeap = host + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: PLANE_VIEWS, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + Some(PlanePass { + cpu: views.GetCPUDescriptorHandleForHeapStart().ptr, + gpu: views.GetGPUDescriptorHandleForHeapStart().ptr, + step: host.device.GetDescriptorHandleIncrementSize(kind), + views, + next: AtomicU32::new(0), + made: Mutex::default(), + }) + } + }) + .as_ref() +} + +/// Compiles function `entry` of `source` for `target` with the system's +/// compiler, as the indirect-argument clamp is (`crate::indirect`). +pub(crate) fn compile( + source: &str, + entry: windows::core::PCSTR, + target: windows::core::PCSTR, +) -> windows::core::Result<Vec<u8>> { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option<ID3DBlob> = None; + let mut errors: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; out pointers ours. + let compiled = unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + windows::core::s!("victory"), + None, + None, + entry, + target, + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(e) = compiled { + if let Some(errors) = errors { + // SAFETY: the blob's own bytes. + let text = unsafe { + std::slice::from_raw_parts( + errors.GetBufferPointer().cast::<u8>(), + errors.GetBufferSize(), + ) + }; + tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes. + let bytes = unsafe { + std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()) + }; + Ok(bytes.to_vec()) +} + +impl PlanePass { + /// The root signature and pipeline for a twin of 16-bit steps (`steps`) + /// or of floats and the depth format `format`. + fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) { + return pipeline.clone(); + } + let pipeline = match Self::make(steps, format) { + Ok(pipeline) => Some(pipeline), + Err(e) => { + tracing::warn!( + error = %e, + steps, + format = format.0, + "no pipeline to draw a depth plane from its twin: such planes stay as they are" + ); + None + } + }; + made.push((steps, format.0, pipeline.clone())); + pipeline + } + + fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> { + use windows::core::s; + let device = &host().ok_or_else(windows::core::Error::empty)?.device; + let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?; + let source = if steps { PLANE_STEPS } else { PLANE_FLOATS }; + let ps = compile(source, s!("plane"), s!("ps_5_1"))?; + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + // SAFETY: the root signature is inside the pixel shader; the + // description points at live data and never releases its pointer. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?; + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs[..]), + PS: code(&ps[..]), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Every texel is written; stencil stays off. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + DSVFormat: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?; + Ok((root, pipeline)) + } + } +} + +/// Records into `list` the pass that draws `plane`, the twin of the depth +/// plane of `depth`, into that plane: `depth` in the depth-write state, +/// `plane` readable by pixel shaders. The pass sets the list's descriptor +/// heap, graphics root signature, pipeline, depth target, viewport, +/// scissor and topology and puts none of them back: it is for a list that +/// records nothing of the title's after it. +fn record_plane_pass( + list: &ID3D12GraphicsCommandList, + depth: &ID3D12Resource, + plane: &ID3D12Resource, +) { + let (Some(host), Some(pass)) = (host(), plane_pass()) else { + return; + }; + // SAFETY: live resources. + let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) }; + // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32 + // typeless one floats, read as R32_FLOAT (41). The depth view names + // the depth-stencil format of the texture's family (44: 45, 19: 20). + let steps = twin.Format.0 == 53; + let format = DXGI_FORMAT(match of.Format.0 { + 44 => 45, + 19 => 20, + typed => typed, + }); + let Some((root, pipeline)) = pass.pipeline(steps, format) else { + return; + }; + for slice in 0..u32::from(of.DepthOrArraySize) { + for mip in 0..u32::from(of.MipLevels) { + let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS; + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(if steps { 57 } else { 41 }), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: mip, + MipLevels: 1, + FirstArraySlice: slice, + ArraySize: 1, + ..Default::default() + }, + }, + }; + let target = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: format, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_DSV { + MipSlice: mip, + FirstArraySlice: slice, + ArraySize: 1, + }, + }, + ..Default::default() + }; + let target = host.dsv(depth, Some(&target)); + let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1)); + let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: pass.cpu + (slot * pass.step) as usize, + }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: pass.gpu + u64::from(slot * pass.step), + }; + // SAFETY: an open list; a slot of our heap; live resources and + // objects (the pass's own live as long as the process). + unsafe { + host.device + .CreateShaderResourceView(plane, Some(&view), cpu); + list.SetDescriptorHeaps(&[Some(pass.views.clone())]); + list.SetGraphicsRootSignature(&root); + list.SetPipelineState(&pipeline); + list.SetGraphicsRootDescriptorTable(0, gpu); + list.OMSetRenderTargets(0, None, false, Some(&target)); + list.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: width as f32, + Height: height as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4), + ); + list.DrawInstanced(3, 1, 0, 0); + } + crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed); + } + } +} + +/// Records into `list` the copy of a depth texture into its colour twin +/// (`colour`) or of the twin into the depth texture, both already in their +/// copy states: whole textures of one size in one format family, which the +/// host copies as they are; or, for the twin of a stencil plane, that plane +/// alone, through the twin's buffer. +fn record_twin_copy( + list: &ID3D12GraphicsCommandList, + depth: &ID3D12Resource, + twin: &crate::resource::Twin, + colour: bool, +) { + let (from, to) = if colour { + (depth, &twin.colour.texture) + } else { + (&twin.colour.texture, depth) + }; + crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed); + // shortcut: the depth plane's twin is not given the plane (that is a + // pass the other way: the plane read by a shader, the twin as its + // target). The twin then lacks what draws and clears wrote to the + // plane since shaders last wrote the twin. In the title + // nothing writes that plane but the twin's pass (its 192 draws against + // it only test, run 29), so the twin lacks nothing. Counted. + if colour && twin.plane.is_some() { + crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed); + } + let Some(through) = &twin.through else { + // SAFETY: an open list and two live textures. + unsafe { list.CopyResource(to, from) }; + return; + }; + // A stencil plane and its twin: each mip and slice of the plane goes + // into the buffer, laid out as the host lays the plane out for copies, + // and from the buffer into the other texture, whole subresources both + // times. In the depth texture the stencil plane's subresources follow + // the depth plane's; the twin has the one plane. + let Some(host) = host() else { return }; + // SAFETY: a live texture. + let of = unsafe { depth.GetDesc() }; + let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize); + let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize]; + // SAFETY: a plain query writing `planes` footprints. + unsafe { + host.device.GetCopyableFootprints( + &of, + planes, + planes, + 0, + Some(rows.as_mut_ptr()), + None, + None, + None, + ); + } + let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) }; + let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index, + }, + }; + let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(through) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *row, + }, + }; + let (common, source, dest) = ( + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + // SAFETY: an open list and live resources; the buffer was made as big + // as these footprints, and rests in the common state between copies. + unsafe { + list.ResourceBarrier(&[transition(through, common, dest)]); + for (i, row) in rows.iter().enumerate() { + let index = first_from + i as u32; + list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None); + } + list.ResourceBarrier(&[transition(through, dest, source)]); + for (i, row) in rows.iter().enumerate() { + let index = first_to + i as u32; + list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None); + } + list.ResourceBarrier(&[transition(through, source, common)]); + } +} -/// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics +/// The forms of device-removed data (`VICTORY_D3D12_DRED`, diagnostics /// builds). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Dred { + /// Not set. + Off, + /// Any value but the two below (`1`): breadcrumbs, the faulting + /// address, and a marker with its text before every noted command. + Full, + /// `light`: breadcrumbs and the faulting address, no marker and no + /// text (which list a removed device stopped in, at which of its + /// commands, and the pipelines the list binds). The full form made a + /// frame's recording 2.4 times slower (run 277: 591 ms against 246); + /// how much of that the marker texts are is what this form measures. + Light, + /// `faults`: the faulting address only (no breadcrumbs, no marker, no + /// text), to stay on while the title is played. + Faults, +} + +impl Dred { + /// For the log. + fn text(self) -> &'static str { + match self { + Dred::Off => "off", + Dred::Full => "full: breadcrumbs, page faults, a marker text per command", + Dred::Light => "light: breadcrumbs and page faults, no marker texts", + Dred::Faults => "faults: page faults only, no breadcrumbs", + } + } +} + +/// The form of device-removed data asked for. +pub(crate) fn dred_mode() -> Dred { + static MODE: OnceLock<Dred> = OnceLock::new(); + *MODE.get_or_init(|| { + if !cfg!(feature = "diagnostics") { + return Dred::Off; + } + match std::env::var_os("VICTORY_D3D12_DRED") { + None => Dred::Off, + Some(v) if v == "light" => Dred::Light, + Some(v) if v == "faults" => Dred::Faults, + // Any other value, as before the two above were known. + Some(_) => Dred::Full, + } + }) +} + +/// Whether device-removed data is on in its full form (`VICTORY_D3D12_DRED` +/// set to anything but `light` or `faults`, diagnostics builds): the one +/// in which every noted command gets a marker and a text +/// (`HostList::note_op`). pub(crate) fn dred_on() -> bool { static ON: OnceLock<bool> = OnceLock::new(); - *ON.get_or_init(|| { - cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some() - }) + *ON.get_or_init(|| dred_mode() == Dred::Full) +} + +/// Whether device-removed data is on in any form ([`Dred`]). +pub(crate) fn dred_any() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| dred_mode() != Dred::Off) } -/// Whether the host device is the software adapter (`VICTORY_D3D12_WARP`, -/// diagnostics builds). The variable is set to `1` to compare a run with -/// WARP, so `0` has to turn it off again: a `0` left in the shell (or in a -/// `.bat` that sets it for one command) used to pick WARP as well. -fn warp_on() -> bool { - cfg!(feature = "diagnostics") && warp_switch(std::env::var_os("VICTORY_D3D12_WARP").as_deref()) +/// Whether objects made while frames are drawn are named too +/// ([`name_frame`]): always in the full form (as before); in `light` and +/// `faults` unless `VICTORY_D3D12_DRED_FRAME_NAMES=0`. +fn frame_names() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + dred_on() || (dred_any() && std::env::var_os("VICTORY_D3D12_DRED_FRAME_NAMES").is_none_or(|v| v != "0")) + }) } -/// The `VICTORY_D3D12_WARP` switch, by its value: on when the variable is -/// set to anything but `0`. An empty value counts as on, like every other -/// switch in the README's table. -fn warp_switch(value: Option<&std::ffi::OsStr>) -> bool { - value.is_some_and(|value| value != "0") +/// Host objects named since the start ([`name`]), and those of them made +/// while frames are drawn ([`name_frame`]): each is one `SetName` call. +static NAMED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Indirect mesh dispatches since the last frame line: the largest group +/// count a record asked for, and the groups asked in all (from the lists' +/// budget buffers, a run late). +static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Since the last frame line: the largest group count in x an indirect +/// compute record asked for, and the records that asked for more than the +/// 65,535 one dispatch runs (cut to that: the groups past it do not run). +static COMPUTE_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether a list's indirect-work budget lives in the card's own memory +/// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as +/// before). The clamp charges it with atomics, at least two in a row for +/// every clamp; in mapped memory on a card of its own each of them +/// crosses the bus. +fn card_budget() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0")) } /// Whether each list of a submission runs and is timed on its own, slow @@ -460,21 +2271,87 @@ fn timing() -> bool { } /// Names a host object for the device-removed report, which names the -/// allocations a page fault hit (only with device-removed data on). +/// allocations a page fault hit (only with device-removed data on, in any +/// of its forms: the names are what a faulting address is read by). pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { - if dred_on() + if dred_any() && let Ok(object) = object.cast::<ID3D12Object>() { + // Counted, so that a log says what naming costs: one text and one + // call each. Said at 4,096 and at every doubling after it. + let named = NAMED[0].fetch_add(1, Ordering::Relaxed) + 1; + if named >= 4096 && named.is_power_of_two() { + tracing::info!( + "device-removed data: {named} host objects named so far, {} of them made while frames are drawn", + NAMED[1].load(Ordering::Relaxed) + ); + } // SAFETY: a plain call on a live object. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) }; } } -/// Upload chunks handed out front to back: the chunks, the one in use and -/// the bytes used in it. +/// As [`name`], for an object made while frames are drawn (a list's upload +/// buffer, a texture upload's staging buffer, a read-back buffer: hundreds +/// a second): those are the freed allocations a faulting address is most +/// likely to be found in, so they are named in every form, and +/// `VICTORY_D3D12_DRED_FRAME_NAMES=0` leaves them unnamed in `light` and +/// `faults` ([`frame_names`]). +pub(crate) fn name_frame(object: &impl Interface, text: impl FnOnce() -> String) { + if frame_names() { + NAMED[1].fetch_add(1, Ordering::Relaxed); + name(object, text); + } +} + +/// One in [`ALIVE`]`[0]` while it lives (a host list), and one in +/// [`LISTS`]`[3]` until it is first reset. +struct Counted { + /// Not reset since it was made. + fresh: std::sync::atomic::AtomicBool, +} + +impl Counted { + fn new() -> Counted { + ALIVE[0].fetch_add(1, Ordering::Relaxed); + LISTS[3].fetch_add(1, Ordering::Relaxed); + Counted { + fresh: std::sync::atomic::AtomicBool::new(true), + } + } + + /// The list is reset: it is in use. + fn used(&self) { + if self.fresh.swap(false, Ordering::Relaxed) { + LISTS[3].fetch_sub(1, Ordering::Relaxed); + } + } +} + +impl Drop for Counted { + fn drop(&mut self) { + ALIVE[0].fetch_sub(1, Ordering::Relaxed); + self.used(); + } +} + +/// A chunk of upload memory for lists' scratch data: the buffer, its +/// mapping and its host GPU address. +struct Chunk { + _buffer: ID3D12Resource, + data: usize, + gpu: u64, +} + +// SAFETY: a D3D12 resource (free-threaded) and its persistent mapping, +// written only by the list that holds the chunk. +unsafe impl Send for Chunk {} + +/// Upload chunks handed out front to back: the chunks (each with its +/// bytes), the one in use and the bytes used in it. #[derive(Default)] struct Scratch { - chunks: Vec<(ID3D12Resource, usize, u64)>, + chunks: Vec<(Chunk, u64)>, current: usize, used: u64, } @@ -482,217 +2359,5447 @@ struct Scratch { // SAFETY: the chunk pointers are persistent mappings of upload buffers. unsafe impl Send for Scratch {} +impl Drop for Scratch { + fn drop(&mut self) { + give_chunks(std::mem::take(&mut self.chunks)); + } +} + const SCRATCH_CHUNK: u64 = 4 << 20; +/// A list's first chunk when the chunks are shared ([`scratch_pool`]): most +/// lists put a few constants or a rectangle's corners there, and every +/// list that did took 4 MiB of the PC's memory for it. +const SCRATCH_FIRST: u64 = 256 << 10; +/// The most bytes of chunks kept while no list holds them. +const SPARE_MOST: u64 = 128 << 20; + +/// Whether lists share their scratch chunks: a list takes a chunk when it +/// first needs one, a small one first, and gives all of them back when it +/// is reset or dropped, for the next list. Before, a list kept every chunk +/// it ever took (4 MiB each) for as long as it lived, used or not, and the +/// host lists of held submissions, which live for one submission, each +/// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and +/// freed per frame of gameplay (run 60). +/// `VICTORY_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before. +fn scratch_pool() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_POOL").is_none_or(|v| v != "0")) +} -/// Per-list GPU-writable buffers for indirect rectangle expansion -/// (`crate::rectangles`): one vertex scratch buffer (reused per draw after -/// its VB -> UAV barrier), one rewritten-arguments buffer (grown if a draw -/// has more records), and chunks of 4-byte atomic counters zeroed before -/// submission. -#[derive(Default)] -struct RectScratch { - vertices: Option<ID3D12Resource>, - args: Option<(ID3D12Resource, u64)>, - counters: Vec<(ID3D12Resource, usize, u64)>, - counter_chunk: usize, - counter_used: u32, +/// Things of some sizes that nothing holds now, kept for whoever next asks +/// for one of the same size. +struct Spare<T> { + kept: Vec<(T, u64)>, + bytes: u64, } -// SAFETY: D3D12 resources are free-threaded; the counter pointers are -// persistent mappings written only before submission. -unsafe impl Send for RectScratch {} +impl<T> Spare<T> { + const fn new() -> Self { + Spare { kept: Vec::new(), bytes: 0 } + } + + /// A kept thing of `size` bytes, the one given last. + fn take(&mut self, size: u64) -> Option<T> { + let at = self.kept.iter().rposition(|(_, s)| *s == size)?; + self.bytes -= size; + Some(self.kept.remove(at).0) + } -/// Counters per chunk (4 KiB = 1024 words). -const RECT_COUNTER_CHUNK: u32 = 1024; -/// Initial rewritten-arguments buffer size (64 KiB = 4096 draw records). -const RECT_ARGS_MIN: u64 = 64 << 10; + /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past + /// `most`: then it comes back. + fn give(&mut self, thing: T, size: u64, most: u64) -> Option<T> { + if self.bytes + size > most { + return Some(thing); + } + self.bytes += size; + self.kept.push((thing, size)); + None + } -/// One piece of submission-time work, in recorded order. -enum Step { - /// A copy into title memory (destination, source, bytes): the title's - /// buffer copies, which later refreshes must see. - Copy(usize, usize, usize), - /// A copy of title memory into the list's own upload memory. - Fill(usize, usize, usize), - /// Brings a range (address, bytes) of a buffer's host copy up to date: - /// once per submission, whichever lists ask, until a `Copy` or `Run` - /// intervenes. - Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize), - /// Work that may write title memory. - Run(Box<dyn Fn() + Send>), - /// Work that writes host memory only. - Host(Box<dyn Fn() + Send>), - /// Shaders write a range (address, bytes) of a buffer's host copy. - GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize), - /// Brings a texture's staging buffer up to date: once per submission, - /// whichever lists sample it, until a `Copy` or `Run` intervenes. - Texture(std::sync::Arc<crate::texture::Staging>), + /// Everything kept past `most` bytes, the oldest first. + fn trim(&mut self, most: u64) -> Vec<(T, u64)> { + let mut cut = 0; + while self.bytes > most && cut < self.kept.len() { + self.bytes -= self.kept[cut].1; + cut += 1; + } + self.kept.drain(..cut).collect() + } } -/// A texture-to-buffer readback copied from a mapped readback buffer into -/// title memory once the GPU submission completes. -struct Readback { - dst: usize, - src: usize, - dst_pitch: usize, - src_pitch: usize, - lines: usize, - row_bytes: usize, - total: usize, +/// An upload buffer a list gave back at its reset ([`HostList::upload`]): +/// the buffer and its persistent mapping. +struct KeptUpload(ID3D12Resource, usize); + +// SAFETY: a D3D12 resource (free-threaded) and its persistent mapping, +// written only by the list that takes it. +unsafe impl Send for KeptUpload {} + +/// Upload buffers of lists' copies no list holds, by size class, kept for +/// the next copy of that class instead of a new committed resource each +/// time: the lists' texture and buffer copies made one per copy, and freed +/// it at the list's reset (our take on codec_d's cool_fox upload pool). +static UPLOAD_SPARE: Mutex<Spare<KeptUpload>> = Mutex::new(Spare::new()); +/// Since the start: upload buffers taken from those kept, and made anew. +pub(crate) static UPLOAD_REUSE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether lists' upload buffers are kept for reuse +/// (`VICTORY_UPLOAD_POOL=0`: one per copy, freed at the reset, as before). +fn upload_pool() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_UPLOAD_POOL").is_none_or(|v| v != "0")) } -/// What a list does on the CPU when it is submitted: copies between host -/// memory regions (title buffers, upload buffers and buffer copies), and -/// the upload/readback buffers its GPU commands name, kept until reset. -#[derive(Default)] -struct Deferred { - /// Destination, source, bytes. - copies: Vec<Step>, - /// Post-submission readbacks from GPU textures into title buffers. - readbacks: Vec<Readback>, - uploads: Vec<ID3D12Resource>, - /// Host objects the list's commands name (pipelines, root signatures, +/// The size class of an upload of `size` bytes: a power of two from 64 KiB +/// to 32 MiB (`None` past it: made to measure, not kept). +fn upload_class(size: u64) -> Option<u64> { + (size <= 32 << 20).then(|| size.max(64 << 10).next_power_of_two()) +} + +/// The most bytes of upload buffers kept at the memory level now. +fn upload_spare_most() -> u64 { + match crate::pressure::level() { + crate::pressure::Level::Normal => 256 << 20, + crate::pressure::Level::Mild => 64 << 20, + crate::pressure::Level::Critical => 0, + } +} + +/// Lets go of kept upload buffers past what the memory level allows. +fn trim_upload_spare() { + let most = upload_spare_most(); + let freed = UPLOAD_SPARE.lock().unwrap_or_else(|e| e.into_inner()).trim(most); + drop(freed); + let freed = STAGING_SPARE.lock().unwrap_or_else(|e| e.into_inner()).trim(staging_spare_most()); + drop(freed); +} + +/// Try 6.4: texture staging buffers no texture holds any more, by size +/// class ([`upload_class`]), kept for the next texture of that class. Every +/// texture uploaded made one (a committed upload buffer, zeroed by the +/// system, mapped) and freed it after its list ran: 59,447 of them in the +/// 6.2 report's first ten minutes, on the thread that records the frame. +static STAGING_SPARE: Mutex<Spare<KeptUpload>> = Mutex::new(Spare::new()); +/// Since the start: staging buffers taken from those kept, and made anew +/// for the pool. +pub(crate) static STAGING_REUSE: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The most bytes of staging buffers kept ([`STAGING_SPARE`]): +/// `VICTORY_STAGING_POOL_MB` (0: none kept, one made per texture as +/// before), else 128 MB, 96 MB when the PC is getting short of memory and +/// 48 MB when it is nearly out (a texture's staging buffer lives for a +/// frame or two: the pool is its churn, not more memory held). +fn staging_spare_most() -> u64 { + static SET: OnceLock<Option<u64>> = OnceLock::new(); + let set = *SET.get_or_init(|| std::env::var("VICTORY_STAGING_POOL_MB").ok().and_then(|v| v.trim().parse().ok())); + match set { + Some(mb) => mb << 20, + None => match crate::pressure::level() { + crate::pressure::Level::Normal => 128 << 20, + crate::pressure::Level::Mild => 96 << 20, + crate::pressure::Level::Critical => 48 << 20, + }, + } +} + +/// A texture's staging buffer of at least `size` bytes: one kept +/// ([`STAGING_SPARE`], zeroed again here as a new one is) or a new one of +/// the size class. The third answer is the class it goes back as +/// ([`give_staging`]); 0: made to measure, not kept. +pub(crate) fn take_staging(host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8, u64)> { + let class = upload_class(size).filter(|_| staging_spare_most() > 0); + let Some(class) = class else { + let (buffer, data) = host.upload_buffer(size)?; + return Some((buffer, data, 0)); + }; + let kept = STAGING_SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(class); + if let Some(KeptUpload(buffer, data)) = kept { + let n = STAGING_REUSE[0].fetch_add(1, Ordering::Relaxed) + 1; + if n >= 256 && n.is_power_of_two() { + tracing::info!( + reused = n, + made = STAGING_REUSE[1].load(Ordering::Relaxed), + "texture staging buffers taken from the pool instead of made (VICTORY_STAGING_POOL_MB=0: one made each time)" + ); + } + let data = data as *mut u8; + // SAFETY: the buffer's persistent mapping, `class` bytes, which no + // list reads any more (it came back when its last holder let go). + unsafe { std::ptr::write_bytes(data, 0, class as usize) }; + return Some((buffer, data, class)); + } + let (buffer, data) = host.upload_buffer(class)?; + STAGING_REUSE[1].fetch_add(1, Ordering::Relaxed); + Some((buffer, data, class)) +} + +/// A texture's staging buffer nothing holds any more (`class` from +/// [`take_staging`]): kept for the next texture of its class while the +/// pool has room, freed if not. +pub(crate) fn give_staging(buffer: ID3D12Resource, data: *mut u8, class: u64) { + if class == 0 { + return; + } + let most = staging_spare_most(); + let back = STAGING_SPARE.lock().unwrap_or_else(|e| e.into_inner()).give(KeptUpload(buffer, data as usize), class, most); + // Freed outside the lock. + drop(back); +} + +/// Lets go of every kept buffer no list holds (upload buffers and scratch +/// chunks), for an allocation the driver refused: the bytes they held. +fn free_spares() -> u64 { + let uploads = UPLOAD_SPARE.lock().unwrap_or_else(|e| e.into_inner()).trim(0); + let staging = STAGING_SPARE.lock().unwrap_or_else(|e| e.into_inner()).trim(0); + let staging_bytes: u64 = staging.iter().map(|(_, size)| size).sum(); + drop(staging); + let chunks = SPARE.lock().unwrap_or_else(|e| e.into_inner()).trim(0); + let mut bytes = 0; + for (_, size) in &chunks { + ALIVE[1].fetch_sub(1, Ordering::Relaxed); + ALIVE[2].fetch_sub(*size, Ordering::Relaxed); + ALIVE[3].fetch_sub(1, Ordering::Relaxed); + ALIVE[4].fetch_sub(*size, Ordering::Relaxed); + bytes += size; + } + bytes + staging_bytes + uploads.iter().map(|(_, size)| size).sum::<u64>() +} + +/// Upload buffers a list held until its reset: kept for the next list if +/// they are of a class (`data` their mapping, 0: not kept), freed if not or +/// past what the memory level allows. +fn give_uploads(uploads: Vec<(ID3D12Resource, u64, usize)>) { + if uploads.is_empty() { + return; + } + let most = upload_spare_most(); + let mut freed = Vec::new(); + { + let mut spare = UPLOAD_SPARE.lock().unwrap_or_else(|e| e.into_inner()); + for (buffer, size, data) in uploads { + if data == 0 || !upload_pool() { + freed.push(buffer); + continue; + } + if let Some(KeptUpload(buffer, _)) = spare.give(KeptUpload(buffer, data), size, most) { + freed.push(buffer); + } + } + } + // Freed outside the lock. + drop(freed); +} + +/// Scratch chunks no list holds. +static SPARE: Mutex<Spare<Chunk>> = Mutex::new(Spare::new()); + +/// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one. +fn take_chunk(host: &Host, size: u64) -> Option<Chunk> { + if scratch_pool() + && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size) + { + ALIVE[3].fetch_sub(1, Ordering::Relaxed); + ALIVE[4].fetch_sub(size, Ordering::Relaxed); + ALIVE[5].fetch_add(1, Ordering::Relaxed); + return Some(chunk); + } + let (buffer, data) = host.upload_buffer(size)?; + name(&buffer, || "list scratch".into()); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + ALIVE[1].fetch_add(1, Ordering::Relaxed); + ALIVE[2].fetch_add(size, Ordering::Relaxed); + Some(Chunk { + _buffer: buffer, + data: data as usize, + gpu, + }) +} + +/// A list is done with `chunks` (it was reset after its submissions ran, +/// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and +/// without the pool. +fn give_chunks(chunks: Vec<(Chunk, u64)>) { + if chunks.is_empty() { + return; + } + let mut freed = Vec::new(); + { + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + for (chunk, size) in chunks { + let back = if scratch_pool() { + spare.give(chunk, size, SPARE_MOST) + } else { + Some(chunk) + }; + match back { + None => { + ALIVE[3].fetch_add(1, Ordering::Relaxed); + ALIVE[4].fetch_add(size, Ordering::Relaxed); + } + Some(chunk) => { + ALIVE[1].fetch_sub(1, Ordering::Relaxed); + ALIVE[2].fetch_sub(size, Ordering::Relaxed); + freed.push(chunk); + } + } + } + } + // Freed outside the lock. + drop(freed); +} + +/// What the host keeps for copies in the card's own memory +/// ([`crate::shadow::cards`]): three lists of ours and the compare. +struct CardWork { + /// Before a submission's lists: what changed on the copies' CPU side + /// goes to their card side. Those not in use: a plan takes one and + /// gives it back when its submission has run (`Host::card_done`), so + /// that submissions sent ahead ([`late`]) each have their own. + sync: Vec<Prelude>, + /// After them, in the same submission: the compare of the declared + /// ranges with their bytes from before. As `sync`. + check: Vec<Prelude>, + /// After it ran: the pieces that differ come down. + fetch: Prelude, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// With `VICTORY_CARD_HASH_WIDE=alt` ([`card_hash_wide_now`]): the compare of [`CARD_COMPARE_WIDE`], `pso` + /// being [`CARD_COMPARE`]'s. Both shaders declare the same root signature. + pso_wide: Option<ID3D12PipelineState>, + /// One dword per piece compared, set where the piece differs: PC + /// memory, mapped (buffer, mapping, bytes). + differs: (ID3D12Resource, usize, u64), + /// Where the pieces that differ are fetched to: PC memory, mapped. + fetched: Option<(ID3D12Resource, usize, u64)>, + /// The dwords of `differs` taken by plans whose results were not read + /// yet. + taken: u32, + /// Plans made and not done with (`Host::card_done`). + out: u32, + /// The fetch inside flights ([`inflight_fetch`]), if it is on and was + /// made. + inflight: Option<CardInflight>, +} + +/// What the fetch inside flights needs ([`inflight_fetch`], [`CARD_FETCH`]). +struct CardInflight { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// PC memory, mapped (buffer, mapping, bytes): dword 0 the counter of + /// tickets, then one dword per dword of `CardWork::differs`, the entry + /// of that piece. + table: (ID3D12Resource, usize, u64), + /// PC memory, mapped (buffer, mapping, slots of [`INFLIGHT_SLOT`] + /// bytes): where the pieces come down. + fetched: (ID3D12Resource, usize, u32), + /// Every ticket below it belongs to a landed flight: its slot may be + /// written over. Raised by the thread that lands flights; read when a + /// compare's list is recorded (an older value only gives fewer slots). + landed: u32, + /// What fetches the old way brought (copy, offsets, and the highest + /// send whose lists were surely on the queue ahead of the fetch: its + /// order of the queue less one). A flight sent at or before that ran + /// ahead of the fetch, so the CPU's side holds those bytes as the card + /// had them after the flight, or newer: the flight's own slot is older + /// there and is not merged there. Dropped once every flight sent up to + /// it has landed. + brought: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)>, +} + +// SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only +// under the submission lock. +unsafe impl Send for CardWork {} + +static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None); + +/// The compare of a declared range of a copy in the card's memory with +/// its bytes from before, one thread per 64 KiB piece (cut at multiples of +/// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs` +/// gets a dword per piece, 1 where a byte differs. The offsets are widened +/// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a +/// byte just outside the range costs a fetch that finds nothing. +pub(crate) const CARD_COMPARE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" +cbuffer Span : register(b0) { + uint first; // the first piece + uint skew; // where the copy starts in its piece 0 + uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored) +}; +ByteAddressBuffer now : register(t0); +// 16 bytes per piece of the copy: the hash of its bytes when they were +// last sent up (or hashed whole, the first time). +RWByteAddressBuffer hashes : register(u0); +RWByteAddressBuffer differs : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= pieces) return; + uint piece = first + id.x; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu); + [loop] + for (uint at = lo; at < hi; at += 16u) { + h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } + if (compare != 0u) { + differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u); + // With the copy-back on its own thread: the next compare of the + // piece finds what is written from here on. + if (compare == 2u) hashes.Store4(piece * 16u, h); + } else { + hashes.Store4(piece * 16u, h); + } +} +"#; + +/// [`CARD_COMPARE`] with a group of 64 threads to a piece +/// (`VICTORY_CARD_HASH_WIDE=1`; the thread a piece unless asked). After fork +/// pull request #1014 by martindevbr. +/// +/// With a thread a piece, a pass hashes its 64 KiB pieces in 4,096 steps +/// one after the other, and its time is that of one piece however few +/// pieces it has: the card waits on one load at a time and runs next to +/// nothing else. The passes run before every submission's lists (hashes +/// after ranges were sent up, 300 to 450 a frame) and after them (compares, +/// about 100). Measured on an RTX 3060 in the first rooms with the frame +/// rate switches on: the card was 85 % busy, and "our send-and-hash lists" +/// were 23 to 29 ms of its frame. +/// +/// Here thread `t` of a piece's group hashes the 16-byte steps `t`, `t + +/// 64`, `t + 128`... of the piece (neighbouring threads read neighbouring +/// bytes), and the first thread folds the 64 lane hashes in lane order into +/// the piece's hash. It is another hash than [`CARD_COMPARE`]'s, so one +/// process uses one of them for every hash it stores and compares (it is +/// chosen once). Copies are under 1 GiB (`shadow::card_for`): at most +/// 16,385 pieces, one group each, within a dispatch's 65,535. +pub(crate) const CARD_COMPARE_WIDE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" +cbuffer Span : register(b0) { + uint first; // the first piece + uint skew; // where the copy starts in its piece 0 + uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored) +}; +ByteAddressBuffer now : register(t0); +RWByteAddressBuffer hashes : register(u0); +RWByteAddressBuffer differs : register(u1); +groupshared uint4 lanes[64]; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 group : SV_GroupID, uint t : SV_GroupIndex) { + uint i = group.x; + if (i >= pieces) return; + uint piece = first + i; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) ^ t; + [loop] + for (uint at = lo + t * 16u; at < hi; at += 1024u) { + h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } + lanes[t] = h; + GroupMemoryBarrierWithGroupSync(); + if (t != 0u) return; + uint4 all = uint4(0x27D4EB2Fu, 0x165667B1u, 0xD3A2646Cu, 0xFD7046C5u); + [loop] + for (uint k = 0u; k < 64u; k++) { + all = (all ^ lanes[k]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + all = all.yzwx ^ (all >> 15); + } + if (compare != 0u) { + differs.Store(out_at + i * 4u, any(all != hashes.Load4(piece * 16u)) ? 1u : 0u); + if (compare == 2u) hashes.Store4(piece * 16u, all); + } else { + hashes.Store4(piece * 16u, all); + } +} +"#; + +/// Whether [`CARD_COMPARE_WIDE`] is the compare (`VICTORY_CARD_HASH_WIDE=1`; +/// off unless asked: it has not run in a game on this tree yet, and it is +/// another hash with another rare pattern of changes it cannot see). Chosen +/// once and said in the log: stored and compared hashes must agree. +pub(crate) fn card_hash_wide() -> bool { + card_hash_mode() == 1 +} + +/// `VICTORY_CARD_HASH_WIDE`: 0 a thread a piece, 1 a group a piece, 2 in turn (`alt`, [`card_hash_wide_now`]). +fn card_hash_mode() -> u8 { + static MODE: OnceLock<u8> = OnceLock::new(); + *MODE.get_or_init(|| { + let mode = match std::env::var("VICTORY_CARD_HASH_WIDE").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }; + if mode == 1 { + tracing::info!("the card's hashes of copies' pieces are made by a group of 64 threads a piece (VICTORY_CARD_HASH_WIDE=1)"); + } + mode + }) +} + +/// Whether the card's hashes of a submission's pieces are made with [`CARD_COMPARE_WIDE`]: with +/// `VICTORY_CARD_HASH_WIDE=1` always; with `alt` twenty seconds with, twenty without, in turn, each change said in the +/// log, so that one run measures the card and the submitting thread in both at equal draws (run 332 compared two +/// launches: card -8 to -24 ms, submit thread +12 to +20, inside the ±10 ms two launches differ by). +/// +/// Read once per submission (`Host::card_before`): its pass after ranges were sent up and its compare use the same +/// form. Why mixing the two forms across submissions is exact: a piece whose hash was stored in one form and is +/// compared in the other is flagged as differing (two different 128-bit functions of the same bytes agree by chance +/// about one time in 2^128, the odds a changed piece already has of a same hash in either form). A flagged piece is +/// fetched and merged, and the merge stores into title memory only the bytes where the card's side differs from the +/// CPU's (`Shadow::card_merge_relay`): a piece nothing changed stores nothing. So a change of phase costs one fetch of +/// each piece compared next (two compares in a row without a store, `compare` 1, fetch it again until the next send +/// stores its hash), never a byte. Each form has its own rare pattern of changes it cannot see, as with `=1`. +fn card_hash_wide_now() -> bool { + match card_hash_mode() { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "the card's hashes of copies' pieces from now (VICTORY_CARD_HASH_WIDE=alt): {}", + if on { "ON, a group of 64 threads a piece" } else { "off, a thread a piece" } + ); + } + on + } + } +} + +impl CardWork { + /// The compare's pipeline for a submission ([`card_hash_wide_now`]) and whether it is the wide form. + fn compare_for(&self, wide_now: bool) -> (&ID3D12PipelineState, bool) { + match (&self.pso_wide, wide_now) { + (Some(wide), true) => (wide, true), + _ => (&self.pso, card_hash_wide()), + } + } +} + +/// The compare's source for this process ([`card_hash_wide`]). +pub(crate) fn card_compare_source() -> &'static str { + if card_hash_wide() { CARD_COMPARE_WIDE } else { CARD_COMPARE } +} + +/// The groups a compare pass over `pieces` pieces is dispatched with. +/// (For the form `wide` of the submission, [`CardWork::compare_for`].) +fn card_compare_groups_as(wide: bool, pieces: u32) -> u32 { + if wide { pieces } else { pieces.div_ceil(64) } +} + +/// Whether the pieces a flight's compare flags come down to the PC inside +/// the flight itself (`VICTORY_CARD_FETCH_INFLIGHT=1`; off by default, and +/// only with [`relay`]). +/// +/// With the relay the thread that lands flights fetched the flagged pieces +/// with a list of its own on the host's queue, the one the submitting +/// thread keeps filling: the fetch ran behind every flight sent meanwhile. +/// Measured on an RTX 3070 Laptop: 140.9 ms a frame of that thread waiting +/// for fetches, for 63 pieces (3.2 MB) in about five fetches, some 28 ms a +/// fetch spent queued behind newer flights; and the submitting thread +/// waited 81.7 ms a frame in "title memory read" settles for that thread. +/// +/// With the switch the compare's list does the fetch: right behind the +/// compare, [`CARD_FETCH`] copies each piece it flagged into a slot of a +/// buffer in the PC's memory ([`CardInflight`]), so when the flight's fence +/// is reached its bytes are there, and the landing merges them +/// (`Shadow::card_merge_relay`) with no list, signal or wait of its own. +/// The merge's "fetched after" is the flight's own send number +/// (`CardPlan::sent_as`): see [`Host::relay_card_back`] for why that is +/// exact and when a landing falls back to the old fetch. +fn inflight_fetch() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_CARD_FETCH_INFLIGHT").is_some_and(|v| v == "1")) +} + +/// The bytes of the PC's memory pieces fetched inside flights go to +/// ([`inflight_fetch`]; `VICTORY_CARD_FETCH_INFLIGHT_MB`, 64): 1,024 slots +/// ([`inflight_slots`]). A flight whose flagged pieces find no free slot +/// lands the old way. +fn inflight_fetch_bytes() -> u64 { + static MOST: OnceLock<u64> = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_CARD_FETCH_INFLIGHT_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(64).max(1) << 20 + }) +} + +/// A slot of [`CARD_FETCH`]: a 64 KiB piece as the compare cuts it, widened +/// to 16 bytes at both ends (one more 16-byte step where the copy does not +/// start at a multiple of 16 in its piece). +pub(crate) const INFLIGHT_SLOT: u64 = (64 << 10) + 16; + +/// The slots for `bytes` asked of [`inflight_fetch_bytes`]: one per 64 KiB, +/// rounded down to a power of two (at least 1, at most 2^15: the shader's +/// byte offsets into the slots are 32-bit), so that +/// `ticket % slots` runs on without a jump when the 32-bit ticket wraps +/// (2^32 is a multiple of it; with 1,023 slots it would jump by 4 and two +/// tickets in the air could share a slot). The buffer is `slots` times +/// [`INFLIGHT_SLOT`], a little over `bytes`. +pub(crate) fn inflight_slots(bytes: u64) -> u32 { + let wanted = (bytes >> 16).clamp(1, 1 << 15); + 1u32 << (63 - wanted.leading_zeros()) +} + +/// [`CARD_FETCH`]'s table entry for a piece the compare did not flag. +pub(crate) const INFLIGHT_NONE: u32 = 0xffff_ffff; + +/// Where piece `i` of `span` starts in its [`CARD_FETCH`] slot, as an +/// offset of the copy: the compare's lower bound of the piece, widened down +/// to 16 bytes (`CARD_COMPARE`, before clamping to the declared range). +/// What `Shadow::card_piece` gives for the piece lies at or above it, and +/// within [`INFLIGHT_SLOT`] of it. +pub(crate) fn inflight_piece_from(span: &crate::shadow::CardSpan, i: u32) -> usize { + let lo = (span.first + i) as usize * 65536; + let lo = lo.saturating_sub(span.skew as usize); + lo & !15 +} + +/// Whether the ticket `k` of [`CARD_FETCH`]'s counter gets a slot, with +/// every ticket below `floor` landed and `slots` slots: the slot is +/// `k % slots`. The tickets of flights still in the air are at or above +/// `floor` (they are taken in the queue's order and flights land in that +/// order), so two that get a slot are fewer than `slots` apart and never +/// share one. The arithmetic of the shader, for the tests. +pub(crate) fn inflight_gets_slot(k: u32, floor: u32, slots: u32) -> bool { + k.wrapping_sub(floor) < slots +} + +/// The fetch inside a flight ([`inflight_fetch`]), run in the compare's list +/// right behind the compare of a declared range (a UAV barrier between): +/// one group per piece (looping where a range has more than 65,535); where +/// `differs` flags the piece, its first thread takes a ticket of the +/// counter (`table`'s dword 0) and, if [`inflight_gets_slot`], the group +/// copies the piece, cut and widened as the compare hashes it, into slot +/// `ticket % slots` of `fetched`. Every piece's entry in `table` (dword 1 + +/// its dword in `differs`) is written: the ticket, also one that got no +/// slot (the landing repeats the test with the plan's `landed`), or +/// [`INFLIGHT_NONE`]. +pub(crate) const CARD_FETCH: &str = r#" +#define RS "RootConstants(num32BitConstants=8, b0), SRV(t0), UAV(u0), UAV(u1), UAV(u2)" +#define SLOT 65552u +#define NONE 0xffffffffu +cbuffer Span : register(b0) { + uint first; // the first piece + uint skew; // where the copy starts in its piece 0 + uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint landed; // every ticket below it is landed + uint slots; // slots of `fetched` + uint groups; // groups dispatched +}; +ByteAddressBuffer now : register(t0); +RWByteAddressBuffer differs : register(u0); +RWByteAddressBuffer table : register(u1); +RWByteAddressBuffer fetched : register(u2); +groupshared uint ticket; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 group : SV_GroupID, uint t : SV_GroupIndex) { + [loop] + for (uint i = group.x; i < pieces; i += groups) { + if (t == 0u) { + uint entry = NONE; + if (differs.Load(out_at + i * 4u) != 0u) { + uint k; + table.InterlockedAdd(0, 1u, k); + entry = k; + } + table.Store(4u + out_at + i * 4u, entry); + ticket = entry; + } + GroupMemoryBarrierWithGroupSync(); + uint k = ticket; + GroupMemoryBarrierWithGroupSync(); + if (k != NONE && (k - landed) < slots) { + uint piece = first + i; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + uint into = (k % slots) * SLOT; + [loop] + for (uint at = lo + t * 16u; at < hi; at += 1024u) { + fetched.Store4(into + (at - lo), now.Load4(at)); + } + } + } +} +"#; + +/// Whether the pieces hashed again after ranges were sent up to a copy in +/// the card's memory are hashed in runs of pieces that touch, each piece +/// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass +/// per range sent up. +/// +/// These passes are ours, they run on the card before every submission's +/// lists, and no timing so far names them: each walks its 64 KiB pieces +/// 16 bytes at a time, 4,096 steps one after the other, so a pass takes +/// the time of one piece however few its pieces are. Run 102 sent up 514 +/// ranges a frame: 514 such passes. The same pieces are hashed either way; +/// a piece hashed when it need not be, or not hashed when it should, costs +/// a fetch that finds nothing and loses no shader write. +/// +/// `VICTORY_CARD_REHASH_RUNS=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log: one run then measures both on the +/// same scene (the card meter's "send-and-hash lists" in the frame log). +/// Runs 105-110 found no change in the frame, but the card was not the +/// frame's limit then. +fn rehash_runs() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock<u8> = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_CARD_REHASH_RUNS").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + let joined = (now_us() / 20_000_000) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(joined), Ordering::Relaxed) != u8::from(joined) { + tracing::info!( + "card rehash passes from now (VICTORY_CARD_REHASH_RUNS=alt): {}", + if joined { "JOINED, one pass a run of touching pieces" } else { "one pass a range sent up, as usual" } + ); + } + joined + } + } +} + +/// Since the last frame-rate line, of our own passes over copies in the +/// card's memory: hash passes after ranges were sent up, the pieces they +/// hashed, and compare passes after the lists. +static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Whether what shaders wrote to copies in the card's memory is merged +/// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by +/// default). The pieces the card's compare found differing come down in +/// one fetch and were then merged one after the other on the thread that +/// settles: about 630 pieces and 40 MB a frame (run 104), each compared +/// with the copy's CPU side byte by byte and put into title memory through +/// the kernel. A piece is its own bytes of its copy and of title memory, +/// so eight threads take an eighth of them each. +fn wide_merge() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1")) +} + +/// One declared range of a copy in the card's memory, in a submission. +struct CardRange { + shadow: std::sync::Arc<crate::shadow::Shadow>, + /// As declared (title addresses), for the statistics. + declared: (usize, usize), + span: crate::shadow::CardSpan, + /// Its first piece's dword in the compare's results. + at: u32, + /// Whether the card compares it; else every piece is fetched. + compared: bool, +} + +/// What a submission does for copies in the card's memory. +struct CardPlan { + ranges: Vec<CardRange>, + /// The compare, run after the submission's lists. + check: Option<ID3D12CommandList>, + /// The copies whose card side was brought up to date, alive until the + /// submission has run. + _synced: Vec<std::sync::Arc<crate::shadow::Shadow>>, + /// The lists of ours the plan recorded (whether the compare, the + /// list), given back by `Host::card_done`. + lists: Vec<(bool, Prelude)>, + /// With [`relay`], the number of this plan's send of changed ranges + /// (`QUEUE_ORDER`); else 0. + sent_as: u64, + /// Whether the compare's list fetches the flagged pieces itself + /// ([`inflight_fetch`]): every compared range has its [`CARD_FETCH`]. + inflight: bool, + /// The `CardInflight::landed` its [`CARD_FETCH`] was told: which of its + /// tickets got a slot ([`inflight_gets_slot`]). + inflight_landed: u32, +} + +/// One piece of submission-time work, in recorded order. +enum Step { + /// A copy into title memory (destination, source, bytes): the title's + /// buffer copies, which later refreshes must see. + Copy(usize, usize, usize), + /// A copy of title memory into the list's own upload memory. + Fill(usize, usize, usize), + /// Brings a range (address, bytes) of a buffer's host copy up to date: + /// once per submission, whichever lists ask, until a `Copy` or `Run` + /// intervenes. + Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize), + /// Work that may write title memory; with the place it writes + /// (address, bytes) when that is known (the title's memory-to-memory + /// copies, `crate::list` `copy_memory`): [`near_writes`]. + Run(Box<dyn Fn() + Send>, Option<(usize, usize)>), + /// Work that writes host memory only. + Host(Box<dyn Fn() + Send>), + /// Work that writes host memory only and reads what the texture checks + /// before it found (levels on demand: the levels a staging buffer holds + /// are judged when it is detiled). The checks run in batches, on several + /// threads, at the next `Copy` or `Run` or at the end; a `Host` step ran + /// before them, so the step that gives levels their memory always saw + /// none held and no texture made level by level ever got memory: 1,448 + /// such textures, 2.9 GB, drawn black for the whole run (2026-11-26 + /// report, "0 MB of the card given to 0 levels"). These run right after + /// the batch before them. + AfterTextures(Box<dyn Fn() + Send>), + /// Shaders write a range (address, bytes) of a buffer's host copy. + GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize), + /// Brings a texture's staging buffer up to date: once per submission, + /// whichever lists sample it, until a `Copy` or `Run` intervenes. + Texture(std::sync::Arc<crate::texture::Staging>), +} + +/// What a list does on the CPU when it is submitted: copies between host +/// memory regions (title buffers, upload buffers and buffer copies), and +/// the upload buffers its GPU commands read, kept until the list is reset. +#[derive(Default)] +struct Deferred { + /// Destination, source, bytes. + copies: Vec<Step>, + /// The buffers, their bytes, and their mapping if they are of a size + /// class ([`upload_class`]: kept for reuse at the reset), else 0. + uploads: Vec<(ID3D12Resource, u64, usize)>, + /// The bytes of `uploads` (counted in [`ALIVE`] while they are held). + upload_bytes: u64, + /// Host objects the list's commands name (pipelines, root signatures, /// descriptor heaps): the title may release its objects before it /// submits the list. kept: Vec<windows::core::IUnknown>, /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize)>, + /// With [`list_reuse`]: the host pipelines the list has kept, by + /// address ([`HostList::first_bind`]). + bound: std::collections::HashSet<usize>, + /// With [`list_reuse`]: upload memory filled from title memory since + /// the last title copy (source, bytes): its host GPU address, which a + /// second fill would find holding the same bytes + /// ([`HostList::fill_scratch`]). + filled: std::collections::HashMap<(usize, usize), u64>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet<usize>, + /// Last GPU source copied into each aliased host texture in this list. + texture_aliases: std::collections::HashMap<usize, usize>, /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, - /// Whether a step zeroes the indirect-work budget. + /// Textures read back (texture to buffer copies), done once the list + /// has run: the host buffer the list copies the texels into, the title + /// memory they go to, the bytes of a row, the rows, the title's row + /// pitch. + backs: Vec<(ID3D12Resource, usize, [usize; 3])>, + /// Title textures of the kinds copied back ([`crate::texback`]) that + /// the list's shaders write, copied when the list closes. + back_wanted: Vec<crate::texback::Target>, + /// Those copies, whose texels go to title memory once the list has run. + texture_backs: Vec<crate::texback::Back>, + /// Whether the indirect-work budget is zeroed for this recording (a + /// step on the CPU, or in the list for the card's copy). budget_zeroed: bool, + /// Steps recorded so far that write title memory (copies and runs): + /// fills recorded between two of them read the same bytes + /// ([`HostList::title_epoch`]). + epoch: u64, + /// The indirect scratch buffer (`HostList::indirect_args`, by its + /// interface pointer) that a clamp in this recording left readable as + /// indirect arguments; 0 if none. It stays readable until the next + /// clamp into it ([`HostList::indirect_state`]). + indirect_readable: usize, +} + +impl Deferred { + /// Holds `buffer` (`size` bytes of upload memory) until the list is + /// reset. + fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) { + self.hold_kept_upload(buffer, size, 0); + } + + /// As [`Self::hold_upload`], a buffer of a size class mapped at `data`, + /// kept for reuse at the reset. + fn hold_kept_upload(&mut self, buffer: ID3D12Resource, size: u64, data: usize) { + ALIVE[6].fetch_add(1, Ordering::Relaxed); + ALIVE[7].fetch_add(size, Ordering::Relaxed); + self.upload_bytes += size; + self.uploads.push((buffer, size, data)); + } +} + +impl Drop for Deferred { + fn drop(&mut self) { + ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed); + ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed); + } +} + +/// Whether a queue's submissions go to the card without a wait for each +/// (`VICTORY_LATE_WAIT=1`; off by default, and off in the timing run, which +/// waits for every list on its own). +/// +/// Every submission was prepared, sent, waited for and copied back before +/// the next one was looked at, so the card stood idle while we prepared +/// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of +/// preparing, 194 ms of waiting and 78 ms of copying back, one after the +/// other, on the one thread that submits. +/// +/// With the switch a queue's submission is sent and joins a line of +/// "flights" ([`Flight`]); the thread goes on to the next one while the +/// card runs. The flights are settled together ([`Host::settle`]: one wait +/// for the card, what their shaders wrote copied back once per byte, then +/// their bottom-of-pipe writes and the fence signals behind them, in +/// order) at the next point where the title, or our own preparing, can +/// observe what they do. Those points, exactly: +/// +/// 1. a synchronous submission of ours ([`Host::execute`]): a present, a +/// read-back or map of a texture, a clear or upload run at once; +/// 2. the next submission reads title memory that a flight's shaders may +/// write: a title buffer copy, a fill of upload memory, a texture's +/// memory, any step that runs code of ours on title memory +/// ([`late_blocked`]); +/// 3. the next submission refreshes a range of a host copy that a flight's +/// shaders may write, and the title wrote a page of it since it was last +/// copied ([`stale_under_flights`]): the refresh leaves such a range +/// alone until the flight's writes are back, as it always did within a +/// submission; +/// 4. a queue stands at a wait for a memory value that no flight's +/// bottom-of-pipe write is known to satisfy, at an address a flight may +/// write ([`late_met`]); +/// 5. the title blocks on a fence without an event; +/// 6. the card has run every flight (a thread of ours waits for that: +/// [`late_helper`]), or the flights hold [`late_most`] host lists. +/// +/// What the title is told (bottom-of-pipe writes, fence values) is told +/// when the card has really run the work, later than before and never +/// earlier; a fence signalled on a queue while flights are in the air is +/// set behind them. A wait for a memory value that a flight's +/// bottom-of-pipe write satisfies counts as met: the waiting part goes to +/// the card behind that flight, which is the order the wait asks for. +/// +/// What it assumes beyond today: memory the title rewrites between two of +/// its submissions, without waiting for the first, may be seen by the +/// first's shaders (as on the console, where the card reads title memory +/// when it runs, not when the list is submitted). +pub(crate) fn late() -> bool { + late_stage() > 0 +} + +/// `VICTORY_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]). +fn late_stage() -> u8 { + static STAGE: OnceLock<u8> = OnceLock::new(); + *STAGE.get_or_init(|| { + if std::env::var_os("VICTORY_GPU_TIMING").is_some() { + return 0; + } + match std::env::var("VICTORY_LATE_WAIT").as_deref() { + Ok("1") => 1, + Ok("2") => 2, + Ok("3") => 3, + // The relay alone: on top of stage 3. + Err(_) if crate::shadow::relay() => 3, + _ => 0, + } + }) +} + +/// Stage 2 of [`late`] (`VICTORY_LATE_WAIT=2`): point 3 of its list is no +/// longer a point. Where the title wrote a page that lies in a range a +/// flight's shaders may write, the bytes the title changed are found (the +/// page as it is now against what the copy held when the flight was +/// prepared) and put into the copy, and only those: what the flight's +/// shaders write beside them stays (`Shadow::merge_under_writes`). The +/// flights are settled for it only where that cannot be done: memory that +/// is not write-watched, or a copy in the card's memory with more changed +/// runs than a submission should send up one by one. +/// +/// In run 92 (stage 1) this point settled the flights five times a frame +/// of twelve, each time with the card's work still to wait for: 172 ms a +/// frame of waiting were left of 200. +/// +/// What differs from settling first: a byte both the title and a flight's +/// shader wrote is the title's if the shader wrote it first, the shader's +/// if it wrote it afterwards; settled first it was always the shader's. +/// The title writing a byte a shader of its own is writing is a race on +/// the console too. +fn late_exact() -> bool { + late_stage() > 1 +} + +/// Stage 3 of [`late`] (`VICTORY_LATE_WAIT=3`: stage 2, and the present is +/// no longer a point where flights are settled). The copy to the back +/// buffer is sent as a flight of its own (`Host::execute_own`, a list of +/// its own for each present in the air) and the swap chain is told to +/// present behind it; the queue's call returns, and the card finishes the +/// frame while the title records the next one. What the title is told +/// about the frame (bottom-of-pipe writes, fences) is told when the card +/// has run it, by the settling thread. +/// +/// What is left out with it: the look whether the presented frame is black +/// (diagnostics; it reads the frame back at once). A frame that is saved +/// or listed is presented the old way. Once every second and a half a +/// submission settles the flights all the same, for the sweep that lets +/// idle host objects go (it needs nothing in the air). +pub(crate) fn late_free_present() -> bool { + late_stage() > 2 +} + +/// The relay's first stage (`VICTORY_RELAY=1`; off by default; it turns +/// [`late`] on at stage 3 unless `VICTORY_LATE_WAIT` says another stage, +/// and is off with it, in the timing run and with kept snapshots). +/// +/// With [`late`] alone every settle does three things on the thread that +/// holds the submission lock: it waits for everything in the air, copies +/// back with the card standing, and only then goes on preparing. The frame +/// stays a relay: the card works about 242 ms of it and one thread +/// prepares, waits and copies back for about 220. +/// +/// With the switch a thread of its own ([`relay_worker`]) lands flights as +/// soon as the card has run them, in the order they were sent and without +/// the submission lock: it fetches and merges what their shaders wrote to +/// copies in the card's memory, compares and merges the other copies, +/// frees the flights' ranges, and then does their read-backs, their +/// bottom-of-pipe writes and the fence signals behind them, in the line's +/// order. The submitting thread meanwhile prepares and sends the next +/// submissions. [`Host::settle`] no longer settles anything: it waits until +/// that thread has landed everything in the air, at the same points as +/// before (the list in [`late`]), so whoever can observe title memory, a +/// fence or a present still does so only after the flights before it are +/// merged. +/// +/// What makes that safe is in `crate::shadow::relay` (ranges counted per +/// flight; a merge that never stores into memory the card may be writing; +/// sends to card copies numbered) and here: flights land in the order of +/// [`LINE`] by one thread, so a later flight's results never reach title +/// memory before an earlier flight's; the compare on the card stores the +/// hash it made, so each flight's compare flags exactly what changed since +/// the compare before it, however late the pieces are fetched; the fetch +/// goes to the queue under [`QUEUE_ORDER`], which says which sends of +/// title bytes the card had received when it ran. +pub(crate) fn relay() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay()) +} + +/// The relay's second stage (`VICTORY_RELAY=2`): a submission that reads +/// title memory a flight's shaders may write (a title buffer copy, a fill +/// of upload memory, a texture) waits only until the flights that declared +/// that memory have landed, not for everything in the air; and at +/// [`late_most`] lists in the air it waits until there are fewer. At `1` +/// both wait for everything. +fn relay_exact() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + // Stage 2 unless `VICTORY_RELAY=1` asks for the first one (the default + // since the walls of the first room were found drawn in every run with + // this set and in fewer than half without it). + *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_none_or(|v| v == "2")) +} + +/// Told when something joins [`LINE`], for the thread that lands flights +/// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at +/// what queues hold. +static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new(); + +/// Told when flights have landed ([`relay`]): who waits for that looks +/// again. +static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new(); + +/// With [`relay`], the order of what we put on the queue: the number of +/// sends of changed ranges to copies in the card's memory so far +/// (`Host::card_before`). Held from the taking of the ranges until their +/// list is on the queue, and while a fetch of pieces goes to the queue: a +/// fetch sent with the count at N ran behind sends 1..N and ahead of every +/// later one. +static QUEUE_ORDER: Mutex<u64> = Mutex::new(0); + +/// Since the last frame-rate line, of the thread that lands flights +/// ([`relay`]): landings, flights landed, microseconds it waited for the +/// card with nothing to land, microseconds it waited for fetches of card +/// copies' pieces, microseconds of landing in all. +static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// Since the last frame-rate line, with [`inflight_fetch`]: pieces merged +/// from the slots their flights fetched them to, their bytes, landings that +/// went the old way because a plan's pieces overflowed the slots, and +/// landings that fetched the old way (for any reason, overflow too). +static INFLIGHT_STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// After a fetch the old way taken with the queue's count at `after`, for +/// plans whose highest send is `landed`: up to which send the notes of +/// sends to card copies may go (`crate::shadow::relay_fetched`). +/// +/// Without [`inflight_fetch`] every later merge is of a later fetch, whose +/// count is `after` or more: notes up to `after` are of no use, as before. +/// With it, a flight still in the air, sent before the fetch, merges its +/// own slot with "fetched after" its own send, which may be below `after`: +/// it needs the notes of the sends between, or it takes the title's bytes +/// that went up in them for its shaders' writes and puts its older card +/// bytes over them. (Flights 5, 6, 7 in the air; 5 lands the old way with +/// the count at 7; a title byte went up in send 7 into a piece 6's shaders +/// write; 6 lands from its slot, which holds that byte from before send 7.) +/// So the mark goes only to the landed plans' highest send: every flight +/// still to land was sent after it, and every later fetch the old way +/// takes a count at least that high. (`CardInflight::brought` is another +/// matter: the card's bytes the fetch put in the CPU's side, not the +/// title's.) +pub(crate) fn fallback_fetched_mark(inflight: bool, after: u64, landed: Option<u64>) -> u64 { + match (inflight, landed) { + (false, _) => after, + (true, Some(landed)) => landed.min(after), + (true, None) => 0, + } +} + +/// The landed mark of [`CARD_FETCH`]'s tickets after ticket `k` landed: one +/// past `k` if that is ahead of `landed`, in wrapping order (tickets in the +/// air are always within 2^31 of the mark), else `landed`. +pub(crate) fn inflight_raise(landed: u32, k: u32) -> u32 { + let next = k.wrapping_add(1); + if (next.wrapping_sub(landed) as i32) > 0 { next } else { landed } +} + +/// With [`inflight_fetch`], after a landing merged (either way): the tickets +/// these plans' fetches took are landed, and their slots may be written +/// over. Plans land in the line's order and tickets are taken in the +/// queue's (a UAV barrier opens every compare's list), so every ticket of a +/// plan in the air is ahead of these. +/// +/// The counter is never reset and wraps after 2^32 tickets: the mark is +/// raised in wrapping order ([`inflight_raise`]), and the slots are a power +/// of two, so `k % slots` runs on across the wrap. shortcut: ticket +/// 0xffff_ffff reads as [`INFLIGHT_NONE`]; a flagged piece that draws it +/// copies nothing and its landing goes the old way, once every 2^32. +fn inflight_tickets_landed(plans: &[&CardPlan]) { + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + let dwords = (work.differs.2 / 4) as usize; + let Some(inflight) = work.inflight.as_mut() else { + return; + }; + // SAFETY: the mapping of the tickets; these plans' fetches have run. + let table = unsafe { std::slice::from_raw_parts((inflight.table.1 as *const u32).add(1), dwords) }; + for plan in plans.iter().filter(|p| p.inflight) { + for r in plan.ranges.iter().filter(|r| r.compared) { + for p in 0..r.span.pieces { + if let Some(&k) = table.get((r.at + p) as usize) + && k != INFLIGHT_NONE + { + inflight.landed = inflight_raise(inflight.landed, k); + } + } + } + } + // Every flight still to land was sent after these: what fetches the old + // way brought up to them concerns none of them. + if let Some(last) = plans.iter().map(|p| p.sent_as).max() { + inflight.brought.retain(|b| b.3 > last); + } +} + +/// Of the line's things in order (a flight: the value signalled on the +/// host's fence behind it; a write or a signal behind a flight: `None`): +/// how many, from the front, can be landed when the card has reached +/// `completed`: everything ahead of the first flight it has not run. A +/// later flight never lands before an earlier one, and what follows a +/// flight (its bottom-of-pipe writes, signals) never before the flight. +fn landable(line: &[Option<u64>], completed: u64) -> usize { + line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len()) +} + +/// For one plan of copies in the card's memory, with [`relay`]: `flags` +/// holds, for every piece of every range of the plan, the copy, the +/// piece's number in the copy and whether the compare flagged it there (or +/// did not run). The pieces to fetch, under whichever range: all of them +/// flagged under any. Two ranges of a plan may hold parts of the same +/// 64 KiB piece; the compare hashes the whole piece for each and stores +/// the hash, so the second of them may find it stored already and not +/// flag it. +fn flagged_pieces(flags: &[(usize, u32, bool)]) -> std::collections::HashSet<(usize, u32)> { + flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect() +} + +/// Whether pieces fetched on a copy queue beside later flights are fetched +/// again when those flights land (`VICTORY_QUEUE2_REFETCH=0`: not, as +/// before; on by default with `VICTORY_QUEUE2` bit 1). +fn refetch() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE2_REFETCH").is_none_or(|v| v != "0")) +} + +/// With fetches on a copy queue (`crate::queue2`, bit 1): the pieces (copy, +/// piece number) a fetch brought down while later submissions may have been +/// running, each with the number of the last submission started when the +/// fetch had run ([`STARTED`]). +/// +/// Such a fetch stands behind the flights being landed and nothing else, +/// so it runs beside whatever was sent after them. A later flight that +/// writes the piece (a buffer cleared and filled again) may be half way +/// through it: the bytes that come down are neither the earlier flight's +/// nor the later one's, and they go into title memory. If the later flight +/// leaves the piece as the earlier one left it (a still scene does, every +/// frame), its own compare finds the stored hash unchanged and flags +/// nothing: title memory kept the half-written bytes until the piece next +/// changed. On the direct queue a fetch only ever sees whole flights. +/// +/// So a flight that declared such a piece and had started before the fetch +/// had run fetches it at its own landing whatever its compare says +/// ([`fetched_beside`]); that fetch stands behind the flight, and is noted +/// here in turn if still later flights were in the air. Between the two +/// landings title memory may hold the half-written bytes, as it does on +/// the console, where the title reads the memory the card is writing: what +/// the title is promised is the piece as the flight left it once that +/// flight's fence is signalled, and the landing comes before the signal. +static BESIDE: Mutex<Option<std::collections::HashMap<(usize, u32), u64>>> = Mutex::new(None); + +/// Since the last frame-rate line: pieces fetched because an earlier fetch +/// of them ran beside their flight ([`BESIDE`]), and pieces noted there. +static BESIDE_STATS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// [`BESIDE`]: whether the flight numbered `number` (among the submissions +/// started) must fetch a piece that an earlier landing's fetch brought +/// down when submissions up to `started` had been started: it had started +/// by then, so it may have been writing the piece under that fetch. +fn fetched_beside(started: Option<u64>, number: u64) -> bool { + started.is_some_and(|started| started >= number) +} + +/// [`BESIDE`], after a landing of flights up to number `landed` whose +/// fetch brought `fetched` down while submissions up to `started` had +/// been started: what is noted of the pieces afterwards, and how many were +/// noted now. A note is done with once every submission it names has +/// landed (each fetched the piece again if it declared it); the pieces +/// just fetched are noted if anything later than the flights landed had +/// started. +fn note_beside(noted: &mut std::collections::HashMap<(usize, u32), u64>, fetched: &[(usize, u32)], landed: u64, started: u64) -> u64 { + noted.retain(|_, upto| *upto > landed); + if started <= landed { + return 0; + } + for piece in fetched { + noted.insert(*piece, started); + } + fetched.len() as u64 +} + +#[cfg(test)] +mod relay_tests { + use super::{fetched_beside, flagged_pieces, landable, note_beside}; + + /// Joined fetch copies land every byte where the piece-by-piece ones + /// did (after Kelvaroq 0032's test). + #[test] + fn joined_fetch_copies_land_the_same_bytes() { + use std::sync::Arc; + let first = Arc::new([1u8, 2, 3, 4, 5, 6, 7, 8]); + let second = Arc::new([11u8, 12, 13, 14, 15, 16, 17, 18]); + let pieces = [ + (first.clone(), 0, 2, 0), + (first.clone(), 2, 4, 2), + (second.clone(), 4, 6, 4), + (second.clone(), 6, 7, 8), + (second, 0, 2, 9), + (first.clone(), 3, 5, 0), + ]; + for (join, calls) in [(false, 6), (true, 5)] { + let mut bytes = [0xffu8; 11]; + let mut count = 0; + for (source, lo, hi, at) in super::relay_copy_runs_with(&pieces, join) { + let at = at as usize; + bytes[at..at + hi - lo].copy_from_slice(&source[lo..hi]); + count += 1; + } + assert_eq!(count, calls); + assert_eq!(bytes, [4, 5, 3, 4, 15, 16, 0xff, 0xff, 17, 11, 12]); + } + let overflow = [(first.clone(), 0, 1, u64::MAX), (first, 1, 2, 0)]; + assert_eq!(super::relay_copy_runs_with(&overflow, true).count(), 2); + } + + /// A piece fetched on the copy queue while a later flight was in the + /// air is fetched again by that flight, and by no flight sent after + /// the fetch had run; the note goes when its flights have landed. + #[test] + fn a_piece_fetched_beside_a_later_flight_is_fetched_again_by_it() { + let mut noted = std::collections::HashMap::new(); + let (a, p) = (0x1000usize, 7u32); + // Flight 5 lands; its fetch ran while 6 and 7 had started. + assert_eq!(note_beside(&mut noted, &[(a, p)], 5, 7), 1); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 6)); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 7)); + // Flight 8 was sent after the fetch had run: its compare decides. + assert!(!fetched_beside(noted.get(&(a, p)).copied(), 8)); + // Another piece was never noted. + assert!(!fetched_beside(noted.get(&(a, p + 1)).copied(), 6)); + // Flight 6 lands and fetches it again, with 7 still in the air and + // nothing newer: the note stays for 7. + assert_eq!(note_beside(&mut noted, &[(a, p)], 6, 7), 1); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 7)); + // Flight 7 lands with nothing behind it: nothing is noted any more. + assert_eq!(note_beside(&mut noted, &[(a, p)], 7, 7), 0); + assert!(noted.is_empty()); + // A fetch with nothing later in the air notes nothing. + assert_eq!(note_beside(&mut noted, &[(a, p)], 9, 9), 0); + assert!(noted.is_empty()); + } + + /// Two flights and what follows each: nothing of the second lands + /// before the card has run it, and nothing behind a flight lands + /// before the flight. + #[test] + fn flights_land_in_the_order_they_were_sent() { + // Flight (fence 5), its write, a signal, flight (fence 6), its write. + let line = [Some(5), None, None, Some(6), None]; + assert_eq!(landable(&line, 4), 0); + assert_eq!(landable(&line, 5), 3); + assert_eq!(landable(&line, 6), 5); + assert_eq!(landable(&line, u64::MAX), 5); + // Signals with no flight ahead land at once; behind one they wait. + assert_eq!(landable(&[None, None], 0), 2); + assert_eq!(landable(&[None, Some(9), None], 8), 1); + assert_eq!(landable(&[], 3), 0); + // After the first three landed, the rest when its turn comes. + assert_eq!(landable(&line[3..], 5), 0); + assert_eq!(landable(&line[3..], 6), 2); + } + + /// A piece flagged under one range of a plan is fetched under every + /// range that holds a part of it; pieces of other copies are not. + #[test] + fn a_piece_flagged_under_one_range_is_fetched_under_all() { + let (a, b) = (0x1000usize, 0x2000usize); + // Copy a: piece 3 under two ranges, flagged under the first only; + // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged. + let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)]; + let fetch = flagged_pieces(&flags); + assert!(fetch.contains(&(a, 3))); + assert!(!fetch.contains(&(a, 4))); + assert!(!fetch.contains(&(b, 3))); + assert!(fetch.contains(&(b, 9))); + assert_eq!(fetch.len(), 2); + } +} + +/// The most host lists in the air before the flights are settled +/// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the +/// relay it stopped the submitting thread twice a frame for 92-103 ms in +/// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162; +/// 32 settled the flights three times a +/// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables +/// asked and none refused; watch "tables asked, N refused"): their dynamic +/// descriptor slots, upload +/// memory and scratch chunks are held until then, and a frame's lists held +/// all at once ran the slots out before (run 45). +fn late_most() -> usize { + static MOST: OnceLock<usize> = OnceLock::new(); + let most = *MOST.get_or_init(|| { + std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1) + }); + if settle_room() { most * 2 } else { most } +} + +/// Whether the flights get twice the room before "lists in the air" +/// settles them ([`late_most`]) and eight times the changed runs before +/// the merge under shaders' writes gives up and settles them +/// (`VICTORY_MERGE_RUNS`, [`stale_under_flights`]) (`VICTORY_SETTLE_ROOM=1`; +/// off by default: the caps as set; `alt`: twenty seconds with, twenty +/// without, in turn, each change said in the log). +/// +/// Why: at the boat save (runs 311 and 316, world readings) the submitting +/// thread waits 4.9 to 6.6 ms a frame in settles: 2.4 to 2.5 ms for "title +/// memory changed under shader writes", where the merge gave up 0.55 times +/// a frame for more than 512 changed runs (about 1,000 changed runs a frame +/// are merged), and 1.6 to 2.9 ms for 256 lists in the air. Watch the +/// tables line ("N refused": dynamic slots are held while lists fly) and +/// the card's time (each merged run is a copy of its own there). +fn settle_room() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock<u8> = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_SETTLE_ROOM").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "flights get more room (lists in the air x2, changed runs merged x8) before they are settled from now (VICTORY_SETTLE_ROOM=alt): {}", + if on { "ON" } else { "off, the caps as set" } + ); + } + on + } + } } -impl Host { - /// Whether the host runs mesh shaders at shader model 6.6 (translated - /// mesh shaders need both); logged once. - pub(crate) fn mesh_shaders(&self) -> bool { - static MESH: OnceLock<bool> = OnceLock::new(); - *MESH.get_or_init(|| { - let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); - let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { - HighestShaderModel: D3D_SHADER_MODEL_6_6, +/// Set when a table found no free dynamic descriptor slots: lists in the +/// air hold theirs, so from then on no more than 256 fly (Try 6.7 asks for +/// 384 to keep the submitting thread off the card's back; the slots are +/// what bounds it). +static SLOTS_RAN_OUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// A table found no free dynamic descriptor slots ([`late_limit`]). +pub(crate) fn slots_ran_out() { + if !SLOTS_RAN_OUT.swap(true, Ordering::Relaxed) && late_most() > 256 { + tracing::warn!( + most = late_most(), + "dynamic descriptor slots ran out: no more than 256 lists fly from now on (VICTORY_LATE_WAIT_LISTS)" + ); + } +} + +/// [`late_most`], or at most 256 once the slots ran out. +fn late_limit() -> usize { + if SLOTS_RAN_OUT.load(Ordering::Relaxed) { late_most().min(256) } else { late_most() } +} + +/// Whether a submission with bottom-of-pipe writes may fly +/// (`VICTORY_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so +/// the title is told at once, as before; for telling a title that polls +/// such a value from one that does not). +fn late_writes() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_WAIT_WRITES").is_none_or(|v| v != "0")) +} + +/// Per host copy, the ranges a submission's shaders may write, as declared +/// (address, end). +type Declared = (std::sync::Arc<crate::shadow::Shadow>, Vec<(usize, usize)>); + +/// What [`Host::submit`] hands back for a submission it sent and did not +/// wait for. +struct Sent { + /// Its number among the submissions started. + number: u64, + card: Option<CardPlan>, + back: Vec<Declared>, + /// Title-memory ranges written when its shader textures are copied back. + texture_back_ranges: Vec<(usize, usize)>, + /// Its bottom-of-pipe writes. + writes: Vec<(usize, crate::queue::Written, usize)>, +} + +/// A submission on the card that has not been waited for ([`late`]): its +/// host lists, taken from the title's (which it may reset meanwhile), and +/// what is to be done once it has run. +struct Flight { + number: u64, + /// The value signalled on the host's fence behind it. + fence: u64, + lists: Vec<crate::list::Detached>, + order: Vec<usize>, + card: Option<CardPlan>, + back: Vec<Declared>, + /// The sends of title bytes to copies in the card's memory on the + /// queue ahead of its end ([`QUEUE_ORDER`]): done once it has run. + sends: u64, + texture_back_ranges: Vec<(usize, usize)>, +} + +/// One thing in the line of what waits for the card, in order. +enum Late { + Run(Flight), + /// A bottom-of-pipe write of the flight before it: address, what, bytes. + Write(usize, crate::queue::Written, usize), + /// A fence (its address) signalled behind the flights before it. + Signal(usize, u64), +} + +struct Line { + line: Vec<Late>, + /// The title memory the flights' shaders and texture readbacks may write + /// (address, end), in order and joined. + written: Vec<(usize, usize)>, + /// Host lists in the flights. + lists: usize, + /// The value signalled on the host's fence behind the last flight. + target: u64, + /// A settle has taken the line and is not done: a signal still goes + /// behind it. + settling: bool, + /// Something was settled away from a queue's own calls: the helper + /// thread looks at what queues hold. + poke: bool, + /// Host lists of settled flights, reset and given back outside the + /// submission lock ([`land`]: a settle may run under a caller's own + /// locks). + landed: Vec<(Vec<crate::list::Detached>, Vec<usize>)>, + /// With [`relay`]: the bottom-of-pipe writes of the flights being + /// landed (taken out of `line`, not done yet), for [`late_met`]. + in_hand: Vec<(usize, crate::queue::Written, usize)>, +} + +// SAFETY: D3D12 objects (free-threaded) and host lists nothing records +// into; touched under the lock. +unsafe impl Send for Line {} + +static LINE: Mutex<Line> = Mutex::new(Line { + line: Vec::new(), + written: Vec::new(), + lists: 0, + target: 0, + settling: false, + poke: false, + landed: Vec::new(), + in_hand: Vec::new(), +}); +/// Told when a flight joins [`LINE`] or it is poked. +static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new(); + +fn line() -> std::sync::MutexGuard<'static, Line> { + LINE.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Why flights were settled ([`LATE_STATS`]' places from 2 on). +const WHY_SYNC: usize = 2; +const WHY_CARD_DONE: usize = 3; +const WHY_VALUE: usize = 4; +const WHY_STALE: usize = 5; +const WHY_READ: usize = 6; +const WHY_RUN: usize = 7; +const WHY_MOST: usize = 8; +const WHY_WRITES: usize = 9; +const WHY_FENCE: usize = 10; + +/// Since the last frame-rate line: submissions sent without a wait; +/// settles; settles by reason ([`WHY_SYNC`]..); flights settled; +/// microseconds settles waited for the card; value waits met by a flight's +/// bottom-of-pipe write; fence signals set behind flights. +/// Then: the settles for title memory read, by what read it (a buffer +/// copy, a fill of upload memory, a texture). +static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18]; + +/// Since the last frame-rate line: the microseconds settles waited for the +/// card, by why they settled (the `WHY_` places). +static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; + +/// Whether `[from, to)` touches one of `ranges` (in order, joined). +fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool { + if from >= to { + return false; + } + let at = ranges.partition_point(|r| r.1 <= from); + ranges.get(at).is_some_and(|r| r.0 < to) +} + +/// `ranges` with `more`, in order, joined where they overlap or touch. +fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator<Item = (usize, usize)>) { + ranges.extend(more.into_iter().filter(|r| r.0 < r.1)); + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for &(from, to) in ranges.iter() { + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + *ranges = out; +} + +/// Whether anything is in the air. +fn flying() -> bool { + if !late() { + return false; + } + let line = line(); + // (With the relay: also while flights are being landed.) + line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_))) +} + +/// With flights in the air ([`late`]): why `runs` cannot be prepared +/// before they are settled, if so. Preparing reads title memory on the +/// CPU (the title's buffer copies, fills of upload memory, textures) and +/// runs steps of ours that may read or write it anywhere; what the +/// flights' shaders write is not there yet. +fn late_blocked(runs: &[&HostList]) -> Option<usize> { + let written = { + let line = line(); + if line.written.is_empty() { + return None; + } + line.written.clone() + }; + blocked_by(&written, runs, true) +} + +/// [`late_blocked`] against `written`, the title memory flights' shaders +/// may write (in order, joined); `count` whether the kind of read is +/// counted for the frame line. +fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option<usize> { + if written.is_empty() { + return None; + } + for list in runs { + for step in &list.deferred().copies { + match step { + &Step::Copy(dst, src, len) => { + let reads = touches(written, src, src + len); + let writes = touches(written, dst, dst + len); + if reads || writes { + // A copy that only READS where flights may write is + // not waited for either, and checked like a fill + // (`fill_ahead`): run 210 looked at 197 such waits + // (20,480 bytes out of the 174 MB buffer into a small + // buffer of its own, four a frame, 43 to 60 ms a + // frame) and neither side had other bytes after + // one. A copy INTO such a range still waits. + if !writes && fill_ahead::on() { + if count { + fill_ahead::read(src, len); + } + continue; + } + // Late readback (Try 6.6): a copy that only reads + // what a flight's shaders may write takes those + // results one flight late, as the fills do. + if late_copies() > u8::from(writes) { + if count { + LATE_COPIES[usize::from(writes)].fetch_add(1, Ordering::Relaxed); + } + continue; + } + if count { + LATE_STATS[15].fetch_add(1, Ordering::Relaxed); + LATE_COPIES[2 + usize::from(writes)].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + fill_check::blocked_copy(written, dst, src, len); + } + return Some(WHY_READ); + } + } + &Step::Fill(_, src, len) => { + if touches(written, src, src + len) { + // Not waited for, and checked when the flights land + // (`fill_ahead`). + if fill_ahead::on() { + if count { + fill_ahead::read(src, len); + } + continue; + } + if late_results() { + // Taken as title memory holds it now. + if count { + LATE_RESULTS.fetch_add(1, Ordering::Relaxed); + } + continue; + } + if count { + LATE_STATS[16].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + fill_check::blocked(written, src, len); + } + return Some(WHY_READ); + } + } + Step::Texture(staging) => { + let (at, len) = staging.memory(); + if touches(written, at, at + len) { + if count { + LATE_STATS[17].fetch_add(1, Ordering::Relaxed); + } + return Some(WHY_READ); + } + } + Step::Run(..) => return Some(WHY_RUN), + Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(_) | Step::AfterTextures(_) => {} + } + } + } + None +} + +/// Copy back only what is read (`VICTORY_READ_BACK_ONLY=0`: all the card +/// changed is copied back), Dolphin's skip of EFB copies to RAM: with lazy +/// copy-back on, a copy in the card's memory whose held memory neither a +/// title thread nor our own code touched in [`quiet_landings`] landings in +/// a row, and that the title does not write, is not fetched or merged; the +/// card keeps the only fresh bytes, which is all the shaders need. If +/// something touches it while a batch is held, its pieces are fetched +/// before the batch is done and it is copied back always from then on. +/// Every [`probe_every`]th landing copies everything back, so a reader +/// shows itself. +/// +/// shortcut: a read of such a copy outside a held batch sees older bytes +/// until a probe or a held read finds it; the title writing it puts its +/// counter back to nothing. +fn read_back_only() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| crate::lazy::on() && std::env::var_os("VICTORY_READ_BACK_ONLY").is_none_or(|v| v != "0")) +} + +/// See [`read_back_only`]: landings in a row a copy must go untouched +/// (`VICTORY_QUIET_LANDINGS`; 16 since Try 4.2, 64 before). +fn quiet_landings() -> u32 { + static N: OnceLock<u32> = OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_QUIET_LANDINGS").ok().and_then(|v| v.trim().parse().ok()).map_or(16, |n: u32| n.max(1))) +} + +/// See [`read_back_only`]: every how many landings everything is copied +/// back (`VICTORY_PROBE_EVERY`; 32 since Try 4.2, 16 before). +fn probe_every() -> u64 { + static N: OnceLock<u64> = OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_PROBE_EVERY").ok().and_then(|v| v.trim().parse().ok()).map_or(32, |n: u64| n.max(2))) +} + +/// Whether copies in the PC's memory are left alone too when nothing +/// reads them (`VICTORY_READ_BACK_ONLY_PC=0`: only copies in the card's +/// memory, as in Try 4.0). Try 4.2, idea 1 (CUDA's unified memory, which +/// moves a page back only when the CPU faults on it): the CPU looked +/// through 350-520 MB of such copies a frame for what shaders wrote (the +/// 2026-11-25 reports), most of it in copies nothing on the CPU reads. +/// Such a copy keeps the shaders' bytes, which is all later shaders need; +/// a touch while its batch is held has it compared and copied back before +/// the batch is let go, and always from then on, as for the card's. +fn read_back_only_pc() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| read_back_only() && std::env::var_os("VICTORY_READ_BACK_ONLY_PC").is_none_or(|v| v != "0")) +} + +/// Per copy in the PC's memory (by address): how many refreshes had +/// brought title bytes in at the last landing ([`read_back_only_pc`]). +fn pc_title_ins() -> std::sync::MutexGuard<'static, std::collections::HashMap<usize, u64>> { + static INS: OnceLock<std::sync::Mutex<std::collections::HashMap<usize, u64>>> = OnceLock::new(); + INS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Per copy in the card's memory (by its address): its title start and +/// the landings in a row nothing touched it, `u32::MAX` once something did. +fn read_quiet() -> std::sync::MutexGuard<'static, std::collections::HashMap<usize, (usize, u32)>> { + static QUIET: OnceLock<std::sync::Mutex<std::collections::HashMap<usize, (usize, u32)>>> = OnceLock::new(); + QUIET.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Pieces left on the card ([`read_back_only`]), their bytes, and pieces +/// fetched after all as something read them, since the frame line. +static READ_ONLY_STATS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// The copies of `plans` (by address) whose pieces are left on the card in +/// this landing ([`read_back_only`]), and of the copies in the PC's memory +/// `pc` those left uncompared ([`read_back_only_pc`]); `held` whether the +/// batch is held (only then are touches seen). +fn read_only_plan(plans: &[&CardPlan], pc: &[Declared], held: bool) -> Vec<usize> { + if !read_back_only() || !held { + return Vec::new(); + } + static LANDINGS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let landing = LANDINGS.fetch_add(1, Ordering::Relaxed); + let touched = crate::lazy::take_touched(); + let mut quiet = read_quiet(); + let mut ins = pc_title_ins(); + let mut seen: Vec<usize> = Vec::new(); + let mut skip = Vec::new(); + let card = plans.iter().flat_map(|plan| plan.ranges.iter().map(|r| &r.shadow)); + let pc = pc.iter().map(|(shadow, _)| shadow).filter(|s| read_back_only_pc() && !s.carded()); + for shadow in card.chain(pc) { + let copy = std::sync::Arc::as_ptr(shadow) as usize; + if seen.contains(©) { + continue; + } + seen.push(copy); + let (from, to) = shadow.title_span(); + let read = touched.as_ref().is_none_or(|t| t.iter().any(|&(a, b)| a < to && b > from)); + let entry = quiet.entry(copy).or_insert((from, 0)); + if entry.0 != from { + *entry = (from, 0); + } + // The title writes it: title bytes on their way to the card's + // side, or (in the PC's memory) brought in since the last landing. + let writes = if shadow.carded() { + shadow.title_writes_card() + } else { + let now = shadow.title_ins(); + ins.insert(copy, now).is_none_or(|before| before != now) + }; + if read { + entry.1 = u32::MAX; + } else if writes { + if entry.1 != u32::MAX { + entry.1 = 0; + } + } else { + entry.1 = entry.1.saturating_add(1); + } + if entry.1 != u32::MAX && entry.1 >= quiet_landings() && !landing.is_multiple_of(probe_every()) { + skip.push(copy); + } + } + skip +} + +/// Whether a fill of upload memory from title memory that a flight's +/// shaders may write goes on with what title memory holds (the results +/// of the last flight copied back there), not waiting for the flight to +/// land (`VICTORY_LATE_RESULTS=0`: waits). Xenia's fast readback: the +/// submitting thread waited 60-275 ms a frame for such fills in the +/// 2026-11-24 report. Most were of ranges the shaders declared but did not +/// write (a view over a whole pool); where they did, the fill takes the +/// results one flight late. +fn late_results() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LATE_RESULTS").is_none_or(|v| v != "0")) +} + +/// Whether the title's buffer copies on the CPU that read title memory a +/// flight's shaders may write go on with what title memory holds, not +/// waiting for the flight to land (`VICTORY_LATE_COPIES`: 1 unless set; +/// 2 also copies that write there, 0 waits, as before Try 6.6). +/// +/// Try 6.6, the late readback of big engines (occlusion queries, exposure +/// and GPU culling results are read a frame or more late on PC, so the CPU +/// never waits for the card): in the 6.5 report the submitting thread +/// stood 105-132 ms a frame waiting for the card, all of it for one settle +/// "title memory read by a buffer copy" a frame. +fn late_copies() -> u8 { + static N: OnceLock<u8> = OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_LATE_COPIES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1).min(2)) +} + +/// Since the frame line, the title's CPU copies over flights' writes: let +/// go one flight late reading them, let go writing them, settled for +/// reading only, settled for writing ([`late_copies`]). +static LATE_COPIES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Fills that went on with the results one flight late ([`late_results`]), +/// since the frame line last took them. +static LATE_RESULTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Fills of upload memory (a constant buffer a table names, copied into +/// the list's own memory when the list is submitted) that read title memory +/// flights "may write" are no longer waited for; what the flights then +/// write is checked against them, and the first fill that read bytes a +/// flight changed afterwards turns the waiting back on for good. +/// +/// Why: a flight declares every range its shaders can store to, and the +/// title has an unordered view over the whole of its 174 MB buffer, whose +/// copy is in the card's memory. Its per-draw constants lie in the same +/// buffer, at new addresses every frame. So the first such fill of a frame +/// waited until those flights had landed: one wait a frame, 56 to 95 ms of +/// the submitting thread standing still (runs 202 and 206; 145 ms while +/// the world loaded in 208), the largest single wait of the frame. Run 208 +/// looked at every one of them: 44 fills of 480 bytes, and after the wait +/// the bytes were the same 44 times. +/// +/// What it risks, and how it is bounded: a fill that reads bytes a flight +/// in the air is about to change takes the old bytes, and the lists of +/// that one submission draw with them. `wrote` sees it when the flight +/// lands (the bytes going into title memory are compared with the ones +/// there, over every fill that read ahead of them) and from then on fills +/// wait as before. `VICTORY_FILL_WAIT=1`: they wait from the start. +mod fill_ahead { + use std::collections::HashMap; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; + use std::sync::{Mutex, OnceLock}; + + /// Fills are looked up by the 64 KiB of title memory they read. + const PIECE: usize = 1 << 16; + /// A fill is checked against flights that land this many frames after + /// it at most (flights are settled at 256 lists in the air, and by + /// every present that waits). + const KEEP: u64 = 16; + + /// A flight changed bytes a fill had read ahead of it: fills wait. + static WAIT: AtomicBool = AtomicBool::new(false); + /// Since the last frame line: fills that read ahead; landings' writes + /// that touched one's piece. Since the start: fills that read bytes a + /// flight then changed. + static COUNT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + + #[derive(Default)] + struct Piece { + /// The frame its old fills were last dropped in. + pruned: u64, + /// From, to, frame, and the number of the last submission started + /// when it read: the flights in the air then have that number or + /// a lower one, and only their writes can be ones it missed. + fills: Vec<(usize, usize, u64, u64)>, + } + + /// The lowest submission number among the flights the landing thread + /// is landing now; 0: not known (a landing by another way), and then + /// every write counts. (Run 211: a read of frame 1381 was taken for + /// missed because shaders wrote the same 80 bytes in frame 1397, in a + /// flight sent sixteen frames after it.) + static LANDING: AtomicU64 = AtomicU64::new(0); + + pub(super) fn landing(first: u64) { + LANDING.store(first, Relaxed); + } + + static READ: Mutex<Option<HashMap<usize, Piece>>> = Mutex::new(None); + + pub(super) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_WAIT").is_none_or(|v| v != "1")) && !WAIT.load(Relaxed) + } + + /// A fill reads `len` bytes at `src` ahead of flights that may write + /// them. + pub(super) fn read(src: usize, len: usize) { + if len == 0 { + return; + } + COUNT[0].fetch_add(1, Relaxed); + let frame = crate::frame::current(); + let mut read = READ.lock().unwrap_or_else(|e| e.into_inner()); + let map = read.get_or_insert_with(HashMap::new); + for piece in src / PIECE..=(src + len - 1) / PIECE { + let p = map.entry(piece).or_default(); + if p.pruned != frame { + p.pruned = frame; + p.fills.retain(|f| f.2 + KEEP >= frame); + } + p.fills.push((src, src + len, frame, super::STARTED.load(Relaxed))); + } + } + + /// A landing is about to put `new` into title memory at `at`: bytes + /// shaders wrote, merged into the title's. + pub(crate) fn wrote(at: usize, new: &[u8]) { + if new.is_empty() || WAIT.load(Relaxed) { + return; + } + let frame = crate::frame::current(); + let landing = LANDING.load(Relaxed); + let hits: Vec<(usize, usize, u64)> = { + let read = READ.lock().unwrap_or_else(|e| e.into_inner()); + let Some(map) = read.as_ref() else { return }; + let end = at + new.len(); + (at / PIECE..=(end - 1) / PIECE) + .filter_map(|piece| map.get(&piece)) + .flat_map(|p| p.fills.iter().copied()) + .filter(|f| f.0 < end && f.1 > at && f.2 + KEEP >= frame && (landing == 0 || landing <= f.3)) + .map(|f| (f.0, f.1, f.2)) + .collect() + }; + if hits.is_empty() { + return; + } + COUNT[1].fetch_add(1, Relaxed); + let mut now = Vec::new(); + for (from, to, read_in) in hits { + let (a, b) = (from.max(at), to.min(at + new.len())); + now.clear(); + now.resize(b - a, 0); + // Title memory as it is, which is what the fill read unless the + // title wrote it since; not there: nothing to say. + if !super::read_into(a as *const u8, &mut now) || now[..] == new[a - at..b - at] { + continue; + } + let n = COUNT[2].fetch_add(1, Relaxed) + 1; + let first = now.iter().zip(&new[a - at..b - at]).position(|(x, y)| x != y).unwrap_or(0); + if !WAIT.swap(true, Relaxed) { + tracing::warn!( + "a fill of upload memory read {} bytes at {from:#x} in frame {read_in} ahead of a flight whose shaders changed \ + them (first at {:#x}, landed in frame {frame}): the lists of that submission drew with the bytes from before. \ + Fills wait for flights again from here on, as with VICTORY_FILL_WAIT=1 ({n} such fills)", + to - from, + a + first + ); + } + return; + } + } + + /// With the frame line. + pub(super) fn line(frames: f64) { + let [ahead, looked] = [0, 1].map(|i| COUNT[i].swap(0, Relaxed)); + if ahead == 0 && looked == 0 { + return; + } + let kept = { + let frame = crate::frame::current(); + let mut read = READ.lock().unwrap_or_else(|e| e.into_inner()); + read.as_mut().map_or(0, |map| { + map.retain(|_, p| { + p.fills.retain(|f| f.2 + KEEP >= frame); + !p.fills.is_empty() + }); + map.values().map(|p| p.fills.len()).sum::<usize>() + }) + }; + tracing::info!( + "fills of upload memory that read title memory flights may write, not waited for (VICTORY_FILL_WAIT=1 waits): {:.1} per \ + frame; {:.1} landings' writes per frame fell in the same 64 KiB as one and were compared with it; fills that read \ + bytes a flight then changed, since the start: {}{}; {kept} fills kept to check", + ahead as f64 / frames, + looked as f64 / frames, + COUNT[2].load(Relaxed), + if WAIT.load(Relaxed) { " (fills wait again)" } else { "" } + ); + } +} + +pub(crate) use fill_ahead::wrote as shaders_write; + +/// Diagnostics: the fills of upload memory that made a submission wait for +/// flights (`blocked_by`), which one they are, and whether the wait was +/// needed: the bytes the fill reads are kept when it blocks and compared +/// with what it reads once the flights have landed. +/// +/// Runs 202 and 206: one such wait a frame, 56 to 95 ms of the submitting +/// thread standing still, the largest single wait of the frame. The ranges +/// flights "may write" are whole views shaders can store to; if the bytes +/// a fill reads never change under the wait, the wait is for nothing. +#[cfg(feature = "diagnostics")] +mod fill_check { + use std::sync::Mutex; + use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + + /// The fill waited for now: source, length, its bytes when it blocked. + static PENDING: Mutex<Option<(usize, usize, Vec<u8>)>> = Mutex::new(None); + /// Fills that blocked by (source page, length): how often. + static SEEN: Mutex<Vec<(usize, usize, u64)>> = Mutex::new(Vec::new()); + /// Fills checked after their wait; those whose bytes had changed; the + /// bytes that had. + static CHECKED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + + /// A fill of `len` bytes at `src` blocks on `written`. + pub(super) fn blocked(written: &[(usize, usize)], src: usize, len: usize) { + let at = written.partition_point(|r| r.1 <= src); + let touched = written.get(at).copied().unwrap_or((0, 0)); + let key = (src & !0xfff, len); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let known = seen.iter().position(|s| (s.0, s.1) == key); + match known { + Some(k) => seen[k].2 += 1, + None if seen.len() < 256 => { + seen.push((key.0, key.1, 1)); + if seen.len() <= 12 { + tracing::info!( + "a fill of upload memory waits for flights: {len} bytes at {src:#x}; the range shaders may write that it touches: {:#x}+{:#x} ({} ranges in the air); frame {}", + touched.0, + touched.1 - touched.0, + written.len(), + crate::frame::current() + ); + } + } + None => {} + } + drop(seen); + let mut bytes = vec![0u8; len.min(1 << 20)]; + if super::read_into(src as *const u8, &mut bytes) { + *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((src, len, bytes)); + } + } + + /// The fill of `len` bytes at `src` runs now. + pub(super) fn runs(src: usize, len: usize) { + let mut pending = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if !pending.as_ref().is_some_and(|p| (p.0, p.1) == (src, len)) { + return; + } + let Some((_, _, before)) = pending.take() else { return }; + drop(pending); + let mut now = vec![0u8; before.len()]; + if !super::read_into(src as *const u8, &mut now) { + return; + } + let differ = before.iter().zip(&now).filter(|(a, b)| a != b).count() as u64; + let n = CHECKED[0].fetch_add(1, Relaxed) + 1; + if differ > 0 { + let bad = CHECKED[1].fetch_add(1, Relaxed) + 1; + CHECKED[2].fetch_add(differ, Relaxed); + if bad <= 12 { + let first = before.iter().zip(&now).position(|(a, b)| a != b).unwrap_or(0); + tracing::info!( + "a fill of upload memory that waited for flights read other bytes after the wait: {differ} of {len} bytes at {src:#x} changed, the first at +{first:#x} (check {n}, frame {})", + crate::frame::current() + ); + } + } + } + + /// The title buffer copy waited for now: destination, source, length, + /// the bytes of both when it blocked. + static PENDING_COPY: Mutex<Option<(usize, usize, usize, Vec<u8>, Vec<u8>)>> = Mutex::new(None); + /// Copies checked after their wait; those whose source had changed; + /// those whose destination had. + static COPIES: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + /// Copies that blocked by (source page, destination page, length). + static SEEN_COPIES: Mutex<Vec<(usize, usize, usize, u64)>> = Mutex::new(Vec::new()); + + /// A title buffer copy of `len` bytes from `src` to `dst` blocks on + /// `written`. + pub(super) fn blocked_copy(written: &[(usize, usize)], dst: usize, src: usize, len: usize) { + let by_src = super::touches(written, src, src + len); + let by_dst = super::touches(written, dst, dst + len); + let key = (src & !0xfff, dst & !0xfff, len); + let mut seen = SEEN_COPIES.lock().unwrap_or_else(|e| e.into_inner()); + let known = seen.iter().position(|s| (s.0, s.1, s.2) == key); + match known { + Some(k) => seen[k].3 += 1, + None if seen.len() < 256 => { + seen.push((key.0, key.1, key.2, 1)); + if seen.len() <= 16 { + let range = |at: usize| { + let k = written.partition_point(|r| r.1 <= at); + written.get(k).copied().unwrap_or((0, 0)) + }; + let (s, d) = (range(src), range(dst)); + tracing::info!( + "a title buffer copy waits for flights: {len} bytes from {src:#x} to {dst:#x}; source in a range shaders may write: {by_src} ({:#x}+{:#x}); destination: {by_dst} ({:#x}+{:#x}); {} ranges in the air; frame {}", + s.0, + s.1 - s.0, + d.0, + d.1 - d.0, + written.len(), + crate::frame::current() + ); + } + } + None => {} + } + drop(seen); + let n = len.min(1 << 20); + let (mut a, mut b) = (vec![0u8; n], vec![0u8; n]); + if super::read_into(src as *const u8, &mut a) && super::read_into(dst as *const u8, &mut b) { + *PENDING_COPY.lock().unwrap_or_else(|e| e.into_inner()) = Some((dst, src, len, a, b)); + } + } + + /// The title buffer copy runs now. + pub(super) fn copy_runs(dst: usize, src: usize, len: usize) { + let mut pending = PENDING_COPY.lock().unwrap_or_else(|e| e.into_inner()); + if !pending.as_ref().is_some_and(|p| (p.0, p.1, p.2) == (dst, src, len)) { + return; + } + let Some((_, _, _, src_before, dst_before)) = pending.take() else { return }; + drop(pending); + let (mut a, mut b) = (vec![0u8; src_before.len()], vec![0u8; dst_before.len()]); + if !super::read_into(src as *const u8, &mut a) || !super::read_into(dst as *const u8, &mut b) { + return; + } + let n = COPIES[0].fetch_add(1, Relaxed) + 1; + let (src_changed, dst_changed) = (a != src_before, b != dst_before); + if src_changed { + COPIES[1].fetch_add(1, Relaxed); + } + if dst_changed { + COPIES[2].fetch_add(1, Relaxed); + } + if (src_changed || dst_changed) && COPIES[1].load(Relaxed) + COPIES[2].load(Relaxed) <= 16 { + let differ = |x: &[u8], y: &[u8]| x.iter().zip(y).filter(|(p, q)| p != q).count(); + tracing::info!( + "a title buffer copy that waited for flights found other bytes after the wait: {len} bytes from {src:#x} to {dst:#x}; {} source bytes changed, {} destination bytes changed (check {n}, frame {})", + differ(&a, &src_before), + differ(&b, &dst_before), + crate::frame::current() + ); + } + } + + /// With the frame line. + pub(super) fn line() { + let copies = COPIES[0].load(Relaxed); + if copies > 0 { + let seen = SEEN_COPIES.lock().unwrap_or_else(|e| e.into_inner()); + let mut most: Vec<_> = seen.clone(); + most.sort_unstable_by_key(|s| std::cmp::Reverse(s.3)); + let most: Vec<String> = + most.iter().take(6).map(|s| format!("{:#x}->{:#x}+{:#x} {}x", s.0, s.1, s.2, s.3)).collect(); + tracing::info!( + "title buffer copies that waited for flights, since the start: {copies} checked after their wait; the source had other bytes after it {} times, the destination {} times; {} distinct copies, the most frequent: {}", + COPIES[1].load(Relaxed), + COPIES[2].load(Relaxed), + seen.len(), + most.join(", ") + ); + } + let n = CHECKED[0].load(Relaxed); + if n == 0 { + return; + } + let seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let mut most: Vec<_> = seen.clone(); + most.sort_unstable_by_key(|s| std::cmp::Reverse(s.2)); + let most: Vec<String> = most.iter().take(6).map(|s| format!("{:#x}+{:#x} {}x", s.0, s.1, s.2)).collect(); + tracing::info!( + "fills of upload memory that waited for flights, since the start: {n} checked after their wait, {} of them read other bytes than before it ({} bytes in all); {} distinct fills (page, length), the most frequent: {}", + CHECKED[1].load(Relaxed), + CHECKED[2].load(Relaxed), + seen.len(), + most.join(", ") + ); + } +} + +/// Whether a submission's passes over its lists' steps find a step's copy +/// by an index instead of a search (`VICTORY_STEP_INDEX=1`; off by default; +/// `alt`: twenty seconds with, twenty without, in turn, each change said in +/// the log). The same copies, ranges and order come out +/// ([`declared_by_index`], [`stale_under_flights`]); what goes is a lock +/// and a search of a list per refresh step and a search of two lists per +/// range given to shaders. +fn step_index() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock<u8> = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_STEP_INDEX").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a submission's steps find their copy by an index from now (VICTORY_STEP_INDEX=alt): {}", + if on { "ON" } else { "off, by a search as usual" } + ); + } + on + } + } +} + +/// The ranges (from, to) given to shaders, as `given` names them in order, +/// per copy: the copies in the order they first come, each range once, in +/// the order it first comes. What the search per step gives +/// ([`declared_writes`], `Host::card_before`), found by an index. +fn declared_by_index<'a>( + given: impl Iterator<Item = (&'a std::sync::Arc<crate::shadow::Shadow>, (usize, usize))>, +) -> Vec<Declared> { + grouped(given.map(|(shadow, range)| (std::sync::Arc::as_ptr(shadow) as usize, shadow, range))) + .into_iter() + .map(|(shadow, ranges)| (shadow.clone(), ranges)) + .collect() +} + +/// `given` (a key, what the key stands for, a range) as one entry per key, +/// in the order the keys first come, each with its ranges, every range +/// once, in the order it first comes ([`declared_by_index`]). +fn grouped<T>(given: impl Iterator<Item = (usize, T, (usize, usize))>) -> Vec<(T, Vec<(usize, usize)>)> { + let mut out: Vec<(T, Vec<(usize, usize)>)> = Vec::new(); + let mut place: std::collections::HashMap<usize, usize> = std::collections::HashMap::new(); + let mut seen: std::collections::HashSet<(usize, usize, usize)> = std::collections::HashSet::new(); + for (key, of, range) in given { + if !seen.insert((key, range.0, range.1)) { + continue; + } + let at = *place.entry(key).or_insert_with(|| { + out.push((of, Vec::new())); + out.len() - 1 + }); + out[at].1.push(range); + } + out +} + +#[cfg(test)] +mod grouped_tests { + /// What the search per step gives (`declared_writes` without the + /// switch), for keys that stand for themselves. + fn searched(given: &[(usize, (usize, usize))]) -> Vec<(usize, Vec<(usize, usize)>)> { + let mut back: Vec<(usize, Vec<(usize, usize)>)> = Vec::new(); + for &(key, range) in given { + match back.iter_mut().find(|(k, _)| *k == key) { + Some((_, ranges)) => { + if !ranges.contains(&range) { + ranges.push(range); + } + } + None => back.push((key, vec![range])), + } + } + back + } + + /// The index gives what the search gives: the same keys in the same + /// order, each with the same ranges in the same order, whatever comes + /// twice and however the keys take turns. + #[test] + fn the_index_gives_what_the_search_gives() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |below: usize| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize % below + }; + assert!(super::grouped(std::iter::empty::<(usize, usize, (usize, usize))>()).is_empty()); + for (keys, ranges, steps) in [(1, 1, 5), (3, 4, 200), (40, 6, 3000), (500, 50, 3000)] { + for _ in 0..20 { + let given: Vec<(usize, (usize, usize))> = (0..steps) + .map(|_| { + let from = next(ranges) * 64; + (0x1000 + next(keys) * 8, (from, from + 16 + next(2) * 16)) + }) + .collect(); + let by_index = super::grouped(given.iter().map(|&(key, range)| (key, key, range))); + assert_eq!(by_index, searched(&given), "{keys} keys, {ranges} ranges, {steps} steps"); + } + } + } +} + +/// The ranges of `runs`' steps that give memory to shaders, with the copy +/// each is of; `carded`: only those of copies in the card's memory. +fn given_to_shaders<'a>( + runs: &'a [&'a HostList], + carded: bool, +) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, (usize, usize))> { + let mut given = Vec::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::GpuWrite(shadow, address, len) = step + && (!carded || shadow.carded()) + { + given.push((shadow.clone(), (*address, *address + *len))); + } + } + } + given +} + +/// With flights in the air, after the submission's write-watch asking: +/// whether `runs` refresh a range of a host copy that a flight's shaders +/// may write and that the title wrote since it was last copied. The +/// refresh leaves ranges shaders are writing alone (`Shadow::update`), so +/// the title's bytes there would reach the card a submission late. +fn stale_under_flights(runs: &[&HostList]) -> bool { + use std::sync::Arc; + // Per copy, the span of what is refreshed (a flush brings that much + // up to date at most). + let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new(); + if step_index() { + // By copy (its address): its place in `spans`, or that no shader's + // writes are pending on it. Asked once a copy, not once a step + // (20,000 to 43,000 refresh steps a frame, each a lock and a search + // of `spans`); steps of one copy mostly follow one another, so the + // last answer is tried first. Only this thread adds pending writes, + // after this; a landing may take a copy's away meanwhile, and then + // its span is as if the landing came before or after all its + // steps, and the merge below finds nothing pending. + let mut known: std::collections::HashMap<usize, Option<usize>> = std::collections::HashMap::new(); + let mut last: (usize, Option<usize>) = (0, None); + for list in runs { + for step in &list.deferred().copies { + if let Step::Refresh(shadow, address, len) = step { + let key = Arc::as_ptr(shadow) as usize; + let at = if last.0 == key { + last.1 + } else { + let at = *known.entry(key).or_insert_with(|| { + shadow.writes_pending().then(|| { + spans.push((shadow.clone(), usize::MAX, 0)); + spans.len() - 1 + }) + }); + last = (key, at); + at + }; + if let Some(at) = at { + let s = &mut spans[at]; + (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len)); + } + } + } + } + } else { + for list in runs { + for step in &list.deferred().copies { + if let Step::Refresh(shadow, address, len) = step + && shadow.writes_pending() + { + match spans.iter_mut().find(|s| Arc::ptr_eq(&s.0, shadow)) { + Some(s) => (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len)), + None => spans.push((shadow.clone(), *address, *address + *len)), + } + } + } + } + } + if late_exact() { + // The title's bytes are put in beside the flights' writes; a + // settle is still due where that could not be done. At most this + // many changed runs go up to copies in the card's memory, each a + // copy of its own there. + // (512 once: pages of the title's constants change in more runs + // than that between two submissions, and every frame then waited + // for its fifteen flights, 400 ms on an RTX 4060, for "3 pages + // looked at, 0 changed runs"; avatarmanz/VIctory-7900XTX 007fe557 + // found the same. A run is one small copy on the card.) + // (`VICTORY_MERGE_RUNS`: the cap; eight times it with + // `VICTORY_SETTLE_ROOM=1`, or `VICTORY_MERGE_RUNS_ALT` in its phases.) + let mut runs_left = merge_runs(); + if settle_room() { + runs_left = (runs_left * 8).min(1 << 16); + } + if let Some(wider) = merge_runs_alt() { + runs_left = wider; + } + let mut unwatched_left = crate::shadow::merge_unwatched_bytes(); + return spans + .iter() + .any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left, &mut unwatched_left)); + } + spans.iter().any(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from)) +} + +/// Changed runs a submission may put in under flights' shader writes +/// before it settles them instead (`VICTORY_MERGE_RUNS`, 16384). +fn merge_runs() -> usize { + static N: OnceLock<usize> = OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_MERGE_RUNS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(16384)) +} + +/// The cap of changed runs the merge under flights' writes takes before it settles the flights, in the phases with +/// `VICTORY_MERGE_RUNS_ALT=N` (unset: none, the cap as set): twenty seconds N (1 to 65,536), twenty seconds the cap +/// of `VICTORY_MERGE_RUNS` (x8 with [`settle_room`]), in turn, each change said in the log. +/// +/// Why: run 345 (warm cache, the owner's flag set, which has `VICTORY_SETTLE_ROOM=1` and no `VICTORY_MERGE_RUNS`: a +/// cap of 4,096) settled 1.4 times a frame for "title memory changed under shader writes", 84.8 ms a frame of the +/// submitting thread waiting for the card, and every give-up of the merge in its lines was "for more changed runs +/// than VICTORY_MERGE_RUNS leaves" (5 to 10 a window; 2,000 to 2,500 changed runs a frame are merged). Both ways are +/// exact: the merge puts the title's changed bytes in beside the flights' writes, a run a copy on the card; the settle +/// waits for the flights and lands them first. The price of the wider cap is those copies' card time, in the same +/// phases (the card meter's "send-and-hash lists"). +fn merge_runs_alt() -> Option<usize> { + static WIDER: OnceLock<Option<usize>> = OnceLock::new(); + let wider = (*WIDER.get_or_init(|| { + std::env::var("VICTORY_MERGE_RUNS_ALT").ok().and_then(|v| v.trim().parse::<usize>().ok()).map(|n| n.clamp(1, 1 << 16)) + }))?; + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "the merge under flights' writes takes {} changed runs a submission before it settles them, from now (VICTORY_MERGE_RUNS_ALT): {}", + if on { wider.to_string() } else { "the cap as set".to_string() }, + if on { "ON" } else { "off" } + ); + } + on.then_some(wider) +} + +/// Whether the list that brings copies in the card's memory up to date +/// records its work in three steps over all the copies: every changed +/// range copied up, then every state change in one call, then every hash +/// pass (`VICTORY_CARD_SYNC_BATCH=1`; fork pull request #1227, where it is +/// on by default. Here: OFF unless set until a run of ours has carried it; +/// `alt`: twenty seconds with, twenty without, in turn, each change said in +/// the log). +/// +/// Copy by copy, each with its copies, its state change and its hash +/// passes, the card went from copying to compute and back for every copy +/// of the list: about 300 times a frame with every title buffer's copy in +/// the card's memory (`VICTORY_CARD_BUFFERS_MIN_KB=64`), where the +/// send-and-hash lists took 24 to 28 ms of the card a frame for 28 MB sent +/// up and 600 pieces hashed. The same work in three steps took 5.3 to 5.7. +/// Nothing a hash pass reads is written by a later copy of the list: each +/// copy's ranges and pieces are its own buffer's. +fn sync_batched() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock<u8> = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_CARD_SYNC_BATCH").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "the send-and-hash list records its copies, one state change and its hash passes in three steps from now (VICTORY_CARD_SYNC_BATCH=alt): {}", + if on { "ON" } else { "off, copy by copy as usual" } + ); + } + on + } + } +} + +/// A fence signal on a queue ([`late`]): goes behind the flights in the +/// air, if there are any, and is set when they are settled. Whether it +/// did; if not the caller sets the fence now. +pub(crate) fn late_signal(fence: usize, value: u64) -> bool { + if !late() { + return false; + } + let mut line = line(); + if line.line.is_empty() && !line.settling { + return false; + } + line.line.push(Late::Signal(fence, value)); + LATE_STATS[14].fetch_add(1, Ordering::Relaxed); + drop(line); + // A signal alone (behind a settle under way) has no flight to wake + // the helper thread for it. + LINE_MOVED.notify_one(); + RELAY_MOVED.notify_one(); + true +} + +/// A queue stands at `wait`, which memory does not meet now ([`late`]): +/// whether it is met once the flights in the air have run. A flight's +/// bottom-of-pipe write of a value that meets it says yes without a wait +/// for the card: the part behind the wait goes to the card behind that +/// flight, which is the order the wait asks for. If the flights may write +/// the value in a way not known here (shaders, a timestamp, another +/// width), they are settled and memory is asked again. +pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool { + let (address, bytes) = wait.place(); + { + let line = line(); + if line.line.is_empty() && line.in_hand.is_empty() { + return false; + } + let mut unsure = touches(&line.written, address, address + bytes); + // (With the relay: first the writes of flights being landed.) + let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item { + Late::Write(at, what, n) => Some((at, what, n)), + _ => None, + })); + for (at, what, n) in writes { + if *at >= address + bytes || address >= *at + *n { + continue; + } + match what { + crate::queue::Written::Value(v) if *at == address && *n >= bytes => { + if wait.holds_for(*v) { + LATE_STATS[13].fetch_add(1, Ordering::Relaxed); + return true; + } + } + _ => unsure = true, + } + } + if !unsure { + return false; + } + } + settle_now(WHY_VALUE); + wait.met() +} + +/// [`late_met`] without its settle: whether a bottom-of-pipe write of a +/// flight in the air, or of one being landed, is known to meet `wait`. +/// False says nothing about what else the flights may write there. +pub(crate) fn late_met_known(wait: &crate::list::ValueWait) -> bool { + let (address, bytes) = wait.place(); + let line = line(); + let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item { + Late::Write(at, what, n) => Some((at, what, n)), + _ => None, + })); + for (at, what, n) in writes { + if let crate::queue::Written::Value(v) = what + && *at == address + && *n >= bytes + && wait.holds_for(*v) + { + LATE_STATS[13].fetch_add(1, Ordering::Relaxed); + return true; + } + } + false +} + +/// Settles the flights in the air, if any ([`Host::settle`]), for reason +/// `why` (one of the `WHY_` places). Not from inside a submission. +pub(crate) fn settle_now(why: usize) { + if !late() { + return; + } + let Some(host) = host() else { + return; + }; + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + host.settle(&mut submitted, why); +} + +/// [`settle_now`] at a present, and for a fence the title blocks on. +pub(crate) fn settle_for_present() { + settle_now(WHY_SYNC); +} +pub(crate) fn settle_for_fence() { + settle_now(WHY_FENCE); +} + +/// Resets the host lists of settled flights and keeps them for reuse, as +/// a queue does for the lists it ran (`crate::list::recycle`). +fn land() { + let landed = std::mem::take(&mut line().landed); + for (lists, order) in landed { + crate::list::recycle(lists, &order); + } +} + +/// The thread that settles the flights once the card has run them all +/// ([`late`]): without it a bottom-of-pipe write would reach the title only +/// at the next call that settles, and a title thread that polls such a +/// value while the submitting thread waits for that thread would never +/// see it. +fn late_helper() { + let Some(host) = host() else { + return; + }; + crate::framelog::keep_on_fast_cores("victory-late-wait"); + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + tracing::warn!("no event for the thread that settles submissions sent ahead"); + return; + }; + loop { + let target = { + let mut line = line(); + loop { + if line.poke { + line.poke = false; + break None; + } + // (With the relay the flights are another thread's.) + if !relay() && !line.line.is_empty() && !line.settling { + break Some(line.target); + } + line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner()); + } + }; + let Some(target) = target else { + land(); + crate::queue::release_held(false); + continue; + }; + // The card first, without the submission lock: the submitting + // thread prepares and sends meanwhile. + // SAFETY: our fence and event. + unsafe { + if host.fence.SetEventOnCompletion(target, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + } + { + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + // Something newer went up meanwhile: the card is waited for + // again, the submitting thread is not held up for it. + if line().target != target { + continue; + } + host.settle(&mut submitted, WHY_CARD_DONE); + } + land(); + crate::queue::release_held(false); + } +} + +/// Starts the threads of [`late`], once: the one that settles flights when +/// the card has run them and looks at what queues hold, and with [`relay`] +/// the one that lands flights. +fn late_threads() { + static HELPER: std::sync::Once = std::sync::Once::new(); + HELPER.call_once(|| { + if let Err(e) = std::thread::Builder::new().name("victory-late-wait".into()).spawn(late_helper) { + tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow"); + } + tracing::info!( + most = late_most(), + writes = late_writes(), + "submissions are sent to the card without a wait for each (VICTORY_LATE_WAIT=1)" + ); + if relay() { + // Without it nothing would ever land. + if let Err(e) = std::thread::Builder::new().name("victory-relay".into()).spawn(relay_worker) { + fail(format_args!("no thread to land submissions sent ahead (VICTORY_RELAY=1): {e}")); + } + tracing::info!( + exact = relay_exact(), + "what shaders wrote is copied back by a thread of its own, beside the submitting thread (VICTORY_RELAY=1)" + ); + } + }); +} + +/// With [`relay`]: waits until `done` says so of the line, looked at each +/// time flights have landed. Counted as a settle for `why`, and its time +/// as waiting for the card. The caller may hold the submission lock: the +/// thread that lands flights never takes it. +fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { + let mut line = line(); + if done(&line) { + return; + } + LATE_STATS[1].fetch_add(1, Ordering::Relaxed); + LATE_STATS[why].fetch_add(1, Ordering::Relaxed); + let was_working = working(false); + let waiting = std::time::Instant::now(); + while !done(&line) { + line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner()); + } + drop(line); + stood(waiting); + working(was_working); + let us = waiting.elapsed().as_micros() as u64; + LATE_STATS[12].fetch_add(us, Ordering::Relaxed); + LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed); + submission_us(1, us); +} + +/// What the thread that lands flights fetches card copies' pieces with +/// ([`relay`]): a list, a fence and an event of its own (the host's are +/// behind the submission lock), and the memory the pieces come down to. +struct RelayFetch { + list: Prelude, + fence: ID3D12Fence, + event: HANDLE, + /// The last value signalled on `fence`. + sent: u64, + /// Buffer, mapping, bytes. + buffer: Option<(ID3D12Resource, usize, u64)>, + /// With [`copy_fetch`]: a queue of the card's copy engine, and a list + /// for it; the fetch goes there, not behind the flights in the air. + copy: Option<(ID3D12CommandQueue, Prelude)>, +} + +/// What [`Host::relay_card_back`] is given beside the plans: the sends of +/// title bytes known done ahead of the landed flights (`Flight::sends`, +/// for the fetch on the card's copy engine, [`copy_fetch`]) and the +/// copies whose pieces wait unless something reads them +/// ([`read_back_only`]). +#[derive(Clone, Copy, Default)] +struct RelayBack<'a> { + sends_done: u64, + skip: &'a [usize], +} + +/// What [`Host::relay_fetch_merge`] needs of the landing it fetches for. +#[derive(Clone, Copy)] +struct FetchAsk<'a> { + /// See [`RelayBack`]. + sends_done: u64, + /// The last send of the landed plans' flights. + sent_as: Option<u64>, + /// The copy queue the fetch goes to (`crate::queue2`), if any. + lane: Option<&'static crate::queue2::Second>, + /// The value signalled on the host's fence behind the last flight. + behind: u64, + /// Whether pieces fetched beside flights are noted ([`BESIDE`]). + beside: bool, + /// Every piece fetched now: (copy, piece number). + numbers: &'a [(usize, u32)], + /// The number of the last flight being landed. + landed: u64, +} + +/// Whether neighbouring pieces of one copy fetched by the relay go down in +/// one copy call (`VICTORY_RELAY_COPY_RUNS=0`: a call a piece, as before). +/// After Kelvaroq 0032 by stellarr-studio (opt-in there). Each piece keeps +/// its own place in the landing buffer and its own merge; only the card's +/// copy calls are joined, where a piece ends where the next begins in both +/// the copy and the landing buffer. +fn relay_copy_runs_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY_RUNS").is_none_or(|v| v != "0")) +} + +/// The relay's fetch copies of `pieces` (copy, first byte, end, place in +/// the landing buffer), neighbours joined ([`relay_copy_runs_on`]). +fn relay_copy_runs<T>(pieces: &[(std::sync::Arc<T>, usize, usize, u64)]) -> impl Iterator<Item = (&T, usize, usize, u64)> { + relay_copy_runs_with(pieces, relay_copy_runs_on()) +} + +fn relay_copy_runs_with<T>(pieces: &[(std::sync::Arc<T>, usize, usize, u64)], join: bool) -> impl Iterator<Item = (&T, usize, usize, u64)> { + pieces + .chunk_by(move |a, b| join && std::sync::Arc::ptr_eq(&a.0, &b.0) && a.2 == b.1 && a.3.checked_add((a.2 - a.1) as u64) == Some(b.3)) + .map(|run| { + let (shadow, lo, _, at) = &run[0]; + (shadow.as_ref(), *lo, run[run.len() - 1].2, *at) + }) +} + +/// Whether the relay fetches what shaders wrote to copies in the card's +/// memory on a queue of the card's copy engine (`VICTORY_COPY_FETCH=0`: on +/// the queue the flights run on, as before). There the fetch ran behind +/// every flight sent since the landed ones, and the thread that copies +/// back waited for those to run: 196 ms a frame for 6 fetches in the +/// 2026-11-24 report. On its own queue it runs at once, beside them. +/// +/// What it may bring then: bytes of a later flight's shaders, even half +/// written; that flight's compare flags the pieces it changed and its +/// landing fetches them again. Which sends of title bytes it saw is known +/// only up to those ahead of the landed flights (`Flight::sends`), so +/// later ones are left out of the merge as not received +/// (`Shadow::card_merge_relay`). +fn copy_fetch() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_COPY_FETCH").is_none_or(|v| v != "0")) +} + +/// The thread that lands flights ([`relay`]): as soon as the card has run +/// the first flights of the line it takes them, with what follows them, +/// and does what they left to do ([`Host::relay_land`]); else it waits for +/// the card, or for a flight. It takes neither the submission lock nor +/// anything a caller of [`Host::settle`] may hold: resetting the landed +/// lists and looking at what queues hold are left to [`late_helper`]. +fn relay_worker() { + let Some(host) = host() else { + return; + }; + // Try 6.0: above normal priority, as the wide threads + // (`VICTORY_WIDE_PRIORITY=0`: normal): the title waits for what this + // thread lands ("copying back", 117-286 ms a world frame in the + // 2026-11-26 report). + if std::env::var_os("VICTORY_WIDE_PRIORITY").is_none_or(|v| v != "0") { + crate::shadow::raise_this_thread(); + } + crate::framelog::keep_on_fast_cores("victory-relay"); + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)")); + }; + let mut fetch: Option<RelayFetch> = None; + crate::lazy::landing_thread(); + loop { + let next = { + let mut line = line(); + loop { + if line.line.is_empty() { + line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner()); + continue; + } + let fences: Vec<Option<u64>> = line + .line + .iter() + .map(|l| match l { + Late::Run(flight) => Some(flight.fence), + _ => None, + }) + .collect(); + // SAFETY: a plain query. + let completed = unsafe { host.fence.GetCompletedValue() }; + let n = landable(&fences, completed); + if n == 0 { + // The first thing is a flight the card has not run. + break Err(fences[0].unwrap_or(0)); + } + line.settling = true; + let items: Vec<Late> = line.line.drain(..n).collect(); + line.in_hand = items + .iter() + .filter_map(|l| match l { + Late::Write(at, what, bytes) => Some((*at, *what, *bytes)), + _ => None, + }) + .collect(); + break Ok(items); + } + }; + match next { + Ok(items) => host.relay_land(items, &mut fetch), + Err(target) => { + let waiting = std::time::Instant::now(); + // SAFETY: the host's fence and this thread's event. + let waited = unsafe { + host.fence.SetEventOnCompletion(target, event).map(|()| { + WaitForSingleObject(event, INFINITE); + }) + }; + if waited.is_err() { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + } + } + } +} + +/// [`relay`]: what shaders wrote to the declared ranges `back` of copies +/// in the PC's memory goes into title memory. As [`hand_back`], each byte +/// once, the pieces that differ found on several threads; but the merge is +/// `Shadow::relay_merge`, which does not write the copy, and the ranges +/// are not done with here (each flight's are, afterwards). +/// +/// Copies in `skip` (by address, [`read_back_only_pc`]) are left alone: +/// returned, for a look again if something touches them before the batch +/// is let go. +fn relay_hand_back(back: &[Declared], skip: &[usize]) -> Vec<Declared> { + let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new(); + let mut left = Vec::new(); + for (shadow, declared) in back { + if shadow.carded() { + continue; + } + if skip.contains(&(std::sync::Arc::as_ptr(shadow) as usize)) { + READ_ONLY_STATS[0].fetch_add(declared.len() as u64, Ordering::Relaxed); + READ_ONLY_STATS[1].fetch_add(declared.iter().map(|&(a, e)| (e - a) as u64).sum::<u64>(), Ordering::Relaxed); + left.push((shadow.clone(), declared.clone())); + continue; + } + let mut spans: Vec<(usize, usize)> = Vec::new(); + join_ranges(&mut spans, declared.iter().copied()); + for &(from, to) in &spans { + shadow.relay_compared(from, to - from); + } + work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to))); + } + if work.is_empty() { + return left; + } + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + // Looked through without a lock: a piece that changes meanwhile (a + // later flight writing, the title's bytes going in) is found now or by + // that flight's landing, and the merge looks again under the lock. + let found = crate::shadow::find_all(&work); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); + let (mut now, mut title) = (Vec::new(), Vec::new()); + for ((shadow, from, to), found) in work.iter().zip(found) { + let mut written = 0; + for (at, n) in found { + written += shadow.relay_merge(at, n, &mut now, &mut title); + } + copy_back(1, written as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(*from, to - from, written); + let _ = (from, to); + } + left +} + +/// For the frame-rate line, with [`late`]: what the line of flights did +/// per frame since the last one. +fn late_line(frames: f64) { + if !late() { + return; + } + #[cfg(feature = "diagnostics")] + fill_check::line(); + fill_ahead::line(frames); + let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ + settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \ + title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \ + a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \ + bottom-of-pipe writes (VICTORY_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \ + {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights", + s[0], + s[1], + if s[1] > 0.0 { s[11] / s[1] } else { 0.0 }, + s[12] / 1000.0, + s[WHY_SYNC], + s[WHY_CARD_DONE], + s[WHY_VALUE], + s[WHY_STALE], + s[WHY_READ], + s[15], + s[16], + s[17], + s[WHY_RUN], + late_most(), + s[WHY_MOST], + s[WHY_WRITES], + s[WHY_FENCE], + s[13], + s[14], + ); + { + let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect(); + tracing::info!( + "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \ + the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \ + title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}", + w[WHY_SYNC], + w[WHY_CARD_DONE], + w[WHY_VALUE], + w[WHY_STALE], + w[WHY_READ], + w[WHY_RUN], + w[WHY_MOST], + w[WHY_WRITES], + w[WHY_FENCE], + ); + } + if relay() { + let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let [again, noted] = [0, 1].map(|i| BESIDE_STATS[i].swap(0, Ordering::Relaxed) as f64 / frames); + tracing::info!( + "the relay per frame (VICTORY_RELAY={}): {:.1} flights landed in {:.1} landings by the thread that copies back, \ + beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \ + fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \ + \"settles\" above are waits of other threads for it); pieces fetched on the copy queue beside later \ + submissions: {noted:.1}, pieces those fetched again at their own landing whatever the compare said: {again:.1} \ + (VICTORY_QUEUE2_REFETCH)", + if relay_exact() { 2 } else { 1 }, + r[1], + r[0], + r[2] / 1000.0, + r[3] / 1000.0, + r[4] / 1000.0, + ); + if crate::lazy::on() { + tracing::info!("{}", crate::lazy::line(frames)); + } + if read_back_only() { + let s: Vec<u64> = READ_ONLY_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed)).collect(); + tracing::info!( + "copy-back of only what is read (VICTORY_READ_BACK_ONLY=0: all): {:.1} pieces ({:.1} MB) left on the card a frame, {:.1} fetched after all as something read them", + s[0] as f64 / frames, + s[1] as f64 / frames / 1048576.0, + s[2] as f64 / frames + ); + } + tracing::info!( + "barriers and full waits left out so far (VICTORY_TRIM_BARRIERS=0: none): {}; draws with a stand-in pipeline so far: {} of the same shape, {} with other depth writes (VICTORY_STAND_IN_LOOSE=0: none), {} of the same shape at once, before any wait (VICTORY_STAND_IN_FIRST=0: none)", + crate::list::TRIMMED_BARRIERS.load(Ordering::Relaxed), + crate::pipeline::stand_ins().saturating_sub(crate::pipeline::loose_stand_ins()), + crate::pipeline::loose_stand_ins(), + crate::pipeline::stand_ins_first() + ); + tracing::info!( + "fills of upload memory that took results one flight late, not waiting (VICTORY_LATE_RESULTS=0: wait): {:.1} a frame", + LATE_RESULTS.swap(0, Ordering::Relaxed) as f64 / frames + ); + let c: Vec<f64> = LATE_COPIES.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "title buffer copies on the CPU over flights' writes, per frame (VICTORY_LATE_COPIES={}): {:.1} reading them took the results one flight late, {:.1} writing there let go; settled for {:.1} reading, {:.1} writing (VICTORY_LATE_COPIES=2 lets those go too)", + late_copies(), + c[0], + c[1], + c[2], + c[3] + ); + if inflight_fetch() { + let i: Vec<f64> = INFLIGHT_STATS.iter().map(|i| i.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "card copies' pieces fetched inside their flights per frame (VICTORY_CARD_FETCH_INFLIGHT=1): {:.1} pieces \ + ({:.2} MB) merged with no fetch of their own; {:.1} landings fetched the old way (the wait above), {:.1} of \ + them because a flight's pieces overflowed the slots", + i[0], + i[1] / (1 << 20) as f64, + i[3], + i[2], + ); + } + } + if late_exact() { + let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames); + let gave_up = crate::shadow::merge_gave_up(); + tracing::info!( + "title bytes put in under flights' shader writes per frame (VICTORY_LATE_WAIT=2): {pages:.0} pages looked at, \ + {runs:.0} changed runs, {:.2} MB; in these frames the merge gave up (the flights are then settled whole): {} times \ + because the copy's memory is not watched, {} because the write tracking had no answer, {} for more changed runs than \ + VICTORY_MERGE_RUNS leaves, {} for a copy in PC memory without its snapshot", + bytes / (1 << 20) as f64, + gave_up[0], + gave_up[1], + gave_up[2], + gave_up[3] + ); + } + { + let found = [0, 1].map(|i| crate::shadow::LOOKUPS[i].swap(0, Ordering::Relaxed) as f64 / frames); + tracing::info!( + "asks for a buffer's host copy per frame: {:.0} answered from the asking thread's memory of them, {:.0} from the tables (VICTORY_LOOKUP_CACHE)", + found[0], + found[1] + ); + } + { + let parts = [0, 1, 2, 3, 4, 5].map(|i| PREP_PARTS[i].swap(0, Ordering::Relaxed) as f64 / 1e3 / frames); + tracing::info!( + "a submission's preparing by part, ms per frame: the write-watch asking and the look for title bytes under flights \ + (settles for them included) {:.1}; the lists' steps (title copies, fills, preludes; refreshes are only noted) {:.1}; \ + the refreshes (the flush) {:.1}; snapshots and the wait for card results {:.1}; the card copies' send and hash lists \ + (card_before) {:.1}; handing the lists to the card and signalling {:.1}", + parts[0], + parts[1], + parts[2], + parts[3], + parts[4], + parts[5] + ); + let [budget, snapshot, runs_out, unjournaled] = crate::shadow::merge_settle_stats().map(|n| n as f64 / frames); + tracing::info!( + "settled for it per frame because: the compare with no write journal was over its budget {budget:.1} \ + (VICTORY_MERGE_UNWATCHED_MB), no snapshot {snapshot:.1}, too many changed runs {runs_out:.1}; \ + {unjournaled:.0} pages compared with no journal" + ); + } +} + +#[cfg(test)] +mod late_tests { + use super::{continues, join_ranges, touches}; + + /// Copies join only when both ends continue and the whole does not + /// overlap itself. + #[test] + fn copies_join_only_end_to_end_and_apart() { + // (destination, source, bytes) + assert!(continues((1000, 5000, 16), (1016, 5016, 32))); + assert!(continues((5000, 1000, 16), (5016, 1016, 32))); + // A gap, or only one side continues. + assert!(!continues((1000, 5000, 16), (1020, 5016, 32))); + assert!(!continues((1000, 5000, 16), (1016, 5020, 32))); + assert!(!continues((1000, 5000, 16), (1000, 5000, 16))); + // Together they would overlap: the second reads what the first wrote. + assert!(!continues((1000, 1016, 16), (1016, 1032, 16))); + assert!(!continues((1016, 1000, 16), (1032, 1016, 16))); + // They touch without overlapping. + assert!(continues((1000, 1032, 16), (1016, 1048, 16))); + assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8))); + } + + /// Ranges are found by what they hold, not by where they start, and a + /// range that only touches another's end does not touch it. + #[test] + fn ranges_touch_where_they_overlap() { + let mut ranges = Vec::new(); + join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]); + assert_eq!(ranges, [(10, 25), (40, 60)]); + join_ranges(&mut ranges, [(25, 40)]); + assert_eq!(ranges, [(10, 60)]); + let ranges = [(10usize, 25usize), (40, 60), (100, 101)]; + for (from, to, hit) in [ + (0, 10, false), + (0, 11, true), + (24, 25, true), + (25, 40, false), + (25, 41, true), + (59, 200, true), + (60, 100, false), + (100, 101, true), + (101, 500, false), + (30, 30, false), + (50, 50, false), + ] { + assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}"); + } + assert!(!touches(&[], 0, usize::MAX)); + } +} + +/// Whether a title buffer copy that continues the one recorded before it +/// in its list becomes one step with it (`VICTORY_JOIN_COPIES=1`; off by +/// default). +/// +/// Each copy is done at submission through the kernel, which reports a +/// page that is not there instead of faulting (`copy_mapped`), tells the +/// write watch and the guards, and ends the refreshes gathered so far: a +/// call into the kernel for some 480 bytes, 14,042 times a frame in run 86 +/// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them +/// continue the one before is counted either way and said on its own line +/// with the frame rate; the switch is worth that many kernel calls. +/// +/// Joined, the same bytes move: [`continues`] joins only copies whose +/// ranges, taken together, do not overlap, and nothing is recorded between +/// two steps that follow each other. What differs: a page that is not +/// mapped now fails the joined copy as a whole (it then goes page by page, +/// zeros for what cannot be read, as a single copy does), where before +/// only the copy that held it did. +fn join_copies() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_JOIN_COPIES").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line: title buffer copies recorded, and those +/// that continue the one before ([`join_copies`]). +static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether the title's own buffer copies run on the host GPU when both sides +/// have a host copy (`VICTORY_GPU_COPIES`, on unless `0`; pablogonz12/ +/// Scarlight #86, Try 4.7): one `CopyBufferRegion` in the list instead of a +/// read and a write of title memory at submission time, with the destination +/// copied back like a shader write (`crate::list::record_gpu_copy`). Off, +/// every copy is a CPU copy, as before. +/// +/// With flights in the air ([`late`]) a CPU copy that touched memory a +/// flight's shaders may write waited for all of them to land first: two +/// such settles a frame, 157 ms of a 485 ms frame, in the 2026-11-25 report. +pub(crate) fn gpu_copies() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_GPU_COPIES").is_none_or(|v| v != "0"); + tracing::info!(on, "title buffer copies on the card through the buffers' host copies (VICTORY_GPU_COPIES)"); + on + }) +} + +/// Since the last frame-rate line: title buffer copies that ran on the card +/// ([`gpu_copies`]), and their bytes. +static GPU_COPIES: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// A title buffer copy of `len` bytes was recorded on the card. +pub(crate) fn gpu_copied(len: usize) { + GPU_COPIES[0].fetch_add(1, Ordering::Relaxed); + GPU_COPIES[1].fetch_add(len as u64, Ordering::Relaxed); +} + +/// Whether the copy `next` (destination, source, bytes) goes on exactly +/// where `last` ended, source and destination both, and the two as one do +/// not overlap (source over destination): then one copy of both moves the +/// bytes the two would move in turn. +fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool { + let ((d, s, n), (dst, src, len)) = (last, next); + let Some(all) = n.checked_add(len) else { + return false; + }; + d.checked_add(n) == Some(dst) + && s.checked_add(n) == Some(src) + && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d)) +} + +/// The ranges the shaders of `runs` may write, per host copy, as declared. +/// One list's lock at a time: a submission may name a list twice. +fn declared_writes(runs: &[&HostList]) -> Vec<Declared> { + let mut back: Vec<Declared> = Vec::new(); + let indexed = step_index(); + if indexed { + let given = given_to_shaders(runs, false); + back = declared_by_index(given.iter().map(|(shadow, range)| (shadow, *range))); + } + for list in if indexed { &[][..] } else { runs } { + for step in &list.deferred().copies { + if let Step::GpuWrite(shadow, address, len) = step { + let range = (*address, *address + *len); + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, ranges)) => { + if !ranges.contains(&range) { + ranges.push(range); + } + } + None => back.push((shadow.clone(), vec![range])), + } + } + } + } + back +} + +/// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log +/// lines that say what the title's CPU was given while it decided whether +/// the camera is in a room. The values of the small read-backs +/// ([`read_backs`]), the frame's main pass by scissor rectangle with its +/// culling dispatches (`draw.rs`, `walls_census`), the shader-written +/// buffers merged into title memory (`shadow.rs`, `walls_merged`), host +/// copies found stale after their refresh (`shadow.rs`; only with +/// `VICTORY_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the +/// runtime, the read requests that fail (with 2: every request). +pub(crate) fn walls_trace() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2")) +} + +/// After `list` has run: the texels its read-backs copied into host +/// buffers of ours go to the title's memory (`HostList::defer_read_back`). +/// +/// A submission that is waited for did this itself. One sent ahead +/// ([`late`]) did not, at any stage: the flights' lists were settled +/// without it, so the title read a buffer nobody wrote, as before read-backs +/// were made (the exposure metering's two small float targets, every frame). +fn read_backs(list: &HostList) { + // Textures shaders wrote that the title reads on the CPU + // ([`crate::texback`]). + for back in &list.deferred().texture_backs { + crate::texback::land(back); + } + for (buffer, at, [row, rows, pitch]) in &list.deferred().backs { + let mut data = std::ptr::null_mut(); + // SAFETY: a read-back buffer of ours, written by the list that has + // run; the title's destination holds every row (checked when the + // copy was recorded). + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() { + let from = data.cast::<u8>().cast_const(); + for line in 0..*rows { + std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row); + } + // The walls trace: what the title is handed (one row of at + // most 24 values: its 5x1 and 1x1 float targets). + if walls_trace() && *rows == 1 && *row <= 96 { + let mut values = [0f32; 24]; + std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3); + tracing::info!( + frame = crate::frame::current(), + to = format_args!("{:#x}", *at), + bytes = *row, + values = ?&values[..*row / 4], + "walls trace: a read-back lands in title memory" + ); + } + buffer.Unmap(0, None); + } + } + } +} + +/// After the card ran what declared `back`: what shaders wrote there goes +/// into title memory, and the ranges are done with. +fn hand_back(back: &[Declared]) { + if crate::shadow::wide_back() { + // Every range first (the pieces that differ, found on several + // threads), then the merges, in order, as below. + let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new(); + for (shadow, declared) in back { + if shadow.carded() { + continue; + } + let mut sorted = declared.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to))); + } + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + let found = crate::shadow::find_all(&work); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); + for ((shadow, from, to), found) in work.iter().zip(found) { + let written = shadow.copy_back_with(*from, to - from, Some(found)); + copy_back(1, written as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(*from, to - from, written); + } + for (shadow, declared) in back { + shadow.copy_back_done(declared); + } + return; + } + for (shadow, declared) in back { + if shadow.carded() { + // Done before (`Host::card_back`). + shadow.copy_back_done(declared); + continue; + } + // Each byte compared once: the world declares dozens of views + // of its 174 MB heap that overlap almost entirely, and comparing + // every one whole was gigabytes a frame (0.3-0.5 s) for the few + // MB shaders wrote. Only ranges that overlap or touch are + // joined: what lies between two was not given to shaders (the + // snapshot does not hold it). + let mut sorted = declared.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + for (from, to) in spans { + let written = shadow.copy_back(from, to - from); + copy_back(1, written as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(from, to - from, written); + } + shadow.copy_back_done(declared); + } +} + +impl Host { + /// Whether the host runs mesh shaders at shader model 6.6 (translated + /// mesh shaders need both); logged once. + pub(crate) fn mesh_shaders(&self) -> bool { + static MESH: OnceLock<bool> = OnceLock::new(); + *MESH.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + // SAFETY: each query writes its own structure of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + && self + .device + .CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut model).cast(), + size_of_val(&model) as u32, + ) + .is_ok() + }; + let mesh = ok + && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED + && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; + tracing::info!(mesh, "host mesh shader support"); + mesh + }) + } + + /// A new list, open for recording. + pub(crate) fn new_list(&self) -> windows::core::Result<HostList> { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + let before = private_bytes(); + let list = self.make_list(); + LISTS[0].fetch_add(1, Ordering::Relaxed); + // (May shrink while a list is made, on another thread's account: + // added as it is, the sum is what counts.) + #[cfg(feature = "diagnostics")] + LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::HostLists, 1); + add(C::HostListNs, started.elapsed().as_nanos() as u64); + } + list + } + + /// An allocator and a closed list for a prelude. + fn make_prelude(&self) -> Option<Prelude> { + // SAFETY: plain object creation. + let made: windows::core::Result<Prelude> = unsafe { + (|| { + let allocator: ID3D12CommandAllocator = + self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = + self.device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + Ok((allocator, list)) + })() + }; + LISTS[1].fetch_add(1, Ordering::Relaxed); + match made { + Ok(prelude) => Some(prelude), + Err(e) => { + tracing::warn!(error = %e, "no host list for a prelude"); + None + } + } + } + + fn make_list(&self) -> windows::core::Result<HostList> { + // SAFETY: plain object creation. + unsafe { + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = self.device.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + &allocator, + None, + )?; + let prelude = OnceLock::new(); + if !lazy_prelude() { + let _ = prelude.set(self.make_prelude()); + } + Ok(HostList { + allocator, + list, + deferred: Mutex::default(), + scratch: Mutex::default(), + states: Mutex::default(), + twins: Mutex::default(), + prelude, + pipelines: Mutex::default(), + budget: OnceLock::new(), + card_budget: OnceLock::new(), + indirect_args: Mutex::default(), + window_check: OnceLock::new(), + clamp_window: Mutex::new(None), + open_queries: Mutex::new(Vec::new()), + _alive: Counted::new(), + meter: AtomicU32::new(u32::MAX), + pipeline_meter: AtomicU32::new(u32::MAX), + gather: Mutex::default(), + #[cfg(feature = "diagnostics")] + notes: Mutex::default(), + #[cfg(feature = "diagnostics")] + stamps: OnceLock::new(), + #[cfg(feature = "diagnostics")] + shot_block: Mutex::default(), + #[cfg(feature = "diagnostics")] + shot_mark: Mutex::default(), + }) + } + } + + /// The card's clock ([`CARD_CLOCK_US`]), made at the first send. + fn card_clock(&self) -> Option<&'static CardClock> { + static CLOCK: OnceLock<Option<CardClock>> = OnceLock::new(); + static WATCH: std::sync::Once = std::sync::Once::new(); + let clock = CLOCK + .get_or_init(|| { + // SAFETY: a plain fence on our device. + let fence = unsafe { self.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?; + Some(CardClock { + fence, + state: Mutex::new((0, None)), + sent: std::sync::Condvar::new(), + }) + }) + .as_ref()?; + WATCH.call_once(|| { + if let Err(e) = std::thread::Builder::new().name("victory-card-clock".into()).spawn(move || card_clock_watch(clock)) { + tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0"); + } + }); + Some(clock) + } + + /// Lists of ours just went to the queue: the clock's signal goes + /// behind them, and an idle stretch of the card, if one was under way, + /// ends here ([`CARD_CLOCK_US`]). + fn card_sent(&self) { + awake::sent(&self.device); + let Some(clock) = self.card_clock() else { + return; + }; + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + state.0 += 1; + // SAFETY: our queue and the clock's fence. + let _ = unsafe { self.queue.Signal(&clock.fence, state.0) }; + if let Some((since, worked_then)) = state.1.take() { + card_clock_us(0, since.elapsed().as_micros() as u64); + card_clock_us(1, worked().saturating_sub(worked_then)); + } + drop(state); + clock.sent.notify_one(); + } + + /// Whether the host has what copies in the card's memory need (three + /// lists and the compare); made at the first ask. A copy goes to the + /// card's memory only if it has. + pub(crate) fn card_ready(&self) -> bool { + static READY: OnceLock<bool> = OnceLock::new(); + *READY.get_or_init(|| match self.make_card_work() { + Ok(work) => { + *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work); + true + } + Err(e) => { + tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made"); + false + } + }) + } + + fn make_card_work(&self) -> windows::core::Result<CardWork> { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; the out + // pointer is ours. + unsafe { + let source = card_compare_source(); + D3DCompile( + source.as_ptr().cast(), + source.len(), + windows::core::s!("card compare"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + } + let code = code.ok_or_else(windows::core::Error::empty)?; + let list = || self.make_prelude().ok_or_else(windows::core::Error::empty); + // A megabyte of results: 262,144 pieces, 16 GB of declared ranges + // in one submission. + const RESULTS: u64 = 1 << 20; + let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?; + name(&differs, || "card compare results".into()); + // SAFETY: the blob's own bytes; the root signature is inside the + // shader. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + // With `alt`: the wide form's pipeline beside it (`pso` is then the thread-a-piece form, as + // `card_compare_source` gives it without `=1`). None if it does not build: every submission keeps `pso`. + let pso_wide = (card_hash_mode() == 2).then(|| self.make_card_compare_wide(&root)).flatten(); + Ok(CardWork { + sync: vec![list()?], + check: vec![list()?], + fetch: list()?, + root, + pso, + pso_wide, + differs: (differs, data as usize, RESULTS), + fetched: None, + taken: 0, + out: 0, + inflight: if inflight_fetch() { self.make_card_inflight(RESULTS) } else { None }, + }) + } + } + + /// [`CARD_COMPARE_WIDE`]'s pipeline with the compare's root signature `root` (the two shaders declare the same + /// one), for `VICTORY_CARD_HASH_WIDE=alt`; `None`, said in the log, if it cannot be made. + fn make_card_compare_wide(&self, root: &ID3D12RootSignature) -> Option<ID3D12PipelineState> { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let made = (|| -> windows::core::Result<ID3D12PipelineState> { + let mut code: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; the out pointer is ours. + unsafe { + D3DCompile( + CARD_COMPARE_WIDE.as_ptr().cast(), + CARD_COMPARE_WIDE.len(), + windows::core::s!("card compare wide"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + } + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes; a root signature the shader declares as well. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + }) + } + })(); + match made { + Ok(pso) => Some(pso), + Err(e) => { + tracing::warn!(error = %e, "VICTORY_CARD_HASH_WIDE=alt: the wide compare could not be made; a thread a piece throughout"); + None + } + } + } + + /// [`CardInflight`] for `results` bytes of the compare's results; `None` + /// (and the old fetch) if the shader or the memory cannot be had. + fn make_card_inflight(&self, results: u64) -> Option<CardInflight> { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let made = (|| -> windows::core::Result<CardInflight> { + let mut code: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; the out + // pointer is ours. + unsafe { + D3DCompile( + CARD_FETCH.as_ptr().cast(), + CARD_FETCH.len(), + windows::core::s!("card fetch in flight"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + } + let code = code.ok_or_else(windows::core::Error::empty)?; + let slots = inflight_slots(inflight_fetch_bytes()); + let (table, table_data) = self.shared_buffer(4 + results).ok_or_else(windows::core::Error::empty)?; + name(&table, || "card fetch in flight: tickets".into()); + let fetched_bytes = u64::from(slots) * INFLIGHT_SLOT; + let (fetched, fetched_data) = self.shared_buffer(fetched_bytes).ok_or_else(windows::core::Error::empty)?; + name(&fetched, || "card fetch in flight: pieces".into()); + // SAFETY: the mapping holds the counter; nothing of ours ran + // on the card with it yet. + unsafe { table_data.cast::<u32>().write_volatile(0) }; + // SAFETY: the blob's own bytes; the root signature is inside + // the shader. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(CardInflight { + root, + pso, + table: (table, table_data as usize, 4 + results), + fetched: (fetched, fetched_data as usize, slots), + landed: 0, + brought: Vec::new(), + }) + } + })(); + match made { + Ok(inflight) => { + tracing::info!( + slots = inflight.fetched.2, + "card copies' flagged pieces come down inside their flights (VICTORY_CARD_FETCH_INFLIGHT=1)" + ); + Some(inflight) + } + Err(e) => { + tracing::warn!(error = %e, "no fetch inside flights (VICTORY_CARD_FETCH_INFLIGHT=1): pieces are fetched the old way"); + None + } + } + } + + /// Before a submission's lists run, for copies in the card's memory + /// ([`crate::shadow::cards`]): what changed on their CPU side since + /// the last submission goes to their card side (a list of ours, run + /// now; the submission's lists follow it on the queue), and the ranges + /// this submission's shaders may write get a compare to run after its + /// lists. `None` if there is nothing to do. + /// + /// `flown`: the submission is sent ahead with [`relay`]. Its compare + /// then stores the hashes it makes (see [`flagged_pieces`] and + /// `relay`). + /// + /// `sent`: the last value signalled on the host's fence; the caller + /// signals the next one behind this submission's lists. + /// + /// With `VICTORY_QUEUE2` bit 2 (`crate::queue2`; off by default) the + /// changed bytes cross from the PC's memory to the card's on a copy + /// queue, on the card's copy engine, while the direct queue still runs + /// what was sent before: they go into a landing buffer in the card's + /// memory that nothing else uses. The direct queue is told to wait for + /// that copy and then moves the bytes from the landing buffer into the + /// copies, inside the card's memory, in the same place of its order as + /// before. So the copies change exactly when they did on one queue; what + /// leaves the direct queue is the crossing from the PC's memory. + fn card_before(&self, runs: &[&HostList], flown: bool, sent: u64) -> Option<CardPlan> { + use std::sync::Arc; + if !crate::shadow::cards() { + return None; + } + // The ranges this submission's shaders may write, per copy. + let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new(); + let indexed = step_index(); + if indexed { + let given = given_to_shaders(runs, true); + declared = declared_by_index(given.iter().map(|(shadow, range)| (shadow, *range))); + } + for list in if indexed { &[][..] } else { runs } { + for step in &list.deferred().copies { + if let Step::GpuWrite(shadow, address, len) = step + && shadow.carded() + { + let range = (*address, *address + *len); + match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) { + Some((_, ranges)) => { + if !ranges.contains(&range) { + ranges.push(range); + } + } + None => declared.push((shadow.clone(), vec![range])), + } + } + } + } + // With the relay: the order of the queue is held from here until + // what is taken is on the queue, and the taking is numbered. + let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + let sent_as = match order.as_mut() { + Some(order) => { + **order += 1; + **order + } + None => 0, + }; + let mut dirty = crate::shadow::card_dirty(sent_as); + // With fetches on a copy queue (`crate::queue2`, bit 1 of + // `VICTORY_QUEUE2`): the send's number is signalled on the direct + // queue behind the send, so that a fetch knows which sends the card + // has finished (`Second::order_done`). + let numbered = || { + if sent_as != 0 + && let Some(second) = crate::queue2::second().filter(|s| s.fetches()) + { + second.sent_up(&self.queue, sent_as); + } + }; + if declared.is_empty() && dirty.is_empty() { + numbered(); + return None; + } + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let work = work.as_mut()?; + // The hash form of this submission's passes, one for all of them (`card_hash_wide_now`). + let wide_now = card_hash_wide_now(); + let (compare_pso, wide) = { + let (pso, wide) = work.compare_for(wide_now); + (pso.clone(), wide) + }; + // A copy whose shader writes are declared for the first time gets + // its bytes from before, whole. + let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new(); + for (shadow, _) in &declared { + if shadow.card_make_before(|size| { + let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?; + name(&before, || "title buffer on the card, hashes of its pieces".into()); + Some(before) + }) { + whole.push(shadow.clone()); + if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) { + dirty.push((shadow.clone(), Vec::new())); + } + } + } + let mut used: Vec<(bool, Prelude)> = Vec::new(); + // The changed bytes through the copy queue (`VICTORY_QUEUE2` bit + // 2): the landing buffer they are in, in the order of `dirty`'s + // ranges, once the direct queue has waited. `None`: straight from + // the PC's memory on the direct queue, as before. + let mut landed: Option<ID3D12Resource> = None; + if let Some(second) = crate::queue2::second().filter(|s| s.uploads()) { + let bytes: u64 = dirty + .iter() + .filter(|(shadow, _)| shadow.carded()) + .flat_map(|(_, ranges)| ranges.iter().map(|&(a, b)| (b - a) as u64)) + .sum(); + // SAFETY: a plain query. + let completed = unsafe { self.fence.GetCompletedValue() }; + // Held until the card has passed this submission's signal: the + // direct queue's copy out of it runs ahead of that. + if bytes > 0 + && let Some(landing) = second.landing(bytes, completed, sent + 1) + { + // SAFETY: an open copy list of the lane's; live buffers, + // and the ranges lie in them; the host's queue. + let sent_up = unsafe { + (|| -> windows::core::Result<()> { + let copy = second.up.list()?; + let mut at = 0u64; + for (shadow, ranges) in &dirty { + let Some((staging, _, _)) = shadow.card_sides() else { + continue; + }; + for &(a, b) in ranges { + copy.1.CopyBufferRegion(&landing, at, staging, a as u64, (b - a) as u64); + at += (b - a) as u64; + } + } + let job = second.up.send(copy, &[], bytes)?; + // Nothing sent to the direct queue from here on + // runs before the bytes have landed. + second.hold(&self.queue, job) + })() + }; + if let Err(e) = sent_up { + fail(format_args!( + "host copies in the card's memory could not be brought up to date through the copy queue ({e}, VICTORY_QUEUE2)" + )); + } + landed = Some(landing); + } + } + if !dirty.is_empty() { + let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else { + fail(format_args!("no host list to bring host copies in the card's memory up to date")); + }; + let (allocator, list) = &sync; + // SAFETY: the list's last run finished (it ran ahead of a + // submission that was waited for, and came back after that); + // live buffers, and the ranges lie in them. + let recorded = unsafe { + (|| -> windows::core::Result<()> { + allocator.Reset()?; + list.Reset(allocator, None)?; + let timed = crate::cardmeter::begin(list, crate::cardmeter::Kind::Sync); + #[cfg(feature = "diagnostics")] + let shot_span = crate::shot::span_begin(list); + // Where the next range lies in the landing buffer. + let mut at = 0u64; + // In three steps over all the copies ([`sync_batched`]): + // every changed range copied up, then every state + // change in one call, then every hash pass. + struct Synced<'a> { + shadow: &'a Arc<crate::shadow::Shadow>, + ranges: &'a [(usize, usize)], + before: Option<ID3D12Resource>, + size: u64, + } + let batched = sync_batched(); + let mut synced: Vec<Synced> = Vec::with_capacity(dirty.len()); + // No twin (it cost the card the copy's size again, 399 MB + // in run 75): `before` holds a 128-bit hash of each 64 KiB + // piece. The pieces just sent up are hashed again, all of + // them the first time; the compare after the lists hashes + // the declared pieces and flags those whose hash is another. + let hashes = |list: &ID3D12GraphicsCommandList, group: &[Synced]| { + // (a copy promoted the buffer to a copy destination) + let moves: Vec<_> = group + .iter() + .filter(|w| w.before.is_some() && !w.ranges.is_empty()) + .map(|w| transition(&w.shadow.buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)) + .collect(); + if !moves.is_empty() { + list.ResourceBarrier(&moves); + } + let mut bound = false; + for w in group { + let Some(before) = &w.before else { + continue; + }; + if !bound { + bound = true; + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&compare_pso); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + } + list.SetComputeRootShaderResourceView(1, w.shadow.buffer.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); + let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, w.shadow)) { + vec![w.shadow.card_run(0, usize::MAX)] + } else { + w.ranges.iter().map(|&(a, b)| w.shadow.card_run(a, b)).collect() + }; + // The same pieces in fewer passes (`rehash_runs`). + let runs = if rehash_runs() { crate::shadow::joined_piece_runs(runs) } else { runs }; + CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); + CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed); + for run in runs { + let constants = [run.first, run.skew, w.shadow.card_hashed().unwrap_or(w.size) as u32, run.pieces, 0, 0]; + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.Dispatch(card_compare_groups_as(wide, run.pieces), 1, 1); + } + } + }; + for (shadow, ranges) in &dirty { + let Some((staging, before, size)) = shadow.card_sides() else { + continue; + }; + for &(a, b) in ranges { + match &landed { + Some(landing) => list.CopyBufferRegion(&shadow.buffer, a as u64, landing, at, (b - a) as u64), + None => list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64), + } + at += (b - a) as u64; + crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed); + } + crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed); + synced.push(Synced { shadow, ranges, before, size }); + if !batched { + // As before: this copy's hash passes behind its copies. + hashes(list, &synced[synced.len() - 1..]); + } + } + if batched { + hashes(list, &synced); + } + crate::cardmeter::end(list, timed); + #[cfg(feature = "diagnostics")] + crate::shot::span_end(list, shot_span, 0, || "SYNC LIST (changed bytes go up to the card's copies and are hashed)".to_string()); + list.Close()?; + self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + Ok(()) + })() + }; + if let Err(e) = recorded { + fail(format_args!("host copies in the card's memory could not be brought up to date ({e})")); + } + used.push((false, sync)); + } + numbered(); + drop(order); + let mut plan = CardPlan { + ranges: Vec::new(), + check: None, + _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(), + lists: used, + sent_as, + inflight: false, + inflight_landed: 0, + }; + // Each byte once, as the copy-back joins the declared ranges. The + // results go behind those of plans still in the air. + let mut at = work.taken; + for (shadow, ranges) in &declared { + let mut sorted = ranges.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + for (from, to) in spans { + let Some(span) = shadow.card_span(from, to) else { + continue; + }; + let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2; + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (from, to), + span, + at, + compared, + }); + if compared { + at += span.pieces; + } + } + } + work.taken = at; + if plan.ranges.iter().any(|r| r.compared) { + let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else { + fail(format_args!("no host list for the compare of host copies in the card's memory")); + }; + let (allocator, list) = ✓ + // SAFETY: the list's last run finished (its submission was + // waited for, and it came back after that); live buffers; the + // compare's own root signature. + let recorded = unsafe { + (|| -> windows::core::Result<ID3D12CommandList> { + allocator.Reset()?; + list.Reset(allocator, None)?; + let timed = crate::cardmeter::begin(list, crate::cardmeter::Kind::Check); + #[cfg(feature = "diagnostics")] + let shot_span = crate::shot::span_begin(list); + // What the submission's shaders wrote, first. + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&compare_pso); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + for r in plan.ranges.iter().filter(|r| r.compared) { + let Some((_, Some(before), size)) = r.shadow.card_sides() else { + continue; + }; + let hashed = r.shadow.card_hashed().unwrap_or(size) as u32; + let constants = [r.span.first, r.span.skew, hashed, r.span.pieces, r.at * 4, if flown { 2 } else { 1 }]; + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); + list.Dispatch(card_compare_groups_as(wide, r.span.pieces), 1, 1); + CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); + } + // The fetch inside the flight (`inflight_fetch`): behind + // every compare of the list, the pieces they flagged go + // to slots in the PC's memory. + if flown && let Some(inflight) = &work.inflight { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.SetComputeRootSignature(&inflight.root); + list.SetPipelineState(&inflight.pso); + list.SetComputeRootUnorderedAccessView(2, work.differs.0.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, inflight.table.0.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(4, inflight.fetched.0.GetGPUVirtualAddress()); + let mut every = true; + for r in plan.ranges.iter().filter(|r| r.compared) { + let Some((_, Some(_), size)) = r.shadow.card_sides() else { + every = false; + continue; + }; + let groups = r.span.pieces.clamp(1, 65535); + let constants = + [r.span.first, r.span.skew, size as u32, r.span.pieces, r.at * 4, inflight.landed, inflight.fetched.2, groups]; + list.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); + list.Dispatch(groups, 1, 1); + } + plan.inflight = every; + plan.inflight_landed = inflight.landed; + } + crate::cardmeter::end(list, timed); + #[cfg(feature = "diagnostics")] + crate::shot::span_end(list, shot_span, 0, || "CHECK LIST (the card compares the pieces shaders may have written)".to_string()); + list.Close()?; + list.cast() + })() + }; + match recorded { + Ok(list) => plan.check = Some(list), + Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")), + } + plan.lists.push((true, check)); + } + work.out += 1; + Some(plan) + } + + /// With [`relay`]: whether the compare's result area is half taken by + /// plans in the air. It starts from the beginning only when no plan is + /// out, so the caller lets the flights land first. + fn card_results_low(&self) -> bool { + CARD_WORK + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2) + } + + /// The plan's submission has run and its results were read + /// ([`Host::card_back`]): its lists are free for the next plan. Called + /// when nothing of ours is on the card, so the compare's results start + /// from the beginning again. + fn card_done(&self, plan: CardPlan) { + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + for (check, list) in plan.lists { + if check { work.check.push(list) } else { work.sync.push(list) } + } + work.out = work.out.saturating_sub(1); + // With the relay other plans may be on the card, their results + // not read yet: the area starts again only when none is out. + if !relay() || work.out == 0 { + work.taken = 0; + } + } + + /// The relay's own list, fence, event for [`Host::relay_card_back`]. + fn make_relay_fetch(&self) -> Option<RelayFetch> { + let list = self.make_prelude()?; + // SAFETY: plain object creation. + let copy = copy_fetch().then(|| unsafe { + (|| -> windows::core::Result<(ID3D12CommandQueue, Prelude)> { + // (High priority too, as the main queue: `queue_priority`.) + let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + Priority: queue_priority(), + ..Default::default() + })?; + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?; + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?; + list.Close()?; + Ok((queue, (allocator, list))) + })() + }); + let copy = match copy { + Some(Ok(copy)) => { + tracing::info!("what shaders wrote to the card's memory is fetched on the card's copy engine (VICTORY_COPY_FETCH=0: behind the flights)"); + Some(copy) + } + Some(Err(e)) => { + tracing::warn!(error = %e, "no queue on the card's copy engine: fetches go behind the flights"); + None + } + None => None, + }; + // SAFETY: plain objects of our own. + unsafe { + let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + Some(RelayFetch { + list, + fence, + event, + sent: 0, + buffer: None, + copy, + }) + } + } + + /// [`relay`], on the thread that lands flights: for the plans of the + /// flights being landed (the card has run them), the pieces their + /// compares flagged are fetched, once each, with a list and a wait of + /// this thread's own, and what shaders wrote in them goes into title + /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but: + /// no submission lock; a piece flagged under one range of a plan is + /// fetched under all ([`flagged_pieces`]); the fetch runs behind + /// whatever was sent meanwhile, so it may bring a later flight's + /// bytes, which that flight's landing then finds merged already; and + /// nothing is sent back up. + /// + /// With [`inflight_fetch`] the pieces are first looked for where the + /// flights' own compare lists put them ([`Host::relay_card_inflight`]); + /// only a landing that cannot take them from there fetches, as here. + /// `behind`: the value signalled on the host's fence behind the last of + /// the flights. With `VICTORY_QUEUE2` bit 1 (`crate::queue2`) the fetch + /// goes to a copy queue, behind that value and nothing else: it does + /// not stand behind what the submitting thread sent meanwhile (run + /// 118: 114-157 ms a frame of this thread's time). It then reads the + /// card's side while later flights may be writing it: a byte is the + /// old one or the new one, and the flight that writes it has a compare + /// and a landing of its own behind it. + /// + /// `plans` come with their flights' numbers and `landed` is the number + /// of the last flight being landed: a piece an earlier fetch on the + /// copy queue brought down beside one of these flights is fetched + /// whatever the compare says ([`BESIDE`]). + /// + /// `back`: the sends known done ahead of these flights (for the fetch + /// on the card's copy engine, [`copy_fetch`]) and the copies whose + /// pieces wait unless something reads them ([`read_back_only`]). + fn relay_card_back( + &self, + plans: &[(u64, &CardPlan)], + fetch: &mut Option<RelayFetch>, + behind: u64, + landed: u64, + back: RelayBack<'_>, + ) { + if inflight_fetch() { + let only: Vec<&CardPlan> = plans.iter().map(|p| p.1).collect(); + let taken = self.relay_card_inflight(&only); + inflight_tickets_landed(&only); + if taken { + return; + } + } + let lane = crate::queue2::second().filter(|s| s.fetches()); + // The pieces fetched beside flights that had started, as noted by + // earlier landings: looked at for these plans, renewed below. + let beside = lane.is_some() && refetch(); + let noted: std::collections::HashMap<(usize, u32), u64> = if beside { + BESIDE.lock().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default() + } else { + Default::default() + }; + let mut again = 0u64; + // Every piece fetched now: (copy, piece number). + let mut numbers: Vec<(usize, u32)> = Vec::new(); + let differs = { + let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) + }; + let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new(); + let mut total = 0u64; + // Copy-back of only what is read: the pieces of copies nothing has + // read lately wait here, fetched only if something reads them + // before the batch is done. + let mut later: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new(); + // The last send of these plans' flights (`relay_fetch_merge`). + let sent_as = plans.iter().map(|p| p.1.sent_as).max(); + if let Some((differs, dwords)) = differs { + // SAFETY: the mapping of the results. The compares of these + // plans have run, and their dwords are given to no other plan + // before these are done with (`card_done`). + let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) }; + let mut seen = std::collections::HashSet::new(); + for &(number, plan) in plans { + let mut flags: Vec<(usize, u32, bool)> = plan + .ranges + .iter() + .flat_map(|r| { + (0..r.span.pieces).map(move |p| { + let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| d != 0); + (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, flagged) + }) + }) + .collect(); + // A piece an earlier fetch brought down while this flight + // may have been writing it: fetched, flagged or not. + for flag in flags.iter_mut().filter(|f| !f.2) { + if fetched_beside(noted.get(&(flag.0, flag.1)).copied(), number) { + flag.2 = true; + again += 1; + } + } + let fetched = flagged_pieces(&flags); + numbers.extend(fetched.iter().copied()); + for r in &plan.ranges { + let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + if !fetched.contains(&(copy, r.span.first + p)) { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo < hi && seen.insert((copy, lo, hi)) { + if back.skip.contains(©) { + later.push((r.shadow.clone(), lo, hi, 0)); + continue; + } + pieces.push((r.shadow.clone(), lo, hi, total)); + total += (hi - lo) as u64; + } + } + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + } + } + BESIDE_STATS[0].fetch_add(again, Ordering::Relaxed); + let ask = FetchAsk { sends_done: back.sends_done, sent_as, lane, behind, beside, numbers: &numbers, landed }; + self.relay_fetch_merge(&pieces, total, fetch, &ask); + if later.is_empty() { + return; + } + // What was read meanwhile (a title thread held at it, or our own + // code): those copies' waiting pieces are fetched too, before the + // batch is done, and the copies are copied back whole from now on. + let mut read: Vec<usize> = Vec::new(); + let mut checked: Vec<usize> = Vec::new(); + for (shadow, ..) in &later { + let copy = std::sync::Arc::as_ptr(shadow) as usize; + if !checked.contains(©) { + checked.push(copy); + let (from, to) = shadow.title_span(); + if crate::lazy::touched_in(from, to) { + read.push(copy); + } + } + } + let mut again = Vec::new(); + let mut again_total = 0u64; + for (shadow, lo, hi, _) in later { + if read.contains(&(std::sync::Arc::as_ptr(&shadow) as usize)) { + again.push((shadow, lo, hi, again_total)); + again_total += (hi - lo) as u64; + } else { + READ_ONLY_STATS[0].fetch_add(1, Ordering::Relaxed); + READ_ONLY_STATS[1].fetch_add((hi - lo) as u64, Ordering::Relaxed); + } + } + if !read.is_empty() { + let mut quiet = read_quiet(); + for copy in &read { + if let Some(q) = quiet.get_mut(copy) { + q.1 = u32::MAX; + } + } + } + if !again.is_empty() { + READ_ONLY_STATS[2].fetch_add(again.len() as u64, Ordering::Relaxed); + self.relay_fetch_merge(&again, again_total, fetch, &ask); + } + } + + /// [`Host::relay_card_back`]'s fetch of `pieces` (copy, from, to, where + /// in the fetch buffer), `total` bytes, and their merge into title + /// memory. + fn relay_fetch_merge( + &self, + pieces: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)], + total: u64, + fetch: &mut Option<RelayFetch>, + ask: &FetchAsk<'_>, + ) { + let FetchAsk { sends_done, sent_as, lane, behind, beside, numbers, landed } = *ask; + if pieces.is_empty() { + if inflight_fetch() { + // The next merge may be of a flight in the air now, with + // bytes from when it ran: only sends up to these plans' are + // older than it. + if let Some(last) = sent_as { + crate::shadow::relay_fetched(last); + } + return; + } + if beside { + // Notes whose flights have all landed are done with. + let mut all = BESIDE.lock().unwrap_or_else(|e| e.into_inner()); + note_beside(all.get_or_insert_with(Default::default), &[], landed, landed); + } + // Nothing to fetch: every send so far is older than the next + // fetch (on a copy queue: every send the card has finished; on + // the copy engine, which does not wait for them, only those + // ahead of the landed flights). + crate::shadow::relay_fetched(match lane { + Some(second) => second.order_done(), + None if copy_fetch() => sends_done, + None => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()), + }); + return; + } + if inflight_fetch() { + INFLIGHT_STATS[3].fetch_add(1, Ordering::Relaxed); + } + if fetch.is_none() { + *fetch = self.make_relay_fetch(); + } + let Some(f) = fetch.as_mut() else { + fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)")); + }; + if f.buffer.as_ref().is_none_or(|b| b.2 < total) { + let size = total.next_multiple_of(16 << 20); + f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + } + let Some((buffer, data, _)) = f.buffer.clone() else { + fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)")); + }; + f.sent += 1; + let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent); + let copy = f.copy.clone(); + let waiting = std::time::Instant::now(); + // SAFETY: the list's last run was waited for by this thread; live + // buffers (the copies are held by the plans); the fence and the + // event are this thread's. + let ran = unsafe { + (|| -> windows::core::Result<u64> { + if let Some(second) = lane { + // The sends of title bytes the card has finished are in + // what comes down. A later one may be too, if the card + // runs it before this fetch: the merge leaves its bytes + // out as a send that came after, and they are the + // title's either way. + let after = second.order_done(); + let copy = second.down.list()?; + for (shadow, lo, hi, at) in relay_copy_runs(pieces) { + copy.1.CopyBufferRegion(&buffer, at, &shadow.buffer, lo as u64, (hi - lo) as u64); + } + let job = second.down.send(copy, &[(&self.fence, behind)], total)?; + second.down.wait(job, event)?; + if beside { + // Whatever had started by now may have been + // writing these pieces while they came down + // (counted before a submission's lists go to the + // queue, `Host::submit`: nothing later ran yet). + let started = STARTED.load(Ordering::Acquire); + let mut all = BESIDE.lock().unwrap_or_else(|e| e.into_inner()); + let noted = note_beside(all.get_or_insert_with(Default::default), numbers, landed, started); + BESIDE_STATS[1].fetch_add(noted, Ordering::Relaxed); + } + second.down.stats.waited_us.fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + return Ok(after); + } + if let Some((queue, (allocator, list))) = © { + allocator.Reset()?; + list.Reset(allocator, None)?; + for (shadow, lo, hi, at) in relay_copy_runs(pieces) { + list.CopyBufferRegion(&buffer, at, &shadow.buffer, lo as u64, (hi - lo) as u64); + } + list.Close()?; + let lists = [Some(list.cast::<ID3D12CommandList>()?)]; + queue.ExecuteCommandLists(&lists); + queue.Signal(&fence, sent)?; + fence.SetEventOnCompletion(sent, event)?; + WaitForSingleObject(event, INFINITE); + // The sends known to have run: those ahead of the landed + // flights. + return Ok(sends_done); + } + allocator.Reset()?; + list.Reset(&allocator, None)?; + for (shadow, lo, hi, at) in relay_copy_runs(pieces) { + list.CopyBufferRegion(&buffer, at, &shadow.buffer, lo as u64, (hi - lo) as u64); + } + list.Close()?; + let lists = [Some(list.cast::<ID3D12CommandList>()?)]; + // In the order of the queue: the sends of title bytes so + // far are ahead of this fetch, every later one behind it. + let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()); + self.queue.ExecuteCommandLists(&lists); + let after = *order; + drop(order); + self.card_sent(); + self.queue.Signal(&fence, sent)?; + fence.SetEventOnCompletion(sent, event)?; + WaitForSingleObject(event, INFINITE); + Ok(after) + })() + }; + let after = match ran { + Ok(after) => after, + Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")), + }; + // This fetch may bring bytes of flights in the air now: their own + // slots are older than what it puts in the CPU's side there + // (`relay_card_inflight`). Sends up to `after` are numbered, and the + // submission numbered `after` may not have its lists on the queue + // yet; every one before it has (the submission lock). + if inflight_fetch() + && after > 1 + && let Some(inflight) = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|w| w.inflight.as_mut()) + { + inflight.brought.extend(pieces.iter().map(|(shadow, lo, hi, _)| (shadow.clone(), *lo, *hi, after - 1))); + } + let us = waiting.elapsed().as_micros() as u64; + RELAY_STATS[3].fetch_add(us, Ordering::Relaxed); + { + use crate::shadow::CARD_STATS; + CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed); + CARD_STATS[4].fetch_add(total, Ordering::Relaxed); + CARD_STATS[5].fetch_add(1, Ordering::Relaxed); + CARD_STATS[6].fetch_add(us, Ordering::Relaxed); + } + let mut title = Vec::new(); + let mut written = 0; + for (shadow, lo, hi, at) in pieces { + // SAFETY: the mapping of the fetched bytes, `total` of them; + // the copy into it has run. + let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; + let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); + shadow.walls_merged(gpu.len(), merged); + written += merged; + } + copy_back(1, written as u64); + // Sends up to `after` are of no use to any later merge; with the + // fetch inside flights only those up to these plans' are + // (`fallback_fetched_mark`). + crate::shadow::relay_fetched(fallback_fetched_mark(inflight_fetch(), after, sent_as)); + } + + /// [`Host::relay_card_back`] with [`inflight_fetch`]: the pieces these + /// plans' compares flagged are taken from the slots their own compare + /// lists copied them to ([`CARD_FETCH`]) and merged, plan by plan in the + /// line's order, with no list or wait of ours. `false` (nothing merged) + /// if any plan cannot land so; the caller then lands them all the old + /// way, as without the switch. + /// + /// The merge's "fetched after" (`Shadow::card_merge_relay`) is the + /// plan's own `sent_as`. `QUEUE_ORDER` is raised only in + /// `Host::card_before`, under the submission lock, and that lock is held + /// until the submission's lists and its compare's list are on the queue + /// behind its sync list: so when the compare's list ran, the card had + /// received exactly the sends 1..=`sent_as` of title bytes and no later + /// one, which is what the merge's skip of later sends asks. (The old + /// fetch, by contrast, ran whenever it reached the queue, and took the + /// count at its own ExecuteCommandLists.) + /// + /// When a landing goes the old way instead, all of it does: a fetch the + /// old way brings the card's bytes as they are now, newer than the slots + /// of plans in the air then, and merging an older slot after it would + /// put a flight's bytes back over a later flight's. For the same reason + /// the bytes such a fetch brought (`CardInflight::brought`) are left + /// out of the slots of flights whose lists were on the queue ahead of + /// it: the CPU's side holds what the card held after them there. The + /// rest of their slots is merged, newer than anything merged there + /// before. (Left out whole, a flight sent before such a fetch would have + /// had to land the old way, its fetch taking a later count still: one + /// overflow kept every landing on the old way while flights were in + /// the air.) Plans land in the line's order, each plan's slot as it was + /// right behind its own lists, so every merge here is of bytes at least + /// as new as the CPU's side holds. + /// + /// shortcut: all or nothing per landing, and a plan whose pieces overflow + /// the slots lands the old way for all its pieces, not only the ones + /// left out. + fn relay_card_inflight(&self, plans: &[&CardPlan]) -> bool { + use std::sync::Arc; + type Piece = (Arc<crate::shadow::Shadow>, usize, usize, usize, u64); + let mut pieces: Vec<Piece> = Vec::new(); + { + let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_ref() else { + return false; + }; + let Some(inflight) = &work.inflight else { + return false; + }; + let dwords = (work.differs.2 / 4) as usize; + // SAFETY: the mappings of the results and the tickets. The + // compares and fetches of these plans have run, and their dwords + // are given to no other plan before these are done with + // (`card_done`). + let (differs, table) = unsafe { + ( + std::slice::from_raw_parts(work.differs.1 as *const u32, dwords), + std::slice::from_raw_parts((inflight.table.1 as *const u32).add(1), dwords), + ) + }; + let slots = inflight.fetched.2; + for plan in plans { + if plan.ranges.is_empty() { + continue; + } + if !plan.inflight || plan.ranges.iter().any(|r| !r.compared) { + return false; + } + // Pieces (copy, number) the compare flagged, with their ticket. + let mut tickets: std::collections::HashMap<(usize, u32), u32> = std::collections::HashMap::new(); + let mut flags: Vec<(usize, u32, bool)> = Vec::new(); + for r in &plan.ranges { + let copy = Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + let at = (r.at + p) as usize; + let (Some(&flag), Some(&entry)) = (differs.get(at), table.get(at)) else { + return false; + }; + if flag != 0 { + if entry == INFLIGHT_NONE { + return false; + } + if !inflight_gets_slot(entry, plan.inflight_landed, slots) { + INFLIGHT_STATS[2].fetch_add(1, Ordering::Relaxed); + return false; + } + tickets.insert((copy, r.span.first + p), entry); + } + flags.push((copy, r.span.first + p, flag != 0)); + } + } + let fetched = flagged_pieces(&flags); + let mut seen = std::collections::HashSet::new(); + for r in &plan.ranges { + let copy = Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + let piece = r.span.first + p; + if !fetched.contains(&(copy, piece)) { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo >= hi || !seen.insert((copy, lo, hi)) { + continue; + } + let from = inflight_piece_from(&r.span, p); + let Some(&k) = tickets.get(&(copy, piece)) else { + return false; + }; + if lo < from || (hi - from) as u64 > INFLIGHT_SLOT { + return false; + } + let slot = inflight.fetched.1 + (k % slots) as usize * INFLIGHT_SLOT as usize; + // Bytes a fetch the old way brought after this flight ran. + let newer: Vec<(usize, usize)> = inflight + .brought + .iter() + .filter(|b| b.3 >= plan.sent_as && Arc::ptr_eq(&b.0, &r.shadow) && b.1 < hi && b.2 > lo) + .map(|b| (b.1, b.2)) + .collect(); + for (a, b) in crate::shadow::outside(lo, hi, newer) { + pieces.push((r.shadow.clone(), a, b, slot + (a - from), plan.sent_as)); + } + } + } + } + } + // Outside the lock: no slot of these plans is written over before + // their tickets are landed (`inflight_tickets_landed`, after this). + let mut title = Vec::new(); + let (mut written, mut bytes) = (0, 0u64); + for (shadow, lo, hi, at, after) in &pieces { + // SAFETY: inside the mapping of the slots (checked above); the + // copy into it ran in the plan's flight, which the card has run. + let gpu = unsafe { std::slice::from_raw_parts(*at as *const u8, hi - lo) }; + written += shadow.card_merge_relay(*lo, gpu, *after, &mut title); + bytes += (hi - lo) as u64; + } + for plan in plans { + for r in &plan.ranges { + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + } + copy_back(1, written as u64); + INFLIGHT_STATS[0].fetch_add(pieces.len() as u64, Ordering::Relaxed); + INFLIGHT_STATS[1].fetch_add(bytes, Ordering::Relaxed); + // The next merge is of a later plan, or a fetch the old way sent now. + if let Some(last) = plans.iter().map(|p| p.sent_as).max() { + crate::shadow::relay_fetched(last); + } + true + } + + /// [`relay`], on the thread that lands flights: `items` are the first + /// things of the line, flights the card has run and what follows them. + /// What their shaders wrote goes into title memory (copies in the + /// card's memory first, then the others, each byte once whichever + /// flights declared it); then every flight's ranges are done with; + /// then, in the line's order, each flight's read-backs, its + /// bottom-of-pipe writes and the fence signals behind it. Title memory + /// is complete before the title is told anything. + fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) { + let landing = std::time::Instant::now(); + // With `crate::lazy`: what was done before the copy-back (the read + // backs of every flight, and the signals and writes up to the first + // write into held memory). + let mut read_back_early = false; + let mut early = vec![false; items.len()]; + { + let flights: Vec<&Flight> = items + .iter() + .filter_map(|l| match l { + Late::Run(flight) => Some(flight), + _ => None, + }) + .collect(); + if !flights.is_empty() { + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect(); + fail(format_args!( + "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}", + flights.len(), + runs.len(), + self.removal_data(&runs), + last_notes(&runs) + )); + } + fill_ahead::landing(flights.iter().map(|f| f.number).min().unwrap_or(0)); + // Lazy copy-back: the memory the shaders may have written is + // held (no access), and the title hears now that the card is + // done; the copy-back below opens it. + let lazy = crate::lazy::on() && { + let ranges: Vec<(usize, usize)> = + flights.iter().flat_map(|f| f.back.iter().flat_map(|(_, r)| r.iter().copied())).collect(); + // The read backs write title memory: before it is held. + for flight in &flights { + for &i in &flight.order { + read_backs(flight.lists[i].host()); + } + } + read_back_early = true; + crate::lazy::hold(&ranges) + }; + if lazy { + let mut sent = 0; + for (k, item) in items.iter().enumerate() { + match item { + Late::Run(_) => {} + Late::Signal(fence, value) => { + crate::fence::set(*fence as crate::object::This, *value); + early[k] = true; + sent += 1; + } + Late::Write(at, what, bytes) => { + // Into held memory: this and what follows + // wait for the copy-back, in order. + if crate::lazy::holds_any(*at, *bytes) { + break; + } + what.write(*at as *mut u8, *bytes); + early[k] = true; + sent += 1; + } + } + } + crate::lazy::LAZY_STATS[2].fetch_add(sent, Ordering::Relaxed); + } + let plans: Vec<(u64, &CardPlan)> = flights.iter().filter_map(|f| f.card.as_ref().map(|card| (f.number, card))).collect(); + let behind = flights.iter().map(|f| f.fence).max().unwrap_or(0); + let landed = flights.iter().map(|f| f.number).max().unwrap_or(0); + let sends_done = flights.iter().map(|f| f.sends).max().unwrap_or(0); + let card_plans: Vec<&CardPlan> = plans.iter().map(|p| p.1).collect(); + let mut back: Vec<Declared> = Vec::new(); + for flight in &flights { + for (shadow, ranges) in &flight.back { + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, all)) => { + for range in ranges { + if !all.contains(range) { + all.push(*range); + } + } + } + None => back.push((shadow.clone(), ranges.clone())), + } + } + } + let skip = read_only_plan(&card_plans, &back, lazy); + self.relay_card_back(&plans, fetch, behind, landed, RelayBack { sends_done, skip: &skip }); + let left = relay_hand_back(&back, &skip); + if lazy { + // What something touched while held is compared and + // copied back before it is let go, and always from now. + let touched: Vec<Declared> = left + .into_iter() + .filter(|(shadow, _)| { + let (from, to) = shadow.title_span(); + crate::lazy::touched_in(from, to) + }) + .collect(); + if !touched.is_empty() { + READ_ONLY_STATS[2].fetch_add(touched.len() as u64, Ordering::Relaxed); + let mut quiet = read_quiet(); + for (shadow, _) in &touched { + if let Some(q) = quiet.get_mut(&(std::sync::Arc::as_ptr(shadow) as usize)) { + q.1 = u32::MAX; + } + } + drop(quiet); + relay_hand_back(&touched, &[]); + } + crate::lazy::done(); + } + // Only now, and flight by flight: a range another flight + // in the air declared too stays closed to refreshes. + for flight in &flights { + for (shadow, ranges) in &flight.back { + shadow.copy_back_done(ranges); + } + } + copy_back(0, landing.elapsed().as_micros() as u64); + RELAY_STATS[0].fetch_add(1, Ordering::Relaxed); + RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed); + } + } + // In the order given: what tells the title the card is done. + let mut last = 0; + let mut landed = Vec::new(); + for (item, early) in items.into_iter().zip(early) { + match item { + Late::Run(mut flight) => { + last = flight.number; + if !read_back_early { + for &i in &flight.order { + read_backs(flight.lists[i].host()); + } + } + if let Some(card) = flight.card { + self.card_done(card); + } + // The dynamic descriptor slots of lists that have run go back now, not + // after the allocator's delay (codec_d, cool_fox f4b48ad: held, they ran + // NVIDIA's slots out and draws went without their tables). + for detached in &mut flight.lists { + detached.release_tables(); + } + landed.push((flight.lists, flight.order)); + } + _ if early => {} + Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), + Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), + } + } + if last > 0 { + FINISHED.store(last, Ordering::Release); + bury(last); + } + self.log_messages(); + fill_ahead::landing(0); + RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); + { + let mut line = line(); + let Line { + line: items, + written, + lists, + settling, + poke, + landed: kept, + in_hand, + .. + } = &mut *line; + kept.extend(landed); + in_hand.clear(); + // What is still in the air, from the flights that are. + written.clear(); + *lists = 0; + let mut ranges = Vec::new(); + for item in items.iter() { + if let Late::Run(flight) = item { + *lists += flight.order.len().max(1); + ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); + ranges.extend(flight.texture_back_ranges.iter().copied()); + } + } + join_ranges(written, ranges); + *settling = false; + // The landed lists are reset, and what queues hold looked at, + // by the helper thread (they take locks a waiter may hold). + *poke = true; + } + LINE_MOVED.notify_all(); + LINE_LANDED.notify_all(); + } + + /// After a submission ran, for copies in the card's memory: the pieces + /// of the declared ranges that the compare found differing (all of a + /// range it did not compare) are fetched, with one more wait for the + /// card, and what shaders wrote in them goes into title memory. + /// `submitted` is the last value signalled on the fence. `seen` holds + /// the pieces fetched already since the card was last waited for + /// (several submissions settled together name the same ones). + fn card_back( + &self, + plan: &CardPlan, + submitted: &mut u64, + seen: &mut std::collections::HashSet<(usize, usize, usize)>, + ) { + if plan.ranges.is_empty() { + return; + } + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + // SAFETY: the mapping of the results, which the compare (it has + // run) wrote. + let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) }; + // The pieces to fetch: the range, the offsets in its copy, and + // where the bytes come down. + let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new(); + let mut total = 0u64; + for (i, r) in plan.ranges.iter().enumerate() { + for p in 0..r.span.pieces { + if r.compared && differs[(r.at + p) as usize] == 0 { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) { + pieces.push((i, lo, hi, total)); + total += (hi - lo) as u64; + } + } + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + let mut written = vec![0usize; plan.ranges.len()]; + if !pieces.is_empty() { + if work.fetched.as_ref().is_none_or(|f| f.2 < total) { + let size = total.next_multiple_of(16 << 20); + work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + } + let Some((fetched, data, _)) = &work.fetched else { + fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)")); }; - // SAFETY: each query writes its own structure of the given size. - let ok = unsafe { - self.device - .CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS7, - (&raw mut options).cast(), - size_of_val(&options) as u32, - ) - .is_ok() - && self - .device - .CheckFeatureSupport( - D3D12_FEATURE_SHADER_MODEL, - (&raw mut model).cast(), - size_of_val(&model) as u32, - ) - .is_ok() + let waiting = std::time::Instant::now(); + let (allocator, list) = &work.fetch; + // SAFETY: the list's last run was waited for; live buffers; the + // fence and event are ours, under the submission lock. + let ran = unsafe { + (|| -> windows::core::Result<()> { + // With `VICTORY_QUEUE2` bit 1 the fetch goes to the copy + // queue here too, behind everything sent to the direct + // queue. Nothing is gained (the card has run it all + // when this is reached); the path is the same one the + // relay uses, in the plainest run there is. + if let Some(second) = crate::queue2::second().filter(|s| s.fetches()) { + let copy = second.down.list()?; + for &(i, lo, hi, at) in &pieces { + copy.1.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64); + } + let job = second.down.send(copy, &[(&self.fence, *submitted)], total)?; + let was_working = working(false); + second.down.wait(job, self.event)?; + stood(waiting); + working(was_working); + second.down.stats.waited_us.fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + return Ok(()); + } + allocator.Reset()?; + list.Reset(allocator, None)?; + for &(i, lo, hi, at) in &pieces { + list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64); + } + list.Close()?; + self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + self.card_sent(); + *submitted += 1; + self.queue.Signal(&self.fence, *submitted)?; + self.fence.SetEventOnCompletion(*submitted, self.event)?; + let was_working = working(false); + WaitForSingleObject(self.event, INFINITE); + stood(waiting); + working(was_working); + Ok(()) + })() }; - let mesh = ok - && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED - && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; - tracing::info!(mesh, "host mesh shader support"); - mesh - }) + if let Err(e) = ran { + fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})")); + } + { + use crate::shadow::CARD_STATS; + CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed); + CARD_STATS[4].fetch_add(total, Ordering::Relaxed); + CARD_STATS[5].fetch_add(1, Ordering::Relaxed); + CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + } + if wide_merge() && pieces.len() >= 8 { + // The pieces are apart from one another (each its own bytes + // of its copy and of title memory): several at a time. + let fetched = *data; + let counts: std::sync::Arc<Vec<std::sync::atomic::AtomicUsize>> = + std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect()); + let each = pieces.len().div_ceil(8); + let jobs: Vec<Box<dyn FnOnce() + Send>> = pieces + .chunks(each) + .map(|chunk| { + let chunk: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, usize, u64)> = + chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect(); + let counts = counts.clone(); + Box::new(move || { + let mut title = Vec::new(); + for (shadow, i, lo, hi, at) in chunk { + // SAFETY: the mapping of the fetched bytes; + // the copy into it has run, and the caller + // waits for this job. + let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) }; + let merged = shadow.card_merge(lo, gpu, &mut title); + shadow.walls_merged(gpu.len(), merged); + counts[i].fetch_add(merged, Ordering::Relaxed); + } + }) as Box<dyn FnOnce() + Send> + }) + .collect(); + crate::shadow::wide_run(jobs); + for (written, count) in written.iter_mut().zip(counts.iter()) { + *written += count.load(Ordering::Relaxed); + } + } else { + let mut title = Vec::new(); + for &(i, lo, hi, at) in &pieces { + // SAFETY: the mapping of the fetched bytes, `total` of + // them; the copy into it has run. + let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) }; + let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title); + plan.ranges[i].shadow.walls_merged(gpu.len(), merged); + written[i] += merged; + } + } + } + for (r, written) in plan.ranges.iter().zip(written) { + copy_back(1, written as u64); + let (from, to) = r.declared; + #[cfg(feature = "diagnostics")] + crate::copystat::compared(from, to - from, written); + let _ = (from, to); + } } - /// A recycled host list (reset and open), or a new one when the pool is - /// empty. - pub(crate) fn acquire_list(&self) -> windows::core::Result<HostList> { - let pooled = self - .free_lists - .lock() - .unwrap_or_else(|e| e.into_inner()) - .pop(); - if let Some(list) = pooled { - #[cfg(test)] - self.reused_lists.fetch_add(1, Ordering::Relaxed); - list.reset(); - return Ok(list); - } - self.new_list() + /// Runs closed lists and waits for them, and with [`late`] for + /// everything sent to the card before them, which is settled first. + pub(crate) fn execute(&self, runs: &[&HostList]) { + // Behind what the queues were given before it and have not run + // yet (`crate::queue::behind`). + crate::queue::before_sync(); + let _ = self.submit(runs, false); } - #[cfg(test)] - pub(crate) fn reused_lists(&self) -> u64 { - self.reused_lists.load(Ordering::Relaxed) + /// A queue's submission with [`late`]: the host lists `lists`, taken + /// from the title's, go to the card in `order` and are not waited for. + /// They join the line of flights and are settled, with the others in + /// the air, at the next point where what they do can be observed + /// ([`late`] lists those points); their host lists are reset and kept + /// for reuse then, as a queue does for the lists it ran. + pub(crate) fn execute_late(&self, mut lists: Vec<crate::list::Detached>, mut order: Vec<usize>) { + if order.is_empty() { + crate::list::recycle(lists, &order); + return; + } + // Textures uploaded ahead (`crate::heap_worker`): their lists run + // before the title's. + let ahead = crate::heap_worker::take_ready(); + if !ahead.is_empty() { + let first = lists.len(); + order.splice(0..0, first..first + ahead.len()); + lists.extend(ahead.into_iter().map(crate::list::Detached::ours)); + } + late_threads(); + let sent = { + let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect(); + self.submit(&runs, true) + }; + let Some((mut submitted, sent)) = sent else { + // (Not reached: a submission sent ahead always comes back.) + crate::list::recycle(lists, &order); + return; + }; + let told = !sent.writes.is_empty(); + // (Under the submission lock: no send goes up meanwhile.) + let sends = *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()); + let most = { + let mut line = line(); + let Line { line: items, written, lists: flying, target, .. } = &mut *line; + join_ranges( + written, + sent.back + .iter() + .flat_map(|(_, ranges)| ranges.iter().copied()) + .chain(sent.texture_back_ranges.iter().copied()), + ); + *flying += order.len(); + *target = *submitted; + items.push(Late::Run(Flight { + number: sent.number, + fence: *target, + lists, + order, + card: sent.card, + back: sent.back, + sends, + texture_back_ranges: sent.texture_back_ranges, + })); + items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); + *flying >= late_limit() + }; + LATE_STATS[0].fetch_add(1, Ordering::Relaxed); + RELAY_MOVED.notify_one(); + if told && !late_writes() { + self.settle(&mut submitted, WHY_WRITES); + } else if most && relay_exact() { + // Until there are fewer, not until there are none. + relay_wait(WHY_MOST, |line| line.lists < late_limit()); + } else if most { + self.settle(&mut submitted, WHY_MOST); + } else { + LINE_MOVED.notify_one(); + } + drop(submitted); + land(); } - /// Returns a finished, unreferenced host list to the pool up to - /// [`LIST_POOL_CAP`], releasing any kept upload blocks and dynamic slots - /// immediately. - pub(crate) fn recycle_list(&self, list: HostList) { - list.release_kept(); - let mut pool = self.free_lists.lock().unwrap_or_else(|e| e.into_inner()); - if pool.len() < LIST_POOL_CAP { - pool.push(list); + /// Sends `list`, a closed list of ours (the present's copy), as a + /// flight ([`late_free_present`]): not waited for, settled with the + /// others. The caller keeps the list and does not reset it before the + /// submission whose number comes back has finished ([`FINISHED`]); 0 if + /// it ran and was waited for after all. + fn execute_own(&self, list: &HostList) -> u64 { + late_threads(); + let Some((submitted, sent)) = self.submit(&[list], true) else { + return 0; + }; + let number = sent.number; + let sends = *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut line = line(); + let Line { line: items, written, lists: flying, target, .. } = &mut *line; + join_ranges( + written, + sent.back + .iter() + .flat_map(|(_, ranges)| ranges.iter().copied()) + .chain(sent.texture_back_ranges.iter().copied()), + ); + *flying += 1; + *target = *submitted; + items.push(Late::Run(Flight { + number, + fence: *target, + lists: Vec::new(), + order: Vec::new(), + card: sent.card, + back: sent.back, + sends, + texture_back_ranges: sent.texture_back_ranges, + })); + items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); } + LATE_STATS[0].fetch_add(1, Ordering::Relaxed); + LINE_MOVED.notify_one(); + RELAY_MOVED.notify_one(); + drop(submitted); + number } - /// A new list, open for recording. - pub(crate) fn new_list(&self) -> windows::core::Result<HostList> { - // SAFETY: plain object creation. - unsafe { - let allocator: ID3D12CommandAllocator = self - .device - .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = self.device.CreateCommandList( - 0, - D3D12_COMMAND_LIST_TYPE_DIRECT, - &allocator, - None, - )?; - let prelude_allocator: ID3D12CommandAllocator = self - .device - .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let prelude: ID3D12GraphicsCommandList = self.device.CreateCommandList( - 0, - D3D12_COMMAND_LIST_TYPE_DIRECT, - &prelude_allocator, - None, - )?; - prelude.Close()?; - Ok(HostList { - allocator, - list, - deferred: Mutex::default(), - scratch: Mutex::default(), - states: Mutex::default(), - prelude: (prelude_allocator, prelude), - kept_uploads: Mutex::default(), - kept_dynamic: Mutex::default(), - pipelines: Mutex::default(), - budget: OnceLock::new(), - rect_scratch: Mutex::default(), - clear_uav_cpu: OnceLock::new(), - #[cfg(feature = "diagnostics")] - notes: Mutex::default(), + /// Waits for the card to run every flight in the air ([`late`]) and + /// does what they left to do, as [`Host::execute`] does for one + /// submission after its wait: the pieces their shaders wrote in copies + /// in the card's memory are fetched and merged (each once), the ranges + /// they declared in the other copies are compared and copied back + /// (each byte once, whichever flights declared it), and then, in the + /// order they were given: their bottom-of-pipe writes and the fence + /// signals behind them. `submitted` is the submission lock's value; + /// `why` one of the `WHY_` places. Nothing happens if nothing flies. + /// + /// Everything in the air is settled, never the first flights alone: + /// the merge writes the copies' CPU side, which a flight still on the + /// card may be writing too. + fn settle(&self, submitted: &mut u64, why: usize) { + if !late() { + return; + } + if relay() { + // Nothing is settled here: the thread that lands flights does + // it, in order, and this waits until nothing is in the air and + // nothing is being landed. Every point that settled before + // comes here, so each still sees title memory, fences and + // bottom-of-pipe values as after a settle. + relay_wait(why, |line| line.line.is_empty() && !line.settling); + return; + } + let was_working = working(true); + let mut counted = false; + loop { + let items = { + let mut line = line(); + if line.line.is_empty() { + line.settling = false; + break; + } + line.settling = true; + line.written.clear(); + line.lists = 0; + std::mem::take(&mut line.line) + }; + let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count(); + if !counted { + counted = true; + LATE_STATS[1].fetch_add(1, Ordering::Relaxed); + LATE_STATS[why].fetch_add(1, Ordering::Relaxed); + } + LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed); + if flights > 0 { + submitting(2, flights); + let waiting = std::time::Instant::now(); + // SAFETY: the fence and event are ours, under the + // submission lock; `submitted` is the last value signalled. + unsafe { + match self.fence.SetEventOnCompletion(*submitted, self.event) { + Ok(()) => { + working(false); + WaitForSingleObject(self.event, INFINITE); + stood(waiting); + working(true); + } + Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"), + } + } + let gpu = waiting.elapsed(); + LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + submission_us(1, gpu.as_micros() as u64); #[cfg(feature = "diagnostics")] - stamps: OnceLock::new(), - }) + crate::copystat::card_waited(gpu.as_micros() as u64, || { + format!("{flights} submissions sent ahead, settled together") + }); + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + let runs: Vec<&HostList> = items + .iter() + .filter_map(|i| match i { + Late::Run(f) => Some(f), + _ => None, + }) + .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())) + .collect(); + fail(format_args!( + "host GPU device removed after {flights} submissions sent ahead (VICTORY_LATE_WAIT=1) of {} lists{}{}", + runs.len(), + self.removal_data(&runs), + last_notes(&runs) + )); + } + submitting(3, flights); + let copying = std::time::Instant::now(); + let mut seen = std::collections::HashSet::new(); + let mut back: Vec<Declared> = Vec::new(); + for item in &items { + let Late::Run(flight) = item else { + continue; + }; + if let Some(card) = &flight.card { + self.card_back(card, submitted, &mut seen); + } + for (shadow, ranges) in &flight.back { + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, all)) => { + for range in ranges { + if !all.contains(range) { + all.push(*range); + } + } + } + None => back.push((shadow.clone(), ranges.clone())), + } + } + } + hand_back(&back); + copy_back(0, copying.elapsed().as_micros() as u64); + } + // In the order given: what tells the title the card is done. + let mut last = 0; + let mut landed = Vec::new(); + for item in items { + match item { + Late::Run(mut flight) => { + last = flight.number; + for &i in &flight.order { + read_backs(flight.lists[i].host()); + } + if let Some(card) = flight.card { + self.card_done(card); + } + // The dynamic descriptor slots of lists that have run go back now, not + // after the allocator's delay (codec_d, cool_fox f4b48ad: held, they ran + // NVIDIA's slots out and draws went without their tables). + for detached in &mut flight.lists { + detached.release_tables(); + } + landed.push((flight.lists, flight.order)); + } + Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), + Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), + } + } + if last > 0 { + FINISHED.store(last, Ordering::Release); + bury(last); + } + line().landed.extend(landed); + } + if counted { + self.log_messages(); + submitting(0, 0); + // What was settled may be what a queue stands at, and the + // caller may not be one that looks (a read-back, a present). + if why != WHY_CARD_DONE { + line().poke = true; + LINE_MOVED.notify_one(); + } } + working(was_working); } - /// Runs closed lists and waits for them. - pub(crate) fn execute(&self, runs: &[&HostList]) { + /// [`Host::execute`], or with `late` the first half of + /// [`Host::execute_late`]: the lists are prepared and sent, and what is + /// to be done once they have run comes back with the submission lock + /// still held. + fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> { + #[cfg(feature = "diagnostics")] + let called = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_begins(); + #[cfg(feature = "diagnostics")] + crate::profile::seen(crate::profile::Seen::Submit); // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let was_working = working(true); + submitting(1, runs.len()); + self.video_memory_look(); + // Flights in the air ([`late`]): a submission that is waited for + // settles them first, one sent ahead only if preparing it reads + // what they write. + if !late { + self.settle(&mut submitted, WHY_SYNC); + } else if let Some(why) = late_blocked(runs) { + if relay_exact() && why == WHY_READ { + // Only until the flights that may write what is read have + // landed: their copy-back's end, not the card's other work. + relay_wait(why, |line| blocked_by(&line.written, runs, false).is_none()); + } else { + self.settle(&mut submitted, why); + } + } + // Descriptors the title copied into placed heaps directly, before + // command lists that index those slots are submitted. With + // `VICTORY_SYNC_BESIDE` on a thread of its own while this one + // prepares, from after the sweep to before the lists go to the card + // (`crate::descriptor::sync_beside`). + let beside = crate::descriptor::sync_beside(); + if !beside { + crate::descriptor::sync_heaps(); + } + let behind = late && flying(); + // Before this submission counts as started: what the sweep lets go + // of is named by no list, and nothing runs now (behind flights the + // sweep waits for a submission that finds none in the air: there is + // one at every present). + static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if !behind { + sweep(); + SWEPT.store(now_ms(), Ordering::Relaxed); + } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 { + // With the present sent ahead nothing else brings a moment + // with nothing in the air: one is made for the sweep. + self.settle(&mut submitted, WHY_SYNC); + sweep(); + SWEPT.store(now_ms(), Ordering::Relaxed); + } + let behind = late && flying(); + // The slots that waited for a texture's host copy, before the + // lists that may read them run (with the pass, beside, after it). + if beside { + crate::descriptor::sync_begin(); + } else { + crate::descriptor::make_waiting(); + } let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1; + // The ranges shaders write are counted for it (with the relay). + crate::shadow::preparing(this_submission); let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] + let lock = (started - called).as_micros() as u64; + #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Submissions, 1); let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len()); // Where each run's lists start in `lists`. let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); + // The time a settle of flights takes inside this preparing: the + // wait for the card and the copy-back have their own places on the + // frame line (run 92 showed them twice, "preparing" 250 ms for 135). + let mut settled = std::time::Duration::ZERO; + // The parts of the preparing, for the line that splits it + // ([`PREP_PARTS`]). + let mut part = std::time::Instant::now(); + // One write-watch asking for everything the submission refreshes + // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges. + if crate::watch::once() { + let mut spans: std::collections::HashMap<usize, (usize, usize)> = std::collections::HashMap::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::Refresh(shadow, address, len) = step + && !shadow.unwatched() + { + let span = spans + .entry(std::sync::Arc::as_ptr(shadow) as usize) + .or_insert((*address, *address + *len)); + *span = (span.0.min(*address), span.1.max(*address + *len)); + } + } + } + let ranges: Vec<(usize, usize)> = spans.into_values().collect(); + crate::watch::ask_once(&ranges); + // Behind flights: the title wrote memory that a flight's shaders + // may write too, and this submission refreshes it. The flights + // are settled, and the asking made again: the copy-back wrote + // title memory, which other copies of it must see. + if behind && stale_under_flights(runs) { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_STALE); + settled += settling.elapsed(); + crate::watch::ask_once(&ranges); + } + } else if behind && stale_under_flights(runs) { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_STALE); + settled += settling.elapsed(); + } + part = prep_part(0, part); for list in runs { list.run_deferred(&mut batch); firsts.push(lists.len()); @@ -701,56 +7808,144 @@ impl Host { } lists.push(list.list.cast().ok()); } + part = prep_part(1, part); batch.flush(); + crate::watch::ask_once_end(); + part = prep_part(2, part); + // The pass over the view heap, if it ran beside: done before any + // list of this submission goes to the card. + if beside { + crate::descriptor::sync_end(); + } + // The snapshots of the ranges shaders may write, if they were left + // for now (`crate::shadow::wide_back`): the refreshes are done, the + // lists have not gone to the card. + { + #[cfg(feature = "diagnostics")] + let snapshots = std::time::Instant::now(); + crate::shadow::take_snapshots(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64); + } + // Copies in the card's memory: what changed on their CPU side goes + // up ahead of the lists, and a compare of what the shaders may + // write follows them in the same submission. + let flown = late && relay(); + if flown && self.card_results_low() { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_MOST); + settled += settling.elapsed(); + } + part = prep_part(3, part); + let card = self.card_before(runs, flown, *submitted); + // Try 6.13, from trustno1-coder/VIctory-NVIDIA d1fe0bd0 (Jeremy + // Goldberg): the compare goes to the queue on its own, after the + // lists. A title list can leave a buffer promoted to COPY_DEST, and + // buffers decay to COMMON only between ExecuteCommandLists calls: in + // the same call the compare read them in the wrong state (D3D12 + // error 538, a fault NVIDIA's driver may take the card down for). + let check = card.as_ref().and_then(|c| c.check.clone()).map(|list| [Some(list)]); + prep_part(4, part); let prepared = std::time::Instant::now(); - // Each run's lists go to the queue on their own, one submission - // each. The host resets a device whose submission runs for about - // 2 s (TDR); with the world streaming, one submission of every list - // comes close to that (0.5 to 1.8 s seen), while the lists are each - // well under it. They are waited for once, after the last; with - // diagnostics timing (`VICTORY_GPU_TIMING`) each on its own. - let groups: Vec<&[Option<ID3D12CommandList>]> = firsts - .iter() - .zip(firsts.iter().skip(1).chain([&lists.len()])) - .map(|(&a, &b)| &lists[a..b]) - .collect(); + if late { + *submitted += 1; + // SAFETY: closed lists; the fence is ours. + let signalled = unsafe { + if !lists.is_empty() { + self.queue.ExecuteCommandLists(&lists); + } + if let Some(check) = &check { + self.queue.ExecuteCommandLists(check); + } + self.queue.Signal(&self.fence, *submitted) + }; + self.card_sent(); + prep_part(5, prepared); + if let Err(e) = signalled { + fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); + } + let back = declared_writes(runs); + let mut texture_back_ranges = Vec::new(); + for list in runs { + texture_back_ranges.extend(list.deferred().texture_backs.iter().map(crate::texback::Back::range)); + } + let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); + submission_us(0, (prepared - started).saturating_sub(settled).as_micros() as u64); + submitting(0, 0); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_ends(lock); + let sent = Sent { + number: this_submission, + card, + back, + texture_back_ranges, + writes, + }; + working(was_working); + return Some((submitted, sent)); + } + // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`). #[cfg(feature = "diagnostics")] - let wait_each = timing(); + let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() { + firsts + .iter() + .zip(firsts.iter().skip(1).chain([&lists.len()])) + .map(|(&a, &b)| &lists[a..b]) + .collect() + } else { + vec![&lists[..]] + }; #[cfg(not(feature = "diagnostics"))] - let wait_each = false; + let groups = [&lists[..]]; + submitting(2, runs.len()); for (i, group) in groups.iter().enumerate() { + *submitted += 1; let started = std::time::Instant::now(); // SAFETY: closed lists; the fence and event are ours. unsafe { - self.queue.ExecuteCommandLists(group); - if wait_each || i + 1 == groups.len() { - *submitted += 1; - let waited = self - .queue - .Signal(&self.fence, *submitted) - .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); - match waited { - Ok(()) => { - WaitForSingleObject(self.event, INFINITE); - } - Err(e) => tracing::warn!(error = %e, "host submission not waited for"), + if !group.is_empty() { + self.queue.ExecuteCommandLists(group); + } + if i + 1 == groups.len() + && let Some(check) = &check + { + self.queue.ExecuteCommandLists(check); + } + self.card_sent(); + let waited = self + .queue + .Signal(&self.fence, *submitted) + .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); + match waited { + Ok(()) => { + working(false); + WaitForSingleObject(self.event, INFINITE); + stood(started); + working(true); } + Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } } + // With timing on each group is one of `runs` (and the compare + // of copies in the card's memory, with the last): every + // command's time on the card goes to the sums by pipeline. #[cfg(feature = "diagnostics")] - if wait_each && started.elapsed() > std::time::Duration::from_millis(50) { + if timing() { // SAFETY: a plain query. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); - let commands = runs[i] - .notes - .lock() - .unwrap_or_else(|e| e.into_inner()) - .len(); - tracing::warn!( - ms = started.elapsed().as_millis(), - commands, - "slow host list" - ); + for (ms, op) in runs[i].slowest(frequency, usize::MAX) { + crate::copystat::command_took(&op, ms); + } + } + // A submission of one list was never named here (`groups.len() + // > 1` was the test): the two 50 ms lists of the gameplay + // frame, each a submission of its own, printed nothing. + #[cfg(feature = "diagnostics")] + if timing() && started.elapsed() > std::time::Duration::from_millis(50) { + // SAFETY: a plain query. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); + let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len(); + tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list"); for (ms, op) in runs[i].slowest(frequency, 6) { tracing::warn!("slow list command, {ms:.1} ms: {op}"); } @@ -761,25 +7956,24 @@ impl Host { FINISHED.store(this_submission, Ordering::Release); bury(this_submission); let gpu = prepared.elapsed(); - SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); - SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + submission_us(0, (prepared - started).as_micros() as u64); + submission_us(1, gpu.as_micros() as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::card_waited(gpu.as_micros() as u64, || { + let pipelines: std::collections::BTreeSet<String> = runs + .iter() + .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone()) + .collect(); + let text = format!("{} lists, pipelines {pipelines:?}", runs.len()); + text.chars().take(1200).collect() + }); // The host resets a device whose submission runs for about 2 s. if gpu > std::time::Duration::from_millis(250) { let pipelines: std::collections::BTreeSet<String> = runs .iter() - .flat_map(|l| { - l.pipelines - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clone() - }) + .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone()) .collect(); - tracing::warn!( - ms = gpu.as_millis(), - lists = runs.len(), - ?pipelines, - "slow host submission" - ); + tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission"); } // SAFETY: a plain query. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { @@ -790,47 +7984,56 @@ impl Host { last_notes(runs) )); } + submitting(3, runs.len()); // What shaders wrote goes back before the bottom-of-pipe writes, // which tell the title the GPU is done; each range once per // submission, however many dispatches declared it (the world's // passes declare the same big ranges dozens of times). let copying = std::time::Instant::now(); - for (shadow, address, len) in batch.gpu_writes { - let written = shadow.copy_back(address, len); - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + // For copies in the card's memory the compare has run there: the + // pieces that differ are fetched and merged. + if let Some(card) = &card { + self.card_back(card, &mut submitted, &mut std::collections::HashSet::new()); } - for list in runs { - for rb in &list.deferred().readbacks { - let written = if rb.dst_pitch == rb.src_pitch { - crate::watch::writing(rb.dst, rb.total); - write_mapped(rb.dst as *mut u8, rb.src as *const u8, rb.total); - rb.total - } else { - let mut n = 0; - for line in 0..rb.lines { - let to = rb.dst + line * rb.dst_pitch; - let from = rb.src + line * rb.src_pitch; - crate::watch::writing(to, rb.row_bytes); - write_mapped(to as *mut u8, from as *const u8, rb.row_bytes); - n += rb.row_bytes; - } - n - }; - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); - } + let back = declared_writes(runs); + hand_back(&back); + if let Some(card) = card { + self.card_done(card); + } + #[cfg(feature = "diagnostics")] + if !back.is_empty() { + crate::copystat::add(crate::copystat::C::BackSubmissions, 1); } - COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); - // Queues these writes release run their work once no lock is held: - // it submits lists itself (this lock, the lists' `deferred`). - let mut woken = crate::fence::Woken::default(); + // Nothing of this submission goes back to the title: no range of + // shader writes, no value written when it is done. The wait for + // such a one is only for order and for what the card still holds. + #[cfg(feature = "diagnostics")] + if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) { + use crate::copystat::{C, add}; + add(C::NothingBack, 1); + add(C::NothingBackUs, gpu.as_micros() as u64); + } + copy_back(0, copying.elapsed().as_micros() as u64); for list in runs { + // Read backs first: a value written at the bottom of the pipe + // may be what tells the title that they are there. + read_backs(list); for &(at, what, bytes) in &list.deferred().writes { - woken.add(what.write(at as *mut u8, bytes)); + what.write(at as *mut u8, bytes); } } self.log_messages(); - drop(submitted); - woken.run(); + submitting(0, 0); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_ends(lock); + // With the relay: nothing is in the air now, so no fetch still to + // be merged is older than the sends to card copies so far, and + // their notes can go. + if relay() { + crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + } + working(was_working); + None } /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations @@ -839,26 +8042,83 @@ impl Host { /// at and what the draws and dispatches in flight there run (or, in /// lists that never started, the pipelines they bind). fn removal_data(&self, runs: &[&HostList]) -> String { - // Without it the queries fail as unsupported, which reads like a - // missing GPU feature. - if !dred_on() { - return "; a diagnostics build with VICTORY_D3D12_DRED=1 records where the GPU stopped" - .to_owned(); - } + self.removal_data_of(runs, true) + } + + /// [`Host::removal_data`]; `tables`: whether a faulting address is also + /// looked up in our own tables (title memory copies, view heaps), which + /// takes their locks. + /// + /// With the data on in any form ([`Dred`]) the report says each of its + /// three parts whatever the runtime answered: why the device went, the + /// page fault (an address, none reported, or the call failed) and the + /// breadcrumbs (how many lists the runtime returned, none, or the call + /// failed). Run 277's report had neither a fault nor a breadcrumb, and + /// nothing in it said whether the runtime had been asked in vain. + fn removal_data_of(&self, runs: &[&HostList], tables: bool) -> String { + DATA_SAID.store(true, Ordering::Relaxed); + let said = dred_any(); let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else { - return String::new(); + return if said { + "; device-removed data: this device has no interface for it".to_owned() + } else { + String::new() + }; }; let mut text = String::new(); + // Whatever the runtime says: which lists in the air bind a pipeline + // this run had not drawn with before. + if !runs.is_empty() { + text.push_str(&first_uses_text(runs, true)); + } let mut fault_va = None; + if said { + // SAFETY: a plain query. + let reason = match unsafe { self.device.GetDeviceRemovedReason() } { + Ok(_) => "none, the device is not removed".to_owned(), + Err(e) => format!("{:#010X}", e.code().0), + }; + text.push_str(&format!( + "; device-removed data ({}): removal reason {reason}; {} host objects named, {} of them made while frames are drawn", + dred_mode().text(), + NAMED[0].load(Ordering::Relaxed), + NAMED[1].load(Ordering::Relaxed) + )); + // The runtime can classify a removal even when it supplies no + // fault address. Older runtimes still have the DRED1 report below. + match dred.cast::<ID3D12DeviceRemovedExtendedData2>() { + Ok(dred2) => { + // SAFETY: a query on the live DRED interface. + let state = unsafe { dred2.GetDeviceState() }; + let name = match state { + D3D12_DRED_DEVICE_STATE_HUNG => "hung", + D3D12_DRED_DEVICE_STATE_FAULT => "fault", + D3D12_DRED_DEVICE_STATE_PAGEFAULT => "page fault", + D3D12_DRED_DEVICE_STATE_UNKNOWN => "unknown", + _ => "unrecognized", + }; + text.push_str(&format!("; DRED device state {name} ({})", state.0)); + } + Err(e) => text.push_str(&format!("; DRED device state unavailable ({:#010X})", e.code().0)), + } + } // SAFETY: the outputs are the runtime's, valid while the device // lives; nodes are walked as linked, histories have their counts. unsafe { - if let Ok(fault) = dred.GetPageFaultAllocationOutput1() + let fault = dred.GetPageFaultAllocationOutput1(); + // Said either way: no address, or no answer at all. + match &fault { + Ok(f) if said && f.PageFaultVA == 0 => text.push_str("; page fault: no fault address reported"), + Err(e) if said => text.push_str(&format!("; page fault: the call failed ({e})")), + _ => {} + } + if let Ok(fault) = fault && fault.PageFaultVA != 0 { let va = fault.PageFaultVA; fault_va = Some(va); text.push_str(&format!("; page fault at {va:#x}")); + let mut found = 0; for (what, head) in [ ("inside", fault.pHeadExistingAllocationNode), ("inside freed", fault.pHeadRecentFreedAllocationNode), @@ -877,21 +8137,46 @@ impl Host { node = n.pNext; } if !names.is_empty() { + found += names.len(); text.push_str(&format!("; {what} {names:?}")); } } - text.push_str(&crate::shadow::near(va)); - text.push_str(&crate::descriptor::host::near_heaps(va)); + if found == 0 { + text.push_str("; inside no allocation the runtime lists, alive or freed lately"); + } + if tables { + text.push_str(&crate::shadow::near(va)); + text.push_str(&crate::descriptor::host::near_heaps(va)); + } + } + // `faults` keeps no breadcrumbs: none are asked for. + if dred_mode() == Dred::Faults { + text.push_str("; breadcrumbs: not kept in this form"); + return text; } // The plain output: the extended one (with marker texts) came // back without stopped lists on this host. - let crumbs = match dred.GetAutoBreadcrumbsOutput() { + let mut crumbs = match dred.GetAutoBreadcrumbsOutput() { Ok(crumbs) => crumbs, Err(e) => { - text.push_str(&format!("; no breadcrumbs ({e})")); + if said { + text.push_str(&format!("; breadcrumbs: the call failed ({e})")); + } else { + text.push_str(&format!("; no breadcrumbs ({e})")); + } return text; } }; + // An empty list within a millisecond of the removal (run 277): + // asked again for half a second before it is believed. + let mut asked = 0u32; + while said && crumbs.pHeadAutoBreadcrumbNode.is_null() && asked < 10 { + std::thread::sleep(std::time::Duration::from_millis(50)); + asked += 1; + if let Ok(again) = dred.GetAutoBreadcrumbsOutput() { + crumbs = again; + } + } // Every list's progress (done/count), in the runtime's order. let mut progress = Vec::new(); let mut node = crumbs.pHeadAutoBreadcrumbNode; @@ -902,6 +8187,18 @@ impl Host { progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount)); node = p.pNext; } + if said { + let again = if asked > 0 { + format!(", asked {asked} more times over {} ms", asked * 50) + } else { + String::new() + }; + if progress.is_empty() { + text.push_str(&format!("; breadcrumbs: the runtime returned none (nodes 0{again})")); + } else { + text.push_str(&format!("; breadcrumbs: data returned (nodes {}{again})", progress.len())); + } + } text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}")); let mut plain = crumbs.pHeadAutoBreadcrumbNode; while let Some(p) = plain.as_ref() { @@ -936,15 +8233,82 @@ impl Host { let _ = fault_va; if done > 0 { text.push_str(&in_flight(history, &markers, done as usize)); - } else if let Some(r) = run { + } + // A list that never started; and in `light`, where no + // marker says what a command runs, every stopped list. + if (done == 0 || dred_mode() == Dred::Light) + && let Some(r) = run + { let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner()); text.push_str(&format!(", its pipelines {pipelines:?}")); } } - plain = p.pNext; + plain = p.pNext; + } + } + text + } + + /// With the frame line (`VICTORY_D3D12_DEBUG=1`, diagnostics builds): + /// the debug layer's messages since the last call go to our log, the + /// first five of each kind in full, the rest counted, with one line of + /// the counts by kind. + /// + /// They were only read when the device was lost ([`fail`]): a run that + /// survived (run 205) said nothing of what the layer had found, and + /// what it finds is what a driver's fault would have to be traced back + /// to (an object let go while the card uses it, a resource in the + /// wrong state, a view of something gone). + pub(crate) fn drain_messages(&self) { + let Some(queue) = &self.messages else { + return; + }; + static SEEN: Mutex<std::collections::BTreeMap<i32, (u64, i32)>> = Mutex::new(std::collections::BTreeMap::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: each message is read into a buffer of the size the queue + // reports, then the queue is emptied. + let stored = unsafe { + let stored = queue.GetNumStoredMessages(); + for i in 0..stored { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() { + let m = &*message; + let kind = seen.entry(m.ID.0).or_insert((0, m.Severity.0)); + kind.0 += 1; + if kind.0 <= 5 { + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = String::from_utf8_lossy(text); + let text = text.trim_end_matches('\0'); + tracing::warn!(id = m.ID.0, severity = m.Severity.0, nth = kind.0, "D3D12 debug layer: {text}"); + } + } } + queue.ClearStoredMessages(); + stored + }; + if stored > 0 { + let counts: Vec<String> = seen.iter().map(|(id, (n, severity))| format!("id {id} (severity {severity}) x{n}")).collect(); + tracing::info!( + "D3D12 debug layer messages so far by kind (severity 0 corruption, 1 error, 2 warning, 3 info, 4 message): {}", + counts.join(", ") + ); } - text + } + + /// The host device (`crate::cardmeter`). + pub(crate) fn device(&self) -> &ID3D12Device { + &self.device + } + + /// Ticks a second of the queue's timestamps; 0 if it has none. + pub(crate) fn timestamp_frequency(&self) -> u64 { + // SAFETY: a plain query. + unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(0) } /// Moves the debug layer's messages into our log; returns the first @@ -980,14 +8344,15 @@ impl Host { first_error } - /// A host render target view, valid until it is recorded. + /// A host render target view of `resource`, valid until it is recorded. pub(crate) fn rtv( &self, resource: Option<&ID3D12Resource>, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>, ) -> D3D12_CPU_DESCRIPTOR_HANDLE { let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING; - // SAFETY: a slot of our heap and a live resource or a typed null view. + // SAFETY: a slot of our heap and a live resource, or none with a + // description (a typed null view). unsafe { let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart(); handle.ptr += (slot * self.rtv_size) as usize; @@ -1016,41 +8381,6 @@ impl Host { } impl HostList { - /// Keeps `blocks` (memory handed out for the recording) until the list - /// finishes executing and is recycled or dropped. - pub(crate) fn keep_uploads(&self, blocks: Vec<Vec<u8>>) { - if !blocks.is_empty() { - self.kept_uploads - .lock() - .unwrap_or_else(|e| e.into_inner()) - .extend(blocks); - } - } - - /// Keeps dynamic descriptor slots alive until this host list finishes - /// executing and is recycled or dropped. - pub(crate) fn keep_dynamic(&self, slots: Vec<(usize, u32, u32)>) { - if !slots.is_empty() { - self.kept_dynamic - .lock() - .unwrap_or_else(|e| e.into_inner()) - .extend(slots); - } - } - - /// Frees kept upload blocks and returns kept dynamic descriptor slots. - fn release_kept(&self) { - self.kept_uploads - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clear(); - let dynamic = - std::mem::take(&mut *self.kept_dynamic.lock().unwrap_or_else(|e| e.into_inner())); - for (heap, first, n) in dynamic { - crate::descriptor::release_dynamic(heap, first, n); - } - } - /// The timestamp heap and its read-back buffer (diagnostics, timing on). #[cfg(feature = "diagnostics")] fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> { @@ -1062,20 +8392,14 @@ impl HostList { let device = &host()?.device; let mut heap: Option<ID3D12QueryHeap> = None; let mut back: Option<ID3D12Resource> = None; - let readback = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_READBACK, - ..Default::default() - }; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: u64::from(STAMPS) * 8, Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; @@ -1083,11 +8407,7 @@ impl HostList { unsafe { device .CreateQueryHeap( - &D3D12_QUERY_HEAP_DESC { - Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, - Count: STAMPS, - NodeMask: 0, - }, + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 }, &mut heap, ) .ok()?; @@ -1116,10 +8436,7 @@ impl HostList { return Vec::new(); }; let mut data = std::ptr::null_mut(); - let range = D3D12_RANGE { - Begin: 0, - End: (count + 1) * 8, - }; + let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 }; // SAFETY: a read-back buffer the finished list resolved into. let stamps: Vec<u64> = unsafe { if back.Map(0, Some(&range), Some(&mut data)).is_err() { @@ -1132,10 +8449,7 @@ impl HostList { let mut times: Vec<(f64, String)> = (0..count) .map(|i| { let ticks = stamps[i + 1].saturating_sub(stamps[i]); - ( - ticks as f64 * 1e3 / frequency.max(1) as f64, - notes[i].0.chars().take(300).collect(), - ) + (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect()) }) .collect(); times.sort_by(|a, b| b.0.total_cmp(&a.0)); @@ -1144,15 +8458,64 @@ impl HostList { } pub(crate) fn close(&self) { + // The copies below write buffers on the card: no draw after them joins a window. + crate::indirect::end_window(self); + // Host queries begun in this list and never ended here: ended now, answered "visible". + let open = std::mem::take(&mut *self.open_queries.lock().unwrap_or_else(|e| e.into_inner())); + if !open.is_empty() { + crate::query::close_open(open, self); + } + self.twins_to_depth(); + self.textures_back(); + let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some((scratch, _)) = scratch { + self.indirect_common(&scratch); + } + self.card_budget_out(); + // The scratch buffers its prelude fills and leaves readable as + // arguments: common again behind the list, as every scratch buffer. + { + let mut gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + for set in gather.sets.iter().filter(|s| s.records() > 0) { + // SAFETY: an open list and a live buffer. + unsafe { + self.list.ResourceBarrier(&[transition( + &set.scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + } + // The segments' slots likewise; the last segment ends here. + gather.segments.open.clear(); + if gather.segments.used + && let Some(buffer) = &gather.segments.buffer + { + // SAFETY: an open list and a live buffer. + unsafe { + self.list.ResourceBarrier(&[transition( + buffer, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + } + } + crate::cardmeter::end(&self.list, crate::cardmeter::Span::from_raw(self.pipeline_meter.swap(u32::MAX, Ordering::Relaxed))); + crate::cardmeter::end_named( + &self.list, + crate::cardmeter::Span::from_raw(self.meter.swap(u32::MAX, Ordering::Relaxed)), + &self.pipelines.lock().unwrap_or_else(|e| e.into_inner()), + ); + #[cfg(feature = "diagnostics")] + crate::shot::close(self); #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { - let count = - (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); + let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); // SAFETY: an open list, our heap and read-back buffer. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count); - self.list - .ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); + self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); } } // SAFETY: our list. @@ -1166,25 +8529,54 @@ impl HostList { /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { - self.release_kept(); - *self.deferred() = Deferred::default(); - self.states - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clear(); - self.pipelines - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clear(); + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + self._alive.used(); + *self.clamp_window.lock().unwrap_or_else(|e| e.into_inner()) = None; + // Every submission of the list has run: its upload buffers go back + // for the next list's copies. + let uploads = { + let mut deferred = self.deferred(); + let uploads = std::mem::take(&mut deferred.uploads); + ALIVE[6].fetch_sub(uploads.len() as u64, Ordering::Relaxed); + ALIVE[7].fetch_sub(deferred.upload_bytes, Ordering::Relaxed); + deferred.upload_bytes = 0; + *deferred = Deferred::default(); + uploads + }; + give_uploads(uploads); + self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); + { + let mut gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + let Gather { closed, written, sets, spare, segments, .. } = &mut *gather; + *closed = false; + written.clear(); + segments.used = false; + segments.passes = 0; + segments.open.clear(); + for set in sets.drain(..) { + if spare.len() < GATHER_SETS { + spare.push(set.into_scratch()); + } + } + } #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); + #[cfg(feature = "diagnostics")] { - let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); - (scratch.current, scratch.used) = (0, 0); + *self.shot_block.lock().unwrap_or_else(|e| e.into_inner()) = (0, 0, 0); + *self.shot_mark.lock().unwrap_or_else(|e| e.into_inner()) = (0, 0); } { - let mut rect = self.rect_scratch.lock().unwrap_or_else(|e| e.into_inner()); - (rect.counter_chunk, rect.counter_used) = (0, 0); + let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + (scratch.current, scratch.used) = (0, 0); + // Every submission of the list has run: nothing reads its + // scratch memory any more, and the next list to ask takes it. + if scratch_pool() { + give_chunks(std::mem::take(&mut scratch.chunks)); + } } // SAFETY: the list is not executing. let reset = unsafe { @@ -1195,6 +8587,19 @@ impl HostList { if let Err(e) = reset { fail(format_args!("a host command list did not reset ({e})")); } + self.meter + .store(crate::cardmeter::begin(&self.list, crate::cardmeter::Kind::Lists).raw(), Ordering::Relaxed); + // A frame shot tells the lists begun inside its frame from the ones + // it found half recorded, and times each from its very start: what + // the card does in a list before the title's first command is the + // list's too. + #[cfg(feature = "diagnostics")] + if crate::shot::keeping_lines() { + crate::shot::stamp(self); + crate::shot::line(std::ptr::from_ref(self) as usize, "LIST BEGINS"); + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); } /// Moves a title texture's host copy to `wanted` (a host state) in this @@ -1209,60 +8614,400 @@ impl HostList { let texture = crate::resource::host_resource(resource)?; let copy = crate::resource::host_copy(resource)?; let wanted = legal_state(texture, wanted); + // A frame shot names its pictures after the title's textures. + #[cfg(feature = "diagnostics")] + if crate::shot::recording() { + crate::shot::known(std::sync::Arc::as_ptr(©) as usize, resource as usize); + } + let before = { + let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + match states.entry(std::sync::Arc::as_ptr(©) as usize) { + std::collections::hash_map::Entry::Vacant(v) => { + v.insert((wanted, wanted, copy.clone())); + None + } + std::collections::hash_map::Entry::Occupied(mut o) => Some(std::mem::replace(&mut o.get_mut().1, wanted)), + } + }?; + if before == wanted { + return None; + } + // A frame shot copies a texture where it leaves a state shaders + // write in, and leaves it in that state: the caller's move is the + // same as in any other frame. + #[cfg(feature = "diagnostics")] + if crate::shot::recording() { + crate::shot::leaves(&self.list, std::ptr::from_ref(self) as usize, Some(self), None, ©, before, wanted); + } + Some((texture, before)) + } + + /// Moves host texture `copy` to `wanted` (a host state) in this list, + /// as [`HostList::transition`] does a title resource's host copy, and + /// records the barrier: for textures that are not a title resource's + /// host copy (colour twins) and for the copies between the two. + fn settle(&self, copy: &std::sync::Arc<crate::resource::HostTexture>, wanted: u32) { + let wanted = legal_state(©.texture, wanted); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - match states.entry(std::sync::Arc::as_ptr(©) as usize) { + let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) { std::collections::hash_map::Entry::Vacant(v) => { - v.insert((wanted, wanted, copy)); + v.insert((wanted, wanted, copy.clone())); None } std::collections::hash_map::Entry::Occupied(mut o) => { let before = std::mem::replace(&mut o.get_mut().1, wanted); - (before != wanted).then_some((texture, before)) + (before != wanted).then_some(before) } + }; + drop(states); + if let Some(before) = before { + let barrier = transition( + ©.texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(wanted as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { self.list.ResourceBarrier(&[barrier]) }; } } - /// The current state established by this list. A texture the list has - /// never used can arrive in a different state at submission. - pub(crate) fn tracked_texture_state( + /// A use of title texture `resource` about to be recorded, if it is a + /// depth texture with a colour twin (false if it is not): of the twin + /// (`colour`: unordered access) or of the depth texture (depth target, + /// clear, shader read, copy, resolve), writing it or only reading. The + /// side used is first brought up to date: by a copy recorded here if + /// this list wrote the other side since, by the list's prelude if the + /// list uses the side as it finds it. The twin is left in the + /// unordered access state; the caller moves the depth texture to the + /// state its use needs, as for any texture. A twin still ahead when the + /// list closes is copied then (`twins_to_depth`). + /// shortcut: every depth target bound for a draw counts as written + /// (also when the draw only tests), and every unordered access view a + /// shader names as written; views a shader picks from the heap by a + /// computed index are not seen here at all. + pub(crate) fn twin_use( &self, - copy: &std::sync::Arc<crate::resource::HostTexture>, - ) -> Option<u32> { - self.states - .lock() - .unwrap_or_else(|e| e.into_inner()) - .get(&(std::sync::Arc::as_ptr(copy) as usize)) - .map(|&(_, last, _)| last) + resource: crate::object::This, + colour: bool, + write: bool, + ) -> bool { + const UNORDERED_ACCESS: u32 = 0x8; + // Asked for every texture a draw reads: most have no twin. + let Some(twin) = crate::resource::twin(resource) else { + return false; + }; + let Some(depth) = crate::resource::host_copy(resource) else { + return false; + }; + let side = usize::from(colour); + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + let u = twins + .entry(std::sync::Arc::as_ptr(&twin) as usize) + .or_insert_with(|| TwinUse { + depth: depth.clone(), + twin: twin.clone(), + needs: [false; 2], + behind: [None; 2], + writing: false, + late: false, + }); + let copy = match u.behind[side] { + Some(behind) => behind, + None => { + u.needs[side] = true; + false + } + }; + u.behind[side] = Some(false); + match (write, colour) { + // Shaders write the twin when the draw or dispatch runs: what + // the same one reads of the depth texture is prepared before + // (`twins_written`). + (true, true) => u.writing = true, + (true, false) => u.behind[1] = Some(true), + (false, _) => {} + } + // shortcut: the depth plane's twin is not drawn into the plane + // here: the pass sets a pipeline and a target of ours, which a list + // still recording the title's commands cannot take. This use sees + // the plane as it was; the pass runs when the list closes + // (`twins_to_depth`). Counted. + if copy && !colour && twin.plane.is_some() { + u.late = true; + crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed); + } + drop(twins); + if copy { + self.twin_copy(&depth, &twin, colour); + } else if colour { + self.settle(&twin.colour, UNORDERED_ACCESS); + } + // The depth plane's twin is written through unordered access too. + if colour && let Some(plane) = &twin.plane { + self.settle(plane, UNORDERED_ACCESS); + } + true + } + + /// Records the pass that draws the twin of the depth plane of `depth` + /// into the plane, if `twin` has one, with the moves to the states the + /// pass needs; the twin is left in the unordered access state. Only + /// for a list that records nothing of the title's afterwards + /// (`record_plane_pass`). + fn pass_plane( + &self, + depth: &std::sync::Arc<crate::resource::HostTexture>, + twin: &crate::resource::Twin, + ) { + const UNORDERED_ACCESS: u32 = 0x8; + const DEPTH_WRITE: u32 = 0x10; + const PIXEL_SHADER_RESOURCE: u32 = 0x80; + let Some(plane) = &twin.plane else { return }; + self.settle(depth, DEPTH_WRITE); + self.settle(plane, PIXEL_SHADER_RESOURCE); + record_plane_pass(&self.list, &depth.texture, &plane.texture); + self.settle(plane, UNORDERED_ACCESS); + } + + /// Records the copy of a depth texture into its colour twin (`colour`) + /// or of the twin into the depth texture, with the moves to the copy + /// states. The twin is left in the unordered access state. + fn twin_copy( + &self, + depth: &std::sync::Arc<crate::resource::HostTexture>, + twin: &crate::resource::Twin, + colour: bool, + ) { + const UNORDERED_ACCESS: u32 = 0x8; + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let (from, to) = if colour { + (depth, &twin.colour) + } else { + (&twin.colour, depth) + }; + self.settle(from, COPY_SOURCE); + self.settle(to, COPY_DEST); + record_twin_copy(&self.list, &depth.texture, twin, colour); + self.settle(&twin.colour, UNORDERED_ACCESS); + } + + /// Before the list closes: the depth textures whose twins it wrote last + /// are given what was written, and left readable by shaders. Shaders + /// that pick a view from the heap by a computed index are not seen by + /// `twin_use` and read the depth texture in lists that never name it + /// (in a captured frame of the title no table names a shadow + /// map for reading but the pass that fills the next one). + fn twins_to_depth(&self) { + const SHADER_RESOURCE: u32 = 0x40 | 0x80; + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + let written: Vec<_> = twins + .values_mut() + .filter(|u| u.behind[0] == Some(true) || u.late) + .map(|u| { + // Not copied again if the list copied since the last write + // and only the depth plane's pass is left. + let copy = u.behind[0] == Some(true); + u.behind[0] = Some(false); + u.late = false; + (u.depth.clone(), u.twin.clone(), copy) + }) + .collect(); + drop(twins); + for (depth, twin, copy) in &written { + if *copy { + self.twin_copy(depth, twin, false); + } + // Nothing of the title's is recorded after this: the pass may + // leave its own pipeline and target set. + self.pass_plane(depth, twin); + self.settle(depth, SHADER_RESOURCE); + } + } + + /// A draw or dispatch being prepared writes title texture `resource` + /// through unordered access: if it is of a kind copied back + /// ([`crate::texback`]), the list copies it when it closes. + pub(crate) fn texture_written(&self, resource: crate::object::This) { + if !crate::texback::wanted(resource) { + return; + } + let mut deferred = self.deferred(); + if !deferred.back_wanted.iter().any(|target| target.owner() == resource as usize) + && let Some(target) = crate::texback::Target::new(resource) + { + deferred.back_wanted.push(target); + } + } + + /// Before the list closes: the textures its shaders wrote that are copied + /// back go into read-back buffers ([`crate::texback::record`]). + fn textures_back(&self) { + const COPY_SOURCE: u32 = 0x800; + let wanted = std::mem::take(&mut self.deferred().back_wanted); + for target in wanted { + self.settle(&target.copy, COPY_SOURCE); + // With device-removed data in its full form: the copies that + // follow are named in the breadcrumbs (a stop in them read "op + // 8, no marker"). Not otherwise: a note is also a line of a + // listed frame and a stamp of a frame shot. + #[cfg(feature = "diagnostics")] + { + if dred_on() { + self.note_op(|| format!("texture read-back of title texture {:#x} (texback)", target.owner())); + } + } + if let Some(back) = crate::texback::record(&self.list, target) { + self.deferred().texture_backs.push(back); + } + } + } + + /// The draw or dispatch just prepared is recorded: the twins it writes + /// now hold what their depth textures lack. + pub(crate) fn twins_written(&self) { + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + for u in twins.values_mut().filter(|u| u.writing) { + u.writing = false; + u.behind[0] = Some(true); + } } /// At submission: the list that moves each texture this list uses from /// its real state to the one the list starts with; the textures' real - /// states become those the list ends with. + /// states become those the list ends with. For depth textures with a + /// colour twin it first copies the side the list uses as it finds it + /// from the other, if a list submitted earlier left it behind. fn prelude(&self) -> Option<ID3D12CommandList> { + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32); let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); - let barriers: Vec<D3D12_RESOURCE_BARRIER> = states - .values() - .filter_map(|(first, last, copy)| { - let real = copy.state.swap(*last, Ordering::Relaxed); - (real != *first).then(|| { - transition( - ©.texture, - D3D12_RESOURCE_STATES(real as i32), - D3D12_RESOURCE_STATES(*first as i32), - ) - }) - }) - .collect(); - if barriers.is_empty() { + // The copies (depth texture, twin, whether into the twin); the + // sides are then as this list leaves them. + let mut syncs = Vec::new(); + let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + for u in twins.values() { + let real = u.twin.behind.load(Ordering::Relaxed); + let mut behind = [real & 1 != 0, real & 2 != 0]; + for side in [0, 1] { + if u.needs[side] && behind[side] { + syncs.push((u.depth.clone(), u.twin.clone(), side == 1)); + behind = [false; 2]; + } + } + let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side])); + let left = u32::from(left[0]) | (u32::from(left[1]) << 1); + u.twin.behind.store(left, Ordering::Relaxed); + } + drop(twins); + // A copy runs with its textures in the copy states: each moves + // there from its real state, and from there to the state the list + // starts with (back to its real state if the list does not use it). + let mut to_copy = Vec::new(); + let mut barriers = Vec::new(); + let mut copying = std::collections::HashMap::new(); + for (depth, twin, colour) in &syncs { + let (from, to) = if *colour { + (depth, &twin.colour) + } else { + (&twin.colour, depth) + }; + for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] { + let key = std::sync::Arc::as_ptr(texture) as usize; + let real = texture.state.load(Ordering::Relaxed); + copying.insert(key, state); + if real != state { + to_copy.push(transition( + &texture.texture, + host_state(real), + host_state(state), + )); + if !states.contains_key(&key) { + barriers.push(transition( + &texture.texture, + host_state(state), + host_state(real), + )); + } + } + } + } + // A frame shot copies the textures that leave a state shaders write + // in between lists, each before the moves below and left in the + // state it was found in. + #[cfg(feature = "diagnostics")] + let shot_begins = crate::shot::of_the_frame(self); + #[cfg(feature = "diagnostics")] + let mut leaving: Vec<(std::sync::Arc<crate::resource::HostTexture>, u32, u32)> = Vec::new(); + barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| { + let real = copy.state.swap(*last, Ordering::Relaxed); + let real = copying.get(key).copied().unwrap_or(real); + #[cfg(feature = "diagnostics")] + if shot_begins.is_some() && !copying.contains_key(key) && crate::shot::might_leave(real, *first) { + leaving.push((copy.clone(), real, *first)); + } + (real != *first) + .then(|| transition(©.texture, host_state(real), host_state(*first))) + })); + // (The same order in every frame, whatever order the map gives.) + #[cfg(feature = "diagnostics")] + leaving.sort_by_key(|l| std::sync::Arc::as_ptr(&l.0) as usize); + // The records the list's draws read from slots (`crate::indirect::gather`). + let gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + let gathered = gather.sets.iter().any(|s| s.records() > 0); + if barriers.is_empty() && syncs.is_empty() && !gathered { return None; } - let (allocator, list) = &self.prelude; + let Some((allocator, list)) = self + .prelude + .get_or_init(|| host().and_then(|h| h.make_prelude())) + .as_ref() + else { + fail(format_args!("no host list for a state prelude")); + }; // SAFETY: the prelude is not executing (every submission is waited // for); the textures are live. let recorded = unsafe { allocator.Reset().and_then(|()| { list.Reset(allocator, None)?; - list.ResourceBarrier(&barriers); + #[cfg(feature = "diagnostics")] + let shot_span = if shot_begins.is_some() { crate::shot::span_begin(list) } else { u32::MAX }; + if !to_copy.is_empty() { + list.ResourceBarrier(&to_copy); + } + for (depth, twin, colour) in &syncs { + record_twin_copy(list, &depth.texture, twin, *colour); + } + #[cfg(feature = "diagnostics")] + for (copy, real, first) in &leaving { + crate::shot::leaves(list, std::ptr::from_ref(self) as usize, None, shot_begins, copy, *real, *first); + } + if !barriers.is_empty() { + list.ResourceBarrier(&barriers); + } + if gathered { + // The slots must hold clamped records before a draw + // reads them: a prelude that cannot record the passes + // is no prelude. + let filled = match &gather.budget { + Some(budget) => crate::indirect::record_gathers(list, &gather.sets, budget), + None => false, + }; + if !filled { + fail(format_args!("a list's gathered indirect records could not be clamped in its prelude")); + } + } + #[cfg(feature = "diagnostics")] + crate::shot::span_end(list, shot_span, std::ptr::from_ref(self) as usize, || { + format!( + "PRELUDE of the recording that begins at line {}: {} moves of textures, {} copies between a depth texture and its twin, {} sets of gathered draw records clamped", + shot_begins.unwrap_or(0), + barriers.len() + to_copy.len(), + syncs.len(), + gather.sets.iter().filter(|s| s.records() > 0).count() + ) + }); list.Close() }) }; @@ -1272,6 +9017,182 @@ impl HostList { list.cast().ok() } + /// From here on the list gathers no records (`crate::indirect::gather`): + /// what is about to be recorded may write arguments. + pub(crate) fn gather_close(&self) { + let mut gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + gather.closed = true; + gather.segments.open.clear(); + } + + /// What is about to be recorded may write arguments: the segment open now ends + /// (`crate::indirect::gather_segments`), whatever the prelude's gathering does. + pub(crate) fn segments_end(&self) { + self.gather.lock().unwrap_or_else(|e| e.into_inner()).segments.open.clear(); + } + + /// Shaders of the list were declared to write the host copy numbered + /// `copy` (`Shadow::gpu_writes`): with + /// `crate::indirect::gather_by_copy`, no record of that copy is + /// gathered from here on. (Without the switch nothing is noted: the + /// list stops gathering whole, as before.) + pub(crate) fn gather_wrote(&self, copy: u64) { + let mut gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + // Shaders about to write: the open segment ends (`crate::indirect::gather_segments`). + gather.segments.open.clear(); + if crate::indirect::gather_by_copy_kept() { + gather.written.insert(copy); + } + } + + /// A slot for the record at `offset` of the host copy `src` in the + /// scratch buffer the list's prelude fills (`crate::indirect::gather`, + /// which checked the record): the buffer and the slot's place in it. + /// + /// Once the list stopped gathering (whole, or for this copy): with `crate::indirect::gather_segments`, a slot of a + /// pass of the open segment ([`HostList::segment_slot`]; the third value: a pass was recorded for it). + pub(crate) fn gather_slot(&self, src: &ID3D12Resource, src_id: u64, offset: u32, (kind, stride): (u32, u32)) -> Option<(ID3D12Resource, u64, bool)> { + let none = |why: usize| { + crate::indirect::GATHER_NONE[why].fetch_add(1, Ordering::Relaxed); + None + }; + let mut gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + if gather.closed || gather.written.contains(&src_id) { + drop(gather); + if !crate::indirect::gather_segments() { + return none(1); + } + return self.segment_slot(src, src_id, offset, (kind, stride)); + } + let found = gather + .sets + .iter() + .position(|s| s.src_id == src_id && s.kind == kind && s.stride == stride && s.src.as_raw() == src.as_raw()); + let at = match found { + Some(at) => at, + None => { + if gather.sets.len() >= GATHER_SETS { + return none(2); + } + // The prelude zeroes the budget as the list zeroes its own. + if self.list.cast::<ID3D12GraphicsCommandList2>().is_err() { + return none(4); + } + let Some(host) = host() else { + return none(4); + }; + if gather.budget.is_none() { + let Some(budget) = host.uav_buffer(256) else { + return none(4); + }; + name(&budget, || "indirect budget of gathered records".to_owned()); + gather.budget = Some(budget); + } + let scratch = match gather.spare.pop() { + Some(scratch) => scratch, + None => { + let Some(scratch) = host.uav_buffer(u64::from(crate::indirect::GATHER_MOST) * u64::from(crate::indirect::GATHER_STRIDE)) else { + return none(4); + }; + name(&scratch, || "indirect arguments, gathered".to_owned()); + scratch + } + }; + let Some(table) = self.scratch(u64::from(crate::indirect::GATHER_MOST) * 4) else { + gather.spare.push(scratch); + return none(4); + }; + gather.sets.push(crate::indirect::GatherSet::new(src.clone(), src_id, (kind, stride), scratch, table)); + gather.sets.len() - 1 + } + }; + let set = &mut gather.sets[at]; + let Some(slot) = set.slot(offset) else { + return none(3); + }; + Some((set.scratch.clone(), u64::from(slot) * u64::from(stride), false)) + } + + /// [`HostList::gather_slot`] once the list stopped gathering for its prelude (`crate::indirect::gather_segments`): + /// a slot of a pass of the segment open now, or of a pass recorded here for it. None: clamped alone, as before. + fn segment_slot(&self, src: &ID3D12Resource, src_id: u64, offset: u32, (kind, stride): (u32, u32)) -> Option<(ID3D12Resource, u64, bool)> { + use crate::indirect::{GATHER_STRIDE, SEGMENT_PASS, SEGMENT_PASSES, SEGMENT_STATS}; + let fell_back = || { + SEGMENT_STATS[2].fetch_add(1, Ordering::Relaxed); + crate::indirect::GATHER_NONE[1].fetch_add(1, Ordering::Relaxed); + None + }; + let pass_bytes = u64::from(SEGMENT_PASS) * u64::from(GATHER_STRIDE); + let take = |pass: &mut SegmentPass, buffer: &ID3D12Resource| { + let i = pass.records; + pass.records += 1; + // SAFETY: the table holds a count and `SEGMENT_PASS` offsets, in the list's upload memory alive until its + // reset; the card reads it only when the list runs. The count is written last. + unsafe { + let table = pass.table as *mut u32; + table.add(1 + i as usize).write_volatile(offset); + table.write_volatile(pass.records); + } + SEGMENT_STATS[0].fetch_add(1, Ordering::Relaxed); + (buffer.clone(), u64::from(pass.pass) * pass_bytes + u64::from(i) * u64::from(stride)) + }; + { + let mut gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + let Segments { buffer, open, .. } = &mut gather.segments; + if let Some(buffer) = buffer.as_ref() + && let Some(pass) = open + .iter_mut() + .find(|p| p.src_id == src_id && p.kind == kind && p.stride == stride && p.src.as_raw() == src.as_raw() && p.records < SEGMENT_PASS) + { + let (buffer, at) = take(pass, buffer); + return Some((buffer, at, false)); + } + } + // A pass for the record, here: the list's budget first (it may record the budget's zeroing). + let Some(budget) = self.budget() else { + return fell_back(); + }; + let Some(table) = self.scratch(4 + u64::from(SEGMENT_PASS) * 4) else { + return fell_back(); + }; + let mut gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + let segments = &mut gather.segments; + if segments.passes >= SEGMENT_PASSES { + return fell_back(); + } + if segments.buffer.is_none() { + let Some(made) = host().and_then(|h| h.uav_buffer(u64::from(SEGMENT_PASSES) * pass_bytes)) else { + return fell_back(); + }; + name(&made, || "indirect arguments, gathered in segments".to_owned()); + segments.buffer = Some(made); + } + let Some(buffer) = segments.buffer.clone() else { + return fell_back(); + }; + // SAFETY: the list's own upload memory: the count starts at none. + unsafe { (table.1 as *mut u32).write_volatile(0) }; + let before = if segments.used { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT } else { D3D12_RESOURCE_STATE_COMMON }; + let pass = segments.passes; + if !crate::indirect::record_segment(&self.list, (&buffer, before), u64::from(pass) * pass_bytes, budget, src, table.0, (kind, stride)) { + return fell_back(); + } + segments.used = true; + segments.passes += 1; + segments.open.push(SegmentPass { src: src.clone(), src_id, kind, stride, pass, records: 0, table: table.1 as usize }); + let passes = SEGMENT_STATS[1].fetch_add(1, Ordering::Relaxed) + 1; + if passes.is_power_of_two() { + tracing::info!( + "segments so far (VICTORY_GATHER_SEGMENTS): {passes} passes took {} records (records per pass is what it saves), {} found no room and were clamped alone", + SEGMENT_STATS[0].load(Ordering::Relaxed) + 1, + SEGMENT_STATS[2].load(Ordering::Relaxed) + ); + } + let last = segments.open.len() - 1; + let (buffer, at) = take(&mut segments.open[last], &buffer); + Some((buffer, at, true)) + } + /// Notes what the command about to be recorded does, as a marker /// command whose text the list keeps (diagnostics, with device-removed /// data on): the report pairs the breadcrumbs' marker commands with the @@ -1290,35 +9211,99 @@ impl HostList { #[cfg(feature = "diagnostics")] fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) { - if dred_on() { + // A frame shot times the command: the card's clock before it. + crate::shot::stamp(self); + // Only the full form of device-removed data goes on: `light` and + // `faults` make no text and set no marker, as with the data off. + if !dred_on() { + crate::capture::op(std::ptr::from_ref(self) as usize, what); + return; + } + { + let started = std::time::Instant::now(); let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32; - if let Some((heap, _)) = self.stamps() - && at < STAMPS - 1 - { + if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 { // SAFETY: an open list and our query heap. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) }; } let what = what(); + crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone()); let text: Vec<u16> = what.encode_utf16().chain([0]).collect(); const UNICODE: u32 = 0; // SAFETY: an open list; the marker is copied when recorded. unsafe { - self.list - .SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32) + self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32) }; self.notes .lock() .unwrap_or_else(|e| e.into_inner()) .push((what, range)); + crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64); + } + } + + /// Whether nothing recorded since the list was opened does any work: + /// no draw or dispatch (the first keeps its pipeline), no copy, clear, + /// upload or resolve (they defer a step or move a texture's state), no + /// bottom-of-pipe write. State set on the list does not count. + pub(crate) fn untouched(&self) -> bool { + { + let deferred = self.deferred(); + if !(deferred.copies.is_empty() + && deferred.uploads.is_empty() + && deferred.kept.is_empty() + && deferred.textures.is_empty() + && deferred.writes.is_empty() + && deferred.backs.is_empty() + && deferred.texture_backs.is_empty()) + { + return false; + } } + self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty() } - /// Notes a pipeline the list binds. + /// Notes a pipeline the list binds; called where it is bound. pub(crate) fn used_pipeline(&self, name: &str) { - let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); - if !pipelines.contains(name) { - pipelines.insert(name.to_owned()); + { + let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); + if !pipelines.contains(name) { + pipelines.insert(name.to_owned()); + } + } + if crate::cardmeter::pipelines() { + // The pipeline before it ends here on the card's clock. + crate::cardmeter::end(&self.list, crate::cardmeter::Span::from_raw(self.pipeline_meter.swap(u32::MAX, Ordering::Relaxed))); + self.pipeline_meter.store(crate::cardmeter::begin_named(&self.list, name).raw(), Ordering::Relaxed); + } + } + + /// With [`list_reuse`]: whether this is the first time since the reset + /// that the list binds the host pipeline at `pipeline` (its interface + /// pointer). The list keeps the pipeline from its first bind to its + /// reset, so the address names the same one until then, and a later + /// bind need not keep it and its root signature again. + pub(crate) fn first_bind(&self, pipeline: usize) -> bool { + self.deferred().bound.insert(pipeline) + } + + /// With [`list_reuse`]: the host GPU address of `len` bytes of upload + /// memory holding the title memory at `src` as of the list's + /// submission: one copy for every ask until a `Copy` or `Run` step + /// intervenes (every fill reads at the submission, in step order, so a + /// second fill of the same bytes with neither between them would read + /// what the first did). + pub(crate) fn fill_scratch(&self, src: *const u8, len: u64) -> Option<u64> { + let key = (src as usize, len as usize); + let found = self.deferred().filled.get(&key).copied(); + if let Some(gpu) = found { + return Some(gpu); } + let (gpu, to) = self.scratch(len)?; + self.defer_fill(to, src, len as usize); + self.deferred().filled.insert(key, gpu); + Some(gpu) } fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> { @@ -1328,10 +9313,34 @@ impl HostList { /// Copies `len` bytes from `src` to `dst` when the list is submitted. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) { let mut deferred = self.deferred(); + COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed); + // A copy that goes on where the one recorded just before it ended, + // source and destination both: with `join_copies` the two are one + // step. + if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut() + && continues((*d, *s, *n), (dst as usize, src as usize, len)) + { + COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed); + if join_copies() { + *n += len; + return; + } + } deferred .copies .push(Step::Copy(dst as usize, src as usize, len)); deferred.refreshed.clear(); + deferred.epoch += 1; + if list_reuse_set() { + deferred.filled.clear(); + } + } + + /// How many steps that write title memory the list has recorded so + /// far: two fills of the same title bytes recorded at the same count + /// copy the same bytes when the list is submitted. + pub(crate) fn title_epoch(&self) -> u64 { + self.deferred().epoch } /// Copies `len` bytes of title memory at `src` into the list's upload @@ -1373,52 +9382,65 @@ impl HostList { .push(Step::GpuWrite(shadow.clone(), address, len)); } + /// A read back: once the list has run, `rows` rows of `row` bytes go + /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`) + /// to title memory at `dst`, pitched `pitch`. The buffer lives until + /// the list is reset. + pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) { + self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch])); + } + /// Stores `what` (`bytes` of it) at `dst` once the list has run. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) { self.deferred().writes.push((dst as usize, what, bytes)); } - /// Copies a GPU texture readback from `src` into title memory at `dst` - /// once the list has finished running on the host GPU. - #[allow(clippy::too_many_arguments)] - pub(crate) fn defer_readback( - &self, - dst: *mut u8, - src: *const u8, - dst_pitch: usize, - src_pitch: usize, - lines: usize, - row_bytes: usize, - total: usize, - ) { - self.deferred().readbacks.push(Readback { - dst: dst as usize, - src: src as usize, - dst_pitch, - src_pitch, - lines, - row_bytes, - total, - }); + /// Whether the list, once it has run, stores at `address` a value of + /// `bytes` bytes or more for which `holds` says yes (one of its + /// bottom-of-pipe writes, as [`late_met`] reads them of a flight). + pub(crate) fn will_write(&self, address: usize, bytes: usize, holds: impl Fn(u64) -> bool) -> bool { + self.deferred() + .writes + .iter() + .any(|(at, what, n)| *at == address && *n >= bytes && matches!(what, crate::queue::Written::Value(v) if holds(*v))) } /// A mapped upload buffer of `size` bytes, alive until the list is /// reset. /// - /// shortcut: one buffer per copy; pool them once uploads are frequent. - pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { - let (buffer, data) = host.upload_buffer(size)?; - name(&buffer, || format!("list upload {size:#x}")); - self.deferred().uploads.push(buffer.clone()); + /// An upload buffer of the size class of `size` ([`upload_class`]), one + /// a list gave back at its reset if there is one, else made; held by + /// the list until its reset, then kept for the next. `None` without the + /// pool, past the classes, or refused. + fn kept_upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let class = upload_class(size).filter(|_| upload_pool())?; + let kept = UPLOAD_SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(class); + let (buffer, data) = match kept { + Some(KeptUpload(buffer, data)) => { + UPLOAD_REUSE[0].fetch_add(1, Ordering::Relaxed); + (buffer, data as *mut u8) + } + None => { + let (buffer, data) = host.upload_buffer(class)?; + UPLOAD_REUSE[1].fetch_add(1, Ordering::Relaxed); + name(&buffer, || format!("list upload {class:#x}")); + (buffer, data) + } + }; + self.deferred().hold_kept_upload(buffer.clone(), class, data as usize); Some((buffer, data)) } - /// A mapped readback buffer of `size` bytes, alive until the list is - /// reset. - pub(crate) fn readback(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *const u8)> { - let (buffer, data) = host.readback_buffer(size)?; - name(&buffer, || format!("list readback {size:#x}")); - self.deferred().uploads.push(buffer.clone()); + /// Of a size class ([`upload_class`]) it is one a list gave back at its + /// reset if there is one ([`UPLOAD_SPARE`]), and may be larger than + /// `size`. + pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + if upload_pool() && upload_class(size).is_some() { + return self.kept_upload(host, size); + } + let (buffer, data) = host.upload_buffer(size)?; + name_frame(&buffer, || format!("list upload {size:#x}")); + self.deferred().hold_upload(buffer.clone(), size); Some((buffer, data)) } @@ -1429,55 +9451,64 @@ impl HostList { let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); let len = len.max(1).next_multiple_of(256); if len > SCRATCH_CHUNK { + // (Of a size class: one kept for reuse, as for copies.) + if let Some((buffer, data)) = self.kept_upload(host, len) { + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + return Some((gpu, data)); + } let (buffer, data) = host.upload_buffer(len)?; - name(&buffer, || format!("list scratch {len:#x}")); + name_frame(&buffer, || format!("list scratch {len:#x}")); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - self.deferred().uploads.push(buffer); + self.deferred().hold_upload(buffer, len); return Some((gpu, data)); } - if s.used + len > SCRATCH_CHUNK && s.current < s.chunks.len() { + // The chunk in use while `len` fits in what is left of it, else the + // next one (a list's first chunk may be a small one). + while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 { (s.current, s.used) = (s.current + 1, 0); } if s.current == s.chunks.len() { - let (buffer, data) = host.upload_buffer(SCRATCH_CHUNK)?; - name(&buffer, || "list scratch".into()); - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - s.chunks.push((buffer, data as usize, gpu)); + let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST { + SCRATCH_FIRST + } else { + SCRATCH_CHUNK + }; + let chunk = take_chunk(host, size)?; + s.chunks.push((chunk, size)); s.used = 0; } - let (_, data, gpu) = s.chunks[s.current]; + let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu); let at = s.used; s.used += len; Some((gpu + at, (data + at as usize) as *mut u8)) } - /// The CPU-only UAV slot used when recording a clear. D3D12 uses - /// this descriptor during recording, so the next clear may reuse it. - pub(crate) fn clear_uav_cpu(&self) -> Option<D3D12_CPU_DESCRIPTOR_HANDLE> { - let heap = self - .clear_uav_cpu - .get_or_init(|| { - // SAFETY: plain allocation of a CPU-only view heap. - unsafe { - host()? - .device - .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - NumDescriptors: 1, - ..Default::default() - }) - } - .ok() - }) - .as_ref()?; - // SAFETY: the list owns this heap until it is dropped. - Some(unsafe { heap.GetCPUDescriptorHandleForHeapStart() }) + /// The bytes of scratch chunks the list holds now (after a reset: + /// none while lists share their chunks). + pub(crate) fn scratch_kept(&self) -> u64 { + let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + scratch.chunks.iter().map(|c| c.1).sum() } /// The host address of the list's indirect-work budget, zeroed at each /// submission of the list from the first use after a reset on. + /// The list's window of indirect draws clamped together (`crate::indirect::windowed`). + pub(crate) fn clamp_window(&self) -> std::sync::MutexGuard<'_, Option<crate::indirect::Window>> { + self.clamp_window.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// An occlusion query begun on the host in this list ([`crate::query::begin`]). + pub(crate) fn query_opened(&self, host: ID3D12QueryHeap, kind: u32, index: u32, console: usize) { + self.open_queries.lock().unwrap_or_else(|e| e.into_inner()).push((host, kind, index, console)); + } + + /// The query `index` of the console heap `console` was ended in this list ([`crate::query::end`]). + pub(crate) fn query_closed(&self, console: usize, index: u32) { + self.open_queries.lock().unwrap_or_else(|e| e.into_inner()).retain(|q| !(q.3 == console && q.2 == index)); + } + pub(crate) fn budget(&self) -> Option<u64> { let (buffer, data) = self .budget @@ -1486,81 +9517,186 @@ impl HostList { Some((b, d as usize)) }) .as_ref()?; + let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref(); let mut deferred = self.deferred(); if !deferred.budget_zeroed { deferred.budget_zeroed = true; let at = *data; - // SAFETY: the list's own mapped budget words (work, mesh - // groups), written before it runs. + // SAFETY: the list's own mapped words, written before it runs. + // The words after the budget hold what the clamp noted about the + // list's last run (mesh dispatches: the largest group count + // asked for, the groups asked in all; with the card's copy, as + // the list's end copied them here): taken, then zeroed. deferred.copies.push(Step::Host(Box::new(move || unsafe { - (at as *mut u64).write_volatile(0) + let words = at as *mut u32; + let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); + MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); + MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed); + // And of its indirect compute records: the largest x asked + // for, and how many asked for more than a dispatch runs. + let (widest, cut) = (words.add(3).read_volatile(), words.add(4).read_volatile()); + COMPUTE_GROUPS[0].fetch_max(u64::from(widest), Ordering::Relaxed); + COMPUTE_GROUPS[1].fetch_add(u64::from(cut), Ordering::Relaxed); + for k in 0..5 { + words.add(k).write_volatile(0); + } }))); + drop(deferred); + if let Some(card) = card { + self.zero_card_budget(card); + } + } + // SAFETY: a live buffer. + Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() }) + } + + /// The budget's words in the card's own memory ([`card_budget`]), if + /// the list can zero them itself (`WriteBufferImmediate`). + fn make_card_budget(&self) -> Option<ID3D12Resource> { + if !card_budget() { + return None; } + self.list.cast::<ID3D12GraphicsCommandList2>().ok()?; + let buffer = host()?.uav_buffer(256)?; + name(&buffer, || "indirect budget".to_owned()); + Some(buffer) + } + + /// Records, before the list's first clamp, the zeroing of the card's + /// copy of the budget: common, written as a copy, then left for + /// unordered access until the list closes ([`HostList::card_budget_out`]). + fn zero_card_budget(&self, card: &ID3D12Resource) { + let Ok(list2) = self.list.cast::<ID3D12GraphicsCommandList2>() else { + return; + }; // SAFETY: a live buffer. - Some(unsafe { buffer.GetGPUVirtualAddress() }) + let at = unsafe { card.GetGPUVirtualAddress() }; + let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { + Dest: at + offset, + Value: 0, + }); + // SAFETY: an open list; the buffer is the list's own and in the + // common state at the start of every recording. + unsafe { + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None); + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } } - /// The list's GPU-writable scratch buffer for expanded indirect - /// rectangle vertices (`capacity` bytes), created on first use. - pub(crate) fn rect_vertices(&self, capacity: u64) -> Option<ID3D12Resource> { - let mut rect = self.rect_scratch.lock().unwrap_or_else(|e| e.into_inner()); - if rect.vertices.is_none() { - let buffer = host()?.default_buffer(capacity)?; - name(&buffer, || format!("rect scratch {capacity:#x}")); - rect.vertices = Some(buffer); + /// Before the list closes, if this recording charged the card's copy + /// of the budget: its notes on mesh records go to the mapped words + /// (read at the next submission), and it goes back to common. + fn card_budget_out(&self) { + if !self.deferred().budget_zeroed { + return; + } + let (Some(Some(card)), Some(Some((mapped, _)))) = + (self.card_budget.get(), self.budget.get()) + else { + return; + }; + // SAFETY: an open list; both buffers are the list's own. The + // mapped one is promoted from common to the copy destination. + unsafe { + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + self.list.CopyBufferRegion(mapped, 4, card, 4, 8); + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); } - rect.vertices.clone() } - /// A GPU-writable buffer of at least `bytes` for rewritten indirect - /// draw arguments, kept alive until the list is reset. - pub(crate) fn rect_args(&self, bytes: u64) -> Option<ID3D12Resource> { - let want = bytes.max(RECT_ARGS_MIN).next_multiple_of(256); - let mut rect = self.rect_scratch.lock().unwrap_or_else(|e| e.into_inner()); - if let Some((buf, len)) = &rect.args - && *len >= want + /// A device-local unordered-access buffer of at least `size` bytes for + /// clamped indirect arguments, reused across executions and resets of the + /// list. Smaller buffers replaced mid-list stay alive until + /// [`HostList::reset`]. + pub(crate) fn indirect_scratch(&self, size: u64) -> Option<ID3D12Resource> { + let needed = size.max(64 << 10); + let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((buffer, cap)) = &*slot + && *cap >= needed { - return Some(buf.clone()); + return Some(buffer.clone()); } - let buffer = host()?.default_buffer(want)?; - name(&buffer, || format!("rect args {want:#x}")); - let old = rect.args.replace((buffer.clone(), want)); - drop(rect); - if let Some((old, _)) = old { - self.keep(&old); + let prev = slot.as_ref().map_or(0, |(_, cap)| *cap); + let alloc = prev + .saturating_mul(2) + .max(needed) + .next_multiple_of(64 << 10); + let buffer = host()?.uav_buffer(alloc)?; + name(&buffer, || format!("indirect arguments {alloc:#x}")); + let old = slot.replace((buffer.clone(), alloc)); + drop(slot); + if let Some((old_buf, _)) = old { + // It ends the list common, as every scratch buffer does. + self.indirect_common(&old_buf); + self.keep(&old_buf); } Some(buffer) } - /// The host GPU address of a 4-byte atomic counter for one indirect - /// rectangle draw, zeroed at each submission before the list runs. - pub(crate) fn rect_counter(&self) -> Option<u64> { - let mut rect = self.rect_scratch.lock().unwrap_or_else(|e| e.into_inner()); - if rect.counter_used == RECT_COUNTER_CHUNK { - rect.counter_chunk += 1; - rect.counter_used = 0; + /// Moves `scratch` back to the common state if a clamp left it readable + /// as indirect arguments ([`HostList::indirect_readable`]): where the + /// list's first clamp expects it. Done before the list closes and before + /// a bigger scratch buffer replaces it: one barrier per list (where + /// there was one per indirect execution), and the list ends as it + /// begins however it is submitted. + fn indirect_common(&self, scratch: &ID3D12Resource) { + { + let mut deferred = self.deferred(); + if deferred.indirect_readable != scratch.as_raw() as usize { + return; + } + deferred.indirect_readable = 0; } - if rect.counter_chunk == rect.counters.len() { - let bytes = u64::from(RECT_COUNTER_CHUNK) * 4; - let (buffer, data) = host()?.shared_buffer(bytes)?; - name(&buffer, || "rect counters".into()); - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - rect.counters.push((buffer, data as usize, gpu)); - rect.counter_used = 0; - } - let (_, data, gpu) = rect.counters[rect.counter_chunk]; - let slot = rect.counter_used; - rect.counter_used += 1; - drop(rect); - if slot == 0 { - let bytes = RECT_COUNTER_CHUNK as usize * 4; - // SAFETY: the list's own mapped chunk, zeroed before it runs. - self.defer_host(move || unsafe { - std::ptr::write_bytes(data as *mut u8, 0, bytes); - }); + let barrier = transition( + scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + ); + // SAFETY: an open list and a live buffer this recording left in + // `INDIRECT_ARGUMENT`. + unsafe { self.list.ResourceBarrier(&[barrier]) }; + } + + /// The state the list's indirect scratch buffer `scratch` is in at this + /// point of the recording: indirect arguments if a clamp in this + /// recording left it so ([`HostList::indirect_readable`]), otherwise + /// common: the state a buffer is made in, and the one a recording + /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]). + pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES { + if self.deferred().indirect_readable == scratch.as_raw() as usize { + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT + } else { + D3D12_RESOURCE_STATE_COMMON } - Some(gpu + u64::from(slot) * 4) + } + + /// A clamp recorded in this list left `scratch` readable as indirect + /// arguments. It stays so for every execution that reads it, until the + /// next clamp moves it back to unordered access. + pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) { + self.deferred().indirect_readable = scratch.as_raw() as usize; + } + + /// The list's buffers for `crate::indirect::window_check`. + pub(crate) fn window_check(&self) -> Option<&crate::indirect::WindowCheck> { + self.window_check.get_or_init(crate::indirect::WindowCheck::new).as_ref() } /// Keeps `object` alive until the list is reset. @@ -1576,11 +9712,24 @@ impl HostList { self.deferred().textures.insert(key) } + pub(crate) fn alias_source_changed(&self, view: &ID3D12Resource, source: &ID3D12Resource) -> bool { + let view = view.as_raw() as usize; + let source = source.as_raw() as usize; + self.deferred().texture_aliases.insert(view, source) != Some(source) + } + /// Runs `work` when the list is submitted, in order with its copies. - /// `work` may write title memory (refreshes after it copy again). - pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { - self.deferred().copies.push(Step::Run(Box::new(work))); - self.deferred().refreshed.clear(); + /// `work` may write title memory, and only in `[at, at + len)` + /// (refreshes after it copy again; [`near_writes`] uses the place, + /// without the switch any write of title memory is assumed). + pub(crate) fn defer_at(&self, at: usize, len: usize, work: impl Fn() + Send + 'static) { + let mut deferred = self.deferred(); + deferred.copies.push(Step::Run(Box::new(work), Some((at, len)))); + deferred.refreshed.clear(); + deferred.epoch += 1; + if list_reuse_set() { + deferred.filled.clear(); + } } /// As [`HostList::defer`], for work that writes only host memory. @@ -1588,19 +9737,55 @@ impl HostList { self.deferred().copies.push(Step::Host(Box::new(work))); } + /// As [`HostList::defer_host`], for work that reads what the texture + /// checks recorded before it found: run once those checks are done. + pub(crate) fn defer_after_textures(&self, work: impl Fn() + Send + 'static) { + self.deferred().copies.push(Step::AfterTextures(Box::new(work))); + } + /// Brings a texture's staging buffer up to date when the list is /// submitted, keeping it alive until the list is reset. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) { self.deferred().copies.push(Step::Texture(staging)); } + /// Detiles the textures the list uploads now, ahead of its submission + /// ([`crate::texture::Staging::refresh_ahead`]); how many were left. + pub(crate) fn refresh_textures_ahead(&self) -> u64 { + let textures: Vec<_> = self + .deferred() + .copies + .iter() + .filter_map(|step| match step { + Step::Texture(staging) => Some(staging.clone()), + _ => None, + }) + .collect(); + textures.iter().filter(|staging| !staging.refresh_ahead()).count() as u64 + } + /// Runs the list's submission-time steps; refreshes go into `batch` /// (the title's big buffers, a 174 MB one among them, are read by most /// lists of a submission, through many ranges). fn run_deferred(&self, batch: &mut Batch) { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; - for step in &self.deferred().copies { + // Texture checks in a row, done together on several threads before + // the next step that writes title memory, and at the end. + let mut textures: Vec<std::sync::Arc<crate::texture::Staging>> = Vec::new(); + let deferred = self.deferred(); + // Steps that wait for the texture checks before them. + let mut after: Vec<&(dyn Fn() + Send)> = Vec::new(); + for step in &deferred.copies { + if matches!(step, Step::Copy(..) | Step::Run(..)) { + refresh_textures(&mut textures); + if !after.is_empty() && !batch.due_textures.is_empty() { + batch.check_textures(); + } + for work in after.drain(..) { + work(); + } + } let started = std::time::Instant::now(); let copied = match step { &Step::Copy(dst, src, len) => { @@ -1609,8 +9794,18 @@ impl HostList { add(C::Copies, 1); add(C::CopyBytes, len as u64); } - batch.title_written(); + if near_writes() { + batch.title_wrote_near(dst, len, false); + } else { + batch.title_wrote(dst, len); + } + #[cfg(feature = "diagnostics")] + fill_check::copy_runs(dst, src, len); + #[cfg(feature = "diagnostics")] + let _reads_as = crate::backreads::reading_as(crate::backreads::TITLE_COPY, 0); copy_mapped(dst as *mut u8, src as *const u8, len, true); + // With the submission's one asking: the journal learns it. + crate::watch::wrote(dst, len); len } &Step::Fill(dst, src, len) => { @@ -1618,8 +9813,11 @@ impl HostList { { add(C::Copies, 1); add(C::CopyBytes, len as u64); + fill_check::runs(src, len); } - copy_mapped(dst as *mut u8, src as *const u8, len, false); + #[cfg(feature = "diagnostics")] + let _reads_as = crate::backreads::reading_as(crate::backreads::TITLE_COPY, 0); + copy_fill(dst as *mut u8, src as *const u8, len); len } Step::Refresh(shadow, address, len) => { @@ -1631,11 +9829,37 @@ impl HostList { batch.add(shadow, *address, *len); continue; } - Step::Run(work) | Step::Host(work) => { - if matches!(step, Step::Run(_)) { + Step::Run(work, Some((at, len))) if near_writes() => { + // Its place is known: only what it touches is brought up + // to date first and checked again after it, and the + // submission's one asking stands, told of the write, as + // for a title buffer copy ([`near_writes`]). + let written = batch.title_wrote_near(*at, *len, true); + work(); + for &(from, to) in &written { + crate::watch::wrote(from, to - from); + } + #[cfg(feature = "diagnostics")] + { + add(C::Runs, 1); + add(C::RunUs, started.elapsed().as_micros() as u64); + } + continue; + } + Step::Run(work, _) | Step::Host(work) => { + if matches!(step, Step::Run(..)) { batch.title_written(); + } else if !batch.due_textures.is_empty() { + // Host callbacks can use a refresh result, including the + // mip mask that maps a reserved texture for this upload. + batch.check_textures(); } work(); + // It wrote title memory, where is not known here: the + // submission's one asking ends, later refreshes ask anew. + if matches!(step, Step::Run(..)) { + crate::watch::ask_once_end(); + } #[cfg(feature = "diagnostics")] { add(C::Runs, 1); @@ -1644,18 +9868,198 @@ impl HostList { continue; } Step::GpuWrite(shadow, address, len) => { - batch.gpu_write(shadow, *address, *len); + // The shaders start from the title's data: this copy's + // pending refresh first. The other copies' wait for + // the next flush of all (flushing all of them at every + // range a dispatch writes made thousands of write-watch + // askings a frame). + batch.flush_one(shadow); + #[cfg(feature = "diagnostics")] + let snapshot = std::time::Instant::now(); + shadow.writing(*address, *len); + #[cfg(feature = "diagnostics")] + { + add(C::GpuWrites, 1); + add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64); + } continue; } Step::Texture(staging) => { if batch.texture_due(staging) { - staging.refresh(); + if near_writes() { + // Where it lies, for a write of ours at a known + // place to leave it checked ([`Batch::title_wrote_near`]). + batch + .texture_spans + .insert(std::sync::Arc::as_ptr(staging) as *const () as usize, staging.memory()); + } + if parallel_refresh() { + // Checked with the others of the batch, several + // at a time, before the next step that writes + // title memory ([`Batch::check_textures`]). + batch.due_textures.push(staging.clone()); + } else { + textures.push(staging.clone()); + } + } + continue; + } + Step::AfterTextures(work) => { + if textures.is_empty() && batch.due_textures.is_empty() { + work(); + } else { + after.push(work.as_ref()); } continue; } }; - PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); - PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + preparing(0, started.elapsed().as_micros() as u64); + preparing(1, copied as u64); + } + refresh_textures(&mut textures); + if !after.is_empty() && !batch.due_textures.is_empty() { + batch.check_textures(); + } + for work in after.drain(..) { + work(); + } + } +} + +/// Whether a submission's texture checks (read, hash, detile into each +/// texture's own staging buffer) run on several threads, the textures of +/// a run of them spread over the threads kept for the snapshots. They ran +/// one after another on the submitting thread: the frame line's +/// "textures", 120-390 ms a frame while the world streams in (2026-11-24 +/// reports). Each texture has its own lock, staging buffer and read buffer +/// (one per thread); the write-watch journal and the mapping lock (shared +/// by readers) are behind their own locks. On with [`wide_refresh`]; +/// `VICTORY_WIDE_TEXTURES=0` checks them one by one as before. +fn wide_textures() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| wide_refresh() && std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0")) +} + +/// Brings the staging buffers of `textures` up to date ([`wide_textures`]), +/// and empties it. +fn refresh_textures(textures: &mut Vec<std::sync::Arc<crate::texture::Staging>>) { + if textures.len() < 2 || !wide_textures() { + for staging in textures.drain(..) { + staging.refresh(); + } + return; + } + let started = std::time::Instant::now(); + let read = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); + let jobs: Vec<Box<dyn FnOnce() + Send>> = textures + .drain(..) + .map(|staging| { + let read = read.clone(); + Box::new(move || { + read.fetch_add(staging.refresh_uncounted() as u64, Ordering::Relaxed); + }) as Box<dyn FnOnce() + Send> + }) + .collect(); + crate::shadow::wide_run(jobs); + PREPARING[2].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + PREPARING[3].fetch_add(read.load(Ordering::Relaxed), Ordering::Relaxed); +} + +/// Whether a submission's refreshes of host copies run on several threads, +/// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it). +/// +/// A submission brings some sixty copies up to date, one after the other +/// on the submitting thread: for each, the pages the title wrote are asked +/// for and read through the kernel into the copy. That is the frame line's +/// "copies", 45-50 ms a frame, and the copies have nothing to do with one +/// another: each refresh writes its own copy and its own notes, and reads +/// title memory. With the switch the copies of a flush (four or more) are +/// spread over the threads kept for the snapshots (`crate::shadow::wide`). +/// The write-watch journal and the guards are behind their own locks, as +/// they are for the title's threads. +/// +/// `VICTORY_WIDE_REFRESH=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log (run 112 measured the switch worse, +/// copies 52 -> 68 ms, in a build whose copies went through the kernel one +/// by one; they are plain copies with one asking ahead now). +fn wide_refresh() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + wide_refresh_enabled( + std::env::var("VICTORY_WIDE_REFRESH").ok().as_deref(), + std::thread::available_parallelism().ok().map(|n| n.get()), + ) + }) +} + +fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option<usize>) -> bool { + match setting { + Some("1") => true, + Some("0") => false, + _ => logical_cpus.is_some_and(|n| n >= 4), + } +} + +#[cfg(test)] +mod wide_refresh_tests { + use super::wide_refresh_enabled; + + #[test] + fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() { + assert!(wide_refresh_enabled(None, Some(4))); + assert!(wide_refresh_enabled(None, Some(16))); + assert!(!wide_refresh_enabled(None, Some(2))); + assert!(!wide_refresh_enabled(None, None)); + assert!(wide_refresh_enabled(Some("1"), Some(1))); + assert!(!wide_refresh_enabled(Some("0"), Some(16))); + assert!(wide_refresh_enabled(Some("auto"), Some(4))); + } +} + +/// Whether a range of a host copy brought up to date in a submission is +/// left alone for the rest of that submission, until a step of ours writes +/// title memory there (`VICTORY_REFRESH_ONCE=1`; off by default). After +/// upstream VIctory 6d021fe ("a copy's range brought up to date is not +/// copied again in the submission until a step writes title memory"). +/// +/// A list of dispatches records "refresh this range, shaders write it" for +/// every dispatch, and each of those refreshes was done on its own +/// (`Batch::flush_one`): a walk of the guards or a failed kernel asking +/// for a copy of view memory, some 1,800 to 2,700 a frame and 23 to 29 ms +/// (runs 222 and 225, "watches"), nearly all finding nothing new. +/// +/// What changes: what the title's other threads write into a range while +/// its submission is being prepared is taken by the next submission, not +/// by a later step of this one, as `crate::watch::once` already has it for +/// write-watched memory. What this submission's lists read was written +/// before they were submitted. A title buffer copy of ours takes its +/// bytes out of what counts as up to date ([`Batch::title_wrote`]); any +/// other step that writes title memory takes everything out. +/// +/// `VICTORY_REFRESH_ONCE=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log, so that one run measures both in +/// the same scene (two runs do not stand in the same scene at the same +/// second: runs 228 and 229). +fn refresh_once() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock<u8> = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_REFRESH_ONCE").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + let on = (now_us() / 20_000_000) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "refreshes once a submission from now (VICTORY_REFRESH_ONCE=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on } } } @@ -1671,86 +10075,548 @@ impl HostList { #[derive(Default)] struct Batch { refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>, - gpu_writes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>, - declared_writes: std::collections::HashSet<(usize, usize, usize)>, + /// Where each copy (by address) is in `refreshes`: the list that makes + /// the heap's buffers ready adds some 4,100 copies, and searching them + /// for every refresh of a submission was tens of millions of + /// comparisons a frame. + index: std::collections::HashMap<usize, usize>, + /// With [`refresh_once`], by copy (its address; the copy is held, so + /// that the address names no other): the range of title addresses + /// brought up to date in this submission that no step of ours has + /// written since. + current: std::collections::HashMap<usize, (std::sync::Arc<crate::shadow::Shadow>, usize, usize)>, /// Staging buffers (by address) refreshed since the last title write. textures: std::collections::HashSet<usize>, + /// With [`parallel_refresh`]: textures due a check, not checked yet + /// ([`Batch::check_textures`], before any write of ours and at every + /// flush). + due_textures: Vec<std::sync::Arc<crate::texture::Staging>>, + /// With [`near_writes`]: the title memory (address, bytes) of the + /// staging buffers in `textures`, by the same key. A texture without + /// an entry is checked again after any write of ours. + texture_spans: std::collections::HashMap<usize, (usize, usize)>, } impl Batch { - fn new_gpu_write<T>(&mut self, shadow: &std::sync::Arc<T>, address: usize, len: usize) -> bool { - self.declared_writes - .insert((std::sync::Arc::as_ptr(shadow) as usize, address, len)) + fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) { + let end = address + len; + let key = std::sync::Arc::as_ptr(shadow) as usize; + // Brought up to date in this submission already ([`refresh_once`]; + // nothing is in `current` without the switch). + if let Some(&(_, from, to)) = self.current.get(&key) + && from <= address + && end <= to + { + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::Skipped, 1); + crate::copystat::add(crate::copystat::C::SkippedBytes, len as u64); + } + return; + } + match self.index.get(&key) { + Some(&at) => { + let r = &mut self.refreshes[at]; + (r.1, r.2) = (r.1.min(address), r.2.max(end)); + } + None => { + self.index.insert(key, self.refreshes.len()); + self.refreshes.push((shadow.clone(), address, end)); + } + } } - fn gpu_write( - &mut self, + /// Before shaders are given a range of `shadow`'s copy: its pending + /// refresh is done, the others stay pending. + fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) { + let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else { + return; + }; + let (shadow, from, to) = self.refreshes.swap_remove(at); + // The last entry took its place. + if let Some(moved) = self.refreshes.get(at) { + self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); + } + Self::update(&shadow, from, to); + Self::brought(&mut self.current, &shadow, from, to); + } + + /// With [`refresh_once`]: `[from, to)` of `shadow`'s copy was brought + /// up to date. Kept: its union with what was up to date if they touch, + /// else the larger of the two. + fn brought( + current: &mut std::collections::HashMap<usize, (std::sync::Arc<crate::shadow::Shadow>, usize, usize)>, shadow: &std::sync::Arc<crate::shadow::Shadow>, - address: usize, - len: usize, + from: usize, + to: usize, ) { - if self.new_gpu_write(shadow, address, len) { - // The first declaration needs the refreshed bytes for its snapshot. - // Another declaration of this exact range is already pending until - // the GPU submission finishes, so it needs no refresh boundary. - self.flush(); - shadow.writing(address, len); - self.gpu_writes.push((shadow.clone(), address, len)); + if !refresh_once() || from >= to { + return; + } + let entry = current + .entry(std::sync::Arc::as_ptr(shadow) as usize) + .or_insert_with(|| (shadow.clone(), from, to)); + if from <= entry.2 && entry.1 <= to { + (entry.1, entry.2) = (entry.1.min(from), entry.2.max(to)); + } else if to - from > entry.2 - entry.1 { + (entry.1, entry.2) = (from, to); } } - fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) { - let end = address + len; - match self - .refreshes - .iter_mut() - .find(|(s, ..)| std::sync::Arc::ptr_eq(s, shadow)) - { - Some((_, from, to)) => (*from, *to) = ((*from).min(address), (*to).max(end)), - None => self.refreshes.push((shadow.clone(), address, end)), - } + /// Brings `[from, to)` of a copy up to date, timed. + fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) { + let started = std::time::Instant::now(); + let copied = shadow.update(from, to - from); + let us = started.elapsed().as_micros() as u64; + #[cfg(feature = "diagnostics")] + crate::copystat::range(from, to - from, us, 0); + preparing(0, us); + preparing(1, copied as u64); } /// Whether `staging` is still to be refreshed in this submission (and /// notes it refreshed). fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool { - self.textures - .insert(std::sync::Arc::as_ptr(staging) as *const () as usize) + self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) } /// Before a step that writes title memory: pending refreshes are done /// first, and textures are checked again after it. fn title_written(&mut self) { + self.check_textures(); + self.flush(); + self.textures.clear(); + self.texture_spans.clear(); + // Where it writes is not known: no copy counts as up to date. + self.current.clear(); + } + + /// [`Batch::title_written`] for a write of ours whose place is known + /// (a title buffer copy into `[at, at + len)`): of a copy up to date + /// in this submission that holds some of those bytes, the larger part + /// beside them stays so. + fn title_wrote(&mut self, at: usize, len: usize) { + self.check_textures(); self.flush(); self.textures.clear(); + self.texture_spans.clear(); + let end = at + len; + self.current.retain(|_, entry| { + let (from, to) = (entry.1, entry.2); + if end <= from || to <= at { + return true; + } + let (left, right) = (at.saturating_sub(from), to.saturating_sub(end)); + if left >= right { + entry.2 = from + left; + } else { + entry.1 = end; + } + entry.1 < entry.2 + }); + } + + /// With [`near_writes`]: a write of ours into `[at, at + len)` of title + /// memory (a title buffer copy, or with `run` a memory-to-memory copy). + /// Only the pending refreshes whose span holds written bytes are done + /// first, and only the textures whose memory holds them are checked + /// again after it; the others stay pending or checked. Where the place + /// is a view of the title's physical pages, every other address that + /// shows the same 64 KiB pages counts as written too + /// (`crate::inplace::pages_of`); a view write of more than + /// [`NEAR_VIEW_PAGES`] pages, or more than [`NEAR_PENDING`] refreshes + /// pending, is done as before ([`Batch::title_wrote`]). Returns the + /// written ranges (the place, and the other addresses of its pages). + fn title_wrote_near(&mut self, at: usize, len: usize, run: bool) -> Vec<(usize, usize)> { + // Textures due a check read title memory as it is before the write. + self.check_textures(); + use std::sync::atomic::Ordering::Relaxed; + const K64: usize = 1 << 16; + let end = at.saturating_add(len); + let mut written = vec![(at, end)]; + let mut whole = self.refreshes.len() > NEAR_PENDING; + if !whole && len > 0 && !crate::inplace::views_between(at, end).is_empty() { + let (first, last) = (at / K64, end.div_ceil(K64)); + if last - first > NEAR_VIEW_PAGES { + whole = true; + } else { + for page in first..last { + for other in crate::inplace::pages_of(page * K64) { + if other != page * K64 { + written.push((other, other + K64)); + } + } + } + } + } + NEAR[usize::from(run)].fetch_add(1, Relaxed); + if whole { + NEAR[2].fetch_add(1, Relaxed); + self.title_wrote(at, len); + near_line(); + return written; + } + let touches = |from: usize, to: usize| written.iter().any(|&(a, b)| from < b && a < to); + // The refreshes that hold written bytes: done now, before the write. + let pending = std::mem::take(&mut self.refreshes); + let (due, keep): (Vec<_>, Vec<_>) = pending.into_iter().partition(|r| touches(r.1, r.2)); + NEAR[3].fetch_add(due.len() as u64, Relaxed); + NEAR[4].fetch_add(keep.len() as u64, Relaxed); + if !due.is_empty() { + self.refreshes = due; + self.flush(); + } + self.refreshes = keep; + self.index = self + .refreshes + .iter() + .enumerate() + .map(|(i, r)| (std::sync::Arc::as_ptr(&r.0) as usize, i)) + .collect(); + // Textures: checked again only where the write lands. + let before = self.textures.len(); + let spans = &self.texture_spans; + self.textures.retain(|key| spans.get(key).is_some_and(|&(a, n)| !touches(a, a.saturating_add(n)))); + let textures = &self.textures; + self.texture_spans.retain(|key, _| textures.contains(key)); + NEAR[5].fetch_add(self.textures.len() as u64, Relaxed); + NEAR[6].fetch_add((before - self.textures.len()) as u64, Relaxed); + // [`refresh_once`]'s note of what is up to date, as in `title_wrote`. + for &(a, b) in &written { + self.current.retain(|_, entry| { + let (from, to) = (entry.1, entry.2); + if b <= from || to <= a { + return true; + } + let (left, right) = (a.saturating_sub(from), to.saturating_sub(b)); + if left >= right { + entry.2 = from + left; + } else { + entry.1 = b; + } + entry.1 < entry.2 + }); + } + near_line(); + written + } + + /// With [`parallel_refresh`]: checks the textures due ([`Batch::due_textures`]) + /// on the helper threads (`crate::shadow::wide_run`, the submitting + /// thread among them), all done before it returns. Each check takes + /// its texture's own lock, the journal's for its asking, the runtime's + /// mapping lock for reading (shared), and a buffer of its thread's own; + /// the hashing and detiling run side by side. "textures N ms" counts + /// the time it took, not the threads' sum. + fn check_textures(&mut self) { + use std::sync::atomic::Ordering::Relaxed; + if self.due_textures.is_empty() { + return; + } + let due = std::mem::take(&mut self.due_textures); + PARALLEL_CHECKS[0].fetch_add(1, Relaxed); + PARALLEL_CHECKS[1].fetch_add(due.len() as u64, Relaxed); + if due.len() < 2 { + for staging in due { + staging.refresh(); + } + return; + } + let started = std::time::Instant::now(); + let before = PREPARING[2].load(Relaxed); + let jobs: Vec<Box<dyn FnOnce() + Send>> = due + .into_iter() + .map(|staging| Box::new(move || staging.refresh()) as Box<dyn FnOnce() + Send>) + .collect(); + crate::shadow::wide_run(jobs); + let summed = PREPARING[2].load(Relaxed).saturating_sub(before); + let wall = started.elapsed().as_micros() as u64; + PREPARING[2].fetch_sub(summed.saturating_sub(wall), Relaxed); + PARALLEL_CHECKS[2].fetch_add(summed, Relaxed); + PARALLEL_CHECKS[3].fetch_add(wall, Relaxed); + let batches = PARALLEL_CHECKS[0].load(Relaxed); + if batches.is_multiple_of(1 << 14) { + let [b, n, sum, w] = [0, 1, 2, 3].map(|i| PARALLEL_CHECKS[i].load(Relaxed)); + tracing::info!( + "texture checks side by side (VICTORY_PARALLEL_REFRESH) so far: {b} batches, {n} textures; the threads' sum {} ms, the time taken {} ms", + sum / 1000, + w / 1000 + ); + } } fn flush(&mut self) { - for (shadow, from, to) in self.refreshes.drain(..) { + self.check_textures(); + self.index.clear(); + // One write-watch asking for the copies that lie close together, + // not one per copy. + let ahead = self.refreshes.len() > 1; + if ahead { let started = std::time::Instant::now(); - let copied = shadow.update(from, to - from); - let us = started.elapsed().as_micros() as u64; - #[cfg(feature = "diagnostics")] - crate::copystat::range(from, to - from, us, 0); - PREPARING[0].fetch_add(us, Ordering::Relaxed); - PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + let ranges: Vec<(usize, usize)> = self + .refreshes + .iter() + .filter(|r| !r.0.unwatched()) + .map(|r| (r.1, r.2)) + .collect(); + crate::watch::ask_ahead(&ranges); + preparing(0, started.elapsed().as_micros() as u64); + } + if wide_refresh() && self.refreshes.len() >= 4 { + // Each copy on its own, several at a time: a copy's refresh + // writes that copy and reads title memory, nothing of another's. + // The time counted is the time it took, not the threads' sum. + let started = std::time::Instant::now(); + let before = PREPARING[0].load(Ordering::Relaxed); + // Noted now: nothing reads the notes before the jobs are done. + for (shadow, from, to) in &self.refreshes { + Self::brought(&mut self.current, shadow, *from, *to); + } + let jobs: Vec<Box<dyn FnOnce() + Send>> = self + .refreshes + .drain(..) + .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box<dyn FnOnce() + Send>) + .collect(); + crate::shadow::wide_run(jobs); + let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); + let over = summed.saturating_sub(started.elapsed().as_micros() as u64); + PREPARING[0].fetch_sub(over, Ordering::Relaxed); + crate::framelog::sub(crate::framelog::T::CopyUs, over); + } else { + for (shadow, from, to) in self.refreshes.drain(..) { + Self::update(&shadow, from, to); + Self::brought(&mut self.current, &shadow, from, to); + } + } + if ahead { + crate::watch::ask_ahead_done(); + } + } +} + +/// What `VICTORY_LIST_REUSE` says: 0 unset (off), 1 on, 2 in turn. +fn list_reuse_mode() -> u8 { + static MODE: OnceLock<u8> = OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_LIST_REUSE").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) +} + +/// Whether the switch is set at all (`1` or `alt`): what a list remembers +/// of its fills is then dropped at every `Copy` and `Run` step in both +/// phases of `alt`, so that nothing remembered in one ON phase is wrong in +/// the next. +fn list_reuse_set() -> bool { + list_reuse_mode() != 0 +} + +/// Whether a list keeps a pipeline it binds once, and copies a root view's +/// title memory into upload memory once for every bind of the same bytes +/// (`VICTORY_LIST_REUSE=1`; off by default: kept and copied at every bind, +/// as before). `alt`: twenty seconds with, twenty without, in turn, each +/// change said in the log. After darkworldhm's snapshot +/// (`HostList::bind_pipeline`, `HostList::fill_scratch` there). +pub(crate) fn list_reuse() -> bool { + match list_reuse_mode() { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a list keeps a pipeline once and copies a repeated root view once from now (VICTORY_LIST_REUSE=alt): {}", + if on { "ON" } else { "off, at every bind as usual" } + ); + } + on + } + } +} + +/// Whether a list's fills of under 256 bytes are copied in place +/// (`VICTORY_FILLS_PLAIN=1`, with `VICTORY_COPY_PLAIN=1`; off by default: +/// through the kernel's copy, as before). `alt`: twenty seconds with, +/// twenty without, in turn, each change said in the log. +/// +/// A fill copies constants the title recorded a draw with into upload +/// memory of the list's own. `crate::plaincopy` leaves copies that short +/// to the kernel because the layer's ASKINGS are that short and fail; the +/// fills are there, and each was a system call +/// (`crate::plaincopy::copy_short`). The same bytes, read at the same +/// step; a source page that is gone goes to the kernel's copy as before. +fn fills_plain() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock<u8> = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_FILLS_PLAIN").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a list's fills of under 256 bytes are copied in place from now (VICTORY_FILLS_PLAIN=alt): {}", + if on { "ON" } else { "off, through the kernel's copy as usual" } + ); + } + on + } + } +} + +/// Whether a write of ours into title memory at a known place (a title +/// buffer copy, a memory-to-memory copy of the title's) brings up to date +/// first only the pending refreshes it touches and has only the textures +/// it touches checked again, and lets the submission's one write-watch +/// asking stand (`VICTORY_NEAR_WRITES=1`; off by default: every pending +/// refresh is done and every texture checked again, and a memory-to-memory +/// copy ends the asking, as before). `alt`: twenty seconds with, twenty +/// without, in turn, each change said in the log. +/// +/// Why (runs 311-316, 184 five-second world readings, fitted on draws and +/// memory-to-memory copies a frame): the title records about 126 of those +/// copies a frame (50 per 1,000 draws), each a [`Step::Run`] whose place +/// was not used: a full flush, every texture hashed again, the asking +/// ended. Per 100 such copies a frame at equal draws: the lists' steps +/// +13.4 ms, the flush +4.9 ms (R2 0.69 / 0.23), "textures" +8.9 ms. The +/// copies themselves take 0.2 ms a frame. +fn near_writes() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock<u8> = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_NEAR_WRITES").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a write of ours at a known place flushes and checks again only what it touches from now (VICTORY_NEAR_WRITES=alt): {}", + if on { "ON" } else { "off, everything as usual" } + ); + } + on + } + } +} + +/// [`Batch::title_wrote_near`]: a view write over more pages than this is +/// done the old way (each page's other addresses are looked up). +const NEAR_VIEW_PAGES: usize = 64; +/// [`Batch::title_wrote_near`]: more refreshes pending than this, and the +/// write is done the old way (the partition walks them all). +const NEAR_PENDING: usize = 4096; + +/// Since the start, of [`Batch::title_wrote_near`]: title buffer copies, +/// memory-to-memory copies, of both those done the old way, refreshes done +/// for them, refreshes left pending, textures left checked, textures to be +/// checked again. +static NEAR: [std::sync::atomic::AtomicU64; 7] = [const { std::sync::atomic::AtomicU64::new(0) }; 7]; + +/// Every 16,384 near writes: [`NEAR`] in a line. +fn near_line() { + let n = NEAR[0].load(Ordering::Relaxed) + NEAR[1].load(Ordering::Relaxed); + if n == 0 || !n.is_multiple_of(16_384) { + return; + } + let [copies, runs, whole, done, left, kept, again] = [0, 1, 2, 3, 4, 5, 6].map(|i| NEAR[i].load(Ordering::Relaxed)); + tracing::info!( + "writes of ours at a known place so far (VICTORY_NEAR_WRITES): {copies} title buffer copies and {runs} memory-to-memory copies, \ + {whole} of them done the old way (a view of over {NEAR_VIEW_PAGES} pages, or over {NEAR_PENDING} refreshes pending); \ + refreshes done for them {done}, left pending {left}; textures left checked {kept}, checked again {again}" + ); +} + +/// Whether a submission's texture checks (`crate::texture::Staging::refresh`: +/// the write watch or guards asked, then the memory hashed and detiled if +/// it may have changed) are gathered between writes of ours and run on the +/// helper threads side by side (`VICTORY_PARALLEL_REFRESH=1`; off by +/// default: one after the other where each texture's step stands; `alt`: +/// twenty seconds with, twenty without, in turn, each change said in the +/// log). Pair with `VICTORY_WIDE_REFRESH` for the host copies of buffers. +/// +/// Why: "textures N ms" is 11-12 ms of a boat frame's preparing (runs +/// 319-321, 28-30 MB hashed a frame), all on the submitting thread. The +/// checks touch different textures; what they share is the journal's lock +/// for the asking (short for write-watched memory, a guard walk for view +/// memory), so the hashing and detiling are what goes side by side. +/// +/// What changes: a texture's check moves from its step to the next write +/// of ours or flush, so it reads title memory a little later in the +/// preparing, and never after a write of ours that its lists come before. +fn parallel_refresh() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock<u8> = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_PARALLEL_REFRESH").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: OnceLock<std::time::Instant> = OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a submission's texture checks run side by side from now (VICTORY_PARALLEL_REFRESH=alt): {}", + if on { "ON" } else { "off, one after the other as usual" } + ); + } + on } } } +/// Since the start, of [`Batch::check_textures`]: batches, textures, the +/// threads' summed microseconds, the microseconds taken. +static PARALLEL_CHECKS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// A fill's copy ([`Step::Fill`]): title memory at `src` into upload memory +/// at `dst`. In place if it is short and [`fills_plain`] says so, else (and +/// if a source page was not there) as every copy ([`copy_mapped`]). +fn copy_fill(dst: *mut u8, src: *const u8, len: usize) { + #[cfg(feature = "diagnostics")] + let timing_only = crate::copystat::mode() != 0; + #[cfg(not(feature = "diagnostics"))] + let timing_only = false; + if len > 0 + && len < crate::plaincopy::least() + && !timing_only + && fills_plain() + && crate::plaincopy::copy_short(dst, src, len) + { + #[cfg(feature = "diagnostics")] + crate::backreads::touched(src as usize, len, false); + return; + } + copy_mapped(dst, src, len, false); +} + /// Copies title memory at submission. The ranges were checked against their /// resources when recorded, but the title may since have unmapped pages of /// them (tiled memory, page mappings), which read as zeros here; a title -/// destination (`title_dst`) that is not all mapped takes nothing from its -/// first unmapped page on. +/// destination (`title_dst`) that is not all mapped is left alone. /// -/// The copy runs in the kernel (`ReadProcessMemory`), which reports an -/// unmapped page of the source, or of the destination it writes, instead of -/// faulting. Asking `VirtualQuery` first cost about 2 ms per copy in the -/// title's big pools (it walks the page tables to the region's end), which -/// made copies run at 100-200 MB/s; a title destination is asked only once -/// its copy has failed (asked before each, the world's 80 copies per frame -/// cost 60 ms). +/// The source is read through the kernel (`ReadProcessMemory`), which +/// reports an unmapped page instead of faulting. Asking `VirtualQuery` first +/// cost about 2 ms per copy in the title's big pools (it walks the page +/// tables to the region's end), which made copies run at 100-200 MB/s. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) { #[cfg(feature = "diagnostics")] match crate::copystat::mode() { @@ -1765,29 +10631,93 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b if len == 0 { return; } + #[cfg(feature = "diagnostics")] + { + crate::backreads::touched(src as usize, len, false); + if title_dst { + crate::backreads::touched(dst as usize, len, false); + } + } + // A title destination that is not all mapped is left alone. Asking + // Windows first (`VirtualQuery`) walks the page tables to the end of + // the destination's region: in the title's big blocks that is + // milliseconds a copy, and it was a seventh of the submitting thread's + // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below + // says the same when it fails, so the question is only asked then. + // `VICTORY_COPY_ASK=1` asks first, as before. + static ASK: OnceLock<bool> = OnceLock::new(); + let ask_first = title_dst + && *ASK.get_or_init(|| std::env::var_os("VICTORY_COPY_ASK").is_some_and(|v| v == "1")); + if ask_first && !crate::texture::committed(dst, len) { + return; + } if title_dst { // The kernel writes the destination: it must not be guarded. crate::watch::writing(dst as usize, len); } #[cfg(feature = "diagnostics")] let moved = std::time::Instant::now(); - let whole = read(src, dst, len); + // Into host memory: in place first, if asked for (`crate::plaincopy`); + // through the kernel if that is off or met a page that was not there. + let whole = (!title_dst && crate::plaincopy::copy(dst, src, len)) || read_parallel(src, dst, len); #[cfg(feature = "diagnostics")] - crate::copystat::add( - crate::copystat::C::MoveUs, - moved.elapsed().as_micros() as u64, - ); + crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64); if whole { return; } - // The copy stopped at an unmapped page. One of a title destination ends - // it: the retries below write the destination themselves (zeros for - // what cannot be read), and would fault there. - if title_dst && !crate::texture::committed(dst, len) { + // The copy failed: a source page is not there, or the destination is + // not all mapped. Then the destination stays as it is (the kernel may + // have written its first pages). + if title_dst && !ask_first && !crate::texture::committed(dst, len) { return; } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Fallbacks, 1); + #[cfg(feature = "diagnostics")] + let sparse = std::time::Instant::now(); + if !title_dst && len >= 64 << 10 { + read_sparse(src, dst, len); + } else { + read_pieces(src, dst, len); + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64); +} + +/// After a failed bulk read into host memory, skip contiguous holes. Never +/// cache the query across copies: the title may remap the same address. +fn read_sparse(src: *const u8, dst: *mut u8, len: usize) { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery, + }; + let mut offset = 0; + while offset < len { + let at = src.wrapping_add(offset); + let to = dst.wrapping_add(offset); + let remaining = len - offset; + // SAFETY: the query inspects an address and fills a local structure. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) }; + let n = (info.BaseAddress as usize).saturating_add(info.RegionSize) + .saturating_sub(at as usize).min(remaining); + if size != size_of_val(&info) || n == 0 { + read_pieces(at, to, remaining); + break; + } + if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Unmapped, n as u64); + // SAFETY: this path is only used with a writable host destination. + unsafe { to.write_bytes(0, n) }; + } else if !read(at, to, n) { + // A mapping may change between query and read. + read_pieces(at, to, n); + } + offset += n; + } +} + +fn read_pieces(src: *const u8, dst: *mut u8, len: usize) { // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece // that fails), zeros for what cannot be read. for_pieces(src as usize, len, 64 << 10, |at, n| { @@ -1809,35 +10739,113 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b /// Reads title memory at `src` into `dst`; false if a page of it is not /// readable. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { - read(src, dst.as_mut_ptr(), dst.len()) + #[cfg(feature = "diagnostics")] + crate::backreads::touched(src as usize, dst.len(), false); + // In place first, if asked for (`crate::plaincopy`): the destination is + // memory of ours, as in `copy_mapped`. + crate::plaincopy::copy(dst.as_mut_ptr(), src, dst.len()) || read(src, dst.as_mut_ptr(), dst.len()) +} + +/// [`read`], cut into up to four pieces on as many threads for a copy of +/// 8 MB or more: the world copies 160-360 MB of title memory a frame, which +/// one thread did at about 1.2 GB/s (90-290 ms a frame on an i5-12400F). +fn read_parallel(src: *const u8, dst: *mut u8, len: usize) -> bool { + const PIECE: usize = 4 << 20; + static THREADS: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + let threads = *THREADS.get_or_init(|| { + std::thread::available_parallelism().map_or(1, |n| (n.get() / 3).clamp(1, 4)) + }); + let pieces = threads.min(len / PIECE); + if pieces < 2 { + return read(src, dst, len); + } + // Page-aligned pieces: an unmapped page fails one piece, not two. + let piece = (len.div_ceil(pieces) + 0xfff) & !0xfff; + let (s, d) = (src as usize, dst as usize); + std::thread::scope(|scope| { + let rest: Vec<_> = (1..pieces) + .map(|i| { + let (at, end) = (i * piece, ((i + 1) * piece).min(len)); + scope.spawn(move || at >= end || read((s + at) as *const u8, (d + at) as *mut u8, end - at)) + }) + .collect(); + let first = read(src, dst, piece.min(len)); + rest.into_iter().fold(first, |whole, h| h.join().unwrap_or(false) && whole) + }) } -/// Copies `len` bytes from `src` to `dst` in the kernel: false if a source -/// page is not readable or a destination page not writable (the bytes -/// before that page may have been copied). +/// Copies `len` bytes from `src` to `dst` unless a source page is not +/// readable. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut done = 0; - // SAFETY: the destination is `len` bytes the caller may write, host - // memory or title memory; the kernel checks both ranges, and a page it - // cannot read or write fails the call instead of faulting. - unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 } + // SAFETY: the destination is mapped writable memory of `len` bytes; the + // kernel checks the source. + if unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) } != 0 { + return true; + } + // Memory held for a copy-back (`crate::lazy`) is opened, and read again. + // SAFETY: as above. + crate::lazy::release(src as usize, len) + && unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) } != 0 +} + +#[link(name = "ntdll", kind = "raw-dylib")] +unsafe extern "system" { + /// The kernel's write into a process's memory, `(process, address, + /// bytes, length, written out)`: an NTSTATUS, negative when a page of + /// the range is not there or not writable. It changes no protection. + fn NtWriteVirtualMemory( + process: *mut std::ffi::c_void, + base: *mut std::ffi::c_void, + buffer: *const std::ffi::c_void, + size: usize, + written: *mut usize, + ) -> i32; +} + +/// Whether title memory is written with the kernel's own call +/// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks +/// what the pages are (as `VirtualQuery` does: about 2 ms a call in the +/// title's big pools, see [`copy_mapped`]): putting back what shaders wrote +/// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size +/// (run 24). On by default; `VICTORY_DIRECT_WRITES=0` writes as before. +fn direct_writes() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_DIRECT_WRITES").is_none_or(|v| v != "0")) } /// Copies host memory into title memory after a submission (what shaders /// wrote), leaving pages that are not mapped alone. -/// -/// Through [`read`]: the kernel refuses an unmapped destination page as it -/// does a source page. `WriteProcessMemory` makes the same copy, but asks -/// for the destination's region first, at `VirtualQuery`'s cost (see -/// [`copy_mapped`]): 0.35 ms for each piece of the world's copy-back, 39 ms -/// per frame. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { - let write = |at: usize, n: usize| read(src.wrapping_add(at - dst as usize), at as *mut u8, n); + use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + #[cfg(feature = "diagnostics")] + crate::backreads::touched(dst as usize, len, true); + let direct = direct_writes(); + let write = |at: usize, n: usize| { + let from = src.wrapping_add(at - dst as usize); + let mut done = 0; + if direct { + // SAFETY: as below; the kernel checks the destination and + // writes nothing it cannot (the caller opened its guards: + // `crate::watch::writing`). + return unsafe { + NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0 + }; + } + // SAFETY: the source is our mapped host copy; the kernel checks the + // destination. + unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 } + }; if len == 0 || write(dst as usize, len) { return; } + // Memory held for a copy-back (`crate::lazy`) is opened first. + if crate::lazy::release(dst as usize, len) && write(dst as usize, len) { + return; + } for_pieces(dst as usize, len, 64 << 10, |at, n| { if !write(at, n) { for_pieces(at, n, 4 << 10, |at, n| { @@ -1859,106 +10867,20 @@ fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, us } } -#[cfg(test)] -mod title_copies { - use super::{copy_mapped, write_mapped}; - use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, - VirtualAlloc, VirtualFree, VirtualProtect, - }; - - const BLOCK: usize = 64 << 10; - - /// Three reserved blocks, the first and the last committed and filled - /// with `fill`: title memory with an unmapped block in it. - fn holed(fill: u8) -> *mut u8 { - // SAFETY: a fresh reservation; the committed blocks are ours to fill. - unsafe { - let base = - VirtualAlloc(std::ptr::null(), 3 * BLOCK, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>(); - assert!(!base.is_null()); - for block in [0, 2] { - let at = base.add(block * BLOCK); - assert!(!VirtualAlloc(at.cast(), BLOCK, MEM_COMMIT, PAGE_READWRITE).is_null()); - at.write_bytes(fill, BLOCK); - } - base - } - } - - fn block<'a>(base: *const u8, n: usize) -> &'a [u8] { - // SAFETY: tests ask for committed blocks only. - unsafe { std::slice::from_raw_parts(base.add(n * BLOCK), BLOCK) } - } - - fn release(base: *mut u8) { - // SAFETY: a reservation of `holed`. - assert_ne!(unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }, 0); - } - - fn pattern() -> Vec<u8> { - (0..3 * BLOCK).map(|i| (i % 251) as u8 + 1).collect() - } - - #[test] - fn title_copies_reach_mapped_destinations_and_stop_at_unmapped_pages() { - let from = pattern(); - // All mapped: copied, through a destination that was never asked. - let to = holed(0xee); - copy_mapped(to, from.as_ptr(), BLOCK, true); - assert_eq!(block(to, 0), &from[..BLOCK]); - release(to); - // An unmapped block in the destination: nothing faults, and nothing - // arrives from that block on. - let to = holed(0xee); - copy_mapped(to, from.as_ptr(), 3 * BLOCK, true); - assert!(block(to, 2).iter().all(|&b| b == 0xee)); - release(to); - // An unmapped block in the source reads as zeros. - let holes = holed(7); - let mut to = vec![0xeeu8; 3 * BLOCK]; - copy_mapped(to.as_mut_ptr(), holes, 3 * BLOCK, true); - assert!(to[..BLOCK].iter().all(|&b| b == 7)); - assert!(to[BLOCK..2 * BLOCK].iter().all(|&b| b == 0)); - assert!(to[2 * BLOCK..].iter().all(|&b| b == 7)); - release(holes); - } - - #[test] - fn copy_back_writes_mapped_pages_only() { - let from = pattern(); - let to = holed(0xee); - write_mapped(to, from.as_ptr(), 3 * BLOCK); - assert_eq!(block(to, 0), &from[..BLOCK]); - assert_eq!(block(to, 2), &from[2 * BLOCK..]); - release(to); - // Neither aligned nor whole: the bytes around the range stay. - let to = holed(0xee); - // SAFETY: inside the first block. - write_mapped(unsafe { to.add(100) }, from.as_ptr(), BLOCK - 300); - let first = block(to, 0); - assert_eq!(first[100..BLOCK - 200], from[..BLOCK - 300]); - let around = first[..100].iter().chain(&first[BLOCK - 200..]); - assert!(around.into_iter().all(|&b| b == 0xee)); - // A page that is mapped but not writable is not written either - // (guarded title blocks are opened before they are copied back). - let mut old = 0; - // SAFETY: a committed block of ours. - let protected = - unsafe { VirtualProtect(to.add(2 * BLOCK).cast(), BLOCK, PAGE_READONLY, &mut old) }; - assert_ne!(protected, 0); - // SAFETY: the third block. - write_mapped(unsafe { to.add(2 * BLOCK) }, from.as_ptr(), BLOCK); - assert!(block(to, 2).iter().all(|&b| b == 0xee)); - release(to); +impl Host { + /// The queue everything of ours runs on, for a call that must go to it + /// in order with the lists (`crate::tiles`: a texture's levels are + /// given memory ahead of the list that uploads them). + pub(crate) fn queue(&self) -> &ID3D12CommandQueue { + &self.queue } -} -impl Host { /// A buffer in the upload heap, mapped for writing. - pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + /// A buffer of `size` bytes the card writes and we read (a read back), + /// in the state copies into it need. + pub(crate) fn read_back_buffer(&self, size: u64) -> Option<ID3D12Resource> { let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_UPLOAD, + Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { @@ -1975,36 +10897,115 @@ impl Host { ..Default::default() }; let mut buffer: Option<ID3D12Resource> = None; - let mut data = std::ptr::null_mut(); - // SAFETY: plain creation and mapping of an upload buffer. + // SAFETY: plain creation of a read-back buffer. let made = unsafe { - self.device - .CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - &desc, - D3D12_RESOURCE_STATE_GENERIC_READ, - None, - &mut buffer, - ) - .and_then(|()| { - let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - b.Map(0, None, Some(&mut data)) - }) + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) }; match made { - Ok(()) => Some((buffer?, data.cast())), + Ok(()) => buffer, Err(e) => { - tracing::warn!(error = %e, size, "no upload buffer"); + tracing::warn!(error = %e, size, "no read-back buffer"); None } } } - /// A buffer in the readback heap, mapped for reading. - pub(crate) fn readback_buffer(&self, size: u64) -> Option<(ID3D12Resource, *const u8)> { + /// Whether upload buffers may be made in the card's own memory that the + /// CPU writes through the PCI bar (`D3D12_HEAP_TYPE_GPU_UPLOAD`, with + /// Resizable BAR on and a driver that offers it: `OPTIONS16` + /// `GPUUploadHeapSupported`). Shaders and copies then read the list's + /// scratch, constants and texture staging from the card's memory, not + /// across the bus at every read. `VICTORY_GPU_UPLOAD=0` keeps them in + /// the PC's memory, as before. + fn gpu_upload_supported(&self) -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + if std::env::var_os("VICTORY_GPU_UPLOAD").is_some_and(|v| v == "0") { + tracing::info!("GPU upload heap (Resizable BAR) off: VICTORY_GPU_UPLOAD=0"); + return false; + } + #[repr(C)] + #[derive(Default)] + struct Options16 { + dynamic_depth_bias: windows::core::BOOL, + gpu_upload_heap: windows::core::BOOL, + } + let mut o = Options16::default(); + // SAFETY: OPTIONS16 (45) and its two-BOOL structure; a runtime + // that does not know it fails the call. + let asked = unsafe { + self.device + .CheckFeatureSupport(D3D12_FEATURE(45), (&raw mut o).cast(), size_of_val(&o) as u32) + }; + let on = asked.is_ok() && o.gpu_upload_heap.as_bool(); + tracing::info!( + supported = on, + asked = asked.is_ok(), + "GPU upload heap (Resizable BAR): upload buffers in the card's memory when supported" + ); + on + }) + } + + /// Whether this upload buffer goes into the card's memory + /// ([`Host::gpu_upload_supported`]): up to 16 MiB, and while this + /// process uses under four fifths of the card's budget (asked at most + /// every quarter second), below where texture copies stop + /// (`resource::room`) so that those keep their room. + fn gpu_upload_fits(&self, size: u64) -> bool { + static ROOM: AtomicU32 = AtomicU32::new(0); + static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if size > 16 << 20 || GPU_UPLOAD_FAILED.load(Ordering::Relaxed) || !self.gpu_upload_supported() { + return false; + } + let now = now_ms(); + if now.saturating_sub(ASKED.load(Ordering::Relaxed)) >= 250 { + ASKED.store(now, Ordering::Relaxed); + let room = self.video_memory().is_some_and(|[budget, used, ..]| used < budget / 5 * 4); + ROOM.store(u32::from(room), Ordering::Relaxed); + } + ROOM.load(Ordering::Relaxed) != 0 + } + + pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let gpu = self.gpu_upload_fits(size); + if gpu { + if let Some(made) = self.upload_buffer_in(size, true) { + GPU_UPLOADS[0].fetch_add(1, Ordering::Relaxed); + GPU_UPLOADS[1].fetch_add(size, Ordering::Relaxed); + return Some(made); + } + // Refused: never again this run, the PC's memory from here on. + if !GPU_UPLOAD_FAILED.swap(true, Ordering::Relaxed) { + tracing::warn!(size, "an upload buffer in the card's memory was refused: upload buffers stay in the PC's memory"); + } + } + if let Some(made) = self.upload_buffer_in(size, false) { + return Some(made); + } + // Refused: what is kept for reuse goes, and it is asked once more; + // the memory level turns critical and what can wait backs off + // (`crate::pressure`). + crate::pressure::refused(); + if free_spares() > 0 { + return self.upload_buffer_in(size, false); + } + None + } + + fn upload_buffer_in(&self, size: u64, gpu: bool) -> Option<(ID3D12Resource, *mut u8)> { + MADE[0].fetch_add(1, Ordering::Relaxed); + MADE[1].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_READBACK, + // GPU_UPLOAD (5): the card's memory, written by the CPU. + Type: if gpu { D3D12_HEAP_TYPE(5) } else { D3D12_HEAP_TYPE_UPLOAD }, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { @@ -2022,14 +11023,14 @@ impl Host { }; let mut buffer: Option<ID3D12Resource> = None; let mut data = std::ptr::null_mut(); - // SAFETY: plain creation and mapping of a readback buffer. + // SAFETY: plain creation and mapping of an upload buffer. let made = unsafe { self.device .CreateCommittedResource( &heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut buffer, ) @@ -2040,14 +11041,31 @@ impl Host { }; match made { Ok(()) => Some((buffer?, data.cast())), + Err(e) if gpu => { + tracing::warn!(error = %e, size, "no upload buffer in the card's memory"); + None + } Err(e) => { - tracing::warn!(error = %e, size, "no readback buffer"); + tracing::warn!(error = %e, size, "no upload buffer"); None } } } } +/// Upload buffers made in the card's memory ([`Host::gpu_upload`]) since +/// the start: count and bytes. +pub(crate) static GPU_UPLOADS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// An upload buffer in the card's memory was refused: none is asked for again. +static GPU_UPLOAD_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Our passes at the present: render scale and frames in between. +#[path = "presentfx.rs"] +mod presentfx; +#[path = "awake.rs"] +pub(crate) mod awake; + /// The swap chain formats a presented texture can be copied into: its own /// family's. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> { @@ -2062,106 +11080,20 @@ fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> { const BUFFERS: u32 = 2; -/// Luminance bounds of the host display when HDR (HDR10 / PQ) is active on -/// Windows. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct HdrDisplayInfo { - pub min_luminance: f32, - pub max_luminance: f32, - pub max_full_frame_luminance: f32, -} - -/// Queries the host display outputs for an active HDR10 (`G2084_NONE_P2020`) -/// desktop mode. Returns `None` when HDR is disabled or unsupported. -pub fn display_hdr_info() -> Option<HdrDisplayInfo> { - // SAFETY: plain DXGI factory, adapter and output enumeration. - unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; - let adapter: IDXGIAdapter1 = if let Some(host) = host() { - let luid = host.device.GetAdapterLuid(); - factory - .EnumAdapterByLuid::<IDXGIAdapter1>(luid) - .or_else(|_| factory.EnumAdapters1(0)) - .ok()? - } else { - factory.EnumAdapters1(0).ok()? - }; - let mut i = 0u32; - while let Ok(output) = adapter.EnumOutputs(i) { - i += 1; - let Ok(output6) = output.cast::<IDXGIOutput6>() else { - continue; - }; - let Ok(desc) = output6.GetDesc1() else { - continue; - }; - if desc.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020 { - return Some(HdrDisplayInfo { - min_luminance: desc.MinLuminance, - max_luminance: desc.MaxLuminance, - max_full_frame_luminance: desc.MaxFullFrameLuminance, - }); - } - } - None - } -} - -fn desired_color_space(format: DXGI_FORMAT, hdr_active: bool) -> DXGI_COLOR_SPACE_TYPE { - if !hdr_active { - return DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; - } - match format { - DXGI_FORMAT_R10G10B10A2_UNORM => DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020, - DXGI_FORMAT_R16G16B16A16_FLOAT => DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, - _ => DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, - } -} - struct Presenter { swap_chain: IDXGISwapChain3, width: u32, height: u32, format: DXGI_FORMAT, - color_space: DXGI_COLOR_SPACE_TYPE, copy: HostList, + /// With presents sent ahead ([`late_free_present`]): a list for each + /// present in the air, and the submission it last flew as (it is used + /// again once that one has finished). + ahead: Vec<(HostList, u64)>, hwnd: HWND, meter: Meter, } -impl Presenter { - fn sync_color_space(&mut self, hdr_active: bool) { - let wanted = desired_color_space(self.format, hdr_active); - if self.color_space == wanted { - return; - } - // SAFETY: `self.swap_chain` is a live `IDXGISwapChain3`. - let supported = unsafe { self.swap_chain.CheckColorSpaceSupport(wanted) }.unwrap_or(0); - if supported & (DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT.0 as u32) == 0 { - tracing::debug!( - color_space = wanted.0, - supported, - "swap chain color space unsupported on host output" - ); - return; - } - // SAFETY: `wanted` is supported for presentation on `self.swap_chain`. - match unsafe { self.swap_chain.SetColorSpace1(wanted) } { - Ok(()) => { - self.color_space = wanted; - tracing::info!( - format = self.format.0, - color_space = wanted.0, - "swap chain color space set" - ); - } - Err(e) => { - tracing::warn!(error = %e, color_space = wanted.0, "SetColorSpace1 failed"); - } - } - } -} - /// The frame rate, shown in the window's caption every second and logged /// every few seconds. struct Meter { @@ -2193,6 +11125,8 @@ impl Meter { fn frame(&mut self, hwnd: HWND) { #[cfg(feature = "diagnostics")] tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present"); + #[cfg(feature = "diagnostics")] + crate::copystat::presented(); self.frames += 1; #[cfg(feature = "diagnostics")] { @@ -2205,42 +11139,308 @@ impl Meter { let drawn = crate::draw::drawn(); let frames = f64::from(self.frames); let fps = frames / elapsed.as_secs_f64(); + crate::fpsbox::set(fps); let ms = elapsed.as_secs_f64() * 1000.0 / frames; let draws = (drawn - self.drawn) as f64 / frames; (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn); // Of a frame, ms preparing submissions and ms waiting for the GPU. - let [cpu, gpu] = - [0, 1].map(|i| SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + let [cpu, gpu] = [0, 1].map(|i| { + SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames + }); let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| { let scale = if i % 2 == 0 { 1e3 } else { 1e6 }; PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames }); - let [back_ms, back_mb] = - [0, 1].map(|i| COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames); + let [back_ms, back_mb] = [0, 1].map(|i| { + COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames + }); let dropped = crate::draw::take_dropped() as f64 / frames; let indirect = crate::list::take_indirect() as f64 / frames; - // Over the same frames as the counts above. + let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed); + let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; + tracing::info!( + "indirect mesh and compute dispatches: the largest group count asked for {mesh_largest} (run: at most 65535 a dimension), {mesh_groups:.0} groups asked per frame" + ); + let compute_widest = COMPUTE_GROUPS[0].swap(0, Ordering::Relaxed); + let compute_cut = COMPUTE_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; + tracing::info!( + "indirect compute dispatches: the largest group count in x asked for {compute_widest} (run: at most 65535), {compute_cut:.1} records per frame asked for more and were cut to that" + ); + let [spread_direct, spread_indirect] = + [0, 1].map(|i| crate::draw::SPREAD[i].swap(0, Ordering::Relaxed) as f64 / frames); + tracing::info!( + "dispatches spread across z past 65,535 groups in x (USER_DISPATCH_SPREAD), per frame: {spread_direct:.2} direct, {spread_indirect:.2} indirect run through the spread signature (programs that read no group id x, and the builder's stages, are not spread)" + ); + // (Run 200 counted indirect compute records asking for 77,000 to + // 98,000 groups in x, 0.2 to 0.8 a frame, cut to the 65,535 one + // dispatch runs; the counter went when the clamp's budget moved to + // the card's memory.) + { + let [texture_us, slots] = [0, 1].map(|i| crate::draw::HEAP_PASS_PARTS[i].swap(0, Ordering::Relaxed)); + tracing::info!( + "the pass over the heap per frame (the frame line's \"heap buffers ... ms\" is both parts): {:.1} ms in its pass over textures picked by index; {:.0} buffer slots looked at by its pass over buffer views", + texture_us as f64 / 1e3 / frames, + slots as f64 / frames + ); + } + crate::shadow::exact_line(frames); + crate::descriptor::sync_line(frames); + late_line(frames); + card_clock_line(frames, ms); + crate::queue2::line(frames); + crate::plaincopy::line(frames); + #[cfg(feature = "diagnostics")] + crate::backreads::line(frames); + crate::shadow::placed_line(); + if let Some(host) = host() { + host.drain_messages(); + } + { + let held = crate::pipeline::WALKS_HELD.swap(0, Ordering::Relaxed); + if held > 0 { + tracing::info!( + "dispatches of programs that walk ray-tracing structures held back per frame (VICTORY_BVH_HOLD=1; the builder has not built them): {:.1}", + held as f64 / frames + ); + } + } + crate::shadow::back_line(frames); + { + let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); + if passes + compares > 0.0 { + tracing::info!( + "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \ + ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes", + if rehash_runs() { "on" } else { "off" } + ); + } + } + { + let [own, asking, still, all] = + [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + if all >= 1.0 { + tracing::info!( + "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \ + is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \ + hold still (the runtime remapping it); the rest is reading, hashing and detiling" + ); + } + let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); + if through + left > 0.0 { + tracing::info!( + "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=0: wait): \ + {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there)" + ); + } + } + { + let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames); + let [on_card, card_bytes] = [0, 1].map(|i| GPU_COPIES[i].swap(0, Ordering::Relaxed) as f64 / frames); + if copies > 0.0 || on_card > 0.0 { + tracing::info!( + "title buffer copies recorded per frame: {copies:.0} on the CPU, of them {joined:.0} continue the one before \ + (VICTORY_JOIN_COPIES=1 makes those one copy with it: now {}); {on_card:.0} on the card, {:.2} MB \ + (VICTORY_GPU_COPIES: now {})", + if join_copies() { "on" } else { "off" }, + card_bytes / 1e6, + if gpu_copies() { "on" } else { "off" } + ); + } + } + // Passes over the heap's buffer views for shaders that pick them by index. + let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames; + let picked_ms = + crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames; + { + let [busy, detiling, lists, shown, again, left] = + std::array::from_fn::<f64, 6, _>(|i| crate::heap_worker::STATS[i].swap(0, Ordering::Relaxed) as f64 / frames); + if busy > 0.0 { + tracing::info!( + "textures picked by index, their own thread (VICTORY_HEAP_WORKER), per frame: {:.1} ms at work, of them {:.1} detiling; \ + {lists:.1} lists, {shown:.0} slots shown, {again:.1} written again before, {left:.1} textures left to the submission", + busy / 1e6, + detiling / 1e6 + ); + } + } + // Copies between depth textures and their colour twins, each way. + let [twin_to_depth, twin_to_colour] = + [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames); + // Depth planes drawn from their twins. + let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames; + // Copies in the card's memory (`crate::shadow::cards`). + let card = crate::shadow::card_stats(); #[cfg(feature = "diagnostics")] + let slow = crate::watch::slow_asks(); + // Over the same frames as the counts above. let drops = crate::pipeline::take_drops(); if self.logged.elapsed() >= std::time::Duration::from_secs(5) { self.logged = std::time::Instant::now(); + tracing::info!( + "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)", + crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed) + ); + tracing::info!( + "copies left out since the start because both sides were one host texture: {}", + crate::list::SELF_COPIES.load(Ordering::Relaxed) + ); + if crate::drvwatch::errors() > 0 { + tracing::warn!( + "errors the graphics driver reported to the system since the start: {} (the paths under suspicion are off)", + crate::drvwatch::errors() + ); + } + crate::tiles::status(); + { + let [queued, due, away, partly, oldest] = + [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); + let [same, parts, tails] = + [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed)); + tracing::info!( + "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \ + {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \ + the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \ + as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \ + {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \ + {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \ + {} made slots found unmapped and made null", + crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed), + crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed), + crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed), + crate::descriptor::host::STALE[0].load(Ordering::Relaxed), + crate::descriptor::host::STALE[1].load(Ordering::Relaxed), + crate::descriptor::host::STALE[2].load(Ordering::Relaxed), + crate::descriptor::host::STALE[3].load(Ordering::Relaxed), + crate::descriptor::host::STALE[4].load(Ordering::Relaxed) + ); + } + { + let mode = crate::watch::page_writes(); + let [writes, bytes, guarded, plain, told] = [0, 1, 2, 3, 4].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); + let [kept, dropped, slots, uploaded] = + [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed)); + tracing::info!( + "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}; {told} passed to the texture pass); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset = guards and slots, plain reads' textures too; guards, 0 counts only, 1, slots, all)", + bytes >> 20, + if mode & 1 != 0 { "opened, taken again" } else { "left as they were" }, + if mode & 4 != 0 { "told as well" } else { "counted only" }, + if mode & 2 != 0 { "made due again" } else { "left as they were" } + ); + } + #[cfg(feature = "diagnostics")] + tracing::info!( + "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms", + slow[0] as f64 / frames, + slow[1] as f64 / 1e3 / frames, + slow[2] as f64 / 1e3 + ); + video_memory_line(); + crate::shadow::windows_line(); + if crate::shadow::cards() { + let per_frame = |i: usize| card[i] as f64 / frames; + tracing::info!( + "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \ + {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \ + ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)", + card[7], + card[8] >> 20, + card[9] >> 20, + per_frame(0) / 1e6, + per_frame(1), + per_frame(2), + per_frame(3), + per_frame(4) / 1e6, + per_frame(5), + per_frame(6) / 1e3 + ); + } tracing::info!( "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \ - dropped {dropped:.0} without a host pipeline ({making} being made) and \ - {indirect:.0} indirect", - making = crate::pipeline::making() + dropped {dropped:.0} without a host pipeline ({making} being made; {stand_ins} drawn with a stand-in so far) and \ + {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \ + textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \ + {picked_waiting} waiting, {picked_away} passed over unmapped; depth textures with unordered access: {du0} made, bound as depth {du1}x, cleared as depth {du2}x, unordered views refused {du3}x; buffer views left null as the host would refuse them: {refused}; \ + upload buffers in the card's memory (Resizable BAR) so far: {bar_uploads} ({bar_mb} MB); \ + title buffers compared on the card from the PC's memory: {pc_card_mb} MB alive; \ + rewritten unchanged, not sent to the card: {same_mb:.1} MB a frame", + same_mb = crate::shadow::same_skipped() as f64 / (1 << 20) as f64 / frames.max(1.0), + bar_uploads = GPU_UPLOADS[0].load(Ordering::Relaxed), + bar_mb = GPU_UPLOADS[1].load(Ordering::Relaxed) >> 20, + pc_card_mb = crate::shadow::pc_card_bytes() >> 20, + picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed), + picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20, + picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed), + picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed), + du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed), + du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed), + du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed), + du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed), + refused = format!( + "{} (and {} empty ones left null as on the console, {} raw ones made typed); depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass", + crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed), + crate::descriptor::host::EMPTY_VIEWS.load(Ordering::Relaxed), + crate::descriptor::host::RAW_TYPED_VIEWS.load(Ordering::Relaxed), + crate::resource::TWINS[0].load(Ordering::Relaxed), + crate::resource::TWINS[1].load(Ordering::Relaxed), + crate::resource::PLANES[1].load(Ordering::Relaxed), + crate::resource::PLANES[2].load(Ordering::Relaxed) + ), + making = crate::pipeline::making(), + stand_ins = crate::pipeline::stand_ins(), + placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed), + objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed) ); - #[cfg(feature = "diagnostics")] { - crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64); - for (why, n) in drops.iter().take(40) { - tracing::info!( - "dropped {:.1}/frame without a host pipeline: {why}", - *n as f64 / frames - ); - } + let spare = UPLOAD_SPARE.lock().unwrap_or_else(|e| e.into_inner()); + tracing::info!( + "{}; list upload buffers since the start: {} reused, {} made; {} kept ({} MB)", + crate::pressure::report(), + UPLOAD_REUSE[0].load(Ordering::Relaxed), + UPLOAD_REUSE[1].load(Ordering::Relaxed), + spare.kept.len(), + spare.bytes >> 20 + ); + } + // 5.7: where the card's memory goes, in every build (the + // reports said the card stood past its budget, not by what). + { + use crate::resource::{HOST_TEXTURES, KINDS}; + let staged = crate::texture::staged_alive(); + let all = HOST_TEXTURES[1].load(Ordering::Relaxed); + let filled = KINDS[1].load(Ordering::Relaxed); + tracing::info!( + "card memory by kind: {} host textures {} MB, of them {} the title fills {} MB and the rest (render targets, depth, the card's own writes) {} MB; tiles given to textures made level by level {} MB; staging buffers {} ({} MB); upload buffers made in the card's memory so far {} MB; console {}", + HOST_TEXTURES[0].load(Ordering::Relaxed), + all >> 20, + KINDS[0].load(Ordering::Relaxed), + filled >> 20, + all.saturating_sub(filled) >> 20, + crate::tiles::given_total() >> 20, + staged[0], + staged[1] >> 20, + GPU_UPLOADS[1].load(Ordering::Relaxed) >> 20, + crate::console::current().name() + ); + } + { + tracing::info!( + "sharper image (5.8): texture levels left out now {}, textures made sharp again {}, textures the rush made soft made whole again {}, slots given a placeholder instead of black {}", + crate::tiles::top_dropped(), + crate::descriptor::host::sharpen(0), + crate::descriptor::host::unrush(0), + crate::descriptor::host::PLACEHOLDERS_SHOWN.load(Ordering::Relaxed) + ); + } + #[cfg(feature = "diagnostics")] + crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64); + // (every build since 4.8: which programs the dropped draws were) + for (why, n) in drops.iter().take(if cfg!(feature = "diagnostics") { 40 } else { 12 }) { + tracing::info!( + "dropped {:.1}/frame without a host pipeline: {why}", + *n as f64 / frames + ); } } if self.caption.is_none() { @@ -2284,7 +11484,39 @@ impl Host { /// Shows `texture`, which is in `state` (a host state) and stays in it, /// as frame `frame` (saved if captures are on). `None` if nothing was /// shown; else, in diagnostics builds, whether the frame was black. - pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> { + /// + /// `over`: the present's second plane and its host state (the title's + /// interface over its game image, in its Series S mode), drawn over the + /// copy ([`crate::over`], fxceless/victory-fork#188). + pub(crate) fn present( + &self, + texture: &ID3D12Resource, + state: u32, + frame: u64, + over: Option<(&ID3D12Resource, u32)>, + ) -> Option<bool> { + let showing = std::time::Instant::now(); + let shown = self.present_now(texture, state, frame, over); + crate::framelog::add(crate::framelog::T::PresentShowUs, showing.elapsed().as_micros() as u64); + shown + } + + fn present_now( + &self, + texture: &ID3D12Resource, + state: u32, + frame: u64, + over: Option<(&ID3D12Resource, u32)>, + ) -> Option<bool> { + // A smaller render size scaled up, or frames in between (Try 4.2); + // not with a second plane, which only the plain copy draws (Series + // S renders smaller and upscales by itself). + if over.is_none() + && presentfx::on() + && let Some(shown) = presentfx::present(self, texture, state) + { + return shown; + } // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; let Some(format) = swap_format(desc.Format) else { @@ -2304,27 +11536,31 @@ impl Host { } let p = presenter.as_mut()?; if (p.width, p.height, p.format) != (width, height, format) { + // Presents sent ahead hold back buffers until they have run. + settle_now(WHY_SYNC); // SAFETY: no back buffer is held; every submission was waited for. let resized = unsafe { p.swap_chain .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0)) }; match resized { - Ok(()) => (p.width, p.height, p.format) = (width, height, format), + Ok(()) => { + (p.width, p.height, p.format) = (width, height, format); + tracing::info!( + width, + height, + format = format.0, + frame, + "the swap chain's buffers were made again for another size or format" + ); + self.log_video_memory("right after the swap chain's buffers were made again"); + } Err(e) => { tracing::warn!(error = %e, width, height, "swap chain not resized"); return None; } } } - if matches!( - format, - DXGI_FORMAT_R10G10B10A2_UNORM | DXGI_FORMAT_R16G16B16A16_FLOAT - ) { - p.sync_color_space(display_hdr_info().is_some()); - } else { - p.sync_color_space(false); - } let state = D3D12_RESOURCE_STATES(state as i32); // SAFETY: our swap chain, list and a live source texture. unsafe { @@ -2332,8 +11568,30 @@ impl Host { let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else { return None; }; - p.copy.reset(); - let list = &p.copy.list; + // Sent ahead ([`late_free_present`]) unless the frame is to be + // read back at once (a saved or listed frame): then a list of + // its own, one whose last flight has finished or a new one. + #[cfg(feature = "diagnostics")] + let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame); + #[cfg(not(feature = "diagnostics"))] + let read_now = false; + let slot = if late_free_present() && !read_now { + let finished = FINISHED.load(Ordering::Acquire); + p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| { + let list = self.new_list().ok()?; + list.close(); + p.ahead.push((list, 0)); + Some(p.ahead.len() - 1) + }) + } else { + None + }; + let copy = match slot { + Some(i) => &p.ahead[i].0, + None => &p.copy, + }; + copy.reset(); + let list = ©.list; list.ResourceBarrier(&[ transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), transition( @@ -2342,37 +11600,90 @@ impl Host { D3D12_RESOURCE_STATE_COPY_DEST, ), ]); - // Diagnostics: `VICTORY_SHOW_TARGET` shows one of the title's render targets instead. - #[cfg(feature = "diagnostics")] - let shown = crate::capture::show(list, &back); - #[cfg(not(feature = "diagnostics"))] - let shown = false; - if !shown { - list.CopyResource(&back, texture); - } + list.CopyResource(&back, texture); + // The frame rate, into the corner of what is shown (not of the + // title's own frame, which the lines below read back). + crate::fpsbox::draw(self, list, &back, (width, height, format)); #[cfg(feature = "diagnostics")] let capture = crate::capture::wanted(frame) .then(|| crate::capture::read_back(&self.device, list, texture)) .flatten(); #[cfg(feature = "diagnostics")] - let probe = crate::capture::probe(&self.device, list, texture); + let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; #[cfg(not(feature = "diagnostics"))] let _ = frame; - list.ResourceBarrier(&[ - transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), - transition( + // The present's second plane, if it has one, goes over the copy + // ([`crate::over`]): the back buffer is a target meanwhile. + let readable = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + let over = over.and_then(|(plane, was)| { + // SAFETY: a live resource. + let plane_format = swap_format(plane.GetDesc().Format)?; + Some((plane, D3D12_RESOURCE_STATES(was as i32), plane_format)) + }); + if let Some((plane, was, plane_format)) = over { + let mut barriers = vec![ + transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), + transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_RENDER_TARGET, + ), + ]; + let moved = was.0 & readable.0 == 0; + if moved { + barriers.push(transition(plane, was, readable)); + } + list.ResourceBarrier(&barriers); + let _ = crate::over::record( + &self.device, + list, &back, - D3D12_RESOURCE_STATE_COPY_DEST, + format, + (width, height), + plane, + plane_format, + ); + let mut barriers = vec![transition( + &back, + D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT, - ), - ]); - p.copy.close(); - self.execute(&[&p.copy]); + )]; + if moved { + barriers.push(transition(plane, readable, was)); + } + list.ResourceBarrier(&barriers); + } else { + list.ResourceBarrier(&[ + transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), + transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PRESENT, + ), + ]); + } + copy.close(); + match slot { + Some(i) => { + let flown = self.execute_own(copy); + p.ahead[i].1 = flown; + } + None => self.execute(&[copy]), + } #[cfg(feature = "diagnostics")] if let Some((buffer, footprint)) = capture { crate::capture::save_read_back(frame, &buffer, &footprint); } - let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + // What Present answers was thrown away: a removal it is the + // first to report then looked as if the next call found it. + // Said once (a status that is no error, as "occluded", is not). + let shown = p.swap_chain.Present(0, DXGI_PRESENT(0)); + if shown.is_err() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::error!("Present answered {:#010x} (said once): the first call to report it, frame {frame}", shown.0 as u32); + }); + } p.meter.frame(p.hwnd); #[cfg(feature = "diagnostics")] return Some(probe.is_some_and(|b| crate::capture::black(&b))); @@ -2391,6 +11702,7 @@ impl Host { Some(hwnd) => hwnd, None => window(width, height)?, }; + self.log_video_memory("right before the swap chain is made"); // SAFETY: plain object creation for our window. unsafe { let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; @@ -2413,18 +11725,17 @@ impl Host { let copy = self.new_list()?; copy.close(); tracing::info!(width, height, format = format.0, "presenting to a window"); - let mut p = Presenter { + self.log_video_memory("right after the swap chain is made"); + Ok(Presenter { swap_chain, width, height, format, - color_space: DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, copy, + ahead: Vec::new(), hwnd, meter: Meter::new(), - }; - p.sync_color_space(display_hdr_info().is_some()); - Ok(p) + }) } } } @@ -2477,11 +11788,203 @@ pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { } impl Host { + /// The card's memory as the system accounts it to this process, in + /// bytes: the budget and the use of the card's own memory, then of the + /// PC's memory shared with the card (where the system moves what does + /// not fit on the card). + pub(crate) fn video_memory(&self) -> Option<[u64; 4]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + // The card's budget moved by 256 MB or more since the last look: + // said at once, with what was in use at the last look, so the log + // has the moment. (It fell from 11,242 MB to some 10,300 MB with + // the first world frame in runs 179 to 185, and the memory line, + // seconds later, was the first to show it. We reserve nothing + // and make the swap chain once, at the start.) + static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage]; + let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed)); + if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) { + tracing::info!( + "the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use", + last[0] >> 20, + own.Budget >> 20, + crate::frame::current(), + last[1] >> 20, + last[2] >> 20 + ); + self.log_video_memory("right after that change"); + } + // For the line between the memory lines ([`video_memory_line`]). + VIDEO_PEAK[0].fetch_max(own.CurrentUsage, Ordering::Relaxed); + VIDEO_PEAK[1].fetch_min(own.Budget, Ordering::Relaxed); + VIDEO_PEAK[2].fetch_max(shared.CurrentUsage, Ordering::Relaxed); + VIDEO_PEAK[3].fetch_add(1, Ordering::Relaxed); + // And for the seconds a removal's report says ([`SECOND_ROWS`]). + second_look(own.Budget, own.CurrentUsage, shared.CurrentUsage); + Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage]) + } + + /// One look at the card's memory of our own, at most every tenth of a + /// second, before a submission is prepared: for [`VIDEO_PEAK`], and so + /// that a change of the budget is said within a tenth of a second + /// ([`Self::video_memory`]). Two plain questions to the system. + fn video_memory_look(&self) { + if !video_look_on() { + return; + } + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let now = now_ms(); + let last = LAST.load(Ordering::Relaxed); + if now < last + 100 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + let _ = self.video_memory(); + } + + /// Both of the system's memory groups for this process, in bytes: for + /// the card's own memory and then for the PC's memory shared with the + /// card, the budget, the use, what could still be reserved and what + /// is reserved (the layer reserves none). + pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| { + [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation] + }; + Some([all(&own), all(&shared)]) + } + + /// Logs [`Self::video_memory_groups`], with `when` it is said. + pub(crate) fn log_video_memory(&self, when: &str) { + let Some([own, shared]) = self.video_memory_groups() else { + return; + }; + tracing::info!( + "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)", + when, + own[0] >> 20, + own[1] >> 20, + own[2] >> 20, + own[3] >> 20, + shared[0] >> 20, + shared[1] >> 20, + shared[2] >> 20, + shared[3] >> 20 + ); + } + + /// Whether the device has GPU upload heaps ([`GPU_UPLOAD`]). + pub(crate) fn gpu_upload(&self) -> bool { + GPU_UPLOAD.load(Ordering::Relaxed) + } + + /// A buffer in the card's own memory that the CPU maps and writes (a + /// GPU upload heap; write-combined: reading it back is slow, and + /// nothing of ours does) and shaders read: for host copies the CPU + /// fills and no shader writes. `None` where the device has no such + /// heaps or turns the buffer down (then the caller's usual buffer). + pub(crate) fn gpu_upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + if !self.gpu_upload() { + return None; + } + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_GPU_UPLOAD, + ..Default::default() + }; + // (Unordered access allowed, as the buffers it stands in for: a + // view of that kind over a window must still be makeable.) + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of a CPU-visible buffer. + let made = unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match (made, buffer) { + (Ok(()), Some(buffer)) if !data.is_null() => { + // The first one is tried before any is used: title memory + // reaches a host copy by a plain copy and, where a page is + // not there, through the kernel (`read`), and this memory + // is the card's, mapped through the bus. Both ways must + // write it and it must read back the same, or no copy goes + // to such a heap in this run. + static WORKS: OnceLock<bool> = OnceLock::new(); + let works = *WORKS.get_or_init(|| { + let n = (size as usize).min(8192); + let pattern: Vec<u8> = (0..n).map(|i| (i * 31 + 7) as u8).collect(); + let half = n / 2; + // SAFETY: the buffer's own mapping, `size` bytes of it; a + // source of ours. + let same = unsafe { + std::ptr::copy_nonoverlapping(pattern.as_ptr(), data.cast::<u8>(), half); + let by_kernel = read(pattern[half..].as_ptr(), data.cast::<u8>().add(half), n - half); + by_kernel && std::slice::from_raw_parts(data.cast::<u8>(), n) == pattern.as_slice() + }; + // SAFETY: as above (left as a fresh buffer is: zeroed). + unsafe { std::ptr::write_bytes(data.cast::<u8>(), 0, n) }; + if same { + tracing::info!("a buffer in a GPU upload heap takes a plain copy and the kernel's copy and reads back the same: such heaps are used"); + } else { + tracing::warn!("a buffer in a GPU upload heap did not read back what was written into it: such heaps are not used in this run"); + } + same + }); + works.then_some((buffer, data.cast())) + } + (made, _) => { + // Said once: every later one would say the same. + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(size, result = ?made, "a buffer in a GPU upload heap could not be made or mapped: such copies stay in the PC's memory") + }); + None + } + } + } + /// A buffer in system memory that the CPU maps (write-back, so reading /// it is fast too) and shaders read and write: for host copies of title /// memory that shaders write, which upload memory cannot be. Starts in /// the common state (buffers move out of it implicitly). pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + MADE[2].fetch_add(1, Ordering::Relaxed); + MADE[3].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, @@ -2529,9 +12032,11 @@ impl Host { } } - /// A GPU-only default-heap buffer that shaders can write (unordered - /// access). Starts in the common state. - pub(crate) fn default_buffer(&self, size: u64) -> Option<ID3D12Resource> { + /// A device-local buffer shaders may write (unordered access) and indirect + /// execution may read, starting in the common state. + pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> { + MADE[4].fetch_add(1, Ordering::Relaxed); + MADE[5].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() @@ -2551,7 +12056,7 @@ impl Host { ..Default::default() }; let mut buffer: Option<ID3D12Resource> = None; - // SAFETY: plain creation of a default-heap buffer. + // SAFETY: plain creation of a device-local buffer. let made = unsafe { self.device.CreateCommittedResource( &heap, @@ -2565,7 +12070,7 @@ impl Host { match made { Ok(()) => buffer, Err(e) => { - tracing::warn!(error = %e, size, "no default buffer"); + tracing::warn!(error = %e, size, "no unordered-access buffer"); None } } @@ -2582,11 +12087,7 @@ fn last_notes(runs: &[&HostList]) -> String { for (i, r) in runs.iter().enumerate() { let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); for (n, _) in notes.iter().rev().take(6).rev() { - text.push_str(&format!( - "; list {i} of {}, of its {}: {n}", - runs.len(), - notes.len() - )); + text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len())); } } text @@ -2617,23 +12118,19 @@ fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String { /// barriers overlaps on the GPU), by kind, and what the markers just /// before them say (`HostList::note_op`: diagnostics builds with /// device-removed data on). -fn in_flight( - history: &[D3D12_AUTO_BREADCRUMB_OP], - markers: &[(u32, String)], - done: usize, -) -> String { +fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String { let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER; - let from = history[..done] - .iter() - .rposition(barrier) - .map_or(0, |b| b + 1); + let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1); let to = history[done..] .iter() .position(barrier) .map_or(history.len(), |b| (done + b).max(done + 1)); let mut text = format!(", commands {from}..{to} between its barriers:"); let mut shown = 0; - for i in from..to { + // From just before the command the GPU had not finished: the first + // twelve after the barrier named draws long done when a list of 79 + // mesh draws stopped at its 45th (run 41). + for i in from.max(done.saturating_sub(4))..to { let op = history[i]; if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 { continue; @@ -2748,158 +12245,56 @@ fn pump() { } } -fn adapter_name(raw: &[u16]) -> String { - let len = raw.iter().position(|&c| c == 0).unwrap_or(raw.len()); - String::from_utf16_lossy(&raw[..len]) -} - -fn adapter_matches(name: &str, filter: &str) -> bool { - name.to_ascii_lowercase() - .contains(&filter.trim().to_ascii_lowercase()) -} - -/// Picks a D3D12-capable adapter, preferring the high-performance GPU on -/// dual-GPU systems so integrated graphics are not chosen over a discrete GPU. -/// When `filter` is given (`VICTORY_ADAPTER`), requires a case-insensitive -/// substring match on the adapter description. -fn pick_hardware_adapter( - filter: Option<&str>, -) -> windows::core::Result<(IDXGIAdapter1, DXGI_ADAPTER_DESC1)> { - // SAFETY: plain DXGI enumeration and D3D12 capability probe. - unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; - let factory6 = factory.cast::<IDXGIFactory6>().ok(); - let mut i = 0u32; - loop { - let adapter: IDXGIAdapter1 = match &factory6 { - Some(f6) => { - match f6.EnumAdapterByGpuPreference(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE) { - Ok(a) => a, - Err(e) if e.code() == DXGI_ERROR_NOT_FOUND => break, - Err(e) => return Err(e), - } - } - None => match factory.EnumAdapters1(i) { - Ok(a) => a, - Err(e) if e.code() == DXGI_ERROR_NOT_FOUND => break, - Err(e) => return Err(e), - }, - }; - i += 1; - let desc = adapter.GetDesc1()?; - let is_sw = desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0; - if let Some(needle) = filter { - if !adapter_matches(&adapter_name(&desc.Description), needle) { - continue; - } - } else if is_sw { - continue; - } - if D3D12CreateDevice( - &adapter, - D3D_FEATURE_LEVEL_12_0, - std::ptr::null_mut::<Option<ID3D12Device>>(), - ) - .is_ok() - { - return Ok((adapter, desc)); - } +#[cfg(test)] +mod trail { + /// The trail keeps the newest things, and the report made when the + /// host device is removed says them and the pipeline library's state + /// (no card is asked for any of it). + #[test] + fn the_removal_report_says_the_newest_things_done() { + for n in 0..super::TRAIL_MOST + 5 { + super::trail(|| format!("thing {n} done")); } - Err(windows::core::Error::from_hresult(DXGI_ERROR_NOT_FOUND)) + let text = super::removal_context(); + assert!(text.contains("the submitting thread was")); + assert!(text.contains("pipeline library: no call running")); + assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4))); + assert!(!text.contains("thing 4 done"), "the oldest entries are dropped"); } } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn warp_adapter_accepts_only_software() { - // This probes DXGI without creating a D3D12 device or running a title. - // SAFETY: plain DXGI adapter queries. - let raw = unsafe { - let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)) - else { - return; - }; - factory.EnumWarpAdapter::<IDXGIAdapter>() - }; - let Ok(raw) = raw else { return }; - // SAFETY: a live adapter the factory just returned. - let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() }; - eprintln!( - "EnumWarpAdapter: vendor={:#x}, flags={:#x}", - desc.VendorId, desc.Flags - ); - assert_eq!( - warp_adapter().is_ok(), - desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, - ); - } - - #[test] - fn adapter_name_stops_at_nul() { - let raw = [b'R' as u16, b'T' as u16, b'X' as u16, 0, b'X' as u16]; - assert_eq!(adapter_name(&raw), "RTX"); - assert_eq!(adapter_name(&[b'X' as u16, b'e' as u16]), "Xe"); - } +mod spare { + use super::Spare; + /// Kept things come back by size, the last given first, and nothing is + /// kept past the limit. #[test] - fn warp_switch_takes_zero_as_off() { - use std::ffi::OsStr; - // Unset, `0`, `1`, empty, and a value the README does not name. - assert!(!warp_switch(None), "unset"); - assert!(!warp_switch(Some(OsStr::new("0"))), "`0` turns it off"); - assert!(warp_switch(Some(OsStr::new("1")))); - assert!(warp_switch(Some(OsStr::new(""))), "empty is set"); - assert!( - warp_switch(Some(OsStr::new("yes"))), - "any other value is on" - ); - } - - #[test] - fn adapter_filter_matches_case_insensitively() { - assert!(adapter_matches("NVIDIA GeForce RTX 3070 Ti", "rtx 3070")); - assert!(adapter_matches("Intel(R) Iris(R) Xe Graphics", " INTEL ")); - assert!(!adapter_matches("Intel(R) Iris(R) Xe Graphics", "RTX")); - } - - #[test] - fn unknown_adapter_filter_fails_instead_of_falling_back() { - let err = pick_hardware_adapter(Some("__victory_no_such_adapter__")).unwrap_err(); - assert_eq!(err.code(), DXGI_ERROR_NOT_FOUND); - } - - #[test] - fn default_adapter_is_hardware_when_present() { - if let Ok((_, desc)) = pick_hardware_adapter(None) { - assert_eq!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32, 0); - } + fn kept_things_come_back_by_size_within_the_limit() { + let mut spare: Spare<u32> = Spare::new(); + assert_eq!(spare.take(4), None); + assert_eq!(spare.give(1, 4, 10), None); + assert_eq!(spare.give(2, 1, 10), None); + assert_eq!(spare.give(3, 4, 10), None); + assert_eq!(spare.bytes, 9); + // Past the limit: handed back, nothing changes. + assert_eq!(spare.give(4, 4, 10), Some(4)); + assert_eq!(spare.bytes, 9); + assert_eq!(spare.take(2), None, "no thing of that size"); + assert_eq!(spare.take(4), Some(3)); + assert_eq!(spare.take(4), Some(1)); + assert_eq!(spare.take(4), None); + assert_eq!(spare.take(1), Some(2)); + assert_eq!(spare.bytes, 0); + assert!(spare.kept.is_empty()); } } #[cfg(test)] -mod batch { - // Batch::texture_due lives here; `mod tests` is already taken above +mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file use super::Batch; use std::sync::Arc; - #[test] - fn exact_gpu_writes_are_declared_once_per_submission() { - let mut batch = Batch::default(); - let (a, b) = (Arc::new(0), Arc::new(0)); - assert!(batch.new_gpu_write(&a, 4096, 16)); - assert!(!batch.new_gpu_write(&a.clone(), 4096, 16)); - assert!(batch.new_gpu_write(&a, 4096, 32)); - assert!(batch.new_gpu_write(&a, 4104, 16)); - assert!(batch.new_gpu_write(&b, 4096, 16)); - // CPU copies can flush refreshes, but these GPU writes stay pending. - batch.title_written(); - assert!(!batch.new_gpu_write(&a, 4096, 16)); - assert!(Batch::default().new_gpu_write(&a, 4096, 16)); - } - #[test] fn a_texture_is_checked_once_per_submission() { let mut batch = Batch::default(); @@ -2967,4 +12362,414 @@ mod batch { before.as_secs_f64() / after.as_secs_f64() ); } + + #[test] + fn vram_idle_ms_scales_with_pressure() { + use super::vram_idle_ms; + let gib = 1024 * 1024 * 1024; + // Normal (< 75%) + assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000); + assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000); + assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000); + // Moderate (75%..85%) + assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500); + assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500); + // High (>= 85%, including over-budget) + assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000); + assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000); + // Missing or zero budget falls back to normal + assert_eq!(vram_idle_ms(None), 5_000); + assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000); + } + + #[test] + fn upload_classes_are_powers_of_two_from_64_kib() { + use super::upload_class; + assert_eq!(upload_class(1), Some(64 << 10)); + assert_eq!(upload_class(64 << 10), Some(64 << 10)); + assert_eq!(upload_class((64 << 10) + 1), Some(128 << 10)); + assert_eq!(upload_class(5 << 20), Some(8 << 20)); + assert_eq!(upload_class(32 << 20), Some(32 << 20)); + assert_eq!(upload_class((32 << 20) + 1), None); + } + + #[test] + fn spare_trims_the_oldest_first() { + let mut spare = super::Spare::<u8>::new(); + assert!(spare.give(1, 10, 100).is_none()); + assert!(spare.give(2, 20, 100).is_none()); + assert!(spare.give(3, 30, 100).is_none()); + let out = spare.trim(35); + assert_eq!(out.iter().map(|t| t.0).collect::<Vec<_>>(), vec![1, 2]); + assert_eq!(spare.bytes, 30); + assert_eq!(spare.take(30), Some(3)); + assert!(spare.trim(0).is_empty()); + } + + #[test] + fn ram_idle_ms_scales_with_pressure() { + use super::ram_idle_ms; + let gib = 1024 * 1024 * 1024; + // Normal (>= 4 GiB) + assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000); + assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000); + // Moderate (2 GiB..4 GiB) + assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000); + assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000); + // High (< 2 GiB) + assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000); + assert_eq!(ram_idle_ms(Some(0)), 2_000); + // Missing falls back to normal + assert_eq!(ram_idle_ms(None), 10_000); + } +} + +/// The host's own paths for a copy in the card's memory, end to end, on +/// the software adapter only: the title's bytes go up, a shader reads them +/// and writes, and what it wrote comes back into title memory. Run it with +/// the switches under test in the environment (they are read once per +/// process); it does nothing unless the host device is the software +/// adapter (`VICTORY_D3D12_WARP=1` in a diagnostics build) and the copy is +/// in the card's memory (`VICTORY_CARD_BUFFERS_MIN_MB=1`): +/// +/// `VICTORY_D3D12_WARP=1 VICTORY_CARD_BUFFERS_MIN_MB=1 [VICTORY_QUEUE2=n] +/// [VICTORY_RELAY=2 | VICTORY_LATE_WAIT=3] cargo test -p victory-gpu +/// --features diagnostics queue2_tests` +/// +/// The same title memory must come out whatever the switches: through the +/// direct queue alone, and through the copy queues. +#[cfg(test)] +mod queue2_tests { + use super::*; + + /// `memory[to] = memory[from] + add`, after `spin` steps. + const ADD: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0)" +cbuffer What : register(b0) { uint to; uint from; uint add; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint h = 0u; + [loop] + for (uint i = 0u; i < spin; i++) { + h = (h ^ memory.Load(from)) * 0x01000193u; + } + memory.Store(to, memory.Load(from) + add + (h & 0u)); +} +"#; + + #[test] + fn warp_title_bytes_go_up_and_shader_writes_come_back_whatever_the_queues() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x0020_0000; + let Some(host) = host() else { + return; + }; + // Never on a real card. + // SAFETY: a plain query. + let software = host + .adapter + .as_ref() + .and_then(|a| unsafe { a.GetDesc1() }.ok()) + .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); + if !software { + eprintln!("queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)"); + return; + } + const PIECE: usize = 64 << 10; + const LEN: usize = 4 << 20; + const ROUNDS: usize = 12; + // "Title memory": write-watched, as the title's is. + // SAFETY: a plain allocation of our own. + let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; + assert!(!title.is_null()); + let dword = |at: usize| unsafe { title.add(at).cast::<u32>() }; + for i in 0..LEN / 4 { + // SAFETY: inside the allocation. + unsafe { dword(i * 4).write_volatile(0x5A00_0000 | i as u32) }; + } + crate::shadow::register(0x51_5151, title as u64, LEN as u64); + let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); + if !shadow.carded() { + eprintln!("queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)"); + return; + } + let code = compile(ADD, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); + // SAFETY: the shader's own root signature; plain creation. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); + let pso = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .expect("a pipeline"); + (root, pso) + }; + // Round k: the title writes a dword in piece 1+k; a submission's + // shader adds k to it and stores the sum in piece 30+k, a range + // declared as shader-written. Nothing is waited for between the + // rounds where submissions are sent ahead. + let from = |k: usize| (1 + k) * PIECE + 4 * k + 64; + let to = |k: usize| (30 + k) * PIECE + 8 * k + 128; + let titles = |k: usize| 0x0100_0000 + 0x1000 * k as u32 + 7; + let mut lists = Vec::new(); + for k in 0..ROUNDS { + // SAFETY: inside the allocation. + unsafe { dword(from(k)).write_volatile(titles(k)) }; + let list = host.new_list().expect("a host list"); + shadow.refresh(&list, title as u64, LEN as u64); + shadow.gpu_writes(&list, (title as usize + (30 + k) * PIECE) as u64, PIECE as u64); + // SAFETY: an open list; the copy's buffer, with unordered + // access; the shader's own root signature. + unsafe { + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + let constants = [to(k) as u32, from(k) as u32, k as u32, 30_000]; + list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + list.list.Dispatch(1, 1, 1); + } + list.close(); + if late() { + host.execute_own(&list); + } else { + host.execute(&[&list]); + } + lists.push(list); + } + settle_now(WHY_SYNC); + for k in 0..ROUNDS { + // SAFETY: inside the allocation. + let (sum, kept) = unsafe { (dword(to(k)).read_volatile(), dword(from(k)).read_volatile()) }; + assert_eq!(kept, titles(k), "round {k}: the title's own dword changed"); + assert_eq!( + sum, + titles(k) + k as u32, + "round {k}: the shader read {:#x} where the title had written {:#x}, or its write did not come back", + sum.wrapping_sub(k as u32), + titles(k) + ); + } + // Nothing else moved. + let touched: std::collections::HashSet<usize> = (0..ROUNDS).flat_map(|k| [from(k), to(k)]).collect(); + for i in (0..LEN / 4).filter(|i| !touched.contains(&(i * 4))) { + // SAFETY: inside the allocation. + let got = unsafe { dword(i * 4).read_volatile() }; + assert_eq!(got, 0x5A00_0000 | i as u32, "dword {i} of title memory changed"); + } + // The queues the switches name did the work. + if let Some(second) = crate::queue2::second() { + let (down, up) = (second.down.stats.jobs.load(Ordering::Relaxed), second.up.stats.jobs.load(Ordering::Relaxed)); + // (Sends that found no landing buffer went the old way.) + let no_room = second.landing[1].load(Ordering::Relaxed); + eprintln!( + "queue2_tests: VICTORY_QUEUE2={} late {} relay {}: {down} fetches and {up} sends through the copy queues ({no_room} more found no landing buffer), the direct queue told to wait {} times", + crate::queue2::bits(), + late(), + relay(), + second.held[0].load(Ordering::Relaxed) + ); + assert_eq!(down > 0, second.fetches(), "fetches through the copy queue"); + assert_eq!(up + no_room > 0, second.uploads(), "sends through the copy queue"); + assert_eq!(up, second.held[0].load(Ordering::Relaxed), "the direct queue waits for every send"); + } else { + eprintln!("queue2_tests: the direct queue alone (late {}, relay {})", late(), relay()); + } + drop(lists); + } + + /// `memory[to] = first` at once; then `spin` steps, each a store to + /// `memory[to + 4]`; then `memory[to + 4] = 0` and `memory[to] = last`. + /// Whatever `spin` is, the bytes it leaves are the same. + const TWICE: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0)" +cbuffer What : register(b0) { uint to; uint first; uint last; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + memory.Store(to, first); + [loop] + for (uint i = 0u; i < spin; i++) { + memory.Store(to + 4u, i); + } + memory.Store(to + 4u, 0u); + memory.Store(to, last); +} +"#; + + /// The hole a fetch on the copy queue had (`VICTORY_QUEUE2` bit 1 with + /// the relay): flight A writes a piece; flight B, sent behind it, + /// writes the same piece through a half-way value and leaves it as A + /// left it. A is landed while B is half way: the fetch, beside B on + /// the copy queue, brings B's half-way bytes into title memory. B's + /// compare finds the piece as A's compare left it and flags nothing, + /// so B's landing fetched nothing and title memory kept the half-way + /// bytes. With the fix B's landing fetches the piece all the same + /// (`BESIDE`). + /// + /// `VICTORY_D3D12_WARP=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_QUEUE2=1 + /// VICTORY_RELAY=1 cargo test -p victory-gpu --features diagnostics + /// fetched_again -- --nocapture` (alone: it lands its two flights + /// itself; `VICTORY_QUEUE2_REFETCH=0` shows the fault). + #[test] + fn warp_a_piece_fetched_while_a_later_flight_writes_it_is_fetched_again() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x0020_0000; + let Some(host) = host() else { + return; + }; + // Never on a real card. + // SAFETY: a plain query. + let software = host + .adapter + .as_ref() + .and_then(|a| unsafe { a.GetDesc1() }.ok()) + .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); + if !software { + eprintln!("queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)"); + return; + } + if !relay() || !crate::queue2::second().is_some_and(|s| s.fetches()) { + eprintln!("queue2_tests: skipped, fetches do not go to a copy queue beside the relay (VICTORY_RELAY=1 VICTORY_QUEUE2=1)"); + return; + } + const PIECE: usize = 64 << 10; + const LEN: usize = 4 << 20; + // SAFETY: a plain allocation of our own. + let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; + assert!(!title.is_null()); + let dword = |at: usize| unsafe { title.add(at).cast::<u32>() }; + for i in 0..LEN / 4 { + // SAFETY: inside the allocation. + unsafe { dword(i * 4).write_volatile(0x5A00_0000 | i as u32) }; + } + crate::shadow::register(0x52_5252, title as u64, LEN as u64); + let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); + if !shadow.carded() { + eprintln!("queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)"); + return; + } + let code = compile(TWICE, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); + // SAFETY: the shader's own root signature; plain creation. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); + let pso = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .expect("a pipeline"); + (root, pso) + }; + // A list whose shader writes the dword at 256 of `piece`, declared. + let record = |piece: usize, first: u32, last: u32, spin: u32| { + let list = host.new_list().expect("a host list"); + shadow.refresh(&list, title as u64, LEN as u64); + shadow.gpu_writes(&list, (title as usize + piece * PIECE) as u64, PIECE as u64); + // SAFETY: an open list; the copy's buffer, with unordered + // access; the shader's own root signature. + unsafe { + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + let constants = [(piece * PIECE + 256) as u32, first, last, spin]; + list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + list.list.Dispatch(1, 1, 1); + } + list.close(); + list + }; + // SAFETY: a plain query. + let completed = || unsafe { host.fence.GetCompletedValue() }; + let wait_for = |value: u64| { + while completed() < value { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + // How many steps keep the card busy for some seconds: timed on + // another piece, waited for. + const TRIAL: u32 = 1 << 20; + let trial = record(40, 1, 2, TRIAL); + let timing = std::time::Instant::now(); + host.execute(&[&trial]); + let took = timing.elapsed().as_secs_f64().max(1e-4); + let spin = (f64::from(TRIAL) * 3.0 / took).clamp(f64::from(TRIAL), 2.0e9) as u32; + // SAFETY: inside the allocation. + assert_eq!(unsafe { dword(40 * PIECE + 256).read_volatile() }, 2, "the trial's write did not come back"); + const AT: usize = 20 * PIECE + 256; + const HALF_WAY: u32 = 0xDEAD_0001; + const LEFT: u32 = 0x600D_0002; + // Flight A, and the card has run it. + let a = record(20, HALF_WAY, LEFT, 16); + let (submitted, mut sent_a) = host.submit(&[&a], true).expect("flight A sent ahead"); + let fence_a = *submitted; + drop(submitted); + wait_for(fence_a); + // Flight B: the same piece, through the half-way value, for seconds. + let b = record(20, HALF_WAY, LEFT, spin); + let (submitted, mut sent_b) = host.submit(&[&b], true).expect("flight B sent ahead"); + let fence_b = *submitted; + drop(submitted); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert!( + completed() < fence_b, + "flight B had run after 0.3 s ({spin} steps; the trial's {TRIAL} took {took:.3} s): nothing to show" + ); + // A lands, as `Host::relay_land` lands it, while B is half way. + let mut fetch = None; + { + let plan = sent_a.card.as_ref().expect("flight A has a plan for the card's copies"); + host.relay_card_back(&[(sent_a.number, plan)], &mut fetch, fence_a, sent_a.number, RelayBack::default()); + } + for (copy, ranges) in &sent_a.back { + copy.copy_back_done(ranges); + } + // SAFETY: inside the allocation. + let seen = unsafe { dword(AT).read_volatile() }; + let b_ran = completed() >= fence_b; + eprintln!( + "queue2_tests: after A's landing title memory holds {seen:#x} (half way {HALF_WAY:#x}, left {LEFT:#x}); B had run: {b_ran}; {spin} steps" + ); + assert_eq!( + seen, HALF_WAY, + "the fetch for A did not come down beside B (it waited for B, or B had not begun): this machine cannot show the fault" + ); + // B has run; it left the piece as A left it, so its compare flags + // nothing. Its landing must bring the piece down all the same. + wait_for(fence_b); + { + let plan = sent_b.card.as_ref().expect("flight B has a plan for the card's copies"); + host.relay_card_back(&[(sent_b.number, plan)], &mut fetch, fence_b, sent_b.number, RelayBack::default()); + } + for (copy, ranges) in &sent_b.back { + copy.copy_back_done(ranges); + } + // SAFETY: inside the allocation. + let (left, beside) = unsafe { (dword(AT).read_volatile(), dword(AT + 4).read_volatile()) }; + assert_eq!( + left, LEFT, + "title memory kept flight B's half-way bytes: B's compare found the piece as A left it and B's landing fetched nothing" + ); + assert_eq!(beside, 0, "the dword beside it holds a half-way count"); + for sent in [&mut sent_a, &mut sent_b] { + if let Some(plan) = sent.card.take() { + host.card_done(plan); + } + } + drop((a, b, trial)); + } } + diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 2d2e2c3f6f..03ffca5bfd 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -2,24 +2,32 @@ //! title's own compute passes write most of them; a pass we drop or //! translate wrongly leaves whatever the memory held, and a draw of four //! billion vertices or a dispatch past the host's limits runs until the -//! host resets the display driver. So every record is clamped on the GPU, -//! just before its execution, by a compute shader of ours (HLSL compiled by -//! the system's compiler as a 5.1 shader, or by DXC; its root signature is -//! built here, since Wine's compiler does not embed one). -//! Non-indexed rectangle-list draws follow the clamp with GPU-side -//! rectangle expansion in [`crate::rectangles`]. +//! host resets the display driver. So active records are copied and clamped +//! on the GPU into a device-local scratch buffer, just before execution, by a +//! compute shader of ours (HLSL compiled by the system's compiler; a 5.1 +//! shader with its root signature inside), leaving the title's argument and +//! count buffers untouched. //! -//! Each list also has budgets (2^27 vertex instances or threads, groups -//! counted as 64 threads; and 2^15 mesh groups): records past them run -//! empty, so a list of thousands of garbage records cannot run for seconds -//! either. A mesh record is limited to 4,096 groups: captured direct mesh -//! work peaks at 260 groups, and allowing D3D12's 65,535 let one corrupt -//! indirect record keep an RX 6700 XT busy until the driver was reset. +//! The scratch buffer is left readable as indirect arguments after a clamp +//! and stays so until the next clamp into it, which moves it straight back +//! to unordered access; it goes back to the common state once, when the +//! list closes. The executions that read it record no barrier of their +//! own, so draws that read records clamped together (`crate::draw`'s +//! windows) follow each other with nothing between them. Before, each +//! execution was followed by a move of the scratch buffer back to the +//! common state, which drivers may treat as a full wait. +//! +//! When a count buffer is given, threads at or past `min(max, count)` return +//! immediately without charging the list's budget or reading uninitialized +//! tail slots. Each list has a budget (2^27 vertex instances or threads, +//! groups counted as 64 threads, mesh groups as 128): active records past it +//! run empty, saturating without 32-bit wraparound so a list of thousands of +//! garbage records cannot run for seconds either. //! //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 -//! compute groups per dimension and 2^20 per dispatch, 4,096 groups per -//! one-dimensional mesh dispatch, the budgets) cut legitimate work beyond -//! them; raise them if the title needs more. +//! groups per dimension and 2^20 per dispatch, one-dimensional mesh +//! dispatches, the budget) cut legitimate work beyond them; raise them if +//! the title needs more. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::ID3DBlob; @@ -28,217 +36,245 @@ use windows::core::s; use crate::host::{HostList, host, transition}; -// Written for both compilers `D3DCompile` may be: Microsoft's and, under -// Wine, vkd3d-shader's, which has no `RWByteAddressBuffer` methods and -// embeds no root signature. So the buffers are structured buffers of words -// (a root UAV takes either) and the root signature is built in code -// ([`root_signature`]). const SOURCE: &str = r#" -cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; -RWStructuredBuffer<uint> args : register(u0); -// The list's work so far (word 0: vertex instances, threads; word 1: mesh -// groups): past the budget, records run empty. -RWStructuredBuffer<uint> budget : register(u1); +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { + uint kind; + uint stride; + uint records; + uint args_offset; + // Bit 0: a count buffer bounds the records. Bit 1: the records are a + // window clamped ahead of their draws: one that asks for more than can + // run is left empty and costs nothing. Bit 2: the records are gathered + // (`gather`): record i lies in the source where word i of the table + // behind `count_buf` says (from `count_offset` on), and goes to slot i. + // Bit 3: dispatch records spread across z past 65,535 groups in x + // (`crate::draw`'s spread command signature): record i goes to byte + // 20 * i as [row, asked x, x, y, z], row 0 when not spread. + // Bit 4, with bit 2: the table's first word is the number of records + // (a window, `windowed`: the CPU adds records while the list is + // recorded), the offsets follow it. + uint has_count; + uint count_offset; +}; +ByteAddressBuffer src_args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer dst_args : register(u0); +// The list's work so far (vertex instances, threads): past the budget, +// records run empty. +RWByteAddressBuffer budget : register(u1); static const uint BUDGET = 1u << 27; -static const uint MESH_BUDGET = 1u << 15; -// Groups of one dispatch (one mesh dispatch); more run empty. +// The vertices or indices an instance from which a draw record runs empty. +static const uint MOST_DRAW = 1u << 23; +// Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; -static const uint MESH_GROUPS = 1u << 12; +// Each group charges the budget once: the costs of its records go here, +// one thread charges their sum, saturating as each record would in lane +// order, and every thread then reads whether its own record fitted. A +// compare and swap per record, 64 threads racing for one word, cost a +// round for each record of a window, and in memory the CPU maps (where the +// budget was, and is with VICTORY_INDIRECT_CARD_BUDGET=0) every atomic +// crosses the bus on a card of its own. +groupshared uint costs[64]; +groupshared uint fits[64]; +groupshared uint largest_asked; +groupshared uint all_asked; +[RootSignature(RS)] [numthreads(64, 1, 1)] -void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= records) return; - uint at = id.x * (stride / 4); - uint cost; - uint counter = 0; - uint limit = BUDGET; - if (kind <= 1) { +void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { + uint eff_count = records; + bool ahead = (has_count & 2u) != 0; + if ((has_count & 1u) != 0) { + eff_count = min(eff_count, count_buf.Load(count_offset)); + } + bool counted_table = (has_count & 16u) != 0; + if (counted_table) { + eff_count = min(eff_count, count_buf.Load(count_offset)); + } + // Threads past the records take part in the group's charge (cost 0) + // and store nothing. + bool active = id.x < eff_count; + uint src_at = args_offset + id.x * stride; + // (A branch, not a select: without the bit the view behind `count_buf` + // is a count of four bytes, or the source itself, and is not read here.) + [branch] + if ((has_count & 4u) != 0) { + src_at = count_buf.Load(count_offset + (counted_table ? 4u : 0u) + id.x * 4u); + } + uint dst_at = id.x * stride; + bool spread = (has_count & 8u) != 0; + uint row = 0; + uint asked_x = 0; + if (spread) { + dst_at = id.x * 20u; + } + uint cost = 0; + uint asked = 0; + uint2 draw_counts = uint2(0, 0); + uint3 groups = uint3(0, 0, 0); + if (gi == 0) { + largest_asked = 0; + all_asked = 0; + } + if (active && kind <= 1) { // Draws: vertex or index count, then instances. - uint count = min(args[at], 1u << 24); - uint instances = min(args[at + 1], (1u << 26) / max(count, 1u)); + uint2 want = src_args.Load2(src_at); + if (ahead && (want.x > (1u << 24) || want.y > (1u << 24))) { + want = uint2(0, 0); + } + uint count = min(want.x, 1u << 24); + uint instances = min(want.y, (1u << 26) / max(count, 1u)); cost = count * instances; - args[at] = count; - args[at + 1] = instances; - } else if (kind == 2) { - uint3 g = min(uint3(args[at], args[at + 1], args[at + 2]), uint3(65535, 65535, 65535)); + // A record that asks for MOST_DRAW vertices or indices an instance + // or more is no draw of the title's (no mesh of a console title has + // 2.8 million triangles): it runs empty and charges nothing. Run + // 206's window check found one list with 90 draws of 2^24 vertices + // and one instance each. Clamped one draw at a time, the list's + // budget lets eight of them run (2^27 in all) and empties the other + // 82; served from a window, whose records are charged once however + // often they are drawn, all 90 ran: 1.5 thousand million vertices + // in one list, with windows on in the runs that lost the device + // (201, 204). + if (count >= MOST_DRAW) { + count = 0; + instances = 0; + cost = 0; + } + draw_counts = uint2(count, instances); + } else if (active && kind == 2) { + uint3 raw = src_args.Load3(src_at); + // Diagnostics: what the record asked for before the clamp (one + // dispatch runs at most 65,535 groups a dimension; run 200 saw + // compute records ask 77,000 to 98,000 in x). A record ahead of + // its dispatch the title has not filled is not counted. + asked = max(raw.x, max(raw.y, raw.z)); + if (ahead && asked > (1u << 24)) { + asked = 0; + } + uint3 g; + asked_x = raw.x; + // Past 65,535 groups in x (one row): spread across z, the program + // takes (x + z * row, y, 0) and leaves past `asked_x` (after + // upstream VIctory pull request #2312). + if (spread && raw.x > 65535u && raw.y >= 1u && raw.y <= 65535u && raw.z == 1u + && !(ahead && raw.x > (1u << 24))) { + uint rows = (raw.x + 65534u) / 65535u; + row = (raw.x + rows - 1u) / rows; + g = uint3(row, raw.y, rows); + } else { + g = min(raw, uint3(65535u, 65535u, 65535u)); + } // x * y fits 32 bits; the whole count may not. if (g.z != 0 && g.x * g.y > GROUPS / g.z) { g = uint3(0, 0, 0); } - cost = g.x * g.y * g.z * 64; - args[at] = g.x; - args[at + 1] = g.y; - args[at + 2] = g.z; - } else { + cost = g.x * g.y * g.z * 64u; + groups = g; + } else if (active) { // Mesh dispatches: the console's are one-dimensional. - uint3 g = uint3(min(args[at], MESH_GROUPS), min(args[at + 1], 1u), min(args[at + 2], 1u)); - cost = g.x * g.y * g.z; - counter = 1; - limit = MESH_BUDGET; - args[at] = g.x; - args[at + 1] = g.y; - args[at + 2] = g.z; - } - // Saturate the shared budget instead of allowing uint wraparound. - // All accesses to the counter are atomic; a rejected record must - // never reopen the budget for later records. - uint before; - InterlockedAdd(budget[counter], 0u, before); - [allow_uav_condition] - while (true) { - if (before >= limit) break; - uint remaining = limit - before; - uint next = before + min(cost, remaining); - uint observed; - InterlockedCompareExchange(budget[counter], before, next, observed); - if (observed == before) { - if (cost <= remaining) return; - break; - } - before = observed; - } - // Draws keep their layout with no vertices; groups become zero. - args[at] = 0; -} -"#; - -/// The clamp's root signature: the record's four constants (b0), the -/// arguments (u0) and the budget (u1) as root UAVs. -fn root_signature(device: &ID3D12Device) -> windows::core::Result<ID3D12RootSignature> { - let uav = |register| D3D12_ROOT_PARAMETER { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, - Anonymous: D3D12_ROOT_PARAMETER_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR { - ShaderRegister: register, - RegisterSpace: 0, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }; - let params = [ - D3D12_ROOT_PARAMETER { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, - Anonymous: D3D12_ROOT_PARAMETER_0 { - Constants: D3D12_ROOT_CONSTANTS { - ShaderRegister: 0, - RegisterSpace: 0, - Num32BitValues: 4, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }, - uav(0), - uav(1), - ]; - let desc = D3D12_ROOT_SIGNATURE_DESC { - NumParameters: params.len() as u32, - pParameters: params.as_ptr(), - ..Default::default() - }; - let mut blob: Option<ID3DBlob> = None; - let mut errors: Option<ID3DBlob> = None; - // SAFETY: the description and its parameters live through the call. - unsafe { - D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, Some(&mut errors))?; - let blob = blob.ok_or_else(windows::core::Error::empty)?; - device.CreateRootSignature( - 0, - std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()), - ) - } -} - -/// Where `dxcompiler.dll` is looked for: `VICTORY_DXC` (the DLL or its -/// folder), beside the `dxil.dll` shader validation uses (the SDK ships them -/// together), then the executable's folder and System32. -fn dxc_library() -> windows::core::Result<windows::Win32::Foundation::HMODULE> { - use windows::Win32::System::LibraryLoader::{ - LOAD_LIBRARY_SEARCH_APPLICATION_DIR, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, - LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, - }; - use windows::core::{HSTRING, w}; - let mut paths: Vec<std::path::PathBuf> = Vec::new(); - if let Some(p) = std::env::var_os("VICTORY_DXC").map(std::path::PathBuf::from) { - paths.push(if p.is_dir() { - p.join("dxcompiler.dll") - } else { - p - }); + uint3 g = src_args.Load3(src_at); + // Ahead of its draw, a record over the most a dispatch runs is a + // slot the title has not filled (the title leaves all + // ones there): empty, and not counted below either. + if (ahead && g.x > 65535u) { + g = uint3(0, 0, 0); + } + asked = g.x; + g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + cost = g.x * g.y * g.z * 128u; + groups = g; } - if let Some(dir) = victory_shader::emit::validator::Validator::default_path() - .and_then(|p| p.parent().map(|d| d.to_path_buf())) - { - paths.push(dir.join("dxcompiler.dll")); + costs[gi] = cost; + GroupMemoryBarrierWithGroupSync(); + if (active && kind >= 2) { + // Diagnostics, in the budget buffer's next words (below): the + // largest group count a mesh or compute record asked for, and the + // groups asked in all. + uint was; + InterlockedMax(largest_asked, asked, was); + InterlockedAdd(all_asked, min(asked, 1u << 24), was); } - for path in paths.iter().filter(|p| p.is_file()) { - // SAFETY: a NUL-terminated path; its folder (dxil.dll) is searched first. - if let Ok(m) = unsafe { - LoadLibraryExW( - &HSTRING::from(path.as_path()), - None, - LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, - ) - } { - return Ok(m); + // The group's own records: none for a group past a count buffer's + // count (an execution may ask for thousands and count a few), which + // touches the budget not at all, as its threads did not before. + uint first = id.x - gi; + uint n = eff_count > first ? min(64u, eff_count - first) : 0u; + if (gi == 0 && n > 0) { + // What the records charge, from `before` on, in lane order: a + // record that does not fit whole runs empty and takes the rest. + // Only the group's own records are walked (one, clamped alone). + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = before; + for (uint j = 0; j < n; j++) { + uint c = costs[j]; + if (c > 0 && next < BUDGET) { + // (`REST` 0: a record that does not fit takes nothing, + // and those after it that fit still run) + if (BUDGET - next > c) { + next += c; + } else if (BUDGET - next == c || REST) { + next = BUDGET; + } + } + } + if (next == before) break; + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + uint at = before; + for (uint k = 0; k < n; k++) { + uint c = costs[k]; + uint fit = 1; + if (c > 0) { + fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; + if (fit != 0u) { + at += c; + } else if (REST) { + at = BUDGET; + } + } + fits[k] = fit; } } - // SAFETY: a bare name, searched only in the executable's folder and System32. - unsafe { - LoadLibraryExW( - w!("dxcompiler.dll"), - None, - LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32, - ) + GroupMemoryBarrierWithGroupSync(); + if (gi == 0 && kind >= 2 && n > 0) { + uint was; + budget.InterlockedMax(4, largest_asked, was); + budget.InterlockedAdd(8, all_asked, was); } -} - -/// Compiles a compute shader with DXC (see [`dxc_library`]). -fn dxc_compile(source: &str) -> windows::core::Result<Vec<u8>> { - use windows::Win32::Graphics::Direct3D::Dxc::*; - use windows::Win32::System::LibraryLoader::GetProcAddress; - use windows::core::{Interface, w}; - type Create = unsafe extern "system" fn( - *const windows::core::GUID, - *const windows::core::GUID, - *mut *mut std::ffi::c_void, - ) -> windows::core::HRESULT; - // SAFETY: loading the compiler and calling its documented entry point with - // out pointers of ours; the buffer and arguments outlive the calls. - unsafe { - let library = dxc_library()?; - let create: Create = std::mem::transmute( - GetProcAddress(library, s!("DxcCreateInstance")) - .ok_or_else(windows::core::Error::from_thread)?, - ); - let mut raw = std::ptr::null_mut(); - create(&CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut raw).ok()?; - let compiler = IDxcCompiler3::from_raw(raw); - let buffer = DxcBuffer { - Ptr: source.as_ptr().cast(), - Size: source.len(), - Encoding: DXC_CP_UTF8.0, - }; - let arguments = [w!("-T"), w!("cs_6_0"), w!("-E"), w!("main"), w!("-O3")]; - let result: IDxcResult = compiler.Compile(&buffer, Some(&arguments), None)?; - if let Err(e) = result.GetStatus()?.ok() { - if let Ok(errors) = result.GetErrorBuffer() { - let text = std::slice::from_raw_parts( - errors.GetBufferPointer().cast::<u8>(), - errors.GetBufferSize(), - ); - tracing::warn!( - "argument clamp: DXC: {}", - String::from_utf8_lossy(text).trim() - ); + if (!active) { + return; + } + bool over = fits[gi] == 0; + if (kind <= 1) { + if (over) { + draw_counts = uint2(0, 0); + } + dst_args.Store2(dst_at, draw_counts); + for (uint off = 8; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } + } else { + if (over) { + groups = uint3(0, 0, 0); + } + if (spread) { + dst_args.Store2(dst_at, uint2(row, asked_x)); + dst_args.Store3(dst_at + 8u, groups); + } else { + dst_args.Store3(dst_at, groups); + for (uint off = 12; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); } - return Err(e); } - let blob = result.GetResult()?; - Ok( - std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()) - .to_vec(), - ) } } +"#; struct Clamp { root: ID3D12RootSignature, @@ -265,13 +301,38 @@ fn clamp() -> Option<&'static Clamp> { fn make() -> windows::core::Result<Clamp> { let device = &host().ok_or_else(windows::core::Error::empty)?.device; + make_for(device) +} + +/// Whether a record that does not fit in what is left of its list's budget +/// takes the rest, so that every record after it runs empty too +/// (`VICTORY_INDIRECT_REST=1`). Off by default, as in codec_d's cool_fox +/// (f4b48ad): one oversized garbage record takes nothing and the later valid +/// draws still run (Belobug 76387c2d saw draws flicker as the records past +/// the budget changed from frame to frame). +fn rest() -> bool { + std::env::var("VICTORY_INDIRECT_REST").is_ok_and(|v| v == "1") +} + +fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> { + make_with(device, rest()) +} + +/// The clamp with [`rest`] given (`REST`). +fn make_with(device: &ID3D12Device, rest: bool) -> windows::core::Result<Clamp> { + make_from(device, &format!("#define REST {}\n{SOURCE}", u32::from(rest))) +} + +/// The clamp compiled from `source` (ours, or in the benchmark the one it +/// replaced). +fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> { let mut code: Option<ID3DBlob> = None; let mut errors: Option<ID3DBlob> = None; // SAFETY: the source and names live through the call; out pointers ours. let compiled = unsafe { D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), + source.as_ptr().cast(), + source.len(), s!("clamp"), None, None, @@ -283,12 +344,8 @@ fn make() -> windows::core::Result<Clamp> { Some(&mut errors), ) }; - // Should the system compiler still refuse it, DXC (dxcompiler.dll; see - // `dxc_library` for where it is looked for) compiles the same source as - // cs_6_0. - let fallback; - if let Err(e) = &compiled { - if let Some(errors) = &errors { + if let Err(e) = compiled { + if let Some(errors) = errors { // SAFETY: the blob's own bytes. let text = unsafe { std::slice::from_raw_parts( @@ -296,23 +353,16 @@ fn make() -> windows::core::Result<Clamp> { errors.GetBufferSize(), ) }; - tracing::info!(error = %e, "argument clamp: the system compiler refused it ({}); trying DXC", String::from_utf8_lossy(text).trim()); + tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text)); } - fallback = dxc_compile(SOURCE) - .inspect_err(|e| tracing::warn!(error = %e, "argument clamp: DXC failed too"))?; - } else { - fallback = Vec::new(); + return Err(e); } - let root = root_signature(device)?; - // SAFETY: the blob's own bytes. + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes; the root signature is inside the shader. unsafe { - let bytes = match (&compiled, &code) { - (Ok(()), Some(code)) => std::slice::from_raw_parts( - code.GetBufferPointer().cast::<u8>(), - code.GetBufferSize(), - ), - _ => &fallback[..], - }; + let bytes = + std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { @@ -325,205 +375,1545 @@ fn make() -> windows::core::Result<Clamp> { } } -/// Records, in `list`, the clamp of `records` records of `kind` (PC -/// argument numbering) `stride` bytes apart at host address `gpu`, leaving -/// the buffer in unordered-access state with a UAV barrier after the write -/// (for passes such as [`crate::rectangles`] that read the clamped records -/// in another compute shader). Replaces the list's compute root signature -/// and pipeline (callers bind theirs after). False if the clamp is not +/// Minimum record byte stride for a supported PC indirect argument `kind`. +fn min_stride(kind: u32) -> Option<u32> { + match kind { + 0 => Some(16), + 1 => Some(20), + 2 | 10 => Some(12), + _ => None, + } +} + +/// Validates record alignment and returns the scratch byte size `stride * records`. +fn validate_layout( + (kind, stride, records): (u32, u32, u32), + src_offset: u64, + count_offset: Option<u64>, +) -> Option<u64> { + let min = min_stride(kind)?; + if stride < min || !stride.is_multiple_of(4) || !src_offset.is_multiple_of(4) { + return None; + } + if count_offset.is_some_and(|off| !off.is_multiple_of(4)) { + return None; + } + let bytes = u64::from(stride).checked_mul(u64::from(records))?; + (bytes <= u64::from(u32::MAX)).then_some(bytes) +} + +/// Records, in `list`, the non-destructive clamp of up to `records` records of +/// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded +/// by the 32-bit count in `count` when given) into a device-local scratch +/// buffer, at offset `0`. The scratch buffer is left in `INDIRECT_ARGUMENT` +/// until the next clamp into it: executions read it with no barrier of +/// their own. Replaces the list's compute root signature and pipeline +/// (callers bind theirs after). `None` if the clamp or alignment is not /// available. -pub(crate) fn clamp_uav( +pub(crate) fn bound( + list: &HostList, + src: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + spec: (u32, u32, u32), + spread: bool, +) -> Option<ID3D12Resource> { + // An open window first: its draws come before this, in order. + end_window(list); + let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?; + // Spread dispatch records are 20 bytes each ([row, asked x, x, y, z]). + let bytes = if spread { bytes.max(20 * u64::from(spec.2)) } else { bytes }; + let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); + clamp_into(list, c, &dst, budget, src, count, spec, false, spread).then_some(dst) +} + +/// [`bound`] for a window of records clamped ahead of the draws that will +/// read them (`crate::draw`'s windows; no count buffer). The records past +/// the ones the title filled are whatever the buffer holds, and each +/// record clamped charges the list's budget when it is clamped: a slot of +/// all ones, clamped to the most a mesh dispatch runs (65,535 groups), +/// charged a sixteenth of the budget, so sixteen of them emptied every +/// draw of the list after them (run 93: "the largest group count asked for +/// 4294967295", 43 to 153 such records a frame). Here a record that asks +/// for more than can run is left empty and charges nothing; a record +/// clamped alone is clamped and charged as before. +pub(crate) fn bound_ahead( + list: &HostList, + src: (&ID3D12Resource, u64), + spec: (u32, u32, u32), +) -> Option<ID3D12Resource> { + end_window(list); + let bytes = validate_layout(spec, src.1, None)?; + let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); + clamp_into(list, c, &dst, budget, src, None, spec, true, false).then_some(dst) +} + +/// [`record_clamp_as`] into `list`'s scratch buffer `dst`, from the state +/// the list left it in; afterwards the list knows it is readable as +/// indirect arguments. +#[allow(clippy::too_many_arguments)] +fn clamp_into( list: &HostList, - gpu: u64, + c: &Clamp, + dst: &ID3D12Resource, + budget: u64, + src: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + spec: (u32, u32, u32), + ahead: bool, + spread: bool, +) -> bool { + let before = list.indirect_state(dst); + let recorded = record_clamp_with(c, &list.list, (dst, before), budget, src, count, spec, ahead, spread, true); + if recorded { + list.indirect_readable(dst); + } + recorded +} + +/// Records the clamp into `dst`, which is in state `before` (common, or +/// indirect arguments after an earlier clamp into it), and leaves `dst` in +/// `INDIRECT_ARGUMENT`. `ahead`: the records are a window clamped ahead of +/// their draws ([`bound_ahead`]). False, with nothing recorded, if the +/// layout or the addresses do not fit the clamp. +#[allow(clippy::too_many_arguments)] +fn record_clamp_as( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + dst: (&ID3D12Resource, D3D12_RESOURCE_STATES), + budget: u64, + src: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + spec: (u32, u32, u32), + ahead: bool, +) -> bool { + record_clamp_with(c, l, dst, budget, src, count, spec, ahead, false, false) +} + +/// [`record_clamp_as`]; `spread`: dispatch records past 65,535 groups in x +/// are spread across z, every record written as [row, asked x, x, y, z] +/// (20 bytes) for `crate::draw`'s spread command signature. +#[allow(clippy::too_many_arguments)] +fn record_clamp_with( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES), + budget: u64, + (src, src_offset): (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, (kind, stride, records): (u32, u32, u32), + ahead: bool, + spread: bool, + lean: bool, ) -> bool { - let (Some(c), Some(budget)) = (clamp(), list.budget()) else { + let Some(bytes) = validate_layout( + (kind, stride, records), + src_offset, + count.map(|(_, off)| off), + ) else { return false; }; - if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { + // SAFETY: live D3D12 buffer resources. + let (src_base, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) }; + if !src_base.is_multiple_of(4) || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) { return false; } - let l = &list.list; - let constants = [kind, stride, records, 0]; - // SAFETY: an open list; our root signature, pipeline and a live buffer - // the caller's list holds. + let (src_gpu, args_offset) = match src_offset + .checked_add(bytes) + .filter(|&end| end <= u64::from(u32::MAX)) + { + Some(_) => (src_base, src_offset as u32), + None => { + let Some(rebased) = src_base.checked_add(src_offset) else { + return false; + }; + (rebased, 0) + } + }; + let (count_gpu, has_count, count_offset) = match count { + Some((buf, off)) => { + // SAFETY: a live D3D12 buffer resource. + let base = unsafe { buf.GetGPUVirtualAddress() }; + if !base.is_multiple_of(4) { + return false; + } + match off.checked_add(4).filter(|&end| end <= u64::from(u32::MAX)) { + Some(_) => (base, 1u32, off as u32), + None => { + let Some(rebased) = base.checked_add(off) else { + return false; + }; + (rebased, 1u32, 0u32) + } + } + } + None => (src_gpu, 0u32, 0u32), + }; + let constants = [ + kind, + stride, + records, + args_offset, + has_count | (u32::from(ahead) << 1) | (u32::from(spread && kind == 2) << 3), + count_offset, + ]; + // SAFETY: an open list; our root signature and pipeline; live source, + // count, scratch destination, and budget buffers. `src` and `count` stay + // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst` + // transitions `before -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. Moving + // it out of `INDIRECT_ARGUMENT` orders this clamp's writes after every + // earlier execution's reads of the scratch buffer; nothing else writes it. + // Diagnostics: counted; `VICTORY_BARRIER_TEST=indirect` leaves the two + // waits for every earlier shader write out (the state changes stay). + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::IndirectBounded, 1); + #[cfg(feature = "diagnostics")] + let waits = crate::copystat::barrier_test() & 2 == 0; + #[cfg(not(feature = "diagnostics"))] + let waits = true; + let first = [ + uav_barrier(), + transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]; + let second = [ + uav_barrier(), + transition( + dst, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ), + ]; + let skip = usize::from(!waits); + // With `VICTORY_CLAMP_LEAN`: after the clamp only `dst`'s own + // transition, no wait for every shader write ([`clamp_lean`]). + let skip_second = if lean && clamp_lean() { 1 } else { skip }; + // The card meter's sample of clamps (`VICTORY_CARD_METER_CLAMPS`): a + // timestamp before the first barrier and one after the second, nothing + // else recorded differently. + let timed = crate::cardmeter::clamp_begin(l); unsafe { - // Earlier shader writes (the title's argument passes) first. - l.ResourceBarrier(&[uav_barrier()]); - l.SetComputeRootSignature(&c.root); - l.SetPipelineState(&c.pso); - l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - l.SetComputeRootUnorderedAccessView(1, gpu); - l.SetComputeRootUnorderedAccessView(2, budget); - l.Dispatch(records.div_ceil(64), 1, 1); - l.ResourceBarrier(&[uav_barrier()]); + // Earlier shader writes (the title's argument and count passes) first. + l.ResourceBarrier(&first[skip..]); + if records > 0 { + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, src_gpu); + l.SetComputeRootShaderResourceView(2, count_gpu); + l.SetComputeRootUnorderedAccessView(3, dst_gpu); + l.SetComputeRootUnorderedAccessView(4, budget); + l.Dispatch(records.div_ceil(64), 1, 1); + } + l.ResourceBarrier(&second[skip_second..]); } + crate::cardmeter::end(l, timed); true } -/// Records, in `list`, the clamp of `records` records of `kind` (PC -/// argument numbering) `stride` bytes apart at host address `gpu` in -/// `buffer`, and leaves the buffer ready to be read as arguments. Replaces -/// the list's compute root signature and pipeline (callers bind theirs -/// after). False if the clamp is not available. -pub(crate) fn bound( +/// Whether the clamp of a title's indirect command (`bound`, `bound_ahead`) +/// ends with `dst`'s transition alone, without the wait for every earlier +/// shader write that came with it (`VICTORY_CLAMP_LEAN=1`; off by default; +/// `alt`: twenty seconds with, twenty without, in turn, each change said in +/// the log). The first barrier, which orders the title's argument and count +/// passes before the clamp reads them, stays as it is. +/// +/// Why it is exact: what the clamp writes is `dst` and the budget words. +/// `dst` goes UNORDERED_ACCESS -> INDIRECT_ARGUMENT, and that transition is +/// what makes the clamp's writes to it visible to the execution that reads +/// it as arguments. The budget words are touched by the clamp shader only +/// through atomic operations (`InterlockedOr`, `InterlockedCompareExchange`, +/// `InterlockedMax`, `InterlockedAdd`), which need no barrier between two +/// clamps, and the card copy of them is copied out at the list's end behind +/// its own transition (`HostList::card_budget_out`). The window check's +/// clamps (`record_clamp_as`) keep both waits. +/// +/// Why it may gain little: the transition still waits for the clamp's +/// dispatch to finish, so the card stops once per clamp either way. The +/// clamp meter (`VICTORY_CARD_METER_CLAMPS`) says it: the clamp's span in +/// ON phases against off. +fn clamp_lean() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_CLAMP_LEAN").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a clamp of an indirect command ends with its arguments' transition alone from now (VICTORY_CLAMP_LEAN=alt): {}", + if on { "ON" } else { "off, with the wait for every shader write as usual" } + ); + } + on + } + } +} + +/// Whether indirect draws are clamped a window at a time (`VICTORY_CLAMP_WINDOW=1`; off by default; `alt`: twenty +/// seconds with, twenty without, in turn, each change said in the log). After Marvisak/VIctory #3197 (Slay326), +/// ported onto this clamp: a window is one pass of the clamp's gather mode whose table the CPU fills while the +/// list is recorded. +/// +/// Without it every indirect draw that no ahead-window or gather serves has a pass of its own between two waits +/// for every earlier shader write, so the card goes from drawing to compute and back for each. +/// +/// With it the first such draw records ONE pass (`count` records in the table, at most [`WINDOW_SLOTS`]) where its +/// single clamp would be, and the next ones that may join add their records to that pass's table and read them from +/// the window's slots, with no pass, wait or pipeline change of their own. +/// +/// Why every draw's arguments stay what its own clamp would read: the pass reads all the window's records at the +/// window's place in the list. A draw joins only if nothing recorded since that place can have written buffers on +/// the card: the window ends (`end_window`) at every dispatch, mesh dispatch, plain draw or indexed draw, every +/// indirect draw that does not join (a dispatch, a count buffer, a spread, a pipeline that may store or that the +/// layer does not know, another argument buffer, kind or stride, a full window), every texture or resource copy the +/// list records, every single clamp, ahead window or gather, and the list's end and reset. The title's buffer +/// copies and fills run on the CPU at submission, before the list, and the arguments' host copy is refreshed then +/// too: they are the same for the pass as for each single clamp. The pass charges the list's budget record by +/// record in the order of the draws, as the single clamps did one after the other. +pub(crate) fn clamp_window() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_CLAMP_WINDOW").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "indirect draws are clamped a window at a time from now (VICTORY_CLAMP_WINDOW=alt): {}", + if on { "ON" } else { "off, a pass for each as usual" } + ); + } + on + } + } +} + +/// Records a window clamps at most (a multiple of the clamp's 64 threads). +const WINDOW_SLOTS: u32 = 256; + +/// Since the start: windows opened (passes), draws served, records. +pub(crate) static WINDOWS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Whether a window was ever opened (until then ending one takes no lock). +static WINDOW_OPENED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// A list's open window ([`clamp_window`]). +pub(crate) struct Window { + /// The arguments' host copy (its GPU address), and the records' kind and stride: one of each a window. + src: u64, + kind: u32, + stride: u32, + /// The table: upload memory of the list, word 0 the records, then their byte offsets in `src`. + table: usize, + records: u32, + /// The list's scratch buffer, readable as indirect arguments until the next clamp into it. + dst: ID3D12Resource, +} + +/// Ends `list`'s window, if one is open. Before anything that may write buffers on the card. +pub(crate) fn end_window(list: &HostList) { + if !WINDOW_OPENED.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + *list.clamp_window() = None; +} + +/// The clamped records of an indirect draw (no count buffer, not spread, shaders that cannot store): `records` +/// records of `kind`, `stride` bytes apart from `offset` in the host copy `src`, in `list`'s open window or in one +/// opened for it. Returns the scratch buffer, the records' byte offset in it, and whether a pass was recorded (it +/// replaced the list's compute root signature and pipeline). `None`: the caller clamps the draw on its own. +pub(crate) fn windowed( list: &HostList, - buffer: &ID3D12Resource, - gpu: u64, - spec: (u32, u32, u32), + (src, offset): (&ID3D12Resource, u64), + (kind, stride, records): (u32, u32, u32), +) -> Option<(ID3D12Resource, u64, bool)> { + use std::sync::atomic::Ordering::Relaxed; + // SAFETY: a live D3D12 buffer resource. + let src_gpu = unsafe { src.GetGPUVirtualAddress() }; + if kind == 2 || records == 0 || records > WINDOW_SLOTS { + return None; + } + // Every record's offset fits the table's 32-bit words and the clamp's gathered form. + let last = offset.checked_add(u64::from(records - 1) * u64::from(stride))?; + gatherable(src_gpu, offset, (kind, stride))?; + gatherable(src_gpu, last, (kind, stride))?; + let mut slot = list.clamp_window(); + let joins = slot + .as_ref() + .is_some_and(|w| w.src == src_gpu && w.kind == kind && w.stride == stride && w.records + records <= WINDOW_SLOTS); + let mut opened = false; + if !joins { + *slot = None; + let (c, budget) = (clamp()?, list.budget()?); + let dst = list.indirect_scratch(u64::from(WINDOW_SLOTS) * u64::from(stride))?; + let (table_gpu, table) = list.scratch(4 + 4 * u64::from(WINDOW_SLOTS))?; + // SAFETY: the first word of the list's fresh upload memory. + unsafe { (table as *mut u32).write_volatile(0) }; + // SAFETY: a live D3D12 buffer resource. + let dst_gpu = unsafe { dst.GetGPUVirtualAddress() }; + if !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) || !table_gpu.is_multiple_of(4) { + return None; + } + let before = list.indirect_state(&dst); + let constants = [kind, stride, WINDOW_SLOTS, 0u32, 4u32 | 16u32, 0u32]; + let first = [uav_barrier(), transition(&dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]; + let second = [ + uav_barrier(), + transition(&dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + ]; + let l = &list.list; + let timed = crate::cardmeter::clamp_begin(l); + // SAFETY: an open list; our root signature and pipeline; the arguments' host copy (held by the list's + // refreshes), the table (the list's upload memory), the scratch and budget buffers. Threads past the + // table's count return at once and charge nothing. + unsafe { + l.ResourceBarrier(&first); + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, src_gpu); + l.SetComputeRootShaderResourceView(2, table_gpu); + l.SetComputeRootUnorderedAccessView(3, dst_gpu); + l.SetComputeRootUnorderedAccessView(4, budget); + l.Dispatch(WINDOW_SLOTS / 64, 1, 1); + l.ResourceBarrier(&second); + } + crate::cardmeter::end(l, timed); + list.indirect_readable(&dst); + WINDOW_OPENED.store(true, Relaxed); + let opened_so_far = WINDOWS[0].fetch_add(1, Relaxed) + 1; + if opened_so_far.is_power_of_two() { + tracing::info!( + "clamp windows so far (VICTORY_CLAMP_WINDOW): {opened_so_far} passes served {} draws, {} records (draws per pass is what it saves)", + WINDOWS[1].load(Relaxed), + WINDOWS[2].load(Relaxed) + ); + } + *slot = Some(Window { src: src_gpu, kind, stride, table: table as usize, records: 0, dst }); + opened = true; + } + let w = slot.as_mut()?; + let first = w.records; + // SAFETY: the table's words lie in the list's upload memory, alive until it is reset; the card reads them + // only when the list runs. The count is written last. + unsafe { + let t = w.table as *mut u32; + for j in 0..records { + t.add(1 + (first + j) as usize).write_volatile((offset + u64::from(j) * u64::from(stride)) as u32); + } + w.records += records; + t.write_volatile(w.records); + } + WINDOWS[1].fetch_add(1, Relaxed); + WINDOWS[2].fetch_add(u64::from(records), Relaxed); + Some((w.dst.clone(), u64::from(first) * u64::from(stride), opened)) +} + +/// The most records of one argument buffer gathered for a list +/// ([`gather`]): a multiple of the clamp's 64 threads a group, so that the +/// threads past the last record read inside the table. +pub(crate) const GATHER_MOST: u32 = 4096; +/// The widest record gathered: its slot in the scratch buffer. +pub(crate) const GATHER_STRIDE: u32 = 32; + +/// The records of one argument buffer that a list's draws read, to be +/// clamped in one pass before the list runs ([`gather`]): the buffer (a +/// host copy, and its number), the records' kind and stride, the scratch +/// buffer whose slot `i` holds record `i` clamped, and the table of the +/// records' offsets in the buffer (upload memory of the list). +pub(crate) struct GatherSet { + pub(crate) src: ID3D12Resource, + pub(crate) src_id: u64, + pub(crate) kind: u32, + pub(crate) stride: u32, + pub(crate) scratch: ID3D12Resource, + table_gpu: u64, + table: usize, + /// A record's offset in the buffer, and its slot. + slots: std::collections::HashMap<u32, u32>, +} + +// SAFETY: D3D12 objects are free-threaded; the table is the list's own +// upload memory, written under the list's lock before the list is submitted. +unsafe impl Send for GatherSet {} + +impl GatherSet { + pub(crate) fn new(src: ID3D12Resource, src_id: u64, (kind, stride): (u32, u32), scratch: ID3D12Resource, (table_gpu, table): (u64, *mut u8)) -> Self { + Self { src, src_id, kind, stride, scratch, table_gpu, table: table as usize, slots: Default::default() } + } + + /// The records gathered so far. + pub(crate) fn records(&self) -> u32 { + self.slots.len() as u32 + } + + /// The slot of the record at `offset`: the one it has, or the next + /// free one. None when the set is full. + pub(crate) fn slot(&mut self, offset: u32) -> Option<u32> { + if let Some(&slot) = self.slots.get(&offset) { + return Some(slot); + } + let slot = self.slots.len() as u32; + if slot >= GATHER_MOST { + return None; + } + // SAFETY: the table holds `GATHER_MOST` words. + unsafe { (self.table as *mut u32).add(slot as usize).write_volatile(offset) }; + self.slots.insert(offset, slot); + Some(slot) + } + + /// The scratch buffer `src`'s set uses, to keep for the list's next recording. + pub(crate) fn into_scratch(self) -> ID3D12Resource { + self.scratch + } +} + +/// Whether [`gather`] can take a record of `kind` and `stride` at `offset` +/// of a buffer at `src_gpu`: what [`record_gather_as`] asks of its +/// arguments, checked when the record is taken, because a record once +/// given a slot is drawn from the slot. +pub(crate) fn gatherable(src_gpu: u64, offset: u64, (kind, stride): (u32, u32)) -> Option<u32> { + let min = min_stride(kind)?; + if stride < min || stride > GATHER_STRIDE || !stride.is_multiple_of(4) || !offset.is_multiple_of(4) || !src_gpu.is_multiple_of(4) { + return None; + } + u32::try_from(offset).ok().filter(|o| o.checked_add(stride).is_some()) +} + +/// For a single record of `kind` and `stride` at `offset` of the host copy +/// `src` (its number `src_id`) that a draw of `list` is about to read: a +/// slot in the list's scratch buffer for that argument buffer, which the +/// list's prelude fills with the record clamped, in one pass with all the +/// other records the list's draws read (`HostList::prelude`, +/// [`record_gathers`]). Nothing is recorded in the list. The scratch +/// buffer and the record's place in it; None if the list no longer +/// gathers (something in it may write arguments), the set is full, or the +/// record does not fit the clamp: the caller clamps it as before. +/// +/// Why: the title keeps its mesh records scattered through one argument +/// buffer of about 100 MB (from one draw to the next 16 to 33,056 bytes +/// on, or back), so a window of records at one step cannot serve them, and +/// about 1,450 draws a frame each had a compute pass of ours in front of +/// them: the card left drawing for compute and came back, about nine +/// microseconds each (run 243, and the windows' own measurement). +/// +/// The third value: a segment's pass was recorded in the list for the record ([`gather_segments`]): the caller binds +/// its own pipeline and root signature again. +pub(crate) fn gather(list: &HostList, (src, src_id): (&ID3D12Resource, u64), offset: u64, spec: (u32, u32)) -> Option<(ID3D12Resource, u64, bool)> { + end_window(list); + clamp()?; + // SAFETY: a live D3D12 buffer resource. + let Some(offset) = gatherable(unsafe { src.GetGPUVirtualAddress() }, offset, spec) else { + GATHER_NONE[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return None; + }; + list.gather_slot(src, src_id, offset, spec) +} + +/// The records a segment's pass clamps at most ([`record_segment`]): one group of the clamp, one dispatch. +pub(crate) const SEGMENT_PASS: u32 = 64; +/// The passes a list records at most in one recording: its buffer of slots holds `SEGMENT_PASSES * SEGMENT_PASS` +/// records of [`GATHER_STRIDE`] bytes (128 KiB). +pub(crate) const SEGMENT_PASSES: u32 = 64; + +/// Whether a list that stopped gathering for its prelude ([`gather`]) gathers in segments (`VICTORY_GATHER_SEGMENTS=1`, +/// with `VICTORY_INDIRECT_GATHER=1`; off by default; `alt`: twenty seconds with, twenty without, in turn, each change +/// said in the log). After flipflop877/victory-nvidia-8gb-16fps c69bff19, ported onto this clamp's counted table +/// (bit 16, as `windowed`). +/// +/// A list stops gathering at the first command that may write arguments (`State::gather_ends`: a dispatch, a draw +/// whose shaders may store, an indirect command that is not windowed): the prelude runs before the list, so it cannot +/// clamp a record written inside it. Every record drawn after that had a pass of its own, between two waits for every +/// earlier shader write. With the switch the stretch from one such command to the next is a segment: the first record +/// of a segment (per argument buffer, kind and stride) records ONE pass in the list right there, after the command that +/// may have written it, and the records drawn after it in the segment take slots that pass fills. The pass reads how +/// many it has from its table's first word, which the CPU writes as records are taken and the card reads when the list +/// runs. +/// +/// Exact as a pass of its own per draw: the pass runs after every command recorded before it (the same full wait for +/// shader writes first) and before the first draw that reads one of its slots, and nothing between it and those draws +/// may write arguments: every `State::gather_ends` with stores (whole or by copy), every `HostList::gather_close` and +/// `gather_wrote` ends all open segments ([`HostList::segments_end`]), and so do the list's close and reset. The rest +/// of what is recorded between writes no buffer the records come from: our own clamps, windows and gathers write their +/// scratch buffers; texture copies write textures; read-backs land in buffers of ours; the title's buffer copies and +/// the host copies' refreshes run before the list (`card_before`), for the pass as for each single clamp. Each draw +/// takes a slot of its own, so a record drawn twice is clamped and charged twice. The records charge the list's own +/// budget word as their single clamps did, in draw order within a pass; what moves is that a pass charges its records +/// when it runs, before passes of ours recorded between its draws: that shows only when the list's budget runs out +/// (2^27 vertex instances or threads). +pub(crate) fn gather_segments() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_GATHER_SEGMENTS").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!("records after a list stops gathering are gathered in segments, a pass of ours per segment from now (VICTORY_GATHER_SEGMENTS=alt): {}", if on { "ON" } else { "off, as usual" }); + } + on + } + } +} + +/// Whether an indirect dispatch's own record (one record, no count buffer, not spread) takes a slot of the prelude or +/// of a segment as a draw's does, and the dispatch ends the gathering after that (`VICTORY_GATHER_DISPATCHES=1`, with +/// `VICTORY_INDIRECT_GATHER=1`; off by default; `alt` as above). Its record is read before the dispatch runs, and +/// nothing since the list's last command that may write arguments wrote it. +pub(crate) fn gather_dispatches() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_GATHER_DISPATCHES").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!("indirect dispatches take gathered slots for their own record from now (VICTORY_GATHER_DISPATCHES=alt): {}", if on { "ON" } else { "off, as usual" }); + } + on + } + } +} + +/// Since the start, with [`gather_segments`]: records taken by segments' passes (each had a pass of its own before), +/// the passes, the records that found no room (the list's passes all used, or no clamp or buffer) and were clamped +/// alone, as before. +pub(crate) static SEGMENT_STATS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Records, in `l`, a segment's pass ([`gather_segments`]): up to [`SEGMENT_PASS`] records of `kind` and `stride` from +/// `src`, record `i` at the byte offset that word `i + 1` of the table at `table_gpu` names, as many as its word 0 says +/// when the list runs; stored clamped at `at + i * stride` of `dst` (in state `before`), which is left in +/// `INDIRECT_ARGUMENT`; charged to the budget word at `budget`. Waits for every earlier shader write first, as a single +/// clamp does. Replaces the list's compute root signature and pipeline. False, with nothing recorded, if the layout or +/// the addresses do not fit the clamp. +pub(crate) fn record_segment( + l: &ID3D12GraphicsCommandList, + (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES), + at: u64, + budget: u64, + src: &ID3D12Resource, + table_gpu: u64, + (kind, stride): (u32, u32), ) -> bool { - if !clamp_uav(list, gpu, spec) { + let Some(c) = clamp() else { + return false; + }; + // SAFETY: live D3D12 buffer resources. + let (src_gpu, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress() + at) }; + if gatherable(src_gpu, 0, (kind, stride)).is_none() || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) || !table_gpu.is_multiple_of(4) { return false; } - // SAFETY: an open list and a live buffer. + // Bit 2: gathered from the table; bit 16: its first word is the count, the offsets follow. + let constants = [kind, stride, SEGMENT_PASS, 0u32, 4u32 | 16u32, 0u32]; + let first = [uav_barrier(), transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]; + let second = [ + uav_barrier(), + transition(dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + ]; + let timed = crate::cardmeter::clamp_begin(l); + // SAFETY: an open list; our root signature and pipeline; live source, table (the list's upload memory), slot + // buffer and budget. Moving the slot buffer out of `INDIRECT_ARGUMENT` orders this pass after the reads of the + // slots earlier passes filled. Threads past the table's count return at once and charge nothing. unsafe { - list.list.ResourceBarrier(&[transition( - buffer, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - )]); + l.ResourceBarrier(&first); + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, src_gpu); + l.SetComputeRootShaderResourceView(2, table_gpu); + l.SetComputeRootUnorderedAccessView(3, dst_gpu); + l.SetComputeRootUnorderedAccessView(4, budget); + l.Dispatch(1, 1, 1); + l.ResourceBarrier(&second); } + crate::cardmeter::end(l, timed); true } -/// The D3D12 argument descriptions of a planned host signature. -pub(crate) fn to_d3d12_descs( - args: &[crate::indirect_plan::HostIndirectArg], -) -> Vec<D3D12_INDIRECT_ARGUMENT_DESC> { - use crate::indirect_plan::HostIndirectArg; - args.iter() - .map(|&arg| match arg { - HostIndirectArg::Constant { - param, - offset, - count, - } => D3D12_INDIRECT_ARGUMENT_DESC { - Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, - Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { - Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { - RootParameterIndex: param, - DestOffsetIn32BitValues: offset, - Num32BitValuesToSet: count, - }, - }, - }, - HostIndirectArg::Execute(kind) => D3D12_INDIRECT_ARGUMENT_DESC { - Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), - ..Default::default() - }, - }) - .collect() +/// `VICTORY_GATHER_BY_COPY`: 0 off, 1 on, 2 in turn. +fn gather_by_copy_mode() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_GATHER_BY_COPY").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) } -/// After the execution: the buffer back to unordered access, where the -/// title's passes keep using it. -pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) { - // SAFETY: an open list and a live buffer. - unsafe { - list.list.ResourceBarrier(&[transition( - buffer, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )]) - }; +/// Whether the copies a list's shaders were declared to write are noted +/// (`HostList::gather_wrote`): with the switch on, and in both phases of +/// `alt`, so that the phase that uses the notes finds them whole. +pub(crate) fn gather_by_copy_kept() -> bool { + gather_by_copy_mode() != 0 } -pub(crate) fn uav_barrier() -> D3D12_RESOURCE_BARRIER { - D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, - Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, - Anonymous: D3D12_RESOURCE_BARRIER_0 { - UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { - pResource: std::mem::ManuallyDrop::new(None), - }), - }, +/// Whether a list stops gathering copy by copy, not whole +/// (`VICTORY_GATHER_BY_COPY=1`, with `VICTORY_INDIRECT_GATHER=1`; off by +/// default; `alt`: twenty seconds with, twenty without, in turn, each +/// change said in the log). +/// +/// A list's prelude reads the records it gathered before the list runs. +/// So a record must not be gathered once something recorded in the list +/// may write it. As before: the first dispatch, and the first draw whose +/// shaders can store to buffers, ended the list's gathering for every +/// argument buffer, whatever those shaders write. In the world that left +/// 1,950 to 2,300 single records a frame with a pass of the layer's own +/// each, between two waits for every earlier shader write (run 281: "the +/// list had stopped gathering"). +/// +/// With the switch a record of an argument buffer's host copy is refused +/// only once the list's shaders were declared to write THAT copy: every +/// buffer a program is given to write is declared, view by view, root +/// view by root view and window by window, where the program is prepared +/// (`Shadow::gpu_writes`; the copy back into title memory depends on the +/// same declarations), and a write to another host copy of the same bytes +/// is not seen through this one on the card either way. A pipeline the +/// layer does not know still ends the gathering whole. +/// +/// NOT PROVEN EXACT (an independent review, 2026-11-26): three kinds of +/// shader write are declared nowhere. (1) A buffer the shader picks from +/// the view heap by an index it computes, and (2) title memory by address +/// through a copy another list numbered: for programs that can do either +/// the gathering still ends whole (`State::gather_ends`). (3) An entry of +/// a descriptor array past the program's used-resource list, and a picked +/// view that needs no stride: NOT covered. Before this switch is used for +/// play, a run with it in turn and `VICTORY_INDIRECT_WINDOW_CHECK=1` must +/// show that "differed" does not grow in the phases with it. +pub(crate) fn gather_by_copy() -> bool { + match gather_by_copy_mode() { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a list stops gathering indirect records copy by copy from now (VICTORY_GATHER_BY_COPY=alt): {}", + if on { "ON" } else { "off, whole at the first dispatch or storing draw as usual" } + ); + } + on + } } } -#[cfg(test)] -mod tests { - /// A corrupt mesh record must not regain D3D12's 65,535-group maximum: - /// one such record ran until the driver reset an RX 6700 XT. - #[test] - fn mesh_indirect_work_is_bounded() { - assert!(super::SOURCE.contains("MESH_GROUPS = 1u << 12")); - assert!(super::SOURCE.contains("min(args[at], MESH_GROUPS)")); - assert!(super::SOURCE.contains("MESH_BUDGET = 1u << 15")); - assert!(super::SOURCE.contains("budget[counter]")); - } +/// Since the last line: records that got no slot because they do not fit +/// the clamp, because their list had stopped gathering, because the list +/// gathers from too many buffers, because their set was full, because a +/// buffer could not be made. +pub(crate) static GATHER_NONE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; +/// Records the clamp of `records` gathered records into `dst`, which is in +/// state `before`, and leaves `dst` in `INDIRECT_ARGUMENT`: record `i` is +/// read at the offset word `i` of the table at `table_gpu` names, in the +/// buffer `src`, and stored clamped at `i * stride`. Charged to the budget +/// word at `budget` as records clamped one by one are. False, with nothing +/// recorded, if the layout or the addresses do not fit the clamp. +fn record_gather_as( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES), + budget: u64, + src: &ID3D12Resource, + table_gpu: u64, + (kind, stride, records): (u32, u32, u32), +) -> bool { + // SAFETY: live D3D12 buffer resources. + let (src_gpu, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) }; + if gatherable(src_gpu, 0, (kind, stride)).is_none() + || records == 0 + || records > GATHER_MOST + || !dst_gpu.is_multiple_of(4) + || !budget.is_multiple_of(4) + || !table_gpu.is_multiple_of(4) + { + return false; + } + let constants = [kind, stride, records, 0u32, 4u32, 0u32]; + let first = [uav_barrier(), transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]; + let second = [ + uav_barrier(), + transition(dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + ]; + // SAFETY: an open list; our root signature and pipeline; live source, + // table, scratch destination and budget buffers. The first wait puts + // the pass behind every earlier shader write (the title's argument + // passes of the lists before); the second puts the list's draws behind + // the pass. + unsafe { + l.ResourceBarrier(&first); + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, src_gpu); + l.SetComputeRootShaderResourceView(2, table_gpu); + l.SetComputeRootUnorderedAccessView(3, dst_gpu); + l.SetComputeRootUnorderedAccessView(4, budget); + l.Dispatch(records.div_ceil(64), 1, 1); + l.ResourceBarrier(&second); + } + true +} - /// The clamp bounds a draw, a dispatch and a mesh dispatch on the GPU. - #[test] - fn arguments_are_clamped_on_the_gpu() { - clamp_on_the_gpu(false); +/// Records, into a list's prelude `l`, the passes that fill the scratch +/// buffers of `sets` ([`gather`]), charged to the words of `budget`, which +/// is zeroed first (the gathered records have a budget of their own: the +/// list's own clamps zero and charge theirs inside the list, after this). +/// False if anything could not be recorded: the slots then hold no clamped +/// records and the list must not run. +pub(crate) fn record_gathers(l: &ID3D12GraphicsCommandList, sets: &[GatherSet], budget: &ID3D12Resource) -> bool { + use windows::core::Interface; + let (Some(c), Ok(l2)) = (clamp(), l.cast::<ID3D12GraphicsCommandList2>()) else { + return false; + }; + // SAFETY: a live buffer. + let at = unsafe { budget.GetGPUVirtualAddress() }; + let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + offset, Value: 0 }); + // SAFETY: an open list; the budget buffer is the list's own and common + // between its runs. + unsafe { + l.ResourceBarrier(&[transition(budget, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + l2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None); + l.ResourceBarrier(&[transition(budget, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + } + let mut all = true; + for set in sets.iter().filter(|s| s.records() > 0) { + all &= record_gather_as(c, l, (&set.scratch, D3D12_RESOURCE_STATE_COMMON), at, &set.src, set.table_gpu, (set.kind, set.stride, set.records())); + } + // SAFETY: as above. + unsafe { + l.ResourceBarrier(&[transition(budget, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON)]); } + all +} - /// The same in a list with the title's kind of descriptor heaps bound - /// (under vkd3d-proton the clamp then faulted on address 0). - #[test] - fn arguments_are_clamped_with_heaps_bound() { - clamp_on_the_gpu(true); +/// Whether every draw served from a window is checked against a fresh +/// clamp of its record (`VICTORY_INDIRECT_WINDOW_CHECK=1`, with +/// `VICTORY_INDIRECT_WINDOW=1`; off by default). A window clamps its +/// records once, ahead of their draws; if anything wrote a record between +/// the window's clamp and its draw, the draw reads the old one. The check +/// clamps the record again just before the draw (into a buffer of its own, +/// charging a budget of its own) and compares the two on the card: the +/// counts are logged ("window check"), and the first record that differs in +/// each run of a list is named. For telling whether windows can be trusted +/// in a scene before they are on by default; it costs a clamp and a compare +/// per window draw. +pub(crate) fn window_check() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + std::env::var_os("VICTORY_INDIRECT_WINDOW_CHECK").is_some_and(|v| v == "1") + }) +} + +/// The compare of [`window_check`]: `words` dwords of the record a window +/// clamped (`t0`) against the same record clamped just now (`t1`). Counts +/// the checks and the records that differ in `u0`, keeps the first record +/// that differs there (eight dwords of each), and zeroes the fresh clamp's +/// own budget (`u1`) for the next check. +const CHECK_SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=1, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Check : register(b0) { + uint words; +}; +ByteAddressBuffer window_record : register(t0); +ByteAddressBuffer fresh_record : register(t1); +RWByteAddressBuffer results : register(u0); +RWByteAddressBuffer fresh_budget : register(u1); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + bool same = true; + for (uint i = 0; i < words; i++) { + if (window_record.Load(4 * i) != fresh_record.Load(4 * i)) { + same = false; + } + } + uint was; + results.InterlockedAdd(4, 1, was); + if (!same) { + uint before; + results.InterlockedAdd(0, 1, before); + if (before == 0) { + for (uint k = 0; k < min(words, 8u); k++) { + results.Store(8 + 4 * k, window_record.Load(4 * k)); + results.Store(40 + 4 * k, fresh_record.Load(4 * k)); + } + } } + fresh_budget.Store3(0, uint3(0, 0, 0)); +} +"#; - fn clamp_on_the_gpu(heaps: bool) { - use super::*; - let Some(host) = host() else { - return; // no host GPU here - }; - let (buffer, data) = host.shared_buffer(256).unwrap(); - let words = data.cast::<u32>(); - let records: [(usize, [u32; 4]); 3] = [ - (0, [u32::MAX, 5, 0, 0]), // draw: vertices, instances - (16, [70_000, 2, 3, 0]), // dispatch - (32, [100_000, 7, 9, 0]), // mesh dispatch - ]; - for (at, w) in records { - // SAFETY: inside the mapped 256 bytes. - unsafe { std::ptr::copy_nonoverlapping(w.as_ptr(), words.add(at / 4), 4) }; - } - let list = host.new_list().unwrap(); - if heaps { - let heap = |kind, count| -> ID3D12DescriptorHeap { - // SAFETY: plain heap creation. - unsafe { - host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: count, - Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - NodeMask: 0, - }) +fn compare() -> Option<&'static Clamp> { + static COMPARE: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new(); + COMPARE + .get_or_init(|| { + let device = &host()?.device; + match make_from(device, CHECK_SOURCE) { + Ok(c) => Some(c), + Err(e) => { + tracing::warn!(error = %e, "no window check"); + None } - .unwrap() + } + }) + .as_ref() +} + +/// A list's buffers for [`window_check`]: the fresh clamps' records and +/// budget (the card's memory), and the results (memory the CPU maps: +/// records that differed, checks, then the first differing record as the +/// window had it and as the fresh clamp made it, eight dwords each). +pub(crate) struct WindowCheck { + args: ID3D12Resource, + budget: ID3D12Resource, + results: ID3D12Resource, + data: usize, +} + +// SAFETY: D3D12 objects are free-threaded; the mapping is read only at +// submission, when the list's last run has finished. +unsafe impl Send for WindowCheck {} +// SAFETY: as above. +unsafe impl Sync for WindowCheck {} + +impl WindowCheck { + pub(crate) fn new() -> Option<WindowCheck> { + let host = host()?; + let (results, data) = host.shared_buffer(256)?; + // SAFETY: the mapping holds 256 bytes; nothing runs yet. + unsafe { std::ptr::write_bytes(data, 0, 256) }; + Some(WindowCheck { + args: host.uav_buffer(64 << 10)?, + budget: host.uav_buffer(256)?, + results, + data: data as usize, + }) + } + + /// What the list's last run found, zeroed for the next: checks, records + /// that differed, and the first that did (as the window had it, as the + /// fresh clamp made it). Only between runs of the list. + pub(crate) fn take(&self) -> (u32, u32, [u32; 8], [u32; 8]) { + let words = self.data as *mut u32; + // SAFETY: the list's own mapped words; its last run has finished. + unsafe { + let at = |k: usize| words.add(k).read_volatile(); + let window = std::array::from_fn(|k| at(2 + k)); + let fresh = std::array::from_fn(|k| at(10 + k)); + let found = (at(1), at(0), window, fresh); + std::ptr::write_bytes(words, 0, 18); + found + } + } +} + +/// Checks and differing records seen by [`window_check`] so far. +static CHECKED: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// [`window_check`] for a draw served from a window: the record of `kind` +/// at `src`, `step` bytes long, which the window clamped into `scratch` at +/// `at`, is clamped again into the list's check buffer and compared. Runs +/// compute work of ours, so the caller binds its pipeline again after it. +/// False if nothing was recorded. +pub(crate) fn check_hit( + list: &HostList, + src: (&ID3D12Resource, u64), + (kind, step): (u32, u32), + scratch: &ID3D12Resource, + at: u64, +) -> bool { + const CHECK_USE: usize = usize::MAX - 0x78; + let (Some(c), Some(cmp), Some(check)) = (clamp(), compare(), list.window_check()) else { + return false; + }; + if list.first_use(CHECK_USE) { + // At this recording's submission: what the list's last run found. + let data = check.data; + let words = WindowCheck { + args: check.args.clone(), + budget: check.budget.clone(), + results: check.results.clone(), + data, + }; + list.defer_host(move || { + let (checked, differed, window, fresh) = words.take(); + if checked == 0 { + return; + } + use std::sync::atomic::Ordering::Relaxed; + let total = CHECKED[0].fetch_add(u64::from(checked), Relaxed) + u64::from(checked); + let bad = CHECKED[1].fetch_add(u64::from(differed), Relaxed) + u64::from(differed); + if differed > 0 { + tracing::warn!( + differed, + checked, + ?window, + ?fresh, + "window check: a draw served from a window read a record that \ + differs from a fresh clamp of it" + ); + } + if total / 10_000 != (total - u64::from(checked)) / 10_000 { + tracing::info!(checked = total, differed = bad, "window check"); + } + }); + } + // SAFETY: live buffers. + let (budget, results, fresh, window) = unsafe { + ( + check.budget.GetGPUVirtualAddress(), + check.results.GetGPUVirtualAddress(), + check.args.GetGPUVirtualAddress(), + scratch.GetGPUVirtualAddress() + at, + ) + }; + // The record again, by the window's rules, into the check's buffer + // (common before and after every check). + let common = D3D12_RESOURCE_STATE_COMMON; + let spec = (kind, step, 1); + if !record_clamp_as(c, &list.list, (&check.args, common), budget, src, None, spec, true) { + return false; + } + let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + let words = step / 4; + // SAFETY: an open list; the compare's own root signature and pipeline; + // the scratch buffer is readable as arguments (and stays so), the + // check's buffer was left so by the clamp above. + unsafe { + list.list.ResourceBarrier(&[ + transition(scratch, args, D3D12_RESOURCE_STATES(args.0 | read.0)), + transition(&check.args, args, read), + ]); + list.list.SetComputeRootSignature(&cmp.root); + list.list.SetPipelineState(&cmp.pso); + list.list.SetComputeRoot32BitConstants(0, 1, (&raw const words).cast(), 0); + list.list.SetComputeRootShaderResourceView(1, window); + list.list.SetComputeRootShaderResourceView(2, fresh); + list.list.SetComputeRootUnorderedAccessView(3, results); + list.list.SetComputeRootUnorderedAccessView(4, budget); + list.list.Dispatch(1, 1, 1); + list.list.ResourceBarrier(&[ + transition(scratch, D3D12_RESOURCE_STATES(args.0 | read.0), args), + transition(&check.args, read, common), + ]); + } + true +} + +fn uav_barrier() -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Foundation::HANDLE; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::Interface; + + const WORKER_CS: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer hits : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint prev; + hits.InterlockedAdd(0, 1, prev); +} +"#; + + struct WarpHarness { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + clamp: Clamp, + worker: Clamp, + } + + impl WarpHarness { + fn new() -> Option<Self> { + // SAFETY: plain DXGI WARP query and D3D12 test harness setup. + unsafe { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option<ID3D12Device> = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + // (the tests below count on a record that does not fit taking the rest) + let clamp = make_with(&device, true).expect("clamp shader must compile on WARP"); + let worker = compile_cs(&device, WORKER_CS).expect("worker shader must compile"); + Some(Self { + device, + queue, + allocator, + list, + fence, + submitted: 0, + event, + clamp, + worker, + }) + } + } + + /// CPU-mapped L0 write-back buffer matching `Shadow`'s heap type. + fn shared_buffer(&self, size: u64) -> (ID3D12Resource, *mut u8, u64) { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() }; - let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1024); - let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 16); - // SAFETY: an open list and shader-visible heaps it keeps alive. - unsafe { list.list.SetDescriptorHeaps(&[Some(views.clone()), Some(samplers.clone())]) }; - list.keep(&views); - list.keep(&samplers); - } - // SAFETY: a live buffer and an open list. - let gpu = unsafe { - list.list.ResourceBarrier(&[transition( - &buffer, - D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )]); - buffer.GetGPUVirtualAddress() + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(4), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain buffer creation and persistent CPU mapping. + unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .unwrap(); + let buffer = buffer.unwrap(); + buffer.Map(0, None, Some(&mut data)).unwrap(); + let gpu = buffer.GetGPUVirtualAddress(); + (buffer, data.cast(), gpu) + } + } + + /// Device-local `DEFAULT`-heap UAV scratch buffer. + fn default_uav(&self, size: u64) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(64 << 10), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain device-local buffer creation. + unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .unwrap(); + } + buffer.unwrap() + } + + fn signature(&self, kind: u32, stride: u32) -> ID3D12CommandSignature { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option<ID3D12CommandSignature> = None; + // SAFETY: valid single-argument command signature description. + unsafe { + self.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + } + + fn submit_and_wait(&mut self) { + self.submitted += 1; + // SAFETY: closing, executing, waiting on fence, and resetting our list. + unsafe { + self.list.Close().unwrap(); + let cmd: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(cmd)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence + .SetEventOnCompletion(self.submitted, self.event) + .unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + } + + fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> { + let mut code: Option<ID3DBlob> = None; + // SAFETY: source and entry names outlive `D3DCompile`. + unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + s!("worker"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + let code = code.unwrap(); + let bytes = std::slice::from_raw_parts( + code.GetBufferPointer().cast::<u8>(), + code.GetBufferSize(), + ); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; + let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(Clamp { root, pso }) + } + } + + /// The compare of copies in the card's memory (`crate::host`), on the + /// software adapter. Told 1 it flags the pieces whose bytes are not + /// what was hashed last and leaves the hashes: a piece a shader changed + /// and a later one changed back then looks untouched, which is right + /// only if the piece was fetched after both. Told 2 (submissions sent + /// ahead with the relay, whose pieces are fetched flight by flight) it + /// stores the hash it made: each compare flags what changed since the + /// compare before it, also a change back. + #[test] + fn warp_card_compare_stores_the_hash_it_made_when_told() { + // Both forms: a thread a piece, and a group a piece (the default). + card_compare_on_warp(crate::host::CARD_COMPARE, |pieces| pieces.div_ceil(64)); + card_compare_on_warp(crate::host::CARD_COMPARE_WIDE, |pieces| pieces); + } + + /// Every one-byte change is found, in the piece it is in, with a copy + /// that does not start on a piece boundary (`skew`) and a span that + /// does not start at piece 0: both forms of the compare. + #[test] + fn warp_card_compare_finds_every_byte_with_skew() { + for (source, groups) in [ + (crate::host::CARD_COMPARE, (|p: u32| p.div_ceil(64)) as fn(u32) -> u32), + (crate::host::CARD_COMPARE_WIDE, |p| p), + ] { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let compare = compile_cs(&warp.device, source).expect("the card compare must compile on WARP"); + const PIECE: usize = 64 << 10; + const SKEW: u32 = 0x3450; + const FIRST: u32 = 1; + const PIECES: u32 = 4; + let size = PIECE * 6; + let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64); + let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * 8); + let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64); + let content: Vec<u8> = (0..size).map(|i| (i * 131 + i / 7) as u8).collect(); + // SAFETY: the mapping holds `size` bytes. + unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) }; + let run = |warp: &mut WarpHarness, mode: u32| -> Vec<u32> { + // SAFETY: as in `card_compare_on_warp`. + unsafe { + for i in 0..PIECES as usize { + differs_ptr.cast::<u32>().add(i).write_volatile(7); + } + warp.list.SetComputeRootSignature(&compare.root); + warp.list.SetPipelineState(&compare.pso); + let constants = [FIRST, SKEW, size as u32, PIECES, 0, mode]; + warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); + warp.list.Dispatch(groups(PIECES), 1, 1); + } + warp.submit_and_wait(); + // SAFETY: as above. + (0..PIECES as usize).map(|i| unsafe { differs_ptr.cast::<u32>().add(i).read_volatile() }).collect() + }; + run(&mut warp, 0); + assert_eq!(run(&mut warp, 1), vec![0; PIECES as usize]); + // Piece `FIRST + i` of the copy covers offsets [lo, hi) as the + // compare cuts them; a byte there changed flags that piece alone. + for (k, step) in [0usize, 1, 15, 16, 1023, 1024, 4095, 30001, 65535].iter().enumerate() { + let i = (k % PIECES as usize) as u32; + let lo = ((FIRST + i) as usize * PIECE).saturating_sub(SKEW as usize); + let at = lo + step % (PIECE - 16); + // SAFETY: inside the mapping. + unsafe { now_ptr.add(at).write_volatile(content[at] ^ 0x5a) }; + let flagged = run(&mut warp, 1); + assert_eq!(flagged[i as usize], 1, "{source:.20}: byte {at:#x} of piece {i} not found"); + // SAFETY: inside the mapping. + unsafe { now_ptr.add(at).write_volatile(content[at]) }; + assert_eq!(run(&mut warp, 1), vec![0; PIECES as usize]); + } + } + } + + fn card_compare_on_warp(source: &str, groups: fn(u32) -> u32) { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let compare = compile_cs(&warp.device, source).expect("the card compare must compile on WARP"); + const PIECE: usize = 64 << 10; + const PIECES: u32 = 3; + let size = PIECE * PIECES as usize; + let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64); + let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES)); + let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64); + let content: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + // SAFETY: the mapping holds `size` bytes. + unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) }; + // One pass over the three pieces; what it left in `differs` (7s + // where it stored nothing). + let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] { + // SAFETY: our open list, live buffers, the compare's own root + // signature; the mappings hold what is read and written. + unsafe { + for piece in 0..PIECES as usize { + differs_ptr.cast::<u32>().add(piece).write_volatile(7); + } + warp.list.SetComputeRootSignature(&compare.root); + warp.list.SetPipelineState(&compare.pso); + let constants = [0u32, 0, size as u32, PIECES, 0, mode]; + warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); + warp.list.Dispatch(groups(PIECES), 1, 1); + } + warp.submit_and_wait(); + // SAFETY: as above. + [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::<u32>().add(piece).read_volatile() }) + }; + let at = PIECE + 1234; + // SAFETY (each): inside the mapping. + let set = |value: u8| unsafe { now_ptr.add(at).write_volatile(value) }; + // 0: the hashes are stored, nothing is flagged. + assert_eq!(run(&mut warp, 0), [7, 7, 7]); + assert_eq!(run(&mut warp, 1), [0, 0, 0]); + // A change in the second piece: flagged, and with 1 flagged again + // (the hash stays the old one). + set(content[at] ^ 0x40); + assert_eq!(run(&mut warp, 1), [0, 1, 0]); + assert_eq!(run(&mut warp, 1), [0, 1, 0]); + // Changed back: with 1 the piece looks untouched. + set(content[at]); + assert_eq!(run(&mut warp, 1), [0, 0, 0]); + // With 2 the change is flagged once, and the hash is the new one. + set(content[at] ^ 0x40); + assert_eq!(run(&mut warp, 2), [0, 1, 0]); + assert_eq!(run(&mut warp, 2), [0, 0, 0]); + // Changed back: flagged, where 1 saw nothing. + set(content[at]); + assert_eq!(run(&mut warp, 2), [0, 1, 0]); + assert_eq!(run(&mut warp, 2), [0, 0, 0]); + } + + /// The fetch inside flights (`crate::host::CARD_FETCH`), on the software + /// adapter, in one list behind the compare as `Host::card_before` + /// records it: each flagged piece takes a ticket and, while it is + /// within the slots of the lowest ticket in the air, its bytes go to + /// its slot; an unflagged piece's entry says so; a ticket past the + /// slots is written but copies nothing. + #[test] + fn warp_card_fetch_copies_flagged_pieces_to_their_slots() { + use crate::host::{CARD_COMPARE, CARD_FETCH, INFLIGHT_NONE, INFLIGHT_SLOT}; + let Some(mut warp) = WarpHarness::new() else { + return; }; - for (kind, at, stride) in [(0, 0, 16), (2, 16, 12), (3, 32, 12)] { - assert!(bound(&list, &buffer, gpu + at, (kind, stride, 1))); - done(&list, &buffer); + let compare = compile_cs(&warp.device, CARD_COMPARE).expect("the card compare must compile on WARP"); + let fetch = compile_cs(&warp.device, CARD_FETCH).expect("the card fetch must compile on WARP"); + const PIECE: usize = 64 << 10; + const PIECES: u32 = 3; + // The copy starts 40 bytes into its piece 0: piece 0 is short, the + // others straddle title pieces and start off a multiple of 16. + const SKEW: u32 = 40; + let size = PIECE * PIECES as usize; + let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64); + let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES + 1)); + let (_differs, _, differs_gpu) = warp.shared_buffer(64); + let (_table, table_ptr, table_gpu) = warp.shared_buffer(4 + 64); + let slots = 1u32; + let (_fetched, fetched_ptr, fetched_gpu) = warp.shared_buffer(INFLIGHT_SLOT * u64::from(slots)); + let content: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + // SAFETY: the mappings hold what is written. + unsafe { + std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size); + table_ptr.cast::<u32>().write_volatile(0); } - list.close(); - host.execute(&[&list]); - // SAFETY: the list ran (execute waits); inside the mapped bytes. - let read = |at: usize| unsafe { std::slice::from_raw_parts(words.add(at / 4), 3).to_vec() }; - assert_eq!(read(0)[..2], [1 << 24, 4]); - assert_eq!(read(16), [65_535, 2, 3]); - assert_eq!(read(32), [4_096, 1, 1]); + let pieces = PIECES + 1; + let run = |warp: &mut WarpHarness, mode: u32, landed: u32| -> Vec<u32> { + // SAFETY: our open list, live buffers, the shaders' own root + // signatures; the mappings hold what is read and written. + unsafe { + warp.list.SetComputeRootSignature(&compare.root); + warp.list.SetPipelineState(&compare.pso); + let constants = [0u32, SKEW, size as u32, pieces, 0, mode]; + warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); + warp.list.Dispatch(1, 1, 1); + if mode == 2 { + warp.list.ResourceBarrier(&[uav_barrier()]); + warp.list.SetComputeRootSignature(&fetch.root); + warp.list.SetPipelineState(&fetch.pso); + // Two groups for four pieces: the loop over pieces. + let constants = [0u32, SKEW, size as u32, pieces, 0, landed, slots, 2]; + warp.list.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, differs_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, table_gpu); + warp.list.SetComputeRootUnorderedAccessView(4, fetched_gpu); + warp.list.Dispatch(2, 1, 1); + } + } + warp.submit_and_wait(); + // SAFETY: as above. + (0..=pieces as usize).map(|i| unsafe { table_ptr.cast::<u32>().add(i).read_volatile() }).collect() + }; + // SAFETY (each): inside the mapping of the copy. + let set = |at: usize, value: u8| unsafe { now_ptr.add(at).write_volatile(value) }; + // SAFETY (each): the slot's mapping holds `INFLIGHT_SLOT` bytes. + let slot = |len: usize| unsafe { std::slice::from_raw_parts(fetched_ptr, len).to_vec() }; + run(&mut warp, 0, 0); + // Piece 2 of the copy (title piece 2: bytes 2 * 64 KiB - 40 on), its + // slot from the multiple of 16 below to the one above its end. + let from = 2 * PIECE - SKEW as usize; + let widened = from & !15; + assert_ne!(widened, from); + set(from + 100, content[from + 100] ^ 0x40); + let table = run(&mut warp, 2, 0); + assert_eq!(table, [1, INFLIGHT_NONE, INFLIGHT_NONE, 0, INFLIGHT_NONE]); + let mut wanted = content[widened..widened + INFLIGHT_SLOT as usize].to_vec(); + wanted[from + 100 - widened] ^= 0x40; + assert_eq!(slot(INFLIGHT_SLOT as usize), wanted, "piece 2 in slot 0"); + // Two pieces flagged with one slot, ticket 0 not landed: tickets 1 + // and 2 get none and the slot keeps what it held. + set(5, content[5] ^ 1); + set(PIECE + 7, content[PIECE + 7] ^ 1); + let table = run(&mut warp, 2, 0); + assert_eq!(table[0], 3); + let mut tickets = [table[1], table[2]]; + tickets.sort_unstable(); + assert_eq!(tickets, [1, 2]); + assert_eq!(&table[3..], [INFLIGHT_NONE, INFLIGHT_NONE]); + assert_eq!(slot(INFLIGHT_SLOT as usize), wanted); + // Every ticket up to 2 landed: the next one, 3, gets slot 0. Piece + // 0 starts at the copy's start. + set(9, content[9] ^ 2); + let table = run(&mut warp, 2, 3); + assert_eq!(table, [4, 3, INFLIGHT_NONE, INFLIGHT_NONE, INFLIGHT_NONE]); + let mut piece0 = content[..PIECE - SKEW as usize].to_vec(); + piece0[5] ^= 1; + piece0[9] ^= 2; + assert_eq!(slot(PIECE - SKEW as usize), piece0); } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { @@ -532,4 +1922,1692 @@ mod tests { } assert!(super::clamp().is_some()); } + + #[test] + fn rejects_unaligned_or_undersized_layouts() { + assert_eq!(validate_layout((0, 16, 4), 0, None), Some(64)); + assert_eq!(validate_layout((1, 20, 4), 64, Some(128)), Some(80)); + assert_eq!(validate_layout((2, 12, 0), 0, Some(0)), Some(0)); + assert_eq!(validate_layout((10, 16, 2), 8, None), Some(32)); + // Undersized strides for each kind. + assert_eq!(validate_layout((0, 12, 1), 0, None), None); + assert_eq!(validate_layout((1, 16, 1), 0, None), None); + assert_eq!(validate_layout((2, 8, 1), 0, None), None); + assert_eq!(validate_layout((10, 8, 1), 0, None), None); + // Unknown kind. + assert_eq!(validate_layout((3, 16, 1), 0, None), None); + // Unaligned stride, source offset, or count offset. + assert_eq!(validate_layout((0, 18, 1), 0, None), None); + assert_eq!(validate_layout((0, 16, 1), 2, None), None); + assert_eq!(validate_layout((0, 16, 1), 0, Some(6)), None); + // Total byte size exceeding 32-bit ByteAddressBuffer indexing. + assert_eq!(validate_layout((1, 20, u32::MAX), 0, None), None); + } + + /// Dispatch records spread across z (bit 3, `crate::draw`'s spread + /// signature): every record is written as [row, asked x, x, y, z], 20 + /// bytes apart; one over 65,535 groups in x with z 1 is spread (115,200 + /// as asked by the title in run 319: rows of 57,600, two of them), one + /// within the limit is not (row 0). (After upstream VIctory pull request + /// #2312's test.) + #[test] + fn warp_spread_records_split_large_x_and_keep_small_unspread() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 12; + let records: [[u32; 3]; 3] = [[115_200, 1, 1], [100, 2, 1], [65_537, 1, 1]]; + let (src_buf, src_ptr, _) = warp.shared_buffer(256); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(256); + let dst_buf = warp.default_uav(256); + // SAFETY: buffers mapped with the capacities above. + unsafe { + for (i, r) in records.iter().enumerate() { + for (w, v) in r.iter().enumerate() { + (src_ptr as *mut u32).add(i * 3 + w).write_volatile(*v); + } + } + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(readback_ptr, 0, 256); + } + assert!(record_clamp_with( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, 0), + None, + (KIND_DISPATCH, STRIDE, records.len() as u32), + false, + true, + false, + )); + // SAFETY: open command list; the clamp left `dst_buf` in `INDIRECT_ARGUMENT`. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, 60); + } + warp.submit_and_wait(); + // SAFETY: the work is done; a mapped buffer. + let out: Vec<u32> = unsafe { std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), 15).to_vec() }; + assert_eq!(&out[0..5], &[57_600, 115_200, 57_600, 1, 2], "115,200 x 1 x 1: spread"); + assert_eq!(&out[5..10], &[0, 100, 100, 2, 1], "100 x 2 x 1: not spread"); + assert_eq!(&out[10..15], &[32_769, 65_537, 32_769, 1, 2], "65,537 x 1 x 1: spread"); + } + + /// WARP D3D12 execution test proving: + /// (a) `countBuffer` with a small count (`3`) and `4,093` garbage tail slots + /// (`max = 4096`) does NOT blow `BUDGET` or zero valid dispatches in + /// this or subsequent `ExecuteIndirect` calls in the same list, + /// (b) `src_args` (and `count_buf`) are NOT mutated in-place, and + /// (c) full `stride` bytes (`stride = 24` > `12`) are copied for active + /// records into `dst_args` at offset `0`. + #[test] + fn warp_count_buffer_ignores_garbage_tail_and_preserves_source() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 24; // 6 dwords: 3 dispatch group counts + 3 extra payload dwords + const MAX: u32 = 4096; + const ARGS_OFFSET: usize = 64; // non-zero offset with sentinel prefix + const COUNT_OFFSET_1: usize = 128; + const COUNT_OFFSET_2: usize = 192; + + let src_bytes = ARGS_OFFSET + (STRIDE as usize) * (MAX as usize) + 64; + let (src_buf, src_ptr, _) = warp.shared_buffer(src_bytes as u64); + let (count_buf, count_ptr, _) = warp.shared_buffer(512); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer((STRIDE * 8) as u64); + let dst_buf = warp.default_uav(u64::from(STRIDE) * u64::from(MAX)); + let sig = warp.signature(KIND_DISPATCH, STRIDE); + + // Fill the entire source buffer with non-zero sentinel bytes, then + // populate 3 valid records at `ARGS_OFFSET` and 4,093 huge garbage + // records in `3..MAX` that would exhaust `BUDGET` ~2,000x over if read. + let mut initial_src = vec![0xA5u8; src_bytes]; + let write_record = |buf: &mut [u8], idx: usize, words: [u32; 6]| { + let base = ARGS_OFFSET + idx * (STRIDE as usize); + for (w, val) in words.into_iter().enumerate() { + buf[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes()); + } + }; + write_record( + &mut initial_src, + 0, + [3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666], + ); + write_record( + &mut initial_src, + 1, + [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC], + ); + // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1). + write_record( + &mut initial_src, + 2, + [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567], + ); + for slot in 3..MAX as usize { + // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups + // (`cost = 67,107,840 ~= BUDGET / 2`), exhausting `BUDGET` immediately! + write_record( + &mut initial_src, + slot, + [0xFFFF_FFFF, 16, 1, 0xDEAD_BEEF, 0xBAD0_C0DE, slot as u32], + ); + } + + // Second indirect call's source records (at offset 0 of a second buffer, + // or later in `count_buf`): put 2 active records + garbage tail in a + // second range to run back-to-back in the SAME command list. + let mut initial_count = vec![0x5Au8; 512]; + initial_count[COUNT_OFFSET_1..COUNT_OFFSET_1 + 4].copy_from_slice(&3u32.to_le_bytes()); + initial_count[COUNT_OFFSET_2..COUNT_OFFSET_2 + 4].copy_from_slice(&2u32.to_le_bytes()); + + // SAFETY: buffers are mapped with exact capacities above. + unsafe { + std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, src_bytes); + std::ptr::copy_nonoverlapping(initial_count.as_ptr(), count_ptr, 512); + (budget_ptr as *mut u32).write_volatile(0); + (hits_ptr as *mut u32).write_volatile(0); + std::ptr::write_bytes(readback_ptr, 0, (STRIDE * 8) as usize); + } + + // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first + // 5 records of `dst_buf` out for inspection, then record Call #2 + // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list! + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, ARGS_OFFSET as u64), + Some((&count_buf, COUNT_OFFSET_1 as u64)), + (KIND_DISPATCH, STRIDE, MAX), + false, + )); + // SAFETY: open command list, valid worker PSO/root and buffers. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list.ExecuteIndirect( + &sig, + MAX, + &dst_buf, + 0, + Some(&count_buf), + COUNT_OFFSET_1 as u64, + ); + } + + // Snapshot `dst_buf` after Call #1 (copy 5 * STRIDE bytes, then leave + // `dst_buf` readable as arguments again, as the clamp left it). + // SAFETY: open command list; the clamp left `dst_buf` in `INDIRECT_ARGUMENT`. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list + .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, u64::from(STRIDE * 5)); + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + )]); + } + + // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1: + // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`! + // The scratch buffer goes straight from arguments back to unordered + // access. + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + budget_gpu, + (&src_buf, ARGS_OFFSET as u64), + Some((&count_buf, COUNT_OFFSET_2 as u64)), + (KIND_DISPATCH, STRIDE, MAX), + false, + )); + // SAFETY: open command list, valid worker PSO/root and buffers. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list.ExecuteIndirect( + &sig, + MAX, + &dst_buf, + 0, + Some(&count_buf), + COUNT_OFFSET_2 as u64, + ); + } + + warp.submit_and_wait(); + + // SAFETY: GPU execution finished; read mapped host results. + let (hits, spent, after_src, after_count, clamped_words) = unsafe { + let hits = (hits_ptr as *const u32).read_volatile(); + let spent = (budget_ptr as *const u32).read_volatile(); + let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), src_bytes).to_vec(); + let after_count = std::slice::from_raw_parts(count_ptr.cast_const(), 512).to_vec(); + let words = std::slice::from_raw_parts( + readback_ptr.cast::<u32>().cast_const(), + (STRIDE as usize / 4) * 5, + ) + .to_vec(); + (hits, spent, after_src, after_count, words) + }; + + // Call #1: (3*2*1) + (5*1*1) + (65535*1*1) = 65,546 groups. + // Call #2: (3*2*1) + (5*1*1) = 11 groups. + let expected_groups = (6 + 5 + 65_535) + (6 + 5); + assert_eq!( + hits, expected_groups, + "valid indirect dispatches must all execute" + ); + assert_eq!( + spent, + expected_groups * 64, + "budget must reflect only active records below countBuffer" + ); + assert_eq!( + after_src, initial_src, + "src_args must never be mutated in-place" + ); + assert_eq!( + after_count, initial_count, + "count_buf must never be mutated" + ); + + // Check `dst_args` records 0..3: clamped group counts + preserved extra stride words. + assert_eq!( + &clamped_words[0..6], + &[3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666] + ); + assert_eq!( + &clamped_words[6..12], + &[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC] + ); + assert_eq!( + &clamped_words[12..18], + &[65_535, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567] + ); + // Inactive slot 3 was never copied from `src_args`. + assert_ne!(clamped_words[21], 0xDEAD_BEEF); + } + + /// WARP D3D12 test proving `BUDGET` saturates without 32-bit unsigned + /// wraparound across >64 huge indexed-draw records (`count = None`), while + /// preserving `StartIndexLocation`, `BaseVertexLocation`, + /// `StartInstanceLocation`, and custom stride padding, and leaving + /// `src_args` untouched. + /// A window of mesh records clamped ahead: the filled ones come out as + /// they are and are charged, the slots of all ones come out empty and + /// charge nothing; clamped as single records the same slots are clamped + /// to the most and spend the budget. + #[test] + fn gathered_records_must_fit_the_clamp() { + // a mesh record 12 bytes wide at a 4-byte offset of a buffer on a 4-byte address + assert_eq!(gatherable(0x1000, 0x6d71550, (10, 12)), Some(0x6d71550)); + assert_eq!(gatherable(0x1000, 0, (1, 20)), Some(0)); + // not on four bytes, too narrow, too wide, an unknown kind, past 4 GiB + assert_eq!(gatherable(0x1000, 0x6d71552, (10, 12)), None); + assert_eq!(gatherable(0x1002, 0x40, (10, 12)), None); + assert_eq!(gatherable(0x1000, 0x40, (10, 8)), None); + assert_eq!(gatherable(0x1000, 0x40, (10, GATHER_STRIDE + 4)), None); + assert_eq!(gatherable(0x1000, 0x40, (7, 12)), None); + assert_eq!(gatherable(0x1000, 1 << 32, (10, 12)), None); + assert_eq!(gatherable(0x1000, u64::from(u32::MAX) - 3, (10, 12)), None); + } + + #[test] + fn warp_gathered_records_come_out_as_if_clamped_one_by_one() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_MESH: u32 = 10; + const STRIDE: u32 = 12; + // Records scattered through a buffer as the title keeps them: 16 to + // thousands of bytes apart, not in order, one of them twice over + // the budget's most (65,535 groups), one of all ones (garbage). + let records: [(u32, [u32; 3]); 7] = [ + (0x3350, [5, 1, 1]), + (0x0040, [519, 1, 1]), + (0x0050, [0, 1, 1]), + (0x7ff0, [70000, 1, 1]), + (0x1230, [u32::MAX, u32::MAX, u32::MAX]), + (0x0010, [9, 7, 3]), + (0x2000, [1, 0, 0]), + ]; + let total = 0x8000usize; + let mut src = vec![0x5Au8; total]; + for (at, words) in records { + for (w, word) in words.into_iter().enumerate() { + let i = at as usize + w * 4; + src[i..i + 4].copy_from_slice(&word.to_le_bytes()); + } + } + let slots = (GATHER_MOST * STRIDE) as u64; + let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64); + let (_table_buf, table_ptr, table_gpu) = warp.shared_buffer(u64::from(GATHER_MOST) * 4); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(slots); + let dst_buf = warp.default_uav(slots); + // SAFETY: mapped buffers of these sizes. + unsafe { + std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total); + std::ptr::write_bytes(table_ptr, 0, GATHER_MOST as usize * 4); + for (i, (at, _)) in records.into_iter().enumerate() { + (table_ptr as *mut u32).add(i).write_volatile(at); + } + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(readback_ptr, 0xEE, slots as usize); + } + assert!(record_gather_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + &src_buf, + table_gpu, + (KIND_MESH, STRIDE, records.len() as u32), + )); + // SAFETY: an open list; the scratch buffer, which the pass left + // readable as arguments, is copied for the check. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, slots); + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (spent, out) = unsafe { + ( + (budget_ptr as *const u32).read_volatile(), + std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), records.len() * 3).to_vec(), + ) + }; + // Slot i holds record i as the clamp leaves a mesh record clamped + // alone: the groups bounded to 65,535 and the other two to one. + let want: Vec<[u32; 3]> = records.iter().map(|(_, w)| [w[0].min(65535), w[1].min(1), w[2].min(1)]).collect(); + for (i, want) in want.iter().enumerate() { + assert_eq!(&out[i * 3..i * 3 + 3], want, "slot {i} (the record at {:#x})", records[i].0); + } + let charged: u32 = want.iter().map(|w| w[0] * w[1] * w[2] * 128).sum(); + assert_eq!(spent, charged, "each record charged once, as clamped alone"); + // The source is read only. + // SAFETY: a mapped buffer. + assert_eq!(unsafe { std::slice::from_raw_parts(src_ptr.cast_const(), total) }, &src[..]); + } + + #[test] + fn warp_window_leaves_unfilled_slots_empty_and_uncharged() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_MESH: u32 = 10; + const STRIDE: u32 = 32; + const RECORDS: u32 = 16; + let filled = [5u32, 0, 519]; + let total = (STRIDE * RECORDS) as usize; + let mut src = vec![0xffu8; total]; + for (i, groups) in filled.into_iter().enumerate() { + let words = [groups, 1, 1, 0xAB00 + i as u32]; + for (w, word) in words.into_iter().enumerate() { + let at = i * STRIDE as usize + w * 4; + src[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + for ahead in [true, false] { + let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64); + let dst_buf = warp.default_uav(total as u64); + // SAFETY: mapped buffers of these sizes. + unsafe { + std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total); + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(readback_ptr, 0, total); + } + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, 0), + None, + (KIND_MESH, STRIDE, RECORDS), + ahead, + )); + // SAFETY: an open list; the scratch buffer, which the clamp left + // readable as arguments, is copied for the check. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (spent, largest, out) = unsafe { + ( + (budget_ptr as *const u32).read_volatile(), + (budget_ptr as *const u32).add(1).read_volatile(), + std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4).to_vec(), + ) + }; + for (i, groups) in filled.into_iter().enumerate() { + let rec = &out[i * 8..i * 8 + 4]; + assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}"); + } + let charged_filled = (5 + 519) * 128; + if ahead { + for i in filled.len()..RECORDS as usize { + assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty"); + assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are"); + } + assert_eq!(spent, charged_filled, "unfilled slots charge nothing"); + assert_eq!(largest, 519, "and are not counted as asked for"); + } else { + // Thirteen slots at 65,535 groups: sixteen would be all of it. + assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most"); + assert_eq!(largest, u32::MAX); + } + } + } + + #[test] + fn warp_budget_saturates_without_wraparound_and_preserves_draw_fields() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_INDEXED: u32 = 1; + const STRIDE: u32 = 24; // 5 indexed-draw words + 1 trailing custom word + const RECORDS: u32 = 128; // 2 waves of 64: old InterlockedAdd wrapped 2^32 at 64! + const BUDGET_CAP: u32 = 1 << 27; + + let total_bytes = (STRIDE * RECORDS) as usize; + let (src_buf, src_ptr, _) = warp.shared_buffer(total_bytes as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total_bytes as u64); + let dst_buf = warp.default_uav(total_bytes as u64); + + let mut initial_src = vec![0u8; total_bytes]; + for i in 0..RECORDS as usize { + // The first record is no draw (2^24 indices): it runs empty + // and charges nothing. + let words: [u32; 6] = [ + if i == 0 { 1 << 24 } else { 1 << 22 }, // IndexCount + if i == 0 { 1 } else { u32::MAX }, // InstanceCount -> clamps to 16 (cost = 1 << 26) + 1000 + i as u32, // StartIndexLocation + (-200i32 + i as i32) as u32, // BaseVertexLocation + 5000 + i as u32, // StartInstanceLocation + 0xCAFE_0000 | (i as u32), // Extra stride word + ]; + let base = i * (STRIDE as usize); + for (w, val) in words.into_iter().enumerate() { + initial_src[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes()); + } + } + + // SAFETY: mapped buffers have sufficient capacity. + unsafe { + std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, total_bytes); + (budget_ptr as *mut u32).write_volatile(0); + std::ptr::write_bytes(readback_ptr, 0, total_bytes); + } + + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, 0), + None, + (KIND_INDEXED, STRIDE, RECORDS), + false, + )); + + // SAFETY: open command list; copy clamped scratch buffer (left + // readable as arguments) for verification. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list + .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64); + } + warp.submit_and_wait(); + + // SAFETY: GPU work completed. + let (spent, after_src, out_words) = unsafe { + let spent = (budget_ptr as *const u32).read_volatile(); + let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), total_bytes).to_vec(); + let out_words = std::slice::from_raw_parts( + readback_ptr.cast::<u32>().cast_const(), + total_bytes / 4, + ) + .to_vec(); + (spent, after_src, out_words) + }; + + assert_eq!( + spent, BUDGET_CAP, + "budget must saturate at BUDGET without wrapping" + ); + assert_eq!(after_src, initial_src, "src_args must remain untouched"); + + let mut kept = 0usize; + let mut zeroed = 0usize; + for i in 0..RECORDS as usize { + let rec = &out_words[i * 6..(i + 1) * 6]; + if rec[0] == (1 << 22) && rec[1] == 16 { + // WHICH two draws keep the budget is the order the card + // runs the threads in, which nothing fixes (the software + // device gave another two in five runs of seven): only how + // many is the clamp's to say, below. + assert_ne!(i, 0, "the record that is no draw charges nothing and is not kept as one"); + kept += 1; + } else { + assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed"); + zeroed += 1; + } + assert_eq!(rec[2], 1000 + i as u32); + assert_eq!(rec[3], (-200i32 + i as i32) as u32); + assert_eq!(rec[4], 5000 + i as u32); + assert_eq!(rec[5], 0xCAFE_0000 | (i as u32)); + } + assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2)); + } + + /// Exercises `HostList::indirect_scratch`, `bound`, the scratch buffer's + /// tracked state, `Host::execute`, and `HostList::reset` end-to-end on + /// the host device. + #[test] + fn host_list_reuses_and_grows_scratch_across_submissions() { + let Some(host) = super::host() else { + return; + }; + // What earlier tests left in the debug layer's queue, if it is on. + let _ = host.log_messages(); + let Ok(list) = host.new_list() else { + return; + }; + let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else { + return; + }; + let Some((count_buf, count_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: mapped host buffers. + unsafe { + std::ptr::write_bytes(src_ptr, 0x7F, 256 << 10); + (count_ptr as *mut u32).write_volatile(2); + } + + let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + // First two calls fit inside the initial 64 KiB scratch buffer and + // must reuse the exact same `ID3D12Resource`, which stays readable + // as arguments between them. + let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64), false).unwrap(); + assert_eq!( + list.indirect_state(&b1), + args, + "a clamp leaves the scratch readable as arguments" + ); + let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128), false).unwrap(); + assert_eq!( + b1.as_raw(), + b2.as_raw(), + "scratch buffer within capacity must be reused" + ); + assert_eq!(list.indirect_state(&b2), args); + + // A call needing >64 KiB grows the scratch buffer mid-list while keeping + // `b1` alive until reset. The new buffer starts out common. + let grown = list.indirect_scratch(5000 * 20).unwrap(); + assert_eq!( + list.indirect_state(&grown), + D3D12_RESOURCE_STATE_COMMON, + "a new scratch buffer is common" + ); + let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000), false).unwrap(); + assert_eq!(b3.as_raw(), grown.as_raw()); + assert_ne!( + b3.as_raw(), + b1.as_raw(), + "larger request must grow scratch buffer" + ); + assert_eq!(list.indirect_state(&b3), args); + assert_eq!( + list.indirect_state(&b1), + D3D12_RESOURCE_STATE_COMMON, + "the replaced buffer went back to common" + ); + + list.close(); + // With the debug layer on (`VICTORY_D3D12_DEBUG=1`, diagnostics): + // every barrier recorded named the state the buffer was in. Read + // before the submission, which moves the messages to the log. + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + + // After reset, requests up to the grown high-water mark reuse `b3` with + // zero new allocations; the buffer decayed to common when the + // submission ran. + assert_eq!( + list.indirect_state(&b3), + D3D12_RESOURCE_STATE_COMMON, + "a reset list starts with a common scratch buffer" + ); + let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096), false).unwrap(); + assert_eq!( + b4.as_raw(), + b3.as_raw(), + "grown scratch buffer must persist across reset" + ); + assert_eq!(list.indirect_state(&b4), args); + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + } + + /// A group charges its records in lane order: with 300 left of the + /// budget, the first draw (100) fits, the second (250) does not and + /// takes the rest, and the ones after it run empty. (Racing for the + /// word record by record, which of them fitted was up to the GPU.) + #[test] + fn warp_a_group_charges_its_records_in_lane_order() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DRAW: u32 = 0; + const STRIDE: u32 = 16; + const BUDGET_CAP: u32 = 1 << 27; + let counts = [100u32, 250, 50, 100]; + let total = counts.len() * STRIDE as usize; + let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64); + let dst_buf = warp.default_uav(total as u64); + // SAFETY: mapped buffers of these sizes. + unsafe { + for (i, &count) in counts.iter().enumerate() { + let words = [count, 1, 7, 9]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::<u8>(), + src_ptr.add(i * STRIDE as usize), + 16, + ); + } + std::ptr::write_bytes(budget_ptr, 0, 256); + (budget_ptr as *mut u32).write_volatile(BUDGET_CAP - 300); + } + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, 0), + None, + (KIND_DRAW, STRIDE, counts.len() as u32), + false, + )); + // SAFETY: an open list; the clamped records are copied for the check. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (spent, out) = unsafe { + ( + (budget_ptr as *const u32).read_volatile(), + std::slice::from_raw_parts(readback_ptr.cast::<u32>().cast_const(), total / 4) + .to_vec(), + ) + }; + assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits"); + for i in 1..counts.len() { + assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty"); + } + assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest"); + } + + /// The list's budget starts empty at each submission, wherever it + /// lives (the card's copy is zeroed in the list): a recording whose + /// clamps spend all of it is followed, after the reset, by one whose + /// small record still runs. + #[test] + fn host_list_budget_starts_empty_at_each_submission() { + // (What it asks of the record after a spent budget, that it runs + // empty, is so only where a record that does not fit takes the rest: + // `VICTORY_INDIRECT_REST=1`. By default it takes nothing and the + // small record after it still runs.) + if !super::rest() { + return; + } + let Some(host) = super::host() else { + return; + }; + let Ok(list) = host.new_list() else { + return; + }; + let _ = host.log_messages(); + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 12; + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: STRIDE, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option<ID3D12CommandSignature> = None; + // SAFETY: a valid single-argument command signature description. + unsafe { + host.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + }; + // Three records of 65,535 x 16 groups: about half the budget each. + let Some((big, big_ptr)) = host.shared_buffer(3 * u64::from(STRIDE)) else { + return; + }; + let Some((small, small_ptr)) = host.shared_buffer(u64::from(STRIDE)) else { + return; + }; + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: mapped buffers of these sizes; nothing runs yet. + unsafe { + for i in 0..3 { + let words = [65535u32, 16, 1]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::<u8>(), + big_ptr.add(i * STRIDE as usize), + 12, + ); + } + std::ptr::copy_nonoverlapping([1u32, 1, 1].as_ptr().cast::<u8>(), small_ptr, 12); + std::ptr::write_bytes(hits_ptr, 0, 256); + } + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for round in 0..2 { + // Spends the budget (clamped, not executed), then one group. + bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3), false).unwrap(); + let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1), false).unwrap(); + // SAFETY: an open list; the worker's root signature and + // pipeline; buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + } + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + // The small record comes after the big ones spent the budget: + // it runs empty, in every round alike (none carries over). + assert_eq!(hits, 0, "round {round}: the spent budget empties the record after it"); + } + // A recording with only the small record: the budget is empty + // again, so it runs. + let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1), false).unwrap(); + // SAFETY: as above. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + } + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, 1, "the budget starts empty at the next submission"); + } + + /// The window check: a record nothing wrote since its window clamped + /// it compares equal; one written on the card after the window's clamp + /// (an untracked writer) is found, and named as the window had it and + /// as it is now. + #[test] + fn host_list_window_check_finds_a_record_written_under_its_window() { + let Some(host) = super::host() else { + return; + }; + let Ok(list) = host.new_list() else { + return; + }; + let _ = host.log_messages(); + const KIND_DISPATCH: u32 = 2; + const STEP: u32 = 32; + let records = [[3u32, 1, 1], [5, 1, 1], [7, 1, 1], [9, 1, 1]]; + let total = records.len() * STEP as usize; + let (Some((src, src_ptr)), Some((patch, patch_ptr))) = + (host.shared_buffer(total as u64), host.shared_buffer(64)) + else { + return; + }; + // SAFETY: mapped buffers of these sizes; nothing runs yet. + unsafe { + std::ptr::write_bytes(src_ptr, 0, total); + for (i, words) in records.iter().enumerate() { + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::<u8>(), + src_ptr.add(i * STEP as usize), + 12, + ); + } + std::ptr::copy_nonoverlapping([11u32, 2, 1].as_ptr().cast::<u8>(), patch_ptr, 12); + } + let spec = (KIND_DISPATCH, STEP, records.len() as u32); + let scratch = bound_ahead(&list, (&src, 0), spec).unwrap(); + // Record 0: nothing wrote it. + assert!(check_hit(&list, (&src, 0), (KIND_DISPATCH, STEP), &scratch, 0)); + // Record 1 is written on the card after the window's clamp. + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + // SAFETY: an open list; `src` was read by the clamp (promoted to a + // shader read), `patch` is common; both live until the list has run. + unsafe { + list.list.ResourceBarrier(&[transition(&src, read, D3D12_RESOURCE_STATE_COPY_DEST)]); + list.list.CopyBufferRegion(&src, u64::from(STEP), &patch, 0, 12); + list.list.ResourceBarrier(&[transition(&src, D3D12_RESOURCE_STATE_COPY_DEST, read)]); + } + let at = u64::from(STEP); + assert!(check_hit(&list, (&src, at), (KIND_DISPATCH, STEP), &scratch, at)); + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + let (checked, differed, window, fresh) = list.window_check().unwrap().take(); + list.reset(); + assert_eq!((checked, differed), (2, 1), "two checks, the written record differs"); + assert_eq!(window[..3], [5, 1, 1], "as the window clamped it"); + assert_eq!(fresh[..3], [11, 2, 1], "as it is now"); + } + + /// Records the dispatch records `groups` (three words each, `step` + /// bytes apart, the rest of each record ones) into a fresh mapped + /// buffer of `warp`'s device. + fn dispatch_records(warp: &WarpHarness, groups: &[u32], step: u32) -> ID3D12Resource { + let total = groups.len() * step as usize; + let (buffer, ptr, _) = warp.shared_buffer(total as u64); + let mut bytes = vec![0xffu8; total]; + for (i, &g) in groups.iter().enumerate() { + for (w, word) in [g, 1, 1].into_iter().enumerate() { + let at = i * step as usize + w * 4; + bytes[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + // SAFETY: the mapping holds `total` bytes. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) }; + buffer + } + + /// Two windows in one list, as `crate::draw` records them: each clamps + /// its records ahead, then one execution per record reads the scratch + /// buffer with no barrier between them; the second clamp moves the + /// scratch buffer straight from arguments back to unordered access. + /// Every record runs once, with the group count it asked for. + #[test] + fn warp_window_executions_read_their_records_with_no_barrier_between() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DISPATCH: u32 = 2; + // The title names 12 bytes and keeps its records 32 apart. + const STRIDE: u32 = 12; + const STEP: u32 = 32; + let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]]; + let sources: Vec<ID3D12Resource> = + windows.iter().map(|g| dispatch_records(&warp, g, STEP)).collect(); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256); + let dst_buf = warp.default_uav(u64::from(STEP) * 4); + let sig = warp.signature(KIND_DISPATCH, STRIDE); + // SAFETY: mapped buffers of these sizes. + unsafe { + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(hits_ptr, 0, 256); + } + let mut state = D3D12_RESOURCE_STATE_COMMON; + for (groups, src) in windows.iter().zip(&sources) { + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, state), + budget_gpu, + (src, 0), + None, + (KIND_DISPATCH, STEP, groups.len() as u32), + true, + )); + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + // SAFETY: an open list; the worker's root signature and + // pipeline; the scratch buffer is readable as arguments. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + for i in 0..groups.len() as u64 { + warp.list.ExecuteIndirect(&sig, 1, &dst_buf, i * u64::from(STEP), None, 0); + } + } + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (hits, spent) = unsafe { + ( + (hits_ptr as *const u32).read_volatile(), + (budget_ptr as *const u32).read_volatile(), + ) + }; + let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum(); + assert_eq!(hits, expected, "every record of both windows runs once"); + assert_eq!(spent, expected * 64, "and is charged what it asked for"); + } + + /// The windows of `warp_window_executions_read_their_records_with_no_barrier_between` + /// through a host list (`bound_ahead`, the list's tracked scratch state, + /// `Host::execute`), twice: on the first recording the scratch buffer + /// starts common, on the second (after the reset) it starts common + /// again. With the debug layer on (`VICTORY_D3D12_DEBUG=1` in a + /// diagnostics build) no barrier names a state the buffer is not in. + #[test] + fn host_list_window_executions_need_no_barrier_of_their_own() { + let Some(host) = super::host() else { + return; + }; + // What earlier tests left in the debug layer's queue, if it is on. + let _ = host.log_messages(); + let Ok(list) = host.new_list() else { + return; + }; + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 12; + const STEP: u32 = 32; + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: STRIDE, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option<ID3D12CommandSignature> = None; + // SAFETY: a valid single-argument command signature description. + unsafe { + host.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + }; + let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]]; + let mut sources = Vec::new(); + for groups in windows { + let total = groups.len() * STEP as usize; + let Some((buffer, ptr)) = host.shared_buffer(total as u64) else { + return; + }; + let mut bytes = vec![0xffu8; total]; + for (i, &g) in groups.iter().enumerate() { + for (w, word) in [g, 1, 1].into_iter().enumerate() { + let at = i * STEP as usize + w * 4; + bytes[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + // SAFETY: the mapping holds `total` bytes. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) }; + sources.push(buffer); + } + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum(); + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for _ in 0..2 { + // SAFETY: the mapping holds 256 bytes; nothing runs. + unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; + for (groups, src) in windows.iter().zip(&sources) { + let spec = (KIND_DISPATCH, STEP, groups.len() as u32); + let scratch = bound_ahead(&list, (src, 0), spec).unwrap(); + assert_eq!(list.indirect_state(&scratch), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + // SAFETY: an open list; the worker's root signature and + // pipeline; buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + for i in 0..groups.len() as u64 { + let at = i * u64::from(STEP); + list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0); + } + } + } + list.close(); + // With the debug layer on: nothing it objects to was recorded. + // Read before the submission, which moves the messages to the log. + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, expected, "every record of both windows runs once"); + } + } +} + +/// The benchmark of the clamp and its barriers (ignored by default). +#[cfg(test)] +mod bench; + +/// What one small draw costs this card, bare and with one thing changed +/// between every two draws: a measurement, not a check (it asserts only +/// that the card answered). The timing run of the lit scene (run 187) has +/// some 11,000 small commands a frame at 5 to 16 microseconds each, and no +/// log says whether that is what we put around a command or what the card +/// takes for one. Each variant here is 10,000 one-triangle draws into a +/// 2560x1440 target, timed on the card by one pair of timestamps around +/// the whole batch (not one per command, which would time the stamps). +/// +/// Run by name, no game needed: +/// `cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture` +#[cfg(test)] +mod bare_cost { + use windows::Win32::Foundation::{HANDLE, RECT}; + use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::{Interface, s}; + + use crate::host::{compile, transition}; + + /// Draws in a batch. + const DRAWS: u32 = 10_000; + const WIDTH: u32 = 2560; + const HEIGHT: u32 = 1440; + + /// One small triangle in the middle of the target (about 180 pixels), + /// and two pixel programs that read one texel of a texture through a + /// table, so that the view heap set is in use. + const DRAW: &str = r#" +#define RS "DescriptorTable(SRV(t0))" +Texture2D<float4> image : register(t0); +[RootSignature(RS)] +float4 corner(uint i : SV_VertexID) : SV_Position { + float2 p = float2((i << 1) & 2, i & 2); + return float4(p * 0.02 - 0.01, 0.5, 1.0); +} +[RootSignature(RS)] +float4 first(float4 at : SV_Position) : SV_Target { + return image.Load(int3(0, 0, 0)); +} +[RootSignature(RS)] +float4 second(float4 at : SV_Position) : SV_Target { + return 1.0 - image.Load(int3(0, 0, 0)); +} +"#; + + /// A compute pass of next to nothing, as our clamp of an indirect + /// record is: one group of one thread that writes one word. + const WORK: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer words : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void work() { + words.Store(0, words.Load(0) + 1); +} +"#; + + /// What changes between every two draws of a batch. + #[derive(Clone, Copy, PartialEq)] + enum Between { + /// Nothing. + Nothing, + /// The pipeline: two alternate. + Pipeline, + /// A second texture goes from target to shader read and back. + BarrierPair, + /// The depth texture bound for testing goes from write to read or + /// back. + DepthMove, + /// The pair of descriptor heaps: two pairs alternate. + Heaps, + /// The colour target: two alternate. + Targets, + /// A compute pass of ours of one group, and the pipeline back. + Compute, + /// The same between two waits for every earlier shader write, as + /// the clamp records them. + ComputeWithWaits, + } + + struct Rig { + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + root: ID3D12RootSignature, + pipelines: [ID3D12PipelineState; 2], + work_root: ID3D12RootSignature, + work: ID3D12PipelineState, + words: ID3D12Resource, + other: ID3D12Resource, + depth: ID3D12Resource, + /// Kept alive: the views below name them. + _kept: Vec<ID3D12Resource>, + _target_heaps: [ID3D12DescriptorHeap; 2], + heap_pairs: [[Option<ID3D12DescriptorHeap>; 2]; 2], + tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], + targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], + /// Kept beside `depth_tested` (the view the rig clears through when it is made). + _depth_written: D3D12_CPU_DESCRIPTOR_HANDLE, + depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, + stamps: ID3D12QueryHeap, + back: ID3D12Resource, + card: String, + } + + fn texture( + device: &ID3D12Device, + (width, height): (u32, u32), + format: DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(width), + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + }; + let mut out: Option<ID3D12Resource> = None; + // SAFETY: plain texture creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn buffer( + device: &ID3D12Device, + size: u64, + kind: D3D12_HEAP_TYPE, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut out: Option<ID3D12Resource> = None; + // SAFETY: plain buffer creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap { + let flags = if visible { + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE + } else { + D3D12_DESCRIPTOR_HEAP_FLAG_NONE + }; + // SAFETY: plain heap creation. + unsafe { + device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: flags, + NodeMask: 0, + }) + .unwrap() + } + } + + fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState { + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 0xf; + let mut formats = [DXGI_FORMAT(0); 8]; + formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + // SAFETY: the description points at live data and never releases + // its pointer to the root signature. + unsafe { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(root), + VS: code(vs), + PS: code(ps), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Depth is tested and never written, so the texture may be + // in the write state or in the read state under one view. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + DSVFormat: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + device.CreateGraphicsPipelineState(&desc).unwrap() + } + } + + impl Rig { + /// The default adapter, as the layer takes it; `None` without one + /// or on a software adapter. + fn new() -> Option<Self> { + let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?; + let ps = [ + compile(DRAW, s!("first"), s!("ps_5_1")).ok()?, + compile(DRAW, s!("second"), s!("ps_5_1")).ok()?, + ]; + let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?; + // SAFETY: plain object creation on a device of our own; the + // views are made in heaps that live as long as the rig. + unsafe { + let mut device: Option<ID3D12Device> = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let desc = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid())) + .ok()? + .cast::<IDXGIAdapter1>() + .ok()? + .GetDesc1() + .ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + return None; + } + let card = String::from_utf16_lossy(&desc.Description) + .trim_end_matches('\0') + .to_owned(); + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?; + let pipelines = [ + pipeline(&device, &root, &vs, &ps[0]), + pipeline(&device, &root, &vs, &ps[1]), + ]; + let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?; + let work: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&work_root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }) + .ok()?; + + let size = (WIDTH, HEIGHT); + let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state); + let target = [ + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + ]; + let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET); + let depth = texture( + &device, + size, + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + ); + let image = texture( + &device, + (4, 4), + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + ); + let words = buffer( + &device, + 64 << 10, + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ); + let back = buffer( + &device, + 16, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let mut stamps: Option<ID3D12QueryHeap> = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut stamps, + ) + .ok()?; + let stamps = stamps?; + + // Target and depth views. + let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false); + let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2]; + targets[1].ptr += rtv_step; + device.CreateRenderTargetView(&target[0], None, targets[0]); + device.CreateRenderTargetView(&target[1], None, targets[1]); + let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false); + let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart(); + let mut depth_tested = depth_written; + depth_tested.ptr += dsv_step; + device.CreateDepthStencilView(&depth, None, depth_written); + let tested = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH, + ..Default::default() + }; + device.CreateDepthStencilView(&depth, Some(&tested), depth_tested); + + // Two pairs of shader-visible heaps: views (one view of the + // small texture each) and samplers (none used). + let view_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + ]; + let sampler_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + ]; + for views in &view_heaps { + device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart()); + } + let tables = [ + view_heaps[0].GetGPUDescriptorHandleForHeapStart(), + view_heaps[1].GetGPUDescriptorHandleForHeapStart(), + ]; + let heap_pairs = [ + [Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())], + [Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())], + ]; + + // The first list: both targets and the depth texture cleared. + list.ClearRenderTargetView(targets[0], &[0.0; 4], None); + list.ClearRenderTargetView(targets[1], &[0.0; 4], None); + list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); + let [first_target, second_target] = target; + let mut rig = Rig { + queue, + allocator, + list, + fence, + submitted: 0, + event, + root, + pipelines, + work_root, + work, + words, + other, + depth, + _kept: vec![first_target, second_target, image], + _target_heaps: [rtvs, dsvs], + heap_pairs, + tables, + targets, + _depth_written: depth_written, + depth_tested, + stamps, + back, + card, + }; + rig.finish(); + Some(rig) + } + } + + /// Closes the open list, runs it, waits for the card and opens the + /// list again. + fn finish(&mut self) { + self.submitted += 1; + // SAFETY: our list, queue and fence; the allocator is reset + // only after the card finished everything recorded from it. + unsafe { + self.list.Close().unwrap(); + let run: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + + /// What every list starts with: a new list has nothing set. + fn begin(&self) { + let l = &self.list; + // SAFETY: an open list and live objects and views. + unsafe { + l.SetDescriptorHeaps(&self.heap_pairs[0]); + l.SetGraphicsRootSignature(&self.root); + l.SetPipelineState(&self.pipelines[0]); + l.SetGraphicsRootDescriptorTable(0, self.tables[0]); + l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested)); + l.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: WIDTH as f32, + Height: HEIGHT as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: WIDTH as i32, + bottom: HEIGHT as i32, + }]); + // A triangle list. + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); + } + } + + /// One batch of [`DRAWS`] draws in `lists` lists run one by one, + /// with `between` recorded before every draw: the microseconds a + /// draw took on the card, and the milliseconds recording took. + fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) { + let (target, read, written, tested) = ( + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_DEPTH_READ, + ); + let started = std::time::Instant::now(); + let mut drawn = 0u32; + for part in 0..lists { + let l = &self.list; + // SAFETY: an open list; our query heap; live objects. + unsafe { + if part == 0 { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + } + } + self.begin(); + // SAFETY: an open list with everything set; live objects. + // Every state moved is moved back within the batch (the + // draws of a list are an even number). + unsafe { + for _ in 0..DRAWS / lists { + let odd = (drawn % 2) as usize; + match between { + Between::Nothing => {} + Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]), + Between::BarrierPair => { + l.ResourceBarrier(&[transition(&self.other, target, read)]); + l.ResourceBarrier(&[transition(&self.other, read, target)]); + } + Between::DepthMove => { + let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) }; + l.ResourceBarrier(&[transition(&self.depth, from, to)]); + } + Between::Heaps => { + l.SetDescriptorHeaps(&self.heap_pairs[odd]); + l.SetGraphicsRootDescriptorTable(0, self.tables[odd]); + } + Between::Targets => { + l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested)); + } + Between::Compute | Between::ComputeWithWaits => { + let waits = between == Between::ComputeWithWaits; + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetComputeRootSignature(&self.work_root); + l.SetPipelineState(&self.work); + l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress()); + l.Dispatch(1, 1, 1); + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetPipelineState(&self.pipelines[0]); + } + } + l.DrawInstanced(3, 1, 0, 0); + drawn += 1; + } + if part + 1 < lists { + // The next list of the batch: this one is sent on + // its own and the list is opened again at once + // (the allocator is not reset before the card is + // done with all of them). + l.Close().unwrap(); + let run: ID3D12CommandList = l.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + l.Reset(&self.allocator, None).unwrap(); + } else { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0); + } + } + } + let recording = started.elapsed().as_secs_f64() * 1e3; + self.finish(); + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: 16 }; + // SAFETY: a read-back buffer the finished list resolved two + // timestamps into. + let ticks = unsafe { + self.back.Map(0, Some(&range), Some(&mut data)).unwrap(); + let stamps = std::slice::from_raw_parts(data.cast::<u64>(), 2).to_vec(); + self.back.Unmap(0, None); + stamps[1].saturating_sub(stamps[0]) + }; + // SAFETY: a plain query of our queue. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1); + (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording) + } + } + + #[test] + #[ignore = "a measurement on the card: run it by name with --ignored --nocapture"] + fn bare_command_cost() { + let Some(mut rig) = Rig::new() else { + eprintln!("no hardware adapter, or our shaders did not compile; skipped"); + return; + }; + eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card); + // The first batch pays for whatever the driver does at first use. + rig.batch(Between::Nothing, 1); + let variants = [ + ("(a) nothing changes between draws", Between::Nothing, 1), + ("(b) another pipeline every draw", Between::Pipeline, 1), + ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1), + ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1), + ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1), + ("(f) another colour target every draw", Between::Targets, 1), + ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100), + ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1), + ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1), + ]; + let mut least = Vec::new(); + for (name, between, lists) in variants { + let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect(); + runs.sort_by(|a, b| a.0.total_cmp(&b.0)); + eprintln!( + "{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms", + runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1 + ); + least.push(runs[0].0); + } + assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch"); + } } diff --git a/crates/victory-gpu/src/indirect/bench.rs b/crates/victory-gpu/src/indirect/bench.rs new file mode 100644 index 0000000000..0e233dbaa0 --- /dev/null +++ b/crates/victory-gpu/src/indirect/bench.rs @@ -0,0 +1,502 @@ +//! A frame's worth of one-record indirect draws on the host GPU, clamped one +//! at a time and in windows, recorded as `main` does (the scratch buffer +//! back to the common state after every execution, the clamp charging the +//! budget record by record) and as this tree does (readable until the next +//! clamp, one charge per group). Ignored by default; run it with +//! `cargo test -p victory-gpu --release --lib indirect::bench -- --ignored --nocapture`. +//! It needs no title files: the draws are tiny triangles of ours. + +use super::*; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; +use windows::Win32::Graphics::Dxgi::{ + CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIFactory4, +}; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::{Interface, PCSTR}; + +/// Draws a frame (the title's gameplay frames hold about 3,200 indirect +/// executions, #107), records a window holds, and how far apart the +/// records are (the title keeps them 32 bytes apart). +const DRAWS: u32 = 3200; +const WINDOW: u32 = 32; +const STEP: u32 = 32; +const RUNS: usize = 9; + +const SHADERS: &str = r#" +#define RS "RootFlags(0)" +[RootSignature(RS)] +float4 vs(uint v : SV_VertexID, uint i : SV_InstanceID) : SV_Position { +float2 p = float2((v & 1) ? 0.05 : 0.0, (v & 2) ? 0.05 : 0.0) - 0.5; +return float4(p, 0.5, 1); +} +float4 ps() : SV_Target { return float4(1, 0.5, 0.25, 1); } +"#; + +fn compile(entry: &str, target: &str) -> Vec<u8> { + let entry = std::ffi::CString::new(entry).unwrap(); + let target = std::ffi::CString::new(target).unwrap(); + let mut code: Option<ID3DBlob> = None; + // SAFETY: the source and names outlive the call. + unsafe { + D3DCompile( + SHADERS.as_ptr().cast(), + SHADERS.len(), + s!("bench"), + None, + None, + PCSTR(entry.as_ptr().cast()), + PCSTR(target.as_ptr().cast()), + 0, + 0, + &mut code, + None, + ) + .unwrap(); + let code = code.unwrap(); + std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()) + .to_vec() + } +} + +/// The clamp as it was before it charged the budget once per group +/// (record by record, every thread racing for the budget word), kept +/// here to measure against. +const OLD_SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { +uint kind; +uint stride; +uint records; +uint args_offset; +// Bit 0: a count buffer bounds the records. Bit 1: the records are a +// window clamped ahead of their draws: one that asks for more than can +// run is left empty and costs nothing. +uint has_count; +uint count_offset; +}; +ByteAddressBuffer src_args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer dst_args : register(u0); +// The list's work so far (vertex instances, threads): past the budget, +// records run empty. +RWByteAddressBuffer budget : register(u1); +static const uint BUDGET = 1u << 27; +// Groups of one dispatch; more run empty. +static const uint GROUPS = 1u << 20; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { +uint eff_count = records; +bool ahead = (has_count & 2u) != 0; +if ((has_count & 1u) != 0) { + eff_count = min(eff_count, count_buf.Load(count_offset)); +} +if (id.x >= eff_count) return; +uint src_at = args_offset + id.x * stride; +uint dst_at = id.x * stride; +uint cost; +uint2 draw_counts = uint2(0, 0); +uint3 groups = uint3(0, 0, 0); +if (kind <= 1) { + // Draws: vertex or index count, then instances. + uint2 asked = src_args.Load2(src_at); + if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) { + asked = uint2(0, 0); + } + uint count = min(asked.x, 1u << 24); + uint instances = min(asked.y, (1u << 26) / max(count, 1u)); + cost = count * instances; + draw_counts = uint2(count, instances); +} else if (kind == 2) { + uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); + // x * y fits 32 bits; the whole count may not. + if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + g = uint3(0, 0, 0); + } + cost = g.x * g.y * g.z * 64u; + groups = g; +} else { + // Mesh dispatches: the console's are one-dimensional. + uint3 g = src_args.Load3(src_at); + // Ahead of its draw, a record over the most a dispatch runs is a + // slot the title has not filled (the title leaves all + // ones there): empty, and not counted below either. + if (ahead && g.x > 65535u) { + g = uint3(0, 0, 0); + } + // Diagnostics, in the budget buffer's next words: the largest + // group count a mesh record asked for, and the groups asked in all. + uint was; + budget.InterlockedMax(4, g.x, was); + budget.InterlockedAdd(8, min(g.x, 1u << 24), was); + g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + cost = g.x * g.y * g.z * 128u; + groups = g; +} +bool over = false; +if (cost > 0) { + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost); + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + over = before >= BUDGET || BUDGET - before < cost; +} +if (kind <= 1) { + if (over) { + draw_counts = uint2(0, 0); + } + dst_args.Store2(dst_at, draw_counts); + for (uint off = 8; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } +} else { + if (over) { + groups = uint3(0, 0, 0); + } + dst_args.Store3(dst_at, groups); + for (uint off = 12; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } +} +} +"#; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Barriers { + /// Back to the common state after every execution (as before). + Old, + /// Readable as arguments until the next clamp, common at the end. + New, +} + +#[test] +#[ignore = "benchmark; see the module notes"] +fn bench_indirect_draw_barriers() { + let Some(host) = super::host() else { + eprintln!("no host GPU"); + return; + }; + let device = &host.device; + let clamps = [ + make_from(device, OLD_SOURCE).expect("the old clamp"), + make_for(device).expect("the clamp"), + ]; + // SAFETY: plain D3D12 object creation with valid descriptions; the + // objects outlive every list recorded and run below. + unsafe { + let adapter = { + let luid = device.GetAdapterLuid(); + CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| { + f.EnumAdapterByLuid::<windows::Win32::Graphics::Dxgi::IDXGIAdapter1>(luid) + }) + .and_then(|a| a.GetDesc1()) + .map(|d| { + String::from_utf16_lossy(&d.Description) + .trim_end_matches('\0') + .to_owned() + }) + .unwrap_or_else(|_| "an unnamed adapter".to_owned()) + }; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); + list.Close().unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + let frequency = queue.GetTimestampFrequency().unwrap() as f64; + + // The pipeline: tiny triangles into a small target. + let (vs, ps) = (compile("vs", "vs_5_1"), compile("ps", "ps_5_1")); + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: vs.as_ptr().cast(), + BytecodeLength: vs.len(), + }, + PS: D3D12_SHADER_BYTECODE { + pShaderBytecode: ps.as_ptr().cast(), + BytecodeLength: ps.len(), + }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); + let target_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut target: Option<ID3D12Resource> = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &target_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut target, + ) + .unwrap(); + let target = target.unwrap(); + let rtvs: ID3D12DescriptorHeap = device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .unwrap(); + let rtv = rtvs.GetCPUDescriptorHandleForHeapStart(); + device.CreateRenderTargetView(&target, None, rtv); + + // The title's records: three vertices, one instance, 32 bytes apart. + let (src, src_ptr) = host.shared_buffer(u64::from(DRAWS * STEP)).unwrap(); + for i in 0..DRAWS as usize { + let words = [3u32, 1, 0, 0]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::<u8>(), + src_ptr.add(i * STEP as usize), + 16, + ); + } + let (budget, budget_ptr) = host.shared_buffer(256).unwrap(); + let budget_gpu = budget.GetGPUVirtualAddress(); + // The same words in the card's own memory (zeroed when made; the + // runs below charge far less than the budget). + let card_budget = host.uav_buffer(256).unwrap(); + let card_budget_gpu = card_budget.GetGPUVirtualAddress(); + let scratch = host + .uav_buffer(u64::from(WINDOW * STEP).max(64 << 10)) + .unwrap(); + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 16, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option<ID3D12CommandSignature> = None; + device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + sig.unwrap() + }; + let stamps: ID3D12QueryHeap = { + let mut heap: Option<ID3D12QueryHeap> = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut heap, + ) + .unwrap(); + heap.unwrap() + }; + let mut back: Option<ID3D12Resource> = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ) + .unwrap(); + let back = back.unwrap(); + let mut submitted = 0u64; + + // One frame's lists: GPU ms (timestamps around the list), CPU ms + // recording it, ms from submission to the end of its run. + let mut frame = |barriers: Barriers, clamp: &Clamp, window: u32, card: bool| -> [f64; 3] { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + let recording = std::time::Instant::now(); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: 256.0, + Height: 256.0, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: 256, + bottom: 256, + }]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ); + list.SetGraphicsRootSignature(&root); + let mut state = D3D12_RESOURCE_STATE_COMMON; + for first in (0..DRAWS).step_by(window as usize) { + let records = window.min(DRAWS - first); + assert!(record_clamp_as( + clamp, + &list, + (&scratch, state), + if card { card_budget_gpu } else { budget_gpu }, + (&src, u64::from(first * STEP)), + None, + (0, STEP, records), + window > 1, + )); + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + list.SetPipelineState(&pso); + for k in 0..records { + list.ExecuteIndirect(&signature, 1, &scratch, u64::from(k * STEP), None, 0); + if barriers == Barriers::Old { + list.ResourceBarrier(&[transition( + &scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + )]); + state = D3D12_RESOURCE_STATE_COMMON; + } + } + } + if state != D3D12_RESOURCE_STATE_COMMON { + list.ResourceBarrier(&[transition(&scratch, state, D3D12_RESOURCE_STATE_COMMON)]); + } + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + list.ResolveQueryData(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &back, 0); + list.Close().unwrap(); + let recorded = recording.elapsed().as_secs_f64() * 1e3; + let running = std::time::Instant::now(); + queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().unwrap())]); + submitted += 1; + queue.Signal(&fence, submitted).unwrap(); + fence.SetEventOnCompletion(submitted, event).unwrap(); + WaitForSingleObject(event, INFINITE); + let ran = running.elapsed().as_secs_f64() * 1e3; + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + let t = std::slice::from_raw_parts(data.cast::<u64>(), 2); + let gpu = t[1].saturating_sub(t[0]) as f64 / frequency * 1e3; + back.Unmap(0, None); + (budget_ptr as *mut u32).write_volatile(0); + [gpu, recorded, ran] + }; + + // What `main` records, then this branch; the windows a step at a + // time (barriers, then the clamp's one charge per group). + let (old, new) = (&clamps[0], &clamps[1]); + // The last two keep the budget in the card's memory instead of + // memory the CPU maps (where the list's budget is now). + let cases: [(&str, Barriers, &Clamp, u32, bool); 7] = [ + ("one at a time, main", Barriers::Old, old, 1, false), + ("one at a time, this", Barriers::New, new, 1, false), + ("windows of 32, main", Barriers::Old, old, WINDOW, false), + ("windows, new barriers", Barriers::New, old, WINDOW, false), + ("windows of 32, this", Barriers::New, new, WINDOW, false), + ("one at a time, card", Barriers::New, new, 1, true), + ("windows of 32, card", Barriers::New, new, WINDOW, true), + ]; + // Warm up, then the cases in turn, so drift falls on all alike. + for &(_, barriers, clamp, window, card) in &cases { + frame(barriers, clamp, window, card); + } + let mut times: Vec<Vec<[f64; 3]>> = vec![Vec::new(); cases.len()]; + for _ in 0..RUNS { + for (i, &(_, barriers, clamp, window, card)) in cases.iter().enumerate() { + times[i].push(frame(barriers, clamp, window, card)); + } + } + let median = |v: &[[f64; 3]], k: usize| { + let mut x: Vec<f64> = v.iter().map(|t| t[k]).collect(); + x.sort_by(f64::total_cmp); + x[x.len() / 2] + }; + eprintln!( + "indirect draw barriers on {adapter}: {DRAWS} one-record draws a frame, \ + medians of {RUNS} frames" + ); + for (i, (name, ..)) in cases.iter().enumerate() { + let gpu = median(×[i], 0); + eprintln!( + " {name:<22} GPU {gpu:7.2} ms ({:5.2} us a draw), recording {:6.2} ms, \ + submit to done {:7.2} ms", + gpu * 1e3 / f64::from(DRAWS), + median(×[i], 1), + median(×[i], 2), + ); + } + for (from, to) in [(0, 1), (2, 3), (3, 4), (2, 4), (1, 5), (4, 6)] { + let (a, b) = (median(×[from], 0), median(×[to], 0)); + eprintln!( + " {} -> {}: GPU time {:+.1} %", + cases[from].0, + cases[to].0, + (b / a - 1.0) * 100.0 + ); + } + } +} diff --git a/crates/victory-gpu/src/indirect_plan.rs b/crates/victory-gpu/src/indirect_plan.rs deleted file mode 100644 index 0eceeb580f..0000000000 --- a/crates/victory-gpu/src/indirect_plan.rs +++ /dev/null @@ -1,280 +0,0 @@ -//! Indirect execution of multi-argument command signatures (#757): the -//! title's root-constant arguments before a draw or dispatch, mapped onto -//! the host root parameters that carry each stage's user data. Pure -//! planning, so it is tested everywhere; [`crate::indirect`] builds the host -//! signature. -//! -//! shortcut: only root constants are mapped; a root view argument, or a -//! constant two stages read, still drops the execution. -//! -//! From upstream PR #956 (Noname0202, 71967c10), hand-ported. - -/// One argument of a host command signature. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum HostIndirectArg { - Constant { param: u32, offset: u32, count: u32 }, - Execute(u32), -} - -/// One stage's user-data root-constant parameter, for mapping title indirect -/// root constants onto our host root signature. -pub(crate) struct StageUserData<'a> { - pub(crate) param: u32, - pub(crate) dwords: u32, - pub(crate) entries: &'a [victory_shader::emit::UserData], -} - -/// Host command-signature layout and trailing draw/dispatch offset for an -/// indirect execution. -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct IndirectPlan { - /// Final execution kind (PC numbering: 0 draw, 1 indexed, 2 dispatch, 10 mesh). - pub(crate) kind: u32, - /// Byte offset of the final draw/dispatch argument inside each record. - pub(crate) arg_offset: u32, - /// Host arguments in record order (0 or more `Constant`s, then `Execute(kind)`). - pub(crate) args: Vec<HostIndirectArg>, -} - -/// Maps a title command signature (`stride`, `title_args`) onto `stages`'s -/// host user-data parameters. Supports single-argument draw/dispatch/mesh -/// signatures and multi-argument signatures whose prefix arguments are root -/// constants (`D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT`). -pub(crate) fn plan_indirect( - stride: u32, - title_args: &[[u32; 4]], - stages: &[StageUserData<'_>], -) -> Option<IndirectPlan> { - const DRAW: u32 = 0; - const INDEXED: u32 = 1; - const DISPATCH: u32 = 2; - const CONSTANT: u32 = 5; - const MESH: u32 = 10; - const DISPATCH_SINGLE: u32 = 105; - - let (last, prefix) = title_args.split_last()?; - let kind = if last[0] == DISPATCH_SINGLE { - DISPATCH - } else { - last[0] - }; - let exec_bytes = match kind { - DRAW => 16, - INDEXED => 20, - DISPATCH | MESH => 12, - _ => return None, - }; - if prefix.is_empty() { - return Some(IndirectPlan { - kind, - arg_offset: 0, - args: vec![HostIndirectArg::Execute(kind)], - }); - } - - let mut host_args = Vec::with_capacity(title_args.len()); - let mut arg_offset = 0u32; - for arg in prefix { - if arg[0] != CONSTANT { - return None; - } - let title_slot = u8::try_from(arg[1]).ok()?; - let dest_off = arg[2]; - let num = arg[3]; - if num == 0 { - return None; - } - let end_dword = dest_off.checked_add(num)?; - - // Find every stage/index reading any dword in [dest_off, dest_off + num). - let mut target_stage: Option<usize> = None; - let mut base_index: Option<u32> = None; - for (si, stage) in stages.iter().enumerate() { - for u in stage.entries { - if u.root == victory_shader::RootType::Constants - && u.slot == title_slot - && u.dword >= dest_off - && u.dword < end_dword - { - let k = u.dword - dest_off; - let candidate = u.index.checked_sub(k)?; - match (target_stage, base_index) { - (None, None) => { - target_stage = Some(si); - base_index = Some(candidate); - } - (Some(s), Some(b)) if s == si && b == candidate => {} - _ => return None, - } - } - } - } - - let mapped = if let (Some(si), Some(base)) = (target_stage, base_index) { - let stage = &stages[si]; - let end_idx = base.checked_add(num)?; - if end_idx > stage.dwords { - return None; - } - // No other user-data entry may live in [base, base + num). - let collides = stage.entries.iter().any(|u| { - u.index >= base - && u.index < end_idx - && !(u.root == victory_shader::RootType::Constants - && u.slot == title_slot - && u.dword == dest_off + (u.index - base)) - }); - if collides { - return None; - } - HostIndirectArg::Constant { - param: stage.param, - offset: base, - count: num, - } - } else { - // No stage reads these constants; keep record alignment by landing - // them in an unused contiguous range of some stage's user data. - let mut free = None; - 'find: for stage in stages { - if num > stage.dwords { - continue; - } - for base in 0..=stage.dwords - num { - let end_idx = base + num; - let used_by_shader = stage - .entries - .iter() - .any(|u| u.index >= base && u.index < end_idx); - let used_by_prev = host_args.iter().any(|a| match *a { - HostIndirectArg::Constant { - param, - offset, - count, - } => param == stage.param && offset < end_idx && offset + count > base, - HostIndirectArg::Execute(_) => false, - }); - if !used_by_shader && !used_by_prev { - free = Some(HostIndirectArg::Constant { - param: stage.param, - offset: base, - count: num, - }); - break 'find; - } - } - } - free? - }; - - host_args.push(mapped); - arg_offset = arg_offset.checked_add(num.checked_mul(4)?)?; - } - if arg_offset.checked_add(exec_bytes)? > stride { - return None; - } - host_args.push(HostIndirectArg::Execute(kind)); - Some(IndirectPlan { - kind, - arg_offset, - args: host_args, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use victory_shader::RootType; - use victory_shader::emit::UserData; - - #[test] - fn plan_indirect_maps_root_constants_and_rejects_unsupported() { - let entries = [ - UserData { - index: 2, - slot: 1, - root: RootType::Constants, - dword: 0, - }, - UserData { - index: 3, - slot: 1, - root: RootType::Constants, - dword: 1, - }, - UserData { - index: 4, - slot: 0, - root: RootType::Table, - dword: 0, - }, - ]; - let stages = [StageUserData { - param: 0, - dwords: 8, - entries: &entries, - }]; - - // Single-argument dispatch stays at offset 0. - let single = plan_indirect(12, &[[2, 0, 0, 0]], &stages).unwrap(); - assert_eq!(single.kind, 2); - assert_eq!(single.arg_offset, 0); - assert_eq!(single.args, vec![HostIndirectArg::Execute(2)]); - - // Console DISPATCH_SINGLE (105) normalizes to DISPATCH (2). - let single_console = plan_indirect(12, &[[105, 0, 0, 0]], &stages).unwrap(); - assert_eq!(single_console.kind, 2); - - // Two root constants followed by Dispatch (stride 20 = 8 + 12). - let multi = plan_indirect(20, &[[5, 1, 0, 2], [2, 0, 0, 0]], &stages).unwrap(); - assert_eq!(multi.kind, 2); - assert_eq!(multi.arg_offset, 8); - assert_eq!( - multi.args, - vec![ - HostIndirectArg::Constant { - param: 0, - offset: 2, - count: 2, - }, - HostIndirectArg::Execute(2), - ] - ); - - // Unused constant lands in an unoccupied slot (0..1) without colliding with entries. - let unused = plan_indirect(16, &[[5, 7, 0, 1], [2, 0, 0, 0]], &stages).unwrap(); - assert_eq!(unused.arg_offset, 4); - assert_eq!( - unused.args[0], - HostIndirectArg::Constant { - param: 0, - offset: 0, - count: 1, - } - ); - - // Collision with an occupied table slot at index 4 is rejected. - assert!(plan_indirect(24, &[[5, 1, 0, 3], [2, 0, 0, 0]], &stages).is_none()); - - // Stride smaller than arg_offset + exec_bytes is rejected. - assert!(plan_indirect(16, &[[5, 1, 0, 2], [2, 0, 0, 0]], &stages).is_none()); - - // Non-constant prefix argument (e.g. CBV = 6) is rejected. - assert!(plan_indirect(20, &[[6, 0, 0, 0], [2, 0, 0, 0]], &stages).is_none()); - - // Same constant read by two different stages cannot map to one host parameter. - let stage2 = [ - StageUserData { - param: 0, - dwords: 4, - entries: &entries[..1], - }, - StageUserData { - param: 1, - dwords: 4, - entries: &entries[..1], - }, - ]; - assert!(plan_indirect(16, &[[5, 1, 0, 1], [2, 0, 0, 0]], &stage2).is_none()); - } -} diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs new file mode 100644 index 0000000000..6b5bf26a7a --- /dev/null +++ b/crates/victory-gpu/src/inplace.rs @@ -0,0 +1,1436 @@ +//! Title memory as the card's own memory: a host heap opened on memory +//! the title already has, and a buffer placed in it, so that shaders read +//! and write the title's bytes themselves and no host copy stands between +//! (the console's one memory). This file holds the two openings Direct3D +//! has, a probe that says what this PC's driver makes of them +//! (`VICTORY_INPLACE_PROBE`), and a census of which title memory could be +//! opened. +//! +//! What the Direct3D runtime and the kernel answer, measured on this PC +//! with the software adapter (the rules are theirs, not the adapter's; +//! what the card's driver adds is what the probe is for): +//! +//! - `OpenExistingHeapFromAddress` takes the base address of a whole +//! `VirtualAlloc` allocation and nothing inside it; every page must be +//! committed and have one protection. Opening locks every page into the +//! PC's memory at once (256 MiB never touched: 70 ms and 256 MB of +//! working set). +//! - `OpenExistingHeapFromAddress1` (`ID3D12Device13`) takes any committed +//! part of an allocation, with the same rule for its pages; parts may +//! overlap, and the whole may be opened beside them. It also takes a +//! committed view of a section. +//! - `OpenExistingHeapFromFileMapping` takes a section made with +//! `SEC_COMMIT` and refuses one made with `SEC_RESERVE` (how `xmem` +//! makes the title's page pool today). The heap is the section, not a +//! view of it: views may be unmapped, mapped elsewhere or made +//! read-only, and the section's handle closed, with the heap alive. +//! Opening it locks nothing (256 MiB: 0.2 ms, no working set). +//! - The heap is a custom heap in the PC's memory (write-back pages, pool +//! L0), shared and cross-adapter shared, 64 KiB aligned. A buffer in it +//! must have `ALLOW_CROSS_ADAPTER`; unordered access beside it is taken. +//! A texture must be row-major with one level. Tile mappings into such +//! a heap are refused and REMOVE THE DEVICE: never call them. +//! - While a heap opened from an address stands, the title cannot +//! decommit, release or protect the pages in it (`VirtualFree` and +//! `VirtualProtect` fail with error 87), nor unmap a view in it. Pages +//! outside the opened part are free to change. + +use std::collections::BTreeMap; +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; +use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; +use windows::core::{Interface, s}; +use windows_sys::Win32::System::Memory as mem; + +/// The unit heaps and placed buffers are cut on, and the console's page. +const K64: usize = 64 << 10; +/// The host's write watching (not in windows-sys' memory module). +const MEM_WRITE_WATCH: u32 = 0x20_0000; + +/// `VICTORY_INPLACE_PROBE`: 0 (unset) nothing; 1 the probe on memory of +/// its own at the first sweep, and the census 30 and 150 seconds later; +/// 2 also opens one part of the title's own memory for a moment at the +/// first census. +pub(crate) fn probe_level() -> u8 { + static LEVEL: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *LEVEL.get_or_init(|| std::env::var("VICTORY_INPLACE_PROBE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// `VICTORY_INPLACE`: 0 (unset) off. 1: a window of title memory outside +/// buffers that lies in private memory committed whole is not copied: a +/// part of the title's allocation is opened as a host heap and the window +/// is a buffer placed over it ([`place_for`]). 2: title buffers too, +/// except the big ones in the card's memory. 3: the hybrid, title buffers +/// only up to [`small_most`]. +/// +/// What stage 1 covers is private memory (`XMemVirtualAlloc`'s). View +/// memory (the page pool) is turned down here: its section is made +/// reserved, which the host refuses, and what a view shows changes when +/// the title maps pages. +/// +/// What it assumes, for 2: nothing reads title memory that a submission +/// not yet run writes through such a buffer. With every submission waited +/// for (the default) that holds; with `VICTORY_LATE_WAIT` it does not, +/// since the flights' rules know shader writes only by the ranges copies +/// declare. Do not combine 2 with late wait. +/// +/// shortcut: while a window is in place the title cannot decommit, free +/// or protect its pages (the call fails with error 87; the probe shows +/// it). The title's heaps are allocated once and kept, and nothing of the +/// kind was seen; [`title_memory_freeing`] is there for the runtime to +/// call before such a call once it takes them over. +pub(crate) fn level() -> u8 { + static LEVEL: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *LEVEL.get_or_init(|| std::env::var("VICTORY_INPLACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// `VICTORY_INPLACE=3`, the hybrid (Try 4.2, idea 2, after the shared +/// memory of Apple's M chips and AMD's APUs, split as consoles split it): +/// windows and title buffers of up to this many bytes +/// (`VICTORY_INPLACE_SMALL_MB`, 8 by default) are the title's own memory, +/// shared with the card: what the title changes every frame (constants, +/// command memory, small pools) is neither copied in before a submission +/// nor compared and copied back after it. The big buffers shaders read +/// most stay in the card's memory ([`crate::shadow`]'s `cards`), and the +/// middle ones copies, as before. +/// +/// What it assumes is what 2 assumes; with flights in the air +/// (`VICTORY_LATE_WAIT`, on by default) a title read of such a buffer may +/// see a flight's writes half done, as [`crate::host`]'s late results do. +fn small_most() -> u64 { + static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *MOST.get_or_init(|| std::env::var("VICTORY_INPLACE_SMALL_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(8) << 20) +} + +/// The most title memory in place at once, in bytes +/// (`VICTORY_INPLACE_MB`, 4096): opening locks the pages into the PC's +/// memory, also those the title never touched. +fn most() -> u64 { + static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *MOST.get_or_init(|| std::env::var("VICTORY_INPLACE_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(4096) << 20) +} + +/// In place now: windows and their bytes, title buffers and their bytes; +/// then, since the start: asks turned down because the memory is a view +/// or not private memory committed whole, because the host refused, +/// because of [`most`]; and what was let go because its memory changed. +static STATS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// A buffer placed over title memory, and its heap. +pub(crate) struct Placed { + pub(crate) buffer: ID3D12Resource, + pub(crate) heap: ID3D12Heap, + /// The host GPU address of the title memory's first byte. + pub(crate) gpu: u64, + /// Bytes from the buffer's first byte to the title memory's first. + pub(crate) bias: u64, +} + +/// Opens the 64 KiB pages that hold title memory `[start, start + len)` +/// as a heap of their own and places one buffer over all of them. `Err` +/// with nothing if the memory is not private memory committed whole +/// (nothing was asked of the host), with the host's error if it refused. +pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result<Placed, Option<windows::core::Error>> { + let at = start & !(K64 as u64 - 1); + let bytes = (start + len.max(1)).next_multiple_of(K64 as u64) - at; + if !private_whole(at as usize, bytes as usize) { + return Err(None); + } + let heap = open(device, From::Part(at as usize, bytes as usize)).map_err(Some)?; + let buffer = place(device, &heap, 0, bytes).map_err(Some)?; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at); + Ok(Placed { buffer, heap, gpu, bias: start - at }) +} + +/// Title memory `[start, start + len)` in place, for a window outside +/// buffers or a title buffer, if [`level`] asks for it and the memory can +/// be opened; `None` leaves the caller to make a copy, as before. +pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option<Placed> { + if level() < if window { 1 } else { 2 } { + return None; + } + // The hybrid: only the small buffers share the title's memory. + if !window && level() == 3 && len > small_most() { + STATS[6].fetch_add(1, Ordering::Relaxed); + return None; + } + // View memory: known from the runtime without asking Windows. + if cover(start as usize, len as usize) != Cover::None { + STATS[4].fetch_add(1, Ordering::Relaxed); + return None; + } + if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + len > most() { + STATS[6].fetch_add(1, Ordering::Relaxed); + return None; + } + let host = crate::host::host()?; + match place_part(&host.device, start, len) { + Ok(placed) => { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_add(1, Ordering::Relaxed); + STATS[at + 1].fetch_add(len, Ordering::Relaxed); + Some(placed) + } + Err(None) => { + STATS[4].fetch_add(1, Ordering::Relaxed); + None + } + Err(Some(e)) => { + if STATS[5].fetch_add(1, Ordering::Relaxed) < 8 { + tracing::warn!(start = format_args!("{start:#x}"), len, error = %e, "title memory not opened in place: a copy instead"); + } + None + } + } +} + +/// What [`place_for`] gave is gone. +pub(crate) fn gone(window: bool, bytes: u64) { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_sub(1, Ordering::Relaxed); + STATS[at + 1].fetch_sub(bytes, Ordering::Relaxed); +} + +/// Title memory `[at, at + len)` is about to show something else, or the +/// title is about to decommit, free or protect it: what is in place there +/// is let go (the tables forget it; its heap goes when the last list and +/// slot that hold it do). Called for memory the runtime maps anew; for +/// the runtime to call before the title's own `VirtualFree` once it takes +/// that call over. +pub fn title_memory_freeing(at: usize, len: usize) { + if STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) == 0 { + return; + } + let gone = crate::shadow::in_place_let_go(at as u64, len as u64); + STATS[7].fetch_add(gone, Ordering::Relaxed); +} + +/// The line of what is in place, every ten seconds while [`level`] is on. +fn say() { + static LAST: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + let last = LAST.load(Ordering::Relaxed); + if now < last + 10_000 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + let s: Vec<u64> = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + tracing::info!( + "title memory in place: {} windows {} MB, {} title buffers {} MB (no copy, no refresh, no copy-back); turned down: {} view memory or not private memory committed whole, \ + {} refused by the host, {} over VICTORY_INPLACE_MB; {} let go because their memory changed", + s[0], + s[1] >> 20, + s[2], + s[3] >> 20, + s[4], + s[5], + s[6], + s[7] + ); +} + +/// What a heap is opened on. +pub(crate) enum From { + /// A whole `VirtualAlloc` allocation, by its base address. + Region(usize), + /// A committed part of one: address and bytes. + Part(usize, usize), + /// A section made with `SEC_COMMIT`, by its handle. + Section(usize), +} + +/// Opens a heap on memory the process has. +pub(crate) fn open(device: &ID3D12Device, from: From) -> windows::core::Result<ID3D12Heap> { + // SAFETY: the calls take an address or a handle and check both + // themselves; a refusal is an error code. + unsafe { + match from { + From::Region(at) => device.cast::<ID3D12Device3>()?.OpenExistingHeapFromAddress(at as *const c_void), + From::Part(at, bytes) => device.cast::<ID3D12Device13>()?.OpenExistingHeapFromAddress1(at as *const c_void, bytes), + From::Section(handle) => device.cast::<ID3D12Device3>()?.OpenExistingHeapFromFileMapping(HANDLE(handle as *mut c_void)), + } + } +} + +fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +/// A buffer of `size` bytes at `offset` (a multiple of 64 KiB) of an +/// opened heap, which shaders may read and write, in the common state. +pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result<ID3D12Resource> { + let mut placed: Option<ID3D12Resource> = None; + // The heap is cross-adapter shared, so the buffer must say so too. + let flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // SAFETY: plain creation in a live heap. + unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? }; + placed.ok_or_else(windows::core::Error::empty) +} + +// The title's views of its physical pages, as the runtime maps them: the +// census needs them to say which view memory is one run of a section (one +// placed buffer could show it) and which is scattered pages. + +struct Views { + /// By address: bytes, the section's handle, the offset in it. + views: BTreeMap<usize, (usize, usize, u64)>, + /// By section and byte offset of a 64 KiB page: the address of that + /// page in every view that shows it. A write through one view of a + /// page is a write of the bytes every other view shows + /// (`crate::watch` guards them all). + pages: BTreeMap<(usize, u64), Vec<usize>>, + /// Sections by handle: bytes, and whether made committed. + sections: Vec<(usize, u64, bool)>, +} + +static VIEWS: Mutex<Views> = + Mutex::new(Views { views: BTreeMap::new(), pages: BTreeMap::new(), sections: Vec::new() }); + +fn views() -> std::sync::MutexGuard<'static, Views> { + VIEWS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The runtime made a section of `bytes` for physical pages; `committed` +/// if with `SEC_COMMIT` (only such a section can be opened as a heap). +pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { + { + let mut v = views(); + v.sections.retain(|s| s.0 != section); + v.sections.push((section, bytes, committed)); + } + // A view of our own made on an earlier section that had this handle's + // number shows that section's pages, not this one's: it is forgotten + // (left mapped: nothing reads it any more) and the next store through + // a view of ours maps this section. + let gone = OWN.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|own| own.remove(§ion)).flatten(); + if gone.is_some() { + tracing::info!(section, "a section handle's number came round again: our own view of the earlier section is forgotten"); + } +} + +/// The runtime mapped `[at, at + len)` as a view of `section` from +/// `offset` on. Call after [`crate::title_memory_remapped`] of the range. +pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { + { + let mut v = views(); + v.views.insert(at, (len, section, offset)); + for k in 0..len.div_ceil(K64) { + v.pages.entry((section, offset + (k * K64) as u64)).or_default().push(at + k * K64); + } + } + // This view is writable from now on: a guard over the same bytes at + // another view must look at them again, and the pages are noted written + // there (`crate::watch`). + crate::watch::views_mapped(section, offset, len); +} + +/// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]): +/// the views that touch it are forgotten (the runtime tells again those it +/// maps anew). +pub(crate) fn views_gone(at: usize, len: usize) { + let mut v = views(); + if v.views.is_empty() { + return; + } + let end = at.saturating_add(len); + let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base); + let gone: Vec<usize> = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect(); + for base in gone { + let Some((bytes, section, offset)) = v.views.remove(&base) else { + continue; + }; + for k in 0..bytes.div_ceil(K64) { + let key = (section, offset + (k * K64) as u64); + if let Some(pages) = v.pages.get_mut(&key) { + let page = base + k * K64; + pages.retain(|&shown| shown != page); + if pages.is_empty() { + v.pages.remove(&key); + } + } + } + } +} + +/// The title views that overlap `[start, end)`, as `(address, bytes)`. +pub(crate) fn views_between(start: usize, end: usize) -> Vec<(usize, usize)> { + if start >= end { + return Vec::new(); + } + let v = views(); + let mut out = Vec::new(); + if let Some((&base, &(bytes, _, _))) = v.views.range(..=start).next_back() + && base + bytes > start + { + out.push((base, bytes)); + } + for (&base, &(bytes, _, _)) in v.views.range(start.saturating_add(1)..end) { + out.push((base, bytes)); + } + out +} + +/// The address of the 64 KiB page shown at `page` in every title view that +/// shows it, `page`'s own address included; empty if `page` is not a view. +pub(crate) fn pages_of(page: usize) -> Vec<usize> { + let v = views(); + let Some((&base, &(bytes, section, offset))) = v.views.range(..=page).next_back() else { + return Vec::new(); + }; + let within = page.wrapping_sub(base); + if within >= bytes || !within.is_multiple_of(K64) { + return Vec::new(); + } + v.pages.get(&(section, offset + within as u64)).cloned().unwrap_or_default() +} + +/// The title views that show any of the physical bytes `[offset, offset + +/// len)` of `section`, as `(address, bytes)` ranges in address order; not +/// those of a page shown in very many views (`MANY_VIEWS`). +pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<(usize, usize)> { + if len == 0 { + return Vec::new(); + } + let v = views(); + let end = offset.saturating_add(len as u64); + let mut pages: Vec<usize> = Vec::new(); + let mut at = offset - offset % K64 as u64; + while at < end { + if let Some(shown) = v.pages.get(&(section, at)) + && shown.len() <= crate::watch::MANY_VIEWS + { + pages.extend(shown.iter().copied()); + } + match at.checked_add(K64 as u64) { + Some(next) => at = next, + None => break, + } + } + pages.sort_unstable(); + pages.dedup(); + let mut runs: Vec<(usize, usize)> = Vec::with_capacity(pages.len()); + for page in pages { + match runs.last_mut() { + Some((first, bytes)) if *first + *bytes == page => *bytes += K64, + _ => runs.push((page, K64)), + } + } + runs +} + +/// Whether what shaders wrote goes back into title view memory through a +/// view of our own (`VICTORY_BACK_OWN_VIEW=1`; off by default). +/// +/// The copy-back writes title memory at the title's address, so it opens +/// the guard on the 64 KiB block first (and on every other view of the +/// page), and the block then counts as written by the title: the host +/// copy that just put the bytes there copies all 64 KiB of it back in at +/// its next refresh, and sends them up to the card again if it lives +/// there. In runs 218-222 the bytes copied in went with the bytes copied +/// back, 0.83 MB for each MB (78 readings), some 50 MB of 142 MB a frame. +/// +/// With the switch the bytes are stored through a view of our own on the +/// same section, which no guard covers: the title's views stay read-only +/// (a title write still faults and is seen), the write-watch journal is +/// told the page was written (`crate::watch::wrote_own`) so that every +/// other copy of it takes it again, and the copy that wrote it notes the +/// page current (`put_back_own` in `crate::shadow`). +/// +/// `VICTORY_BACK_OWN_VIEW=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log, for measuring it in one scene. +pub(crate) fn back_own() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_BACK_OWN_VIEW").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "copy-back through views of our own from now (VICTORY_BACK_OWN_VIEW=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// A view of our own on a whole section of the title's physical pages: +/// where it is, its bytes, and which of its 64 KiB blocks we have asked +/// to be committed through it (a bit each). +struct Own { + base: usize, + bytes: u64, + committed: Vec<u64>, +} + +/// Our own views by section handle; `None` in a section's place if the +/// host refused the view (not asked again). +static OWN: Mutex<Option<std::collections::HashMap<usize, Option<Own>>>> = Mutex::new(None); + +/// Stores `bytes` at title address `at` through a view of our own +/// ([`back_own`]), if `[at, at + bytes.len())` lies in one 64 KiB page of +/// a title view of a section. Gives the addresses of that page in every +/// title view that shows it (the page of `at` among them), or `None` with +/// nothing written: not view memory, a page of very many views, the +/// runtime changing mappings at this moment, or the host refusing. +pub(crate) fn write_own(at: usize, bytes: &[u8]) -> Option<Vec<usize>> { + if bytes.is_empty() || at / K64 != (at + bytes.len() - 1) / K64 { + return None; + } + // No mapping changes until the bytes are in: the view found below + // shows these pages for as long as this is held. + let _still = crate::watch::title_memory_reading_now()?; + let (section, offset, shown, section_bytes) = { + let v = views(); + let (&base, &(len, section, offset)) = v.views.range(..=at).next_back()?; + if at + bytes.len() > base + len { + return None; + } + let offset = offset + (at - base) as u64; + let shown = v.pages.get(&(section, offset - offset % K64 as u64))?.clone(); + if shown.len() > crate::watch::MANY_VIEWS { + return None; + } + let section_bytes = v.sections.iter().find(|s| s.0 == section)?.1; + (section, offset, shown, section_bytes) + }; + if offset + bytes.len() as u64 > section_bytes { + return None; + } + let mut own = OWN.lock().unwrap_or_else(|e| e.into_inner()); + let view = own + .get_or_insert_with(Default::default) + .entry(section) + .or_insert_with(|| { + // SAFETY: a section handle the runtime gave us, alive as long + // as the title's views of it are; the view is ours and stays. + let at = unsafe { mem::MapViewOfFile(section as *mut c_void, mem::FILE_MAP_WRITE, 0, 0, 0) }; + if at.Value.is_null() { + tracing::warn!( + section, + error = %std::io::Error::last_os_error(), + "no view of our own on a section of title pages: what shaders wrote goes back the old way there" + ); + return None; + } + tracing::info!( + section, + mb = section_bytes >> 20, + "a view of our own on a section of title pages, for what shaders wrote (VICTORY_BACK_OWN_VIEW=1)" + ); + Some(Own { + base: at.Value as usize, + bytes: section_bytes, + committed: vec![0; (section_bytes as usize).div_ceil(K64).div_ceil(64)], + }) + }) + .as_mut()?; + if offset + bytes.len() as u64 > view.bytes { + return None; + } + let block = offset as usize / K64; + if (view.committed[block / 64] & (1u64 << (block % 64))) == 0 { + // The title's view committed these pages of the section; asked + // once more through ours, which changes nothing if they are. + // SAFETY: a block inside our own view. + let there = unsafe { + mem::VirtualAlloc((view.base + block * K64) as *const c_void, K64, mem::MEM_COMMIT, mem::PAGE_READWRITE) + }; + if there.is_null() { + return None; + } + view.committed[block / 64] |= 1u64 << (block % 64); + } + // SAFETY: committed bytes inside our own view; the source is the + // caller's slice. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), (view.base + offset as usize) as *mut u8, bytes.len()) }; + Some(shown) +} + +/// How the views cover `[at, at + len)`. +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub(crate) enum Cover { + /// No view holds its first byte. + None, + /// Views hold a part of it only. + Holes, + /// Views hold all of it, from more than one place. + Scattered, + /// All of it is one run of one section: the section and the offset of + /// `at` in it. + Run(usize, u64), +} + +fn cover_in(views: &BTreeMap<usize, (usize, usize, u64)>, at: usize, len: usize) -> Cover { + let end = at + len.max(1); + let Some((&base, &(bytes, section, offset))) = views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at) else { + return Cover::None; + }; + let first = (section, offset + (at - base) as u64); + let (mut reached, mut one) = (base + bytes, true); + while reached < end { + let Some(&(bytes, s, o)) = views.get(&reached) else { + return Cover::Holes; + }; + one &= s == first.0 && o == first.1 + (reached - at) as u64; + reached += bytes; + } + if one { Cover::Run(first.0, first.1) } else { Cover::Scattered } +} + +/// [`Cover`] of `[at, at + len)` by the title's views as they are now. +pub(crate) fn cover(at: usize, len: usize) -> Cover { + cover_in(&views().views, at, len) +} + +/// Whether `[at, at + len)` is private memory, all committed and +/// read-write: what [`From::Part`] takes. One question to Windows (it +/// walks the page tables to the end of the pages that share the first +/// one's state: a millisecond in the title's big blocks, so ask when a +/// copy is made, not when it is used). +pub(crate) fn private_whole(at: usize, len: usize) -> bool { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + n != 0 + && info.State == mem::MEM_COMMIT + && info.Type == mem::MEM_PRIVATE + && info.Protect == mem::PAGE_READWRITE + && (info.BaseAddress as usize).saturating_add(info.RegionSize) >= at.saturating_add(len) +} + +fn hr<T>(result: &windows::core::Result<T>) -> String { + match result { + Ok(_) => "ok".to_owned(), + Err(e) => format!("REFUSED {:#010x} ({})", e.code().0, e.message().trim()), + } +} + +/// A queue, a list and a fence of the probe's own on `device`: nothing of +/// the host's submissions is touched. +struct Rig { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + done: u64, + event: HANDLE, +} + +impl Drop for Rig { + fn drop(&mut self) { + // SAFETY: our event. + unsafe { + let _ = windows::Win32::Foundation::CloseHandle(self.event); + } + } +} + +impl Rig { + fn new(device: &ID3D12Device) -> windows::core::Result<Rig> { + // SAFETY: plain creation of objects of our own. + unsafe { + let queue: ID3D12CommandQueue = + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + Ok(Rig { device: device.clone(), queue, allocator, list, fence, done: 0, event }) + } + } + + /// Records with `record`, runs it and waits (ten seconds at most). + fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> windows::core::Result<()> { + // SAFETY: our own list and queue, one run at a time. + unsafe { + self.allocator.Reset()?; + self.list.Reset(&self.allocator, None)?; + record(&self.list); + self.list.Close()?; + self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]); + self.done += 1; + self.queue.Signal(&self.fence, self.done)?; + self.fence.SetEventOnCompletion(self.done, self.event)?; + if WaitForSingleObject(self.event, 10_000).0 != 0 { + return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)); + } + self.device.GetDeviceRemovedReason() + } + } + + fn committed(&self, kind: D3D12_HEAP_TYPE, size: u64, state: D3D12_RESOURCE_STATES) -> windows::core::Result<ID3D12Resource> { + let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), state, None, &mut buffer)? + }; + buffer.ok_or_else(windows::core::Error::empty) + } + + /// What the GPU reads of `size` bytes of `resource` from `offset`. + fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result<Vec<u8>> { + let back = self.committed(D3D12_HEAP_TYPE_READBACK, size as u64, D3D12_RESOURCE_STATE_COPY_DEST)?; + // SAFETY: two live buffers, the range inside both. + self.run(|list| unsafe { list.CopyBufferRegion(&back, 0, resource, offset, size as u64) })?; + let mut data = std::ptr::null_mut(); + // SAFETY: the mapping holds `size` bytes until unmapped. + unsafe { + back.Map(0, None, Some(&mut data))?; + let bytes = std::slice::from_raw_parts(data.cast::<u8>(), size).to_vec(); + back.Unmap(0, None); + Ok(bytes) + } + } + + /// The GPU writes `bytes` at `offset` of `resource` (a copy). + fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> { + let up = self.committed(D3D12_HEAP_TYPE_UPLOAD, bytes.len() as u64, D3D12_RESOURCE_STATE_GENERIC_READ)?; + let mut data = std::ptr::null_mut(); + // SAFETY: the mapping holds the buffer's bytes until unmapped. + unsafe { + up.Map(0, None, Some(&mut data))?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::<u8>(), bytes.len()); + up.Unmap(0, None); + } + // SAFETY: two live buffers, the range inside both. + self.run(|list| unsafe { list.CopyBufferRegion(resource, offset, &up, 0, bytes.len() as u64) }) + } + + /// A compute shader stores, through a root unordered-access view at + /// `gpu`, the sum of the buffer's first two words in its third. + fn shade(&mut self, gpu: u64) -> windows::core::Result<()> { + const SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n"; + let mut code: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; then the + // blob's own bytes, which hold the root signature too. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?; + let code = code.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + })?; + (root, pso) + }; + // SAFETY: an open list of ours; the view names a live buffer. + self.run(|list| unsafe { + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, gpu); + list.Dispatch(1, 1, 1); + }) + } + + /// Milliseconds the card takes to copy `bytes` of `from` into its own + /// memory, the best of three. + fn copy_ms(&mut self, from: &ID3D12Resource, bytes: u64) -> windows::core::Result<f64> { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut to: Option<ID3D12Resource> = None; + // SAFETY: plain creation. + unsafe { + self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut to)? + }; + let to = to.ok_or_else(windows::core::Error::empty)?; + let mut best = f64::MAX; + for _ in 0..3 { + let started = std::time::Instant::now(); + // SAFETY: two live buffers of `bytes` bytes or more. + self.run(|list| unsafe { list.CopyBufferRegion(&to, 0, from, 0, bytes) })?; + best = best.min(started.elapsed().as_secs_f64() * 1000.0); + } + Ok(best) + } +} + +fn fill(at: *mut u8, len: usize, seed: u8) { + for i in 0..len { + // SAFETY: the caller's own committed memory of `len` bytes. + unsafe { at.add(i).write((i as u8).wrapping_mul(31).wrapping_add(seed)) }; + } +} + +fn same(at: *const u8, bytes: &[u8]) -> bool { + // SAFETY: the caller's own committed memory of that length. + unsafe { std::slice::from_raw_parts(at, bytes.len()) == bytes } +} + +/// The process's working set in MB. +fn working_set_mb() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + let mut counters = PROCESS_MEMORY_COUNTERS { cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, ..Default::default() }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut counters, counters.cb) }; + counters.WorkingSetSize as u64 >> 20 +} + +/// What the probe found. The lines are the whole account; the flags are +/// what the stages build on. +#[derive(Default)] +pub(crate) struct Probe { + pub(crate) lines: Vec<String>, + /// A part of private, write-watched memory opens, a buffer in it shows + /// the memory's bytes to the GPU, also those the CPU wrote afterwards. + pub(crate) part_reads: bool, + /// What the GPU writes there (a copy, and a shader through unordered + /// access) the CPU reads at the memory's address. + pub(crate) part_writes: bool, + /// The same two for a committed section, through a view of it. + pub(crate) section_reads: bool, + pub(crate) section_writes: bool, + /// The section's heap outlives the view: the GPU's write with no view + /// mapped shows in a view mapped afterwards. + pub(crate) section_outlives_views: bool, + /// A section made with `SEC_RESERVE` (as `xmem` makes the page pool) + /// was refused. + pub(crate) reserved_section_refused: bool, +} + +/// Tries the openings on memory of the probe's own, made the way `xmem` +/// makes title memory, with a queue of its own on `device`; `memory` +/// gives the card's memory account (`Host::video_memory`) where there is +/// one. Nothing of the title's is touched. `mb` is the size of the cost +/// measurement (0 leaves it out). +pub(crate) fn probe(device: &ID3D12Device, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) -> Probe { + let mut p = Probe::default(); + let mut rig = match Rig::new(device) { + Ok(rig) => rig, + Err(e) => { + p.lines.push(format!("no queue of its own: {e}")); + return p; + } + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: a plain query that fills our structure. + let _ = unsafe { device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, (&raw mut options).cast(), size_of_val(&options) as u32) }; + p.lines.push(format!( + "the device: ID3D12Device3 {}, ID3D12Device13 {} (parts of an allocation); cross-adapter row-major textures {}; heap tier {}", + device.cast::<ID3D12Device3>().is_ok(), + device.cast::<ID3D12Device13>().is_ok(), + options.CrossAdapterRowMajorTextureSupported.as_bool(), + options.ResourceHeapTier.0 + )); + // SAFETY: memory of the probe's own, made and released here; every + // address used lies inside it. + unsafe { + private(&mut p, &mut rig); + section(&mut p, &mut rig); + if mb > 0 { + cost(&mut p, &mut rig, memory, mb); + } + } + p.lines.push(format!( + "VERDICT: private memory in place: reads {}, writes {}; the page pool's section in place: reads {}, writes {}, whatever the views do {}; \ + a reserved section is refused {} (the pool must be made committed to be opened)", + p.part_reads, p.part_writes, p.section_reads, p.section_writes, p.section_outlives_views, p.reserved_section_refused + )); + p +} + +fn describe(heap: &ID3D12Heap) -> String { + // SAFETY: a plain query. + let d = unsafe { heap.GetDesc() }; + format!( + "heap of {} KiB: type {} (4 = custom), CPU pages {} (3 = write-back), pool {} (1 = the PC's memory), alignment {}, flags {:#x} (0x1 shared, 0x20 cross-adapter, 0x200 write watch, 0x400 shader atomics)", + d.SizeInBytes >> 10, + d.Properties.Type.0, + d.Properties.CPUPageProperty.0, + d.Properties.MemoryPoolPreference.0, + d.Alignment, + d.Flags.0 + ) +} + +/// Private memory, reserved as `xmem` reserves the title's heaps +/// (committed, read-write, write-watched): a part of it opened. +unsafe fn private(p: &mut Probe, rig: &mut Rig) { + const SIZE: usize = 64 * K64; + // SAFETY (the whole function): the allocation below, `SIZE` bytes. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>(); + if base.is_null() { + p.lines.push("private memory: none to try with".to_owned()); + return; + } + // The part: 16 pages from the 16th on. + let (at, bytes) = (base.add(16 * K64), 16 * K64); + let whole = open(&rig.device, From::Region(base as usize)); + p.lines.push(format!("private memory, the whole allocation (OpenExistingHeapFromAddress): {}", hr(&whole))); + drop(whole); + let opened = open(&rig.device, From::Part(at as usize, bytes)); + p.lines.push(format!("private memory, a part of it (OpenExistingHeapFromAddress1): {}", hr(&opened))); + if let Ok(heap) = &opened { + p.lines.push(format!(" {}", describe(heap))); + let placed = place(&rig.device, heap, K64 as u64, 4 * K64 as u64); + p.lines.push(format!(" a buffer placed in it (cross-adapter, unordered access): {}", hr(&placed))); + if let Ok(buffer) = &placed { + let memory = at.add(K64); + fill(memory, 4 * K64, 1); + let first = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + fill(memory, 4 * K64, 77); + let second = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + p.part_reads = first && second; + p.lines.push(format!(" the GPU reads the memory's bytes: {first}; and those the CPU wrote afterwards, with no call in between: {second}")); + mem::ResetWriteWatch(base.cast(), SIZE); + let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x5a).collect(); + let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new); + let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32); + let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0; + memory.cast::<[u32; 3]>().write([40, 2, 0]); + let shaded = rig.shade(buffer.GetGPUVirtualAddress()); + let shader = shaded.is_ok() && memory.cast::<[u32; 3]>().read()[2] == 42; + p.part_writes = copied && shader; + p.lines.push(format!( + " the CPU reads at the memory's address what the GPU wrote: by a copy {copied}; by a shader through unordered access {shader} ({}); \ + write watching saw {} of the copy's 16 pages{}", + hr(&shaded), + if watched { count } else { 0 }, + if watched { "" } else { " (the asking failed)" } + )); + } + // What the title can still do with the pages while the heap stands. + let mut old = 0; + let protect_in = mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + if protect_in { + mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READWRITE, &mut old); + } + let decommit_in = mem::VirtualFree(at.add(9 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + let decommit_out = mem::VirtualFree(base.add(40 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + p.lines.push(format!( + " with the heap standing, the title's own calls: read-only inside the part {protect_in}, decommit inside {decommit_in}, decommit outside {decommit_out} \ + (false inside means the heap must go before the title frees or guards those pages)" + )); + drop(placed); + } + drop(opened); + let freed = mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE) != 0; + p.lines.push(format!(" released after the heap went: {freed}")); + } +} + +/// A section and a view of it in a placeholder, as `xmem` maps physical +/// pages: reserved (as it is made today) and committed. +unsafe fn section(p: &mut Probe, rig: &mut Rig) { + const SIZE: usize = 32 * K64; + // SAFETY (the whole function): the sections, placeholder and views + // made below. + unsafe { + let process = windows_sys::Win32::System::Threading::GetCurrentProcess(); + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let reserved = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_RESERVE, 0, SIZE as u32, std::ptr::null()); + if !reserved.is_null() { + let opened = open(&rig.device, From::Section(reserved as usize)); + p.reserved_section_refused = opened.is_err(); + p.lines.push(format!("a section made reserved, as the page pool is today (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + drop(opened); + windows_sys::Win32::Foundation::CloseHandle(reserved); + } + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); + let hole = mem::VirtualAlloc2(process, std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, mem::PAGE_NOACCESS, std::ptr::null_mut(), 0).cast::<u8>(); + if handle.is_null() || hole.is_null() { + p.lines.push("a committed section: none to try with".to_owned()); + return; + } + // Pages 4..12 of the section at the placeholder's start. + mem::VirtualFree(hole.cast(), 8 * K64, mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER); + let view = mem::MapViewOfFile3(handle, process, hole.cast(), (4 * K64) as u64, 8 * K64, mem::MEM_REPLACE_PLACEHOLDER, mem::PAGE_READWRITE, std::ptr::null_mut(), 0); + let opened = open(&rig.device, From::Section(handle as usize)); + p.lines.push(format!("a section made committed (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + let mut unmapped = false; + if let (Ok(heap), false) = (&opened, view.Value.is_null()) { + p.lines.push(format!(" {}", describe(heap))); + // The section's page 5 is the view's second page. + let placed = place(&rig.device, heap, 5 * K64 as u64, 2 * K64 as u64); + p.lines.push(format!(" a buffer placed at the section's offset of a view's pages: {}", hr(&placed))); + if let Ok(buffer) = &placed { + let memory = hole.add(K64); + fill(memory, 2 * K64, 3); + p.section_reads = rig.fetch(buffer, 0, 2 * K64).is_ok_and(|got| same(memory, &got)); + let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x33).collect(); + p.section_writes = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); + // The guard of `watch.rs`: the view read-only. + let mut old = 0; + let guarded = mem::VirtualProtect(memory.cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x44).collect(); + let through = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); + // The view goes; the GPU writes; another view shows it. + unmapped = mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0; + let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x55).collect(); + let stored = rig.store(buffer, 0, &new).is_ok(); + let other = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (5 * K64) as u32, K64); + p.section_outlives_views = unmapped && stored && !other.Value.is_null() && same(other.Value.cast(), &new); + p.lines.push(format!( + " the GPU reads the view's bytes {}; the CPU reads through the view what the GPU wrote {}; the view made read-only under the heap {guarded}, \ + and the GPU writes it all the same {through}; the view unmapped under the heap {unmapped}, the GPU's write then shows in a view mapped afterwards {}", + p.section_reads, p.section_writes, p.section_outlives_views + )); + if !other.Value.is_null() { + mem::UnmapViewOfFile(other); + } + } + } + drop(opened); + if !unmapped && !view.Value.is_null() { + mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER); + } + windows_sys::Win32::Foundation::CloseHandle(handle); + // The placeholder was split in two: each half is released. + mem::VirtualFree(hole.cast(), 0, mem::MEM_RELEASE); + mem::VirtualFree(hole.add(8 * K64).cast(), 0, mem::MEM_RELEASE); + } +} + +/// What opening costs, on `mb` MB each of private memory never touched +/// and of a committed section never touched: the time, the working set, +/// the card's account of the PC's memory shared with it; and how fast the +/// card copies out of such a heap against a shared buffer of today's kind. +unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) { + let bytes = mb << 20; + let shared = || memory().map_or(0, |m| m[3] >> 20); + let ms = |speed: Option<f64>| speed.map_or("?".to_owned(), |ms| format!("{ms:.1}")); + // SAFETY (the whole function): the allocation and the section below. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>(); + if !base.is_null() { + let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); + let opened = open(&rig.device, From::Part(base as usize, bytes)); + let took = started.elapsed().as_secs_f64() * 1000.0; + let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + p.lines.push(format!( + "cost, {mb} MB of private memory never touched: {}; opened in {took:.1} ms; working set {set} -> {} MB; shared with the card {account} -> {} MB; \ + the card copies it out in {} ms", + hr(&opened), + working_set_mb(), + shared(), + ms(speed) + )); + drop((placed, opened)); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, (bytes as u64 >> 32) as u32, bytes as u32, std::ptr::null()); + if !handle.is_null() { + let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); + let opened = open(&rig.device, From::Section(handle as usize)); + let took = started.elapsed().as_secs_f64() * 1000.0; + let (set_opened, account_opened) = (working_set_mb(), shared()); + let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + p.lines.push(format!( + "cost, {mb} MB of a committed section never touched: {}; opened in {took:.1} ms; working set {set} -> {set_opened} -> after the card read all of it {} MB; \ + shared with the card {account} -> {account_opened} -> {} MB; the card copies it out in {} ms", + hr(&opened), + working_set_mb(), + shared(), + ms(speed) + )); + drop((placed, opened)); + windows_sys::Win32::Foundation::CloseHandle(handle); + } + // Today's kind of host copy, for the comparison. + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + let made = rig.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &buffer_desc(bytes as u64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ); + if let (Ok(()), Some(buffer)) = (made, buffer) { + let speed = rig.copy_ms(&buffer, bytes as u64).ok(); + p.lines.push(format!("cost, for comparison: the card copies {mb} MB out of a shared buffer of today's kind in {} ms", ms(speed))); + } + } +} + +// The census: which of the title memory that has host copies today could +// be opened, and by which opening. + +/// Counts and bytes by kind, in the order of [`KINDS`]. +#[derive(Default, Clone, Copy)] +struct Tally([(u64, u64); 6]); + +const KINDS: [&str; 6] = [ + "private, committed whole (a part can be opened)", + "view memory, one run of a section (one placed buffer)", + "view memory, scattered pages", + "view memory with unmapped pages", + "private but not committed whole, or guarded", + "other", +]; + +fn kind_of(at: usize, len: usize, known: &mut Vec<(usize, usize)>) -> usize { + match cover(at, len) { + Cover::Run(..) => return 1, + Cover::Scattered => return 2, + Cover::Holes => return 3, + Cover::None => {} + } + let end = at + len; + if known.iter().any(|&(from, to)| from <= at && end <= to) { + return 0; + } + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + if n == 0 { + return 5; + } + let reach = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if info.Type == mem::MEM_PRIVATE && info.State == mem::MEM_COMMIT && info.Protect == mem::PAGE_READWRITE { + known.push((info.BaseAddress as usize, reach)); + return if reach >= end { 0 } else { 4 }; + } + match info.Type { + mem::MEM_PRIVATE => 4, + mem::MEM_MAPPED => 3, + _ => 5, + } +} + +/// The census lines for `spans` (start, bytes, whether a window outside +/// buffers). +fn census_of(spans: &[(u64, u64, bool)]) -> Vec<String> { + let mut known = Vec::new(); + let (mut buffers, mut windows) = (Tally::default(), Tally::default()); + for &(start, len, window) in spans { + let kind = kind_of(start as usize, len as usize, &mut known); + let tally = if window { &mut windows } else { &mut buffers }; + tally.0[kind].0 += 1; + tally.0[kind].1 += len; + } + let mut lines = Vec::new(); + for (name, tally) in [("title buffers", buffers), ("windows outside buffers", windows)] { + let all = tally.0.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); + lines.push(format!("census, {name}: {} of {} MB", all.0, all.1 >> 20)); + for (kind, &(n, bytes)) in KINDS.iter().zip(&tally.0) { + if n > 0 { + lines.push(format!("census, {kind}: {n} of {} MB", bytes >> 20)); + } + } + } + let v = views(); + let (count, bytes) = (v.views.len(), v.views.values().map(|view| view.0 as u64).sum::<u64>()); + let pages = v.views.values().filter(|view| view.0 == K64).count(); + let big = v.views.values().map(|view| view.0).max().unwrap_or(0); + lines.push(format!( + "census, the title's views of physical pages: {count} of {} MB; {pages} of them one 64 KiB page; the longest {} MB", + bytes >> 20, + big >> 20 + )); + for &(_, bytes, committed) in &v.sections { + lines.push(format!( + "census, a section of {} MB, {}", + bytes >> 20, + if committed { "committed: it can be opened as one heap" } else { "reserved: refused as a heap until it is made with SEC_COMMIT" } + )); + } + lines +} + +/// With [`probe_level`] 2: one part of the title's own private memory +/// (the start of the biggest such title buffer, 4 MiB at most) is opened +/// for a moment, a buffer placed, 64 KiB read by the GPU and compared +/// with what the CPU reads there (the title may be writing it meanwhile: +/// the count of equal bytes is given), and all of it released. While the +/// heap stands (milliseconds) a `VirtualFree` of the title's on those +/// pages would fail. +fn real_part(spans: &[(u64, u64, bool)]) -> Vec<String> { + let Some(host) = crate::host::host() else { + return Vec::new(); + }; + let mut known = Vec::new(); + let found = spans + .iter() + .filter(|s| !s.2 && s.1 >= 2 * K64 as u64) + .filter(|s| kind_of(s.0 as usize, s.1 as usize, &mut known) == 0) + .max_by_key(|s| s.1); + let Some(&(start, len, _)) = found else { + return vec!["the title's memory: no title buffer in private, committed memory to try".to_owned()]; + }; + let at = (start as usize).next_multiple_of(K64); + let bytes = ((start + len) as usize).saturating_sub(at).min(4 << 20) & !(K64 - 1); + if bytes == 0 || !private_whole(at, bytes) { + return vec!["the title's memory: the buffer found holds no whole 64 KiB page that is still committed".to_owned()]; + } + let mut lines = Vec::new(); + let (set, started) = (working_set_mb(), std::time::Instant::now()); + let opened = open(&host.device, From::Part(at, bytes)); + lines.push(format!( + "the title's memory, {} KiB at {at:#x} (of the title buffer {start:#x}+{len:#x}): {}; in {:.1} ms; working set {set} -> {} MB", + bytes >> 10, + hr(&opened), + started.elapsed().as_secs_f64() * 1000.0, + working_set_mb() + )); + if let Ok(heap) = &opened { + let placed = place(&host.device, heap, 0, bytes as u64); + lines.push(format!(" a buffer placed over it: {}", hr(&placed))); + if let (Ok(buffer), Ok(mut rig)) = (&placed, Rig::new(&host.device)) { + let mut before = vec![0u8; K64]; + crate::host::copy_mapped(before.as_mut_ptr(), at as *const u8, K64, false); + let got = rig.fetch(buffer, 0, K64); + let mut after = vec![0u8; K64]; + crate::host::copy_mapped(after.as_mut_ptr(), at as *const u8, K64, false); + match got { + Ok(got) => { + let equal = (0..K64).filter(|&i| got[i] == before[i] || got[i] == after[i]).count(); + let zeros = got.iter().filter(|&&b| b == 0).count(); + lines.push(format!( + " the GPU read 64 KiB of the title's own bytes: {equal} of {K64} equal to what the CPU read just before or just after ({zeros} of them zero)" + )); + } + Err(e) => lines.push(format!(" the GPU's read failed: {e}")), + } + } + } + lines +} + +/// Called once a second by the thread that submits, before a submission +/// (`host::sweep`): with [`probe_level`], the probe at the first call, the +/// census (on a thread of its own: it asks Windows about every copy) 30 +/// and 150 seconds later. +pub(crate) fn tick() { + if level() > 0 { + say(); + } + if probe_level() == 0 { + return; + } + static STARTED: AtomicU64 = AtomicU64::new(0); + static DONE: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms().max(1); + let started = match STARTED.compare_exchange(0, now, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => { + let Some(host) = crate::host::host() else { + return; + }; + let mb = std::env::var("VICTORY_INPLACE_PROBE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64usize); + let took = std::time::Instant::now(); + let probe = probe(&host.device, &|| host.video_memory(), mb.min(1024)); + for line in &probe.lines { + tracing::info!("in place probe: {line}"); + } + tracing::info!("in place probe: took {:.0} ms", took.elapsed().as_secs_f64() * 1000.0); + now + } + Err(started) => started, + }; + let due = match DONE.load(Ordering::Relaxed) { + 0 => now >= started + 30_000, + 1 => now >= started + 150_000, + _ => false, + }; + if due { + let which = DONE.fetch_add(1, Ordering::Relaxed); + std::thread::spawn(move || { + let spans = crate::shadow::spans(); + for line in census_of(&spans) { + tracing::info!("in place {line}"); + } + if which == 0 && probe_level() >= 2 { + for line in real_part(&spans) { + tracing::info!("in place probe: {line}"); + } + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Views as the runtime tells them: a range inside one view, or over + /// views that continue each other in one section, is one run; over + /// views from elsewhere it is scattered; over a gap it has holes. + #[test] + fn views_say_what_one_placed_buffer_could_show() { + let mut views = BTreeMap::new(); + let at = 0x7_0000_0000usize; + views.insert(at, (4 * K64, 9, 16 * K64 as u64)); + // Continues the first in the section. + views.insert(at + 4 * K64, (2 * K64, 9, 20 * K64 as u64)); + // Follows in address, from elsewhere in the section. + views.insert(at + 6 * K64, (K64, 9, 3 * K64 as u64)); + // After a gap of one page. + views.insert(at + 8 * K64, (K64, 9, 4 * K64 as u64)); + assert_eq!(cover_in(&views, at + K64, 2 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!(cover_in(&views, at + K64, 5 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!(cover_in(&views, at, 7 * K64), Cover::Scattered); + assert_eq!(cover_in(&views, at + 6 * K64, 3 * K64), Cover::Holes); + assert_eq!(cover_in(&views, at + 7 * K64, K64), Cover::None); + assert_eq!(cover_in(&views, at - K64, 2 * K64), Cover::None); + } + + /// What the runtime forgets when memory is mapped anew. + #[test] + fn remapped_memory_forgets_its_views() { + let at = 0x7_4000_0000usize; + title_memory_view(at, 4 * K64, 77, 0); + title_memory_view(at + 4 * K64, K64, 77, 4 * K64 as u64); + assert_eq!(cover(at, 5 * K64), Cover::Run(77, 0)); + // One page inside the first view goes: the whole view is forgotten + // (the runtime maps and tells again what stays of it). + views_gone(at + K64, K64); + assert_eq!(cover(at, K64), Cover::None); + assert_eq!(cover(at + 4 * K64, K64), Cover::Run(77, 4 * K64 as u64)); + views_gone(at + 4 * K64, K64); + assert_eq!(cover(at + 4 * K64, K64), Cover::None); + } + + /// Only private memory committed whole, read-write, is taken for a part. + #[test] + fn only_private_memory_committed_whole_is_a_part() { + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE, mem::PAGE_NOACCESS).cast::<u8>(); + assert!(!base.is_null()); + assert!(!private_whole(base as usize, K64), "reserved only"); + mem::VirtualAlloc(base.cast(), 4 * K64, mem::MEM_COMMIT, mem::PAGE_READWRITE); + assert!(private_whole(base as usize, 4 * K64)); + assert!(private_whole(base as usize + K64, 2 * K64)); + assert!(!private_whole(base as usize, 5 * K64), "reaches into the reserved half"); + let mut old = 0; + mem::VirtualProtect(base.cast(), K64, mem::PAGE_READONLY, &mut old); + assert!(!private_whole(base as usize, 2 * K64), "a guarded page"); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + } + + pub(crate) fn warp() -> Option<ID3D12Device> { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::*; + // SAFETY: plain DXGI queries and device creation on the software + // adapter; a card is never opened. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option<ID3D12Device> = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + device + } + } + + /// The probe, whole, on the software adapter: the same calls the card + /// gets. The runtime's and the kernel's rules hold there; the card's + /// driver is what a run with `VICTORY_INPLACE_PROBE=1` adds. + #[test] + fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() { + eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); + return; + } + let probe = probe(&device, &|| None, 4); + for line in &probe.lines { + eprintln!("in place probe: {line}"); + } + assert!(probe.part_reads, "the GPU reads private memory in place"); + assert!(probe.part_writes, "GPU writes land in private memory"); + assert!(probe.section_reads && probe.section_writes, "a committed section in place"); + assert!(probe.section_outlives_views, "the section's heap does not depend on views"); + assert!(probe.reserved_section_refused, "a reserved section is refused"); + } + + /// Stage 1's own call on the software adapter: a title buffer that + /// begins and ends off the 64 KiB lines is placed over its pages, the + /// GPU reads the buffer's bytes at the offset the views use, and its + /// write lands at the title's address. Memory that is not committed + /// whole is turned down without asking the host. + #[test] + fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() { + return; + } + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>(); + let (start, len) = (base as u64 + K64 as u64 + 0x1230, 2 * K64 as u64 + 5); + let placed = place_part(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(placed.bias, 0x1230); + assert_eq!(placed.gpu, placed.buffer.GetGPUVirtualAddress() + 0x1230); + assert_eq!(placed.buffer.GetDesc().Width, 3 * K64 as u64, "the pages that hold the buffer"); + let mut rig = Rig::new(&device).unwrap(); + fill(start as *mut u8, len as usize, 7); + let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap(); + assert!(same(start as *const u8, &got), "the GPU reads the title buffer's bytes"); + rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap(); + assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); + drop(placed); + // Half of it decommitted: turned down, the host not asked. + assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + assert!(matches!(place_part(&device, start, len), Err(None))); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + } + + /// The census names each kind of memory. + #[test] + fn census_tells_private_memory_from_views() { + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as u64; + let view = 0x7_8000_0000u64; + title_memory_view(view as usize, 2 * K64, 5, 0); + title_memory_view(view as usize + 2 * K64, K64, 5, 9 * K64 as u64); + let lines = census_of(&[(base, 2 * K64 as u64, false), (base + 4 * K64 as u64, K64 as u64, true), (view, K64 as u64, true), (view, 3 * K64 as u64, false)]); + let text = lines.join("\n"); + assert!(text.contains("census, title buffers: 2 of"), "{text}"); + assert!(text.contains("census, private, committed whole (a part can be opened): 1 of"), "{text}"); + assert!(text.contains("census, view memory, scattered pages: 1 of"), "{text}"); + assert!(text.contains("census, view memory, one run of a section (one placed buffer): 1 of"), "{text}"); + views_gone(view as usize, 3 * K64); + mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE); + } + } +} diff --git a/crates/victory-gpu/src/lazy.rs b/crates/victory-gpu/src/lazy.rs new file mode 100644 index 0000000000..831872d344 --- /dev/null +++ b/crates/victory-gpu/src/lazy.rs @@ -0,0 +1,401 @@ +//! Lazy copy-back (`VICTORY_LAZY_BACK=0` turns it off): with the relay +//! (`crate::host::relay`), when the card has run a batch of flights, the +//! title memory their shaders may have written is made no-access, the +//! fences behind them are signalled at once, and only then is what the +//! shaders wrote copied back into it. Before, the title heard that the card +//! was done only after the whole copy-back, 200-800 ms a frame in the +//! 2026-11-24 reports: every title thread that waited for a fence to reuse +//! memory, pace its frames or submit more waited for it, even when it never +//! read what the shaders wrote. +//! +//! Now a title thread that touches held memory takes an access violation; +//! our handler holds it until the batch is copied back (or +//! `VICTORY_LAZY_BACK_WAIT_MS`, 1000 unless set, have passed: then that +//! piece is opened as it is, so no thread waits for ever on one that waits +//! for it), then the access runs again. Our own reads and writes of title +//! memory through the kernel (`crate::host::read_into`, +//! `crate::host::write_mapped`) fail on held memory; they open the 64 KiB +//! pieces they touch and try again, which is how the copy-back itself gets +//! in, piece by piece, right before it merges one. The pieces nothing +//! wrote are opened together when the batch is done, each with the +//! protection it had (write-watch guards of `crate::watch` included). +//! +//! shortcut: a title thread that first touches a piece in the microseconds +//! between the copy-back opening it and writing it reads the bytes from +//! before (the copy-back already races title writes the same way). A +//! system call that reads held memory (a file write from it) fails rather +//! than waits; none is known to read what shaders wrote. If any page of a +//! batch cannot be made no-access, nothing of the batch is held and the +//! fences wait for the copy-back as before. + +use std::cell::Cell; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; +use std::time::{Duration, Instant}; + +/// The kernel's page, the unit of protection. +const PAGE: usize = 4096; +/// What a merge opens at a time, and what the held memory is noted in. +const PIECE: usize = 64 << 10; + +/// One held piece of title memory: where it ends, the protection it had, +/// and the start of the region it was protected with (pieces of one +/// region are opened together). +struct Held { + end: usize, + old: u32, + region: usize, +} + +struct State { + /// Piece start → piece; the pieces never overlap. + held: BTreeMap<usize, Held>, +} + +static STATE: Mutex<State> = Mutex::new(State { held: BTreeMap::new() }); +/// Told when a batch is done (everything opened). +static DONE: Condvar = Condvar::new(); +/// Something is held: the cheap test before the lock. +static ACTIVE: AtomicBool = AtomicBool::new(false); + +/// For the frame line: batches held, batches that could not be (copied +/// back first, as before), fence signals and writes sent before the +/// copy-back, title accesses held, microseconds they were held, accesses +/// let through after the longest wait. +pub(crate) static LAZY_STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +thread_local! { + /// The thread that lands flights: it opens what it touches, it never + /// waits (the copy-back it would wait for is its own). + static LANDING: Cell<bool> = const { Cell::new(false) }; +} + +/// Whether lazy copy-back is on (`VICTORY_LAZY_BACK=0` turns it off). +pub(crate) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_LAZY_BACK").is_none_or(|v| v != "0"); + if on { + tracing::info!( + wait_most_ms = wait_most().as_millis() as u64, + "the card's results are copied back after the title hears it is done; title threads that touch them first wait (VICTORY_LAZY_BACK=0: copied back first)" + ); + } + on + }) +} + +/// The longest a title thread is held (`VICTORY_LAZY_BACK_WAIT_MS`). +fn wait_most() -> Duration { + static MS: OnceLock<u64> = OnceLock::new(); + Duration::from_millis(*MS.get_or_init(|| { + std::env::var("VICTORY_LAZY_BACK_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1000) + })) +} + +/// Held memory touched by a title thread or by our own code (not by the +/// thread that lands flights, whose touches are the copy-back), as +/// (start, end), for `crate::host`'s copy-back of only what is read; a +/// fixed array, as the exception handler notes into it, and whether more +/// touches came than it holds (then everything counts as touched). +static TOUCHED: Mutex<([(usize, usize); 256], usize, bool)> = Mutex::new(([(0, 0); 256], 0, false)); + +/// Notes a touch of held `[at, at + len)` ([`TOUCHED`]). +fn touched(at: usize, len: usize) { + if LANDING.get() { + return; + } + let mut t = TOUCHED.lock().unwrap_or_else(|e| e.into_inner()); + let n = t.1; + if n < t.0.len() { + t.0[n] = (at, at.saturating_add(len.max(1))); + t.1 = n + 1; + } else { + t.2 = true; + } +} + +/// Whether held memory in `[from, to)` was touched since the last +/// [`take_touched`]. +pub(crate) fn touched_in(from: usize, to: usize) -> bool { + let t = TOUCHED.lock().unwrap_or_else(|e| e.into_inner()); + t.2 || t.0[..t.1].iter().any(|&(a, b)| a < to && b > from) +} + +/// The touches since the last call (None: more than are noted, so take +/// everything as touched), forgotten. +pub(crate) fn take_touched() -> Option<Vec<(usize, usize)>> { + let mut t = TOUCHED.lock().unwrap_or_else(|e| e.into_inner()); + let out = (!t.2).then(|| t.0[..t.1].to_vec()); + t.1 = 0; + t.2 = false; + out +} + +/// Called once by the thread that lands flights. +pub(crate) fn landing_thread() { + LANDING.set(true); +} + +fn state() -> MutexGuard<'static, State> { + STATE.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Sets the protection of `[from, to)` back to `old`. +fn restore(from: usize, to: usize, old: u32) -> bool { + use windows_sys::Win32::System::Memory::VirtualProtect; + let mut was = 0; + // SAFETY: title memory we made no-access; only its protection changes. + unsafe { VirtualProtect(from as *const _, to - from, old, &mut was) != 0 } +} + +/// Makes the title memory of `ranges` (address, end) no-access and notes +/// it held. False, with nothing held, if some committed page of it cannot +/// be (or a batch is held already): the caller copies back first, as +/// before. +pub(crate) fn hold(ranges: &[(usize, usize)]) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualProtect, VirtualQuery, + }; + install(); + let mut pages: Vec<(usize, usize)> = ranges + .iter() + .filter(|r| r.0 < r.1) + .map(|&(a, b)| (a & !(PAGE - 1), b.div_ceil(PAGE).saturating_mul(PAGE))) + .collect(); + if pages.is_empty() { + return false; + } + pages.sort_unstable(); + let mut joined: Vec<(usize, usize)> = Vec::with_capacity(pages.len()); + for (a, b) in pages { + match joined.last_mut() { + Some(last) if a <= last.1 => last.1 = last.1.max(b), + _ => joined.push((a, b)), + } + } + let mut st = state(); + if !st.held.is_empty() { + LAZY_STATS[1].fetch_add(1, Ordering::Relaxed); + return false; + } + let mut made: Vec<(usize, usize, u32)> = Vec::new(); + let mut ok = true; + 'all: for (a, b) in joined { + let mut at = a; + while at < b { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + let end = (info.BaseAddress as usize).saturating_add(info.RegionSize).min(b); + if n == 0 || end <= at { + ok = false; + break 'all; + } + if info.State != MEM_COMMIT { + // Nothing there to read; left alone. + at = end; + continue; + } + if info.Protect == 0 || info.Protect & (PAGE_GUARD | PAGE_NOACCESS) != 0 { + ok = false; + break 'all; + } + let mut old = 0; + // SAFETY: committed title memory; only its protection changes. + if unsafe { VirtualProtect(at as *const _, end - at, PAGE_NOACCESS, &mut old) } == 0 { + ok = false; + break 'all; + } + made.push((at, end, old)); + at = end; + } + } + if !ok || made.is_empty() { + for &(a, e, old) in &made { + restore(a, e, old); + } + if !ok { + LAZY_STATS[1].fetch_add(1, Ordering::Relaxed); + } + return false; + } + for (a, e, old) in made { + let mut at = a; + while at < e { + let next = ((at / PIECE + 1) * PIECE).min(e); + st.held.insert(at, Held { end: next, old, region: a }); + at = next; + } + } + ACTIVE.store(true, Ordering::Release); + LAZY_STATS[0].fetch_add(1, Ordering::Relaxed); + true +} + +/// Whether `at` lies in a held piece. +fn holds_at(st: &State, at: usize) -> bool { + st.held.range(..=at).next_back().is_some_and(|(_, h)| h.end > at) +} + +/// Whether any byte of `[at, at + len)` is held. +pub(crate) fn holds_any(at: usize, len: usize) -> bool { + if !ACTIVE.load(Ordering::Acquire) { + return false; + } + let end = at.saturating_add(len.max(1)); + state().held.range(..end).next_back().is_some_and(|(_, h)| h.end > at) +} + +/// Opens the held pieces that overlap `[from, to)`, each with the +/// protection it had; true if there were any. +fn open_locked(st: &mut State, from: usize, to: usize) -> bool { + let keys: Vec<usize> = st.held.range(..to).rev().take_while(|(_, h)| h.end > from).map(|(k, _)| *k).collect(); + for k in &keys { + if let Some(h) = st.held.remove(k) { + restore(*k, h.end, h.old); + } + } + !keys.is_empty() +} + +/// Our own access to title memory `[at, at + len)` through the kernel +/// failed: opens what of it is held (true if anything was, and the access +/// is worth another try). +pub(crate) fn release(at: usize, len: usize) -> bool { + if !ACTIVE.load(Ordering::Acquire) { + return false; + } + let opened = open_locked(&mut state(), at, at.saturating_add(len.max(1))); + if opened { + touched(at, len); + } + opened +} + +/// The runtime maps or unmaps title memory `[at, at + len)`: what is held +/// there is no longer ours to open (the new pages have their own +/// protection). +pub(crate) fn forget(at: usize, len: usize) { + if !ACTIVE.load(Ordering::Acquire) { + return; + } + let mut st = state(); + let to = at.saturating_add(len); + let keys: Vec<usize> = st.held.range(..to).rev().take_while(|(_, h)| h.end > at).map(|(k, _)| *k).collect(); + for k in keys { + st.held.remove(&k); + } +} + +/// The batch is copied back: everything still held is opened (a region's +/// pieces with one call), and the title threads held go on. +pub(crate) fn done() { + let mut st = state(); + let held = std::mem::take(&mut st.held); + let mut run: Option<(usize, usize, u32, usize)> = None; + let flush = |run: (usize, usize, u32, usize)| { + if !restore(run.0, run.1, run.2) { + // Piece by piece, as a fallback. + let mut at = run.0; + while at < run.1 { + let next = ((at / PIECE + 1) * PIECE).min(run.1); + restore(at, next, run.2); + at = next; + } + } + }; + for (start, h) in held { + match &mut run { + Some((_, end, old, region)) if *end == start && *old == h.old && *region == h.region => *end = h.end, + _ => { + if let Some(r) = run.take() { + flush(r); + } + run = Some((start, h.end, h.old, h.region)); + } + } + } + if let Some(r) = run { + flush(r); + } + ACTIVE.store(false, Ordering::Release); + drop(st); + DONE.notify_all(); +} + +/// An access violation at `at`: if it is held memory, the thread waits +/// until the batch is copied back (the thread that lands flights opens the +/// piece instead), and true says to run the access again. +pub(crate) fn fault(at: usize) -> bool { + if !ACTIVE.load(Ordering::Acquire) { + return false; + } + let mut st = state(); + if !holds_at(&st, at) { + return false; + } + if LANDING.get() { + open_locked(&mut st, at, at + 1); + return true; + } + touched(at, 1); + let began = Instant::now(); + let deadline = began + wait_most(); + LAZY_STATS[3].fetch_add(1, Ordering::Relaxed); + while holds_at(&st, at) { + let now = Instant::now(); + if now >= deadline { + open_locked(&mut st, at, at + 1); + LAZY_STATS[5].fetch_add(1, Ordering::Relaxed); + break; + } + st = DONE.wait_timeout(st, deadline - now).unwrap_or_else(|e| e.into_inner()).0; + } + LAZY_STATS[4].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + true +} + +/// Registers the handler that holds title threads at held memory, once, +/// ahead of the crash reporter's. +fn install() { + use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; + use windows_sys::Win32::System::Diagnostics::Debug::{ + AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, + }; + unsafe extern "system" fn on_fault(info: *mut EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes the exception being dispatched. + let r = unsafe { &*(*info).ExceptionRecord }; + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 { + return EXCEPTION_CONTINUE_SEARCH; + } + if fault(r.ExceptionInformation[1]) { + EXCEPTION_CONTINUE_EXECUTION + } else { + EXCEPTION_CONTINUE_SEARCH + } + } + static ONCE: std::sync::Once = std::sync::Once::new(); + // SAFETY: the handler only touches our own state and protections. + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(on_fault)); + }); +} + +/// For the frame line, since the last one. +pub(crate) fn line(frames: f64) -> String { + let s: Vec<u64> = LAZY_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed)).collect(); + let per = |v: u64| v as f64 / frames.max(1.0); + format!( + "lazy copy-back (VICTORY_LAZY_BACK=0: off) per frame: {:.1} batches held, {:.1} copied back first, {:.1} signals and writes sent before the copy-back, {:.1} title accesses held for {:.1} ms, {:.1} let through after {} ms", + per(s[0]), + per(s[1]), + per(s[2]), + per(s[3]), + per(s[4]) / 1000.0, + per(s[5]), + wait_most().as_millis() + ) +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 99a986053e..79c022243a 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -15,33 +15,66 @@ //! share, [`console`] which console model the title sees. Planned: //! `present` (swap chain). +#[cfg(windows)] +mod ambient; +#[cfg(all(windows, feature = "diagnostics"))] +mod backreads; #[cfg(all(windows, feature = "diagnostics"))] mod capture; +#[cfg(windows)] +mod cardmeter; +#[cfg(all(windows, feature = "diagnostics"))] +mod renderdoc; +#[cfg(all(windows, feature = "diagnostics"))] +mod shot; pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; pub mod descriptor; pub mod device; #[cfg(windows)] +mod drvwatch; +#[cfg(windows)] +mod fpsbox; +#[cfg(windows)] +mod stats; +#[cfg(windows)] +mod spread; +#[cfg(windows)] mod draw; pub mod dxgi; +#[cfg(windows)] +pub mod external; pub mod fence; pub mod frame; +#[cfg_attr(not(windows), allow(dead_code))] +mod heap_pass; +#[cfg(windows)] +pub mod framelog; +#[cfg(windows)] +mod heap_worker; #[cfg(windows)] mod host; #[cfg(windows)] +mod over; +#[cfg(windows)] mod indirect; -#[cfg_attr(not(windows), allow(dead_code))] -mod indirect_plan; +#[cfg(windows)] +mod inplace; pub mod list; pub mod object; pub mod pipeline; #[cfg(windows)] +mod pressure; +mod plaincopy; +#[cfg(windows)] mod primitive; +#[cfg(all(windows, feature = "diagnostics"))] +mod profile; pub mod query; pub mod queue; #[cfg(windows)] -mod rectangles; +mod queue2; pub mod resource; pub mod root; #[cfg(windows)] @@ -49,15 +82,27 @@ mod sampler; #[cfg(windows)] pub mod shader_cache; #[cfg(windows)] +mod lazy; +#[cfg(windows)] +mod memory; +#[cfg(windows)] mod shadow; +#[cfg(windows)] +mod tiles; pub mod signature; #[cfg(windows)] mod texture; -mod timeline; #[cfg(windows)] mod watch; +#[cfg(windows)] +mod texback; #[cfg(windows)] -pub use host::{HdrDisplayInfo, display_hdr_info, on_failure}; +pub use host::on_failure; +#[cfg(windows)] +pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; #[cfg(windows)] -pub use watch::{title_memory_remapped, writing as kernel_will_write}; +pub use watch::{ + title_memory_committed, title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_written, + writing as kernel_will_write, +}; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index c46adfa51b..087c1241ac 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -10,7 +10,7 @@ //! written yet log once with their caller, so a run lists what to do next. #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::{ffi::c_void, mem::offset_of}; +use std::mem::offset_of; use crate::object::{ self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid, @@ -32,7 +32,7 @@ const ALLOCATOR_IIDS: [Iid; 4] = [ /// The list interfaces up to `ID3D12GraphicsCommandList6` (the table has /// all their slots): those whose ids are the same as on PC, the console's -/// own List5 and List6 (Grand Theft Auto VI asks for List6), then the +/// own List5 and List6 (the title asks for List6), then the /// device child's. const LIST_IIDS: [Iid; 10] = [ guid( @@ -106,7 +106,7 @@ struct List { graphics_root_headers: [u32; 128], compute_root_headers: [u32; 128], pipeline_shadow: [u32; 8], - /// Newer titles' lists are larger: Grand Theft Auto VI's state flush + /// Newer titles' lists are larger: the title's state flush /// (title+0x32786) copies a pipeline's 32 bytes to +0x544..+0x564 and /// tests +0x548, so its layout runs past 0x560. Its size is unknown; /// this keeps our fields clear of whatever the title writes there. @@ -115,56 +115,398 @@ struct List { /// [`allocate_upload`], kept until the list is reset; the host list the /// calls record into (decision 0007), and the draw state the title set. uploads: std::sync::Mutex<Vec<Vec<u8>>>, - /// Shared with submissions still to run (queues held back by a wait). #[cfg(windows)] - host: std::sync::Mutex<Option<std::sync::Arc<crate::host::HostList>>>, + host: Option<crate::host::HostList>, #[cfg(windows)] state: std::sync::Mutex<crate::draw::State>, + /// The parts of the recording before `host`, in order, each closed: the + /// list is cut at its waits for memory values ([`cut`]). + #[cfg(windows)] + earlier: Vec<Part>, + /// The waits recorded before the first work of `host`: the queue stands + /// at them before it runs `host`. + #[cfg(windows)] + gate: Vec<ValueWait>, } -const _: () = assert!(offset_of!(List, put) == 0x18); -const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); +/// One part of a title list cut at its waits: the waits the queue stands +/// at, then the host list that runs once they are met. #[cfg(windows)] -impl Drop for List { - fn drop(&mut self) { - let uploads = std::mem::take(self.uploads.get_mut().unwrap_or_else(|e| e.into_inner())); - if let Some(pending) = self - .host - .get_mut() - .unwrap_or_else(|e| e.into_inner()) - .as_ref() - && std::sync::Arc::strong_count(pending) > 1 - { - pending.keep_uploads(uploads); - let dynamic = self - .state - .get_mut() - .unwrap_or_else(|e| e.into_inner()) - .take_dynamic(); - pending.keep_dynamic(dynamic); - } - } +struct Part { + waits: Vec<ValueWait>, + host: crate::host::HostList, } +const _: () = assert!(offset_of!(List, put) == 0x18); +const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); /// Runs `f` with the host list and draw state of a title list, if there /// is a host GPU. #[cfg(windows)] -fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) { +pub(crate) fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) { let Some(list) = host_list(this) else { return }; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); // SAFETY: the title passes one of our lists. let state = unsafe { &(*this.cast::<List>()).state }; - f(&list, &mut state.lock().unwrap_or_else(|e| e.into_inner())); + f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner())); + #[cfg(feature = "diagnostics")] + crate::copystat::recorded(started); + #[cfg(feature = "diagnostics")] + crate::profile::seen(crate::profile::Seen::Record); +} + +/// The submission of `lists` has run: each gives its descriptor tables' +/// slots back ([`crate::draw::State::tables_done`]). A list cut at waits +/// keeps them: its state goes with its last part. +#[cfg(windows)] +pub(crate) fn tables_done(lists: &[This]) { + for &this in lists { + if this.is_null() { + continue; + } + // SAFETY: the title passes our lists. + let list = unsafe { &*this.cast::<List>() }; + if list.earlier.is_empty() { + list.state.lock().unwrap_or_else(|e| e.into_inner()).tables_done(); + } + } } /// The host list behind a title list, if there is a host GPU. #[cfg(windows)] -pub(crate) fn host_list(this: This) -> Option<std::sync::Arc<crate::host::HostList>> { +pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { if this.is_null() { return None; } // SAFETY: the title passes one of our lists. - let host = unsafe { &(*this.cast::<List>()).host }; - host.lock().unwrap_or_else(|e| e.into_inner()).clone() + unsafe { (*this.cast::<List>()).host.as_ref() } +} + +/// The host side of a submitted list, taken from it: a queue that waits +/// for a fence runs it later, and the title may reset the list meanwhile. +/// With it go the upload memory and the dynamic descriptor slots its +/// commands name, kept until it has run. +#[cfg(windows)] +pub(crate) struct Detached { + host: crate::host::HostList, + _uploads: Vec<Vec<u8>>, + _state: crate::draw::State, +} + +#[cfg(windows)] +impl Detached { + /// A closed list of ours, to run among a title's. + pub(crate) fn ours(host: crate::host::HostList) -> Self { + Detached { host, _uploads: Vec::new(), _state: Default::default() } + } + + pub(crate) fn host(&self) -> &crate::host::HostList { + &self.host + } + + /// Gives back this list's dynamic descriptor slots once its submission + /// has run on the card (codec_d, cool_fox f4b48ad). + pub(crate) fn release_tables(&mut self) { + self._state.tables_done(); + } +} + +/// A host list that has run and waits to be used again, and the bytes of +/// upload memory it keeps. +#[cfg(windows)] +struct Idle(crate::host::HostList, u64); + +// SAFETY: D3D12 objects are free-threaded, and an idle list is touched by +// nobody until it is taken out again. +#[cfg(windows)] +unsafe impl Send for Idle {} + +/// Host lists that have run, reset and ready to record: the host side of +/// a list a queue held, or of a part of a list cut at a wait, is taken +/// from the title's list at its submission, and the title's list needs +/// another. Each was made new and thrown away after its run: a hundred a +/// frame in gameplay, each two command allocators and two lists, and for +/// four in ten a budget and an argument buffer (run 61: "104 host lists +/// made 21.2 ms" a frame, and the graphics kernel's time to free them). +#[cfg(windows)] +static IDLE: std::sync::Mutex<(Vec<Idle>, u64)> = std::sync::Mutex::new((Vec::new(), 0)); + +/// The most host lists kept idle, and the most upload memory they may keep +/// between them (a list keeps scratch chunks over a reset only while lists +/// do not share them, `VICTORY_SCRATCH_POOL=0`). +#[cfg(windows)] +// (512 since run 221: with submissions prepared by a thread of ours the +// title has its lists back at once and resets them while the flights of +// the frame before are still in the air, so more than 128 are out at a +// time: 80 host lists were made and as many thrown away every frame, +// 8 ms to make and more to free, on the thread that submits.) +const IDLE_MOST: (usize, u64) = (512, 256 << 20); + +/// Whether host lists that have run are used again (on by default; +/// `VICTORY_LIST_POOL=0`: each is made new and thrown away, as before). +#[cfg(windows)] +fn pools() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIST_POOL").is_none_or(|v| v != "0")) +} + +/// A host list open for recording: one that has run, as a title's list is +/// after its reset, or a new one. +#[cfg(windows)] +pub(crate) fn fresh_list() -> Option<crate::host::HostList> { + let idle = { + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + let taken = idle.0.pop(); + if let Some(Idle(_, bytes)) = &taken { + idle.1 -= bytes; + } + taken + }; + match idle { + Some(Idle(list, _)) => Some(list), + None => crate::host::host().and_then(|h| h.new_list().ok()), + } +} + +/// The host sides of lists whose submission has run (submissions are +/// waited for; `ran` names the ones it ran, by their place in `lists`): +/// what they held is let go, as before, and the host lists are reset and +/// kept for [`fresh_list`]. +#[cfg(windows)] +pub(crate) fn recycle(lists: Vec<Detached>, ran: &[usize]) { + if !pools() { + return; + } + for (i, Detached { host, _uploads, _state }) in lists.into_iter().enumerate() { + // The descriptor slots and the upload memory its commands named. + drop(_state); + drop(_uploads); + if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 { + continue; + } + // As the title's reset does: what the list kept for its commands + // goes, its allocators stay. + host.reset(); + let bytes = host.scratch_kept(); + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 { + idle.0.push(Idle(host, bytes)); + idle.1 += bytes; + } + } +} + +/// A wait for a memory value recorded into list `this`, with waits cut +/// into lists (`crate::queue::cuts`). On the console the queue runs the +/// list up to the wait, stands there until the value is in memory, and +/// runs on; the list's bottom-of-pipe writes before the wait are done by +/// then, and other queues may be waiting for exactly those. So the +/// recording is cut here: the host list so far is closed and kept as a +/// part of its own ([`Part`]), the title's calls record into a new host +/// list from here on, and the wait stands before that one. A submission +/// then gives the queue the parts in order ([`detach_parts`]). +/// +/// A wait before any work (the first call after a reset, or a wait right +/// after another) cuts nothing: it joins the waits before the current +/// host list. +/// shortcut: a bottom-of-pipe write is done when its part has run, not at +/// its place in the part: a queue waiting for it starts later than on the +/// console, never earlier, and nothing can wait for itself that way (a +/// part has no wait after its first work). +#[cfg(windows)] +fn cut(this: This, wait: ValueWait) { + if this.is_null() { + return; + } + // SAFETY: the title passes one of our lists; a list is recorded by one + // thread at a time and is not submitted while it records. + let list = unsafe { &mut *this.cast_mut().cast::<List>() }; + let Some(current) = list.host.as_ref() else { + return; + }; + if current.untouched() { + list.gate.push(wait); + return; + } + let Some(fresh) = fresh_list() else { + // shortcut: without a new host list the wait stands before the part + // it was recorded in. + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("no host list for the part after a wait: the wait moves to the part's start")); + list.gate.push(wait); + return; + }; + current.close(); + static CUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if CUTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + tracing::info!(parts = list.earlier.len() + 2, "a list is cut at a wait for a memory value"); + } + if let Some(done) = list.host.replace(fresh) { + let waits = std::mem::replace(&mut list.gate, vec![wait]); + list.earlier.push(Part { waits, host: done }); + } + // What the title set so far, on the new host list. + if let Some(host) = list.host.as_ref() { + list.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .replay(host); + } +} + +/// Whether list `this` recorded a wait for a memory value (with waits cut +/// into lists). +#[cfg(windows)] +pub(crate) fn cut_list(this: This) -> bool { + if this.is_null() { + return false; + } + // SAFETY: one of our lists, closed and submitted: nothing records + // into it. + let list = unsafe { &*this.cast::<List>() }; + !list.earlier.is_empty() || !list.gate.is_empty() +} + +/// What a queue is given for submitted lists that were cut at their waits: +/// the waits it stands at, the host lists it runs once they are met, and +/// the order those run in. +#[cfg(windows)] +pub(crate) type Parts = Vec<(Vec<ValueWait>, Vec<Detached>, Vec<usize>)>; + +/// Takes the host sides of the submitted `lists`, part by part ([`cut`]), +/// and leaves each list a new, closed host list for its next reset, as +/// [`detach`] does. What comes back is in the order the queue runs it: a +/// new entry starts at every part that has waits; host lists without +/// waits join the entry before them. The list's upload memory and draw +/// state (its dynamic descriptor slots) go with its last part, which runs +/// last. +/// shortcut: a list the submission names a second time runs again only if +/// it has one part and that part is in the entry being filled; otherwise +/// the second naming is dropped (logged once). +#[cfg(windows)] +pub(crate) fn detach_parts(lists: &[This]) -> Parts { + let mut parts: Parts = vec![(Vec::new(), Vec::new(), Vec::new())]; + // The lists taken: where its one host list is (entry, place), or none + // for a list of several parts. + let mut seen: Vec<(This, Option<(usize, usize)>)> = Vec::new(); + for &this in lists { + if this.is_null() { + continue; + } + if let Some(&(_, at)) = seen.iter().find(|(t, _)| *t == this) { + match at { + Some((entry, place)) if entry + 1 == parts.len() => parts[entry].2.push(place), + _ => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!("a list named twice by a submission that waits for memory values runs once") + }); + } + } + continue; + } + let Some(fresh) = fresh_list() else { + continue; + }; + // A new host list is open; the title's next call on its list is a + // reset, which wants it closed. + fresh.close(); + // SAFETY: one of our lists, closed and submitted: nothing records + // into it until the title resets it. + let list = unsafe { &mut *this.cast_mut().cast::<List>() }; + let Some(host) = list.host.replace(fresh) else { + continue; + }; + let earlier = std::mem::take(&mut list.earlier); + let gate = std::mem::take(&mut list.gate); + let uploads = std::mem::take(&mut *list.uploads.lock().unwrap_or_else(|e| e.into_inner())); + let state = std::mem::take(&mut *list.state.lock().unwrap_or_else(|e| e.into_inner())); + let single = earlier.is_empty() && gate.is_empty(); + let mut pieces: Vec<(Vec<ValueWait>, Detached)> = earlier + .into_iter() + .map(|part| { + ( + part.waits, + Detached { + host: part.host, + _uploads: Vec::new(), + _state: Default::default(), + }, + ) + }) + .collect(); + pieces.push(( + gate, + Detached { + host, + _uploads: uploads, + _state: state, + }, + )); + let mut last = None; + for (waits, detached) in pieces { + if !waits.is_empty() { + parts.push((waits, Vec::new(), Vec::new())); + } + let entry = parts.len() - 1; + let (_, taken, order) = &mut parts[entry]; + let place = taken.len(); + order.push(place); + taken.push(detached); + last = Some((entry, place)); + } + seen.push((this, if single { last } else { None })); + } + // (The first entry is empty if the first list begins with a wait.) + parts.retain(|(_, taken, _)| !taken.is_empty()); + parts +} + +/// Takes the host sides of submitted lists (each once, however often the +/// submission names it) and leaves each list a new, closed host list for +/// its next reset: what was taken, and which of them run in what order. +#[cfg(windows)] +pub(crate) fn detach(lists: &[This]) -> (Vec<Detached>, Vec<usize>) { + let mut taken: Vec<(This, Detached)> = Vec::new(); + let mut order = Vec::new(); + for &this in lists { + if this.is_null() { + continue; + } + if let Some(i) = taken.iter().position(|(t, _)| *t == this) { + order.push(i); + continue; + } + let Some(fresh) = fresh_list() else { + continue; + }; + // A new host list is open; the title's next call on its list is a + // reset, which wants it closed. + fresh.close(); + let list = this.cast_mut().cast::<List>(); + // SAFETY: one of our lists, closed and submitted: nothing records + // into it until the title resets it. + let (host, uploads, state) = unsafe { + let Some(host) = (*list).host.replace(fresh) else { + continue; + }; + let uploads = + std::mem::take(&mut *(*list).uploads.lock().unwrap_or_else(|e| e.into_inner())); + let state = + std::mem::take(&mut *(*list).state.lock().unwrap_or_else(|e| e.into_inner())); + (host, uploads, state) + }; + order.push(taken.len()); + taken.push(( + this, + Detached { + host, + _uploads: uploads, + _state: state, + }, + )); + } + (taken.into_iter().map(|(_, d)| d).collect(), order) } pub(crate) extern "system" fn create_allocator( @@ -220,6 +562,8 @@ pub(crate) extern "system" fn create_list_x( new_list(desc.kind, allocator, pipeline, iid, out) } +/// `pipeline` is the list's initial pipeline (null: none), bound until the +/// title sets another, as after a reset. fn new_list( kind: u32, allocator: This, @@ -246,19 +590,23 @@ fn new_list( newer: [0; 256], uploads: Default::default(), #[cfg(windows)] - host: std::sync::Mutex::new(crate::host::host().and_then(|h| match h.acquire_list() { - Ok(list) => Some(std::sync::Arc::new(list)), + host: crate::host::host().and_then(|h| match h.new_list() { + Ok(list) => Some(list), Err(e) => { tracing::warn!(error = %e, "no host command list"); None } - })), + }), #[cfg(windows)] state: { let mut state = crate::draw::State::default(); state.set_pipeline(pipeline); std::sync::Mutex::new(state) }, + #[cfg(windows)] + earlier: Vec::new(), + #[cfg(windows)] + gate: Vec::new(), }); #[cfg(not(windows))] let _ = pipeline; @@ -298,43 +646,28 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT if allocator.is_null() { return E_INVALIDARG; } + // A wait recorded and never submitted goes with the recording. + VALUE_WAITS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|&(list, _)| list != this as usize); + // Every submission of the list has run (submissions are waited for). // SAFETY: the title passes one of our lists. - let list = unsafe { &*this.cast::<List>() }; - let uploads = std::mem::take(&mut *list.uploads.lock().unwrap_or_else(|e| e.into_inner())); - // A submission of the list still to run (its queue waits for a fence) - // keeps the host list, its upload memory and its dynamic descriptor - // slots; recording goes on in a pooled or new list, open already. + let uploads = unsafe { &(*this.cast::<List>()).uploads }; + uploads.lock().unwrap_or_else(|e| e.into_inner()).clear(); + // The parts of a recording that was cut and never submitted go with it + // (a submission takes the parts it runs). #[cfg(windows)] - let (fresh, keep_pending) = { - let mut host = list.host.lock().unwrap_or_else(|e| e.into_inner()); - match host.as_ref() { - Some(pending) if std::sync::Arc::strong_count(pending) > 1 => { - pending.keep_uploads(uploads); - let dynamic = list - .state - .lock() - .unwrap_or_else(|e| e.into_inner()) - .take_dynamic(); - pending.keep_dynamic(dynamic); - match crate::host::host().map(|h| h.acquire_list()) { - Some(Ok(new)) => { - *host = Some(std::sync::Arc::new(new)); - (true, false) - } - _ => { - tracing::warn!("no new host list: a list to run is reset"); - (false, true) - } - } - } - _ => (false, false), - } - }; + { + // SAFETY: the title passes one of our lists, and neither records + // into it nor submits it during its reset. + let list = unsafe { &mut *this.cast_mut().cast::<List>() }; + list.earlier.clear(); + list.gate.clear(); + } #[cfg(windows)] with_state(this, |host, state| { - if !fresh && !keep_pending { - host.reset(); - } + host.reset(); state.reset(pipeline); }); #[cfg(not(windows))] @@ -397,7 +730,13 @@ fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option<Barrier> { first: if b.first.is_null() { b.first } else { - host(b.first)? + // A depth texture's unordered access is its colour twin's + // (the host gives the depth texture none): the barrier is + // on the texture shaders write. + match crate::resource::twin_resource(b.first) { + Some(twin) => twin.as_raw().cast_const().cast(), + None => host(b.first)?, + } }, ..*b }), @@ -415,6 +754,34 @@ const UAV_BARRIER: Barrier = Barrier { last: 0, }; +/// Barrier trimming (`VICTORY_TRIM_BARRIERS=0`: every barrier as before): +/// a buffer transition from a state nothing writes in to another such +/// state (vertex or index data, constants, shader reads, indirect +/// arguments, copy source) no longer waits for every shader write on the +/// card, as there is no write to wait for; a wait for every shader write +/// drops the waits on single resources beside it; a barrier given twice +/// in one call is made once. +#[cfg(windows)] +fn trim_barriers() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TRIM_BARRIERS").is_none_or(|v| v != "0")) +} + +/// Barriers and full waits [`trim_barriers`] left out, since the start. +#[cfg(windows)] +pub(crate) static TRIMMED_BARRIERS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether `b` is a transition between two states nothing writes in +/// (neither common nor any write state). +#[cfg(windows)] +fn read_to_read(b: &Barrier) -> bool { + // Render target, unordered access, depth write, stream out, copy + // destination, resolve destination, and video and ray tracing ones. + const WRITES: u32 = 0x4 | 0x8 | 0x10 | 0x100 | 0x400 | 0x1000 | 0x00ff_0000; + let (before, after) = ((b.second >> 32) as u32, b.last as u32); + b.kind == 0 && before != 0 && after != 0 && (before | after) & WRITES == 0 && (before | after) & 0xff00_0000 == 0 +} + /// Returns the console's barrier "actions" (none). extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 { #[cfg(windows)] @@ -425,14 +792,53 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) }; let mut host: Vec<Barrier> = barriers .iter() - .filter_map(|b| host_barrier(&list, b)) + .filter_map(|b| host_barrier(list, b)) .collect(); // Buffers have host copies, not resources the barrier can name: // a barrier on one waits for every shader write before it. if barriers.iter().any(|b| { - b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some() + b.kind != 1 + && !b.first.is_null() + && !(trim_barriers() && read_to_read(b)) + && crate::resource::buffer_bytes(b.first).is_some() }) { host.push(UAV_BARRIER); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1); + } else if trim_barriers() + && barriers.iter().any(|b| b.kind == 0 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some()) + { + TRIMMED_BARRIERS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + if trim_barriers() { + // One wait for every shader write covers the waits on single + // resources beside it, and a barrier twice is one barrier. + let before = host.len(); + if host.iter().any(|b| b.kind == 2 && b.first.is_null()) { + let mut global = false; + host.retain(|b| { + if b.kind != 2 { + return true; + } + if b.first.is_null() && !global { + global = true; + return true; + } + false + }); + } + let mut seen: Vec<(u32, usize, u64, u64)> = Vec::with_capacity(host.len()); + host.retain(|b| { + let key = (b.kind, b.first as usize, b.second, b.last); + if seen.contains(&key) { + return false; + } + seen.push(key); + true + }); + if host.len() < before { + TRIMMED_BARRIERS.fetch_add((before - host.len()) as u64, std::sync::atomic::Ordering::Relaxed); + } } if !host.is_empty() { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; @@ -452,6 +858,135 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> 0 } +/// Stands in for the console upscaler's dispatch on title list `this`: +/// `output` gets the stretched top-left `render` texels of `colour` +/// ([`crate::over`]). False if nothing was recorded (no host GPU, textures +/// we do not hold, an output shaders cannot write). +/// +/// The real dispatch leaves its own state in the list, so the title sets +/// its own again afterwards; ours is replayed all the same. +#[cfg(windows)] +pub fn upscale_stretch( + this: *const std::ffi::c_void, + colour: *const std::ffi::c_void, + output: *const std::ffi::c_void, + render: [u32; 2], +) -> bool { + const SHADER_READ: u32 = 0x40; + const UNORDERED: u32 = 0x8; + let (this, colour, output): (This, This, This) = (this.cast(), colour.cast(), output.cast()); + if this.is_null() || colour.is_null() || output.is_null() { + return false; + } + let mut done = false; + with_state(this, |list, state| { + let (Some(to), Some(from), Some(host)) = ( + crate::resource::host_resource(output), + crate::resource::host_resource(colour), + crate::host::host(), + ) else { + return; + }; + ensure_state(list, colour, SHADER_READ); + ensure_state(list, output, UNORDERED); + done = crate::over::record_stretch(&host.device, &list.list, to, from, render); + if done { + crate::texture::host_written(output); + } + state.replay(list); + }); + done +} + +/// What an upscale dispatch says besides its textures, for +/// [`upscale_temporal`]. +#[cfg(windows)] +#[derive(Clone, Copy, Debug, Default)] +pub struct UpscaleFrame { + /// The rendered top-left part of the colour input. + pub render: [u32; 2], + /// The projection's jitter this frame, in rendered texels. + pub jitter: [f32; 2], + /// What the motion input is multiplied by to be in rendered texels. + pub motion_scale: [f32; 2], + /// The title starts its history again (a camera cut). + pub reset: bool, + /// The sharpening the title asks for, if it asks. + pub sharpness: Option<f32>, + /// The exposure the colour input was rendered with. + pub pre_exposure: f32, +} + +/// Stands in for the console upscaler's dispatch on title list `this` as +/// that upscaler does, by accumulating frames ([`crate::over::temporal`]): +/// `output` gets this frame's `colour` with the jitter taken off, blended +/// with the history moved by `motion`. Stretches instead when the resolve +/// is off (`VICTORY_UPSCALE_TEMPORAL=0`) or cannot be recorded. False if +/// nothing was recorded. +#[cfg(windows)] +pub fn upscale_temporal( + this: *const std::ffi::c_void, + colour: *const std::ffi::c_void, + motion: *const std::ffi::c_void, + output: *const std::ffi::c_void, + frame: UpscaleFrame, +) -> bool { + const SHADER_READ: u32 = 0x40; + const UNORDERED: u32 = 0x8; + if !crate::over::temporal::enabled() { + return upscale_stretch(this, colour, output, frame.render); + } + let (this, colour, motion, output): (This, This, This, This) = + (this.cast(), colour.cast(), motion.cast(), output.cast()); + if this.is_null() || colour.is_null() || output.is_null() { + return false; + } + let mut done = false; + with_state(this, |list, state| { + let (Some(to), Some(from), Some(host)) = ( + crate::resource::host_resource(output), + crate::resource::host_resource(colour), + crate::host::host(), + ) else { + return; + }; + // A motion input that is the colour or the output is not one. + let moved = if motion.is_null() || motion == colour || motion == output { + None + } else { + crate::resource::host_resource(motion) + }; + ensure_state(list, colour, SHADER_READ); + if moved.is_some() { + ensure_state(list, motion, SHADER_READ); + } + ensure_state(list, output, UNORDERED); + done = crate::over::temporal::record( + &host.device, + list, + to, + from, + moved, + crate::over::temporal::Frame { + render: frame.render, + jitter: frame.jitter, + motion_scale: frame.motion_scale, + reset: frame.reset, + sharpness: frame.sharpness, + pre_exposure: frame.pre_exposure, + }, + ); + if !done { + done = crate::over::record_stretch(&host.device, &list.list, to, from, frame.render); + } + if done { + crate::texture::host_written(output); + } + state.replay(list); + }); + done +} + /// Moves a title texture's host copy to `state` in the list, if needed. #[cfg(windows)] pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { @@ -482,7 +1017,113 @@ fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> { Some(unsafe { data.add(offset as usize) }) } -/// Buffer to buffer: both are host memory, copied at submission. +/// What a title buffer copy does (pablogonz12/Scarlight #86). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CopyPlan { + /// One `CopyBufferRegion` on the host GPU: both sides have a host copy of + /// their range, so the GPU moves the bytes between them and title memory + /// gets them after the submission (like a shader write) instead of a + /// kernel read and write of title memory at submission time. + Gpu, + /// On the CPU, as always: a side without a host copy, or + /// `VICTORY_GPU_COPIES=0`. + Title, +} + +/// [`CopyPlan`] for a copy whose sides do or do not have host copies: the +/// whole decision, so it can be tested without a device. +pub(crate) fn copy_plan(enabled: bool, src_hosted: bool, dst_hosted: bool) -> CopyPlan { + if enabled && src_hosted && dst_hosted { + CopyPlan::Gpu + } else { + CopyPlan::Title + } +} + +/// Records a GPU copy of `len` bytes at `src_address` into `dst_address` +/// through the buffers' host copies, in this list where the copy was +/// recorded: `false` (nothing recorded) unless both ranges are inside their +/// host copies (and do not overlap, when it is one copy). +/// +/// The source's host copy is brought up to date by the submission-time steps, +/// before the list runs (so after every CPU-side step recorded before this +/// one), and the destination is marked GPU-written there: nothing refreshes +/// title memory over it, and once the submission has run it is copied back +/// like a shader write. Buffers are in the `COMMON` state, which a buffer copy +/// promotes to and from without a barrier; a barrier on every unordered +/// access before and after keeps the copy in order with the shaders around +/// it (Try 4.7). +/// +/// With flights in the air this is also what saves the wait: a copy on the +/// CPU that reads or writes title memory a flight's shaders may write had +/// to wait for every flight to land first (157 ms a frame in the +/// 2026-11-25 report, all of it "title memory read by a buffer copy"). On +/// the card the copy simply runs behind them, in the queue's order. +#[cfg(windows)] +pub(crate) fn record_gpu_copy( + list: &crate::host::HostList, + dst: &std::sync::Arc<crate::shadow::Shadow>, + dst_address: usize, + src: &std::sync::Arc<crate::shadow::Shadow>, + src_address: usize, + len: usize, +) -> bool { + use windows::Win32::Graphics::Direct3D12::{D3D12_RESOURCE_BARRIER, D3D12_RESOURCE_BARRIER_TYPE_UAV}; + // A copy within one buffer whose two ranges overlap is not something + // `CopyBufferRegion` does: on the CPU, as before. + if std::sync::Arc::ptr_eq(dst, src) && dst_address < src_address + len && src_address < dst_address + len { + return false; + } + let (Some((dst_buffer, dst_offset)), Some((src_buffer, src_offset))) = + (dst.gpu_range(dst_address, len), src.gpu_range(src_address, len)) + else { + return false; + }; + // The source first: the copy reads the host copy's bytes, and the refresh + // is what makes them the title's (the pages a CPU copy would read). + src.refresh(list, src_address as u64, len as u64); + // Then the destination, brought up to date too (Try 4.7): the copy-back + // keeps a byte the title changed since the copy last took it, so the + // copy's bytes must start from the title's or a copied byte is lost + // there. Then its bytes before are kept for the copy-back, and a refresh + // in the meantime leaves title memory alone there. + dst.refresh(list, dst_address as u64, len as u64); + dst.gpu_writes(list, dst_address as u64, len as u64); + let all_writes = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + ..Default::default() + }; + // SAFETY: an open list and live buffers, both ranges inside their + // resources (checked by `gpu_range`); the barriers name no resource. + unsafe { + list.list.ResourceBarrier(std::slice::from_ref(&all_writes)); + list.list.CopyBufferRegion(&dst_buffer, dst_offset, &src_buffer, src_offset, len as u64); + list.list.ResourceBarrier(std::slice::from_ref(&all_writes)); + } + crate::host::gpu_copied(len); + true +} + +/// A title buffer copy of `len` bytes at `from` into `to`: on the host GPU +/// when both ranges have a host copy, else on the CPU as always. +#[cfg(windows)] +fn buffer_copy(list: &crate::host::HostList, to: *mut u8, from: *const u8, len: usize) { + let on = crate::host::gpu_copies(); + if len > 0 && on { + let src = crate::shadow::peek(from as u64, len as u64); + let dst = crate::shadow::peek(to as u64, len as u64); + if copy_plan(on, src.is_some(), dst.is_some()) == CopyPlan::Gpu + && let (Some(s), Some(d)) = (&src, &dst) + && record_gpu_copy(list, d, to as usize, s, from as usize, len) + { + return; + } + } + list.defer_copy(to, from, len); +} + +/// Buffer to buffer: both are host memory, copied at submission, or on the +/// host GPU through their host copies when both have one. extern "system" fn copy_buffer_region( this: This, dst: This, @@ -495,44 +1136,33 @@ extern "system" fn copy_buffer_region( if let Some(list) = host_list(this) && let Some(to) = buffer_range(dst, dst_offset, len) && let Some(from) = buffer_range(src, src_offset, len) + && let Ok(len) = usize::try_from(len) { - list.defer_copy(to, from, len as usize); + buffer_copy(list, to, from, len); } #[cfg(not(windows))] let _ = (this, dst, dst_offset, src, src_offset, len); } -/// Whether host formats `a` and `b` can meet in one copy: the same family. -/// A render target or UAV texture whose console format PC forbids is made -/// in another format (`resource::target_format`); a copy between it and a -/// texture of the title's own format would be refused by the runtime, so it -/// is skipped. -#[cfg(any(windows, test))] -fn same_family(a: u32, b: u32) -> bool { - let ok = a == b || crate::resource::family(a) == crate::resource::family(b); - if !ok { +/// Whether one of two resources is a target in a stand-in format and the +/// other is not ([`crate::resource::target_format`]): their texels differ +/// in size, so the host cannot copy between them (logged once). +#[cfg(windows)] +fn unlike(dst: This, src: This) -> bool { + let unlike = crate::resource::stands_in(dst) != crate::resource::stands_in(src); + if unlike { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { - tracing::warn!( - a, - b, - "texture copy between formats of different families skipped (a substituted target)", - ); + tracing::warn!(?dst, ?src, "copy between a stand-in target and title-format texels skipped") }); } - ok + unlike } -/// [`same_family`] for two host resources. +/// Copies left out because both sides were one host texture +/// ([`copy_resource`], [`copy_texture_region`]), since the start. #[cfg(windows)] -fn copyable( - to: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, - from: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, -) -> bool { - // SAFETY: live resources. - let (a, b) = unsafe { (to.GetDesc().Format.0, from.GetDesc().Format.0) }; - same_family(a as u32, b as u32) -} +pub(crate) static SELF_COPIES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); extern "system" fn copy_resource(this: This, dst: This, src: This) { #[cfg(windows)] @@ -540,21 +1170,52 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { let Some(list) = host_list(this) else { return; }; + // A copy on the card may write a buffer: no indirect draw after it joins a window before it. + crate::indirect::end_window(list); if let (Some(to), Some(from)) = ( crate::resource::host_resource(dst), crate::resource::host_resource(src), ) { - if !copyable(to, from) { + if unlike(dst, src) { return; } - // A texture the title fills through memory has its contents in - // the staging copy until an upload records them. + // Two title textures over the same memory have one host + // texture between them: the copy would be of that texture onto + // itself, which the host does not allow, and it would change + // nothing. It was recorded all the same, with the texture left + // in the source state as the copy's destination (run 205's + // debug layer: "CopyResource with its destination in the + // COPY_SOURCE state", 37 times, a 2560x1440 depth texture). + // Only the two state changes and the copy are left out: what + // is noted of the textures stays as it was. After + // triippywhale 6e502b3b. + let same = windows::core::Interface::as_raw(to) == windows::core::Interface::as_raw(from); + // A source the title fills itself is uploaded first (upstream + // PR #671): a copy read whatever the host texture held. if crate::texture::title_written(from) { - crate::texture::upload(&list, src, from); + crate::texture::upload(list, src, from); } - ensure_state(&list, dst, COPY_DEST); - ensure_state(&list, src, COPY_SOURCE); + // Depth textures shaders also write: what they wrote, first. + list.twin_use(dst, false, true); + list.twin_use(src, false, false); + // A destination made level by level gets its levels' memory + // ahead of this list (`crate::tiles`). + crate::texture::card_writes(list, dst, to, None); crate::texture::host_written(dst); + if same { + SELF_COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + ?dst, + ?src, + "a copy between two title textures that share one host texture is left out: the first one" + ); + }); + return; + } + ensure_state(list, dst, COPY_DEST); + ensure_state(list, src, COPY_SOURCE); #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); // SAFETY: an open list and live textures. @@ -563,7 +1224,7 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::buffer_bytes(dst), crate::resource::buffer_bytes(src), ) { - list.defer_copy(to, from, a.min(b) as usize); + buffer_copy(list, to, from, a.min(b) as usize); } } #[cfg(not(windows))] @@ -584,9 +1245,9 @@ pub(crate) struct CopyLocation { footprint: crate::resource::PlacedFootprint, } -/// Texture to texture on the GPU, buffer to texture through an upload -/// buffer filled at submission, and texture to buffer through a readback -/// buffer copied into title memory once the submission completes. +/// Texture to texture on the GPU; buffer to texture through an upload +/// buffer filled at submission. Texture to buffer (read back) is not done +/// yet. extern "system" fn copy_texture_region( this: This, dst: *const CopyLocation, @@ -609,123 +1270,49 @@ extern "system" fn copy_texture_region( else { return; }; - const _: () = - assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>()); - let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>()); - if dst.kind == FOOTPRINT { - if src.kind == FOOTPRINT { - return; - } - let (Some(host), Some(from_tex)) = ( - crate::host::host(), - crate::resource::host_resource(src.resource), - ) else { - return; - }; - let Some((lines, row_bytes, total)) = dst.footprint.layout() else { - return; - }; - let host_format = crate::resource::pc_format(dst.footprint.format); - if crate::resource::element(host_format) - != crate::resource::element(dst.footprint.format) - { - // Console formats such as 118..=120 (3-byte D16S8) map to - // 4-byte PC substitutes (45..=47): raw readback would mis-size - // the staging buffer and write the wrong texel layout. - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!( - format = dst.footprint.format, - host_format, - "texture-to-buffer readback skipped: host format has a different texel size", - ); + // A copy on the card (textures, or texels read back into a buffer of ours): no indirect draw after it joins + // a window before it (conservative: none of these writes an argument buffer). + crate::indirect::end_window(list); + let Some(to) = crate::resource::host_resource(dst.resource) else { + // Texture to buffer: a read back. The list copies the texels + // into a host buffer of ours; once it has run they go to the + // title's buffer (`HostList::defer_read_back`). + // The title reads two tiny float targets back every frame (5x1 + // and 1x1 RGBA32F, 80 and 16 bytes: run 90), and read a buffer + // nobody wrote. `VICTORY_READ_BACK=0` leaves them unmade, as + // before. + static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let made = read_back(list, dst, x, y, z, src, source_box); + if n <= 16 || n.is_multiple_of(4096) || made.is_err() { + static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 { + return; + } + let source = crate::resource::host_resource(src.resource).map(|r| { + // SAFETY: a live resource. + let d = unsafe { r.GetDesc() }; + format!("{}x{} f{} mips {}", d.Width, d.Height, d.Format.0, d.MipLevels) }); - return; - } - // SAFETY: a live texture. - let from_format = unsafe { from_tex.GetDesc() }.Format.0 as u32; - if !same_family(from_format, host_format) { - return; - } - if total == 0 || lines == 0 || row_bytes == 0 { - return; - } - let dst_pitch = u64::from(dst.footprint.row_pitch); - if lines > 1 && dst_pitch < row_bytes { - return; + tracing::info!( + copies = n, + made = ?made, + source = ?source, + source_kind = src.kind, + destination_kind = dst.kind, + destination_offset = dst.footprint.offset, + destination_bytes = ?dst.footprint.bytes(), + "a texture to buffer copy (a read back)" + ); } - let Some(target) = buffer_range(dst.resource, dst.footprint.offset, total) else { - return; - }; - let Ok(row_bytes_u32) = u32::try_from(row_bytes) else { - return; - }; - // D3D12 requires placed footprints' row pitch to be 256-byte aligned. - let host_pitch = dst - .footprint - .row_pitch - .max(row_bytes_u32) - .next_multiple_of(256); - let Some(staging_bytes) = u64::from(host_pitch) - .checked_mul(lines - 1) - .and_then(|n| n.checked_add(row_bytes)) - else { - return; - }; - let Some((buffer, staging)) = list.readback(host, staging_bytes) else { - return; - }; - crate::texture::upload(&list, src.resource, from_tex); - ensure_state(&list, src.resource, COPY_SOURCE); - let mut to_location = dst; - to_location.resource = buffer.as_raw().cast_const().cast(); - to_location.footprint.offset = 0; - to_location.footprint.format = host_format; - to_location.footprint.row_pitch = host_pitch; - let mut from_location = src; - from_location.resource = from_tex.as_raw().cast_const().cast(); - #[cfg(feature = "diagnostics")] - list.note_op(|| { - // SAFETY: a live texture; the box is the title's or null. - let (d, b) = unsafe { (from_tex.GetDesc(), host_box.map(|b| *b)) }; - format!( - "readback to {:?} footprint {:?} at {x},{y},{z} from {:?} {}x{} f{} sub {} box {b:?}", - dst.resource, - dst.footprint, - src.resource, - d.Width, - d.Height, - d.Format.0, - src.kind, - ) - }); - // SAFETY: an open list; both locations in the host's layout, naming - // live resources; the box is the title's (same layout). - unsafe { - list.list.CopyTextureRegion( - (&raw const to_location).cast(), - x, - y, - z, - (&raw const from_location).cast(), - host_box, - ) - }; - list.defer_readback( - target, - staging, - dst_pitch as usize, - host_pitch as usize, - lines as usize, - row_bytes as usize, - total as usize, - ); - return; - } - let Some(to) = crate::resource::host_resource(dst.resource) else { return; }; + if unlike(dst.resource, src.resource) { + return; + } let mut from = src; + // Both sides are the same subresource of one host texture (set below). + let mut same = false; let _upload; // keeps the source alive while this call records it #[cfg(feature = "diagnostics")] let mut read = None; @@ -754,19 +1341,40 @@ extern "system" fn copy_texture_region( let Some(texture) = crate::resource::host_resource(src.resource) else { return; }; - if !copyable(to, texture) { - return; - } + // The same subresource of one host texture on both sides (two + // title textures over one memory): not a copy the host allows. + // The states and the copy are left out below; the rest is + // noted as before. + same = texture.as_raw() == to.as_raw() + && src.kind != FOOTPRINT + && dst.kind != FOOTPRINT + && src.footprint.offset as u32 == dst.footprint.offset as u32; + list.twin_use(src.resource, false, false); if crate::texture::title_written(texture) { - crate::texture::upload(&list, src.resource, texture); + crate::texture::upload(list, src.resource, texture); + } + if !same { + ensure_state(list, src.resource, COPY_SOURCE); } - ensure_state(&list, src.resource, COPY_SOURCE); from.resource = texture.as_raw().cast_const().cast(); } - ensure_state(&list, dst.resource, COPY_DEST); + // A depth texture shaders also write: what they wrote, first (the + // source above too). + list.twin_use(dst.resource, false, true); + // A destination made level by level gets the level's memory ahead + // of this list (`crate::tiles`): the title's bake copies each level + // of its result into a block-compressed texture of that kind, and + // a copy into a level without memory is dropped. + crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32)); crate::texture::host_written(dst.resource); - let mut to_location = dst; + if same { + SELF_COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return; + } + ensure_state(list, dst.resource, COPY_DEST); + let mut to_location = dst; to_location.resource = to.as_raw().cast_const().cast(); + let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>()); #[cfg(feature = "diagnostics")] { let text = || { @@ -789,6 +1397,8 @@ extern "system" fn copy_texture_region( None => list.note_op(text), } } + const _: () = + assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>()); // SAFETY: an open list; both locations in the host's layout, naming // live resources; the box is the title's (same layout). unsafe { @@ -806,6 +1416,70 @@ extern "system" fn copy_texture_region( let _ = (this, dst, x, y, z, src, source_box); } +/// Records a texture to buffer copy (a read back) of [`copy_texture_region`] +/// into `list`, or says why not. +#[cfg(windows)] +#[allow(clippy::too_many_arguments)] // the method's own arguments +fn read_back( + list: &crate::host::HostList, + dst: CopyLocation, + x: u32, + y: u32, + z: u32, + src: CopyLocation, + source_box: *const [u32; 6], +) -> Result<(), &'static str> { + use windows::Win32::Graphics::Direct3D12::D3D12_BOX; + use windows::core::Interface; + const FOOTPRINT: u32 = 1; + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_READ_BACK").is_none_or(|v| v != "0")) { + return Err("switched off"); + } + if dst.kind != FOOTPRINT || src.kind == FOOTPRINT { + return Err("not a texture subresource into a placed footprint"); + } + if (x, y, z) != (0, 0, 0) { + return Err("a destination corner other than the footprint's"); + } + let host = crate::host::host().ok_or("no host")?; + let (footprint, [size, row, rows, pitch]) = dst.footprint.host_rows().ok_or("an unknown format")?; + // The title's buffer holds every row at its own pitch. + let bytes = pitch * (rows - 1) + row; + let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?; + let texture = crate::resource::host_resource(src.resource).ok_or("no host texture")?; + let buffer = host.read_back_buffer(size).ok_or("no read-back buffer")?; + // As a texture source of any copy: what shaders wrote to a depth twin + // and what the title wrote itself first, then the state. + list.twin_use(src.resource, false, false); + if crate::texture::title_written(texture) { + crate::texture::upload(list, src.resource, texture); + } + ensure_state(list, src.resource, COPY_SOURCE); + let mut from = src; + from.resource = texture.as_raw().cast_const().cast(); + let mut to = dst; + to.resource = buffer.as_raw().cast_const().cast(); + to.footprint = footprint; + let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>()); + #[cfg(feature = "diagnostics")] + list.note_op(|| { + format!( + "read back of {:?} sub {} into buffer {:?}+{:#x}: {rows} rows of {row} bytes", + src.resource, src.footprint.offset as u32, dst.resource, dst.footprint.offset + ) + }); + // SAFETY: an open list; both locations in the host's layout (asserted + // in `copy_texture_region`), naming a live texture and our buffer, which + // the list keeps until it is reset; the box is the title's. + unsafe { + list.list + .CopyTextureRegion((&raw const to).cast(), 0, 0, 0, (&raw const from).cast(), host_box) + }; + list.defer_read_back(buffer, data, [row as usize, rows as usize, pitch as usize]); + Ok(()) +} + #[allow(clippy::too_many_arguments)] // the method's own arguments extern "system" fn copy_texture_region_x( this: This, @@ -837,28 +1511,30 @@ extern "system" fn resolve( { use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D12::{ - D3D12_RESOLVE_MODE_AVERAGE, D3D12_RESOURCE_DESC, ID3D12GraphicsCommandList1, + D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1, }; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; use windows::core::Interface; const RESOLVE_DEST: u32 = 0x1000; const RESOLVE_SOURCE: u32 = 0x2000; - ensure_state(&list, dst, RESOLVE_DEST); - ensure_state(&list, src, RESOLVE_SOURCE); + if unlike(dst, src) { + return; + } + // Depth textures shaders also write: what they wrote, first. + list.twin_use(dst, false, true); + list.twin_use(src, false, false); + // As for a copy (`crate::tiles`). + crate::texture::card_writes(list, dst, to, Some(dst_sub)); + ensure_state(list, dst, RESOLVE_DEST); + ensure_state(list, src, RESOLVE_SOURCE); crate::texture::host_written(dst); #[cfg(feature = "diagnostics")] list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}")); - let extent = |d: D3D12_RESOURCE_DESC, subresource: u32| { - // Mips are the low-order component of an array or plane subresource index. - let mip = subresource % u32::from(d.MipLevels); - ((d.Width >> mip).max(1), (d.Height >> mip).max(1)) - }; // SAFETY: an open list and live textures; the region is inside both. unsafe { - let (dst_width, dst_height) = extent(to.GetDesc(), dst_sub); - let (src_width, src_height) = extent(from.GetDesc(), src_sub); - let format = DXGI_FORMAT(format as i32); - if (dst_width, dst_height) == (src_width, src_height) { + let (a, b) = (to.GetDesc(), from.GetDesc()); + let format = if crate::resource::stands_in(dst) { a.Format } else { DXGI_FORMAT(format as i32) }; + if (a.Width, a.Height) == (b.Width, b.Height) { list.list .ResolveSubresource(to, dst_sub, from, src_sub, format); } else if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() { @@ -866,8 +1542,8 @@ extern "system" fn resolve( let rect = RECT { left: 0, top: 0, - right: dst_width.min(src_width) as i32, - bottom: dst_height.min(src_height) as i32, + right: a.Width.min(b.Width) as i32, + bottom: a.Height.min(b.Height) as i32, }; list1.ResolveSubresourceRegion( to, @@ -895,170 +1571,6 @@ pub(crate) struct Rect { bottom: i32, } -#[repr(C)] -#[derive(Clone, Copy)] -struct DiscardRegion { - num_rects: u32, - rects: *const Rect, - first_subresource: u32, - num_subresources: u32, -} - -#[cfg(windows)] -const _: () = { - use windows::Win32::Foundation::RECT; - use windows::Win32::Graphics::Direct3D12::D3D12_DISCARD_REGION; - assert!(size_of::<DiscardRegion>() == size_of::<D3D12_DISCARD_REGION>()); - assert!(align_of::<DiscardRegion>() == align_of::<D3D12_DISCARD_REGION>()); - assert!(size_of::<Rect>() == size_of::<RECT>()); - assert!(align_of::<Rect>() == align_of::<RECT>()); -}; - -/// A non-null, aligned rectangle pointer must cover `num_rects` rectangles. -#[cfg(any(windows, test))] -unsafe fn valid_discard_region( - region: Option<&DiscardRegion>, - dimension: u32, - mip_levels: u16, - depth_or_array_size: u16, - planes: u8, - extent: [u64; 2], -) -> bool { - const TEXTURE_2D: u32 = 3; - const TEXTURE_3D: u32 = 4; - let Some(region) = region else { return true }; - let mips = u64::from(mip_levels.max(1)); - let slices = if dimension == TEXTURE_3D { - 1 - } else { - u64::from(depth_or_array_size.max(1)) - }; - let first = u64::from(region.first_subresource); - let count = u64::from(region.num_subresources); - if count == 0 || first + count > mips * slices * u64::from(planes) { - return false; - } - if region.num_rects == 0 { - return true; - } - let rects = region.num_rects as usize; - // Rectangles apply to 2D subresources of the same dimensions. In a - // contiguous range with multiple mips, adjacent subresources differ. - if dimension != TEXTURE_2D - || (mips > 1 && count > 1) - || region.rects.is_null() - || !region.rects.is_aligned() - || rects > isize::MAX as usize / size_of::<Rect>() - { - return false; - } - let [width, height] = - extent.map(|size| size.checked_shr((first % mips) as u32).unwrap_or(0).max(1)); - // SAFETY: the caller supplies the array, and its pointer and size were checked. - unsafe { std::slice::from_raw_parts(region.rects, rects) } - .iter() - .all(|r| { - r.left >= 0 - && r.top >= 0 - && r.left < r.right - && r.top < r.bottom - && r.right as u64 <= width - && r.bottom as u64 <= height - }) -} - -#[cfg(any(windows, test))] -fn discard_state_allowed(state: u32, flags: u32) -> bool { - let required_flag = match state { - 0x4 => 0x1, // RENDER_TARGET - 0x10 => 0x2, // DEPTH_WRITE / ALLOW_DEPTH_STENCIL - 0x8 => 0x4, // UNORDERED_ACCESS - _ => return false, - }; - flags & required_flag != 0 -} - -extern "system" fn discard_resource(this: This, resource: This, region: *const DiscardRegion) { - #[cfg(windows)] - { - use windows::Win32::Graphics::Direct3D12::*; - let (Some(list), Some(copy)) = (host_list(this), crate::resource::host_copy(resource)) - else { - return; - }; - // SAFETY: a live host texture. - let desc = unsafe { copy.texture.GetDesc() }; - let tracked = list.tracked_texture_state(©); - let state = match tracked { - Some(state) => state, - None if list_type(this) == D3D12_COMMAND_LIST_TYPE_DIRECT.0 as u32 => { - if desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { - D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32 - } else if desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) { - D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32 - } else { - return; - } - } - None => return, - }; - if !discard_state_allowed(state, desc.Flags.0 as u32) || !region.is_aligned() { - return; - } - // SAFETY: the title passes a discard region or null. - let region = unsafe { region.as_ref() }; - if let Some(region) = region { - let Some(host) = crate::host::host() else { - return; - }; - let mut format = D3D12_FEATURE_DATA_FORMAT_INFO { - Format: desc.Format, - PlaneCount: 0, - }; - // SAFETY: the feature data matches the requested query. - if unsafe { - host.device.CheckFeatureSupport( - D3D12_FEATURE_FORMAT_INFO, - (&raw mut format).cast(), - size_of::<D3D12_FEATURE_DATA_FORMAT_INFO>() as u32, - ) - } - .is_err() - { - return; - } - // SAFETY: the title supplies the rectangles described by the region. - if !unsafe { - valid_discard_region( - Some(region), - desc.Dimension.0 as u32, - desc.MipLevels, - desc.DepthOrArraySize, - format.PlaneCount, - [desc.Width, u64::from(desc.Height)], - ) - } { - return; - } - } - // When discard is the first use, the normal submission prelude - // establishes its state before the list executes. - if tracked.is_none() { - ensure_state(&list, resource, state); - } - #[cfg(feature = "diagnostics")] - list.note_op(|| format!("discard resource {resource:?}")); - // SAFETY: the list holds the texture in a compatible state. The - // checked region and its rectangles have the host layout. - unsafe { - list.list - .DiscardResource(©.texture, region.map(|r| std::ptr::from_ref(r).cast())) - }; - } - #[cfg(not(windows))] - let _ = (this, resource, region); -} - extern "system" fn clear_rtv( this: This, handle: u64, @@ -1134,97 +1646,24 @@ extern "system" fn clear_dsv( unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } }); const DEPTH_WRITE: u32 = 0x10; - ensure_state(&list, record.resource, DEPTH_WRITE); + // A depth texture shaders also write: what they wrote, first (the + // clear may be of one slice or of some rectangles). + list.twin_use(record.resource, false, true); + ensure_state(list, record.resource, DEPTH_WRITE); + if crate::resource::depth_and_unordered(record.resource) { + crate::resource::DEPTH_UNORDERED[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } let dsv = host.dsv(texture, record.depth_desc().as_ref()); // SAFETY: an open list, a fresh view of a live texture. unsafe { - list.list.ClearDepthStencilView( - dsv, - D3D12_CLEAR_FLAGS(flags as i32 & 3), - depth, - stencil, - rects, - ) + list.list + .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects) }; } #[cfg(not(windows))] let _ = (this, handle, flags, depth, stencil, count, rects); } -/// Clear a resource-backed texture with a matching bound GPU UAV and CPU UAV. -#[cfg(windows)] -fn clear_uav( - this: This, - gpu: u64, - cpu: u64, - resource: This, - value: crate::draw::UavClear, - count: u32, - rects: *const Rect, -) { - let rects = if count == 0 || rects.is_null() { - &[] - } else { - // SAFETY: the title passes count rectangles in the host's layout. - unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } - }; - with_state(this, |list, state| { - state.clear_texture_uav(list, gpu, cpu, resource, value, rects) - }); -} - -extern "system" fn clear_uav_uint( - this: This, - gpu: u64, - cpu: u64, - resource: This, - values: *const [u32; 4], - count: u32, - rects: *const Rect, -) { - #[cfg(windows)] - // SAFETY: the title passes four values; null is tolerated. - if let Some(values) = unsafe { values.as_ref() } { - clear_uav( - this, - gpu, - cpu, - resource, - crate::draw::UavClear::Uint(*values), - count, - rects, - ); - } - #[cfg(not(windows))] - let _ = (this, gpu, cpu, resource, values, count, rects); -} - -extern "system" fn clear_uav_float( - this: This, - gpu: u64, - cpu: u64, - resource: This, - values: *const [f32; 4], - count: u32, - rects: *const Rect, -) { - #[cfg(windows)] - // SAFETY: the title passes four values; null is tolerated. - if let Some(values) = unsafe { values.as_ref() } { - clear_uav( - this, - gpu, - cpu, - resource, - crate::draw::UavClear::Float(*values), - count, - rects, - ); - } - #[cfg(not(windows))] - let _ = (this, gpu, cpu, resource, values, count, rects); -} - /// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses /// are title memory, copied at submission like buffer copies (if mapped). extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) { @@ -1234,7 +1673,9 @@ extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: && src != 0 { let len = len as usize; - list.defer(move || { + // Its place is known: `VICTORY_NEAR_WRITES` uses it (without the + // switch the step is the same as `defer`'s). + list.defer_at(dst as usize, len, move || { if crate::texture::committed(src as *const u8, len) && crate::texture::committed(dst as *const u8, len) { @@ -1252,21 +1693,40 @@ extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 { 0 } -/// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the -/// host has no use for (the ray-tracing builder dispatches this way). -extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) { +/// `DispatchX(x, y, z, flags)`: a dispatch with the console's +/// `COMPUTE_DISPATCH_INITIATOR` flags. Bit 5 (0x20, +/// `USE_THREAD_DIMENSIONS`): `x`, `y`, `z` count threads, not groups (the +/// ray-tracing structure builder's box stages; fork pull request #646). +extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, flags: u32) { #[cfg(windows)] - state::dispatch(this, x, y, z); + state::dispatch_x(this, x, y, z, flags); #[cfg(not(windows))] { - let _ = (this, x, y, z); + let _ = (this, x, y, z, flags); count_dispatch(); } } -/// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when -/// resolved. -extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {} +/// `BeginQuery(heap, type, index)`: counted; an occlusion query runs on the host GPU with `VICTORY_OCCLUSION`. +extern "system" fn begin_query(this: This, heap: This, kind: u32, index: u32) { + crate::query::counted(kind); + #[cfg(windows)] + if let Some(list) = host_list(this) { + crate::query::begin(list, heap, kind, index); + } + #[cfg(not(windows))] + let _ = (this, heap, index); +} + +/// `EndQuery(heap, type, index)`: ends what [`begin_query`] began on the host. +extern "system" fn end_query(this: This, heap: This, kind: u32, index: u32) { + #[cfg(windows)] + if let Some(list) = host_list(this) { + crate::query::end(list, heap, kind, index); + } + #[cfg(not(windows))] + let _ = (this, heap, kind, index); +} /// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes /// each query's result into the buffer once the list has run. Timestamps @@ -1277,9 +1737,9 @@ extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {} /// not measured ones (time spans come out as the submission's length). extern "system" fn resolve_queries( this: This, - _heap: This, + heap: This, kind: u32, - _first: u32, + first: u32, count: u32, buffer: This, offset: u64, @@ -1301,6 +1761,17 @@ extern "system" fn resolve_queries( if offset + u64::from(count) * bytes > size { return; } + // With `VICTORY_OCCLUSION`: occlusion results from the host GPU, if every query of the range ran there. + #[cfg(windows)] + if (kind == OCCLUSION || kind == BINARY) + && let Some(list) = host_list(this) + // SAFETY: inside the buffer, checked above. + && crate::query::resolve(list, heap, kind, first, count, unsafe { data.add(offset as usize) } as u64) + { + return; + } + #[cfg(not(windows))] + let _ = (heap, first); for i in 0..u64::from(count) { // Wider results are written as 8-byte pieces. for piece in 0..bytes / 8 { @@ -1312,107 +1783,6 @@ extern "system" fn resolve_queries( } } -extern "system" fn set_predication(this: This, buffer: This, offset: u64, operation: u32) { - #[cfg(windows)] - { - use windows::Win32::Graphics::Direct3D12::*; - - let Some(host) = host_list(this) else { - return; - }; - if buffer.is_null() { - #[cfg(feature = "diagnostics")] - host.note_op(|| "disable predication".into()); - // SAFETY: an open list; a null buffer disables predication. - unsafe { - host.list - .SetPredication(None, 0, D3D12_PREDICATION_OP_EQUAL_ZERO) - }; - return; - } - let operation = match operation { - 0 => D3D12_PREDICATION_OP_EQUAL_ZERO, - 1 => D3D12_PREDICATION_OP_NOT_EQUAL_ZERO, - _ => { - tracing::debug!(operation, "invalid predication operation"); - return; - } - }; - if !offset.is_multiple_of(8) { - tracing::debug!(offset, "unaligned predication offset"); - return; - } - let Some(data) = buffer_range(buffer, offset, 8) else { - return; - }; - #[cfg(feature = "diagnostics")] - host.note_op(|| format!("set predication {buffer:?}+{offset:#x} {operation:?}")); - if let Some(resource) = crate::resource::host_resource(buffer) { - ensure_state(&host, buffer, D3D12_RESOURCE_STATE_PREDICATION.0 as u32); - // SAFETY: an open list and a live buffer with an aligned predicate. - unsafe { host.list.SetPredication(Some(resource), offset, operation) }; - } else if let Some(device) = crate::host::host() - && let Some((upload, mapped)) = host.upload(device, 8) - { - // Title buffers live in CPU memory. Take each predicate at its place - // among deferred title writes. The list owns the upload, whose - // GENERIC_READ state includes PREDICATION. - host.defer_fill(mapped, data, 8); - // SAFETY: the list retains the upload through execution. - unsafe { host.list.SetPredication(Some(&upload), 0, operation) }; - } - } - #[cfg(not(windows))] - let _ = (this, buffer, offset, operation); -} - -#[cfg(windows)] -fn event_payload(data: *const c_void, size: u32) -> (Option<*const c_void>, u32) { - if data.is_null() || size == 0 { - (None, 0) - } else { - (Some(data), size) - } -} - -extern "system" fn set_marker(this: This, metadata: u32, data: *const c_void, size: u32) { - #[cfg(windows)] - if let Some(host) = host_list(this) { - let (data, size) = event_payload(data, size); - #[cfg(feature = "diagnostics")] - host.note_op(|| format!("set marker metadata={metadata:#x} size={size}")); - // SAFETY: an open list; the caller provides `size` bytes for this call. - unsafe { host.list.SetMarker(metadata, data, size) }; - } - #[cfg(not(windows))] - let _ = (this, metadata, data, size); -} - -extern "system" fn begin_event(this: This, metadata: u32, data: *const c_void, size: u32) { - #[cfg(windows)] - if let Some(host) = host_list(this) { - let (data, size) = event_payload(data, size); - #[cfg(feature = "diagnostics")] - host.note_op(|| format!("begin event metadata={metadata:#x} size={size}")); - // SAFETY: an open list; the caller provides `size` bytes for this call. - unsafe { host.list.BeginEvent(metadata, data, size) }; - } - #[cfg(not(windows))] - let _ = (this, metadata, data, size); -} - -extern "system" fn end_event(this: This) { - #[cfg(windows)] - if let Some(host) = host_list(this) { - #[cfg(feature = "diagnostics")] - host.note_op(|| "end event".into()); - // SAFETY: an open list; the caller pairs this with BeginEvent. - unsafe { host.list.EndEvent() }; - } - #[cfg(not(windows))] - let _ = this; -} - /// IUnknown 3, object 4, device child 1, allocator 2. static ALLOCATOR_FUNCTIONS: Table<24> = { let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>()); @@ -1440,79 +1810,44 @@ extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _siz /// Reset with console flags `(allocator, pipeline, flags)`; the flags only /// tune the console's command memory. -/// `ClearState` (0x58): the host list's state and ours back to their -/// defaults, `pipeline` bound at the next draw or dispatch. -extern "system" fn clear_state(this: This, pipeline: This) { - #[cfg(windows)] - with_state(this, |host, state| { - // SAFETY: an open list; the translated pipeline is bound later. - unsafe { host.list.ClearState(None) }; - state.clear(pipeline); - #[cfg(feature = "diagnostics")] - host.note_op(|| format!("clear state {pipeline:?}")); - }); - #[cfg(not(windows))] - let _ = (this, pipeline); -} - extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT { reset(this, allocator, pipeline) } /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list /// owns until it is reset, which the CPU writes and the GPU reads at the -/// same address; null on failure. Grand Theft Auto VI's BVH builder puts +/// same address; null on failure. The title's BVH builder puts /// its instance descriptions there (and wrote through our old /// `E_NOTIMPL` as a pointer). extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 { - if this.is_null() { - return std::ptr::null_mut(); - } - let Ok(raw_align) = usize::try_from(alignment) else { - return std::ptr::null_mut(); - }; - if raw_align != 0 && !raw_align.is_power_of_two() { - return std::ptr::null_mut(); - } - let align = raw_align.max(16); - let Some(len) = usize::try_from(size) - .ok() - .and_then(|s| s.checked_add(align)) - else { + let align = usize::try_from(alignment).unwrap_or(0).max(16); + let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else { return std::ptr::null_mut(); }; - let mut block = Vec::new(); - if block.try_reserve_exact(len).is_err() { + if this.is_null() || !align.is_power_of_two() { return std::ptr::null_mut(); } - block.resize(len, 0); + let mut block = vec![0u8; len]; let start = block.as_mut_ptr(); - let offset = start.align_offset(align); - if offset >= align { - return std::ptr::null_mut(); - } - // SAFETY: `offset < align` and `len == size + align`, so `size` bytes fit at `start + offset`. - let at = unsafe { start.add(offset) }; + // SAFETY: the offset is below `align`, so `size` bytes fit after it. + let at = unsafe { start.add(start.align_offset(align)) }; // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::<List>()).uploads }; // Moving the vector keeps its heap block where it is. - uploads - .lock() - .unwrap_or_else(|e| e.into_inner()) - .push(block); + uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block); at } /// Draw state the host has no use for (root signatures: ours come with -/// the pipeline; depth bounds, depth order and shading rate hints): any -/// arguments, nothing returned. +/// the pipeline; depth order and shading rate hints): any arguments, +/// nothing returned. extern "system" fn ignored_state(_: This) {} /// The title's draw state (decision 0007, step 3), kept for its draws or /// set on the host list at once. Without a host GPU these do nothing. #[cfg(windows)] mod state { - use super::{This, host_list, with_state}; + use super::{This, with_state}; use crate::draw::{IndexView, VertexView}; use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT; @@ -1534,32 +1869,24 @@ mod state { count: u32, viewports: *const D3D12_VIEWPORT, ) { - if let Some(list) = host_list(this) { - crate::draw::viewports(&list, items(viewports, count)); - } + // (Through the draw state, which keeps them for the host list + // that continues this one after a cut: `State::replay`.) + with_state(this, |list, s| s.set_viewports(list, items(viewports, count))); } pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) { - if let Some(list) = host_list(this) { - crate::draw::scissors(&list, items(rects, count)); - } + with_state(this, |list, s| s.set_scissors(list, items(rects, count))); } pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) { - if let Some(list) = host_list(this) { + with_state(this, |list, s| { // SAFETY: the title passes four floats or null. - crate::draw::blend_factor(&list, unsafe { factor.as_ref() }); - } + s.set_blend_factor(list, unsafe { factor.as_ref() }) + }); } pub(super) extern "system" fn stencil_ref(this: This, reference: u32) { - if let Some(list) = host_list(this) { - crate::draw::stencil_ref(&list, reference); - } + with_state(this, |list, s| s.set_stencil_ref(list, reference)); } - /// `OMSetDepthBounds`: for pipelines with the depth bounds test (see - /// the host pipeline); lists start at 0..1, as the host's do. pub(super) extern "system" fn depth_bounds(this: This, min: f32, max: f32) { - if let Some(list) = host_list(this) { - crate::draw::depth_bounds(&list, min, max); - } + with_state(this, |list, s| s.set_depth_bounds(list, min, max)); } pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { with_state(this, |_, s| s.set_heaps(items(heaps, count))); @@ -1664,33 +1991,23 @@ mod state { super::count_dispatch(); with_state(this, |list, s| s.dispatch(list, x, y, z)); } - /// The groups a mesh dispatch of `x` × `y` × `z` groups runs: the - /// title's mesh programs read only the x group id, so `x` (y and z - /// other than 1 are logged once); none if any dimension is empty. - pub(super) fn mesh_groups(x: u32, y: u32, z: u32) -> Option<u32> { - if x == 0 || y == 0 || z == 0 { - return None; - } - if y != 1 || z != 1 { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups")); - } - Some(x) + pub(super) fn dispatch_x(this: This, x: u32, y: u32, z: u32, flags: u32) { + super::count_dispatch(); + with_state(this, |list, s| s.dispatch_x(list, x, y, z, flags)); } - /// `DispatchMesh(x, y, z)` (the PC method of List6). + /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh + /// programs take `x` groups only. pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) { super::count_draw(); - if let Some(x) = mesh_groups(x, y, z) { - with_state(this, |list, s| s.dispatch_mesh(list, x)); + if y * z != 1 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups")); } + with_state(this, |list, s| s.dispatch_mesh(list, x)); } - /// `DispatchMeshX(x, flags, indirect arguments, payload)`. With an - /// indirect address the group counts are in GPU memory there, run as - /// indirect execution of one mesh dispatch. - /// Inferred, not documented: the arguments are those of a PC indirect - /// mesh dispatch (D3D12_DISPATCH_MESH_ARGUMENTS, three 32-bit group - /// counts, as the title's mesh dispatch signatures have) and `x` is then - /// unused; `flags` and `payload` are unknown. + /// `DispatchMeshX(x, flags, indirect arguments, payload)`. + /// shortcut: dispatches whose group count is in GPU memory (indirect) + /// are dropped; make them ExecuteIndirect when the title uses them. pub(super) extern "system" fn dispatch_mesh_x( this: This, x: u32, @@ -1698,22 +2015,13 @@ mod state { indirect: u64, _payload: u64, ) { - const MESH: u32 = 10; - const STRIDE: u32 = 12; super::count_draw(); - if indirect == 0 { - if x != 0 { - with_state(this, |list, s| s.dispatch_mesh(list, x)); - } + if indirect != 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped")); return; } - let mut ran = false; - with_state(this, |list, s| { - ran = s.execute_indirect(list, STRIDE, &[[MESH, 0, 0, 0]], 1, indirect, None); - }); - if !ran { - super::INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - } + with_state(this, |list, s| s.dispatch_mesh(list, x)); } pub(super) extern "system" fn draw_indexed( this: This, @@ -1739,7 +2047,6 @@ mod state { pub(super) use super::draw as dispatch_mesh; pub(super) use super::draw as dispatch_mesh_x; pub(super) use super::ignored_state as blend_factor; - pub(super) use super::ignored_state as depth_bounds; pub(super) use super::ignored_state as compute_constant; pub(super) use super::ignored_state as compute_constants; pub(super) use super::ignored_state as compute_table; @@ -1752,6 +2059,7 @@ mod state { pub(super) use super::ignored_state as index_buffer; pub(super) use super::ignored_state as scissors; pub(super) use super::ignored_state as stencil_ref; + pub(super) use super::ignored_state as depth_bounds; pub(super) use super::ignored_state as targets; pub(super) use super::ignored_state as topology; pub(super) use super::ignored_state as vertex_buffers; @@ -1760,8 +2068,13 @@ mod state { fn count_draw() { DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + DRAWS_EVER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } +/// Draws recorded since the start (never taken): the texture pass tells a +/// loading screen (a few draws a frame) from the world by it. +pub(crate) static DRAWS_EVER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// Draws of the kinds the host does not run yet (indirect, mesh), and /// dispatches, counted per frame for the log. /// shortcut: dropped until their shaders translate (decision 0007). @@ -1771,7 +2084,7 @@ extern "system" fn draw(_: This) { } /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer, -/// offset)`. Grand Theft Auto VI's signatures (title+0x2479466, 2026-11-24) +/// offset)`. The title's signatures (title+0x2479466, 2026-11-24) /// hold one argument each: draw (stride 16), indexed draw (20), dispatch /// (12), mesh dispatch (12), and the console's single-pass dispatch, type /// 105 (stride 12: the three group counts; its flags live in the @@ -1796,14 +2109,17 @@ extern "system" fn execute_indirect( let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset); let mut ran = false; #[cfg(windows)] - if let (false, Some(address)) = (args.is_empty(), address) + if let ([[kind, ..]], Some(address)) = (args, address) && (count.is_null() || counter.is_some()) { + const DISPATCH: u32 = 2; + const DISPATCH_SINGLE: u32 = 105; + let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind }; with_state(this, |list, s| { - ran = s.execute_indirect(list, stride, args, max, address, counter); + ran = s.execute_indirect(list, (kind, stride, max), address, counter); }); } else { - #[cfg(all(windows, feature = "diagnostics"))] + #[cfg(windows)] crate::pipeline::note_why(format!( "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}", address.is_some(), @@ -1851,37 +2167,216 @@ pub(crate) fn take_counts() -> (u64, u64) { (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed)) } -/// A GPU wait for a memory value `(address, comparison, reference, ...)`. -/// Lists run one after another and to completion, so a value another queue -/// or the CPU has to write first cannot be waited for; nothing to do. -extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _reference: u64) {} +/// A GPU wait for a memory value: the list's commands after it run when +/// the 32 or 64 bits at `address` compare as asked with `reference`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ValueWait { + address: u64, + comparison: u32, + reference: u64, + wide: bool, +} + +impl ValueWait { + /// Whether the memory holds what is waited for now. + /// shortcut: the comparison codes are taken to be the comparison + /// functions' (1 never .. 8 always, value against reference); one not + /// known counts as met, and so does memory that is not mapped. + /// + /// The value is read through the kernel, which reports memory that is + /// not there instead of faulting (as the copies of title memory are + /// read, `crate::host::copy_mapped`). Asking Windows first whether the + /// memory is committed (`VirtualQuery`) walks the page tables to the + /// end of the region: the title keeps these values in a 1.1 GB + /// allocation (0xd00000000), where one question took about 8 ms, and a + /// queue asks at every submission and every signal, for each queue that + /// stands at a wait (the title has five queues). That was + /// 1.0-2.2 s of every cutscene frame on the thread that submits (runs + /// 36-49: "between its submissions ... kernel"; 47 of 110 looks at + /// that thread in run 49 found it in this question). + /// `VICTORY_WAIT_ASK=1` asks first, as before. + pub(crate) fn met(&self) -> bool { + #[cfg(all(windows, feature = "diagnostics"))] + let started = std::time::Instant::now(); + let met = self.holds(); + #[cfg(all(windows, feature = "diagnostics"))] + { + use crate::copystat::{C, add}; + add(C::WaitChecks, 1); + add(C::WaitCheckNs, started.elapsed().as_nanos() as u64); + } + met + } + + fn holds(&self) -> bool { + let bytes = if self.wide { 8 } else { 4 }; + if self.address == 0 { + return true; + } + static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if *ASK.get_or_init(|| std::env::var_os("VICTORY_WAIT_ASK").is_some_and(|v| v == "1")) + && !crate::texture::committed(self.address as *const u8, bytes) + { + return true; + } + // The low `bytes` bytes; the rest stays zero. + let mut raw = [0u8; 8]; + if !crate::host::read_into(self.address as *const u8, &mut raw[..bytes]) { + return true; + } + self.holds_for(u64::from_le_bytes(raw)) + } -/// The enhanced barriers `(group count, groups)`: buffer, texture and -/// global barriers with layouts instead of states. Every host use of a -/// title texture (clears, copies) moves its host copy to the state it needs -/// first, so only their ordering matters: one barrier on every shader -/// write (the title's buffer barriers order compute passes). -extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { + /// Where the value waited for is: address and bytes. #[cfg(windows)] - if count > 0 - && let Some(list) = host_list(this) - { - use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; - // SAFETY: the same layout; no resource named. - let barrier = - unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) }; - // SAFETY: an open list. - unsafe { list.list.ResourceBarrier(&[barrier]) }; + pub(crate) fn place(&self) -> (usize, usize) { + (self.address as usize, if self.wide { 8 } else { 4 }) + } + + /// Whether the wait is met with `value` at its address (its low half + /// for a 32-bit wait). + pub(crate) fn holds_for(&self, value: u64) -> bool { + let (value, reference) = if self.wide { + (value, self.reference) + } else { + (value & 0xFFFF_FFFF, self.reference & 0xFFFF_FFFF) + }; + match self.comparison { + 1 => false, + 2 => value < reference, + 3 => value == reference, + 4 => value <= reference, + 5 => value > reference, + 6 => value != reference, + 7 => value >= reference, + _ => true, + } } - #[cfg(not(windows))] - let _ = (this, count); } -/// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and -/// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the +/// The waits lists recorded since their last reset, by list. +static VALUE_WAITS: std::sync::Mutex<Vec<(usize, ValueWait)>> = std::sync::Mutex::new(Vec::new()); + +/// The waits of the submitted `lists` that are not met yet (taken from +/// them): what the console's GPU would stop at. The title orders work +/// between its queues this way (the title: the compute queue's +/// lighting passes wait for a value the graphics queue's depth pass writes +/// at the bottom of the pipe; run at once, they read a cleared depth +/// buffer and nothing was lit). +/// shortcut: a wait holds its whole list (and submission) back, not only +/// the commands after it. +pub(crate) fn unmet_waits(lists: &[This]) -> Vec<ValueWait> { + let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + let mut unmet = Vec::new(); + waits.retain(|&(list, wait)| { + if !lists.iter().any(|&l| l as usize == list) { + return true; + } + if !wait.met() { + unmet.push(wait); + } + false + }); + unmet +} + +/// The waits each of the submitted `lists` recorded (taken from them), +/// met or not, at the list's first place in the submission. +#[cfg(windows)] +pub(crate) fn waits_by_list(lists: &[This]) -> Vec<Vec<ValueWait>> { + let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + let mut by = vec![Vec::new(); lists.len()]; + waits.retain(|&(list, wait)| { + match lists.iter().position(|&l| l as usize == list) { + Some(i) => { + by[i].push(wait); + false + } + None => true, + } + }); + by +} + +fn wait_for(this: This, address: u64, comparison: u32, reference: u64, wide: bool) { + let wait = ValueWait { + address, + comparison, + reference, + wide, + }; + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 12 { + tracing::info!( + address = format_args!("{address:#x}"), + comparison, + reference, + wide, + met = wait.met(), + "a list waits for a memory value" + ); + } + #[cfg(all(windows, feature = "diagnostics"))] + if let Some(host) = host_list(this) { + crate::capture::op(std::ptr::from_ref(host) as usize, || { + format!( + "WAIT VALUE at {address:#x} comparison {comparison} reference {reference:#x} wide {wide} met {}", + wait.met() + ) + }); + } + // The list is cut here, and the wait stands before what follows. + #[cfg(windows)] + if crate::queue::cuts() { + cut(this, wait); + return; + } + VALUE_WAITS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((this as usize, wait)); +} +extern "system" fn wait_value(this: This, address: u64, comparison: u32, reference: u64) { + wait_for(this, address, comparison, reference, false); +} +extern "system" fn wait_value64(this: This, address: u64, comparison: u32, reference: u64) { + wait_for(this, address, comparison, reference, true); +} + +/// The enhanced barriers `(group count, groups)`: buffer, texture and +/// global barriers with layouts instead of states. Every host use of a +/// title texture (clears, copies) moves its host copy to the state it needs +/// first, so only their ordering matters: one barrier on every shader +/// write (the title's buffer barriers order compute passes). +extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { + // Diagnostics: counted, and left out under `VICTORY_BARRIER_TEST=groups`. + #[cfg(all(windows, feature = "diagnostics"))] + if count > 0 { + crate::copystat::add(crate::copystat::C::WaitsForGroups, 1); + if crate::copystat::barrier_test() & 1 != 0 { + return; + } + } + #[cfg(windows)] + if count > 0 + && let Some(list) = host_list(this) + { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } + #[cfg(not(windows))] + let _ = (this, count); +} + +/// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and +/// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the /// GPU timestamp instead (64-bit form), flag 2 the system timestamp. extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) { defer_write(this, address, Written::Value(u64::from(value)), 4); + value_written(this, address, u64::from(value)); } extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) { const GPU_TIMESTAMP: u32 = 1; @@ -1892,6 +2387,65 @@ extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, fl _ => Written::Value(value), }; defer_write(this, address, what, 8); + if let Written::Value(value) = what { + value_written(this, address, value); + } +} + +/// The title wrote a value at the bottom of the pipe (not a timestamp, not +/// a query result): listed (diagnostics), and with `VICTORY_CUT_WRITES=1` +/// the host list is cut right behind it, so that the value is stored when +/// the card has run the list up to there, as on the console, and not when +/// the whole list has run. Lists of other queues wait for these values +/// (the title: the compute list that builds the depth pyramid +/// waits for one, and the meshlet culling of the same frame reads that +/// pyramid). Off by default: every such write then ends a host list, and +/// each part is a submission of its own. +fn value_written(this: This, address: u64, value: u64) { + #[cfg(windows)] + { + if address == 0 || this.is_null() { + return; + } + #[cfg(not(feature = "diagnostics"))] + let _ = value; + #[cfg(feature = "diagnostics")] + if let Some(host) = host_list(this) { + crate::capture::op(std::ptr::from_ref(host) as usize, || { + format!("WRITE VALUE at {address:#x} value {value:#x}") + }); + } + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WRITES").is_some_and(|v| v == "1")) + || !crate::queue::cuts() + { + return; + } + // SAFETY: the title passes one of our lists; a list is recorded by + // one thread at a time and is not submitted while it records. + let list = unsafe { &mut *this.cast_mut().cast::<List>() }; + let Some(current) = list.host.as_ref() else { + return; + }; + let Some(fresh) = fresh_list() else { + return; + }; + current.close(); + if let Some(done) = list.host.replace(fresh) { + // The part so far keeps its waits; nothing stands before the + // next one but this part itself. + let waits = std::mem::take(&mut list.gate); + list.earlier.push(Part { waits, host: done }); + } + if let Some(host) = list.host.as_ref() { + list.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .replay(host); + } + } + #[cfg(not(windows))] + let _ = (this, address, value); } fn defer_write(this: This, address: u64, what: Written, bytes: usize) { @@ -1904,22 +2458,21 @@ fn defer_write(this: This, address: u64, what: Written, bytes: usize) { return; } let _ = this; - // Without a host GPU nothing runs later: write now (no lock held). - what.write(address as *mut u8, bytes).run(); + // Without a host GPU nothing runs later: write now. + what.write(address as *mut u8, bytes); } /// The list methods by their slot in older titles' lists (the 2020-era /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96 /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 /// + 13): 140 slots. -const METHODS: [(usize, *const ()); 59] = [ +const METHODS: [(usize, *const ()); 52] = [ (0, list_query as *const ()), (2, list_release as *const ()), (7, object::parent_device as *const ()), // 0x38 (8, list_type as *const ()), // 0x40 (9, close as *const ()), // 0x48 (10, reset as *const ()), // 0x50 - (11, clear_state as *const ()), // 0x58 (12, state::draw as *const ()), // 0x60 instanced (13, state::draw_indexed as *const ()), // 0x68 indexed (14, state::dispatch as *const ()), // 0x70 @@ -1954,19 +2507,13 @@ const METHODS: [(usize, *const ()); 59] = [ (50, state::targets as *const ()), // 0x190 (51, clear_dsv as *const ()), // 0x198 (52, clear_rtv as *const ()), // 0x1a0 - (53, clear_uav_uint as *const ()), // 0x1a8 - (54, clear_uav_float as *const ()), // 0x1b0 - (55, discard_resource as *const ()), // 0x1b8 - (56, set_marker as *const ()), // 0x1c0 - (57, begin_event as *const ()), // 0x1c8 - (58, end_event as *const ()), // 0x1d0 (59, execute_indirect as *const ()), // 0x1d8 indirect (60, copy_memory as *const ()), // 0x1e0 (68, state::depth_bounds as *const ()), // 0x220 depth bounds (69, write32 as *const ()), // 0x228 (70, write64 as *const ()), // 0x230 (71, wait_value as *const ()), // 0x238, 32 bits - (72, wait_value as *const ()), // 0x240, 64 bits + (72, wait_value64 as *const ()), // 0x240, 64 bits (73, ignored_state as *const ()), // 0x248 pixel shader depth order (83, copy_texture_region_x as *const ()), // 0x298 (84, copy_resource_x as *const ()), // 0x2a0 @@ -1974,11 +2521,10 @@ const METHODS: [(usize, *const ()); 59] = [ (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch ]; /// The rest of [`METHODS`], kept apart only to stay readable. -const MORE_METHODS: [(usize, *const ()); 10] = [ - (28, query_mark as *const ()), // 0xe0 BeginQuery - (29, query_mark as *const ()), // 0xe8 EndQuery +const MORE_METHODS: [(usize, *const ()); 9] = [ + (28, begin_query as *const ()), // 0xe0 BeginQuery + (29, end_query as *const ()), // 0xe8 EndQuery (30, resolve_queries as *const ()), // 0xf0 - (31, set_predication as *const ()), // 0xf8 (78, dispatch_x as *const ()), // 0x270 (98, state::dispatch_mesh_x as *const ()), // 0x310 (99, driver_hint as *const ()), // 0x318 @@ -1992,7 +2538,7 @@ const MORE_METHODS: [(usize, *const ()); 10] = [ /// base list, after the clears (0x198/0x1a0 as before) and before /// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8 /// on is two later (taken here as starting exactly at 0x1d8). Inferred from -/// Grand Theft Auto VI's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe +/// The title's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe /// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate /// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure). const fn newer_slot(slot: usize) -> usize { @@ -2002,7 +2548,7 @@ const fn newer_slot(slot: usize) -> usize { /// Methods only newer titles' lists have. 0x490: the enhanced barrier /// `(group count, groups)`, with 16-byte groups `(type, count, barriers)` /// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`, -/// called from Grand Theft Auto VI's state flush with its result unused. +/// called from the title's state flush with its result unused. /// shortcut: 0x470's purpose is unknown; ignored until a title shows it /// matters. const NEWER_METHODS: [(usize, *const ()); 3] = [ @@ -2041,424 +2587,6 @@ mod tests { use super::*; use crate::object::slot; - /// A texture made in a substituted target format meets only its own - /// family in a copy (upstream #735): RGBA8 and its typeless and sRGB - /// twins copy, the title's B5G5R5A1 or R9G9B9E5 textures do not. - #[test] - fn copies_stay_within_a_format_family() { - use crate::resource::target_format; - assert!(same_family(28, 28)); - assert!(same_family(27, 29)); - assert!(same_family(10, 2 + 8)); - assert!(!same_family(target_format(86), 86)); - assert!(!same_family(target_format(115), 115)); - assert!(!same_family(target_format(67), 67)); - assert!(same_family(86, 86)); - } - - #[cfg(windows)] - #[test] - fn command_list_creation_keeps_the_initial_pipeline() { - use windows::Win32::Graphics::Direct3D12::ID3D12PipelineState; - use windows::core::Interface; - - let null = std::ptr::null(); - let iid = ID3D12PipelineState::IID; - // SAFETY: ComputeHead contains only raw pointers and a byte count. No - // shader is needed to verify which pipeline object the list remembers. - let desc: crate::pipeline::ComputeHead = unsafe { std::mem::zeroed() }; - let mut pipeline = null; - let mut allocator = null; - assert_eq!( - crate::pipeline::create_compute(null, &desc, (&raw const iid).cast(), &mut pipeline), - S_OK - ); - assert_eq!( - create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), - S_OK - ); - let desc = ListDesc { - kind: 0, - flags: 0, - nodes: 0, - barrier_batch: 0, - }; - let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); - let bound = |list: This| { - // SAFETY: the test owns this live command list. - unsafe { &*list.cast::<List>() } - .state - .lock() - .unwrap() - .current_pipeline() - }; - let created_with = [false, true].map(|extended| { - let mut list = null; - let hr = if extended { - create_list_x(null, &desc, allocator, pipeline, &LIST_IIDS[1], &mut list) - } else { - create_list(null, 0, 0, allocator, pipeline, &LIST_IIDS[1], &mut list) - }; - assert_eq!(hr, S_OK); - let initial = bound(list); - if host_list(list).is_some() { - assert_eq!(close(list), S_OK); - assert_eq!(reset_x(list, allocator, null, 0), S_OK); - assert_eq!(bound(list), null); - assert_eq!(close(list), S_OK); - assert_eq!(reset(list, allocator, pipeline), S_OK); - assert_eq!(bound(list), pipeline); - } - assert_eq!(release(list), 0); - initial - }); - assert_eq!(release(allocator), 0); - assert_eq!(release(pipeline), 0); - assert_eq!( - created_with, - [pipeline, pipeline], - "initial PSO for CreateCommandList and CreateCommandListX" - ); - } - - /// Mesh programs read only the x group id, so a mesh dispatch runs its - /// x groups; one with no groups in any dimension runs nothing. - #[cfg(windows)] - #[test] - fn mesh_dispatches_run_x_groups_unless_empty() { - use state::mesh_groups; - assert_eq!(mesh_groups(5, 1, 1), Some(5)); - assert_eq!(mesh_groups(0, 1, 1), None); - assert_eq!(mesh_groups(5, 0, 1), None); - assert_eq!(mesh_groups(5, 1, 0), None); - assert_eq!(mesh_groups(5, 2, 3), Some(5)); - assert_eq!(mesh_groups(5, u32::MAX, u32::MAX), Some(5)); - } - - /// An indirect mesh dispatch the host does not run (no host device, as - /// in tests) is counted with the other indirect work dropped. - #[cfg(windows)] - #[test] - fn indirect_mesh_dispatches_not_run_are_counted() { - let null = std::ptr::null(); - let mut allocator = null; - assert_eq!( - create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), - S_OK - ); - let mut list = null; - let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list); - assert_eq!(hr, S_OK); - let arguments = [7u32, 1, 1]; - let before = INDIRECT.load(std::sync::atomic::Ordering::Relaxed); - state::dispatch_mesh_x(list, 0, 0, arguments.as_ptr() as u64, 0); - assert!(INDIRECT.load(std::sync::atomic::Ordering::Relaxed) > before); - assert_eq!(close(list), S_OK); - let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); - assert_eq!(release(list), 0); - assert_eq!(release(allocator), 0); - } - - /// The UAV clears sit in their slots (0x1a8, 0x1b0), not the - /// missing-method stub (upstream #771), and the table stays in slot - /// order without duplicates. - #[test] - fn uav_clears_fill_their_slots() { - let has = |i: usize, f: *const ()| METHODS.iter().any(|&(j, g)| j == i && g == f); - assert!(has(53, clear_uav_uint as *const ())); - assert!(has(54, clear_uav_float as *const ())); - assert!(METHODS.windows(2).all(|w| w[0].0 < w[1].0)); - } - - /// A clear with no values does nothing, host or not. - #[test] - fn uav_clears_tolerate_null_values() { - let null = std::ptr::null(); - clear_uav_uint(null, 0, 0, null, std::ptr::null(), 0, std::ptr::null()); - clear_uav_float(null, 0, 0, null, std::ptr::null(), 0, std::ptr::null()); - } - - #[test] - fn discard_resource_slot_is_stable() { - assert_eq!(LIST_FUNCTIONS.0[55], discard_resource as *const ()); - assert_eq!(NEWER_LIST_FUNCTIONS.0[55], discard_resource as *const ()); - } - - #[test] - fn discard_region_validation() { - let rect = Rect { - left: 1, - top: 1, - right: 4, - bottom: 4, - }; - let valid = DiscardRegion { - num_rects: 1, - rects: &rect, - first_subresource: 1, - num_subresources: 1, - }; - let whole_subresource = DiscardRegion { - num_rects: 0, - rects: std::ptr::null(), - ..valid - }; - let check = |region: Option<&DiscardRegion>, dimension, mips, slices, planes| { - // SAFETY: each non-null rectangle pointer names one live rectangle. - unsafe { valid_discard_region(region, dimension, mips, slices, planes, [8, 8]) } - }; - assert!(check(None, 3, 2, 3, 1)); - assert!(check(Some(&valid), 3, 2, 3, 1)); - assert!(!check(Some(&valid), 2, 2, 3, 1)); // 1D subresources - assert!(!check(Some(&valid), 4, 2, 3, 1)); // 3D subresources - assert!(check(Some(&whole_subresource), 4, 2, 3, 1)); - assert!(check(Some(&whole_subresource), 3, 1, 1, 2)); // stencil plane - assert!(!check(Some(&whole_subresource), 3, 1, 1, 1)); - - for (first, count) in [(5, 2), (6, 1), (u32::MAX, 2), (1, u32::MAX), (1, 0)] { - let bad_range = DiscardRegion { - first_subresource: first, - num_subresources: count, - ..whole_subresource - }; - assert!(!check(Some(&bad_range), 3, 2, 3, 1)); - } - let last_slice = DiscardRegion { - first_subresource: 5, - ..whole_subresource - }; - assert!(check(Some(&last_slice), 3, 2, 3, 1)); - assert!(!check(Some(&last_slice), 4, 2, 3, 1)); // depth is not an array size - - let null_rects = DiscardRegion { - rects: std::ptr::null(), - ..valid - }; - assert!(!check(Some(&null_rects), 3, 2, 3, 1)); - let different_mips = DiscardRegion { - num_subresources: 2, - ..valid - }; - assert!(!check(Some(&different_mips), 3, 2, 3, 1)); - assert!(check(Some(&different_mips), 3, 1, 3, 1)); - for right in [0, 1, 5] { - let rect = Rect { right, ..rect }; - let bad_rect = DiscardRegion { - rects: &rect, - ..valid - }; - assert!(!check(Some(&bad_rect), 3, 2, 3, 1)); - } - } - - #[test] - fn discard_requires_matching_state_and_flags() { - for (state, flag) in [(0x4, 1), (0x10, 2), (0x8, 4)] { - assert!(discard_state_allowed(state, flag)); - assert!(discard_state_allowed(state, flag | 0x20)); // simultaneous access - assert!(!discard_state_allowed(state, 0x7 ^ flag)); - assert!(!discard_state_allowed(state | 0x80, flag)); - } - for state in [0, 0x400, 0x80] { - assert!(!discard_state_allowed(state, 0x7)); - } - } - - #[cfg(windows)] - #[test] - fn discard_resource_executes_on_guest_queue() { - use windows::Win32::Graphics::Direct3D12::*; - use windows::Win32::Graphics::Dxgi::Common::*; - use windows::Win32::Graphics::Dxgi::{ - CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4, - }; - - let Some(host) = crate::host::host() else { - eprintln!("skipped live discard: no host D3D12 device"); - return; - }; - // SAFETY: plain DXGI queries for the device the guest queue uses. - unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); - let adapter: IDXGIAdapter1 = factory - .EnumAdapterByLuid(host.device.GetAdapterLuid()) - .unwrap(); - let desc = adapter.GetDesc1().unwrap(); - let name = String::from_utf16_lossy(&desc.Description); - eprintln!("live discard adapter: {}", name.trim_end_matches('\0')); - } - - let null = std::ptr::null(); - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; - let resource_iid = guid( - 0x696442be, - 0xa72e, - 0x4059, - [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad], - ); - let make_resource = |desc: D3D12_RESOURCE_DESC| { - let mut resource = null; - assert_eq!( - crate::resource::create_committed( - null, - (&raw const heap).cast(), - 0, - (&raw const desc).cast(), - 0, - null.cast(), - &resource_iid, - &mut resource, - ), - S_OK - ); - resource - }; - let make_texture = |format, flags| { - let resource = make_resource(D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: 8, - Height: 8, - DepthOrArraySize: 1, - MipLevels: 1, - Format: format, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Flags: flags, - ..Default::default() - }); - assert!( - crate::resource::host_resource(resource).is_some(), - "missing host texture for {format:?}" - ); - resource - }; - let rt = make_texture( - DXGI_FORMAT_R8G8B8A8_UNORM, - D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, - ); - let ds = make_texture( - DXGI_FORMAT_D24_UNORM_S8_UINT, - D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, - ); - let uav = make_texture( - DXGI_FORMAT_R32_UINT, - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - ); - let srv = make_texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE); - let buffer = make_resource(D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: 256, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - ..Default::default() - }); - assert!(crate::resource::buffer_bytes(buffer).is_some()); - - let (mut queue, mut allocator, mut list) = (null, null, null); - let queue_iid = guid( - 0x0ec870a6, - 0x5d7e, - 0x4c22, - [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], - ); - let queue_desc = [0_u32; 4]; - assert_eq!( - crate::queue::create(null, queue_desc.as_ptr().cast(), &queue_iid, &mut queue), - S_OK - ); - assert_eq!( - create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), - S_OK - ); - assert_eq!( - create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), - S_OK - ); - let host_list = &*host_list(list).unwrap(); - let discard = slot::<extern "system" fn(This, This, *const DiscardRegion)>(list, 0x1b8); - discard(list, null, null.cast()); - discard(list, buffer, null.cast()); - ensure_state( - host_list, - srv, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 as u32, - ); - discard(list, srv, null.cast()); - discard(list, rt, null.cast()); // no state established by this list yet - - ensure_state(host_list, rt, D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32); - discard(list, rt, null.cast()); - let rect = Rect { - left: 1, - top: 2, - right: 5, - bottom: 6, - }; - discard( - list, - rt, - &DiscardRegion { - num_rects: 1, - rects: &rect, - first_subresource: 0, - num_subresources: 1, - }, - ); - let mut descriptor = [0_u64; 14]; - let handle = descriptor.as_mut_ptr() as u64; - crate::descriptor::create_rtv(null, rt, std::ptr::null(), handle); - let clear = - slot::<extern "system" fn(This, u64, *const [f32; 4], u32, *const Rect)>(list, 0x1a0); - clear(list, handle, &[0.25, 0.5, 0.75, 1.0], 0, std::ptr::null()); - - ensure_state(host_list, ds, D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32); - for first_subresource in [0, 1] { - discard( - list, - ds, - &DiscardRegion { - num_rects: 0, - rects: std::ptr::null(), - first_subresource, - num_subresources: 1, - }, - ); - } - ensure_state( - host_list, - uav, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32, - ); - discard(list, uav, null.cast()); - - assert_eq!( - slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list), - S_OK - ); - assert_eq!(host.log_messages(), None); - slot::<extern "system" fn(This, u32, *const This)>(queue, 0x50)(queue, 1, &list); - // SAFETY: the guest queue waits for submission and the device is live. - unsafe { host.device.GetDeviceRemovedReason().unwrap() }; - - for object in [list, allocator, queue, rt, ds, uav, srv, buffer] { - assert_eq!( - slot::<extern "system" fn(This) -> u32>(object, 0x10)(object), - 0 - ); - } - } - #[test] fn every_inline_command_falls_back_to_the_table() { let null = std::ptr::null(); @@ -2477,7 +2605,7 @@ mod tests { (at(0x18), at(0x28), at(0x30)) }; assert!(put >= draw_limit && put >= api_limit); - // The console's ID3D12GraphicsCommandList6, as Grand Theft Auto VI asks. + // The console's ID3D12GraphicsCommandList6, as the title asks. let mut same = null; assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK); assert_eq!(same, list); @@ -2492,445 +2620,25 @@ mod tests { assert!(!p.is_null() && (p as usize).is_multiple_of(0x100)); // SAFETY: 40 bytes were handed out. unsafe { p.write_bytes(0xab, 40) }; - assert!( - allocate_upload(list, 8, 0x30).is_null(), - "not a power of two" - ); + assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two"); assert_eq!(reset(list, allocator, null), S_OK); - assert!( - // SAFETY: the list is ours. - unsafe { &(*list.cast::<List>()).uploads } - .lock() - .unwrap() - .is_empty() - ); + // SAFETY: the list is ours. + assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty()); let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); assert_eq!(release(list), 0); assert_eq!(release(allocator), 0); } - /// Resetting or dropping a list whose submission is held behind a fence - /// wait keeps its upload blocks alive until the submission runs, and - /// recycles the detached host list back into the host's pool. - #[cfg(windows)] + /// The copy decision, without a device: only a copy whose source and + /// destination both have a host copy goes to the host GPU, and the switch + /// turns every one of them back into a CPU copy (pablogonz12/Scarlight + /// #86). #[test] - fn pending_list_reset_and_drop_keep_uploads_and_recycle_host_list() { - use windows::core::Interface; - - let Some(host) = crate::host::host() else { - return; - }; - type Sync = extern "system" fn(This, This, u64) -> HRESULT; - type Execute = extern "system" fn(This, u32, *const This); - let null = std::ptr::null(); - let (waits, sig_slot) = crate::queue::test_queue(); - let wait = slot::<Sync>(waits, sig_slot + 8); - let signal = slot::<Sync>(waits, sig_slot); - let execute = slot::<Execute>(waits, 0x50); - let completed = |f: This| slot::<extern "system" fn(This) -> u64>(f, 0x40)(f); - let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); - - let fence_iid = &crate::fence::FENCE_IIDS[0]; - let (mut ready, mut done) = (null, null); - assert_eq!( - crate::fence::create(null, 0, 0, fence_iid, &mut ready), - S_OK - ); - assert_eq!(crate::fence::create(null, 0, 0, fence_iid, &mut done), S_OK); - - let mut allocator = null; - assert_eq!( - create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), - S_OK - ); - let mut list = null; - assert_eq!( - create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), - S_OK - ); - - // Hold the queue, record a copy from list upload memory, submit, then - // reset the list while its submission is still waiting. - assert_eq!(wait(waits, ready, 1), S_OK); - let src1 = allocate_upload(list, 64, 16); - assert!(!src1.is_null()); - // SAFETY: 64 bytes handed out above. - unsafe { src1.write_bytes(0x3c, 64) }; - let mut dst1 = [0u8; 64]; - copy_memory(list, dst1.as_mut_ptr() as u64, src1 as u64, 64, 0); - assert_eq!(close(list), S_OK); - let raw1 = host_list(list).unwrap().list.as_raw() as usize; - execute(waits, 1, &list); - assert_eq!(signal(waits, done, 1), S_OK); - assert_eq!(reset(list, allocator, null), S_OK); - let raw2 = host_list(list).unwrap().list.as_raw() as usize; - assert_ne!(raw2, raw1, "reset must detach from the pending host list"); - assert_eq!(dst1, [0u8; 64]); - - let reused_before = host.reused_lists(); - assert_eq!(crate::fence::signal(ready, 1), S_OK); - assert_eq!(completed(done), 1); - assert_eq!(dst1, [0x3c; 64], "kept upload memory reached the copy"); - - // Now hold behind ready == 2: reset `list` again (reusing a pooled - // host list) and also drop a second list while its submission waits. - assert_eq!(wait(waits, ready, 2), S_OK); - assert_eq!(close(list), S_OK); - execute(waits, 1, &list); - assert_eq!(reset(list, allocator, null), S_OK); - assert!( - host.reused_lists() > reused_before, - "detached host list should be recycled from the pool" - ); - - let mut list2 = null; - assert_eq!( - create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list2), - S_OK - ); - let src2 = allocate_upload(list2, 64, 16); - assert!(!src2.is_null()); - // SAFETY: 64 bytes handed out above. - unsafe { src2.write_bytes(0x5a, 64) }; - let mut dst2 = [0u8; 64]; - copy_memory(list2, dst2.as_mut_ptr() as u64, src2 as u64, 64, 0); - assert_eq!(close(list2), S_OK); - execute(waits, 1, &list2); - assert_eq!(signal(waits, done, 2), S_OK); - // Drop `list2` while its submission is still held back. - assert_eq!(release(list2), 0); - assert_eq!(dst2, [0u8; 64]); - - assert_eq!(crate::fence::signal(ready, 2), S_OK); - assert_eq!(completed(done), 2); - assert_eq!( - dst2, [0x5a; 64], - "dropping a pending list must keep its upload memory until run" - ); - - for object in [list, allocator, waits, ready, done] { - assert_eq!(release(object), 0); - } - } - - #[test] - fn allocate_upload_rejects_bad_alignments_and_oversized_requests() { - let null = std::ptr::null(); - let mut allocator = null; - assert_eq!( - create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), - S_OK - ); - let mut list = null; - assert_eq!( - create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), - S_OK - ); - - assert!(allocate_upload(null, 16, 16).is_null(), "null list"); - for bad in [3u64, 5, 6, 7, 9, 10, 12, 15, 0x30] { - assert!( - allocate_upload(list, 8, bad).is_null(), - "non-power-of-two alignment {bad} must fail" - ); - } - // Oversized alignments and sizes must return null rather than panicking - // or aborting across the FFI boundary. - assert!( - allocate_upload(list, 16, 1u64 << 63).is_null(), - "alignment > isize::MAX must return null" - ); - assert!( - allocate_upload(list, isize::MAX as u64, 16).is_null(), - "size + align > isize::MAX must return null" - ); - assert!( - allocate_upload(list, u64::MAX, 16).is_null(), - "wrapping size must return null" - ); - assert!( - allocate_upload(list, 1u64 << 50, 16).is_null(), - "unallocatable size must return null" - ); - // SAFETY: `list` is ours and stays live until released below. - let uploads = unsafe { &(*list.cast::<List>()).uploads }; - assert!(uploads.lock().unwrap().is_empty()); - - // Default alignment (0) and valid sub-16 powers of two still succeed - // with at least 16-byte alignment. - for align in [0u64, 1, 2, 4, 8, 16, 64] { - let p = allocate_upload(list, 24, align); - let want = align.max(16) as usize; - assert!( - !p.is_null() && (p as usize).is_multiple_of(want), - "valid alignment {align} failed" - ); - // SAFETY: 24 bytes were allocated at `p`. - unsafe { p.write_bytes(0x5a, 24) }; - } - assert_eq!(close(list), S_OK); - assert_eq!(reset(list, allocator, null), S_OK); - assert!(uploads.lock().unwrap().is_empty()); - let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); - assert_eq!(release(list), 0); - assert_eq!(release(allocator), 0); - } - - type SetPredication = extern "system" fn(This, This, u64, u32); - type Marker = extern "system" fn(This, u32, *const c_void, u32); - type EndEvent = extern "system" fn(This); - - #[test] - fn predication_and_marker_slots_are_stable() { - let predication: SetPredication = set_predication; - let marker: Marker = set_marker; - let begin: Marker = begin_event; - let end: EndEvent = end_event; - for table in [&LIST_FUNCTIONS, &NEWER_LIST_FUNCTIONS] { - let object = Object::new(table); - assert_eq!( - slot::<SetPredication>(&object, 0xf8) as *const (), - predication as *const () - ); - assert_eq!( - slot::<Marker>(&object, 0x1c0) as *const (), - marker as *const () - ); - assert_eq!( - slot::<Marker>(&object, 0x1c8) as *const (), - begin as *const () - ); - assert_eq!( - slot::<EndEvent>(&object, 0x1d0) as *const (), - end as *const () - ); - } - } - - #[cfg(windows)] - #[test] - fn set_predication_and_markers_execute_on_gpu() { - use windows::Win32::Graphics::Direct3D12::*; - use windows::Win32::Graphics::Dxgi::Common::{ - DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC, - }; - use windows::core::{IUnknown, Interface}; - - let Some(device) = crate::host::host() else { - assert!( - std::env::var_os("VICTORY_D3D12_WARP").is_none(), - "WARP unavailable" - ); - eprintln!("skipping predication readback: no host D3D12 device"); - return; - }; - let null = std::ptr::null(); - let (mut allocator, mut list, mut predicate) = (null, null, null); - assert_eq!( - create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), - S_OK - ); - assert_eq!( - create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), - S_OK - ); - let host = host_list(list).unwrap(); - let native = &host.list; - let buf = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: 16, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - ..Default::default() - }; - let default_heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; - assert_eq!( - crate::resource::create_committed( - null, - (&raw const default_heap).cast(), - 0, - (&raw const buf).cast(), - 0, - null.cast(), - &PAGEABLE_IIDS[0], - &mut predicate, - ), - S_OK - ); - let (predicate_data, _) = crate::resource::buffer_bytes(predicate).unwrap(); - - let create = |heap, desc: &D3D12_RESOURCE_DESC, state| -> ID3D12Resource { - let properties = D3D12_HEAP_PROPERTIES { - Type: heap, - ..Default::default() - }; - let mut resource = None; - // SAFETY: valid resource and heap descriptions and an initialized out pointer. - unsafe { - device - .device - .CreateCommittedResource( - &properties, - D3D12_HEAP_FLAG_NONE, - desc, - state, - None, - &mut resource, - ) - .unwrap(); - } - resource.unwrap() - }; - let target_desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: 1, - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, - Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, - ..buf - }; - let target = create( - D3D12_HEAP_TYPE_DEFAULT, - &target_desc, - D3D12_RESOURCE_STATE_RENDER_TARGET, - ); - let dest = create( - D3D12_HEAP_TYPE_DEFAULT, - &D3D12_RESOURCE_DESC { Width: 48, ..buf }, - D3D12_RESOURCE_STATE_COPY_DEST, - ); - let readback = create( - D3D12_HEAP_TYPE_READBACK, - &D3D12_RESOURCE_DESC { Width: 512, ..buf }, - D3D12_RESOURCE_STATE_COPY_DEST, - ); - let (upload, upload_data) = device.upload_buffer(80).unwrap(); - // SAFETY: the mapped upload has room for all three byte patterns. - unsafe { - upload_data.write_bytes(0x11, 48); - upload_data.add(48).write_bytes(0x22, 16); - upload_data.add(64).write_bytes(0x33, 16); - } - - let begin = slot::<Marker>(list, 0x1c8); - let mark = slot::<Marker>(list, 0x1c0); - let end = slot::<EndEvent>(list, 0x1d0); - let predicate_at = slot::<SetPredication>(list, 0xf8); - let label = b"predication test\0"; - begin(list, 1, label.as_ptr().cast(), label.len() as u32); - mark(list, 1, label.as_ptr().cast(), label.len() as u32); - end(list); - begin(list, 0, null.cast(), 1); - mark(list, 0, label.as_ptr().cast(), 0); - mark(list, 0, null.cast(), 0); - end(list); - - let rtv = device.rtv(Some(&target), None); - // SAFETY: the list is open and all resources outlive its execution. - // The texture copy locations borrow those resources without adding refs. - unsafe { - native.ClearRenderTargetView(rtv, &[1.0, 0.0, 0.0, 1.0], None); - native.CopyBufferRegion(&dest, 0, &upload, 0, 48); - - predicate_at(list, predicate, 0, 0); - predicate_at(list, predicate, 8, u32::MAX); - predicate_at(list, predicate, 1, 0); - native.CopyBufferRegion(&dest, 0, &upload, 48, 16); - predicate_at(list, predicate, 8, 0); - native.CopyBufferRegion(&dest, 16, &upload, 48, 16); - predicate_at(list, predicate, 8, 1); - predicate_at(list, null, 0, 0); - native.CopyBufferRegion(&dest, 32, &upload, 64, 16); - - native.ResourceBarrier(&[ - crate::host::transition( - &dest, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_COPY_SOURCE, - ), - crate::host::transition( - &target, - D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_COPY_SOURCE, - ), - ]); - native.CopyBufferRegion(&readback, 256, &dest, 0, 48); - native.CopyTextureRegion( - &D3D12_TEXTURE_COPY_LOCATION { - pResource: std::mem::transmute_copy(&readback), - Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { - Offset: 0, - Footprint: D3D12_SUBRESOURCE_FOOTPRINT { - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - Width: 1, - Height: 1, - Depth: 1, - RowPitch: 256, - }, - }, - }, - }, - 0, - 0, - 0, - &D3D12_TEXTURE_COPY_LOCATION { - pResource: std::mem::transmute_copy(&target), - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: 0, - }, - }, - None, - ); - } - - // SAFETY: these two predicate values fit in the guest buffer. Write - // after recording so only a submission-time fill observes them. - unsafe { predicate_data.cast::<[u64; 2]>().write_unaligned([0, 1]) }; - host.close(); - device.execute(&[&host]); - // SAFETY: execution has finished and the readback contains 512 bytes. - unsafe { - device.device.GetDeviceRemovedReason().unwrap(); - let mut mapped = std::ptr::null_mut(); - readback - .Map( - 0, - Some(&D3D12_RANGE { Begin: 0, End: 304 }), - Some(&mut mapped), - ) - .unwrap(); - let bytes = std::slice::from_raw_parts(mapped.cast::<u8>(), 304); - assert_eq!(&bytes[..4], &[255, 0, 0, 255]); - assert_eq!(&bytes[256..272], &[0x11; 16], "zero skips the copy"); - assert_eq!(&bytes[272..288], &[0x22; 16], "one allows the copy"); - assert_eq!(&bytes[288..304], &[0x33; 16], "disabling allows the copy"); - readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); - } - - fn release_native(object: impl Interface) -> u32 { - // SAFETY: all COM vtables begin with IUnknown. Release consumes the owned reference. - unsafe { (object.assume_vtable::<IUnknown>().Release)(object.into_raw()) } - } - let native = native.clone(); - let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); - assert_eq!(release(list), 0); - assert_eq!(release(allocator), 0); - assert_eq!(release(predicate), 0); - assert_eq!(release_native(native), 0); - for resource in [target, dest, readback, upload] { - assert_eq!(release_native(resource), 0); - } + fn a_copy_goes_to_the_gpu_only_when_both_sides_have_a_host_copy() { + assert_eq!(copy_plan(true, true, true), CopyPlan::Gpu); + assert_eq!(copy_plan(true, true, false), CopyPlan::Title); + assert_eq!(copy_plan(true, false, true), CopyPlan::Title); + assert_eq!(copy_plan(true, false, false), CopyPlan::Title); + assert_eq!(copy_plan(false, true, true), CopyPlan::Title); } } diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs new file mode 100644 index 0000000000..e1a81fec2d --- /dev/null +++ b/crates/victory-gpu/src/memory.rs @@ -0,0 +1,340 @@ +//! Title memory by address, for translated shaders that read and write +//! through raw 40-bit addresses (`victory_shader::emit::SLOT_MEMORY`: the +//! console's ray-tracing structure builder and the programs that walk its +//! structures; the structures themselves lie in plain title memory, in no +//! buffer object). +//! +//! The copies are the ones every other access uses ([`crate::shadow`]: a +//! title buffer's copy, or the 4 MiB window of memory outside buffers), so +//! a root view and a raw address reach the same host bytes. This module +//! keeps what a shader needs to find them: +//! +//! - the **directory**: per 64 KiB page of title address space the number +//! of the copy that holds the page (0: none) and the page's byte offset +//! in it; one buffer for all lists, entries only ever go from empty to +//! filled; +//! - per view heap a run of slots with a raw unordered access view of each +//! numbered copy (slot 0 of the run: a null view, for pages without a +//! copy); +//! - the **faults**: the page numbers shaders found empty, read back here +//! once a frame, so the copies exist from the next frame on. A pointer a +//! shader takes out of memory cannot be known before it runs; the +//! addresses a dispatch is given as root views are made ready before it. +//! +//! **A page that is not there when a shader touches it is a lost access**: +//! the read gives 0, the store is dropped, and the fault note only helps +//! the next frame. For the structure builder that is the same as a dropped +//! stage, so before a dispatch the host makes ready everything it can see +//! the dispatch name: the whole copy around each root view, around each +//! pair of root constants that is a title address and around each root +//! constant that is one in 256-byte units (the builder passes structures +//! all three ways), and the 4 MiB after each (a structure may cross a +//! window's end). +//! shortcut: what a stage reaches only through pointers it reads out of +//! memory (InitHeaders' table of structure addresses, LoadInstances' +//! instance records) is not made ready unless something else named it; +//! the fault count in the log says whether that happens. The whole answer +//! is the extent of the title's allocation around an address, which the +//! memory module of the layer knows and this one does not ask yet. +//! +//! shortcut: a copy that is numbered is kept for the rest of the run, and +//! there are at most [`COPIES`] of them (4 MiB windows mostly: 4 GiB at +//! most). Every dispatch of such a shader brings all numbered copies up to +//! date and, if it can store, declares all of them written (the bytes are +//! compared on the CPU afterwards, as for any unordered access view): a +//! dirty-page mask written by the shader would bound both. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES}; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::descriptor::host::HostHeap; +use crate::host::{HostList, host}; +use crate::shadow::Shadow; + +/// Copies that can be numbered (the run of heap slots is one longer). A +/// listed frame of the opening cutscene names about 50 windows. +const COPIES: u32 = 1023; +/// A window of memory outside buffers (`shadow.rs`). +const CELL: u64 = 4 << 20; +/// A directory page. +const PAGE: u64 = 1 << 16; + +struct Memory { + /// Buffer, its mapping, its GPU address. + directory: (ID3D12Resource, *mut u32, u64), + faults: (ID3D12Resource, *mut u32, u64), + /// Copy `n` is `copies[n - 1]`. + copies: Vec<Arc<Shadow>>, + /// Per host view heap (by address): the first slot of its run, and how + /// many copies have their view there. + heaps: HashMap<usize, (u32, u32)>, + /// The frame the faults were last read in. + frame: u64, + /// Pages asked for this frame that are not the title's memory. + refused: std::collections::HashSet<u64>, +} + +// SAFETY: the mappings are of buffers the struct owns; all access is under +// the mutex. +unsafe impl Send for Memory {} + +static MEMORY: Mutex<Option<Memory>> = Mutex::new(None); + +/// What a draw binds. +pub(crate) struct Ready { + pub(crate) directory: u64, + pub(crate) faults: u64, + /// The view heap slot of the null view; copy `n`'s view is `n` further. + pub(crate) base: u32, +} + +impl Memory { + fn new() -> Option<Memory> { + let host = host()?; + let make = |dwords: u64, what: &str| { + let (buffer, data) = host.shared_buffer(dwords * 4)?; + crate::host::name(&buffer, || format!("title memory by address: {what}")); + // SAFETY: a fresh mapping of at least that many bytes. + unsafe { std::ptr::write_bytes(data, 0, (dwords * 4) as usize) }; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + Some((buffer, data.cast::<u32>(), gpu)) + }; + tracing::info!("title memory by address: a shader reads or writes through raw addresses"); + Some(Memory { + directory: make(u64::from(MEMORY_PAGES) * 2, "directory")?, + faults: make(u64::from(MEMORY_FAULTS), "faults")?, + copies: Vec::new(), + heaps: HashMap::new(), + frame: u64::MAX, + refused: Default::default(), + }) + } + + /// Gives the page of `address` its copy, if it has none and the memory + /// is the title's. + fn map(&mut self, address: u64) { + let page = address / PAGE; + // The last entry stays empty: addresses past the directory read it. + if page >= u64::from(MEMORY_PAGES) - 1 { + return; + } + // SAFETY: inside the directory's mapping. + let entry = unsafe { self.directory.1.add(page as usize * 2) }; + // SAFETY: as above. + if unsafe { entry.read() } != 0 { + return; + } + let start = page * PAGE; + // A shader's pointer, or a constant taken for an address, may be + // anything: only memory the title has. + if self.refused.contains(&page) { + return; + } + if !crate::texture::committed(start as *const u8, PAGE as usize) { + self.refused.insert(page); + return; + } + // The copy a root view at that address would get; a buffer that + // ends inside the page is passed over for what holds all of it. + let whole = |s: &Arc<Shadow>| s.offset_in(start).is_some_and(|_| s.left(start) >= PAGE); + let Some(shadow) = crate::shadow::find(start, 1) + .filter(whole) + .or_else(|| crate::shadow::find(start, PAGE).filter(whole)) + else { + return; + }; + // SAFETY: a live buffer. + let flags = unsafe { shadow.buffer.GetDesc() }.Flags; + if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { + return; + } + let n = match self.copies.iter().position(|c| Arc::ptr_eq(c, &shadow)) { + Some(n) => n, + None if self.copies.len() < COPIES as usize => { + self.copies.push(shadow.clone()); + let n = self.copies.len() - 1; + // Every page the copy holds whole, not only the one asked + // for: a structure is more than 64 KiB. + // shortcut: a page of a title buffer inside this one that + // has a copy of its own is given this copy too. + let (first, len) = shadow.span(); + let mut at = first.next_multiple_of(PAGE); + while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 { + // SAFETY: inside the directory's mapping. + let other = unsafe { self.directory.1.add((at / PAGE) as usize * 2) }; + // SAFETY: as above; the offset first, as below. + unsafe { + if other.read() == 0 { + other.add(1).write_volatile((at - first) as u32); + other.write_volatile(n as u32 + 1); + } + } + at += PAGE; + } + n + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros") + }); + return; + } + }; + let offset = shadow.offset_in(start).unwrap_or(0); + // The offset first: a shader that sees the number sees it too. + // SAFETY: inside the directory's mapping. + unsafe { + entry.add(1).write_volatile(offset as u32); + entry.write_volatile(n as u32 + 1); + } + } + + /// The pages shaders found empty since the last frame. + fn take_faults(&mut self) { + let mut pages = Vec::new(); + for i in 1..MEMORY_FAULTS as usize { + // SAFETY: inside the faults' mapping; the GPU may be writing, + // a number missed now is written again next frame. + let at = unsafe { self.faults.1.add(i) }; + // SAFETY: as above. + let page = unsafe { at.read_volatile() }; + if page != 0 { + pages.push(page); + // SAFETY: as above. + unsafe { at.write_volatile(0) }; + } + } + if !pages.is_empty() { + // Each is an access that read 0 or was dropped. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 50 { + tracing::warn!( + pages = pages.len(), + first = format_args!("{:#x}", u64::from(pages[0]) * PAGE), + "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now" + ); + } + } + for page in pages { + self.map(u64::from(page) * PAGE); + } + } + + /// What a dispatch names: the copy around `address` and the 4 MiB + /// after it. + fn name(&mut self, address: u64) { + self.map(address); + self.map((address & !(CELL - 1)) + CELL); + } +} + +/// Before a draw whose shader reads title memory by address: what its +/// root arguments name gets its copies (`addresses`: its root views; +/// `constants`: its root constants, see the module), every numbered copy +/// has its view in `heap`'s run and is brought up to date when `list` is +/// submitted (and, with `writes`, copied back after). None if the host +/// cannot hold it; the draw is then dropped. +pub(crate) fn ready( + list: &HostList, + heap: &HostHeap, + addresses: &[u64], + constants: &[u32], + writes: bool, +) -> Option<Ready> { + let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); + if guard.is_none() { + *guard = Memory::new(); + } + let m = guard.as_mut()?; + let frame = crate::frame::current(); + if m.frame != frame { + m.frame = frame; + m.refused.clear(); + m.take_faults(); + } + let numbered = m.copies.len(); + for &address in addresses { + m.name(address); + } + // A title address in two constants (low dword, then bits 32 to 39), or + // in one in 256-byte units. A constant that only looks like one names + // memory nothing reads; one that is not the title's memory is refused. + for (i, &c) in constants.iter().enumerate() { + if let Some(&high) = constants.get(i + 1) + && (1..=0xFF).contains(&high) + && c >= 0x1_0000 + { + m.name(u64::from(c) | u64::from(high) << 32); + } + if c >= 0x0100_0000 { + m.name(u64::from(c) << 8); + } + } + let key = std::ptr::from_ref(heap) as usize; + let (base, made) = match m.heaps.get(&key) { + Some(&run) => run, + None => { + // Held for the heap's life: not given back with a list's slots. + let base = heap.dynamic(COPIES + 1)?; + heap.null_raw_uav_at(base); + (base, 0) + } + }; + for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) { + let (_, len) = shadow.span(); + heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); + } + m.heaps.insert(key, (base, m.copies.len() as u32)); + // Once per list, and for copies numbered since: the builder alone + // dispatches hundreds of times a frame. + // shortcut: a copy another list numbers meanwhile is brought up to date + // by that list's submission, which may run after this one's. + const READ: usize = usize::MAX - 0x6d; + const WRITE: usize = usize::MAX - 0x6e; + let first_read = list.first_use(READ); + let first_write = writes && list.first_use(WRITE); + for (n, shadow) in m.copies.iter().enumerate() { + let (start, len) = shadow.span(); + if first_read || n >= numbered { + shadow.refresh(list, start, len); + } + if writes && (first_write || n >= numbered) { + shadow.gpu_writes(list, start, len); + } + } + if first_read { + list.keep(&m.directory.0); + list.keep(&m.faults.0); + } + Some(Ready { + directory: m.directory.2, + faults: m.faults.2, + base, + }) +} + +/// Forgets the run of title-memory views kept for host view heap `heap` +/// (`Memory::heaps`, by address), when the title releases its heap. A heap +/// made later at the same address found the old run: its null view and the +/// copies' views were never written there, and the run's first slot could +/// lie among the new heap's title slots or past its end, so shaders reading +/// through raw addresses indexed views that were not theirs. (Fork pull +/// request #589, AscilCH.) +pub(crate) fn forget_heap(heap: &HostHeap) { + let key = std::ptr::from_ref(heap) as usize; + if let Some(m) = MEMORY.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + m.heaps.remove(&key); + } +} + +/// Whether a run of title-memory views is kept for the host view heap at +/// address `key` (tests). +#[cfg(test)] +pub(crate) fn has_run(key: usize) -> bool { + MEMORY.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.heaps.contains_key(&key)) +} diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index 99a264e9e8..a60a484c33 100644 --- a/crates/victory-gpu/src/object.rs +++ b/crates/victory-gpu/src/object.rs @@ -61,34 +61,6 @@ impl Object { pub(crate) type This = *const Object; -/// A reference to one of our objects held by work that runs later (on a -/// queue held back by a wait), given back on drop. -pub(crate) struct Held(This); - -// SAFETY: our objects are made for use from many threads (counts atomic, -// state locked). -unsafe impl Send for Held {} - -impl Held { - pub(crate) fn new(this: This) -> Held { - add_ref(this); - Held(this) - } - - pub(crate) fn get(&self) -> This { - self.0 - } -} - -impl Drop for Held { - fn drop(&mut self) { - // SAFETY: one of our objects; slot 2 of its table is `Release`. - let release: extern "system" fn(This) -> u32 = - unsafe { std::mem::transmute(*(*self.0).functions.add(2)) }; - release(self.0); - } -} - #[repr(transparent)] pub(crate) struct Table<const N: usize>(pub [*const (); N]); // SAFETY: function addresses only. @@ -99,6 +71,15 @@ pub(crate) extern "system" fn add_ref(this: This) -> u32 { unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 } +/// Adds a reference to an object that has one; false if it has none any +/// more (its last one is being released). +#[cfg(windows)] +pub(crate) fn add_ref_alive(this: This) -> bool { + // SAFETY: `this` is one of our objects, not freed yet. + let refs = &unsafe { &*this }.refs; + refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n > 0).then(|| n + 1)).is_ok() +} + pub(crate) extern "system" fn release(this: This) -> u32 { // SAFETY: `this` is one of our objects. let refs = &unsafe { &*this }.refs; @@ -129,13 +110,10 @@ pub(crate) fn answer(kind: usize, iid: *const Iid, found: Option<This>, out: *mu hr } -/// `IUnknown`, which every COM object answers for. -pub(crate) const IUNKNOWN: Iid = guid(0, 0, 0, [0xc0, 0, 0, 0, 0, 0, 0, 0x46]); - -/// Whether `iid` is one of `known`, or `IUnknown`. +/// Whether `iid` is one of `known`. pub(crate) fn is(iid: *const Iid, known: &[Iid]) -> bool { // SAFETY: the title passes an interface id (null is tolerated). - unsafe { iid.as_ref() }.is_some_and(|i| *i == IUNKNOWN || known.contains(i)) + unsafe { iid.as_ref() }.is_some_and(|i| known.contains(i)) } /// Hands a new object to the title as one of `known`, or drops it. `T` @@ -164,16 +142,7 @@ pub(crate) fn release_boxed<T>(this: This) -> u32 { let refs = &unsafe { &*this }.refs; match refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) { Ok(1) => { - let address = this as usize; - let keys = (address, [u8::MIN; 16])..=(address, [u8::MAX; 16]); - { - let mut data = private_data(); - // An object's IDs are contiguous in key order. Seek directly to - // them so releases don't visit private data held by other objects. - while let Some((&key, _)) = data.range(keys.clone()).next() { - data.remove(&key); - } - } + private_data().retain(|&(object, _), _| object != this as usize); // SAFETY: that was the last reference to a `Box<T>`. drop(unsafe { Box::from_raw(this.cast_mut().cast::<T>()) }); 0 @@ -410,142 +379,6 @@ pub(crate) fn slot<F: Copy>(object: This, offset: usize) -> F { mod tests { use super::*; - const TAG: Iid = [1; 16]; - const OTHER_TAG: Iid = [2; 16]; - - extern "system" fn release_test_object(this: This) -> u32 { - release_boxed::<Object>(this) - } - - fn new_test_object() -> This { - static TABLE: Table<7> = { - let mut functions = d3d12_object(missing_table::<DEVICE, 7>()); - functions[2] = release_test_object as *const (); - Table(functions) - }; - let mut this = std::ptr::null(); - assert_eq!( - hand_out( - DEVICE, - Box::new(Object::new(&TABLE)), - &TAG, - &[TAG], - &mut this - ), - S_OK - ); - this - } - - #[test] - fn private_data_is_scoped_to_object_and_id() { - let first = new_test_object(); - let second = new_test_object(); - let set = - slot::<extern "system" fn(This, *const Iid, u32, *const u8) -> HRESULT>(first, 0x20); - let get = - slot::<extern "system" fn(This, *const Iid, *mut u32, *mut u8) -> HRESULT>(first, 0x18); - let release = slot::<extern "system" fn(This) -> u32>(first, 0x10); - - assert_eq!(set(first, &TAG, 1, b"a".as_ptr()), S_OK); - assert_eq!(set(first, &OTHER_TAG, 0, b"".as_ptr()), S_OK); - assert_eq!(set(second, &TAG, 2, b"bc".as_ptr()), S_OK); - assert_eq!(set(first, &TAG, 3, b"def".as_ptr()), S_OK); - assert_eq!(add_ref(first), 2); - assert_eq!(release(first), 1); - - let mut size = 0; - let mut data = [0; 3]; - assert_eq!(get(first, &TAG, &mut size, std::ptr::null_mut()), S_OK); - assert_eq!(size, 3); - size = 1; - assert_eq!(get(first, &TAG, &mut size, data.as_mut_ptr()), MORE_DATA); - assert_eq!(size, 3); - assert_eq!(data, [0; 3]); - assert_eq!(get(first, &TAG, &mut size, data.as_mut_ptr()), S_OK); - assert_eq!(&data, b"def"); - - assert_eq!(set(first, &TAG, 99, std::ptr::null()), S_OK); - assert_eq!(get(first, &TAG, &mut size, data.as_mut_ptr()), NOT_FOUND); - assert_eq!(size, 0); - assert_eq!(get(first, &OTHER_TAG, &mut size, data.as_mut_ptr()), S_OK); - assert_eq!(size, 0); - assert_eq!(release(first), 0); - size = 3; - assert_eq!(get(second, &TAG, &mut size, data.as_mut_ptr()), S_OK); - assert_eq!(&data[..size as usize], b"bc"); - assert_eq!(release(second), 0); - } - - #[test] - #[ignore = "synthetic release benchmark; run with --release --ignored --nocapture"] - fn benchmark_private_data_release() { - use std::hint::black_box; - use std::time::Instant; - - const RELEASES: usize = 50_000; - for count in [128, 512, 1024] { - let live: Vec<_> = (0..count).map(|_| new_test_object()).collect(); - let set = slot::<extern "system" fn(This, *const Iid, u32, *const u8) -> HRESULT>( - live[0], 0x20, - ); - let release = slot::<extern "system" fn(This) -> u32>(live[0], 0x10); - for &object in &live { - assert_eq!(set(object, &TAG, 1, b"a".as_ptr()), S_OK); - } - let mut samples = [0.0; 5]; - for sample in &mut samples { - let mut retiring: Vec<_> = (0..256).map(|_| new_test_object()).collect(); - let retiring_count = retiring.len(); - let start = Instant::now(); - for index in 0..RELEASES { - let object = new_test_object(); - if index % 4 == 0 { - assert_eq!(set(object, &TAG, 1, b"b".as_ptr()), S_OK); - } - let old = std::mem::replace(&mut retiring[index % retiring_count], object); - black_box(release(black_box(old))); - } - *sample = start.elapsed().as_secs_f64() * 1e9 / RELEASES as f64; - for object in retiring { - assert_eq!(release(object), 0); - } - } - samples.sort_by(f64::total_cmp); - println!( - "{count:4} live entries: {:8.1} ns/object (median)", - samples[2] - ); - for object in live { - assert_eq!(release(object), 0); - } - } - } - - #[test] - fn final_release_clears_private_data_before_drop() { - #[repr(C)] - struct OwnedObject(Object); - - impl Drop for OwnedObject { - fn drop(&mut self) { - let address = std::ptr::from_ref(&self.0) as usize; - let data = private_data(); - assert!(!data.contains_key(&(address, [u8::MIN; 16]))); - assert!(!data.contains_key(&(address, TAG))); - assert!(!data.contains_key(&(address, [u8::MAX; 16]))); - } - } - - static TABLE: Table<0> = Table([]); - let this: This = Box::into_raw(Box::new(OwnedObject(Object::new(&TABLE)))).cast(); - assert_eq!(add_ref(this), 1); - for id in [[u8::MIN; 16], TAG, [u8::MAX; 16]] { - assert_eq!(set_private_data(this, &id, 1, b"a".as_ptr()), S_OK); - } - assert_eq!(release_boxed::<OwnedObject>(this), 0); - } - #[test] fn guids_round_trip_through_text() { let g = guid( @@ -557,36 +390,4 @@ mod tests { assert_eq!(g[..4], [0xf1, 0x19, 0x98, 0x18]); assert_eq!(guid_text(&g), "189819f1-1db6-4b57-be54-1821339b85f7"); } - - /// Every COM object answers for `IUnknown`, and with one pointer - /// whichever of its interfaces is asked: the object's identity. - #[test] - fn every_object_answers_for_iunknown() { - type Query = extern "system" fn(This, *const Iid, *mut This) -> HRESULT; - let unknown = |object: This| { - let mut found = std::ptr::null(); - let hr = slot::<Query>(object, 0)(object, &IUNKNOWN, &mut found); - (hr, found) - }; - let device = crate::device::device(); - let mut fence = std::ptr::null(); - let fence_iid = &crate::fence::FENCE_IIDS[0]; - assert_eq!( - crate::fence::create(std::ptr::null(), 0, 0, fence_iid, &mut fence), - S_OK - ); - assert_eq!(unknown(device), (S_OK, device)); - assert_eq!(unknown(fence), (S_OK, fence)); - // The DXGI device is the same object as the device it answers for. - assert_eq!(unknown(crate::dxgi::device()), (S_OK, device)); - // An id nobody has is still nobody's. - let mut found = fence; - let nobodys = guid(0x189819f1, 0x1db6, 0x4b57, [0xbe; 8]); - assert_eq!( - slot::<Query>(fence, 0)(fence, &nobodys, &mut found), - E_NOINTERFACE - ); - assert!(found.is_null()); - slot::<extern "system" fn(This) -> u32>(fence, 0x10)(fence); - } } diff --git a/crates/victory-gpu/src/over.rs b/crates/victory-gpu/src/over.rs new file mode 100644 index 0000000000..e2385c6c69 --- /dev/null +++ b/crates/victory-gpu/src/over.rs @@ -0,0 +1,560 @@ +//! A present's second plane, drawn over the first in our window. +//! +//! The console's display composes the planes of a present. The title in +//! its Series S mode presents two: its game image at 1920x1080 and its +//! interface at 3840x2160, whose empty texels are zero with alpha zero. A +//! window showing the first plane alone is black wherever the game plane +//! is, the menus and loading screens included. +//! +//! The pass here draws the second plane over the back buffer once the first +//! has been copied there: one triangle, the plane sampled across the whole +//! buffer (stretched to it), blended by its alpha. +//! +//! shortcut: the alpha is taken as premultiplied (what an interface drawn +//! onto a cleared target with the usual blending holds); planes after the +//! second, and the placement and scaling a plane's parameters can ask for, +//! are not read. + +use std::sync::Mutex; + +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + +pub(crate) mod temporal; + +const SOURCE: &str = r#" +Texture2D<float4> plane : register(t0); +SamplerState bilinear : register(s0); +struct Corner { float4 position : SV_Position; float2 at : TEXCOORD0; }; +Corner corner(uint i : SV_VertexID) { + Corner c; + c.at = float2(float(i & 1) * 2.0, float(i >> 1) * 2.0); + c.position = float4(c.at.x * 2.0 - 1.0, 1.0 - c.at.y * 2.0, 0.0, 1.0); + return c; +} +float4 over(Corner c) : SV_Target { return plane.Sample(bilinear, c.at); } +"#; + +/// Views kept until the list that uses them has run: a present can be sent +/// ahead of the card, so a view is not reused for this many presents. +/// +/// shortcut: a fixed count, not derived from how many presents are in +/// flight. Presents sent ahead each hold a back buffer and the swap chain +/// has two, so no more than a few lists are ever waiting; 16 is well past +/// that. +const RING: u32 = 16; + +struct Pass { + format: i32, + root: ID3D12RootSignature, + pipeline: ID3D12PipelineState, + targets: ID3D12DescriptorHeap, + views: ID3D12DescriptorHeap, + target_step: usize, + view_step: u32, + next: u32, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Pass {} + +static PASS: Mutex<Option<Pass>> = Mutex::new(None); + +/// A bilinear, clamping sampler at `s0` for the stages `visibility` names. +fn bilinear(visibility: D3D12_SHADER_VISIBILITY) -> D3D12_STATIC_SAMPLER_DESC { + D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + MaxLOD: f32::MAX, + ShaderRegister: 0, + RegisterSpace: 0, + ShaderVisibility: visibility, + ..Default::default() + } +} + +/// A root signature of `parameters` and one bilinear sampler, serialized by +/// the runtime and not taken from a shader: the system compiler under Wine +/// compiles a `[RootSignature]` attribute without writing the signature +/// into the shader, and `CreateRootSignature` then fails on it (#188). +fn root_signature( + device: &ID3D12Device, + parameters: &[D3D12_ROOT_PARAMETER], + sampler: D3D12_SHADER_VISIBILITY, + flags: D3D12_ROOT_SIGNATURE_FLAGS, +) -> windows::core::Result<ID3D12RootSignature> { + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let samplers = [bilinear(sampler)]; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: parameters.len() as u32, + pParameters: parameters.as_ptr(), + NumStaticSamplers: 1, + pStaticSamplers: samplers.as_ptr(), + Flags: flags, + }; + let mut blob: Option<ID3DBlob> = None; + // SAFETY: the description points at live slices; the blob is the + // runtime's own, read while it lives. + unsafe { + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None)?; + let blob = blob.ok_or_else(windows::core::Error::empty)?; + let bytes = + std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes) + } +} + +/// One descriptor range of one view at register 0, at `offset` in its table. +fn range(kind: D3D12_DESCRIPTOR_RANGE_TYPE, offset: u32) -> D3D12_DESCRIPTOR_RANGE { + D3D12_DESCRIPTOR_RANGE { + RangeType: kind, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: offset, + } +} + +/// A root parameter that is a table of `ranges`, for the stages `visibility` +/// names. +fn table(ranges: &[D3D12_DESCRIPTOR_RANGE], visibility: D3D12_SHADER_VISIBILITY) -> D3D12_ROOT_PARAMETER { + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { + NumDescriptorRanges: ranges.len() as u32, + pDescriptorRanges: ranges.as_ptr(), + }, + }, + ShaderVisibility: visibility, + } +} + +fn make(device: &ID3D12Device, format: DXGI_FORMAT) -> windows::core::Result<Pass> { + use windows::core::s; + let vs = crate::host::compile(SOURCE, s!("corner"), s!("vs_5_1"))?; + let ps = crate::host::compile(SOURCE, s!("over"), s!("ps_5_1"))?; + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let plane = [range(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0)]; + let root = root_signature( + device, + &[table(&plane, D3D12_SHADER_VISIBILITY_PIXEL)], + D3D12_SHADER_VISIBILITY_PIXEL, + D3D12_ROOT_SIGNATURE_FLAG_NONE, + )?; + // SAFETY: the description points at live data and never releases its + // pointer. + unsafe { + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs[..]), + PS: code(&ps[..]), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + desc.RTVFormats[0] = format; + desc.BlendState.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { + BlendEnable: true.into(), + SrcBlend: D3D12_BLEND_ONE, + DestBlend: D3D12_BLEND_INV_SRC_ALPHA, + BlendOp: D3D12_BLEND_OP_ADD, + SrcBlendAlpha: D3D12_BLEND_ONE, + DestBlendAlpha: D3D12_BLEND_INV_SRC_ALPHA, + BlendOpAlpha: D3D12_BLEND_OP_ADD, + RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?; + let targets: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: RING, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + })?; + let views: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: RING, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })?; + Ok(Pass { + format: format.0, + root, + pipeline, + target_step: device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) + as usize, + view_step: device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + targets, + views, + next: 0, + }) + } +} + +/// Records into `list` the draw of `plane` (readable by pixel shaders, read +/// as `plane_format`) over `back` (in the render-target state, `width` by +/// `height`, of `format`). False if the pass could not be made: nothing was +/// recorded then. +/// +/// The pass sets the list's descriptor heap, root signature, pipeline, +/// target, viewport, scissor and topology and puts none of them back: it is +/// for a list of ours that records nothing of the title's. +pub(crate) fn record( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + back: &ID3D12Resource, + format: DXGI_FORMAT, + (width, height): (u32, u32), + plane: &ID3D12Resource, + plane_format: DXGI_FORMAT, +) -> bool { + let mut pass = PASS.lock().unwrap_or_else(|e| e.into_inner()); + if pass.as_ref().is_none_or(|p| p.format != format.0) { + *pass = match make(device, format) { + Ok(p) => Some(p), + Err(e) => { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::warn!(error = %e, "no pass to draw a present's second plane: it is not shown"); + }); + return false; + } + }; + tracing::info!(format = format.0, "a present's second plane is drawn over the first"); + } + let Some(p) = pass.as_mut() else { return false }; + let slot = p.next % RING; + p.next = p.next.wrapping_add(1); + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: plane_format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 1, + ..Default::default() + }, + }, + }; + let target_desc = D3D12_RENDER_TARGET_VIEW_DESC { + Format: format, + ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + // SAFETY: an open list; slots of our heaps; live resources and objects + // (the pass's own live as long as the process or until remade, and a + // list holds what it was recorded with). + unsafe { + let target = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: p.targets.GetCPUDescriptorHandleForHeapStart().ptr + slot as usize * p.target_step, + }; + let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: p.views.GetCPUDescriptorHandleForHeapStart().ptr + + (slot * p.view_step) as usize, + }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: p.views.GetGPUDescriptorHandleForHeapStart().ptr + + u64::from(slot * p.view_step), + }; + device.CreateRenderTargetView(back, Some(&target_desc), target); + device.CreateShaderResourceView(plane, Some(&view), cpu); + list.SetDescriptorHeaps(&[Some(p.views.clone())]); + list.SetGraphicsRootSignature(&p.root); + list.SetPipelineState(&p.pipeline); + list.SetGraphicsRootDescriptorTable(0, gpu); + list.OMSetRenderTargets(1, Some(&target), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: width as f32, + Height: height as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }]); + list.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4)); + list.DrawInstanced(3, 1, 0, 0); + } + true +} + +// --------------------------------------------------------------------------- +// The upscaler's output, by a plain stretch +// --------------------------------------------------------------------------- + +/// The title in its Series S mode renders below its output size and has the +/// console's upscaler (its `ffxDispatch`) write the output. That upscaler's +/// passes are compute pipelines in a container we do not translate, so the +/// output stayed black. This pass stands in for it: each output texel is the +/// bilinear sample of the rendered part of the colour input. +/// +/// shortcut: no temporal accumulation, sharpening or use of the depth and +/// motion inputs: an image, not the upscaler's quality. +const STRETCH: &str = r#" +cbuffer Sizes : register(b0) { float2 scale; float2 texel; }; +Texture2D<float4> source : register(t0); +RWTexture2D<float4> target : register(u0); +SamplerState bilinear : register(s0); +[numthreads(8, 8, 1)] +void stretch(uint3 id : SV_DispatchThreadID) { + // Groups are 8 by 8: the last ones reach past a size that is not a + // multiple of 8. + uint width, height; + target.GetDimensions(width, height); + if (id.x >= width || id.y >= height) return; + float2 at = (float2(id.xy) + 0.5) * texel * scale; + // The rendered size can be the top left of a larger texture: stay half a + // texel inside it, or the filter takes in what is beside it. + uint sw, sh; + source.GetDimensions(sw, sh); + at = min(at, scale - 0.5 / float2(sw, sh)); + target[id.xy] = source.SampleLevel(bilinear, at, 0); +} +"#; + +struct Stretch { + root: ID3D12RootSignature, + pipeline: ID3D12PipelineState, + views: ID3D12DescriptorHeap, + step: u32, + next: u32, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Stretch {} + +static STRETCHER: Mutex<Option<Stretch>> = Mutex::new(None); + +/// Views of a stretch are kept this many stretches (two views each). +/// +/// shortcut: a fixed count. The title dispatches the upscaler once a frame +/// and a list runs within the frames the title keeps in flight; 64 frames +/// is far more than it keeps. +const STRETCH_RING: u32 = 64; + +fn make_stretch(device: &ID3D12Device) -> windows::core::Result<Stretch> { + use windows::core::s; + let cs = crate::host::compile(STRETCH, s!("stretch"), s!("cs_5_1"))?; + let views = [ + range(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0), + range(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1), + ]; + let sizes = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: 4, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let root = root_signature( + device, + &[sizes, table(&views, D3D12_SHADER_VISIBILITY_ALL)], + D3D12_SHADER_VISIBILITY_ALL, + D3D12_ROOT_SIGNATURE_FLAG_NONE, + )?; + // SAFETY: the description points at live data and never releases its + // pointer. + unsafe { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = device.CreateComputePipelineState(&desc)?; + let views: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: STRETCH_RING * 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })?; + Ok(Stretch { + root, + pipeline, + step: device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + views, + next: 0, + }) + } +} + +/// A typeless colour format as the typed one shaders read and write. +fn typed(format: DXGI_FORMAT) -> DXGI_FORMAT { + DXGI_FORMAT(match format.0 { + 1 => 2, + 9 => 10, + 23 => 24, + 27 => 28, + // R32G32_TYPELESS and R16G16_TYPELESS: motion vectors. + 15 => 16, + 33 => 34, + f => f, + }) +} + +/// Records into `list` the stretch of the top-left `render` texels of +/// `source` (readable by compute shaders) over the whole of `target` (in +/// the unordered-access state). False if nothing was recorded. +/// +/// The pass sets the list's descriptor heap, compute root signature and +/// pipeline and puts none of them back: the caller replays the title's. +pub(crate) fn record_stretch( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + target: &ID3D12Resource, + source: &ID3D12Resource, + render: [u32; 2], +) -> bool { + // SAFETY: live resources. + let (to, from) = unsafe { (target.GetDesc(), source.GetDesc()) }; + if to.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 + || to.Width == 0 + || from.Width == 0 + { + return false; + } + let mut made = STRETCHER.lock().unwrap_or_else(|e| e.into_inner()); + if made.is_none() { + // Tried again at the next dispatch if it fails, as the pass over a + // present is: a failure need not last. + *made = match make_stretch(device) { + Ok(p) => { + tracing::info!("the upscaler's output is made by a plain stretch of its colour input"); + Some(p) + } + Err(e) => { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::warn!(error = %e, "no pass to stretch the upscaler's input: its output stays as it is"); + }); + None + } + }; + } + let Some(p) = made.as_mut() else { return false }; + let slot = (p.next % STRETCH_RING) * 2; + p.next = p.next.wrapping_add(1); + let (width, height) = (to.Width as u32, to.Height); + let rendered = [ + if render[0] == 0 { from.Width as u32 } else { render[0].min(from.Width as u32) }, + if render[1] == 0 { from.Height } else { render[1].min(from.Height) }, + ]; + let sizes = [ + rendered[0] as f32 / from.Width as f32, + rendered[1] as f32 / from.Height as f32, + 1.0 / width as f32, + 1.0 / height as f32, + ]; + let read = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: typed(from.Format), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 1, + ..Default::default() + }, + }, + }; + let written = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: typed(to.Format), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + // SAFETY: an open list; slots of our heap; live resources and objects + // (the pass's own live as long as the process). + unsafe { + let cpu = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: p.views.GetCPUDescriptorHandleForHeapStart().ptr + ((slot + i) * p.step) as usize, + }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: p.views.GetGPUDescriptorHandleForHeapStart().ptr + u64::from(slot * p.step), + }; + device.CreateShaderResourceView(source, Some(&read), cpu(0)); + device.CreateUnorderedAccessView(target, None, Some(&written), cpu(1)); + list.SetDescriptorHeaps(&[Some(p.views.clone())]); + list.SetComputeRootSignature(&p.root); + list.SetPipelineState(&p.pipeline); + list.SetComputeRoot32BitConstants(0, 4, sizes.as_ptr().cast(), 0); + list.SetComputeRootDescriptorTable(1, gpu); + list.Dispatch(width.div_ceil(8), height.div_ceil(8), 1); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Typeless colour formats are read and written as their typed ones; + /// typed formats, and formats with no typeless form here, stay. + #[test] + fn typeless_formats_get_their_typed_one() { + for (typeless, typed_one) in [(1, 2), (9, 10), (23, 24), (27, 28), (15, 16), (33, 34)] { + assert_eq!(typed(DXGI_FORMAT(typeless)).0, typed_one); + assert_eq!(typed(DXGI_FORMAT(typed_one)).0, typed_one); + } + // R11G11B10_FLOAT, R8G8B8A8_UNORM_SRGB and the FP16 stand-in's own. + for format in [26, 29, 10, 0] { + assert_eq!(typed(DXGI_FORMAT(format)).0, format); + } + } + + /// The passes' root signatures are serialized by the runtime: neither + /// source asks the compiler for one (Wine's writes none). + #[test] + fn the_sources_carry_no_root_signature() { + for source in [SOURCE, STRETCH] { + assert!(!source.contains("RootSignature")); + assert!(!source.contains("#define RS")); + } + } + + /// The stretch's source guards its writes: groups of 8 reach past sizes + /// that are not multiples of 8. + #[test] + fn the_stretch_writes_inside_its_target_only() { + assert!(STRETCH.contains("numthreads(8, 8, 1)")); + assert!(STRETCH.contains("if (id.x >= width || id.y >= height) return;")); + } +} + +#[cfg(test)] +mod readback; diff --git a/crates/victory-gpu/src/over/readback.rs b/crates/victory-gpu/src/over/readback.rs new file mode 100644 index 0000000000..dd42b07c4b --- /dev/null +++ b/crates/victory-gpu/src/over/readback.rs @@ -0,0 +1,178 @@ +//! GPU readback for the two Series S display passes. + +use super::*; + +/// Stretches a blue 3 by 2 scene to 5 by 3 and reads the result back, `None` +/// without a device. `padded`: the scene is the top left of a 4 by 3 texture +/// whose other texels are red, and the interface over it is empty; otherwise +/// the interface has a half green and a red strip. +fn stretched(padded: bool) -> Option<[[u8; 20]; 3]> { + use crate::host::{host, transition}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM as RGBA8; + let Some(host) = host() else { + eprintln!("no D3D12 device; skipping display readback"); + return None; + }; + let texture = |width: u32, height, flags, state| { + let mut resource: Option<ID3D12Resource> = None; + // SAFETY: plain creation of a texture with one RGBA8 subresource. + unsafe { + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(width), + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: RGBA8, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: flags, + ..Default::default() + }, + state, + None, + &mut resource, + ) + .unwrap(); + } + resource.unwrap() + }; + let sub = |r: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: the copy location borrows this resource. + pResource: unsafe { std::mem::transmute_copy(r) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let rows = |r: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: the copy location borrows this resource. + pResource: unsafe { std::mem::transmute_copy(r) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: RGBA8, + Width: 5, + Height: 3, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let uav = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + let rtv = D3D12_RESOURCE_STATE_RENDER_TARGET; + let (width, height) = if padded { (4, 3) } else { (3, 2) }; + let scene = texture(width, height, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, rtv); + let ui = texture(5, 3, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, rtv); + let target = texture( + 5, + 3, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + uav, + ); + let readback = host.read_back_buffer(768).unwrap(); + let commands = host.new_list().unwrap(); + let list = &commands.list; + // SAFETY: both views and all resources live through command completion. + unsafe { + let scene_view = host.rtv(Some(&scene), None); + let ui_view = host.rtv(Some(&ui), None); + list.ClearRenderTargetView(scene_view, &[1.0, 0.0, 0.0, 1.0], None); + let drawn = RECT { + left: 0, + right: 3, + top: 0, + bottom: 2, + }; + list.ClearRenderTargetView(scene_view, &[0.0, 0.0, 1.0, 1.0], Some(&[drawn])); + list.ClearRenderTargetView(ui_view, &[0.0; 4], None); + let strip = |left, right| RECT { + left, + right, + top: 0, + bottom: 3, + }; + if !padded { + list.ClearRenderTargetView( + ui_view, + &[0.0, 128.0 / 255.0, 0.0, 128.0 / 255.0], + Some(&[strip(2, 3)]), + ); + list.ClearRenderTargetView(ui_view, &[1.0, 0.0, 0.0, 1.0], Some(&[strip(3, 5)])); + } + list.ResourceBarrier(&[ + transition(&scene, rtv, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(&ui, rtv, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), + ]); + assert!(record_stretch(&host.device, list, &target, &scene, [3, 2])); + list.ResourceBarrier(&[transition(&target, uav, rtv)]); + assert!(record( + &host.device, + list, + &target, + RGBA8, + (5, 3), + &ui, + RGBA8 + )); + list.ResourceBarrier(&[transition(&target, rtv, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyTextureRegion(&rows(&readback), 0, 0, 0, &sub(&target), None); + } + commands.close(); + host.execute(&[&commands]); + // SAFETY: execute waited for the copy. Each row contains five texels. + let mut ptr = std::ptr::null_mut(); + let mut pixels = [[0u8; 20]; 3]; + unsafe { + readback.Map(0, None, Some(&mut ptr)).unwrap(); + for (y, row) in pixels.iter_mut().enumerate() { + row.copy_from_slice(std::slice::from_raw_parts( + ptr.cast::<u8>().add(y * 256), + 20, + )); + } + readback.Unmap(0, None); + } + Some(pixels) +} + +#[test] +fn stretch_and_overlay_preserve_the_expected_pixels() { + let Some(pixels) = stretched(false) else { + return; + }; + let expected = [ + [0, 0, 255, 255], + [0, 0, 255, 255], + [0, 128, 127, 255], + [255, 0, 0, 255], + [255, 0, 0, 255], + ]; + for row in pixels { + assert_eq!(&row[..], expected.as_flattened()); + } +} + +/// The title's colour is the top left of a larger texture: what is beside +/// the rendered size must not be filtered into the right and bottom edges. +#[test] +fn stretch_does_not_filter_in_what_is_beside_the_rendered_size() { + let Some(pixels) = stretched(true) else { + return; + }; + for row in pixels { + assert_eq!(&row[..], [[0u8, 0, 255, 255]; 5].as_flattened()); + } +} diff --git a/crates/victory-gpu/src/over/temporal.rs b/crates/victory-gpu/src/over/temporal.rs new file mode 100644 index 0000000000..2d99414b7e --- /dev/null +++ b/crates/victory-gpu/src/over/temporal.rs @@ -0,0 +1,663 @@ +//! The upscaler's output, by a temporal resolve (Try 6.7). +//! +//! The plain stretch (`super::record_stretch`) shows one frame's samples +//! and nothing more. The title draws hair with dithered transparency and +//! its soft shadows and screen-space passes with a few jittered samples a +//! texel, counting on the console's upscaler to average them over frames. +//! Shown one frame at a time they are dotted, see-through and shimmering. +//! +//! This pass does what that upscaler's accumulation does, in one compute +//! dispatch (the TAA/TAAU of the 2010s engines): +//! +//! * the colour input is sampled where the texel's sample really was: +//! the jitter the title passes is taken off; +//! * the image built so far (the history, at output size, ours) is moved +//! along the title's motion vectors to where this frame sees it, with a +//! Catmull-Rom filter, so it stays sharp; +//! * the history is clipped to the colours of this frame's 3x3 +//! neighbourhood (variance clipping in YCoCg, within its minimum and +//! maximum), so what moved or was uncovered does not trail; +//! * the two are blended, a tenth of the new frame by default, in a +//! tonemapped space so lone bright texels do not flash; +//! * a little of the detail against the neighbourhood's mean is added +//! back (sharpening, the title's own amount when it asks for it). +//! +//! The history is two buffers of half-precision texels, ping-ponged: +//! buffers promote to unordered access by themselves and decay back after +//! each submission, so no state of ours is tracked. It starts again when +//! the output size changes, when the title asks (a camera cut), and after +//! a long gap between dispatches (a loading screen). +//! +//! `VICTORY_UPSCALE_TEMPORAL=0` brings back the plain stretch; +//! `VICTORY_UPSCALE_FEEDBACK` (percent of the new frame, 10) and +//! `VICTORY_UPSCALE_SHARPEN` (percent, 10) tune it. +//! +//! Try 6.10: this frame's colour is taken by Catmull-Rom (one bilinear tap +//! before), clipped to its neighbourhood, and sharpened against a smooth +//! tent blur instead of the nearest rendered texel's 3x3 mean, which made +//! blocks of the rendered grid on bright, lit and reflecting surfaces. + +use super::*; + +/// The resolve, compiled with the system compiler (`crate::host::compile`). +pub(super) const RESOLVE: &str = r#" +cbuffer Sizes : register(b0) { + float2 src_size; float2 rendered; + float2 out_size; float2 jitter; + float2 mv_scale; float2 mv_size; + float feedback; float sharpen; float exposure; uint flags; +}; +Texture2D<float4> source : register(t0); +Texture2D<float4> motion : register(t1); +RWTexture2D<float4> target : register(u0); +RWStructuredBuffer<uint2> before : register(u1); +RWStructuredBuffer<uint2> after : register(u2); +SamplerState bilinear : register(s0); + +float3 clean(float3 c) { return (c == c && abs(c) < 65000.0) ? max(c, 0.0) : 0.0; } +float most(float3 c) { return max(c.r, max(c.g, c.b)); } +float3 squash(float3 c) { return c / (1.0 + most(c)); } +float3 unsquash(float3 c) { return c / max(1.0 - most(c), 0.001); } +float3 to_ycocg(float3 c) { + return float3(dot(c, float3(0.25, 0.5, 0.25)), dot(c, float3(0.5, 0.0, -0.5)), dot(c, float3(-0.25, 0.5, -0.25))); +} +float3 from_ycocg(float3 c) { return float3(c.x + c.y - c.z, c.x + c.z, c.x - c.y - c.z); } +float4 unpack(uint2 v) { + return float4(f16tof32(v.x), f16tof32(v.x >> 16), f16tof32(v.y), f16tof32(v.y >> 16)); +} +uint2 pack(float4 c) { + return uint2(f32tof16(c.x) | (f32tof16(c.y) << 16), f32tof16(c.z) | (f32tof16(c.w) << 16)); +} +float3 history_at(int2 p) { + p = clamp(p, int2(0, 0), int2(out_size) - 1); + return clean(unpack(before[uint(p.y) * uint(out_size.x) + uint(p.x)]).rgb); +} +// Catmull-Rom over 4x4 history texels around `pos` (output pixels). +float3 catmull(float2 pos) { + float2 f = pos - 0.5; + float2 i = floor(f); + float2 t = f - i; + float2 w[4]; + w[0] = t * (-0.5 + t * (1.0 - 0.5 * t)); + w[1] = 1.0 + t * t * (-2.5 + 1.5 * t); + w[2] = t * (0.5 + t * (2.0 - 1.5 * t)); + w[3] = t * t * (-0.5 + 0.5 * t); + float3 sum = 0.0; + [unroll] for (int y = 0; y < 4; y++) { + [unroll] for (int x = 0; x < 4; x++) { + sum += history_at(int2(i) + int2(x - 1, y - 1)) * (w[x].x * w[y].y); + } + } + return max(sum, 0.0); +} +// The colour input at `uv` by Catmull-Rom in nine bilinear taps, each +// kept inside the rendered part: sharper than one bilinear tap, which +// blurred the 1.5x upscale (Try 6.10). +float3 source_at(float2 uv) { + float2 lo_uv = 0.5 / src_size, hi_uv = (rendered - 0.5) / src_size; + float2 pos = uv * src_size; + float2 c = floor(pos - 0.5) + 0.5; + float2 f = pos - c; + float2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f)); + float2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f); + float2 w2 = f * (0.5 + f * (2.0 - 1.5 * f)); + float2 w3 = f * f * (-0.5 + 0.5 * f); + float2 w12 = w1 + w2; + float2 t0 = (c - 1.0) / src_size; + float2 t12 = (c + w2 / w12) / src_size; + float2 t3 = (c + 2.0) / src_size; + float2 xs[3] = { float2(t0.x, w0.x), float2(t12.x, w12.x), float2(t3.x, w3.x) }; + float2 ys[3] = { float2(t0.y, w0.y), float2(t12.y, w12.y), float2(t3.y, w3.y) }; + float3 sum = 0.0; + [unroll] for (int y = 0; y < 3; y++) { + [unroll] for (int x = 0; x < 3; x++) { + float2 p = clamp(float2(xs[x].x, ys[y].x), lo_uv, hi_uv); + sum += clean(source.SampleLevel(bilinear, p, 0).rgb) * (xs[x].y * ys[y].y); + } + } + return max(sum, 0.0); +} +// A tent blur of the colour input around `uv` (four bilinear taps half a +// texel off): what the sharpening works against. It moves smoothly with +// the output texel; the 3x3 mean of the nearest rendered texel did not, +// and sharpening against it drew the rendered grid into bright, lit +// surfaces as blocks (Try 6.10). +float3 blur_at(float2 uv) { + float2 lo_uv = 0.5 / src_size, hi_uv = (rendered - 0.5) / src_size; + float2 h = 0.5 / src_size; + float3 sum = 0.0; + sum += squash(clean(source.SampleLevel(bilinear, clamp(uv + float2(-h.x, -h.y), lo_uv, hi_uv), 0).rgb)); + sum += squash(clean(source.SampleLevel(bilinear, clamp(uv + float2(h.x, -h.y), lo_uv, hi_uv), 0).rgb)); + sum += squash(clean(source.SampleLevel(bilinear, clamp(uv + float2(-h.x, h.y), lo_uv, hi_uv), 0).rgb)); + sum += squash(clean(source.SampleLevel(bilinear, clamp(uv + float2(h.x, h.y), lo_uv, hi_uv), 0).rgb)); + return sum * 0.25; +} +[numthreads(8, 8, 1)] +void resolve(uint3 id : SV_DispatchThreadID) { + // Groups are 8 by 8: the last ones reach past a size that is not a + // multiple of 8. + uint width, height; + target.GetDimensions(width, height); + if (id.x >= width || id.y >= height) return; + float2 out_pos = float2(id.xy) + 0.5; + // Where this output texel is in the rendered image, without jitter; + // the rendered texel whose sample is nearest it. + float2 src_pos = out_pos * rendered / out_size; + int2 last = int2(rendered) - 1; + int2 centre = clamp(int2(floor(src_pos + jitter)), int2(0, 0), last); + // The neighbourhood: the clip box and the mean. + float3 m1 = 0.0, m2 = 0.0, lo = 1e30, hi = -1e30; + [unroll] for (int y = -1; y <= 1; y++) { + [unroll] for (int x = -1; x <= 1; x++) { + int2 p = clamp(centre + int2(x, y), int2(0, 0), last); + float3 c = to_ycocg(squash(clean(source.Load(int3(p, 0)).rgb))); + m1 += c; + m2 += c * c; + lo = min(lo, c); + hi = max(hi, c); + } + } + float3 mean = m1 / 9.0; + float3 sigma = sqrt(max(m2 / 9.0 - mean * mean, 0.0)); + float3 box_lo = max(lo, mean - 1.25 * sigma); + float3 box_hi = min(hi, mean + 1.25 * sigma); + // This frame's colour, filtered at the unjittered place. + float2 at = (src_pos + jitter) / src_size; + at = clamp(at, 0.5 / src_size, (rendered - 0.5) / src_size); + float4 now = source.SampleLevel(bilinear, at, 0); + // Catmull-Rom's overshoot kept inside what the texels around it hold. + float3 current = clamp(to_ycocg(squash(source_at(at))), lo, hi); + // Motion: the longest of a cross around the texel, so the edges of + // what moves carry its motion (UV, current to previous). + float2 mv = 0.0; + if (flags & 2) { + int2 mlast = int2(mv_size) - 1; + float best = -1.0; + int2 taps[5] = { int2(0, 0), int2(1, 0), int2(-1, 0), int2(0, 1), int2(0, -1) }; + [unroll] for (int k = 0; k < 5; k++) { + int2 p = clamp(centre + taps[k], int2(0, 0), mlast); + float2 m = motion.Load(int3(p, 0)).xy * mv_scale; + m = (m == m && abs(m) < 4.0) ? m : 0.0; + float l = dot(m, m); + if (l > best) { best = l; mv = m; } + } + } + float2 prev = out_pos / out_size + mv; + bool valid = (flags & 1) == 0 && all(prev >= 0.0) && all(prev <= 1.0); + float alpha = feedback; + float3 result = current; + if (valid) { + float3 h = to_ycocg(squash(catmull(prev * out_size) * exposure)); + h = clamp(h, box_lo, box_hi); + // Fast motion keeps less of the history: the filter softens it. + alpha = max(alpha, saturate(length(mv * out_size) * 0.01)); + result = lerp(h, current, alpha); + } + float3 rgb = from_ycocg(result); + rgb = max(rgb + sharpen * (rgb - blur_at(at)), 0.0); + rgb = min(rgb, 0.995); + float3 linear_rgb = unsquash(rgb); + after[id.y * width + id.x] = pack(float4(min(linear_rgb, 65000.0), 1.0)); + target[id.xy] = float4(linear_rgb, now.a); +} +"#; + +pub(super) struct Temporal { + root: ID3D12RootSignature, + pipeline: ID3D12PipelineState, + views: ID3D12DescriptorHeap, + step: u32, + next: u32, + /// The two history buffers and the output size they are for. + history: Option<([ID3D12Resource; 2], (u32, u32))>, + /// Which history buffer the next resolve reads. + read: usize, + /// When the last resolve was recorded, for the gap that starts the + /// history again. + last: Option<std::time::Instant>, + /// The title's pre-exposure at the last resolve. + exposure: f32, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Temporal {} + +pub(super) static TEMPORAL: Mutex<Option<Temporal>> = Mutex::new(None); + +/// Views of a resolve are kept this many resolves (five views each), as +/// the stretch's are (`STRETCH_RING`). +const RING: u32 = 64; +const VIEWS: u32 = 5; + +/// A gap between two resolves longer than this starts the history again: +/// what the last one saw is from before a loading screen. +const GAP_SECS: u64 = 5; + +/// Whether the upscaler's output is made by the temporal resolve +/// (`VICTORY_UPSCALE_TEMPORAL`, on unless `0`). +pub(crate) fn enabled() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_UPSCALE_TEMPORAL").is_none_or(|v| v != "0")) +} + +fn percent(name: &str, default: f32, low: f32, high: f32) -> f32 { + std::env::var(name) + .ok() + .and_then(|v| v.trim().parse::<f32>().ok()) + .map_or(default, |p| (p / 100.0).clamp(low, high)) +} + +/// How much of the new frame each resolve keeps (`VICTORY_UPSCALE_FEEDBACK`). +fn feedback() -> f32 { + static F: std::sync::OnceLock<f32> = std::sync::OnceLock::new(); + *F.get_or_init(|| percent("VICTORY_UPSCALE_FEEDBACK", 0.1, 0.02, 1.0)) +} + +/// The sharpening amount, unless the title asks for its own +/// (`VICTORY_UPSCALE_SHARPEN`). +fn sharpen(title: Option<f32>) -> f32 { + static S: std::sync::OnceLock<Option<f32>> = std::sync::OnceLock::new(); + let set = *S.get_or_init(|| { + std::env::var("VICTORY_UPSCALE_SHARPEN") + .ok() + .and_then(|v| v.trim().parse::<f32>().ok()) + .map(|p| (p / 100.0).clamp(0.0, 1.0)) + }); + // 0.1: the colour is now taken by Catmull-Rom, sharp by itself. + set.or(title.map(|s| (s * 0.5).clamp(0.0, 0.5))).unwrap_or(0.1) +} + +/// Colour formats whose two first channels a float view reads as motion. +fn motion_format(format: DXGI_FORMAT) -> bool { + // R32G32B32A32_FLOAT, R16G16B16A16_FLOAT, R32G32_FLOAT, R16G16_FLOAT, + // R16G16_SNORM. + matches!(format.0, 2 | 10 | 16 | 34 | 37) +} + +fn ranges() -> [D3D12_DESCRIPTOR_RANGE; 2] { + [ + D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 2, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }, + D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + NumDescriptors: 3, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 2, + }, + ] +} + +fn make(device: &ID3D12Device) -> windows::core::Result<Temporal> { + use windows::core::s; + let cs = crate::host::compile(RESOLVE, s!("resolve"), s!("cs_5_1"))?; + let views = ranges(); + let sizes = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: 16, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let root = root_signature( + device, + &[sizes, table(&views, D3D12_SHADER_VISIBILITY_ALL)], + D3D12_SHADER_VISIBILITY_ALL, + D3D12_ROOT_SIGNATURE_FLAG_NONE, + )?; + // SAFETY: the description points at live data and never releases its + // pointer. + unsafe { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = device.CreateComputePipelineState(&desc)?; + let views: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: RING * VIEWS, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })?; + Ok(Temporal { + root, + pipeline, + step: device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + views, + next: 0, + history: None, + read: 0, + last: None, + exposure: 1.0, + }) + } +} + +/// A history buffer of `texels` half-precision RGBA texels. +fn history_buffer(device: &ID3D12Device, texels: u64) -> windows::core::Result<ID3D12Resource> { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: texels * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let mut made: Option<ID3D12Resource> = None; + // SAFETY: live descriptions; the out pointer is ours. + unsafe { + device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut made, + )?; + } + made.ok_or_else(windows::core::Error::empty) +} + +/// What one upscale dispatch gives the resolve besides its textures. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Frame { + pub render: [u32; 2], + pub jitter: [f32; 2], + pub motion_scale: [f32; 2], + pub reset: bool, + pub sharpness: Option<f32>, + pub pre_exposure: f32, +} + +/// Records into `list` the temporal resolve of the top-left `frame.render` +/// texels of `source` over the whole of `target` (in the unordered-access +/// state), moved by `motion` when there is one. False if nothing was +/// recorded; the caller then stretches. +/// +/// The pass sets the list's descriptor heap, compute root signature and +/// pipeline and puts none of them back: the caller replays the title's. +pub(crate) fn record( + device: &ID3D12Device, + host: &crate::host::HostList, + target: &ID3D12Resource, + source: &ID3D12Resource, + motion: Option<&ID3D12Resource>, + frame: Frame, +) -> bool { + let list = &host.list; + // SAFETY: live resources. + let (to, from) = unsafe { (target.GetDesc(), source.GetDesc()) }; + if to.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 + || to.Width == 0 + || to.Height == 0 + || from.Width == 0 + || from.Height == 0 + { + return false; + } + let mut made = TEMPORAL.lock().unwrap_or_else(|e| e.into_inner()); + if made.is_none() { + *made = match make(device) { + Ok(p) => { + tracing::info!( + feedback = feedback(), + "the upscaler's output is made by a temporal resolve: jitter taken off, history moved by the title's motion, clipped to the neighbourhood" + ); + Some(p) + } + Err(e) => { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::warn!(error = %e, "no temporal resolve: the upscaler's output is stretched"); + }); + None + } + }; + } + let Some(p) = made.as_mut() else { return false }; + let (width, height) = (to.Width as u32, to.Height); + let mut reset = frame.reset; + if p.history.as_ref().map(|h| h.1) != Some((width, height)) { + let texels = u64::from(width) * u64::from(height); + match (history_buffer(device, texels), history_buffer(device, texels)) { + (Ok(a), Ok(b)) => { + // The old buffers can still be read by lists in flight. + if let Some((old, _)) = p.history.take() { + host.keep(&old[0]); + host.keep(&old[1]); + } + tracing::info!(width, height, "temporal resolve history made"); + p.history = Some(([a, b], (width, height))); + reset = true; + } + (Err(e), _) | (_, Err(e)) => { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::warn!(error = %e, "no memory for the temporal resolve's history: the upscaler's output is stretched"); + }); + return false; + } + } + } + let now = std::time::Instant::now(); + if p.last.is_none_or(|t| now.duration_since(t).as_secs() >= GAP_SECS) { + reset = true; + } + p.last = Some(now); + let exposure_now = if frame.pre_exposure.is_finite() && frame.pre_exposure > 0.0 { + frame.pre_exposure + } else { + 1.0 + }; + let exposure = if reset { 1.0 } else { (exposure_now / p.exposure).clamp(0.01, 100.0) }; + p.exposure = exposure_now; + let Some((history, _)) = p.history.as_ref() else { return false }; + let (before, after) = (&history[p.read], &history[1 - p.read]); + p.read = 1 - p.read; + let slot = (p.next % RING) * VIEWS; + p.next = p.next.wrapping_add(1); + let rendered = [ + if frame.render[0] == 0 { from.Width as u32 } else { frame.render[0].min(from.Width as u32) }, + if frame.render[1] == 0 { from.Height } else { frame.render[1].min(from.Height) }, + ]; + // Motion: a float view of its two first channels, scaled to UV. + // SAFETY: a live resource. + let motion = motion.map(|m| (m, unsafe { m.GetDesc() })).filter(|(_, d)| { + let ok = motion_format(typed(d.Format)) && d.Width > 0 && d.Height > 0; + if !ok { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::info!(format = d.Format.0, "the upscaler's motion input is not read: the resolve keeps still history"); + }); + } + ok + }); + let (mv_scale, mv_size) = match &motion { + Some((_, d)) => ( + [ + frame.motion_scale[0] / rendered[0] as f32, + frame.motion_scale[1] / rendered[1] as f32, + ], + [(d.Width as u32).min(rendered[0]) as f32, d.Height.min(rendered[1]) as f32], + ), + None => ([0.0, 0.0], [1.0, 1.0]), + }; + let jitter = if frame.jitter.iter().all(|j| j.is_finite() && j.abs() <= 2.0) { + frame.jitter + } else { + [0.0, 0.0] + }; + let flags = u32::from(reset) | (u32::from(motion.is_some()) << 1); + let constants: [u32; 16] = [ + (from.Width as f32).to_bits(), + (from.Height as f32).to_bits(), + (rendered[0] as f32).to_bits(), + (rendered[1] as f32).to_bits(), + (width as f32).to_bits(), + (height as f32).to_bits(), + jitter[0].to_bits(), + jitter[1].to_bits(), + mv_scale[0].to_bits(), + mv_scale[1].to_bits(), + mv_size[0].to_bits(), + mv_size[1].to_bits(), + feedback().to_bits(), + sharpen(frame.sharpness).to_bits(), + exposure.to_bits(), + flags, + ]; + let read = |format: DXGI_FORMAT| D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: typed(format), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 1, + ..Default::default() + }, + }, + }; + let written = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: typed(to.Format), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let texels = u32::try_from(u64::from(width) * u64::from(height)).unwrap_or(u32::MAX); + let buffer_view = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: 0, + NumElements: texels, + StructureByteStride: 8, + CounterOffsetInBytes: 0, + Flags: D3D12_BUFFER_UAV_FLAG_NONE, + }, + }, + }; + // SAFETY: an open list; slots of our heap; live resources and objects + // (the pass's own live as long as the process, or are kept by the + // list when replaced). + unsafe { + let cpu = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: p.views.GetCPUDescriptorHandleForHeapStart().ptr + ((slot + i) * p.step) as usize, + }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: p.views.GetGPUDescriptorHandleForHeapStart().ptr + u64::from(slot * p.step), + }; + device.CreateShaderResourceView(source, Some(&read(from.Format)), cpu(0)); + match &motion { + Some((m, d)) => device.CreateShaderResourceView(*m, Some(&read(d.Format)), cpu(1)), + // Never read (the flag is off), but every view of the table is + // a valid one. + None => device.CreateShaderResourceView(source, Some(&read(from.Format)), cpu(1)), + } + device.CreateUnorderedAccessView(target, None, Some(&written), cpu(2)); + device.CreateUnorderedAccessView(before, None, Some(&buffer_view), cpu(3)); + device.CreateUnorderedAccessView(after, None, Some(&buffer_view), cpu(4)); + // The last resolve's writes of the history are done before this + // one reads them (a list can hold two resolves). + list.ResourceBarrier(&[uav_barrier(before)]); + list.SetDescriptorHeaps(&[Some(p.views.clone())]); + list.SetComputeRootSignature(&p.root); + list.SetPipelineState(&p.pipeline); + list.SetComputeRoot32BitConstants(0, 16, constants.as_ptr().cast(), 0); + list.SetComputeRootDescriptorTable(1, gpu); + list.Dispatch(width.div_ceil(8), height.div_ceil(8), 1); + } + // How the history fares, now and then: resolves that started it + // again are frames shown without accumulation. + use std::sync::atomic::Ordering::Relaxed; + let resets = RESETS.load(Relaxed) + u64::from(reset); + RESETS.store(resets, Relaxed); + let resolves = RESOLVES.fetch_add(1, Relaxed) + 1; + if resolves.is_power_of_two() || resolves.is_multiple_of(256) { + tracing::info!( + resolves, + resets, + motion = motion.is_some(), + jitter = ?jitter, + mv_scale = ?mv_scale, + exposure, + "temporal resolves" + ); + } + true +} + +static RESOLVES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static RESETS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +fn uav_barrier(resource: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + // SAFETY: a borrowed pointer; the barrier never releases it. + pResource: unsafe { std::mem::transmute_copy(resource) }, + }), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The resolve's source asks the compiler for no root signature and + /// guards its writes, as the stretch's does. + #[test] + fn the_resolve_is_a_guarded_compute_pass_without_a_root_signature() { + assert!(!RESOLVE.contains("RootSignature")); + assert!(RESOLVE.contains("numthreads(8, 8, 1)")); + assert!(RESOLVE.contains("if (id.x >= width || id.y >= height) return;")); + } + + /// The table holds the five views the source declares: two textures + /// read, the output and the two history buffers written. + #[test] + fn the_table_matches_the_source() { + let r = ranges(); + assert_eq!(r[0].NumDescriptors + r[1].NumDescriptors, VIEWS); + for register in ["t0", "t1", "u0", "u1", "u2"] { + assert!(RESOLVE.contains(&format!("register({register})"))); + } + } + + /// Only float views of motion are read. + #[test] + fn motion_is_read_from_float_formats_only() { + for f in [2, 10, 16, 34, 37] { + assert!(motion_format(DXGI_FORMAT(f))); + } + // R32_UINT, R16G16_UINT, R8G8B8A8_UNORM. + for f in [42, 36, 28] { + assert!(!motion_format(DXGI_FORMAT(f))); + } + } +} diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 7ca4dd9988..8894d31594 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -4,7 +4,7 @@ //! types. //! //! Host pipelines are made on a pipeline's first draw, not at creation: -//! Grand Theft Auto VI creates some 60,000 pipelines in its first 20 +//! The title creates some 60,000 pipelines in its first 20 //! seconds and draws with a few dozen (decision 0007, step 3). Shader //! containers are shared by content hash and translated once, on first //! use (decision 0003). @@ -61,8 +61,18 @@ pub(crate) struct Shader { /// The first 8 bytes of its BLAKE3, as logged. pub(crate) hash: String, container: Vec<u8>, + /// Its result gets the least indirect light ([`crate::ambient`]). + #[cfg(windows)] + pub(crate) resolves_light: bool, + /// A pixel program of the title's decoration bake ([`bakes`]). + #[cfg(windows)] + pub(crate) bakes: bool, #[cfg(windows)] translated: OnceLock<Option<Translated>>, + /// Whether its code walks the ray-tracing structures, once looked at + /// ([`Shader::walks`]). + #[cfg(windows)] + walks: OnceLock<bool>, } impl std::fmt::Debug for Shader { @@ -74,6 +84,29 @@ impl std::fmt::Debug for Shader { /// Every container seen, by full content hash. static SHADERS: Mutex<Option<HashMap<[u8; 32], Arc<Shader>>>> = Mutex::new(None); +/// For the memory lines: containers kept and their bytes, translations +/// kept and the bytes of their host code. None of them is ever let go. +static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// What the shader table and the pipeline library keep in memory: +/// containers and their bytes, translations and their bytes, the bytes of +/// the library's file (kept whole while the library lives) and what its +/// last save wrote. +#[cfg(windows)] +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] +pub(crate) fn kept() -> [u64; 7] { + use std::sync::atomic::Ordering::Relaxed; + [ + KEPT[0].load(Relaxed), + KEPT[1].load(Relaxed), + KEPT[2].load(Relaxed), + KEPT[3].load(Relaxed), + library::BLOB.load(Relaxed), + library::SAVED.load(Relaxed), + library::TRIMMED_BYTES.load(Relaxed), + ] +} + /// The shared container for `bytes`. fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> { let full = blake3::hash(bytes); @@ -82,12 +115,22 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> { .get_or_insert_with(HashMap::new) .entry(*full.as_bytes()) .or_insert_with(|| { + KEPT[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + KEPT[1].fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed); Arc::new(Shader { stage, hash: full.to_hex()[..16].to_owned(), container: bytes.to_vec(), #[cfg(windows)] + resolves_light: bytes + .windows(crate::ambient::PROGRAM.len()) + .any(|w| w == crate::ambient::PROGRAM), + #[cfg(windows)] + bakes: stage == "pixel" && bakes(bytes), + #[cfg(windows)] translated: OnceLock::new(), + #[cfg(windows)] + walks: OnceLock::new(), }) }) .clone() @@ -98,42 +141,70 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> { pub(crate) struct Translated { pub(crate) host: victory_shader::emit::HostShader, pub(crate) used: Vec<victory_shader::UsedResource>, + /// Whether the shader's code can store to buffer memory ([`stores`]); + /// true when its code is not known. + pub(crate) stores: bool, + /// A compute shader's group size (`numthreads`); `[0; 3]` for other + /// stages. A `DispatchX` that counts threads is made groups with it. + pub(crate) threads: [u32; 3], } #[cfg(windows)] impl Shader { + /// The container's size in bytes. + pub(crate) fn size(&self) -> usize { + self.container.len() + } + /// The translation, made on first use; a shader that does not /// translate is logged once. pub(crate) fn translated(&self) -> Option<&Translated> { self.translated .get_or_init(|| { let done = translate(&self.container); + // `VICTORY_SHADER_SAVE=<dir>`: each shader as the title gave it (`.cdxil`) and as + // translated (`.dxil`), by the hash crash reports name it with + if let Some(dir) = std::env::var_os("VICTORY_SHADER_SAVE") { + let dir = std::path::PathBuf::from(dir); + let _ = std::fs::create_dir_all(&dir); + let stem = format!("{}.{}", self.hash, self.stage); + let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &self.container); + if let Ok(t) = &done { + let _ = std::fs::write(dir.join(format!("{stem}.dxil")), &t.host.dxil); + } + } + if let Ok(t) = &done { + KEPT[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + KEPT[3].fetch_add(t.host.dxil.len() as u64, std::sync::atomic::Ordering::Relaxed); + } match &done { - Ok(t) => { - // `VICTORY_DUMP_SHADERS=<dir>`: the emitted DXIL, to read - // with a disassembler (`dxc -dumpbin`). - #[cfg(feature = "diagnostics")] - if let Some(dir) = std::env::var_os("VICTORY_DUMP_SHADERS") { - let file = std::path::Path::new(&dir) - .join(format!("{}-{}.dxil", self.stage, self.hash)); - if let Err(e) = std::fs::write(&file, &t.host.dxil) { + Ok(t) => tracing::info!( + stage = self.stage, + hash = %self.hash, + user_data = t.host.user_data.len(), + samplers = t.host.samplers.len(), + "shader translated" + ), + Err(e) => { + tracing::warn!( + stage = self.stage, + hash = %self.hash, + error = %e, + "shader does not translate; its pipelines' draws are dropped" + ); + // `VICTORY_DUMP_FAILED=<dir>`: only the containers of + // shaders that do not translate, to study offline + // (`victory translate`). + if let Some(dir) = std::env::var_os("VICTORY_DUMP_FAILED") { + let dir = std::path::PathBuf::from(dir); + let file = dir.join(format!("{}-{}.dxbc", self.stage, self.hash)); + let written = std::fs::create_dir_all(&dir) + .and_then(|()| std::fs::write(&file, &self.container)); + if let Err(e) = written { tracing::warn!(error = %e, file = %file.display(), "shader not dumped"); } } - tracing::info!( - stage = self.stage, - hash = %self.hash, - user_data = t.host.user_data.len(), - samplers = t.host.samplers.len(), - "shader translated" - ) } - Err(e) => tracing::warn!( - stage = self.stage, - hash = %self.hash, - error = %e, - "shader does not translate; its pipelines' draws are dropped" - ), } done.ok() }) @@ -144,23 +215,375 @@ impl Shader { #[cfg(windows)] fn translate(container: &[u8]) -> Result<Translated, String> { use victory_shader::{Container, FourCC, HwStage}; - let host = crate::shader_cache::host_shader(container)?; + // The translation depends on it (a view index past a capped heap). + crate::descriptor::host::probe_view_limit(); let c = Container::parse(container).map_err(|e| e.to_string())?; - let used = match c.part(FourCC::DXIL) { - Some(part) => victory_shader::native_programs(part.data) - .map_err(|e| e.to_string())? - .into_iter() - .find(|p| { - matches!( - p.stage, - HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs - ) - }) - .map(|p| p.used) - .unwrap_or_default(), + let programs = match c.part(FourCC::DXIL) { + Some(part) => victory_shader::native_programs(part.data).map_err(|e| e.to_string())?, None => Vec::new(), }; - Ok(Translated { host, used }) + let host = crate::shader_cache::host_shader(container)?; + let stores = programs.is_empty() || programs.iter().any(stores); + let main = programs.into_iter().find(|p| { + matches!( + p.stage, + HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs + ) + }); + let threads = match main.as_ref().map(|p| &p.io) { + Some(victory_shader::native::StageIo::Cs(cs)) => cs.threads, + _ => [0; 3], + }; + let used = main.map(|p| p.used).unwrap_or_default(); + Ok(Translated { host, used, stores, threads }) +} + +/// The compute pipelines of the console's ray-tracing structure builder +/// (`XboxBvhBuilder.dll`; its programs are the ones with a spilled +/// user-data table) run **all or none**. Its stages feed each other +/// through memory: a stage that runs on what a dropped stage never wrote +/// computes its store offsets from garbage. The structures lie in plain +/// title memory, between the title's own objects, and a root view has no +/// size, so those stores land on the neighbours (run 98, with 14 of 35 +/// stages translated: the title died within a second of the first builder +/// submission, on pointers that had become bounding-box bit patterns). +/// +/// So a builder dispatch runs only while every builder pipeline the title +/// has created has a host pipeline; the first builder dispatch makes them +/// all on the spot instead of over the next frames (a stage "still being +/// made" would be a dropped stage). One that cannot be made turns the +/// builder off for the rest of the run. +/// +/// shortcut: and only with `VICTORY_BVH_BUILDER=1`, until a run has shown +/// the whole builder and the host side of title memory by address +/// (`memory.rs`) working on a card; nothing reads the structures before +/// the programs that walk them translate. +#[cfg(windows)] +struct Builder { + pipelines: Vec<Arc<make::Pending>>, + /// Every one of `pipelines` has a host pipeline. + whole: bool, + /// One could not be made. + off: bool, +} + +#[cfg(windows)] +static BUILDER: Mutex<Builder> = Mutex::new(Builder { + pipelines: Vec::new(), + whole: false, + off: false, +}); + +/// Whether `shaders` are a pipeline of the structure builder. +#[cfg(windows)] +fn of_builder(shaders: &[Arc<Shader>]) -> bool { + use victory_shader::{Container, FourCC}; + let [shader] = shaders else { return false }; + if shader.stage != "compute" { + return false; + } + let Ok(c) = Container::parse(&shader.container) else { + return false; + }; + c.part(FourCC::DXIL) + .and_then(|part| victory_shader::native_programs(part.data).ok()) + .is_some_and(|programs| programs.iter().any(victory_shader::spill::is_spilled)) +} + +/// Whether a compute container is one of the title's passes that only +/// serve rays (Try 6.12, ported from edsuuu/VI-BR-PORT ab4571df, 1556de82, +/// f1e5e454 and 24f8d2ed, GPL-3.0-or-later; their last two after +/// codec-d/cool_fox `make.rs`): +/// +/// - `bvh_skinning`: all 30 entry points named `CSComputeSkinning*` pose +/// every animated mesh once more, only for the ray-tracing structures, +/// and `bvh_skinning_smh`'s `CSGenerateHairVB` makes the hair's geometry +/// for them. They were the largest share of the card's time in a cutscene +/// there (Series S, RTX 4060 Ti 8 GB: 6.8 -> 10.2 fps). The picture's own +/// skinning is `CS_PedStandardSkinning*`, `CS_PosOnlyLodSkinning*` and the +/// cloth's `computeclothSkinning`: they run. +/// - `CS_RaytracingResolve*` shades what a ray hit (some 1,000 programs). +/// - `CS_ScreenProbes_ActivateRays*` picks the screen probes that cast rays. +/// - The tracing against the structures: the screen probes' +/// `CS_ScreenProbes_TraceRays*_BVH*` and the reflections' +/// `CS_RaytraceVBuffer*`. Their `Fallback` and `Voxels` forms march +/// through the title's voxels, not the structures, and light the +/// picture: they run. +/// +/// The container holds its entry point's name, not the effect's. +#[cfg(windows)] +fn for_rays(bytes: &[u8]) -> RayOnly { + let has = |name: &[u8]| bytes.windows(name.len()).any(|w| w == name); + if has(b"CSComputeSkinning") || has(b"CSGenerateHairVB") { + RayOnly::Skin + } else if has(b"CS_RaytracingResolve") { + RayOnly::Resolve + } else if has(b"CS_ScreenProbes_ActivateRays") { + RayOnly::Activate + } else if (has(b"CS_ScreenProbes_TraceRays") && has(b"_BVH")) + || (has(b"CS_RaytraceVBuffer") && !has(b"Voxels")) + { + RayOnly::Trace + } else { + RayOnly::No + } +} + +/// What a compute pipeline does only for rays ([`for_rays`]). +#[cfg(windows)] +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum RayOnly { + No, + Skin, + Resolve, + Activate, + Trace, +} + +#[cfg(all(test, windows))] +#[test] +fn ray_programs_are_known_by_name() { + assert_eq!(for_rays(b"..\0CSComputeSkinningRigidVelocity_1c34db0a_Wrapped\0.."), RayOnly::Skin); + assert_eq!(for_rays(b"..\0CS_PedStandardSkinning_3_00aa11bb_Wrapped\0.."), RayOnly::No); + assert_eq!(for_rays(b"computeclothSkinning"), RayOnly::No); + assert_eq!(for_rays(b"..\0CS_RaytracingResolve_Opaque_12345678_Wrapped\0.."), RayOnly::Resolve); + assert_eq!(for_rays(b"..\0CS_ScreenProbes_ActivateRays_0_Wrapped\0.."), RayOnly::Activate); + assert_eq!(for_rays(b"..\0CSGenerateHairVB_c88a8f19_Wrapped\0.."), RayOnly::Skin); + assert_eq!(for_rays(b"..\0CS_ScreenProbes_TraceRays_RayBinning_BVH_Mixed\0.."), RayOnly::Trace); + assert_eq!(for_rays(b"..\0CS_ScreenProbes_TraceRays_Voxels\0.."), RayOnly::No); + assert_eq!(for_rays(b"..\0CS_ScreenProbes_TraceRays_Fallback\0.."), RayOnly::No); + assert_eq!(for_rays(b"..\0CS_RaytraceVBuffer_ShaderBinning_WithFar\0.."), RayOnly::Trace); + assert_eq!(for_rays(b"..\0CS_RaytraceVBuffer_Voxels_RayBinning\0.."), RayOnly::No); + // The ambient stand-in's program is not one of them. + assert_eq!(for_rays(b"..\0CS_ScreenProbes_TemporalResolve_0\0.."), RayOnly::No); +} + +/// Whether a dispatch of `this` is left out because it only serves rays +/// and nothing they could hit is there: every ray misses +/// (`VICTORY_SKIP_RT=1`) and the structure builder is off. Each kind runs +/// anyway with its switch: `VICTORY_RT_SKIN=1`, `VICTORY_RT_RESOLVE=1`, +/// `VICTORY_RT_TRACE=1`, `VICTORY_ACTIVATE_RAYS=1`. +#[cfg(windows)] +pub(crate) fn only_for_rays(this: This) -> bool { + !this.is_null() && rays_only_off(pipeline(this).rt_only) +} + +/// Whether passes of `kind` are left out ([`only_for_rays`]). +#[cfg(windows)] +fn rays_only_off(kind: RayOnly) -> bool { + fn off(switch: &str) -> bool { + std::env::var_os("VICTORY_SKIP_RT").is_some_and(|v| v == "1") + && std::env::var_os("VICTORY_BVH_BUILDER").is_none_or(|v| v != "1") + && std::env::var_os(switch).is_none_or(|v| v != "1") + } + static SKIN: OnceLock<bool> = OnceLock::new(); + static RESOLVE: OnceLock<bool> = OnceLock::new(); + static ACTIVATE: OnceLock<bool> = OnceLock::new(); + static TRACE: OnceLock<bool> = OnceLock::new(); + match kind { + RayOnly::No => false, + RayOnly::Skin => *SKIN.get_or_init(|| off("VICTORY_RT_SKIN")), + RayOnly::Resolve => *RESOLVE.get_or_init(|| off("VICTORY_RT_RESOLVE")), + RayOnly::Activate => *ACTIVATE.get_or_init(|| off("VICTORY_ACTIVATE_RAYS")), + RayOnly::Trace => *TRACE.get_or_init(|| off("VICTORY_RT_TRACE")), + } +} + +/// The ray-only kind of a pipeline of `shaders` ([`for_rays`] of its +/// compute container). +#[cfg(windows)] +fn rt_only_of(shaders: &[Arc<Shader>]) -> RayOnly { + shaders + .iter() + .filter(|s| s.stage == "compute") + .map(|s| for_rays(&s.container)) + .find(|k| *k != RayOnly::No) + .unwrap_or(RayOnly::No) +} + +/// Whether a pipeline of `shaders` is not built at all: its dispatches +/// are left out anyway ([`only_for_rays`]), and its driver compile (some +/// 1,000 `CS_RaytracingResolve` programs among them) was time the +/// pipeline workers spent before and while the game ran. +#[cfg(windows)] +pub(crate) fn never_built(shaders: &[Arc<Shader>]) -> bool { + rays_only_off(rt_only_of(shaders)) +} + +/// `VICTORY_BVH_QUARANTINE=1`: what the structure builder's stages store +/// stays in the host's copies and is not copied back into title memory. A +/// check for a first run of the whole builder: a stage that stores where +/// it should not can then not reach the title's own objects (run 98), and +/// the programs that walk the structures read the host's copies anyway. +/// shortcut: not a way to run: the title also reads results back (sizes, +/// counters) and gets none, and a copy's pages are overwritten from title +/// memory when the title writes them. +#[cfg(windows)] +pub(crate) fn builder_quarantined(this: This) -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + is_builder(this) && *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_QUARANTINE").is_some_and(|v| v == "1")) +} + +#[cfg(windows)] +impl Shader { + /// Whether the program walks the ray-tracing structures: its code has + /// an `image_bvh_intersect_ray` or `image_bvh64_intersect_ray`. Looked + /// at once, when a dispatch first asks. + fn walks(&self) -> bool { + *self.walks.get_or_init(|| container_walks(&self.container)) + } +} + +/// Whether a console container's code tests rays against the nodes of a +/// ray-tracing structure. +#[cfg(windows)] +fn container_walks(container: &[u8]) -> bool { + use victory_shader::{Container, FourCC}; + let Ok(c) = Container::parse(container) else { + return false; + }; + c.part(FourCC::DXIL) + .and_then(|part| victory_shader::native_programs(part.data).ok()) + .is_some_and(|programs| programs.iter().any(|p| code_walks(&p.code))) +} + +/// Whether native code has a ray-tracing node test. +#[cfg(windows)] +fn code_walks(code: &[u8]) -> bool { + victory_shader::gfx10::decode(code).is_ok_and(|code| code.iter().any(|i| i.name().is_some_and(|n| n.starts_with("image_bvh")))) +} + +/// Dispatches held back by [`walk_held`] since the last frame line. +#[cfg(windows)] +pub(crate) static WALKS_HELD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether a dispatch with the title's pipeline `this` is held back +/// because its program walks ray-tracing structures nothing has built +/// (`VICTORY_BVH_HOLD=1`; off by default). +/// +/// The structure builder does not run (see [`Builder`]: only with +/// `VICTORY_BVH_BUILDER=1`, and then only whole, which a host of 32-lane +/// waves does not manage yet). The title's ray-traced passes run all the +/// same: 64 programs of its shader pack test rays against structure nodes +/// (ray-traced shadows, screen probes, reflections, the irradiance cache; +/// one of them, `CS_IrradianceCache_ShadowTrace_WithFar` f607780aa8e502d0, +/// from the first world frame on in every run). Each walks, in a loop the +/// title bounds at 65,535 steps a wave, whatever bytes lie where the +/// structure would be: what it returns is not a picture of the scene, and +/// how long it runs depends on those bytes. Upstream's pull request 2311 +/// measured a card hung in exactly that dispatch on an NVIDIA card, every +/// run, and both card losses of ours since the draw windows' own fault was +/// fixed (runs 208 and 224) came within a second of the first use of the +/// programs that shade those rays' hits (`CS_RaytracingResolve`). +/// +/// With the switch such a dispatch is dropped until the builder has run +/// whole. What the passes would have written stays as the title left it +/// (their targets are not cleared by us): the picture has to be looked at. +#[cfg(windows)] +pub(crate) fn walk_held(this: This) -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + if this.is_null() || !*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_HOLD").is_some_and(|v| v == "1")) { + return false; + } + let p = pipeline(this); + if !p.shaders.iter().any(|s| s.stage == "compute" && s.walks()) { + return false; + } + // (Asked only for the few programs that walk: the lock is the builder's.) + if BUILDER.lock().unwrap_or_else(|e| e.into_inner()).whole { + return false; + } + if WALKS_HELD.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + shaders = ?p.shaders, + "a dispatch of a program that walks ray-tracing structures is held back: the structure builder has not built them (VICTORY_BVH_HOLD=1); the first one" + ); + }); + } + true +} + +/// Whether the title's pipeline `this` is one of the structure builder's. +#[cfg(windows)] +pub(crate) fn is_builder(this: This) -> bool { + !this.is_null() && pipeline(this).builder +} + +/// A stage of the builder was dropped after all: none runs from here on. +#[cfg(windows)] +pub(crate) fn builder_off(why: &'static str) { + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + if !b.off { + b.off = true; + tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none"); + } +} + +/// At a dispatch of a builder pipeline: whether the builder runs (see +/// [`Builder`]). +#[cfg(windows)] +pub(crate) fn builder_runs() -> bool { + static ALLOWED: OnceLock<bool> = OnceLock::new(); + if !*ALLOWED.get_or_init(|| std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1")) { + return false; + } + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + if b.off { + return false; + } + if b.whole { + return true; + } + let missing = b.pipelines.iter().filter(|p| !make::now(p)).count(); + if missing > 0 { + b.off = true; + for p in b.pipelines.iter().filter(|p| !make::now(p)) { + tracing::warn!(shaders = ?make::shaders(p), "a builder pipeline with no host pipeline"); + } + tracing::warn!( + missing, + of = b.pipelines.len(), + "the ray-tracing structure builder stays off: not all of its programs have a host pipeline, and its stages run all or none" + ); + return false; + } + tracing::info!( + pipelines = b.pipelines.len(), + "the ray-tracing structure builder runs: all of its programs have host pipelines" + ); + b.whole = true; + true +} + +/// Whether a console program can store to buffer memory: it has a buffer, +/// typed-buffer, scalar-memory, flat or global store or atomic, or code +/// that is not all known (an instruction of those kinds outside our table, +/// an indirect jump, code that does not decode). Stores to textures +/// (image instructions) and to the program's own scratch memory do not +/// count: neither reaches a buffer's host copy. After upstream #413, +/// which leaves scalar-memory stores out and counts image stores. +#[cfg(windows)] +fn stores(program: &victory_shader::NativeProgram) -> bool { + use victory_shader::gfx10::{Encoding, decode}; + let Ok(code) = decode(&program.code) else { + return true; + }; + code.iter().any(|i| { + let name = i.name(); + match i.encoding { + Encoding::Mubuf + | Encoding::Mtbuf + | Encoding::Smem + | Encoding::Flat + | Encoding::Global => name.is_none_or(|n| { + (n.contains("store") || n.contains("atomic")) && !n.contains("scratch") + }), + Encoding::Sop1 => name.is_none_or(|n| matches!(n, "s_setpc_b64" | "s_swappc_b64")), + _ => false, + } + }) } #[repr(C)] @@ -175,6 +598,12 @@ struct Pipeline { /// (by a worker: the title may release the pipeline meanwhile). #[cfg(windows)] host: Arc<make::Pending>, + /// One of the ray-tracing structure builder's ([`Builder`]). + #[cfg(windows)] + builder: bool, + /// One of the title's passes that only serve rays ([`for_rays`]). + #[cfg(windows)] + rt_only: RayOnly, } const _: () = assert!(offset_of!(Pipeline, packet) == 0x10); @@ -213,15 +642,54 @@ pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> { make::ready(&pipeline(this).host) } +/// As [`host_pipeline`], for a draw into render target and depth views of +/// the formats `bound`: if a bound view has another format than the title's +/// pipeline declares for its slot (`host::formats_differ`), the host +/// pipeline of the same shaders and state made for the bound formats +/// (`make::for_formats`). A draw whose views are as declared pays one +/// comparison of the nine words. +#[cfg(windows)] +pub(crate) fn host_pipeline_for<'a>(this: This, bound: &host::TargetFormats) -> Option<&'a host::HostPipeline> { + if this.is_null() { + return None; + } + let p = &pipeline(this).host; + if p.formats != *bound && host::formats_differ(&p.formats, bound) { + return make::for_formats(p, bound); + } + make::ready(p) +} + /// Host pipelines queued and not made yet. #[cfg(windows)] pub(crate) fn making() -> u64 { make::waiting() } -/// Draws and dispatches dropped since the last [`take_drops`], by reason -/// (diagnostics). -#[cfg(all(windows, feature = "diagnostics"))] +/// Draws that went out with a stand-in while their pipeline was being made. +#[cfg(windows)] +pub(crate) fn stand_ins() -> u64 { + make::STAND_INS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Of [`stand_ins`], those of the second tier (other depth writes). +#[cfg(windows)] +pub(crate) fn loose_stand_ins() -> u64 { + make::LOOSE_STAND_INS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Draws that took a same-shape stand-in before any wait (Try 6.15, +/// `VICTORY_STAND_IN_FIRST`); counted apart from [`stand_ins`]. +#[cfg(windows)] +pub(crate) fn stand_ins_first() -> u64 { + make::STAND_INS_FIRST.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Draws and dispatches dropped since the last [`take_drops`], by reason. +/// Kept in every build (4.8): the frame lines said how many draws a frame +/// were dropped "without a host pipeline", 166 to 2,546 in the user's runs, +/// but only a diagnostics build said which programs they were. +#[cfg(windows)] static DROPS: Mutex<Option<HashMap<String, u64>>> = Mutex::new(None); /// Shader hashes as printed in the pipeline diagnostics. @@ -267,34 +735,35 @@ pub(crate) fn is_skipped(this: This) -> bool { } /// Counts a draw or dispatch of `this` intentionally skipped or dropped -/// for want of a host pipeline (diagnostics). -#[cfg(all(windows, feature = "diagnostics"))] +/// for want of a host pipeline, or with one that could not be bound. +#[cfg(windows)] pub(crate) fn note_drop(this: This) { let why = if this.is_null() { - Some("no pipeline set".to_owned()) + "no pipeline set".to_owned() } else { let p = pipeline(this); - skipped_shader(p) - .map(|hash| format!("skipped shader {hash}")) - .or_else(|| make::missing(&p.host)) + #[cfg(feature = "diagnostics")] + let skipped = skipped_shader(p).map(|hash| format!("skipped shader {hash}")); + #[cfg(not(feature = "diagnostics"))] + let skipped: Option<String> = None; + skipped.or_else(|| make::missing(&p.host)).unwrap_or_else(|| { + format!("its host pipeline is there but the draw could not be bound or run {:?}", p.shaders) + }) }; - if let Some(why) = why { - note_why(why); - } + note_why(why); } -/// Counts a draw or dispatch dropped for `why` (diagnostics). -#[cfg(all(windows, feature = "diagnostics"))] +/// Counts a draw or dispatch dropped for `why`. +#[cfg(windows)] pub(crate) fn note_why(why: String) { + #[cfg(feature = "diagnostics")] + crate::capture::op(0, || format!("DROPPED {why}")); let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()); - *drops - .get_or_insert_with(HashMap::new) - .entry(why) - .or_default() += 1; + *drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1; } -/// The drops counted since the last call, most first (diagnostics). -#[cfg(all(windows, feature = "diagnostics"))] +/// The drops counted since the last call, most first. +#[cfg(windows)] pub(crate) fn take_drops() -> Vec<(String, u64)> { let drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut drops: Vec<(String, u64)> = drops.into_iter().flatten().collect(); @@ -326,11 +795,27 @@ fn hand_out( let host = Arc::new(make::Pending::new(shaders.clone(), graphics)); #[cfg(windows)] make::early(&host); + #[cfg(windows)] + let builder = of_builder(&shaders); + #[cfg(windows)] + if builder { + // Another stage: the group is looked at again at its next dispatch. + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + b.pipelines.push(host.clone()); + b.whole = false; + // Named once each (gfx41): which programs are the builder's, to + // match against the refused and untranslated ones. + tracing::info!(n = b.pipelines.len(), ?shaders, "a pipeline of the ray-tracing structure builder"); + } let pipeline = Box::new(Pipeline { object: Object::new(&FUNCTIONS), packet: [0; 8], #[cfg(windows)] host, + #[cfg(windows)] + builder, + #[cfg(windows)] + rt_only: rt_only_of(&shaders), shaders, bound: std::sync::atomic::AtomicBool::new(false), }); @@ -394,6 +879,59 @@ pub(crate) extern "system" fn create_compute_x( create_compute(this, desc, iid, out) } +/// One part of a derived pipeline: which part, then its description, at +/// the size of the largest (the blend state). +pub(crate) const DERIVED_PART: usize = 0x14c; + +/// Device method 0x1b8, `CreateDerivedGraphicsPipelineStateX(base, part +/// count, parts, iid, out)`: the base pipeline with some of its state +/// replaced (depth and stencil, rasterizer, blend, sample mask), each part +/// a `u32` kind and the description at +4, [`DERIVED_PART`] bytes apart. +/// The shaders are the base's. Parts only the console's GPU uses are +/// skipped. +pub(crate) extern "system" fn create_derived( + _: This, + base: This, + count: u32, + parts: *const u8, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + if base.is_null() || (count != 0 && parts.is_null()) { + return E_INVALIDARG; + } + let base = pipeline(base); + #[cfg(windows)] + let graphics = base.host.graphics.as_deref().map(|g| { + let mut g = g.derive(); + for i in 0..count as usize { + // SAFETY: the title passes `count` parts. + let (part, data) = unsafe { + let at = parts.add(i * DERIVED_PART); + (at.cast::<u32>().read_unaligned(), at.add(4)) + }; + // SAFETY: as above. + if !unsafe { g.patch(part, data) } { + static SKIPPED: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + if !SKIPPED.swap(true, std::sync::atomic::Ordering::Relaxed) { + tracing::info!(part, "derived pipeline part skipped (console only)"); + } + } + } + Box::new(g) + }); + #[cfg(not(windows))] + let _ = (count, parts); + hand_out( + base.shaders.clone(), + #[cfg(windows)] + graphics, + iid, + out, + ) +} + /// A pipeline described as a stream: its size and the subobjects, each a /// type then its data, padded to 8 bytes. #[repr(C)] @@ -472,6 +1010,17 @@ pub(crate) extern "system" fn create_stream( }; at += size; } + // The whole state is read: integer targets do not blend on the host + // (`GraphicsState::integer_targets_do_not_blend`). + #[cfg(windows)] + if graphics.integer_targets_do_not_blend() { + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| { + tracing::info!( + "a pipeline of the title's blends into a render target of integers: blending is off for that target on the host (said once)" + ); + }); + } hand_out( shaders, #[cfg(windows)] @@ -502,8 +1051,43 @@ static FUNCTIONS: Table<24> = { pub(crate) mod host; #[cfg(windows)] mod library; + +/// Host pipelines created and loaded from the library since the start +/// (`crate::framelog`). +#[cfg(windows)] +pub(crate) fn frame_log_counts() -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + (library::MADE.load(Relaxed), library::LOADED.load(Relaxed)) +} #[cfg(windows)] mod make; +#[cfg(windows)] +mod recipe; + +#[cfg(windows)] +pub use recipe::Prepared; + +/// Makes the host pipeline of every recipe the runs kept (`victory +/// prepare`, with the game closed) into the pipeline library, on `threads` +/// workers; `progress` is called every 15 s and at the end (`true`). +#[cfg(windows)] +pub fn prepare_recipes(threads: usize, progress: &(dyn Fn(&Prepared, bool) + Sync)) -> Prepared { + recipe::prepare(threads, progress) +} + +/// Lets the pipeline library's mapped file go from memory when no pipeline +/// has loaded for a while (`library::trim`); called by the host's sweep. +#[cfg(windows)] +pub(crate) fn trim_library() { + library::trim(); +} + +/// The pipeline library's part of the report when the host device is +/// removed (`library::removal_note`). +#[cfg(windows)] +pub(crate) fn library_removal_note() -> String { + library::removal_note() +} /// Keeps compiled host pipelines, and the list of title pipelines to start /// early, in `dir` (a folder of the cache) across runs. @@ -541,6 +1125,55 @@ mod tests { .collect() } + #[test] + fn derived_pipelines_keep_the_base_shaders() { + let vs = [7u8, 8, 9]; + let none = || Bytecode { + code: std::ptr::null(), + size: 0, + }; + let desc = GraphicsHead { + root: std::ptr::null(), + stages: [ + Bytecode { + code: vs.as_ptr(), + size: vs.len(), + }, + none(), + none(), + none(), + none(), + ], + }; + let mut base = std::ptr::null(); + create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut base); + // A rasterizer part and one of the console's own. + let mut parts = vec![0u8; 2 * DERIVED_PART]; + parts[0] = 1; + parts[DERIVED_PART] = 5; + let mut derived = std::ptr::null(); + let hr = create_derived( + std::ptr::null(), + base, + 2, + parts.as_ptr(), + &PIPELINE_IIDS[0], + &mut derived, + ); + assert_eq!(hr, S_OK); + assert!(!derived.is_null() && derived != base); + assert_eq!(shaders(derived), [("vertex", vs.to_vec())]); + let hr = create_derived( + std::ptr::null(), + std::ptr::null(), + 0, + std::ptr::null(), + &PIPELINE_IIDS[0], + &mut derived, + ); + assert_eq!(hr, E_INVALIDARG); + } + #[test] fn pipelines_keep_their_shaders() { let (vs, ps) = ([1u8, 2, 3], [4u8; 5]); @@ -583,7 +1216,7 @@ mod tests { assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0); } - /// The stream layout Grand Theft Auto VI builds (title+0x86f090): root + /// The stream layout the title builds (title+0x86f090): root /// signature, five shader slots (the first a mesh shader), blend, sample /// mask, rasterizer, depth-stencil 1, sample description, input layout, /// topology, render target and depth formats: 0x2b0 bytes. @@ -637,3 +1270,25 @@ mod tests { } } } + +/// Whether a container is a pixel program of the title's decoration bake, +/// by its name inside (`PS_DecorationBlend_*`, `PS_BakeDecorations_*`: 51 +/// of them). Try 6.13, ported from edsuuu/VI-BR-PORT 10ac68f9 +/// (GPL-3.0-or-later): a list of four hashes (`crate::draw`'s) missed the +/// one the cutscene's faces are baked with (`PS_DecorationBlend_0011`, +/// fcee612943c008e0): its sources were not on the card and the face came +/// out black or flat. +#[cfg(windows)] +fn bakes(bytes: &[u8]) -> bool { + [&b"PS_DecorationBlend_"[..], b"PS_BakeDecorations_"] + .iter() + .any(|name| bytes.windows(name.len()).any(|w| w == *name)) +} + +#[cfg(all(test, windows))] +#[test] +fn bake_programs_are_known_by_name() { + assert!(bakes(b"..\0PS_DecorationBlend_0011_ff00f5de_Wrapped\0..")); + assert!(bakes(b"PS_BakeDecorations_0100_583f45fe_Wrapped")); + assert!(!bakes(b"PS_PedSkin_0001")); +} diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index a78366e042..0628fc34dd 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -152,7 +152,179 @@ fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D1 host } +/// The formats of what a draw draws into, as the host has them: the eight +/// render targets (0 where there is none), then depth (0 for none) +/// (fxceless). +pub(crate) type TargetFormats = [u32; 9]; + +/// Whether a draw into views of the formats `bound` cannot go to the host +/// with a pipeline that declares `declared`: a render target slot for which +/// the pipeline declares a format AND a view of another format is bound. On +/// the console the format is the view's, and the title draws so (a +/// pipeline declaring R10G10B10A2_UNORM into an R11G11B10_FLOAT target); on +/// the host that draw is an invalid call. A slot nothing is bound to does +/// not count; nor a view in a slot the pipeline declares nothing for; nor +/// the depth view (its own format can be a typeless one). +pub(crate) fn formats_differ(declared: &TargetFormats, bound: &TargetFormats) -> bool { + declared[..8].iter().zip(&bound[..8]).any(|(&d, &b)| d != 0 && b != 0 && b != d) +} + +/// The formats a pipeline for a draw into `bound` declares +/// ([`formats_differ`]): the title's own, but for the render target slots +/// it declares a format for and a view of another format is bound to, +/// which take the view's. The count of targets and the depth format stay +/// the title's. +pub(crate) fn formats_for(declared: &TargetFormats, bound: &TargetFormats) -> TargetFormats { + let mut formats = *declared; + for i in 0..8 { + if declared[i] != 0 && bound[i] != 0 { + formats[i] = bound[i]; + } + } + formats +} + +impl GraphicsState { + /// A state that declares one render target, of format `format` (tests). + #[cfg(test)] + pub(crate) fn declaring(format: i32) -> Self { + let mut g = Self::default(); + g.targets.NumRenderTargets = 1; + g.targets.RTFormats[0] = DXGI_FORMAT(format); + g + } + + /// The formats the state declares ([`TargetFormats`]): nothing past its + /// count of render targets. + pub(crate) fn formats(&self) -> TargetFormats { + let mut formats = [0; 9]; + let n = (self.targets.NumRenderTargets as usize).min(8); + for (to, from) in formats.iter_mut().zip(&self.targets.RTFormats[..n]) { + *to = from.0 as u32; + } + formats[8] = self.depth_format.0 as u32; + formats + } + + /// The same state for a draw into views of the formats `bound` (what + /// [`formats_for`] gives): those render target formats, everything else + /// the title's. Blending is decided again for them when the pipeline is + /// made ([`host_blend`]). Its [`GraphicsState::describe`] differs (the + /// formats are part of it), so its host pipeline has a name of its own + /// in the library. + pub(crate) fn with_formats(&self, bound: &TargetFormats) -> GraphicsState { + let mut g = self.derive(); + let n = (g.targets.NumRenderTargets as usize).min(8); + for (to, &from) in g.targets.RTFormats[..n].iter_mut().zip(bound) { + *to = DXGI_FORMAT(from as i32); + } + g + } + + /// Whether the title's blend state blends into a render target that + /// holds integers, which the host pipeline turns off ([`host_blend`]). + pub(crate) fn integer_targets_do_not_blend(&self) -> bool { + let count = (self.targets.NumRenderTargets as usize).min(8); + let per_target = self.blend.IndependentBlendEnable.as_bool(); + (0..count).any(|i| { + integer_format(self.targets.RTFormats[i]) + && self.blend.RenderTarget[if per_target { i } else { 0 }].BlendEnable.as_bool() + }) + } +} + +/// The layout [`GraphicsState::encode`] writes; a change to it changes this. +const RECIPE_STATE_VERSION: u32 = 1; + +/// Little-endian words, for [`GraphicsState::encode`]. +struct Writer(Vec<u8>); + +impl Writer { + fn u32(&mut self, v: u32) { + self.0.extend_from_slice(&v.to_le_bytes()); + } + + fn i32(&mut self, v: i32) { + self.0.extend_from_slice(&v.to_le_bytes()); + } +} + +/// The words a [`Writer`] wrote, in order. +struct Reader<'a>(&'a [u8]); + +impl Reader<'_> { + fn take(&mut self, n: usize) -> Option<&[u8]> { + if self.0.len() < n { + return None; + } + let (head, rest) = self.0.split_at(n); + self.0 = rest; + Some(head) + } + + fn u32(&mut self) -> Option<u32> { + Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) + } + + fn i32(&mut self) -> Option<i32> { + Some(i32::from_le_bytes(self.take(4)?.try_into().ok()?)) + } +} + impl GraphicsState { + /// A copy for a derived pipeline; its input elements point into its + /// own names. + pub(crate) fn derive(&self) -> GraphicsState { + let names = self.names.clone(); + let inputs = self + .inputs + .iter() + .zip(&names) + .map(|(e, name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + ..*e + }) + .collect(); + GraphicsState { + blend: self.blend, + sample_mask: self.sample_mask, + rasterizer: self.rasterizer, + depth: self.depth, + depth_bounds: self.depth_bounds, + inputs, + names, + strip_cut: self.strip_cut, + topology: self.topology, + targets: self.targets, + depth_format: self.depth_format, + samples: self.samples, + } + } + + /// Takes in one part of a derived pipeline (`CreateDerivedGraphicsPipelineStateX`): + /// 0 depth and stencil, 1 rasterizer, 2 blend, 3 sample mask; the + /// console's own parts are skipped. Returns whether the part is known. + /// + /// # Safety + /// `data` points at the part's description. + pub(crate) unsafe fn patch(&mut self, part: u32, data: *const u8) -> bool { + // SAFETY: the caller passes a whole part. + unsafe { + match part { + 0 => { + // A plain description: no depth bounds test (as before). + self.depth = data.cast::<D3D12_DEPTH_STENCIL_DESC>().read_unaligned(); + self.depth_bounds = false; + } + 1 => self.rasterizer = data.cast::<D3D12_RASTERIZER_DESC>().read_unaligned(), + 2 => self.blend = data.cast::<D3D12_BLEND_DESC>().read_unaligned(), + 3 => self.sample_mask = data.cast::<u32>().read_unaligned(), + _ => return false, + } + } + true + } + /// Takes in one subobject of a stream: its type, then its data at +4 /// (+8 for those holding pointers). /// @@ -220,7 +392,9 @@ impl GraphicsState { 15 => { self.targets = data.cast::<D3D12_RT_FORMAT_ARRAY>().read_unaligned(); for f in &mut self.targets.RTFormats { - f.0 = crate::resource::target_format(f.0 as u32) as i32; + f.0 = crate::resource::target_format(crate::resource::pc_format( + f.0 as u32, + )) as i32; } } 16 => { @@ -243,12 +417,7 @@ impl GraphicsState { .map(|(e, name)| { format!( "{name:?} {} {} {} {} {} {}", - e.SemanticIndex, - e.Format.0, - e.InputSlot, - e.AlignedByteOffset, - e.InputSlotClass.0, - e.InstanceDataStepRate + e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate ) }) .collect(); @@ -266,6 +435,236 @@ impl GraphicsState { ) + if self.bounds() { " depth bounds" } else { "" } } + /// What another pipeline of the same shaders must share with this one to + /// draw in its place ([`super::make::stand_in`]): what the host checks + /// against the list (input layout, topology, target and depth formats, + /// samples, the depth bounds test) and what would leave something + /// behind for later passes (depth and stencil writes, which targets are + /// written and blended). The rest (culling, the depth test's function + /// and bias, blend factors) may differ. + pub(crate) fn shape(&self) -> String { + let inputs: Vec<String> = self + .inputs + .iter() + .zip(&self.names) + .map(|(e, name)| format!("{name:?} {} {} {} {}", e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset)) + .collect(); + let targets: Vec<(i32, u8)> = self + .blend + .RenderTarget + .iter() + .map(|t| (t.BlendEnable.0, t.RenderTargetWriteMask)) + .collect(); + format!( + "{inputs:?} {} {} {:?} {} {:?} {} {} {} {:?} {}", + self.strip_cut.0, + self.topology.0, + self.targets, + self.depth_format.0, + self.samples, + self.bounds(), + self.depth.DepthWriteMask.0, + self.depth.StencilEnable.0, + targets, + self.blend.IndependentBlendEnable.0 + ) + } + + /// [`GraphicsState::shape`] without the depth and stencil writes: for + /// the second tier of stand-ins (`crate::pipeline::make`), a pipeline + /// that differs only in those may draw for one still being made. + pub(crate) fn loose_shape(&self) -> String { + let inputs: Vec<String> = self + .inputs + .iter() + .zip(&self.names) + .map(|(e, name)| format!("{name:?} {} {} {} {}", e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset)) + .collect(); + let targets: Vec<(i32, u8)> = self + .blend + .RenderTarget + .iter() + .map(|t| (t.BlendEnable.0, t.RenderTargetWriteMask)) + .collect(); + format!( + "loose {inputs:?} {} {} {:?} {} {:?} {} {:?} {}", + self.strip_cut.0, + self.topology.0, + self.targets, + self.depth_format.0, + self.samples, + self.bounds(), + targets, + self.blend.IndependentBlendEnable.0 + ) + } + + /// Everything the state holds, as bytes (a pipeline recipe kept for + /// `victory prepare`, read back by [`GraphicsState::decode`]). Field by + /// field: the descriptions' padding is never read. + pub(crate) fn encode(&self) -> Vec<u8> { + let mut w = Writer(Vec::with_capacity(512)); + w.u32(RECIPE_STATE_VERSION); + let b = &self.blend; + w.i32(b.AlphaToCoverageEnable.0); + w.i32(b.IndependentBlendEnable.0); + for t in &b.RenderTarget { + for v in [ + t.BlendEnable.0, + t.LogicOpEnable.0, + t.SrcBlend.0, + t.DestBlend.0, + t.BlendOp.0, + t.SrcBlendAlpha.0, + t.DestBlendAlpha.0, + t.BlendOpAlpha.0, + t.LogicOp.0, + ] { + w.i32(v); + } + w.u32(u32::from(t.RenderTargetWriteMask)); + } + w.u32(self.sample_mask); + let r = &self.rasterizer; + w.i32(r.FillMode.0); + w.i32(r.CullMode.0); + w.i32(r.FrontCounterClockwise.0); + w.i32(r.DepthBias); + w.u32(r.DepthBiasClamp.to_bits()); + w.u32(r.SlopeScaledDepthBias.to_bits()); + w.i32(r.DepthClipEnable.0); + w.i32(r.MultisampleEnable.0); + w.i32(r.AntialiasedLineEnable.0); + w.u32(r.ForcedSampleCount); + w.i32(r.ConservativeRaster.0); + let d = &self.depth; + w.i32(d.DepthEnable.0); + w.i32(d.DepthWriteMask.0); + w.i32(d.DepthFunc.0); + w.i32(d.StencilEnable.0); + w.u32(u32::from(d.StencilReadMask)); + w.u32(u32::from(d.StencilWriteMask)); + for f in [&d.FrontFace, &d.BackFace] { + w.i32(f.StencilFailOp.0); + w.i32(f.StencilDepthFailOp.0); + w.i32(f.StencilPassOp.0); + w.i32(f.StencilFunc.0); + } + w.u32(u32::from(self.depth_bounds)); + w.u32(self.inputs.len() as u32); + for (e, name) in self.inputs.iter().zip(&self.names) { + let name = name.as_bytes(); + w.u32(name.len() as u32); + w.0.extend_from_slice(name); + w.u32(e.SemanticIndex); + w.i32(e.Format.0); + w.u32(e.InputSlot); + w.u32(e.AlignedByteOffset); + w.i32(e.InputSlotClass.0); + w.u32(e.InstanceDataStepRate); + } + w.i32(self.strip_cut.0); + w.i32(self.topology.0); + for f in &self.targets.RTFormats { + w.i32(f.0); + } + w.u32(self.targets.NumRenderTargets); + w.i32(self.depth_format.0); + w.u32(self.samples.Count); + w.u32(self.samples.Quality); + w.0 + } + + /// The state [`GraphicsState::encode`] wrote; `None` for bytes it did + /// not write (another version, cut short). + pub(crate) fn decode(bytes: &[u8]) -> Option<GraphicsState> { + let mut r = Reader(bytes); + if r.u32()? != RECIPE_STATE_VERSION { + return None; + } + let mut g = GraphicsState::default(); + let b = &mut g.blend; + b.AlphaToCoverageEnable.0 = r.i32()?; + b.IndependentBlendEnable.0 = r.i32()?; + for t in &mut b.RenderTarget { + t.BlendEnable.0 = r.i32()?; + t.LogicOpEnable.0 = r.i32()?; + t.SrcBlend.0 = r.i32()?; + t.DestBlend.0 = r.i32()?; + t.BlendOp.0 = r.i32()?; + t.SrcBlendAlpha.0 = r.i32()?; + t.DestBlendAlpha.0 = r.i32()?; + t.BlendOpAlpha.0 = r.i32()?; + t.LogicOp.0 = r.i32()?; + t.RenderTargetWriteMask = u8::try_from(r.u32()?).ok()?; + } + g.sample_mask = r.u32()?; + let ra = &mut g.rasterizer; + ra.FillMode.0 = r.i32()?; + ra.CullMode.0 = r.i32()?; + ra.FrontCounterClockwise.0 = r.i32()?; + ra.DepthBias = r.i32()?; + ra.DepthBiasClamp = f32::from_bits(r.u32()?); + ra.SlopeScaledDepthBias = f32::from_bits(r.u32()?); + ra.DepthClipEnable.0 = r.i32()?; + ra.MultisampleEnable.0 = r.i32()?; + ra.AntialiasedLineEnable.0 = r.i32()?; + ra.ForcedSampleCount = r.u32()?; + ra.ConservativeRaster.0 = r.i32()?; + let d = &mut g.depth; + d.DepthEnable.0 = r.i32()?; + d.DepthWriteMask.0 = r.i32()?; + d.DepthFunc.0 = r.i32()?; + d.StencilEnable.0 = r.i32()?; + d.StencilReadMask = u8::try_from(r.u32()?).ok()?; + d.StencilWriteMask = u8::try_from(r.u32()?).ok()?; + for f in [&mut d.FrontFace, &mut d.BackFace] { + f.StencilFailOp.0 = r.i32()?; + f.StencilDepthFailOp.0 = r.i32()?; + f.StencilPassOp.0 = r.i32()?; + f.StencilFunc.0 = r.i32()?; + } + g.depth_bounds = r.u32()? != 0; + let count = r.u32()? as usize; + if count > 64 { + return None; + } + let mut elements = Vec::with_capacity(count); + for _ in 0..count { + let len = r.u32()? as usize; + let name = CString::new(r.take(len)?.to_vec()).ok()?; + let e = D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR::null(), + SemanticIndex: r.u32()?, + Format: DXGI_FORMAT(r.i32()?), + InputSlot: r.u32()?, + AlignedByteOffset: r.u32()?, + InputSlotClass: D3D12_INPUT_CLASSIFICATION(r.i32()?), + InstanceDataStepRate: r.u32()?, + }; + elements.push((e, name)); + } + g.names = elements.iter().map(|(_, name)| name.clone()).collect(); + g.inputs = elements + .iter() + .zip(&g.names) + .map(|((e, _), name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + ..*e + }) + .collect(); + g.strip_cut = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE(r.i32()?); + g.topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE(r.i32()?); + for f in &mut g.targets.RTFormats { + f.0 = r.i32()?; + } + g.targets.NumRenderTargets = r.u32()?; + g.depth_format = DXGI_FORMAT(r.i32()?); + g.samples.Count = r.u32()?; + g.samples.Quality = r.u32()?; + r.0.is_empty().then_some(g) + } + /// Whether the host pipeline tests depth bounds: the title's stream /// enables the test and the host has it (else it is left out, as /// before: pixels the test would drop are drawn). @@ -335,6 +734,17 @@ pub(crate) struct Input { const RECTANGLES: i32 = 19; const QUADS: i32 = 32; +/// Whether the title's root SRVs are bound as one-view tables of the +/// buffer's host copy, whose reads past its end return zeros, rather than +/// as root descriptors, which have no size: a mesh shader's vertex fetch +/// has no record limit, and a read past the copy reaches whatever the host +/// placed after it (memory it has freed: the device is removed, upstream +/// PR #493). `VICTORY_ROOT_SRV_DIRECT=1` goes back to root descriptors. +pub(crate) fn bounded_root_srvs() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_ROOT_SRV_DIRECT").is_none()) +} + /// One stage of a host pipeline and where its bindings go. pub(crate) struct Stage { pub(crate) shader: Arc<Shader>, @@ -347,6 +757,9 @@ pub(crate) struct Stage { /// Root parameters of its root views: (title root parameter, ours). pub(crate) root_cbvs: Vec<(u8, u32)>, pub(crate) root_srvs: Vec<(u8, u32)>, + /// Root UAVs: one-view tables like the SRVs (or root descriptors with + /// `VICTORY_ROOT_SRV_DIRECT=1`). + pub(crate) root_uavs: Vec<(u8, u32)>, } impl Stage { @@ -369,19 +782,16 @@ pub(crate) struct HostPipeline { /// The vertex buffer slots it reads (bit per slot). pub(crate) slots: u32, pub(crate) inputs: Vec<Input>, - /// Index buffer strip-cut value for graphics pipelines. - pub(crate) strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, + /// Has the geometry stage that completes the console's rectangles + /// (`victory_shader::emit::rect_list_gs`): its rectangle draws go out + /// as the title gives them, three vertices a rectangle. + pub(crate) rects: bool, /// Its shaders, for reports of slow submissions. pub(crate) name: String, - /// Multi-argument host command signatures bound to `root`, by argument - /// layout and record stride. - pub(crate) signatures: std::sync::Mutex< - Vec<( - Vec<crate::indirect_plan::HostIndirectArg>, - u32, - ID3D12CommandSignature, - )>, - >, + /// Its depth, stencil, cull and blend state in short, for the frame + /// listing (empty for compute). + #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] + pub(crate) state: String, } /// Logs a pipeline that gets no host pipeline, once per reason. @@ -399,6 +809,9 @@ impl HostPipeline { /// A host pipeline for vertex and pixel shaders with the graphics /// state `g`, or for one compute shader. pub(crate) fn new(shaders: &[Arc<Shader>], g: Option<&GraphicsState>) -> Option<HostPipeline> { + // For the report when the host device is removed: what this thread + // has in the library from here on. + super::library::label(format!("{shaders:?}")); let find = |stage| shaders.iter().find(|s| s.stage == stage); let compute = match shaders { [cs] if cs.stage == "compute" => Some(cs), @@ -428,10 +841,7 @@ impl HostPipeline { stages }; if mesh.is_some() && !host()?.mesh_shaders() { - return refuse( - "the host GPU has no mesh shaders (or no shader model 6.6)", - shaders, - ); + return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders); } for (s, _) in &stages { s.translated()?; @@ -440,8 +850,8 @@ impl HostPipeline { // The root signature the translated shaders' bindings define. let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new(); - // Root SRVs are bound as one-view tables (see below); their ranges - // must outlive the serialisation, so each is boxed here. + // The ranges table parameters point at, alive until the root + // signature is made. let mut ranges: Vec<Box<D3D12_DESCRIPTOR_RANGE1>> = Vec::new(); let mut samplers = Vec::new(); let mut bound = Vec::new(); @@ -453,6 +863,7 @@ impl HostPipeline { user_data_cbv: false, root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), }; let dwords = t.user_data_dwords(); if dwords > 0 { @@ -480,19 +891,35 @@ impl HostPipeline { D3D12_ROOT_PARAMETER_TYPE_SRV, &mut stage.root_srvs, ), + ( + &t.root_uavs, + D3D12_ROOT_PARAMETER_TYPE_UAV, + &mut stage.root_uavs, + ), ] { for &slot in slots { - out.push((slot, params.len() as u32)); - // A root SRV is a raw address the GPU reads without - // bounds: the console's reads past the title buffer - // land in other title memory, ours past its host copy - // in unmapped memory (a GPU page fault and a lost - // device in the world). A table of one raw view sized - // to the copy reads zeros there instead; the shader's - // binding (`t<slot>`, a ByteAddressBuffer) is the same. - if kind == D3D12_ROOT_PARAMETER_TYPE_SRV { + let uav = kind == D3D12_ROOT_PARAMETER_TYPE_UAV; + // Ours, not the title's, stay root descriptors: the + // table of strides, the directory of title memory by + // address and its fault notes. + let ours = if uav { + slot == victory_shader::emit::SLOT_FAULTS + } else { + slot == victory_shader::emit::SLOT_STRIDES + || slot == victory_shader::emit::SLOT_TABLE_STRIDES + || slot == victory_shader::emit::SLOT_MEMORY + }; + if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { + // A one-view table: the view's size bounds the + // reads (and a root UAV's writes), which a root + // descriptor leaves unbounded. + // (Our own table of strides stays a descriptor.) ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 { - RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + RangeType: if uav { + D3D12_DESCRIPTOR_RANGE_TYPE_UAV + } else { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV + }, NumDescriptors: 1, BaseShaderRegister: u32::from(slot), RegisterSpace: ROOT_CBV_SPACE, @@ -500,7 +927,8 @@ impl HostPipeline { | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, OffsetInDescriptorsFromTableStart: 0, })); - let range: &D3D12_DESCRIPTOR_RANGE1 = ranges.last().expect("just pushed"); + let range: *const D3D12_DESCRIPTOR_RANGE1 = &**ranges.last()?; + out.push((slot, params.len() as u32)); params.push(D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, Anonymous: D3D12_ROOT_PARAMETER1_0 { @@ -513,6 +941,7 @@ impl HostPipeline { }); continue; } + out.push((slot, params.len() as u32)); params.push(D3D12_ROOT_PARAMETER1 { ParameterType: kind, Anonymous: D3D12_ROOT_PARAMETER1_0 { @@ -527,13 +956,16 @@ impl HostPipeline { } } for (n, s) in t.static_samplers.iter().enumerate() { + // Sharper surfaces (`crate::sampler::enhance`). + let (mut filter, mut max_anisotropy, mut bias) = (s.filter, s.max_anisotropy, s.mip_lod_bias); + crate::sampler::enhance_static(&mut filter, &mut max_anisotropy, &mut bias, s.min_lod, s.max_lod); samplers.push(D3D12_STATIC_SAMPLER_DESC { - Filter: D3D12_FILTER(s.filter as i32), + Filter: D3D12_FILTER(filter as i32), AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32), AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32), AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32), - MipLODBias: s.mip_lod_bias, - MaxAnisotropy: s.max_anisotropy, + MipLODBias: bias, + MaxAnisotropy: max_anisotropy, ComparisonFunc: D3D12_COMPARISON_FUNC(s.comparison as i32), BorderColor: D3D12_STATIC_BORDER_COLOR(s.border as i32), MinLOD: s.min_lod, @@ -564,12 +996,6 @@ impl HostPipeline { ) }; if compute.is_some() { - // D3D12 rejects empty mandatory stages with E_INVALIDARG; on - // hardware that arrives as a GPU device removal instead of a - // clean refusal, so bail before CreateComputePipelineState. - if code(0).BytecodeLength == 0 { - return refuse("compute shader did not translate", shaders); - } let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { // SAFETY: a borrowed pointer the description never releases. pRootSignature: unsafe { std::mem::transmute_copy(&root) }, @@ -589,6 +1015,7 @@ impl HostPipeline { Err(e) => { tracing::warn!(error = %e, ?shaders, "host pipeline refused"); host.log_messages(); + dump_refused(shaders, &[code_bytes(&code(0))], &root_blob); return None; } }; @@ -601,10 +1028,10 @@ impl HostPipeline { root, stages: bound, name: format!("{shaders:?}"), - signatures: std::sync::Mutex::new(Vec::new()), slots: 0, inputs: Vec::new(), - strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, + rects: false, + state: String::new(), }); } let Some(g) = g else { @@ -627,6 +1054,7 @@ impl HostPipeline { Err(e) => { tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused"); host.log_messages(); + dump_refused(shaders, &[code_bytes(&code(0)), code_bytes(&code(1))], &root_blob); return None; } }; @@ -639,23 +1067,37 @@ impl HostPipeline { root, stages: bound, name: format!("{shaders:?}"), - signatures: std::sync::Mutex::new(Vec::new()), slots: 0, inputs: Vec::new(), - strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, + rects: false, + state: String::new(), }); } - // VS is mandatory; an empty bytecode causes GPU device removal on - // hardware (E_INVALIDARG on WARP). PS may be absent (depth-only). - if code(0).BytecodeLength == 0 { - return refuse("vertex shader did not translate", shaders); + // A pipeline the title makes for rectangles gets a geometry stage + // that completes each one from the three vertices the vertex + // shader made. Without it (refused here or by the host) the draws + // fall back on what `draw` does for rectangles. + let mut rect_gs = None; + if g.topology.0 == RECTANGLES { + let ps = stages.get(1).and_then(|(s, _)| s.translated()); + let vs = &stages[0].0.translated()?.host.dxil; + match victory_shader::emit::rect_list_gs(vs, ps.map(|t| &t.host.dxil[..])) { + Ok(gs) => rect_gs = Some(gs), + Err(e) => tracing::warn!(error = %e, ?shaders, "no rectangle geometry stage"), + } } - let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { // SAFETY: a borrowed pointer the description never releases. pRootSignature: unsafe { std::mem::transmute_copy(&root) }, VS: code(0), PS: code(1), + GS: rect_gs.as_ref().map_or(D3D12_SHADER_BYTECODE::default(), |gs| { + D3D12_SHADER_BYTECODE { + pShaderBytecode: gs.as_ptr().cast(), + BytecodeLength: gs.len(), + } + }), BlendState: host_blend(&g.blend, &g.targets), SampleMask: g.sample_mask, RasterizerState: g.rasterizer, @@ -677,28 +1119,50 @@ impl HostPipeline { SampleDesc: g.samples, ..Default::default() }; - let name = super::library::name( - "graphics", - &root_blob, - &[&code_bytes(&code(0)), &code_bytes(&code(1))], - &state, - ); - let made = if g.bounds() { - bounds_pipeline(&host.device, &desc, &root, g, &name) - } else { + // A pipeline with the geometry stage has a name of its own in the + // library; the others keep theirs. + let name = |gs: Option<&Vec<u8>>| match gs { + Some(gs) => super::library::name( + "graphics rectangles", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs[..]], + &state, + ), + None => super::library::name( + "graphics", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1))], + &state, + ), + }; + let make = |desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, name: &str| { + // The depth bounds test needs the stream form (DEPTH_STENCIL1). + if g.bounds() { + return bounds_pipeline(&host.device, desc, &root, g, name); + } super::library::pipeline( - &name, + name, // SAFETY: the description points at live data. - |library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) }, + |library, name| unsafe { library.LoadGraphicsPipeline(name, desc) }, // SAFETY: as above. - || unsafe { host.device.CreateGraphicsPipelineState(&desc) }, + || unsafe { host.device.CreateGraphicsPipelineState(desc) }, ) }; + let mut made = make(&desc, &name(rect_gs.as_ref())); + if made.is_err() && rect_gs.is_some() { + // The host refused the geometry stage: once more without it. + tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage"); + host.log_messages(); + desc.GS = D3D12_SHADER_BYTECODE::default(); + rect_gs = None; + made = make(&desc, &name(None)); + } let pso = match made { Ok(pso) => pso, Err(e) => { tracing::warn!(error = %e, ?shaders, "host pipeline refused"); host.log_messages(); + dump_refused(shaders, &[code_bytes(&desc.VS), code_bytes(&desc.PS)], &root_blob); return None; } }; @@ -720,10 +1184,36 @@ impl HostPipeline { root, stages: bound, name: format!("{shaders:?}"), - signatures: std::sync::Mutex::new(Vec::new()), slots: g.slots(), inputs: g.elements(), - strip_cut: g.strip_cut, + rects: rect_gs.is_some(), + state: { + let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]); + let face = |f: &D3D12_DEPTH_STENCILOP_DESC| { + format!( + "fail {} depth-fail {} pass {} func {}", + f.StencilFailOp.0, f.StencilDepthFailOp.0, f.StencilPassOp.0, f.StencilFunc.0 + ) + }; + format!( + "depth {} write {} func {}; stencil {} read {:#x} write {:#x} front [{}] back [{}]; cull {} front-ccw {}; blend {} src {} dst {} op {} mask {:#x}", + d.DepthEnable.as_bool(), + d.DepthWriteMask.0, + d.DepthFunc.0, + d.StencilEnable.as_bool(), + d.StencilReadMask, + d.StencilWriteMask, + face(&d.FrontFace), + face(&d.BackFace), + r.CullMode.0, + r.FrontCounterClockwise.as_bool(), + b.BlendEnable.as_bool(), + b.SrcBlend.0, + b.DestBlend.0, + b.BlendOp.0, + b.RenderTargetWriteMask + ) + }, }) } } @@ -809,10 +1299,7 @@ fn mesh_stream<D>( topology: Sub<D3D12_PRIMITIVE_TOPOLOGY_TYPE>, } let mut stream = Stream { - root: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, - root.as_raw(), - ), + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), blend: Sub( @@ -825,14 +1312,8 @@ fn mesh_stream<D>( ), raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), depth, - targets: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, - g.targets, - ), - dsv: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, - g.depth_format, - ), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), topology: Sub( D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, @@ -843,8 +1324,8 @@ fn mesh_stream<D>( } /// A vertex pipeline with the depth bounds test, which the plain -/// description cannot name: the same state as a stream, its depth -/// subobject `DEPTH_STENCIL1`. +/// description cannot name: the same state as a stream (geometry stage +/// included), its depth subobject `DEPTH_STENCIL1`. fn bounds_pipeline( device: &ID3D12Device, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, @@ -857,6 +1338,7 @@ fn bounds_pipeline( struct Stream { root: Sub<*mut std::ffi::c_void>, vs: Sub<D3D12_SHADER_BYTECODE>, + gs: Sub<D3D12_SHADER_BYTECODE>, ps: Sub<D3D12_SHADER_BYTECODE>, blend: Sub<D3D12_BLEND_DESC>, mask: Sub<u32>, @@ -869,55 +1351,31 @@ fn bounds_pipeline( dsv: Sub<DXGI_FORMAT>, samples: Sub<DXGI_SAMPLE_DESC>, } - let mut targets = D3D12_RT_FORMAT_ARRAY { + let targets = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: desc.NumRenderTargets, - ..Default::default() + RTFormats: desc.RTVFormats, }; - targets.RTFormats = desc.RTVFormats; let mut stream = Stream { - root: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, - root.as_raw(), - ), + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), vs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, desc.VS), + gs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, desc.GS), ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, desc.PS), blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, desc.BlendState), - mask: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, - desc.SampleMask, - ), - raster: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, - desc.RasterizerState, - ), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, desc.SampleMask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, desc.RasterizerState), depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, g.depth1()), - inputs: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, - desc.InputLayout, - ), - strip_cut: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, - desc.IBStripCutValue, - ), - topology: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, - desc.PrimitiveTopologyType, - ), - targets: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, - targets, - ), - dsv: Sub( - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, - desc.DSVFormat, - ), + inputs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, desc.InputLayout), + strip_cut: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, desc.IBStripCutValue), + topology: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, desc.PrimitiveTopologyType), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, desc.DSVFormat), samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, desc.SampleDesc), }; stream_pipeline(device, &mut stream, name) } /// Whether the host has the depth bounds test (`DepthBoundsTestSupported`); -/// said once when a title wants it and the host has not. +/// said once when the host has not. pub(crate) fn depth_bounds_supported() -> bool { static SUPPORTED: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); *SUPPORTED.get_or_init(|| { @@ -933,22 +1391,51 @@ pub(crate) fn depth_bounds_supported() -> bool { }; let supported = asked.is_ok() && options.DepthBoundsTestSupported.as_bool(); if !supported { - tracing::warn!( - "the host has no depth bounds test: pixels outside a title's depth bounds are drawn" - ); + tracing::warn!("the host has no depth bounds test: pixels outside a title's depth bounds are drawn"); } supported }) } /// The bytes of shader code (none for an absent stage). +/// With `VICTORY_DUMP_FAILED=<dir>`: a pipeline the host refused goes to +/// `<dir>/refused/`, the host DXIL of each stage and the root signature +/// (`{first hash}-{n}.dxil`, `{first hash}.rootsig`), so the refusal can be +/// replayed against the debug layer offline (`dxc -dumpbin`, a small +/// D3D12 program). The world's refusals are E_INVALIDARG without the +/// debug layer, which says nothing more. +fn dump_refused(shaders: &[Arc<Shader>], codes: &[Vec<u8>], root_blob: &[u8]) { + let Some(dir) = std::env::var_os("VICTORY_DUMP_FAILED") else { + return; + }; + let dir = std::path::PathBuf::from(dir).join("refused"); + if std::fs::create_dir_all(&dir).is_err() { + return; + } + let Some(first) = shaders.first() else { + return; + }; + for (i, code) in codes.iter().enumerate() { + if !code.is_empty() { + let _ = std::fs::write(dir.join(format!("{}-{i}.dxil", first.hash)), code); + } + } + let _ = std::fs::write(dir.join(format!("{}.rootsig", first.hash)), root_blob); + let _ = std::fs::write(dir.join(format!("{}.txt", first.hash)), format!("{shaders:?}\n")); + // The console containers too (4.8), as the title gave them: a refusal + // is studied with `victory translate` on them (only the host's DXIL was + // kept, which cannot be translated again another way). + for s in shaders { + let _ = std::fs::write(dir.join(format!("{}-{}.dxbc", s.stage, s.hash)), &s.container); + } +} + fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec<u8> { if code.pShaderBytecode.is_null() { return Vec::new(); } // SAFETY: a translation's own bytes, alive while its shader is. - unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::<u8>(), code.BytecodeLength) } - .to_vec() + unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::<u8>(), code.BytecodeLength) }.to_vec() } /// The most a host root signature may cost, in dwords. @@ -1061,62 +1548,6 @@ fn root_signature( #[cfg(test)] mod tests { - fn targets(formats: &[DXGI_FORMAT]) -> D3D12_RT_FORMAT_ARRAY { - let mut t = D3D12_RT_FORMAT_ARRAY { - NumRenderTargets: formats.len() as u32, - ..Default::default() - }; - t.RTFormats[..formats.len()].copy_from_slice(formats); - t - } - - fn blending(independent: bool) -> D3D12_BLEND_DESC { - let mut b = GraphicsState::default().blend; - b.IndependentBlendEnable = independent.into(); - for t in &mut b.RenderTarget { - t.BlendEnable = true.into(); - t.SrcBlend = D3D12_BLEND_SRC_ALPHA; - t.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; - } - b - } - - #[test] - fn integer_targets_do_not_blend() { - let t = targets(&[ - DXGI_FORMAT_R8G8B8A8_UNORM, - DXGI_FORMAT_R16G16B16A16_FLOAT, - DXGI_FORMAT_R8_UINT, - ]); - for independent in [false, true] { - let host = host_blend(&blending(independent), &t); - assert!(host.IndependentBlendEnable.as_bool()); - assert!(host.RenderTarget[0].BlendEnable.as_bool()); - assert!(host.RenderTarget[1].BlendEnable.as_bool()); - assert!(!host.RenderTarget[2].BlendEnable.as_bool()); - // The rest of the target's state is the title's. - assert_eq!(host.RenderTarget[2].SrcBlend, D3D12_BLEND_SRC_ALPHA); - assert_eq!(host.RenderTarget[0].DestBlend, D3D12_BLEND_INV_SRC_ALPHA); - } - } - - #[test] - fn blend_states_without_integer_blending_are_kept() { - // No integer target. - let b = blending(false); - let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R11G11B10_FLOAT]); - assert_eq!(host_blend(&b, &t), b); - // An integer target that does not blend. - let mut b = blending(true); - b.RenderTarget[1].BlendEnable = false.into(); - let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT]); - assert_eq!(host_blend(&b, &t), b); - // Integer formats past the targets in use. - let mut t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM]); - t.RTFormats[1] = DXGI_FORMAT_R8_UINT; - assert_eq!(host_blend(&blending(false), &t), blending(false)); - } - /// A stream's `DEPTH_STENCIL1` keeps its depth bounds test; a plain /// `DEPTH_STENCIL` after it turns the test off again. #[test] @@ -1138,6 +1569,7 @@ mod tests { let one = g.depth1(); assert!(one.DepthBoundsTestEnable.as_bool()); assert_eq!(one.DepthFunc, D3D12_COMPARISON_FUNC_GREATER_EQUAL); + assert!(g.derive().depth_bounds, "a derived pipeline keeps the test"); #[repr(C, align(8))] struct Sub0(u32, D3D12_DEPTH_STENCIL_DESC); let sub = Sub0(11, D3D12_DEPTH_STENCIL_DESC::default()); @@ -1147,6 +1579,48 @@ mod tests { assert!(!g.bounds()); } + /// A recipe's state reads back as it was written: the same description + /// (its name in the library), input names and all. + #[test] + fn graphics_state_reads_back_from_a_recipe() { + let mut g = GraphicsState::default(); + g.blend.RenderTarget[1].BlendEnable = true.into(); + g.blend.RenderTarget[1].RenderTargetWriteMask = 0x7; + g.rasterizer.DepthBias = -12; + g.rasterizer.SlopeScaledDepthBias = 1.5; + g.depth.StencilReadMask = 0x3c; + g.depth.BackFace.StencilFunc = D3D12_COMPARISON_FUNC_EQUAL; + g.depth_bounds = true; + g.names = vec![c"POSITION".to_owned(), c"TEXCOORD".to_owned()]; + g.inputs = g + .names + .iter() + .enumerate() + .map(|(i, name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + SemanticIndex: i as u32, + Format: DXGI_FORMAT_R32G32B32_FLOAT, + InputSlot: 0, + AlignedByteOffset: 12 * i as u32, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + }) + .collect(); + g.topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + g.targets.NumRenderTargets = 2; + g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + g.targets.RTFormats[1] = DXGI_FORMAT_R16G16B16A16_FLOAT; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + let bytes = g.encode(); + let back = GraphicsState::decode(&bytes).expect("reads back"); + assert_eq!(back.describe(), g.describe()); + assert_eq!(back.encode(), bytes); + // SAFETY: the name points into `back.names`, alive here. + let name = unsafe { CStr::from_ptr(back.inputs[1].SemanticName.0.cast()) }; + assert_eq!(name, c"TEXCOORD"); + assert!(GraphicsState::decode(&bytes[..bytes.len() - 1]).is_none()); + } + /// Over 64 dwords, the largest user data blocks become root CBVs until /// the signature fits; under it nothing changes. #[test] @@ -1186,6 +1660,88 @@ mod tests { use super::*; + /// A draw needs another host pipeline only for a bound view whose + /// format its pipeline does not name for that slot (fxceless). + #[test] + fn bound_formats_are_compared_slot_by_slot() { + let mut g = GraphicsState::default(); + g.targets.NumRenderTargets = 2; + g.targets.RTFormats[0] = DXGI_FORMAT_R10G10B10A2_UNORM; + g.targets.RTFormats[1] = DXGI_FORMAT_R8G8B8A8_UNORM; + // Past the count: not declared. + g.targets.RTFormats[2] = DXGI_FORMAT_R8_UINT; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + let declared = g.formats(); + assert_eq!(declared, [24, 28, 0, 0, 0, 0, 0, 0, 40]); + assert!(!formats_differ(&declared, &declared)); + assert!(!formats_differ(&declared, &[24, 0, 0, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[0; 9])); + assert!(formats_differ(&declared, &[26, 28, 0, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 28, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 0, 0, 0, 0, 0, 0, 45])); + assert_eq!(formats_for(&declared, &[26, 28, 28, 0, 0, 0, 0, 0, 45]), [26, 28, 0, 0, 0, 0, 0, 0, 40]); + assert_eq!(formats_for(&declared, &declared), declared); + let v = g.with_formats(&formats_for(&declared, &[26, 0, 0, 0, 0, 0, 0, 0, 0])); + assert_eq!(v.formats(), [26, 28, 0, 0, 0, 0, 0, 0, 40]); + assert_ne!(v.describe(), g.describe()); + } + + fn targets(formats: &[DXGI_FORMAT]) -> D3D12_RT_FORMAT_ARRAY { + let mut t = D3D12_RT_FORMAT_ARRAY { + NumRenderTargets: formats.len() as u32, + ..Default::default() + }; + t.RTFormats[..formats.len()].copy_from_slice(formats); + t + } + + fn blending(independent: bool) -> D3D12_BLEND_DESC { + let mut b = GraphicsState::default().blend; + b.IndependentBlendEnable = independent.into(); + for t in &mut b.RenderTarget { + t.BlendEnable = true.into(); + t.SrcBlend = D3D12_BLEND_SRC_ALPHA; + t.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + } + b + } + + #[test] + fn integer_targets_do_not_blend() { + let t = targets(&[ + DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16B16A16_FLOAT, + DXGI_FORMAT_R8_UINT, + ]); + for independent in [false, true] { + let host = host_blend(&blending(independent), &t); + assert!(host.IndependentBlendEnable.as_bool()); + assert!(host.RenderTarget[0].BlendEnable.as_bool()); + assert!(host.RenderTarget[1].BlendEnable.as_bool()); + assert!(!host.RenderTarget[2].BlendEnable.as_bool()); + // The rest of the target's state is the title's. + assert_eq!(host.RenderTarget[2].SrcBlend, D3D12_BLEND_SRC_ALPHA); + assert_eq!(host.RenderTarget[0].DestBlend, D3D12_BLEND_INV_SRC_ALPHA); + } + } + + #[test] + fn blend_states_without_integer_blending_are_kept() { + // No integer target. + let b = blending(false); + let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R11G11B10_FLOAT]); + assert_eq!(host_blend(&b, &t), b); + // An integer target that does not blend. + let mut b = blending(true); + b.RenderTarget[1].BlendEnable = false.into(); + let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT]); + assert_eq!(host_blend(&b, &t), b); + // Integer formats past the targets in use. + let mut t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM]); + t.RTFormats[1] = DXGI_FORMAT_R8_UINT; + assert_eq!(host_blend(&blending(false), &t), blending(false)); + } + /// A triangle mesh shader of our own and a pixel shader for it. const MS: &str = "struct V { float4 p : SV_Position; }; [outputtopology(\"triangle\")] [numthreads(1, 1, 1)] @@ -1238,6 +1794,10 @@ mod tests { let Some(host) = host() else { return; // no host GPU here }; + if !host.mesh_shaders() { + eprintln!("no host mesh shader support; skipped"); + return; + } let Some(dxc) = dxc() else { eprintln!("no PC dxc.exe; skipped"); return; @@ -1247,6 +1807,8 @@ mod tests { let ps = compile(&dxc, dir.path(), PS, "ps_6_5"); let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap(); let mut g = GraphicsState::default(); + // This pipeline has only a color target, with no depth buffer. + g.depth.DepthEnable = false.into(); g.targets.NumRenderTargets = 1; g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe()); diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index b3312ed4db..e9e4994644 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -12,13 +12,45 @@ //! graphics state); the next run hands those to the workers at //! creation, during loading. //! -//! All library calls are serialised: the interface does not promise that -//! stores, loads and serialising may overlap. +//! Library calls overlap: the host documents the library as safe to use +//! from several threads ("The pipeline library is thread-safe to use, and +//! will internally synchronize as necessary", `CreatePipelineLibrary`, +//! Thread Safety), with one exception kept here: two loads of the same +//! pipeline are made one after the other ([`same_name`]). Under one lock of +//! ours for every call, the eight workers made pipelines one at a time: +//! 87 to 96 of 110 looks at each worker found it waiting for that lock +//! (run 49), and an earlier run's 2,300 pipelines, all in the library, were +//! still being loaded 46 s into the opening cutscene. +//! `VICTORY_LIBRARY_LOCK=1`: one call at a time, as before. +//! +//! The library's file is mapped, not read into memory ([`Blob`]): the host +//! keeps pointing into the bytes it was made from for as long as it lives, +//! and read into a buffer they were 1,352 MB of the process's own memory +//! for the whole run (run 60), all of it in physical memory. Mapped, the +//! pages are the file's: only those the host reads are in memory, and the +//! system can drop them without writing them anywhere. A save writes the +//! new library through a mapping of the new file in the same way (a buffer +//! of the library's size was made, filled and written out at each save). +//! `VICTORY_LIBRARY_MAP=0`: read and written through buffers, as before. +//! +//! The mapped file's handle stays open for as long as the mapping lives +//! ([`holds`]). A save renames the new library over the file this run has +//! mapped, and with the handle closed Windows then gives up the old file's +//! contents: every page of the mapping that is not in memory at that +//! moment, or leaves memory later (the trim below, or Windows taking pages +//! back), reads as zeros from then on. The host's library reads such pages +//! as stored pipelines; the driver, handed a pipeline of zeros, removes the +//! device with DXGI_ERROR_DRIVER_INTERNAL_ERROR (runs 72, 73 and 82, each +//! within 5 ms of the first library call after a save and a trim; and the +//! library run 77 saved from such pages was refused by run 78). Measured +//! with a 64 MB file written past the system's cache, mapped and replaced: +//! 16,352 of 16,384 pages read zeros with the handle closed, none with it +//! open (the test below). `VICTORY_LIBRARY_HANDLE=0`: closed, as before. use std::collections::HashSet; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Mutex, MutexGuard, OnceLock, RwLock, TryLockError}; use windows::Win32::Graphics::Direct3D12::*; use windows::core::{HSTRING, Interface, PCWSTR}; @@ -30,119 +62,619 @@ pub fn use_pipeline_cache(dir: PathBuf) { let _ = DIR.set(dir); } +/// The pipeline cache's folder, if one is used. +pub(crate) fn dir() -> Option<&'static std::path::Path> { + DIR.get().map(PathBuf::as_path) +} + /// Host pipelines created, loaded from the library, and title pipelines /// started at creation, since the start. pub(crate) static MADE: AtomicU64 = AtomicU64::new(0); pub(crate) static LOADED: AtomicU64 = AtomicU64::new(0); pub(crate) static EARLY: AtomicU64 = AtomicU64::new(0); +/// For the memory lines: the bytes of the library's file, kept in memory +/// while the library lives, and the bytes the last save wrote (a buffer of +/// that size is made, filled and written every time pipelines were added, +/// at most every 20 s). +pub(crate) static BLOB: AtomicU64 = AtomicU64::new(0); +pub(crate) static SAVED: AtomicU64 = AtomicU64::new(0); + +/// Whether the library's file is mapped ([`Blob`]) and saved through a +/// mapping. On by default; `VICTORY_LIBRARY_MAP=0` uses buffers, as before. +fn mapped() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_MAP").is_none_or(|v| v != "0")) +} + +/// Whether the mapped library file's handle is kept open while it is +/// mapped (see the module's notes: without it a save in the same run turns +/// the mapping's pages into zeros as they leave memory). On by default; +/// `VICTORY_LIBRARY_HANDLE=0` closes it after mapping, as before. +fn holds() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_HANDLE").is_none_or(|v| v != "0")) +} + +/// A whole file mapped into memory: read-only (the library's file) or +/// writable (the file a save fills). Unmapped when dropped. +struct Mapped { + at: windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS, + len: usize, + /// The file, for a mapping made by [`Mapped::open`] ([`holds`]): open + /// until after the view is unmapped, so that the file a rename took + /// the name from keeps its contents for the view. + _file: Option<std::fs::File>, +} + +impl Mapped { + /// Maps `file` (`len` bytes, not zero) for reading, or for reading and + /// writing. + fn map(file: &std::fs::File, len: usize, write: bool) -> Option<Mapped> { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MapViewOfFile, PAGE_READONLY, PAGE_READWRITE, + }; + if len == 0 { + return None; + } + // SAFETY: a file we hold open; the view keeps the file's pages + // after the mapping object and the file are closed. + let at = unsafe { + let mapping = CreateFileMappingW( + file.as_raw_handle(), + std::ptr::null(), + if write { PAGE_READWRITE } else { PAGE_READONLY }, + 0, + 0, + std::ptr::null(), + ); + if mapping.is_null() { + return None; + } + let at = MapViewOfFile(mapping, if write { FILE_MAP_WRITE } else { FILE_MAP_READ }, 0, 0, 0); + CloseHandle(mapping); + at + }; + (!at.Value.is_null()).then_some(Mapped { at, len, _file: None }) + } + + /// The file at `path`, mapped for reading; `None` if it is not there, + /// is empty or cannot be mapped. + fn open(path: &std::path::Path) -> Option<Mapped> { + Mapped::open_holding(path, holds()) + } + + /// As [`Mapped::open`]; `hold` says whether the file stays open with + /// the mapping. + fn open_holding(path: &std::path::Path, hold: bool) -> Option<Mapped> { + // Opened as the standard library opens a file to read: others may + // read, write, rename and delete it meanwhile, so a save still + // renames the new library over this one. + let file = std::fs::File::open(path).ok()?; + let len = usize::try_from(file.metadata().ok()?.len()).ok()?; + let mut mapped = Mapped::map(&file, len, false)?; + if hold { + mapped._file = Some(file); + } + Some(mapped) + } + + /// A new file of `len` bytes at `path` (replacing what is there), + /// mapped for writing. + fn create(path: &std::path::Path, len: usize) -> Option<Mapped> { + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(path) + .ok()?; + file.set_len(len as u64).ok()?; + Mapped::map(&file, len, true) + } + + fn bytes(&self) -> &[u8] { + // SAFETY: the view holds `len` readable bytes until dropped. + unsafe { std::slice::from_raw_parts(self.at.Value.cast(), self.len) } + } + + /// Only for a view made by [`Mapped::create`]. + fn bytes_mut(&mut self) -> &mut [u8] { + // SAFETY: a writable view of `len` bytes, ours alone. + unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) } + } +} + +impl Drop for Mapped { + fn drop(&mut self) { + // SAFETY: our view. + unsafe { windows_sys::Win32::System::Memory::UnmapViewOfFile(self.at) }; + } +} + +/// The bytes a library is made from: the host reads them for as long as +/// the library lives, so they are kept beside it. +enum Blob { + /// No file (an empty library). + None, + /// The file read into memory (`VICTORY_LIBRARY_MAP=0`, tests, or a file + /// that could not be mapped). + Held(Vec<u8>), + /// The file itself, mapped. + Mapped(Mapped), +} + +impl Blob { + /// The library file in `dir`: a library a save left beside it + /// ([`NEXT_FILE`]) takes its place first. + fn of(dir: &std::path::Path) -> Blob { + let path = dir.join(LIBRARY_FILE); + let next = dir.join(NEXT_FILE); + if next.exists() && std::fs::rename(&next, &path).is_err() { + tracing::warn!("the host pipeline library saved last could not take the old one's place"); + } + if mapped() + && let Some(file) = Mapped::open(&path) + { + prefetch(file.at.Value as usize, file.len); + return Blob::Mapped(file); + } + match std::fs::read(&path) { + Ok(bytes) if !bytes.is_empty() => Blob::Held(bytes), + _ => Blob::None, + } + } + + fn bytes(&self) -> &[u8] { + match self { + Blob::None => &[], + Blob::Held(bytes) => bytes, + Blob::Mapped(file) => file.bytes(), + } + } +} + +/// Try 6.4: the mapped library file read into memory at the start, on a +/// thread of its own, while the PC has its memory to spare +/// (`VICTORY_LIBRARY_PREFETCH=0`: not). The pipelines the title asks for at +/// the loading screen then load from memory: in the 6.2 report pipelines +/// loaded from the library took 2.6-4.5 s each there, read page by page +/// from the disk. (A hint to the system: the pages are the file's, which it +/// may drop again when memory runs short.) +/// +/// Try 6.11: the room left free after it is 1 GB (4 GB before; +/// `VICTORY_LIBRARY_PREFETCH_ROOM_MB` sets it), and with less free than the +/// whole file needs the front of it is read ahead, as much as fits (the +/// library is written in the order runs asked for pipelines, the loading +/// screen's first). On a 16 GB laptop with 4.2 GB free the 773 MB library +/// was not read ahead at all in the 6.7 report, so every pipeline loaded +/// from it in play waited on the disk: stutter while "shaders compile". +fn prefetch(at: usize, len: usize) { + if len == 0 || std::env::var_os("VICTORY_LIBRARY_PREFETCH").is_some_and(|v| v == "0") { + return; + } + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32; + // SAFETY: a sized structure. + let free = if unsafe { GlobalMemoryStatusEx(&mut m) } != 0 { m.ullAvailPhys } else { 0 }; + let room = std::env::var("VICTORY_LIBRARY_PREFETCH_ROOM_MB") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(1024) + << 20; + let fits = usize::try_from(free.saturating_sub(room)).unwrap_or(usize::MAX); + // Less than 64 MB is not worth a thread. + if fits < 64 << 20 { + tracing::info!( + free_mb = free >> 20, + library_mb = len >> 20, + room_mb = room >> 20, + "host pipeline library not read ahead: the PC has too little memory free (VICTORY_LIBRARY_PREFETCH_ROOM_MB)" + ); + return; + } + let whole = len; + let len = len.min(fits); + if len < whole { + tracing::info!( + free_mb = free >> 20, + library_mb = whole >> 20, + read_mb = len >> 20, + "host pipeline library read ahead in part: the front of it, as much as leaves the PC its room free" + ); + } + let spawned = std::thread::Builder::new().name("library read-ahead".into()).spawn(move || { + use windows_sys::Win32::System::Memory::{PrefetchVirtualMemory, WIN32_MEMORY_RANGE_ENTRY}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let began = std::time::Instant::now(); + let range = WIN32_MEMORY_RANGE_ENTRY { VirtualAddress: at as *mut core::ffi::c_void, NumberOfBytes: len }; + // SAFETY: a range of this process's mapped view of the library + // file; the call only reads its pages in (a hint, it changes no + // byte). + let ok = unsafe { PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0) } != 0; + tracing::info!( + ok, + mb = len >> 20, + ms = began.elapsed().as_millis() as u64, + "host pipeline library read ahead into memory (VICTORY_LIBRARY_PREFETCH=0: not)" + ); + }); + if let Err(e) = spawned { + tracing::warn!(error = %e, "no thread to read the host pipeline library ahead"); + } +} + +/// The mapped library file's view (address, bytes; 0: not mapped), when a +/// pipeline was last loaded from the library (`crate::host::now_ms`), and +/// whether the view's pages were let go since ([`trim`]). +static VIEW: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; +static LOADED_AT: AtomicU64 = AtomicU64::new(0); +static TRIMMED: AtomicBool = AtomicBool::new(false); +/// The bytes of the view let go so far, for the memory line. +pub(crate) static TRIMMED_BYTES: AtomicU64 = AtomicU64::new(0); +/// When the view's pages were last let go (`crate::host::now_ms`), and how +/// often and when a save of this run last renamed a new library over the +/// mapped file: for [`removal_note`]. +static TRIMMED_AT: AtomicU64 = AtomicU64::new(0); +static REPLACED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The library calls running now: thread, what (load, make, store, +/// serialise), the pipeline, and since when (`crate::host::now_us`). +static CALLS: Mutex<Vec<(u32, &'static str, String, u64)>> = Mutex::new(Vec::new()); + +thread_local! { + /// The pipeline this thread is making (its shaders), for [`CALLS`]. + static LABEL: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) }; +} + +/// Names the pipeline this thread makes next. +pub(crate) fn label(text: String) { + LABEL.with(|l| *l.borrow_mut() = text); +} + +/// A library call of this thread, listed in [`CALLS`] until dropped. +struct Call(u32, u64); + +fn call(what: &'static str, name: &str) -> Call { + let (thread, since) = (crate::host::thread_id(), crate::host::now_us()); + let label = LABEL.with(|l| l.borrow().clone()); + CALLS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((thread, what, format!("{name} {label}"), since)); + Call(thread, since) +} + +impl Drop for Call { + fn drop(&mut self) { + CALLS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|c| (c.0, c.3) != (self.0, self.1)); + } +} + +/// For the report when the host device is removed: the library calls +/// running at that moment, whether this run replaced the mapped file and +/// let its pages go, and how many pages of the mapping read as zeros now. +/// A library holds no page of zeros (the 259 MB one of run 83 has no run of +/// 2,048 zero bytes): each such page is one whose contents were lost (see +/// the module's notes), and a pipeline stored there is what the driver was +/// handed. +pub(crate) fn removal_note() -> String { + use std::fmt::Write; + let now = crate::host::now_us(); + let mut text = String::from("pipeline library: "); + { + let calls = CALLS.lock().unwrap_or_else(|e| e.into_inner()); + if calls.is_empty() { + text.push_str("no call running"); + } + for (i, (thread, what, name, since)) in calls.iter().enumerate() { + let _ = write!( + text, + "{}{what} of {name} running for {:.1} ms on thread {thread}", + if i == 0 { "" } else { ", " }, + now.saturating_sub(*since) as f64 / 1000.0 + ); + } + } + let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + if at == 0 { + text.push_str("; its file is not mapped"); + return text; + } + let ago = |ms: u64| crate::host::now_ms().saturating_sub(ms) as f64 / 1000.0; + let _ = write!( + text, + "; its file is mapped ({len} bytes), the handle {}", + if holds() { "kept open" } else { "closed (VICTORY_LIBRARY_HANDLE=0)" } + ); + match REPLACED[0].load(Ordering::Relaxed) { + 0 => text.push_str("; this run has not replaced the file"), + n => { + let _ = write!( + text, + "; this run replaced the file under the mapping {n} times, last {:.1} s ago", + ago(REPLACED[1].load(Ordering::Relaxed)) + ); + } + } + if TRIMMED_BYTES.load(Ordering::Relaxed) > 0 { + let _ = write!(text, "; its pages were last let go {:.1} s ago", ago(TRIMMED_AT.load(Ordering::Relaxed))); + } + // Within two seconds: pages not in memory come from the disk. + let started = std::time::Instant::now(); + // SAFETY: the view lives as long as the library, which is never dropped. + let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, len) }; + let (mut zero, mut looked, mut first) = (0u64, 0u64, None); + for (n, page) in bytes.chunks(4096).enumerate() { + if n % 4096 == 0 && started.elapsed() > std::time::Duration::from_secs(2) { + break; + } + looked += 1; + if page.iter().all(|&b| b == 0) { + zero += 1; + if first.is_none() { + first = Some(n); + } + } + } + let _ = write!(text, "; {zero} of the {looked} pages looked at read as zeros now"); + if let Some(first) = first { + let _ = write!(text, " (the first is page {first}): the library's contents were lost there"); + } + text +} + +/// Lets the mapped library file's pages go from the process's memory once +/// no pipeline has been loaded for ten seconds. The host reads nearly the +/// whole file while the early pipelines load (run 65: all 1,490 MB of it +/// were in the process's memory a minute in, and 1,300 MB still at the +/// end, on a PC with 2 GB free); after that it reads the file again only +/// when a new pipeline loads. Pages let go stay in Windows' file cache +/// while nothing else wants the memory, and come back on the next read. +/// Called once a second by the sweep; does its work on a thread of its own +/// (hundreds of thousands of pages), once after each burst of loads. +/// `VICTORY_LIBRARY_TRIM=0`: the pages stay until Windows takes them. +pub(crate) fn trim() { + static ON: OnceLock<bool> = OnceLock::new(); + let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + if at == 0 + || TRIMMED.load(Ordering::Relaxed) + || !*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_TRIM").is_none_or(|v| v != "0")) + { + return; + } + let quiet_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + if crate::host::now_ms() < LOADED_AT.load(Ordering::Relaxed) + quiet_ms + || TRIMMED.swap(true, Ordering::Relaxed) + { + return; + } + let work = move || { + // SAFETY: the view lives as long as the library, which is never + // dropped. Unlocking pages that are not locked fails, as expected, + // and takes them out of the working set: the documented way to let + // pages of a mapped file go. + unsafe { windows_sys::Win32::System::Memory::VirtualUnlock(at as *const _, len) }; + TRIMMED_BYTES.fetch_add(len as u64, Ordering::Relaxed); + TRIMMED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + crate::host::trail(|| format!("pipeline library: the mapped file's pages let go from memory ({len} bytes)")); + }; + if std::thread::Builder::new().name("victory-library-trim".into()).spawn(work).is_err() { + TRIMMED.store(false, Ordering::Relaxed); + } +} struct Library { library: ID3D12PipelineLibrary1, /// The blob the library was made from: it must outlive the library. - _blob: Vec<u8>, + _blob: Blob, /// Pipelines stored since the last save. - added: u64, + added: AtomicU64, + /// Stores share it and a save takes it alone: the size the library + /// asks for must still be its size when it is written out. + saving: RwLock<()>, } -// SAFETY: D3D12 objects are free-threaded; every call is made under the -// mutex that holds the library. +// SAFETY: D3D12 objects are free-threaded, and the library synchronises +// its own calls (see the module's notes); what it does not, two loads of +// one name, is serialised by `same_name`. unsafe impl Send for Library {} +// SAFETY: as above; the other fields are an atomic and a lock. +unsafe impl Sync for Library {} + +/// Held by a load of the pipeline named `name`: loads of the same name +/// wait for each other (the host's one exception to the library's thread +/// safety: such a load may change that pipeline's entry). Names share 64 +/// locks, so two different names seldom wait. +fn same_name(name: &str) -> MutexGuard<'static, ()> { + static LOADING: [Mutex<()>; 64] = [const { Mutex::new(()) }; 64]; + let at = name.bytes().fold(0usize, |h, b| h.wrapping_mul(31).wrapping_add(usize::from(b))); + LOADING[at % LOADING.len()].lock().unwrap_or_else(|e| e.into_inner()) +} + +/// With `VICTORY_LIBRARY_LOCK=1`: held by every library call, as before. +fn one_call() -> Option<MutexGuard<'static, ()>> { + static ON: OnceLock<bool> = OnceLock::new(); + static CALLING: Mutex<()> = Mutex::new(()); + ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_LOCK").is_some_and(|v| v == "1")) + .then(|| CALLING.lock().unwrap_or_else(|e| e.into_inner())) +} const LIBRARY_FILE: &str = "host-pipelines.bin"; +/// A library the driver refused, kept as it was ([`open`]). +const REJECTED_FILE: &str = "host-pipelines.rejected.bin"; +/// A saved library that could not replace [`LIBRARY_FILE`] while this run +/// had it mapped (a system that refuses to replace a mapped file): the next +/// start renames it over the library first ([`Blob::of`]). +const NEXT_FILE: &str = "host-pipelines.next"; const EARLY_FILE: &str = "early-pipelines.txt"; +/// Pipelines the host's compiler failed on with `E_OUTOFMEMORY`, and in how +/// many launches (see [`crashes`]). +const CRASHED_FILE: &str = "crashed-pipelines.txt"; /// Title pipelines listed for an early start, at most. const EARLY_MAX: usize = 8192; -fn library() -> Option<&'static Mutex<Library>> { - static LIBRARY: OnceLock<Option<Mutex<Library>>> = OnceLock::new(); +/// Whether the library came from this cache's file (not rejected: the same +/// adapter and driver as when it was saved). +static KEPT: AtomicBool = AtomicBool::new(false); + +/// The pipelines NVIDIA's compiler crashed on, by name, and in how many +/// launches. In a world run on an RTX 4060, 25 compute pipelines took the +/// driver's compiler down (an access violation in `nvgpucomp64.dll`, four +/// times each, reported as `E_OUTOFMEMORY`), each holding a worker for +/// 10-40 s, again at every launch, while 1,675 other pipelines waited. +/// One that failed in two launches is no longer tried (its draws are +/// dropped, as when it fails); a real shortage of memory passes the second +/// time and is forgotten. A driver or adapter change (the library file is +/// rejected) forgets them all. `VICTORY_RETRY_CRASHED=1` tries them anyway. +fn crashes() -> &'static Mutex<std::collections::HashMap<String, u32>> { + static CRASHES: OnceLock<Mutex<std::collections::HashMap<String, u32>>> = OnceLock::new(); + CRASHES.get_or_init(|| { + let mut map = std::collections::HashMap::new(); + if let Some(dir) = DIR.get() { + let path = dir.join(CRASHED_FILE); + if library().is_some() && KEPT.load(Ordering::Relaxed) { + map = parse_crashes(&std::fs::read_to_string(&path).unwrap_or_default()); + } else { + let _ = std::fs::remove_file(&path); + } + } + Mutex::new(map) + }) +} + +/// `name launches` lines. +fn parse_crashes(text: &str) -> std::collections::HashMap<String, u32> { + text.lines() + .filter_map(|l| { + let (name, n) = l.trim().split_once(' ')?; + Some((name.to_owned(), n.parse().ok()?)) + }) + .collect() +} + +/// Whether the pipeline `name` crashed the compiler in two launches before. +fn crashed_before(name: &str) -> bool { + if std::env::var_os("VICTORY_RETRY_CRASHED").is_some_and(|v| v == "1") { + return false; + } + crashes().lock().unwrap_or_else(|e| e.into_inner()).get(name).is_some_and(|&n| n >= 2) +} + +/// Records how making the pipeline `name` went: a compiler failure counts +/// a launch more (once per launch), a success forgets it. +fn note_made(name: &str, crashed: bool) { + static THIS_LAUNCH: Mutex<Vec<String>> = Mutex::new(Vec::new()); + let mut map = crashes().lock().unwrap_or_else(|e| e.into_inner()); + if crashed { + let mut seen = THIS_LAUNCH.lock().unwrap_or_else(|e| e.into_inner()); + if seen.iter().any(|n| n == name) { + return; + } + seen.push(name.to_owned()); + *map.entry(name.to_owned()).or_insert(0) += 1; + } else if map.remove(name).is_none() { + return; + } + let mut lines: Vec<String> = map.iter().map(|(n, c)| format!("{n} {c}")).collect(); + lines.sort(); + if let Some(dir) = DIR.get() { + let _ = write_atomically(&dir.join(CRASHED_FILE), lines.join("\n").as_bytes()); + } +} + +fn library() -> Option<&'static Library> { + static LIBRARY: OnceLock<Option<Library>> = OnceLock::new(); LIBRARY .get_or_init(|| { + // With RenderDoc loaded the device is RenderDoc's: the card's + // library is not for it, and what it would save is not for + // the card. Neither read nor written in such a run. + #[cfg(feature = "diagnostics")] + if crate::renderdoc::loaded() { + tracing::info!("RenderDoc is loaded: the host pipeline library is neither read nor saved in this run"); + return None; + } let device = crate::host::host()?.device.cast::<ID3D12Device1>().ok()?; - let blob = DIR - .get() - .and_then(|d| std::fs::read(d.join(LIBRARY_FILE)).ok()) - .unwrap_or_default(); + let blob = DIR.get().map_or(Blob::None, |d| Blob::of(d)); let library = open(&device, blob); if library.is_none() { tracing::warn!("no host pipeline library: pipelines are not kept"); } - library.map(Mutex::new) + library }) .as_ref() } /// The library in `blob`, or an empty one if the host rejects the blob (an /// adapter or driver change, damage). -fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> { +fn open(device: &ID3D12Device1, blob: Blob) -> Option<Library> { let make = |bytes: &[u8]| -> windows::core::Result<ID3D12PipelineLibrary1> { // SAFETY: the bytes outlive the library (kept beside it). unsafe { - device - .CreatePipelineLibrary::<ID3D12PipelineLibrary>(bytes)? - .cast() + device.CreatePipelineLibrary::<ID3D12PipelineLibrary>(bytes)?.cast() } }; - if !blob.is_empty() { - match make(&blob) { + let mut rejected = false; + if !blob.bytes().is_empty() { + match make(blob.bytes()) { Ok(library) => { - tracing::info!(bytes = blob.len(), "host pipeline library loaded"); + let bytes = blob.bytes().len(); + BLOB.store(bytes as u64, Ordering::Relaxed); + tracing::info!(bytes, mapped = matches!(blob, Blob::Mapped(_)), "host pipeline library loaded"); + if let Blob::Mapped(file) = &blob { + VIEW[1].store(file.len, Ordering::Relaxed); + VIEW[0].store(file.at.Value as usize, Ordering::Relaxed); + LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + } + KEPT.store(true, Ordering::Relaxed); return Some(Library { library, _blob: blob, - added: 0, + added: AtomicU64::new(0), + saving: RwLock::new(()), }); } Err(e) => { - tracing::info!(error = %e, "host pipeline library rejected; starting an empty one") + rejected = true; + tracing::warn!(error = %e, "host pipeline library rejected; starting an empty one (the rejected file is kept as {REJECTED_FILE})"); } } } else { tracing::info!("no host pipeline library yet; starting an empty one"); } - // An empty library is asked for with no blob at all, which `make` cannot - // say: an empty slice still has an address, and vkd3d-proton refuses an - // address with no bytes behind it. That left it with no library at all. - let mut raw = std::ptr::null_mut(); - // SAFETY: no blob is read; a success that wrote a pointer wrote an owned - // ID3D12PipelineLibrary. - let made = unsafe { - (Interface::vtable(device).CreatePipelineLibrary)( - Interface::as_raw(device), - std::ptr::null(), - 0, - &ID3D12PipelineLibrary::IID, - &mut raw, - ) - .ok() - .and_then(|()| { - if raw.is_null() { - return Err(windows::Win32::Foundation::E_POINTER.into()); - } - ID3D12PipelineLibrary::from_raw(raw).cast::<ID3D12PipelineLibrary1>() - }) - }; - match made { - Ok(library) => Some(Library { - library, - _blob: Vec::new(), - added: 0, - }), - Err(e) => { - tracing::info!(error = %e, "the host refused an empty pipeline library"); - None + // The rejected bytes are let go (a mapped file is unmapped) before the + // empty library is made: nothing reads them any more. + drop(blob); + // And the file is kept under another name, not written over by this + // run's first save: a refusal may be this device's alone (run 263: + // RenderDoc's device refused the card's library, an empty one was + // saved over 366 MB of built pipelines, and the next run drew black + // until they were built again). + if rejected && let Some(dir) = DIR.get() + && let Err(e) = std::fs::rename(dir.join(LIBRARY_FILE), dir.join(REJECTED_FILE)) { + tracing::warn!(error = %e, "the rejected host pipeline library could not be kept under its other name"); } - } + let library = make(&[]).ok()?; + Some(Library { + library, + _blob: Blob::None, + added: AtomicU64::new(0), + saving: RwLock::new(()), + }) } /// A pipeline's name in the library: the hash of what its host /// description holds. pub(crate) fn name(kind: &str, root: &[u8], code: &[&[u8]], state: &str) -> String { let mut h = blake3::Hasher::new(); - for part in [kind.as_bytes(), root] - .into_iter() - .chain(code.iter().copied()) - .chain([state.as_bytes()]) - { + for part in [kind.as_bytes(), root].into_iter().chain(code.iter().copied()).chain([state.as_bytes()]) { h.update(&(part.len() as u64).to_le_bytes()); h.update(part); } @@ -161,113 +693,295 @@ pub(crate) fn pipeline( MADE.fetch_add(1, Ordering::Relaxed); return create(); }; - if let Ok(pso) = load( - &library.lock().unwrap_or_else(|e| e.into_inner()).library, - PCWSTR(wide.as_ptr()), - ) { - LOADED.fetch_add(1, Ordering::Relaxed); - return Ok(pso); + let began = std::time::Instant::now(); + let loaded = { + let _all = one_call(); + let _one = same_name(name); + let _call = call("load", name); + load(&library.library, PCWSTR(wide.as_ptr())) + }; + // The load read the library's file (see `trim`). + LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + TRIMMED.store(false, Ordering::Relaxed); + let refused = match loaded { + Ok(pso) => { + LOADED.fetch_add(1, Ordering::Relaxed); + crate::host::trail(|| { + let label = LABEL.with(|l| l.borrow().clone()); + format!("pipeline library: loaded {label} in {:.1} ms", began.elapsed().as_secs_f64() * 1e3) + }); + return Ok(pso); + } + Err(e) => e, + }; + if crashed_before(name) { + static SAID: AtomicBool = AtomicBool::new(false); + if !SAID.swap(true, Ordering::Relaxed) { + tracing::info!("pipelines that crashed the host's compiler in two launches are not tried again (VICTORY_RETRY_CRASHED=1 tries them)"); + } + return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_OUTOFMEMORY)); } - // Compiled outside the lock: compiles take up to seconds. - let pso = create()?; + // Compiled outside any lock: compiles take up to seconds. + let pso = { + let _call = call("make", name); + let made = create(); + match &made { + Err(e) if e.code() == windows::Win32::Foundation::E_OUTOFMEMORY => note_made(name, true), + Ok(_) => note_made(name, false), + Err(_) => {} + } + made? + }; MADE.fetch_add(1, Ordering::Relaxed); - let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); - // SAFETY: a live pipeline; a name already stored (a description that - // differs) is refused, which leaves the library as it was. - if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { - l.added += 1; + crate::host::trail(|| { + let label = LABEL.with(|l| l.borrow().clone()); + format!( + "pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})", + began.elapsed().as_secs_f64() * 1e3 + ) + }); + let _all = one_call(); + if stores_later() { + match library.saving.try_read() { + Ok(_stores) => store(library, &wide, &pso), + Err(TryLockError::Poisoned(e)) => { + let _stores = e.into_inner(); + store(library, &wide, &pso); + } + Err(TryLockError::WouldBlock) => { + LATER.lock().unwrap_or_else(|e| e.into_inner()).push(Later(wide, pso.clone())); + STORED_LATER.fetch_add(1, Ordering::Relaxed); + } + } + return Ok(pso); } + let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner()); + store(library, &wide, &pso); Ok(pso) } +/// Stores `pso` as `wide`; the caller holds a read of `saving`. +fn store(library: &Library, wide: &HSTRING, pso: &ID3D12PipelineState) { + let _call = call("store", &wide.to_string_lossy()); + // SAFETY: a live pipeline; a name already stored (a description that + // differs, or one made twice at once) is refused, which leaves the + // library as it was. + if unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), pso) }.is_ok() { + library.added.fetch_add(1, Ordering::Relaxed); + } +} + +/// Whether a pipeline made while a save holds the library alone is handed +/// out at once and stored after the save (`VICTORY_LIBRARY_STORE_LATER=0`: +/// it waits for the whole save, as before). Try 6.15, after cool_fox +/// 4a028f31 (Esteban Viera, opt-in there). +/// +/// Why: a save writes the whole library (1.1 GB in the 6.12 report, ten +/// times in eighteen minutes, every 20 s while pipelines were being made +/// on a PC with memory to spare), and every pipeline finished meanwhile +/// stood until it was written: the frames of those saves dropped 19 to 24 +/// draws a frame as "being made" and took 400 ms to 5.2 s. That is when +/// new things come into view. +fn stores_later() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_STORE_LATER").is_none_or(|v| v != "0")) +} + +/// A pipeline made while a save held the library, with its name. +struct Later(HSTRING, ID3D12PipelineState); +// SAFETY: D3D12 objects are free-threaded; only moved into and out of +// `LATER`. +unsafe impl Send for Later {} + +/// Pipelines handed out during a save and not stored yet ([`stores_later`]). +static LATER: Mutex<Vec<Later>> = Mutex::new(Vec::new()); +/// Pipelines handed out during a save since the start (the save line). +static STORED_LATER: AtomicU64 = AtomicU64::new(0); + +/// Stores what [`LATER`] holds (outside a save). +fn store_later(library: &Library) { + let later = std::mem::take(&mut *LATER.lock().unwrap_or_else(|e| e.into_inner())); + if later.is_empty() { + return; + } + let _all = one_call(); + let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner()); + for Later(wide, pso) in later { + store(library, &wide, &pso); + } +} + +/// Saves the library now and then on a thread of its own (Try 6.15; +/// `VICTORY_LIBRARY_SAVE_THREAD=0`: on the pipeline worker that finished +/// a pipeline, as before). A save took that worker away from compiling +/// for the seconds it wrote 1.1 GB, right when new things came into view. +/// The thread looks every 5 s; [`save`] decides whether one is due. +pub(crate) fn save_soon() { + static THREAD: OnceLock<bool> = OnceLock::new(); + let running = *THREAD.get_or_init(|| { + std::env::var_os("VICTORY_LIBRARY_SAVE_THREAD").is_none_or(|v| v != "0") + && std::thread::Builder::new() + .name("pipeline library save".into()) + .spawn(save_loop) + .is_ok() + }); + if !running { + save(false); + } +} + +/// [`save_soon`]'s thread. +fn save_loop() { + loop { + std::thread::sleep(std::time::Duration::from_secs(5)); + save(false); + } +} + /// Writes the library and the early list if pipelines were added since the /// last save and `SAVE_EVERY` has passed (or `now`). pub(crate) fn save(now: bool) { - // Held over serialisation and both writes, so overlapping saves cannot - // replace files under each other. static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None); + // One save at a time ([`save_soon`]'s thread and the last one at the end). + static ONE: Mutex<()> = Mutex::new(()); const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); - let (Some(dir), Some(library)) = (DIR.get(), library()) else { - return; + let (Some(dir), Some(library)) = (DIR.get(), library()) else { return }; + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + store_later(library); + // Try 6.3: in the world, on a PC short of memory, at most every + // `VICTORY_LIBRARY_SAVE_S` seconds (180 unless set): each save writes the + // whole library again (770 MB in the 6.2 report, eight times in its + // five minutes of world, with 400-800 MB of the PC's memory free), and + // those pages push the title's own out. Behind a loading screen every + // 20 s as before; at the end always. + // Try 6.15: in the world at most every `VICTORY_LIBRARY_SAVE_S` (300 + // unless set) with memory to spare too: the 6.12 report's PC (32 GB) + // wrote 1.1 GB every 20-40 s while new things came into view, and + // those frames took 0.4-5.2 s. The pipelines are kept in memory + // meanwhile; a crash loses at most those of the last minutes. + let every = if crate::draw::loading_now() { + SAVE_EVERY + } else { + static S: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + std::time::Duration::from_secs( + (*S.get_or_init(|| { + std::env::var("VICTORY_LIBRARY_SAVE_S").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(300) + })) + .max(20), + ) }; - let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); - if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { + { + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + if !now && last.is_some_and(|t| t.elapsed() < every) { + return; + } + *last = Some(std::time::Instant::now()); + } + if let Err(e) = std::fs::create_dir_all(dir) { + tracing::warn!(error = %e, "host pipeline library not saved"); return; } - *last = Some(std::time::Instant::now()); - let (blob, saved_additions) = { - let l = library.lock().unwrap_or_else(|e| e.into_inner()); - if l.added == 0 && !USED_CHANGED.load(Ordering::Relaxed) { + let tmp = dir.join(LIBRARY_FILE).with_extension("tmp"); + // The bytes of the library written to `tmp`; 0 when no pipeline was + // added: the library on disk is then what it was, and only the early + // list is written (a title pipeline first drawn with wrote all 1,352 MB + // of the library again: run 60's second save). + let bytes = { + let _all = one_call(); + // No store between asking the size and writing; loads go on. + let _alone = library.saving.write().unwrap_or_else(|e| e.into_inner()); + let added = library.added.load(Ordering::Relaxed); + if !USED_CHANGED.swap(false, Ordering::Relaxed) && added == 0 { return; } - // SAFETY: a buffer of the size the library asks for. - let bytes = unsafe { - let mut bytes = vec![0u8; l.library.GetSerializedSize()]; - l.library.Serialize(&mut bytes).map(|()| bytes) - }; - match bytes { - Ok(bytes) => (bytes, l.added), - Err(e) => { + if added == 0 { + 0 + } else { + // SAFETY: a plain query. + let size = unsafe { library.library.GetSerializedSize() }; + let _call = call("serialise", "the whole library"); + if let Err(e) = serialise(&library.library, &tmp, size) { tracing::warn!(error = %e, "host pipeline library not serialised"); + let _ = std::fs::remove_file(&tmp); return; } + library.added.store(0, Ordering::Relaxed); + SAVED.store(size as u64, Ordering::Relaxed); + size } }; - let used_changed = USED_CHANGED.swap(false, Ordering::Relaxed); - let used: Vec<String> = USED - .lock() - .unwrap_or_else(|e| e.into_inner()) - .iter() - .flatten() - .cloned() - .collect(); - let written = std::fs::create_dir_all(dir) - .and_then(|()| write_atomically(&dir.join(LIBRARY_FILE), &blob)) + // What was made while this save held the library alone. + store_later(library); + let used: Vec<String> = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect(); + let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) }; + if bytes > 0 && library_written.is_ok() { + // In place unless the system refused and the new one waits beside it. + let in_place = !dir.join(NEXT_FILE).exists(); + if in_place && VIEW[0].load(Ordering::Relaxed) != 0 { + REPLACED[1].store(crate::host::now_ms(), Ordering::Relaxed); + REPLACED[0].fetch_add(1, Ordering::Relaxed); + } + crate::host::trail(|| { + format!( + "pipeline library: saved {bytes} bytes, {}", + if in_place { "renamed over the library's file" } else { "left beside the library's file for the next start" } + ) + }); + } + let written = library_written .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); match written { - Ok(()) => { - let mut l = library.lock().unwrap_or_else(|e| e.into_inner()); - // Keep pipelines stored while the files were being written. - l.added = l.added.saturating_sub(saved_additions); - tracing::info!( - bytes = blob.len(), - early = used.len(), - made = MADE.load(Ordering::Relaxed), - loaded = LOADED.load(Ordering::Relaxed), - started_early = EARLY.load(Ordering::Relaxed), - "host pipeline library saved" - ); - } - Err(e) => { - // At least one cache file was not published. Keep the counters - // dirty for the next save. - if used_changed { - USED_CHANGED.store(true, Ordering::Relaxed); - } - tracing::warn!(error = %e, "host pipeline library not saved"); - } + Ok(()) => tracing::info!( + bytes, + early = used.len(), + made = MADE.load(Ordering::Relaxed), + loaded = LOADED.load(Ordering::Relaxed), + started_early = EARLY.load(Ordering::Relaxed), + handed_out_during_saves = STORED_LATER.load(Ordering::Relaxed), + "host pipeline library saved" + ), + Err(e) => tracing::warn!(error = %e, "host pipeline library not saved"), } } -/// Writes `bytes` to a unique temporary file beside `path`, then renames it -/// over `path`: a reader never sees a part, and overlapping saves do not -/// share a temporary file. -fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { - static NEXT: AtomicU64 = AtomicU64::new(0); - let extension = format!( - "tmp-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - ); - let tmp = path.with_extension(extension); - let written = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)); - if written.is_err() { - let _ = std::fs::remove_file(&tmp); +/// Writes the library's `size` serialised bytes to the file `tmp`: through +/// a mapping of that file, so that the bytes are the file's pages and not +/// 1.3 GB more of the process's own memory for the seconds a save takes; +/// through a buffer where the file cannot be mapped (and with +/// `VICTORY_LIBRARY_MAP=0`). +fn serialise(library: &ID3D12PipelineLibrary1, tmp: &std::path::Path, size: usize) -> std::io::Result<()> { + let failed = |e: windows::core::Error| std::io::Error::other(e.to_string()); + if mapped() + && let Some(mut file) = Mapped::create(tmp, size) + { + // SAFETY: a buffer of the size the library asks for. + return unsafe { library.Serialize(file.bytes_mut()) }.map_err(failed); } - written + let mut bytes = vec![0u8; size]; + // SAFETY: a buffer of the size the library asks for. + unsafe { library.Serialize(&mut bytes) }.map_err(failed)?; + std::fs::write(tmp, &bytes) } -/// Title pipeline keys drawn or dispatched with (this run and the last). +/// Renames the written library `tmp` over the library's file in `dir`. This +/// run may have that file mapped: Windows 11 replaces a mapped file, and +/// the mapping goes on reading the old one for as long as a handle on it +/// is open ([`holds`]; with none, only the pages in memory at that moment +/// stay: the rest read as zeros). Where a system refuses, the new library +/// is left beside it as [`NEXT_FILE`] for the next start. +fn replace_library(dir: &std::path::Path, tmp: &std::path::Path) -> std::io::Result<()> { + std::fs::rename(tmp, dir.join(LIBRARY_FILE)).or_else(|_| std::fs::rename(tmp, dir.join(NEXT_FILE))) +} + +/// Writes `bytes` to a temporary file beside `path`, then renames it over +/// `path`: a reader never sees a part. +fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path) +} + +/// Title pipeline keys requested by draws or dispatches (this run and the last). static USED: Mutex<Option<HashSet<String>>> = Mutex::new(None); static USED_CHANGED: AtomicBool = AtomicBool::new(false); @@ -278,23 +992,51 @@ fn used() -> std::sync::MutexGuard<'static, Option<HashSet<String>>> { .get() .and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok()) .unwrap_or_default(); - let set: HashSet<String> = listed - .lines() - .filter(|l| !l.is_empty()) - .map(str::to_owned) - .collect(); + let set: HashSet<String> = listed.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect(); tracing::info!(pipelines = set.len(), "title pipelines to start early"); *used = Some(set); } used } -/// Whether the title pipeline with `key` was drawn with in an earlier run. +/// The shared pipeline list (`shared-pipelines.txt` in the cache's +/// folder, which VIctory Try fills from the list in the repository): keys +/// of title pipelines other players' runs drew with, one a line (`#` lines +/// are notes). A pipeline the title creates that is on it is started at +/// once, as one this machine drew with before would be, so a first run +/// makes them during loading instead of at the first draw (when that draw +/// is dropped or stood in for). Only keys: no shader of the game is in it. +/// `VICTORY_SHARED_PIPELINES=0` ignores it. +const SHARED_FILE: &str = "shared-pipelines.txt"; + +fn shared() -> &'static HashSet<String> { + static SHARED: OnceLock<HashSet<String>> = OnceLock::new(); + SHARED.get_or_init(|| { + if std::env::var_os("VICTORY_SHARED_PIPELINES").is_some_and(|v| v == "0") { + return HashSet::new(); + } + let listed = DIR + .get() + .and_then(|d| std::fs::read_to_string(d.join(SHARED_FILE)).ok()) + .unwrap_or_default(); + let set: HashSet<String> = listed + .lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .map(str::to_owned) + .collect(); + tracing::info!(pipelines = set.len(), "title pipelines other players met, to start early (VICTORY_SHARED_PIPELINES=0: not)"); + set + }) +} + +/// Whether the title pipeline with `key` was requested in this or an +/// earlier run, or is on the shared list ([`SHARED_FILE`]). pub(crate) fn wanted_early(key: &str) -> bool { - used().as_ref().is_some_and(|s| s.contains(key)) + used().as_ref().is_some_and(|s| s.contains(key)) || shared().contains(key) } -/// The title pipeline with `key` was drawn or dispatched with. +/// A draw or dispatch requested the title pipeline with `key`. pub(crate) fn note_used(key: &str) { let mut used = used(); let set = used.get_or_insert_with(HashSet::new); @@ -305,6 +1047,13 @@ pub(crate) fn note_used(key: &str) { #[cfg(test)] mod tests { + + #[test] + fn crashed_pipelines_read_back() { + let map = super::parse_crashes("abc 1\ndef 2\nbroken\n"); + assert_eq!(map.len(), 2); + assert_eq!(map["def"], 2); + } use super::*; #[test] @@ -321,62 +1070,114 @@ mod tests { #[test] fn a_rejected_blob_gives_an_empty_library() { - let Some(device) = crate::host::host().and_then(|h| h.device.cast::<ID3D12Device1>().ok()) - else { + let Some(device) = crate::host::host().and_then(|h| h.device.cast::<ID3D12Device1>().ok()) else { return; // no host GPU here }; - let library = - open(&device, b"not a pipeline library".repeat(16)).expect("an empty library"); + let library = open(&device, Blob::Held(b"not a pipeline library".repeat(16))).expect("an empty library"); // SAFETY: a plain query on a live library. assert!(unsafe { library.library.GetSerializedSize() } > 0); - assert!(library._blob.is_empty()); + assert!(matches!(library._blob, Blob::None)); } + /// A mapped file reads as the file's bytes, a file written through a + /// mapping holds what was written, and the library's file can be + /// replaced while it is mapped (or the new one waits as the next). #[test] - fn concurrent_atomic_writes_publish_one_complete_file() { + fn the_library_file_is_mapped_and_replaced() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(LIBRARY_FILE); - let start = std::sync::Arc::new(std::sync::Barrier::new(8)); - let mut threads = Vec::new(); - for thread in 0..8 { - let path = path.clone(); - let start = start.clone(); - threads.push(std::thread::spawn(move || { - start.wait(); - let byte = thread as u8 + 1; - for _ in 0..32 { - write_atomically(&path, &[byte; 64 * 1024]).unwrap(); - } - })); + assert!(matches!(Blob::of(dir.path()), Blob::None), "no file yet"); + std::fs::write(&path, b"").unwrap(); + assert!(matches!(Blob::of(dir.path()), Blob::None), "an empty file"); + let old: Vec<u8> = (0..200_000u32).map(|i| i as u8).collect(); + std::fs::write(&path, &old).unwrap(); + let blob = Blob::of(dir.path()); + assert!(matches!(blob, Blob::Mapped(_)) || !mapped()); + assert_eq!(blob.bytes(), &old[..]); + // A save while the old file is mapped. + let tmp = path.with_extension("tmp"); + let new: Vec<u8> = (0..300_000u32).map(|i| (i * 7) as u8).collect(); + { + let mut file = Mapped::create(&tmp, new.len()).expect("a new file, mapped"); + file.bytes_mut().copy_from_slice(&new); } - for thread in threads { - thread.join().unwrap(); + assert_eq!(std::fs::read(&tmp).unwrap(), new); + replace_library(dir.path(), &tmp).unwrap(); + assert!(!tmp.exists()); + // The mapping still reads the old library. + assert_eq!(blob.bytes(), &old[..]); + drop(blob); + // The next start reads the new one, wherever the save left it. + assert_eq!(Blob::of(dir.path()).bytes(), &new[..]); + assert!(!dir.path().join(NEXT_FILE).exists()); + } + + /// The bytes at `at` of the pattern the test below writes. + fn pattern(at: usize, out: &mut [u8]) { + for (i, word) in out.chunks_exact_mut(4).enumerate() { + let v = ((at / 4 + i) as u32).wrapping_mul(2_654_435_761).wrapping_add(1); + word.copy_from_slice(&v.to_le_bytes()); } + } - let published = std::fs::read(&path).unwrap(); - assert_eq!(published.len(), 64 * 1024); - assert!(published.iter().all(|&byte| byte == published[0])); - assert!((1..=8).contains(&published[0])); - assert!( - !std::fs::read_dir(dir.path()) - .unwrap() - .flatten() - .any(|entry| entry.file_name().to_string_lossy().contains(".tmp-")) - ); + /// A file of `len` bytes (whole MiB) of [`pattern`], written past the + /// system's cache: none of its pages is in memory afterwards. False + /// where the folder's file system does not take such writes. + fn write_uncached(path: &std::path::Path, len: usize) -> bool { + use std::io::Write; + use std::os::windows::fs::OpenOptionsExt; + // FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH + const UNCACHED: u32 = 0x2000_0000 | 0x8000_0000; + const CHUNK: usize = 1 << 20; + let Ok(mut file) = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .custom_flags(UNCACHED) + .open(path) + else { + return false; + }; + // Such writes want a buffer on a sector boundary. + let mut store = vec![0u8; CHUNK + 4096]; + let start = store.as_ptr().align_offset(4096); + for at in (0..len).step_by(CHUNK) { + let chunk = &mut store[start..start + CHUNK]; + pattern(at, chunk); + if file.write_all(chunk).is_err() { + return false; + } + } + true } + /// The device loss of runs 72, 73 and 82: the library's file is + /// replaced while it is mapped, and pages of the mapping that were not + /// in memory then are read afterwards (in the runs: pages the trim let + /// go and Windows gave to something else). With the file's handle kept + /// open they still read as the old file. (With it closed, as before, + /// all but the first few read as zeros on the PC this was found on.) #[test] - fn failed_atomic_writes_remove_their_temporary_file() { + fn a_replaced_library_file_still_reads_from_the_disk() { + const LEN: usize = 8 << 20; let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(LIBRARY_FILE); - std::fs::create_dir(&path).unwrap(); - - assert!(write_atomically(&path, b"not published").is_err()); - assert!( - !std::fs::read_dir(dir.path()) - .unwrap() - .flatten() - .any(|entry| entry.file_name().to_string_lossy().contains(".tmp-")) - ); + if !write_uncached(&path, LEN) { + return; // no uncached writes here: nothing to show + } + let mapped = Mapped::open_holding(&path, true).expect("the file, mapped"); + // A save: the new library, renamed over the mapped one. + let tmp = path.with_extension("tmp"); + { + let mut file = Mapped::create(&tmp, LEN).expect("a new file, mapped"); + file.bytes_mut().fill(0xEE); + } + replace_library(dir.path(), &tmp).unwrap(); + // Every page of the old mapping, read for the first time now. + let mut expected = vec![0u8; 4096]; + for (page, bytes) in mapped.bytes().chunks(4096).enumerate() { + pattern(page * 4096, &mut expected); + assert!(bytes == &expected[..], "page {page} of the replaced library no longer reads as the old file"); + } } } diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 6eb7d8e797..a9b45d1366 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -1,8 +1,8 @@ //! Host pipelines are made by workers, not by the title thread that first //! records a draw with them. Translating a shader and the host driver's //! compile take from milliseconds to seconds each (structurisation of the -//! biggest compute programs ~0.4 s, some driver compiles 3.4 s), and Grand -//! Theft Auto VI's first world frame wants over 1,200 new pipelines: made +//! biggest compute programs ~0.4 s, some driver compiles 3.4 s), and +//! the title's first world frame wants over 1,200 new pipelines: made //! on its recording threads, that frame took more than 30 s and the //! title's GPU watchdog ended the run (decision 0007, "Pipelines made off //! the title's threads"). @@ -12,9 +12,8 @@ //! bake) are there at once as before; past the budget a draw or dispatch //! whose pipeline is not ready is dropped, as an untranslated one is. //! -//! shortcut: the budget (half a second of waiting per title frame) is a -//! guess; a pass the title runs only once and whose pipeline takes longer -//! is lost. +//! The default budget is half a second per title frame. A pass the title +//! runs only once and whose pipeline takes longer is lost. use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; @@ -22,7 +21,36 @@ use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; use super::Shader; -use super::host::{GraphicsState, HostPipeline}; +use super::host::{GraphicsState, HostPipeline, TargetFormats}; + +/// `VICTORY_DENY_PIPELINES=<16-hex shader hash>,...` (off unless set): the +/// hash of a shader of `shaders` that is listed there. Such a pipeline is +/// never built (no driver compile) and counts as refused, so its draws and +/// dispatches are dropped: a test of whether building a pipeline, rather +/// than running it, is what loses the card (runs 281 and 318: the removal +/// 32 and 81 ms after the 3-second build of `CS_RaytracingResolve` of the +/// two-layer vehicle wheel material, 57a3fad03cac36af and d5b9c94a30d7cf28; +/// gfx41). Unlike `VICTORY_SKIP_PIPELINES`, in release builds too. +pub(super) fn denied(shaders: &[Arc<Shader>]) -> Option<&str> { + static LIST: OnceLock<Vec<String>> = OnceLock::new(); + let list = LIST.get_or_init(|| { + std::env::var("VICTORY_DENY_PIPELINES") + .unwrap_or_default() + .split(',') + .map(|h| h.trim().to_ascii_lowercase()) + .filter(|h| h.len() == 16 && h.bytes().all(|b| b.is_ascii_hexdigit())) + .collect() + }); + if list.is_empty() { + return None; + } + shaders.iter().find(|s| list.contains(&s.hash)).map(|s| s.hash.as_str()) +} + +/// The shaders of `p` (for logs). +pub(crate) fn shaders(p: &Pending) -> &[Arc<Shader>] { + &p.shaders +} /// What a host pipeline is made from, and the host pipeline once made. pub(crate) struct Pending { @@ -31,9 +59,33 @@ pub(crate) struct Pending { queue_state: AtomicU8, made: OnceLock<Option<HostPipeline>>, /// What identifies it across runs (shader containers and state), and - /// whether a draw has used it yet. + /// whether a draw or dispatch has requested it yet. key: String, used: AtomicBool, + /// Its shaders and [`GraphicsState::shape`], for a stand-in while it is + /// being made ([`stand_in`]); `None` for compute. + shape: Option<String>, + /// Its shaders and [`GraphicsState::loose_shape`], for the second tier + /// of stand-ins ([`stand_in`]). + loose: Option<String>, + /// Whether it is in [`SIBLINGS`] (or was looked at for it). + listed: AtomicBool, + /// Draws and dispatches that asked for it before it was made: the + /// queue makes the most asked for first ([`most_asked_first`]). + asks: AtomicU64, + /// Whether the made pipeline has gone to a draw or dispatch yet + /// (`crate::host::first_use`: for a device removal's report). + handed: AtomicBool, + /// The formats its state declares for what a draw draws into (zeros + /// without a graphics state). + pub(crate) formats: TargetFormats, + /// The same shaders and state for other formats, bound at a draw + /// ([`for_formats`]): a chain from the title's pipeline, one link per + /// set of formats met, never shortened. + variant: OnceLock<Arc<Pending>>, + /// The first title frame in which a draw or dispatch waited for it + /// (`u64::MAX`: none yet; [`wait_once`]). + waited_frame: AtomicU64, } // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input @@ -49,35 +101,92 @@ impl Pending { key.update(s.stage.as_bytes()); key.update(s.hash.as_bytes()); } - key.update( - graphics - .as_ref() - .map(|g| g.describe()) - .unwrap_or_default() - .as_bytes(), - ); + key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); + let names = || { + let mut s = String::new(); + for shader in &shaders { + s.push_str(shader.stage); + s.push(' '); + s.push_str(&shader.hash); + s.push(' '); + } + s + }; + let shape = graphics.as_ref().filter(|_| !shaders.is_empty()).map(|g| names() + &g.shape()); + let loose = graphics.as_ref().filter(|_| !shaders.is_empty()).map(|g| names() + &g.loose_shape()); Pending { + formats: graphics.as_ref().map_or([0; 9], |g| g.formats()), + variant: OnceLock::new(), shaders, graphics, queue_state: AtomicU8::new(NOT_QUEUED), made: OnceLock::new(), key: key.finalize().to_hex()[..32].to_owned(), used: AtomicBool::new(false), + shape, + loose, + listed: AtomicBool::new(false), + asks: AtomicU64::new(0), + handed: AtomicBool::new(false), + waited_frame: AtomicU64::new(u64::MAX), } } + /// Whether a shader's container is past [`HEAVY_BYTES`]. + fn heavy(&self) -> bool { + self.shaders.iter().any(|s| s.size() > HEAVY_BYTES) + } + fn make(&self) { - self.made - .get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref())); + let started = Instant::now(); + self.made.get_or_init(|| { + if let Some(hash) = denied(&self.shaders) { + // (Try 6.12 denies a list of 1,034 by default: the first + // few said, the rest counted.) + static SAID: AtomicU64 = AtomicU64::new(0); + let n = SAID.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + tracing::warn!(hash, shaders = ?self.shaders, so_far = n, "pipeline not built: its shader is in VICTORY_DENY_PIPELINES"); + } + return None; + } + // Try 6.12 (edsuuu/VI-BR-PORT): passes that only serve rays, + // whose dispatches are left out, are not compiled either. + if super::never_built(&self.shaders) { + static SAID: AtomicU64 = AtomicU64::new(0); + let n = SAID.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_power_of_two() { + tracing::info!(so_far = n, "pipelines of passes that only serve rays not built (VICTORY_SKIP_RT=1; VICTORY_RT_SKIN, VICTORY_RT_RESOLVE, VICTORY_RT_TRACE, VICTORY_ACTIVATE_RAYS =1 build them)"); + } + return None; + } + // Try 6.15, after cool_fox 744c09ba (Filip Michalski, #1353): a + // build that panics (a translation bug) is a refused pipeline. + // Before, the panic ended the worker thread and left the entry + // unmade for good: its draws were dropped as "being made" for + // the rest of the run, and one worker fewer made the others. + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + HostPipeline::new(&self.shaders, self.graphics.as_deref()) + })) { + Ok(made) => made, + Err(_) => { + tracing::warn!(shaders = ?self.shaders, "host pipeline build panicked: refused"); + None + } + } + }); + let took = started.elapsed(); + if took > Duration::from_secs(2) { + tracing::info!(ms = took.as_millis() as u64, heavy = self.heavy(), shaders = ?self.shaders, "slow host pipeline"); + } let (lock, done) = &DONE; let _held = lock.lock().unwrap_or_else(|e| e.into_inner()); done.notify_all(); } } -/// Why a pipeline has no host pipeline (diagnostics): its shaders that do -/// not translate, else "refused" or "being made"; `None` if it has one. -#[cfg(feature = "diagnostics")] +/// Why a pipeline has no host pipeline: its shaders that do not +/// translate, else "refused" or "being made"; `None` if it has one. pub(crate) fn missing(p: &Pending) -> Option<String> { match p.made.get() { Some(Some(_)) => None, @@ -102,7 +211,31 @@ pub(crate) fn missing(p: &Pending) -> Option<String> { static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new()); /// Waiting allowed per title frame, over all threads. -const BUDGET: Duration = Duration::from_millis(500); +fn wait_budget() -> Duration { + static BUDGET: OnceLock<Duration> = OnceLock::new(); + *BUDGET.get_or_init(|| { + let millis = std::env::var("VICTORY_PIPELINE_WAIT_MS") + .ok() + .and_then(|value| value.trim().parse::<u64>().ok()) + .unwrap_or(500); + tracing::info!(millis, "host pipeline wait budget per frame"); + Duration::from_millis(millis) + }) +} + +/// Try 6.13, from edsuuu/VI-BR-PORT dc3fa30b and trustno1-coder/VIctory-NVIDIA +/// 77e13a97 (the problem of fxceless issue #1181): whether a pipeline still +/// being made is waited for in the first frame that asks for it only. A +/// pipeline whose make takes longer than the budget (a driver compile of +/// seconds) otherwise cost the whole budget in every frame it was in view: +/// the picture stood still, half a second a frame, until the camera turned +/// away. After that frame its draws get a stand-in or are dropped until it +/// is made, as past any frame's budget. On by default; +/// `VICTORY_PIPELINE_WAIT_ONCE=0` waits in every frame as before. +fn wait_once() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_ONCE").is_none_or(|v| v != "0")) +} /// Pipelines queued and not made yet. static WAITING: AtomicU64 = AtomicU64::new(0); @@ -115,34 +248,271 @@ pub(crate) fn waiting() -> u64 { /// The host pipeline if it is made (or is made within the frame's budget); /// queues it on first use. pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> { + // A still-pending pipeline was requested by the title too. Prewarm it + // on the next launch, even if this run never got to use it. + if !p.used.load(Ordering::Relaxed) && !p.used.swap(true, Ordering::Relaxed) { + super::library::note_used(&p.key); + // And what it is made from, for `victory prepare` after the run. + super::recipe::note(&p.key, &p.shaders, p.graphics.as_deref()); + } if p.made.get().is_none() { + p.asks.fetch_add(1, Ordering::Relaxed); start(p, REQUESTED); - wait(p, crate::frame::current()); + let frame = crate::frame::current(); + // Waited for in the first frame that asks for it only + // ([`wait_once`]); later frames go on without it. + let first = match p.waited_frame.compare_exchange(u64::MAX, frame, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => frame, + Err(f) => f, + }; + // Try 6.15, a new thing on screen at once: a stand-in of the same + // shaders and shape (`stand_in`, its first tier) is taken before any + // wait. The object is drawn in this very frame, and the frame does + // not stand still for the driver's compile; the real pipeline + // replaces it as soon as it is made. After Kelvaroq 0050 + // (stellarr-studio: "a hit binds immediately, a miss keeps the + // budget"). `VICTORY_STAND_IN_FIRST=0`: wait first, as before. + if stand_in_first() + && let Some(made) = stand_in_tier(p, false) + { + STAND_INS_FIRST.fetch_add(1, Ordering::Relaxed); + return Some(made); + } + if first == frame || !wait_once() { + wait(p, frame); + } + if p.made.get().is_none() { + return stand_in(p); + } } let made = p.made.get()?.as_ref(); - if made.is_some() && !p.used.swap(true, Ordering::Relaxed) { - super::library::note_used(&p.key); + if made.is_some() && p.shape.is_some() && !p.listed.swap(true, Ordering::Relaxed) { + let mut siblings = SIBLINGS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(shape) = &p.shape { + let map = siblings.get_or_insert_with(std::collections::HashMap::new); + let new_shape = !map.contains_key(shape); + let new_loose = p.loose.as_ref().filter(|l| !map.contains_key(*l)); + if new_shape || new_loose.is_some() { + let leaked: &'static Arc<Pending> = &*Box::leak(Box::new(p.clone())); + if new_shape { + map.insert(shape.clone(), leaked); + } + if let Some(loose) = new_loose { + map.insert(loose.clone(), leaked); + } + } + } + } + // The first time the made pipeline goes to a draw or dispatch: noted + // for a device removal's report (one load a call after that). + if let Some(host) = made + && !p.handed.load(Ordering::Relaxed) + && !p.handed.swap(true, Ordering::Relaxed) + { + crate::host::first_use(&host.name); } made } +/// Pipelines made again for the formats bound at a draw, since the start. +static VARIANTS: AtomicU64 = AtomicU64::new(0); + +/// Whether a draw into views of other formats than its pipeline declares +/// gets a host pipeline for those formats ([`for_formats`]). On by +/// default; `VICTORY_TARGET_VARIANTS=0` sends such a draw to the host with +/// the title's pipeline, as before. +fn variants_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TARGET_VARIANTS").is_none_or(|v| v != "0")) +} + +/// The host pipeline for a draw with `p` into views of the formats +/// `bound`, which `p` does not declare (`host::formats_differ`): that of +/// the same shaders and state for those formats. It is a pipeline like the +/// title's own: queued at its first draw, made by a worker, waited for +/// within the frame's budget, and the draw is dropped while it is not +/// there ([`ready`]). +#[cold] +pub(crate) fn for_formats<'a>(p: &'a Arc<Pending>, bound: &TargetFormats) -> Option<&'a HostPipeline> { + match p.graphics.as_deref() { + Some(g) if variants_on() => ready(variant(p, g, &super::host::formats_for(&p.formats, bound))), + _ => ready(p), + } +} + +/// The pipeline of `p`'s shaders and its state `g` for the formats +/// `bound`: found in the chain that starts at `p`, or added to it (logged +/// then: once per pipeline and set of formats). +fn variant<'a>(p: &'a Arc<Pending>, g: &GraphicsState, bound: &TargetFormats) -> &'a Arc<Pending> { + let mut at = p; + // (`bound` is what `host::formats_for` gives, and a state made for it + // declares exactly it, so the walk ends at the link made for it; the + // count is a bound all the same: past it the title's own pipeline.) + for _ in 0..64 { + let next = at.variant.get_or_init(|| { + let so_far = VARIANTS.fetch_add(1, Ordering::Relaxed) + 1; + tracing::info!( + pipeline = ?p.shaders, + declared = ?p.formats, + bound = ?bound, + so_far, + "a pipeline is made again for the render target formats bound at its draw (eight render targets, then depth; VICTORY_TARGET_VARIANTS=0: the draw goes out with the title's pipeline)" + ); + Arc::new(Pending::new(p.shaders.clone(), Some(Box::new(g.with_formats(bound))))) + }); + // (A state made for `bound` declares exactly `bound`.) + if next.formats == *bound { + return next; + } + at = next; + } + p +} + +/// The first made pipeline of each [`Pending::shape`] that a draw used: +/// kept for the rest of the run (one host pipeline per shape). +static SIBLINGS: Mutex<Option<std::collections::HashMap<String, &'static Arc<Pending>>>> = Mutex::new(None); + +/// Draws that went out with a stand-in pipeline since the start. +pub(crate) static STAND_INS: AtomicU64 = AtomicU64::new(0); + +/// `VICTORY_STAND_IN=0`: a draw whose pipeline is still being made is +/// dropped, as before. +fn stand_in_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_STAND_IN").is_none_or(|v| v != "0")) +} + +/// For a graphics pipeline still being made (never one refused or that does +/// not translate): a made pipeline of the same shaders and +/// [`GraphicsState::shape`], which differs from it only in state that +/// leaves nothing behind for later passes (culling, the depth test's +/// function, blend factors). Its draws go out where they were dropped +/// until the pipeline is made: in the first frames of a scene, geometry +/// that was missing (or a frame late) is there. +/// shortcut: for those frames such a draw may cull or blend as its +/// sibling does. +/// +/// Second tier, Dolphin's ubershader idea (a pipeline that draws anything +/// while the real one is made): with none of the same shape, one of the +/// same shaders, formats and blending whose depth and stencil writes differ +/// (`VICTORY_STAND_IN_LOOSE=0`: not taken). The object is drawn rather than +/// missing; for those frames it may write depth where it would not. +fn stand_in(p: &Pending) -> Option<&HostPipeline> { + stand_in_tier(p, true) +} + +/// Draws that took a same-shape stand-in before any wait +/// ([`stand_in_first`]), since the start. +pub(crate) static STAND_INS_FIRST: AtomicU64 = AtomicU64::new(0); + +/// Whether a same-shape stand-in is taken before the frame waits for a +/// pipeline being made (`VICTORY_STAND_IN_FIRST=0`: after the wait, as +/// before). Only with stand-ins on. +fn stand_in_first() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + let on = stand_in_on() && std::env::var_os("VICTORY_STAND_IN_FIRST").is_none_or(|v| v != "0"); + if on { + tracing::info!("a draw whose pipeline is being made takes a stand-in of the same shaders and shape at once, before any wait (VICTORY_STAND_IN_FIRST=0: after the wait)"); + } + on + }) +} + +/// [`stand_in`]; the second tier (other depth writes) only with `loose`. +fn stand_in_tier(p: &Pending, loose: bool) -> Option<&HostPipeline> { + let shape = p.shape.as_ref().filter(|_| stand_in_on())?; + let siblings = SIBLINGS.lock().unwrap_or_else(|e| e.into_inner()); + let siblings = siblings.as_ref()?; + let made_of = |key: &String| -> Option<&'static HostPipeline> { + let sibling: &'static Arc<Pending> = *siblings.get(key)?; + sibling.made.get()?.as_ref() + }; + if let Some(made) = made_of(shape) { + STAND_INS.fetch_add(1, Ordering::Relaxed); + return Some(made); + } + let loose = p.loose.as_ref().filter(|_| loose && loose_on())?; + let made = made_of(loose)?; + STAND_INS.fetch_add(1, Ordering::Relaxed); + LOOSE_STAND_INS.fetch_add(1, Ordering::Relaxed); + Some(made) +} + +/// Draws that went out with a second-tier stand-in since the start. +pub(crate) static LOOSE_STAND_INS: AtomicU64 = AtomicU64::new(0); + +/// See [`stand_in`]. +fn loose_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_STAND_IN_LOOSE").is_none_or(|v| v != "0")) +} + +/// Makes `p` on this thread if it is not made yet (waiting for a worker +/// that is making it); whether it has a host pipeline. +pub(crate) fn now(p: &Arc<Pending>) -> bool { + p.make(); + p.made.get().is_some_and(|made| made.is_some()) +} + /// At the title's creation of a pipeline: starts it at once if an earlier -/// run drew with it (during loading, so the world's first frames find it). +/// run drew with it (during loading, so the world's first frames find it), +/// and (Try 6.13, edsuuu/VI-BR-PORT b9d4f96c) every compute pipeline: its +/// first dispatch waits for it, and a frame that first dispatches hundreds +/// of them (the world's) waited for each in turn. Most come out of the +/// pipeline library at once. `VICTORY_PIPELINE_EARLY_COMPUTE=0`: only the +/// ones an earlier run drew with, as before. pub(crate) fn early(p: &Arc<Pending>) { - if !p.shaders.is_empty() && super::library::wanted_early(&p.key) { + static COMPUTE: OnceLock<bool> = OnceLock::new(); + // (Only with workers: without them a start is a make on the title's + // own thread.) + let compute = p.graphics.is_none() + && workers() + && *COMPUTE.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_EARLY_COMPUTE").is_none_or(|v| v != "0")); + if !p.shaders.is_empty() && (compute || super::library::wanted_early(&p.key)) { super::library::EARLY.fetch_add(1, Ordering::Relaxed); start(p, EARLY); } } +/// Whether the frame's budget is one for all threads together: a thread +/// that waits takes what is left of it and gives back what it did not +/// use. Counted only when a wait had ended, the budget was one per thread: +/// each of the title's five recording threads began its first wait of a +/// frame with nothing counted yet and waited the whole half second, 2.5 s +/// of waiting in every frame in which pipelines were being made (runs +/// 34-49: "2504 ms waiting for pipelines" in each such frame). +/// On by default; `VICTORY_PIPELINE_WAIT_SHARED=0` counts as before. +fn shared_budget() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0")) +} + /// Waits for `p` while frame `frame` has budget left. fn wait(p: &Pending, frame: u64) { - static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); - static WAITED_US: AtomicU64 = AtomicU64::new(0); - if FRAME.swap(frame, Ordering::Relaxed) != frame { - WAITED_US.store(0, Ordering::Relaxed); + let budget = wait_budget(); + if budget.is_zero() { + return; + } + // The frame the budget belongs to, and what was waited of it (or is + // taken by a thread waiting now). + static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO)); + let shared = shared_budget(); + let left = { + let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner()); + if spent.0 != frame { + *spent = (frame, Duration::ZERO); + } + let left = budget.saturating_sub(spent.1); + if shared { + spent.1 += left; + } + left + }; + if left.is_zero() { + return; } - let left = BUDGET.saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed))); let started = Instant::now(); let (lock, done) = &DONE; let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); @@ -151,12 +521,27 @@ fn wait(p: &Pending, frame: u64) { if rest.is_zero() { break; } - held = done - .wait_timeout(held, rest) - .unwrap_or_else(|e| e.into_inner()) - .0; + held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0; } - WAITED_US.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + drop(held); + let waited = started.elapsed().min(left); + { + let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner()); + // A frame that began meanwhile has its own budget. + if spent.0 == frame { + if shared { + spent.1 = spent.1.saturating_sub(left - waited); + } else { + spent.1 += waited; + } + } + } + crate::framelog::add(crate::framelog::T::PipelineWaitUs, started.elapsed().as_micros() as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::add( + crate::copystat::C::PipelineWaitUs, + started.elapsed().as_micros() as u64, + ); } const NOT_QUEUED: u8 = 0; @@ -164,9 +549,23 @@ const EARLY: u8 = 1; const REQUESTED: u8 = 2; const MAKING: u8 = 3; +/// A shader container past this size makes its pipeline heavy: the +/// world's biggest compute programs (275 of 60-78 KB in the first world +/// frames) each took an RTX 4060's driver ~18 s to compile. Queued with the +/// rest, they held every worker for minutes while ~1,600 small draw +/// pipelines waited behind them (4-9 made a minute), so the world's draws +/// were dropped and the picture stayed black. +pub(super) const HEAVY_BYTES: usize = 32 * 1024; + struct Queue { early: VecDeque<Arc<Pending>>, requested: VecDeque<Arc<Pending>>, + /// Heavy pipelines, made by at most `heavy_limit` workers at once so + /// the others keep making the light ones. + heavy_early: VecDeque<Arc<Pending>>, + heavy_requested: VecDeque<Arc<Pending>>, + heavy_making: usize, + heavy_limit: usize, } impl Queue { @@ -174,6 +573,10 @@ impl Queue { Self { early: VecDeque::new(), requested: VecDeque::new(), + heavy_early: VecDeque::new(), + heavy_requested: VecDeque::new(), + heavy_making: 0, + heavy_limit: 1, } } @@ -185,25 +588,69 @@ impl Queue { return None; } p.queue_state.store(priority, Ordering::Relaxed); - if priority == REQUESTED { - self.requested.push_back(p.clone()); - } else { - self.early.push_back(p.clone()); - } + let heavy = p.heavy(); + let lane = match (priority == REQUESTED, heavy) { + (true, false) => &mut self.requested, + (true, true) => &mut self.heavy_requested, + (false, false) => &mut self.early, + (false, true) => &mut self.heavy_early, + }; + lane.push_back(p.clone()); Some(prev == NOT_QUEUED) } + /// `pop_for(false)`. + #[cfg(test)] fn pop(&mut self) -> Option<Arc<Pending>> { - let p = self.requested.pop_front().or_else(|| { + self.pop_for(false) + } + + /// The next pipeline to make: light requested ones first, then heavy + /// requested ones while a heavy slot is free, then those queued early + /// (not with `asked_only`: the worker kept for requested ones, + /// [`kept_worker`]). Of the requested ones, the one the most draws + /// asked for so far ([`most_asked_first`]), the first queued of those. + fn pop_for(&mut self, asked_only: bool) -> Option<Arc<Pending>> { + fn requested(lane: &mut VecDeque<Arc<Pending>>) -> Option<Arc<Pending>> { + if !most_asked_first() { + return lane.pop_front(); + } + let at = lane + .iter() + .enumerate() + .max_by_key(|(i, p)| (p.asks.load(Ordering::Relaxed), std::cmp::Reverse(*i))) + .map(|(i, _)| i)?; + lane.remove(at) + } + fn early(lane: &mut VecDeque<Arc<Pending>>) -> Option<Arc<Pending>> { // An early entry can have been promoted and claimed already. - std::iter::from_fn(|| self.early.pop_front()) + std::iter::from_fn(|| lane.pop_front()) .find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY) - })?; + } + let heavy_free = self.heavy_making < self.heavy_limit; + let p = requested(&mut self.requested) + .or_else(|| heavy_free.then(|| requested(&mut self.heavy_requested)).flatten()) + .or_else(|| (!asked_only).then(|| early(&mut self.early)).flatten()) + .or_else(|| (heavy_free && !asked_only).then(|| early(&mut self.heavy_early)).flatten())?; + ASKED_WAITING.store((self.requested.len() + self.heavy_requested.len()) as u64, Ordering::Relaxed); + if p.heavy() { + self.heavy_making += 1; + } p.queue_state.store(MAKING, Ordering::Relaxed); Some(p) } } +/// Whether requested pipelines are made most asked for first, not in the +/// order first asked for (`VICTORY_PIPELINE_MOST_ASKED=0`). A backlog of +/// 1,600 pipelines took minutes to work through; the pipeline of the +/// ground that 400 draws a frame wait for went behind a hundred that one +/// draw each asked for once. +fn most_asked_first() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_MOST_ASKED").is_none_or(|v| v != "0")) +} + static QUEUE: Mutex<Queue> = Mutex::new(Queue::new()); static AVAILABLE: Condvar = Condvar::new(); @@ -222,47 +669,159 @@ fn start(p: &Arc<Pending>, priority: u8) { let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); if let Some(new) = queue.push(p, priority) { if new { - PEAK.fetch_max( - WAITING.fetch_add(1, Ordering::Relaxed) + 1, - Ordering::Relaxed, - ); + PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); } - AVAILABLE.notify_one(); + ASKED_WAITING.store((queue.requested.len() + queue.heavy_requested.len()) as u64, Ordering::Relaxed); + // All: the worker kept for requested pipelines ([`kept_worker`]) + // may be the one woken, and it leaves an early one where it is. + AVAILABLE.notify_all(); + } +} + +/// Requested pipelines (draws wait for them) left in the queue at the last +/// claim: what raises the workers above the title ([`worker_level`]). +static ASKED_WAITING: AtomicU64 = AtomicU64::new(0); + +/// Whether worker `worker` of `workers` makes requested pipelines only: +/// the first, when there are three or more. At the intro every worker was +/// busy with pipelines started early from the last run's list (heavy ones +/// take a driver 10-40 s), so the one the intro's next draw asked for +/// waited for a worker while each frame waited up to +/// `VICTORY_PIPELINE_WAIT_MS` for it: the stutter at the first load. +/// `VICTORY_PIPELINE_KEEP_WORKER=0`: every worker takes any pipeline. +fn kept_worker(worker: usize, workers: usize) -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + worker == 0 + && workers >= 3 + && *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_KEEP_WORKER").is_none_or(|v| v != "0")) +} + +/// The priority level of a worker: [`priority_level`] by the requested +/// backlog; pipelines only started early (no draw waits for them) raise the +/// workers to normal at most, so a long early list no longer runs above +/// the title's own threads while it plays its intro video (it stuttered +/// at 10-21 fps there with 84-230 early pipelines queued, 2026-11-25). +/// `VICTORY_PIPELINE_EARLY_BOOST=1`: every queued pipeline counts, as before. +fn worker_level(worker: usize, workers: usize) -> u8 { + static ALL: OnceLock<bool> = OnceLock::new(); + let waiting = WAITING.load(Ordering::Relaxed); + if *ALL.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_EARLY_BOOST").is_some_and(|v| v == "1")) { + return priority_level(waiting, worker, workers); } + priority_level(ASKED_WAITING.load(Ordering::Relaxed), worker, workers).max(priority_level(waiting, worker, workers).min(1)) } -fn next() -> Arc<Pending> { +fn next(asked_only: bool) -> Arc<Pending> { let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); loop { - if let Some(p) = queue.pop() { + if let Some(p) = queue.pop_for(asked_only) { return p; } queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner()); } } -/// Starts the workers (half the logical processors, 2 to 8) on first use. +/// A worker is done with `p`: frees its heavy slot. +fn finished(p: &Pending) { + if p.heavy() { + let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); + queue.heavy_making = queue.heavy_making.saturating_sub(1); + AVAILABLE.notify_all(); + } +} + +/// Pipelines waiting past which the workers run above the title's +/// ordinary threads. +const BACKLOG: u64 = 64; + +/// Pipelines waiting past which half the workers run at the highest +/// priority short of time-critical. +const BIG_BACKLOG: u64 = 512; + +/// The priority level a worker runs at, 0 to 3 (below normal, normal, +/// above normal, highest), with `waiting` pipelines queued. +/// +/// Normal was not enough: the title raises its own threads (it binds +/// `SetThreadPriority` to the host's), and in a world run on an +/// i5-12400F and RTX 4060 the workers made 71 pipelines in 9 minutes +/// (about 7 a minute) while 1,675 waited and 5,000 draws a frame were +/// dropped for them. With a backlog the workers now go above the +/// title's ordinary threads, and with a long one half of them go to the +/// highest priority, the other half staying above normal so the title +/// keeps running; once the backlog is gone they drop back below normal. +/// `VICTORY_PIPELINE_BOOST=0`: normal at most, as before. +fn priority_level(waiting: u64, worker: usize, workers: usize) -> u8 { + static BOOST: OnceLock<bool> = OnceLock::new(); + let boost = *BOOST.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_BOOST").is_none_or(|v| v != "0")); + match waiting { + w if w <= BACKLOG => 0, + _ if !boost => 1, + w if w > BIG_BACKLOG && worker < workers.div_ceil(2) => 3, + _ => 2, + } +} + +/// Starts the workers on first use: two thirds of the logical processors, +/// 2 to 10, half of them (1 to 3: the driver ran out of memory with six +/// heavy compiles at once) allowed on heavy pipelines. +/// +/// Each gets a 64 MB stack (Peppacodes, upstream #966): NVIDIA's compiler +/// recursed past the default 2 MB on a world compute pipeline, and the +/// driver reported the overflow as E_OUTOFMEMORY, refusing it for good. +/// Only the pages used are committed. fn workers() -> bool { static RUNNING: OnceLock<bool> = OnceLock::new(); *RUNNING.get_or_init(|| { let mut running = false; - let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8)); + // Try 6.12 (all-out mode, as lepotane/VIctory-leonida's launcher): + // `VICTORY_PIPELINE_WORKERS` sets how many (1 to 32) and + // `VICTORY_PIPELINE_HEAVY` how many of them take heavy pipelines at + // once (1 to 8; more than 3 ran the driver out of memory before). + let env = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<usize>().ok()); + let workers = env("VICTORY_PIPELINE_WORKERS").map_or_else( + || std::thread::available_parallelism().map_or(2, |n| (n.get() * 2 / 3).clamp(2, 10)), + |n| n.clamp(1, 32), + ); + let heavy = + env("VICTORY_PIPELINE_HEAVY").map_or((workers / 2).clamp(1, 3), |n| n.clamp(1, 8).min(workers)); + QUEUE.lock().unwrap_or_else(|e| e.into_inner()).heavy_limit = heavy; + tracing::info!(workers, heavy, "pipeline workers"); for i in 0..workers { let spawned = std::thread::Builder::new() .name(format!("victory-pipelines-{i}")) - .spawn(|| { - // Below the title's own threads (loading, recording). - // SAFETY: a plain call on our own thread. - unsafe { - use windows::Win32::System::Threading::*; - let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); - } + .stack_size(64 << 20) + .spawn(move || { + let mut raised = None; loop { - next().make(); + let p = next(kept_worker(i, workers)); + // Below the title's own threads (loading, recording) + // unless a backlog waits: the title then runs at + // full load and starved the workers (4-9 pipelines a + // minute in the world on an i5-12400F; see + // `priority_level`). + let level = worker_level(i, workers); + if raised != Some(level) { + raised = Some(level); + // SAFETY: a plain call on our own thread. + unsafe { + use windows::Win32::System::Threading::*; + let _ = SetThreadPriority( + GetCurrentThread(), + match level { + 0 => THREAD_PRIORITY_BELOW_NORMAL, + 1 => THREAD_PRIORITY_NORMAL, + 2 => THREAD_PRIORITY_ABOVE_NORMAL, + _ => THREAD_PRIORITY_HIGHEST, + }, + ); + } + } + p.make(); + finished(&p); if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { drained(); } else { - super::library::save(false); + super::library::save_soon(); } } }); @@ -291,7 +850,7 @@ fn drained() { "host pipelines all made" ); } - super::library::save(false); + super::library::save_soon(); } #[cfg(test)] @@ -312,6 +871,44 @@ mod tests { assert!(matches!(p.made.get(), Some(None))); } + /// A draw into other formats than its pipeline declares finds the + /// pipeline for them, which exists once per set of formats and is + /// queued by its first draw like any other. + #[test] + fn a_pipeline_for_bound_formats_is_made_once() { + // The title's pipeline declares one render target, format 24. + let p = Arc::new(Pending::new(Vec::new(), Some(Box::new(GraphicsState::declaring(24))))); + assert_eq!(p.formats, [24, 0, 0, 0, 0, 0, 0, 0, 0]); + let g = p.graphics.as_deref().unwrap(); + let (a, b) = ([26, 0, 0, 0, 0, 0, 0, 0, 0], [28, 0, 0, 0, 0, 0, 0, 0, 0]); + let first = variant(&p, g, &a); + assert_eq!(first.formats, a); + assert_ne!(first.key, p.key); + assert!(Arc::ptr_eq(first, variant(&p, g, &a))); + let second = variant(&p, g, &b); + assert_eq!(second.formats, b); + assert!(!Arc::ptr_eq(first, second)); + assert_ne!(second.key, first.key); + assert!(Arc::ptr_eq(first, variant(&p, g, &a))); + assert!(Arc::ptr_eq(second, variant(&p, g, &b))); + assert_eq!(first.queue_state.load(Ordering::Relaxed), NOT_QUEUED); + assert_eq!(p.queue_state.load(Ordering::Relaxed), NOT_QUEUED); + } + + #[test] + fn pending_pipeline_is_recorded_for_the_next_launch() { + let mut p = Pending::new(Vec::new(), None); + p.key = "pending-pipeline-test".to_owned(); + // Simulate a worker that has taken the job but cannot finish it yet. + p.queue_state.store(MAKING, Ordering::Relaxed); + let p = Arc::new(p); + + assert!(!super::super::library::wanted_early(&p.key)); + assert!(ready(&p).is_none()); + assert!(p.made.get().is_none()); + assert!(super::super::library::wanted_early(&p.key)); + } + #[test] fn draws_promote_early_pipelines_without_claiming_them_twice() { let earlier = Arc::new(Pending::new(Vec::new(), None)); @@ -331,4 +928,41 @@ mod tests { assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier)); assert!(queue.pop().is_none()); } + + /// Workers go above the title's threads only with a backlog, and half + /// of them to the highest priority only with a long one. + #[test] + fn workers_rise_with_the_backlog() { + assert_eq!(priority_level(0, 0, 8), 0); + assert_eq!(priority_level(BACKLOG, 0, 8), 0); + assert_eq!(priority_level(BACKLOG + 1, 0, 8), 2); + assert_eq!(priority_level(BIG_BACKLOG + 1, 0, 8), 3); + assert_eq!(priority_level(BIG_BACKLOG + 1, 3, 8), 3); + assert_eq!(priority_level(BIG_BACKLOG + 1, 4, 8), 2); + assert_eq!(priority_level(BIG_BACKLOG + 1, 7, 8), 2); + } + + /// Heavy pipelines wait while their slots are taken; light ones and + /// those queued early go on past them. + #[test] + fn heavy_pipelines_do_not_hold_up_light_ones() { + let big = super::super::shader("compute", &vec![7u8; HEAVY_BYTES + 1]); + let heavy = || Arc::new(Pending::new(vec![big.clone()], None)); + let (h1, h2) = (heavy(), heavy()); + let light = Arc::new(Pending::new(Vec::new(), None)); + let early = Arc::new(Pending::new(Vec::new(), None)); + let mut queue = Queue::new(); + assert_eq!(queue.heavy_limit, 1); + + queue.push(&h1, REQUESTED); + queue.push(&h2, REQUESTED); + queue.push(&early, EARLY); + queue.push(&light, REQUESTED); + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &light)); + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &h1)); + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &early)); + assert!(queue.pop().is_none(), "the heavy slot is taken"); + queue.heavy_making -= 1; + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &h2)); + } } diff --git a/crates/victory-gpu/src/pipeline/recipe.rs b/crates/victory-gpu/src/pipeline/recipe.rs new file mode 100644 index 0000000000..48d8c85adc --- /dev/null +++ b/crates/victory-gpu/src/pipeline/recipe.rs @@ -0,0 +1,412 @@ +//! Pipeline recipes: what each title pipeline a draw or dispatch asked for +//! is made from (its shader containers and graphics state), kept in the +//! pipeline cache's folder so that `victory prepare` can make its host +//! pipeline with the game closed, on the cores the game would otherwise +//! fight for, into the same pipeline library a run loads from. +//! +//! In a world run on an RTX 4060 and i5-12400F, 1,675 pipelines were still +//! waiting after 9 minutes (4,600-6,000 draws a frame dropped for them: the +//! see-through world), because the title's own threads left the workers +//! a few pipelines a minute; each launch got further only by what the one +//! before had made. With the recipes, one launch that reaches a place is +//! enough: everything it asked for is made after it closes, and the next +//! launch loads it all from the library at its start. +//! +//! Two files, appended by one background thread so the title's threads +//! never wait on the disk: `recipe-shaders.bin` (every container once, by +//! its BLAKE3) and `recipes.bin` (one record per pipeline key). Each record +//! is a little-endian length and its bytes; a record cut short by a run +//! that ended while writing it is ignored. `VICTORY_RECIPES=0` keeps none. + +use std::collections::{HashMap, HashSet}; +use std::io::Write; +use std::path::Path; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc::{Sender, channel}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use super::Shader; +use super::host::{GraphicsState, HostPipeline}; + +const SHADERS_FILE: &str = "recipe-shaders.bin"; +const RECIPES_FILE: &str = "recipes.bin"; +/// Recipes kept at most (the early list keeps 8,192 keys). +const MAX_RECIPES: usize = 16_384; +/// A record past this is not one of ours (a damaged file). +const MAX_RECORD: usize = 64 << 20; + +enum Note { + Shader([u8; 32], Vec<u8>), + Recipe(String, Vec<u8>), +} + +fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RECIPES").is_none_or(|v| v != "0")) +} + +/// The writer thread's queue, started on first use; `None` without a cache +/// folder or with recipes off. +fn sender() -> Option<&'static Mutex<Sender<Note>>> { + static SENDER: OnceLock<Option<Mutex<Sender<Note>>>> = OnceLock::new(); + SENDER + .get_or_init(|| { + if !on() { + return None; + } + let dir = super::library::dir()?.to_path_buf(); + let (tx, rx) = channel::<Note>(); + let spawned = std::thread::Builder::new() + .name("victory-recipes".into()) + .spawn(move || { + let mut shaders: HashSet<[u8; 32]> = HashSet::new(); + for_each_record(&dir.join(SHADERS_FILE), |r| { + if let Some(hash) = r.get(..32).and_then(|h| <[u8; 32]>::try_from(h).ok()) { + shaders.insert(hash); + } + }); + let mut recipes: HashSet<String> = HashSet::new(); + for_each_record(&dir.join(RECIPES_FILE), |r| { + if let Some(recipe) = Recipe::parse(r) { + recipes.insert(recipe.key); + } + }); + let _ = std::fs::create_dir_all(&dir); + let open = |name: &str| { + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(dir.join(name)) + .ok() + }; + let (mut shader_file, mut recipe_file) = (None, None); + for note in rx { + let (file, name, bytes) = match note { + Note::Shader(hash, container) => { + if !shaders.insert(hash) { + continue; + } + let mut bytes = hash.to_vec(); + bytes.extend_from_slice(&container); + (&mut shader_file, SHADERS_FILE, bytes) + } + Note::Recipe(key, bytes) => { + if recipes.len() >= MAX_RECIPES || !recipes.insert(key) { + continue; + } + (&mut recipe_file, RECIPES_FILE, bytes) + } + }; + if file.is_none() { + *file = open(name); + } + if let Some(f) = file.as_mut() { + // One write per record: a run that ends mid-way + // leaves at most the last one cut short. + let mut record = (bytes.len() as u32).to_le_bytes().to_vec(); + record.extend_from_slice(&bytes); + if let Err(e) = f.write_all(&record) { + tracing::warn!(error = %e, file = name, "pipeline recipe not kept"); + *file = None; + } + } + } + }); + if let Err(e) = spawned { + tracing::warn!(error = %e, "no pipeline recipes"); + return None; + } + Some(Mutex::new(tx)) + }) + .as_ref() +} + +/// A draw or dispatch asked for the title pipeline `key` (made from +/// `shaders` and `graphics`) for the first time in this run: keeps its +/// recipe for `victory prepare`. +pub(crate) fn note(key: &str, shaders: &[Arc<Shader>], graphics: Option<&GraphicsState>) { + if shaders.is_empty() { + return; + } + let Some(tx) = sender() else { return }; + // Containers already sent in this run (the writer also skips those an + // earlier run kept). + static SENT: Mutex<Option<HashSet<String>>> = Mutex::new(None); + let mut notes = Vec::new(); + let mut record = Vec::new(); + record.push(key.len() as u8); + record.extend_from_slice(key.as_bytes()); + record.push(shaders.len() as u8); + { + let mut sent = SENT.lock().unwrap_or_else(|e| e.into_inner()); + let sent = sent.get_or_insert_with(HashSet::new); + for s in shaders { + let full = *blake3::hash(&s.container).as_bytes(); + record.push(s.stage.len() as u8); + record.extend_from_slice(s.stage.as_bytes()); + record.extend_from_slice(&full); + if sent.insert(s.hash.clone()) { + notes.push(Note::Shader(full, s.container.clone())); + } + } + } + if let Some(g) = graphics { + record.extend_from_slice(&g.encode()); + } + notes.push(Note::Recipe(key.to_owned(), record)); + let tx = tx.lock().unwrap_or_else(|e| e.into_inner()); + for n in notes { + let _ = tx.send(n); + } +} + +/// Calls `f` with each whole record of `path`. +fn for_each_record(path: &Path, mut f: impl FnMut(&[u8])) { + let Ok(bytes) = std::fs::read(path) else { return }; + let mut at = 0usize; + while let Some(len) = bytes.get(at..at + 4).map(|l| u32::from_le_bytes([l[0], l[1], l[2], l[3]]) as usize) { + let Some(record) = bytes.get(at + 4..at + 4 + len).filter(|_| len <= MAX_RECORD) else { break }; + f(record); + at += 4 + len; + } +} + +/// One recipe as kept. +struct Recipe { + key: String, + /// Stage and the container's BLAKE3. + shaders: Vec<(&'static str, [u8; 32])>, + /// The graphics state's bytes; empty for compute. + graphics: Vec<u8>, +} + +impl Recipe { + fn parse(mut r: &[u8]) -> Option<Recipe> { + fn take<'a>(r: &mut &'a [u8], n: usize) -> Option<&'a [u8]> { + if r.len() < n { + return None; + } + let (head, rest) = r.split_at(n); + *r = rest; + Some(head) + } + let key_len = take(&mut r, 1)?[0] as usize; + let key = String::from_utf8(take(&mut r, key_len)?.to_vec()).ok()?; + let count = take(&mut r, 1)?[0] as usize; + let mut shaders = Vec::with_capacity(count); + for _ in 0..count { + let len = take(&mut r, 1)?[0] as usize; + let stage = match take(&mut r, len)? { + b"vertex" => "vertex", + b"pixel" => "pixel", + b"mesh" => "mesh", + b"compute" => "compute", + b"amplification" => "amplification", + b"hull" => "hull", + b"domain" => "domain", + b"geometry" => "geometry", + _ => return None, + }; + let hash = <[u8; 32]>::try_from(take(&mut r, 32)?).ok()?; + shaders.push((stage, hash)); + } + let graphics = r.to_vec(); + Some(Recipe { key, shaders, graphics }) + } +} + +/// One host pipeline to make. +struct Job { + shaders: Vec<Arc<Shader>>, + graphics: Option<GraphicsState>, + heavy: bool, +} + +// SAFETY: as `make::Pending`: D3D12 objects are free-threaded and the +// graphics state (whose input elements point into its own names) is only +// read. +unsafe impl Send for Job {} +// SAFETY: as above. +unsafe impl Sync for Job {} + +/// What [`prepare`] did. +#[derive(Clone, Copy, Debug, Default)] +pub struct Prepared { + /// Recipes kept, and those whose containers were all kept. + pub recipes: usize, + pub usable: usize, + /// Host pipelines that were in the library already, made now, and + /// that could not be made (a shader that does not translate, a + /// pipeline the host refused). + pub loaded: u64, + pub made: u64, + pub failed: u64, +} + +/// Makes the host pipeline of every recipe kept (`victory prepare`), on +/// `threads` workers, into the pipeline library, which is saved at the +/// end; `progress` is called every 15 s and at the end. +pub fn prepare(threads: usize, progress: &(dyn Fn(&Prepared, bool) + Sync)) -> Prepared { + let mut out = Prepared::default(); + let Some(dir) = super::library::dir().map(Path::to_path_buf) else { + return out; + }; + // The early list is written with the library: read it first, so the + // save at the end keeps it. + let _ = super::library::wanted_early(""); + let mut containers: HashMap<[u8; 32], Vec<u8>> = HashMap::new(); + for_each_record(&dir.join(SHADERS_FILE), |r| { + if let Some(hash) = r.get(..32).and_then(|h| <[u8; 32]>::try_from(h).ok()) { + containers.entry(hash).or_insert_with(|| r[32..].to_vec()); + } + }); + let mut seen = HashSet::new(); + let mut recipes = Vec::new(); + for_each_record(&dir.join(RECIPES_FILE), |r| { + if let Some(recipe) = Recipe::parse(r) + && seen.insert(recipe.key.clone()) + { + recipes.push(recipe); + } + }); + out.recipes = recipes.len(); + // The programs a run skips (`VICTORY_SKIP_PIPELINES`) are not made. + let skipped: Vec<String> = std::env::var("VICTORY_SKIP_PIPELINES") + .unwrap_or_default() + .split(',') + .map(|h| h.trim().to_ascii_lowercase()) + .filter(|h| !h.is_empty()) + .collect(); + let jobs: Vec<Job> = recipes + .iter() + .filter_map(|r| { + let shaders: Option<Vec<Arc<Shader>>> = r + .shaders + .iter() + .map(|&(stage, hash)| containers.get(&hash).map(|c| super::shader(stage, c))) + .collect(); + let shaders = shaders?; + if shaders.iter().any(|s| skipped.contains(&s.hash)) { + return None; + } + // Try 6.12: nor those a run never builds (`VICTORY_DENY_PIPELINES`, + // and the passes that only serve rays with every ray a miss). + if super::make::denied(&shaders).is_some() || super::never_built(&shaders) { + return None; + } + let graphics = if r.graphics.is_empty() { + None + } else { + Some(GraphicsState::decode(&r.graphics)?) + }; + let heavy = shaders.iter().any(|s| s.size() > super::make::HEAVY_BYTES); + Some(Job { shaders, graphics, heavy }) + }) + .collect(); + drop(containers); + out.usable = jobs.len(); + tracing::info!(recipes = out.recipes, usable = out.usable, threads, "preparing host pipelines"); + let (loaded0, made0) = ( + super::library::LOADED.load(Ordering::Relaxed), + super::library::MADE.load(Ordering::Relaxed), + ); + let failed = AtomicU64::new(0); + let next = AtomicUsize::new(0); + // As the run's workers: at most half of them (1 to 3) on the biggest + // programs at once, which take the driver the most memory. + let heavy_limit = (threads / 2).clamp(1, 3); + let heavy_now = (Mutex::new(0usize), Condvar::new()); + let base = out; + let snapshot = |failed: u64| Prepared { + loaded: super::library::LOADED.load(Ordering::Relaxed).saturating_sub(loaded0), + made: super::library::MADE.load(Ordering::Relaxed).saturating_sub(made0), + failed, + ..base + }; + let last_said = Mutex::new(Instant::now()); + std::thread::scope(|s| { + for _ in 0..threads.max(1) { + // The run's workers' stack (NVIDIA's compiler recursed past 2 MB). + let worker = std::thread::Builder::new().stack_size(64 << 20); + let _ = worker.spawn_scoped(s, || { + while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let Job { shaders, graphics, heavy } = job; + if *heavy { + let (count, freed) = &heavy_now; + let mut n = count.lock().unwrap_or_else(|e| e.into_inner()); + while *n >= heavy_limit { + n = freed.wait(n).unwrap_or_else(|e| e.into_inner()); + } + *n += 1; + } + let made = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + HostPipeline::new(shaders, graphics.as_ref()).is_some() + })) + .unwrap_or(false); + if *heavy { + let (count, freed) = &heavy_now; + *count.lock().unwrap_or_else(|e| e.into_inner()) -= 1; + freed.notify_all(); + } + if !made { + failed.fetch_add(1, Ordering::Relaxed); + } + // Every 20 s at most, so a prepare cut short keeps most of its work. + super::library::save(false); + let mut last = last_said.lock().unwrap_or_else(|e| e.into_inner()); + if last.elapsed() >= Duration::from_secs(15) { + *last = Instant::now(); + progress(&snapshot(failed.load(Ordering::Relaxed)), false); + } + } + }); + } + }); + super::library::save(true); + out = snapshot(failed.load(Ordering::Relaxed)); + progress(&out, true); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recipes_read_back_and_a_cut_record_is_ignored() { + let mut record = vec![4u8]; + record.extend_from_slice(b"abcd"); + record.push(2); + for (stage, fill) in [("vertex", 1u8), ("pixel", 2u8)] { + record.push(stage.len() as u8); + record.extend_from_slice(stage.as_bytes()); + record.extend_from_slice(&[fill; 32]); + } + record.extend_from_slice(&[9, 9, 9]); + let r = Recipe::parse(&record).expect("parses"); + assert_eq!(r.key, "abcd"); + assert_eq!(r.shaders, vec![("vertex", [1u8; 32]), ("pixel", [2u8; 32])]); + assert_eq!(r.graphics, vec![9, 9, 9]); + + let dir = std::env::temp_dir().join(format!("victory-recipes-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join(RECIPES_FILE); + let mut bytes = Vec::new(); + for _ in 0..2 { + bytes.extend_from_slice(&(record.len() as u32).to_le_bytes()); + bytes.extend_from_slice(&record); + } + // A third record cut short, as by a run that ended writing it. + bytes.extend_from_slice(&(record.len() as u32).to_le_bytes()); + bytes.extend_from_slice(&record[..5]); + std::fs::write(&file, &bytes).unwrap(); + let mut n = 0; + for_each_record(&file, |r| { + assert!(Recipe::parse(r).is_some()); + n += 1; + }); + assert_eq!(n, 2); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/victory-gpu/src/plaincopy.rs b/crates/victory-gpu/src/plaincopy.rs new file mode 100644 index 0000000000..6d7e86b070 --- /dev/null +++ b/crates/victory-gpu/src/plaincopy.rs @@ -0,0 +1,385 @@ +//! Copies of title memory made in place, by this process, with a way back +//! when a page is not there (`VICTORY_COPY_PLAIN=1`; off by default). +//! +//! Every copy of title memory into a host buffer goes through the kernel +//! (`ReadProcessMemory` on our own process, `crate::host::copy_mapped`): +//! the title unmaps and remaps its memory while we read it, a read in +//! place of a page that is gone is an access violation, and the kernel's +//! copy fails instead. It costs what a system call that locks and probes +//! every page costs: run 225's profile has the submitting thread 35 ms a +//! frame inside `ZwReadVirtualMemory` for about 100 MB (3 GB a second), +//! where the processor's own copy moves that much in a third of the time. +//! +//! Here the copy is one `rep movsb` in a function of ours that uses no +//! stack. An exception handler, first in the line, looks at every access +//! violation: one that is a READ and happened at exactly that instruction +//! continues at the function's other exit, which returns 0, and the +//! caller falls back to the kernel's copy as before (it says which page +//! is gone and fills in zeros). A write that faults is not ours to take: +//! the destination is host memory, which is always there; such a fault +//! goes on to the handlers after this one. + +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +#[cfg(target_arch = "x86_64")] +core::arch::global_asm!( + ".globl victory_copy_guarded", + ".globl victory_copy_guarded_at", + ".globl victory_copy_guarded_fault", + "victory_copy_guarded:", + // rcx: to, rdx: from, r8: bytes. rsi and rdi are the caller's: kept in + // r9 and r10, which are ours to use, so nothing is on the stack. + " mov r9, rsi", + " mov r10, rdi", + " mov rdi, rcx", + " mov rsi, rdx", + " mov rcx, r8", + "victory_copy_guarded_at:", + " rep movsb", + " mov rsi, r9", + " mov rdi, r10", + " mov eax, 1", + " ret", + "victory_copy_guarded_fault:", + " mov rsi, r9", + " mov rdi, r10", + " xor eax, eax", + " ret", +); + +#[cfg(target_arch = "x86_64")] +unsafe extern "C" { + fn victory_copy_guarded(to: *mut u8, from: *const u8, len: usize) -> u32; + static victory_copy_guarded_at: u8; + static victory_copy_guarded_fault: u8; +} + +/// Whether copies of title memory into host memory are made in place +/// (`VICTORY_COPY_PLAIN=1`). +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = cfg!(target_arch = "x86_64") && std::env::var_os("VICTORY_COPY_PLAIN").is_some_and(|v| v == "1"); + if on { + install(); + tracing::info!( + "copies of title memory into host buffers are made in place, with the kernel's copy behind them for a \ + page that is not there (VICTORY_COPY_PLAIN=1)" + ); + } + on + }) +} + +/// Copies made in place, their bytes, the copies that met a page that was +/// not there (and went to the kernel's copy), and the copies not tried in +/// place because their source faulted lately ([`RECENT`]) or they were +/// under [`LEAST`] bytes, since the last line; and the fills of under +/// [`LEAST`] bytes made in place ([`copy_short`]). +static COUNT: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; + +/// The fewest bytes copied in place. A read of a byte or a word is how the +/// layer ASKS whether a page is there (a texture's first page, a record): +/// it is expected to fail, and a failed kernel read costs a microsecond +/// where a fault and its handler cost tens (run 230: 1,000 to 1,300 faults +/// a frame, nearly all of them such askings, took back most of what the +/// copies in place had won). +const LEAST: usize = 256; + +/// The 64 KiB blocks of title memory a copy in place faulted in lately: +/// their copies go straight to the kernel's, which reads round the hole. +/// By the block's number, in the place its low bits name (a later block +/// with the same low bits takes the place). Forgotten every two seconds: +/// the title maps the memory in the end. +static RECENT: [std::sync::atomic::AtomicUsize; 1024] = [const { std::sync::atomic::AtomicUsize::new(0) }; 1024]; +/// When [`RECENT`] was last emptied (milliseconds of [`now_ms`]). +static EMPTIED: AtomicU64 = AtomicU64::new(0); + +fn now_ms() -> u64 { + static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// The numbers of the first and last 64 KiB block of `[from, from + len)`, +/// never 0 (0 is an empty place). +fn blocks(from: usize, len: usize) -> (usize, usize) { + ((from >> 16) | 1 << 63, ((from + len.max(1) - 1) >> 16) | 1 << 63) +} + +/// Whether a copy from there faulted lately. +fn faulted_lately(from: usize, len: usize) -> bool { + let now = now_ms(); + let emptied = EMPTIED.load(Relaxed); + if now.saturating_sub(emptied) >= 2_000 && EMPTIED.compare_exchange(emptied, now, Relaxed, Relaxed).is_ok() { + for place in &RECENT { + place.store(0, Relaxed); + } + return false; + } + let (first, last) = blocks(from, len); + RECENT[first & 1023].load(Relaxed) == first || RECENT[last & 1023].load(Relaxed) == last +} + +/// A copy from there faulted. +fn note_fault(from: usize, len: usize) { + let (first, last) = blocks(from, len); + RECENT[first & 1023].store(first, Relaxed); + RECENT[last & 1023].store(last, Relaxed); +} + +/// The handler that turns a read fault inside [`guarded`] into its return +/// of false; put first in the line, once. +#[cfg(target_arch = "x86_64")] +fn install() { + use windows_sys::Win32::Foundation::{ + EXCEPTION_ACCESS_VIOLATION, EXCEPTION_GUARD_PAGE, EXCEPTION_IN_PAGE_ERROR, + }; + use windows_sys::Win32::System::Diagnostics::Debug::{ + AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, + }; + unsafe extern "system" fn on_fault(info: *mut EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes the exception being dispatched and the + // context it will continue with. + let (r, context) = unsafe { (&*(*info).ExceptionRecord, &mut *(*info).ContextRecord) }; + // Only at the copy's own instruction. + if context.Rip != (&raw const victory_copy_guarded_at) as u64 { + return EXCEPTION_CONTINUE_SEARCH; + } + const READ: usize = 0; + let read = r.NumberParameters >= 1 && r.ExceptionInformation[0] == READ; + let gone = (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION || r.ExceptionCode == EXCEPTION_IN_PAGE_ERROR) && read; + if gone || r.ExceptionCode == EXCEPTION_GUARD_PAGE { + context.Rip = (&raw const victory_copy_guarded_fault) as u64; + return EXCEPTION_CONTINUE_EXECUTION; + } + EXCEPTION_CONTINUE_SEARCH + } + static ONCE: std::sync::Once = std::sync::Once::new(); + // SAFETY: a handler that reads the record it is given and nothing else. + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(on_fault)); + }); +} + +#[cfg(not(target_arch = "x86_64"))] +fn install() {} + +/// Copies `len` bytes from `from` to `to` in place; false if a page of the +/// source was not there (then some of `to` may have been written). +/// +/// `to` must be writable memory of `len` bytes that is ours (host memory); +/// `from` may be anything. +#[cfg(target_arch = "x86_64")] +fn guarded(to: *mut u8, from: *const u8, len: usize) -> bool { + install(); + // SAFETY: the destination is the caller's to write; a source page that + // is not there ends the copy with 0 instead of a fault ([`install`]). + unsafe { victory_copy_guarded(to, from, len) != 0 } +} + +#[cfg(not(target_arch = "x86_64"))] +fn guarded(_: *mut u8, _: *const u8, _: usize) -> bool { + false +} + +/// With [`on`]: copies title memory at `from` into host memory at `to`; +/// false if it is off or a source page was not there (the caller then +/// copies through the kernel, as before). +pub(crate) fn copy(to: *mut u8, from: *const u8, len: usize) -> bool { + if !on() { + return false; + } + if len < LEAST { + COUNT[4].fetch_add(1, Relaxed); + return false; + } + if faulted_lately(from as usize, len) { + COUNT[3].fetch_add(1, Relaxed); + return false; + } + let whole = guarded(to, from, len); + if whole { + COUNT[0].fetch_add(1, Relaxed); + COUNT[1].fetch_add(len as u64, Relaxed); + } else { + COUNT[2].fetch_add(1, Relaxed); + note_fault(from as usize, len); + } + whole +} + +/// With [`on`]: copies `len` bytes, fewer than [`LEAST`], of title memory +/// at `from` into host memory at `to`, for a caller that is NOT asking +/// whether the page is there but expects it to be (a list's fill of upload +/// memory: constants the title recorded a draw with). False if it is off, +/// if the source faulted lately, or if a source page was not there; the +/// caller then copies through the kernel, as before. +/// +/// Why: the floor of [`copy`] is there for the askings, which fail. The +/// fills do not: 8,000 to 12,000 of them a frame went to the kernel's copy +/// (run 279's lines, "of under 256 bytes"), about 400 ns each where the +/// copy in place of 16 to 128 bytes is about 30 ns (timed on this +/// processor, 2026-11-25, two million copies each). +pub(crate) fn copy_short(to: *mut u8, from: *const u8, len: usize) -> bool { + if !on() { + return false; + } + if faulted_lately(from as usize, len) { + COUNT[3].fetch_add(1, Relaxed); + return false; + } + let whole = guarded(to, from, len); + if whole { + COUNT[5].fetch_add(1, Relaxed); + } else { + COUNT[2].fetch_add(1, Relaxed); + note_fault(from as usize, len); + } + whole +} + +/// The fewest bytes [`copy`] takes: what is shorter is [`copy_short`]'s, +/// for callers that may use it. +pub(crate) const fn least() -> usize { + LEAST +} + +/// With the frame line: what [`copy`] did per frame over `frames`. +pub(crate) fn line(frames: f64) { + if !on() { + return; + } + let [copies, bytes, gone, lately, small, fills] = [0, 1, 2, 3, 4, 5].map(|i| COUNT[i].swap(0, Relaxed) as f64 / frames); + tracing::info!( + "copies of title memory made in place per frame (VICTORY_COPY_PLAIN=1): {copies:.0}, {:.1} MB; {gone:.1} met a page \ + that was not there and went through the kernel's copy; left to the kernel's copy untried: {lately:.0} whose source \ + faulted in the last two seconds, {small:.0} of under {LEAST} bytes; fills of under {LEAST} bytes made in place \ + (VICTORY_FILLS_PLAIN): {fills:.0}", + bytes / 1e6 + ); +} + +#[cfg(all(test, target_arch = "x86_64"))] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + + const PAGE: usize = 4096; + + #[test] + fn memory_that_is_there_is_copied() { + let from: Vec<u8> = (0..100_000u32).map(|i| (i * 7 + 3) as u8).collect(); + let mut to = vec![0u8; from.len()]; + assert!(guarded(to.as_mut_ptr(), from.as_ptr(), from.len())); + assert_eq!(to, from); + // Nothing to copy is a copy. + assert!(guarded(to.as_mut_ptr(), from.as_ptr(), 0)); + } + + /// A fill's few bytes: copied whole where they are there, up to the last + /// byte of a page; a copy that runs into a hole by one byte ends with + /// false and the thread goes on. + #[test] + fn a_short_copy_is_whole_or_ends_without_a_fault() { + // SAFETY: memory of the test's own. + let base = unsafe { VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } as *mut u8; + assert!(!base.is_null()); + // SAFETY: the first page of that reservation. + assert!(!unsafe { VirtualAlloc(base.cast(), PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + // SAFETY: committed and writable. + let page = unsafe { std::slice::from_raw_parts_mut(base, PAGE) }; + for (i, b) in page.iter_mut().enumerate() { + *b = (i * 13 + 5) as u8; + } + for len in [1usize, 16, 64, 255] { + let mut to = vec![0u8; len]; + // The page's last bytes. + assert!(guarded(to.as_mut_ptr(), base.wrapping_add(PAGE - len), len), "{len}"); + assert_eq!(to, page[PAGE - len..], "{len}"); + // One byte into the hole. + let mut to = vec![0u8; len]; + assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(PAGE - len + 1), len), "{len}"); + assert_eq!(to[..len - 1], page[PAGE - len + 1..], "{len}: the bytes before the hole"); + } + // SAFETY: the test's reservation. + unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }; + } + + /// Three pages reserved, the first committed: a copy that stays in the + /// first page is whole; one that runs into the second ends with false, + /// the bytes before the hole copied, and the thread goes on. + #[test] + fn a_page_that_is_not_there_ends_the_copy_without_a_fault() { + // SAFETY: memory of the test's own. + let base = unsafe { VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } as *mut u8; + assert!(!base.is_null()); + // SAFETY: the first page of that reservation. + assert!(!unsafe { VirtualAlloc(base.cast(), PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + // SAFETY: committed and writable. + unsafe { std::slice::from_raw_parts_mut(base, PAGE) }.fill(0xAB); + let mut to = vec![0u8; 2 * PAGE]; + assert!(guarded(to.as_mut_ptr(), base, PAGE)); + assert!(to[..PAGE].iter().all(|&b| b == 0xAB)); + to.fill(0); + assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(PAGE / 2), PAGE)); + assert!(to[..PAGE / 2].iter().all(|&b| b == 0xAB), "the bytes before the hole"); + assert!(to[PAGE / 2..].iter().all(|&b| b == 0), "nothing after it"); + // A source that is not there at all. + assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(PAGE), PAGE)); + // Committed but closed to reads. + // SAFETY: the third page of the reservation. + assert!(!unsafe { VirtualAlloc(base.wrapping_add(2 * PAGE).cast(), PAGE, MEM_COMMIT, PAGE_NOACCESS) }.is_null()); + assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(2 * PAGE), 16)); + // And the registers the caller owns came back: this still works. + assert!(guarded(to.as_mut_ptr(), base, PAGE)); + assert!(to[..PAGE].iter().all(|&b| b == 0xAB)); + // SAFETY: the test's reservation. + unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }; + } + + /// A source that faulted is remembered by its 64 KiB blocks, and only + /// those. + #[test] + fn a_source_that_faulted_is_remembered_by_its_blocks() { + // (Addresses no other test uses; the table is shared.) + let at = 0x7654_3210_0000usize; + assert!(!faulted_lately(at, 4096)); + note_fault(at + 100, 4096); + assert!(faulted_lately(at, 16)); + assert!(faulted_lately(at + 0xffff, 1)); + // A copy that ends in the block, and one that begins in it. + assert!(faulted_lately(at - 4096, 8192)); + // The blocks beside it are not remembered. + assert!(!faulted_lately(at + 0x10000, 4096)); + assert!(!faulted_lately(at - 0x10000, 4096)); + assert_eq!(blocks(0, 0), (1 << 63, 1 << 63)); + } + + /// Many threads at once, half of them faulting: each gets its own answer. + #[test] + fn threads_fault_and_copy_side_by_side() { + // SAFETY: memory of the test's own. + let base = unsafe { VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(base, 0); + // SAFETY: the first page of that reservation. + assert!(!unsafe { VirtualAlloc(base as *const _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + let threads: Vec<_> = (0..8) + .map(|t| { + std::thread::spawn(move || { + let mut to = vec![0u8; PAGE]; + for _ in 0..2_000 { + let from = (base + if t % 2 == 0 { 0 } else { PAGE }) as *const u8; + assert_eq!(guarded(to.as_mut_ptr(), from, PAGE), t % 2 == 0); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + // SAFETY: the test's reservation. + unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) }; + } +} diff --git a/crates/victory-gpu/src/presentfx.rs b/crates/victory-gpu/src/presentfx.rs new file mode 100644 index 0000000000..5ad8443503 --- /dev/null +++ b/crates/victory-gpu/src/presentfx.rs @@ -0,0 +1,765 @@ +//! What the present does to the title's frames on their way to the screen +//! (Try 4.2), a child of `host` so it shares the swap chain's helpers: +//! +//! * **Render scale** (idea 6, after the DLSS/FSR enabler mods): +//! `VICTORY_RENDER_SCALE` below 100 tells the title a smaller display +//! (`crate::dxgi::render_scale`), so it renders every pass at that +//! size, and here each frame is scaled up to the screen's size with a +//! Catmull-Rom filter, clamped to the four nearest texels as FSR's EASU +//! is (no rings), and sharpened with FSR's RCAS (contrast-adaptive: +//! edges and texture detail get their contrast back, flat areas and +//! noise are left alone; `VICTORY_SHARPEN`, percent, 80 by default since +//! Try 5.8). +//! * **Frames in between** (idea 7, after VR's asynchronous spacewarp): +//! with `VICTORY_FRAMEGEN=1`, each new frame of the title is compared +//! with the one before, block by block (16x16 pixels, a search of ±20 +//! pixels coarse and then to the pixel), and while the title works on +//! its next frame, a frame is shown every `VICTORY_FRAMEGEN_MS` (33 by +//! default) that moves the last one on along that motion, as far as the +//! time since it was shown is of the time between the title's frames. +//! The camera and what moves keep moving on the screen between the +//! title's frames. It adds no frames of the title's own: the frame-rate +//! line still counts only those. +//! +//! How: the title's frame is copied on the host's queue into a ring of +//! three textures of ours, and a fence is signalled behind the copy. The +//! swap chain is on a queue of its own: it waits for that fence, runs our +//! passes and presents, so the frames made in between never wait behind +//! the title's work. Before a ring texture is written again the host's +//! queue waits until our queue is done with it. +//! +//! Anything that fails while setting up leaves the present as it was. + +use super::*; + +use std::sync::atomic::{AtomicBool, AtomicU64}; + +/// The passes, compiled with the system's compiler (`super::compile`). +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=12, b0), DescriptorTable(SRV(t0, numDescriptors=2), UAV(u0, numDescriptors=2))" +cbuffer C : register(b0) { + uint2 inSize; + uint2 outSize; + float amount; + float sharp; + uint useMotion; + uint blocksX; + uint blocksY; + uint3 pad; +}; +Texture2D<float4> cur : register(t0); +Texture2D<float4> prev : register(t1); +RWTexture2D<float4> outTex : register(u0); +RWStructuredBuffer<float2> motion : register(u1); + +#define BLOCK 16 + +float luma(float3 c) { return dot(c, float3(0.299, 0.587, 0.114)); } + +float3 texelOf(Texture2D<float4> t, int2 p) { + p = clamp(p, int2(0, 0), int2(inSize) - 1); + return t.Load(int3(p, 0)).rgb; +} + +groupshared uint best; + +uint cost(int2 origin, int2 d) { + float s = 0; + [loop] for (int y = 0; y < BLOCK; y += 2) { + [loop] for (int x = 0; x < BLOCK; x += 2) { + int2 p = origin + int2(x, y); + s += abs(luma(texelOf(cur, p)) - luma(texelOf(prev, p + d))); + } + } + // A small toll per pixel of motion: flat areas stay still. + s += 0.004 * (abs(d.x) + abs(d.y)); + return min((uint)(s * 4096.0), 0x1ffffffu); +} + +[RootSignature(RS)] +[numthreads(9, 9, 1)] +void motionMain(uint3 g : SV_GroupID, uint3 t : SV_GroupThreadID, uint i : SV_GroupIndex) { + int2 origin = int2(g.xy) * BLOCK; + if (i == 0) best = 0xffffffffu; + GroupMemoryBarrierWithGroupSync(); + int2 d = (int2(t.xy) - 4) * 5; + InterlockedMin(best, (cost(origin, d) << 7) | i); + GroupMemoryBarrierWithGroupSync(); + uint k = best & 127; + int2 coarse = (int2(k % 9, k / 9) - 4) * 5; + GroupMemoryBarrierWithGroupSync(); + if (i == 0) best = 0xffffffffu; + GroupMemoryBarrierWithGroupSync(); + d = coarse + int2(t.xy) - 4; + InterlockedMin(best, (cost(origin, d) << 7) | i); + GroupMemoryBarrierWithGroupSync(); + if (i == 0) { + uint k2 = best & 127; + int2 fine = coarse + int2(k2 % 9, k2 / 9) - 4; + motion[g.y * blocksX + g.x] = float2(fine); + } +} + +float2 motionAt(float2 p) { + float2 b = p / BLOCK - 0.5; + int2 b0 = (int2)floor(b); + float2 f = b - float2(b0); + int2 most = int2(blocksX, blocksY) - 1; + int2 a = clamp(b0, int2(0, 0), most); + int2 c = clamp(b0 + 1, int2(0, 0), most); + float2 m00 = motion[a.y * blocksX + a.x]; + float2 m10 = motion[a.y * blocksX + c.x]; + float2 m01 = motion[c.y * blocksX + a.x]; + float2 m11 = motion[c.y * blocksX + c.x]; + return lerp(lerp(m00, m10, f.x), lerp(m01, m11, f.x), f.y); +} + +// The title's frame at output pixel `o` (pixel centres at +0.5): a +// Catmull-Rom filter clamped to the four nearest texels, as FSR's EASU is +// (no rings). +float3 upscaled(int2 o) { + o = clamp(o, int2(0, 0), int2(outSize) - 1); + float2 p = (float2(o) + 0.5) * float2(inSize) / float2(outSize); + if (useMotion != 0) p += motionAt(p) * amount; + float2 q = p - 0.5; + int2 i = (int2)floor(q); + float2 f = q - float2(i); + float2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f)); + float2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f); + float2 w2 = f * (0.5 + f * (2.0 - 1.5 * f)); + float2 w3 = f * f * (-0.5 + 0.5 * f); + float wx[4] = { w0.x, w1.x, w2.x, w3.x }; + float wy[4] = { w0.y, w1.y, w2.y, w3.y }; + float3 c = 0; + [unroll] for (int y = 0; y < 4; y++) { + [unroll] for (int x = 0; x < 4; x++) { + c += texelOf(cur, i + int2(x - 1, y - 1)) * (wx[x] * wy[y]); + } + } + float3 s00 = texelOf(cur, i); + float3 s10 = texelOf(cur, i + int2(1, 0)); + float3 s01 = texelOf(cur, i + int2(0, 1)); + float3 s11 = texelOf(cur, i + int2(1, 1)); + float3 lo = min(min(s00, s10), min(s01, s11)); + float3 hi = max(max(s00, s10), max(s01, s11)); + return saturate(clamp(c, lo, hi)); +} + +// Try 5.8: then sharpened as FSR 1's RCAS does (robust contrast-adaptive +// sharpening, AMD, MIT licence): each pixel against its four neighbours, +// as hard as it can be without going past their range (no halos), less +// where the contrast is high already. The old pass sharpened against a +// bilinear blur and clamped the result back to the four nearest texels, +// which took most of it away again. +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void resolveMain(uint3 id : SV_DispatchThreadID) { + if (id.x >= outSize.x || id.y >= outSize.y) return; + int2 o = int2(id.xy); + float3 e = upscaled(o); + if (sharp > 0) { + float3 b = upscaled(o + int2(0, -1)); + float3 d = upscaled(o + int2(-1, 0)); + float3 fr = upscaled(o + int2(1, 0)); + float3 h = upscaled(o + int2(0, 1)); + float3 mn4 = min(min(b, d), min(fr, h)); + float3 mx4 = max(max(b, d), max(fr, h)); + float3 hitMin = mn4 / (4.0 * mx4 + 1e-5); + float3 hitMax = (1.0 - mx4) / (4.0 * mn4 - 4.0 - 1e-5); + float3 lobeRGB = max(-hitMin, hitMax); + float lobe = max(-0.1875, min(max(lobeRGB.r, max(lobeRGB.g, lobeRGB.b)), 0.0)) * sharp; + e = (lobe * (b + d + fr + h) + e) / (4.0 * lobe + 1.0); + } + outTex[id.xy] = float4(saturate(e), 1.0); +} +"#; + +/// Whether frames are made between the title's (`VICTORY_FRAMEGEN=1`). +fn framegen() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FRAMEGEN").is_some_and(|v| v == "1")) +} + +/// Milliseconds between frames made in between (`VICTORY_FRAMEGEN_MS`). +fn framegen_ms() -> u64 { + static MS: OnceLock<u64> = OnceLock::new(); + *MS.get_or_init(|| { + std::env::var("VICTORY_FRAMEGEN_MS") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .map_or(33, |ms| ms.clamp(8, 200)) + }) +} + +/// How much the scaled frame is sharpened, 0 to 1 (`VICTORY_SHARPEN`, +/// percent; 80 by default since 5.8, RCAS's own default strength). +fn sharpen() -> f32 { + static SHARP: OnceLock<f32> = OnceLock::new(); + *SHARP.get_or_init(|| { + std::env::var("VICTORY_SHARPEN") + .ok() + .and_then(|v| v.trim().parse::<u32>().ok()) + .map_or(80, |p| p.min(100)) as f32 + / 100.0 + }) +} + +/// Whether the present goes through here. +pub(super) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| framegen() || crate::dxgi::output_size().is_some()) && !FAILED.load(Ordering::Relaxed) +} + +/// Setting up failed: the present is as it was for the rest of the run. +static FAILED: AtomicBool = AtomicBool::new(false); + +/// Frames made in between since the last line about them. +static MADE: AtomicU64 = AtomicU64::new(0); + +/// Blocks of the motion field at most (a 4096x2304 frame). +const BLOCKS: u32 = 256 * 144; + +/// Ring textures. +const RING: usize = 3; + +/// Descriptor sets for the ring's generations (each set: the frame, the +/// one before, the output, the motion field; one set per ring texture). +const GENERATIONS: u32 = 16; + +/// Our queue's lists. +const LISTS: usize = 8; + +struct Fx { + queue: ID3D12CommandQueue, + swap_chain: IDXGISwapChain3, + hwnd: HWND, + out_size: (u32, u32), + root: ID3D12RootSignature, + motion_pso: ID3D12PipelineState, + resolve_pso: ID3D12PipelineState, + views: ID3D12DescriptorHeap, + view_cpu: usize, + view_gpu: u64, + step: u32, + out: ID3D12Resource, + motion: ID3D12Resource, + /// The ring of the title's frames, their size and format, and the + /// descriptor generation they are in. + ring: Vec<ID3D12Resource>, + in_size: (u32, u32), + in_format: DXGI_FORMAT, + generation: u32, + /// Ring textures of earlier sizes: lists of ours may still read them. + retired: Vec<ID3D12Resource>, + /// The value of `done` after our queue's last use of each ring texture. + used: [u64; RING], + /// The host queue's lists for the copies, with the submission each + /// last flew as, and the one for copies waited for at once. + copies: Vec<(HostList, u64)>, + copy_now: Option<HostList>, + /// Signalled on the host's queue behind each copy. + ready: ID3D12Fence, + ready_value: u64, + /// Signalled on our queue behind each list. + done: ID3D12Fence, + done_value: u64, + lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u64)>, + event: HANDLE, + /// The title's frames copied so far. + frames: u64, + /// `done`'s value behind the last of them, when it was seen shown, + /// and the time between the title's frames (seconds, smoothed). + last_real: u64, + shown: Option<std::time::Instant>, + last_present: Option<std::time::Instant>, + interval: f64, + logged: std::time::Instant, + meter: Meter, +} + +// SAFETY: D3D12 and DXGI objects are free-threaded; the window handle is +// only passed to the system; everything is used under `FX`'s lock. +unsafe impl Send for Fx {} + +static FX: Mutex<Option<Fx>> = Mutex::new(None); + +fn texture(device: &ID3D12Device, (width, height): (u32, u32), format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> windows::core::Result<ID3D12Resource> { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: u64::from(width), + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + }; + let mut made: Option<ID3D12Resource> = None; + // SAFETY: plain creation from descriptions that live through the call. + unsafe { device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made)? }; + made.ok_or_else(windows::core::Error::empty) +} + +fn uav_barrier(resource: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + // SAFETY: a borrowed pointer; the barrier never releases it. + pResource: unsafe { std::mem::transmute_copy(resource) }, + }), + }, + } +} + +impl Fx { + fn new(host: &Host, in_size: (u32, u32), format: DXGI_FORMAT) -> windows::core::Result<Fx> { + use windows::core::s; + let device = &host.device; + let out_size = crate::dxgi::output_size().unwrap_or(in_size); + let motion_cs = super::compile(SOURCE, s!("motionMain"), s!("cs_5_1"))?; + let resolve_cs = super::compile(SOURCE, s!("resolveMain"), s!("cs_5_1"))?; + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + // SAFETY: plain object creation; the descriptions and the shaders' + // bytes live through each call, and the root signature is inside + // the shaders. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &resolve_cs[..])?; + let pso = |cs: &[u8]| { + device.CreateComputePipelineState::<ID3D12PipelineState>(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: code(cs), + ..Default::default() + }) + }; + let motion_pso = pso(&motion_cs[..])?; + let resolve_pso = pso(&resolve_cs[..])?; + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + let views: ID3D12DescriptorHeap = device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: GENERATIONS * RING as u32 * 4, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })?; + let out = texture(device, out_size, swap_format(format).unwrap_or(format), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)?; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let buffer = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: u64::from(BLOCKS) * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let mut motion: Option<ID3D12Resource> = None; + device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, None, &mut motion)?; + let motion = motion.ok_or_else(windows::core::Error::empty)?; + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; + let ready: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let done: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + let mut lists = Vec::with_capacity(LISTS); + for _ in 0..LISTS { + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + lists.push((allocator, list, 0)); + } + // The swap chain last: once it is made, the window is ours. + let hwnd = match title_window() { + Some(hwnd) => hwnd, + None => window(out_size.0, out_size.1)?, + }; + let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let desc = DXGI_SWAP_CHAIN_DESC1 { + Width: out_size.0, + Height: out_size.1, + Format: swap_format(format).unwrap_or(format), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: BUFFERS, + SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, + ..Default::default() + }; + let swap_chain = factory.CreateSwapChainForHwnd(&queue, hwnd, &desc, None, None)?.cast::<IDXGISwapChain3>()?; + tracing::info!( + in_width = in_size.0, + in_height = in_size.1, + out_width = out_size.0, + out_height = out_size.1, + render_scale = crate::dxgi::render_scale(), + framegen = framegen(), + framegen_ms = framegen_ms(), + sharpen = sharpen(), + "presenting through our passes (VICTORY_RENDER_SCALE: the title renders smaller and is scaled up; VICTORY_FRAMEGEN=1: frames in between)" + ); + let mut fx = Fx { + queue, + swap_chain, + hwnd, + out_size, + root, + motion_pso, + resolve_pso, + view_cpu: views.GetCPUDescriptorHandleForHeapStart().ptr, + view_gpu: views.GetGPUDescriptorHandleForHeapStart().ptr, + step: device.GetDescriptorHandleIncrementSize(kind), + views, + out, + motion, + ring: Vec::new(), + in_size: (0, 0), + in_format: DXGI_FORMAT_UNKNOWN, + generation: 0, + retired: Vec::new(), + used: [0; RING], + copies: Vec::new(), + copy_now: None, + ready, + ready_value: 0, + done, + done_value: 0, + lists, + event, + frames: 0, + last_real: 0, + shown: None, + last_present: None, + interval: 0.0, + logged: std::time::Instant::now(), + meter: Meter::new(), + }; + fx.make_ring(device, in_size, format)?; + Ok(fx) + } + } + + /// The ring for frames of `size` in `format`, and its descriptor sets. + fn make_ring(&mut self, device: &ID3D12Device, size: (u32, u32), format: DXGI_FORMAT) -> windows::core::Result<()> { + let typed = swap_format(format).unwrap_or(format); + let mut ring = Vec::with_capacity(RING); + for _ in 0..RING { + ring.push(texture(device, size, typed, D3D12_RESOURCE_FLAG_NONE)?); + } + self.retired.append(&mut self.ring); + self.ring = ring; + self.in_size = size; + self.in_format = format; + self.generation = (self.generation + 1) % GENERATIONS; + self.frames = 0; + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: 0, + NumElements: BLOCKS, + StructureByteStride: 8, + CounterOffsetInBytes: 0, + Flags: D3D12_BUFFER_UAV_FLAG_NONE, + }, + }, + }; + for k in 0..RING { + let at = |n: usize| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: self.view_cpu + (self.set(k) * 4 + n as u32) as usize * self.step as usize, + }; + // SAFETY: slots of our heap that no list of ours still reads + // (a generation is used again only after 15 more sizes); live + // resources. + unsafe { + device.CreateShaderResourceView(&self.ring[k], None, at(0)); + device.CreateShaderResourceView(&self.ring[(k + RING - 1) % RING], None, at(1)); + device.CreateUnorderedAccessView(&self.out, None::<&ID3D12Resource>, None, at(2)); + device.CreateUnorderedAccessView(&self.motion, None::<&ID3D12Resource>, Some(&uav), at(3)); + } + } + tracing::info!(width = size.0, height = size.1, format = format.0, "frames of the title taken for our passes at this size"); + Ok(()) + } + + /// The descriptor set of ring texture `k` in this generation. + fn set(&self, k: usize) -> u32 { + self.generation * RING as u32 + k as u32 + } + + /// Records our passes for ring texture `cur` into `l`, shown into the + /// back buffer `back`: the motion field first if `motion`, and the + /// frame moved on by `amount` of it (0: as it is). + /// + /// # Safety + /// `l` is open; `back` is the swap chain's current back buffer. + unsafe fn record(&self, l: &ID3D12GraphicsCommandList, back: &ID3D12Resource, cur: usize, motion: bool, amount: f32) { + let prev = (cur + RING - 1) % RING; + let (bx, by) = (self.in_size.0.div_ceil(16), self.in_size.1.div_ceil(16)); + let constants: [u32; 12] = [ + self.in_size.0, + self.in_size.1, + self.out_size.0, + self.out_size.1, + amount.to_bits(), + (if self.in_size == self.out_size { 0.0f32 } else { sharpen() }).to_bits(), + u32::from(amount > 0.0), + bx, + by, + 0, + 0, + 0, + ]; + let table = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: self.view_gpu + u64::from(self.set(cur) * 4) * u64::from(self.step), + }; + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + let common = D3D12_RESOURCE_STATE_COMMON; + let uav = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + // SAFETY: (the caller's) an open list; our own live objects. + unsafe { + l.SetDescriptorHeaps(&[Some(self.views.clone())]); + l.SetComputeRootSignature(&self.root); + l.ResourceBarrier(&[ + transition(&self.ring[cur], common, read), + transition(&self.ring[prev], common, read), + transition(&self.out, common, uav), + transition(&self.motion, common, uav), + ]); + l.SetComputeRootDescriptorTable(1, table); + l.SetComputeRoot32BitConstants(0, 12, constants.as_ptr().cast(), 0); + if motion && bx * by <= BLOCKS { + l.SetPipelineState(&self.motion_pso); + l.Dispatch(bx, by, 1); + l.ResourceBarrier(&[uav_barrier(&self.motion)]); + } + l.SetPipelineState(&self.resolve_pso); + l.Dispatch(self.out_size.0.div_ceil(8), self.out_size.1.div_ceil(8), 1); + l.ResourceBarrier(&[ + transition(&self.out, uav, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST), + transition(&self.ring[cur], read, common), + transition(&self.ring[prev], read, common), + transition(&self.motion, uav, common), + ]); + l.CopyResource(back, &self.out); + l.ResourceBarrier(&[ + transition(&self.out, D3D12_RESOURCE_STATE_COPY_SOURCE, common), + transition(back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT), + ]); + } + } + + /// Runs our passes for ring texture `cur` on our queue (after the + /// host's queue reached `ready` value `wait`, if given) and presents. + fn show(&mut self, cur: usize, motion: bool, amount: f32, wait: Option<u64>) -> windows::core::Result<()> { + // SAFETY: our own objects; a list is reset only once our queue is + // done with it; the back buffer is the current one, under the lock. + unsafe { + let done = self.done.GetCompletedValue(); + let i = match self.lists.iter().position(|l| l.2 <= done) { + Some(i) => i, + None => { + let (i, oldest) = self.lists.iter().enumerate().min_by_key(|(_, l)| l.2).map(|(i, l)| (i, l.2)).unwrap_or((0, 0)); + self.done.SetEventOnCompletion(oldest, self.event)?; + WaitForSingleObject(self.event, INFINITE); + i + } + }; + let (allocator, list) = (self.lists[i].0.clone(), self.lists[i].1.clone()); + allocator.Reset()?; + list.Reset(&allocator, None)?; + let index = self.swap_chain.GetCurrentBackBufferIndex(); + let back: ID3D12Resource = self.swap_chain.GetBuffer(index)?; + self.record(&list, &back, cur, motion, amount); + list.Close()?; + if let Some(value) = wait { + self.queue.Wait(&self.ready, value)?; + } + self.queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>()?)]); + self.done_value += 1; + self.queue.Signal(&self.done, self.done_value)?; + self.lists[i].2 = self.done_value; + self.used[cur] = self.done_value; + self.used[(cur + RING - 1) % RING] = self.done_value; + let _ = self.swap_chain.Present(0, DXGI_PRESENT(0)); + } + Ok(()) + } + + /// The title's frame `texture` (in host state `state`): copied into + /// the ring on the host's queue, then shown through our passes. + fn present(&mut self, host: &Host, texture: &ID3D12Resource, state: u32) -> windows::core::Result<()> { + // SAFETY: a live resource. + let desc = unsafe { texture.GetDesc() }; + let size = (desc.Width as u32, desc.Height); + if (size, desc.Format) != (self.in_size, self.in_format) { + self.make_ring(&host.device, size, desc.Format)?; + } + let slot = (self.frames % RING as u64) as usize; + let state = D3D12_RESOURCE_STATES(state as i32); + let ahead = late_free_present(); + let index = if ahead { + let finished = FINISHED.load(Ordering::Acquire); + match self.copies.iter().position(|(_, flown)| *flown <= finished) { + Some(i) => Some(i), + None => { + let list = host.new_list()?; + list.close(); + self.copies.push((list, 0)); + Some(self.copies.len() - 1) + } + } + } else { + None + }; + if index.is_none() && self.copy_now.is_none() { + let list = host.new_list()?; + list.close(); + self.copy_now = Some(list); + } + let copy = match index { + Some(i) => &self.copies[i].0, + None => self.copy_now.as_ref().ok_or_else(windows::core::Error::empty)?, + }; + copy.reset(); + let ring = &self.ring[slot]; + // SAFETY: an open list of ours; live resources; the ring texture + // rests in the common state between our uses. + unsafe { + let list = ©.list; + list.ResourceBarrier(&[ + transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition(ring, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST), + ]); + list.CopyResource(ring, texture); + list.ResourceBarrier(&[ + transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), + transition(ring, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON), + ]); + } + copy.close(); + // Our queue is done with the ring texture before it is written. + // SAFETY: our fence; a wait on the host's queue. + unsafe { host.queue.Wait(&self.done, self.used[slot])? }; + match index { + Some(i) => { + let flown = host.execute_own(&self.copies[i].0); + self.copies[i].1 = flown; + } + None => { + if let Some(copy) = &self.copy_now { + host.execute(&[copy]); + } + } + } + self.ready_value += 1; + // SAFETY: our fence, behind the copy on the host's queue. + unsafe { host.queue.Signal(&self.ready, self.ready_value)? }; + let motion = framegen() && self.frames >= 1; + self.frames += 1; + self.show(slot, motion, 0.0, Some(self.ready_value))?; + self.last_real = self.done_value; + self.shown = None; + let now = std::time::Instant::now(); + if let Some(last) = self.last_present { + let dt = now.duration_since(last).as_secs_f64().min(1.0); + self.interval = if self.interval <= 0.0 { dt } else { 0.7 * self.interval + 0.3 * dt }; + } + self.last_present = Some(now); + self.meter.frame(self.hwnd); + if framegen() && self.logged.elapsed().as_secs() >= 5 { + let made = MADE.swap(0, Ordering::Relaxed) as f64 / self.logged.elapsed().as_secs_f64(); + self.logged = now; + tracing::info!( + "frames made between the title's (VICTORY_FRAMEGEN=1): {made:.1} a second, the title's every {:.0} ms", + self.interval * 1000.0 + ); + } + Ok(()) + } + + /// The thread's turn: a frame moved on from the title's last, if that + /// one is on the screen and the title's next is not due yet. + fn between(&mut self) { + if self.frames < 2 || self.interval <= 0.0 { + return; + } + // SAFETY: a plain query. + if unsafe { self.done.GetCompletedValue() } < self.last_real { + return; + } + let shown = *self.shown.get_or_insert_with(std::time::Instant::now); + let amount = shown.elapsed().as_secs_f64() / self.interval; + if !(0.1..=1.0).contains(&amount) { + return; + } + let cur = ((self.frames - 1) % RING as u64) as usize; + match self.show(cur, false, amount as f32, None) { + Ok(()) => { + MADE.fetch_add(1, Ordering::Relaxed); + } + Err(e) => tracing::warn!(error = %e, "a frame in between was not shown"), + } + } +} + +/// The thread that shows frames in between ([`framegen`]). +fn between_thread() { + loop { + std::thread::sleep(std::time::Duration::from_millis(framegen_ms())); + let mut fx = FX.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(fx) = fx.as_mut() { + fx.between(); + } + } +} + +/// Shows the title's frame `texture` through our passes. `None`: not +/// here (a format the passes do not write, or setting up failed), the +/// caller presents as before. +pub(super) fn present(host: &Host, texture: &ID3D12Resource, state: u32) -> Option<Option<bool>> { + // SAFETY: a live resource. + let desc = unsafe { texture.GetDesc() }; + let format = swap_format(desc.Format)?; + if format != DXGI_FORMAT_R8G8B8A8_UNORM && format != DXGI_FORMAT_R10G10B10A2_UNORM && format != DXGI_FORMAT_R16G16B16A16_FLOAT { + return None; + } + let mut fx = FX.lock().unwrap_or_else(|e| e.into_inner()); + if fx.is_none() { + match Fx::new(host, (desc.Width as u32, desc.Height), desc.Format) { + Ok(made) => { + *fx = Some(made); + if framegen() { + let _ = std::thread::Builder::new().name("victory-frames-between".into()).spawn(between_thread); + } + } + Err(e) => { + FAILED.store(true, Ordering::Relaxed); + tracing::warn!(error = %e, "our present passes could not be set up: frames are shown as before"); + return None; + } + } + } + let fx = fx.as_mut()?; + if let Err(e) = fx.present(host, texture, state) { + tracing::warn!(error = %e, "a frame was not shown through our passes"); + } + Some(Some(false)) +} diff --git a/crates/victory-gpu/src/pressure.rs b/crates/victory-gpu/src/pressure.rs new file mode 100644 index 0000000000..38d9f7a2e2 --- /dev/null +++ b/crates/victory-gpu/src/pressure.rs @@ -0,0 +1,332 @@ +//! How short the PC and the card are of memory, for the work that can wait. +//! +//! Our take on what codec_d's cool_fox (DoubleGhosty/cool_fox ab75ac3e, +//! f4b48ad) does with its residency guard and pool back-off, for this +//! fork, which has neither its block pool nor its residency module: +//! +//! - three levels ([`Level`]) from what Windows has left to commit, the free +//! physical memory and the card's budget, looked at most every 32 ms; a +//! refused allocation makes it [`Level::Critical`] for two seconds +//! (cool_fox's `critical_commit`, apart from mild pressure, so that mild +//! pressure no longer starves textures); +//! - after a refused upload buffer, uploads that can wait (texture staging) +//! are not asked of the driver for half a second ([`backing_off`]): the +//! driver refused one, and asking again for every texture is a burst of +//! failing calls, felt as a stutter (cool_fox: eight refused block +//! creations in one burst); +//! - the sweeps let go of idle memory sooner as the level rises, the texture +//! pass takes fewer bytes a frame, and kept upload buffers are fewer. +//! +//! `VICTORY_PRESSURE=0`: always [`Level::Normal`], and no back-off. + +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// How short of memory the host is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Level { + /// Room: everything as it was. + Normal = 0, + /// Getting short: idle memory goes sooner, fewer upload buffers kept. + Mild = 1, + /// Nearly out, or a refusal just now: no texture catch-up, idle memory + /// goes after a second, nothing kept. + Critical = 2, +} + +const MIB: u64 = 1 << 20; +const GIB: u64 = 1 << 30; + +/// How long after a refused allocation the level stays critical. +const REFUSED_CRITICAL_MS: u64 = 2000; +/// How long uploads that can wait are not asked for after a refusal. +const BACK_OFF_MS: u64 = 500; + +/// The level from the figures (pure, for the tests): bytes Windows has +/// left to commit, free physical bytes, the card's budget and use, and how +/// long ago an allocation was refused. +#[cfg(test)] +pub(crate) fn classify( + commit_left: Option<u64>, + ram_left: Option<u64>, + card: Option<(u64, u64)>, + refused_ago_ms: Option<u64>, +) -> Level { + classify_with(&Limits::DEFAULT, commit_left, ram_left, card, refused_ago_ms) +} + +/// Where the levels start: (mild, critical) bytes left to commit, bytes of +/// free physical memory, and percent of the card's budget in use. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Limits { + commit: (u64, u64), + ram: (u64, u64), + card_percent: (u64, u64), +} + +impl Limits { + const DEFAULT: Limits = + Limits { commit: (4 * GIB, 1536 * MIB), ram: (3 * GIB, GIB), card_percent: (85, 97) }; + + /// [`Limits::DEFAULT`] with the pairs the variables give, each + /// `mild,critical` (Try 6.12's all-out mode sets them to about 1% of + /// the PC's memory and 98/99% of the card): `VICTORY_PRESSURE_COMMIT_MB`, + /// `VICTORY_PRESSURE_RAM_MB`, `VICTORY_PRESSURE_CARD_PERCENT`. + fn from_vars(get: impl Fn(&str) -> Option<String>) -> Limits { + let pair = |name: &str, unit: u64, or: (u64, u64)| -> (u64, u64) { + let Some(text) = get(name) else { return or }; + let mut parts = text.split(',').map(|p| p.trim().parse::<u64>().ok()); + match (parts.next().flatten(), parts.next().flatten()) { + (Some(mild), Some(critical)) => (mild * unit, critical * unit), + (Some(both), None) => (both * unit, both * unit), + _ => or, + } + }; + let d = Limits::DEFAULT; + // Mild comes first: at least as many bytes left as critical, and at + // most the card's share critical starts at. + let commit = pair("VICTORY_PRESSURE_COMMIT_MB", MIB, d.commit); + let ram = pair("VICTORY_PRESSURE_RAM_MB", MIB, d.ram); + let card = pair("VICTORY_PRESSURE_CARD_PERCENT", 1, d.card_percent); + let card = (card.0.clamp(50, 100), card.1.clamp(50, 100)); + Limits { + commit: (commit.0.max(commit.1), commit.1), + ram: (ram.0.max(ram.1), ram.1), + card_percent: (card.0.min(card.1), card.1), + } + } +} + +/// The limits of this run ([`Limits::from_vars`] the environment), said once. +fn limits() -> &'static Limits { + static L: std::sync::OnceLock<Limits> = std::sync::OnceLock::new(); + L.get_or_init(|| { + let l = Limits::from_vars(|name| std::env::var(name).ok()); + if l != Limits::DEFAULT { + tracing::info!( + commit_mb = ?(l.commit.0 / MIB, l.commit.1 / MIB), + ram_mb = ?(l.ram.0 / MIB, l.ram.1 / MIB), + card_percent = ?l.card_percent, + "memory pressure starts later (mild, critical): VICTORY_PRESSURE_*" + ); + } + l + }) +} + +/// [`classify`] against `limits`. +pub(crate) fn classify_with( + limits: &Limits, + commit_left: Option<u64>, + ram_left: Option<u64>, + card: Option<(u64, u64)>, + refused_ago_ms: Option<u64>, +) -> Level { + let card_pct = card + .filter(|&(budget, _)| budget > 0) + .map(|(budget, used)| (u128::from(used) * 100 / u128::from(budget)) as u64); + if refused_ago_ms.is_some_and(|ago| ago < REFUSED_CRITICAL_MS) + || commit_left.is_some_and(|c| c < limits.commit.1) + || ram_left.is_some_and(|r| r < limits.ram.1) + || card_pct.is_some_and(|p| p >= limits.card_percent.1) + { + Level::Critical + } else if commit_left.is_some_and(|c| c < limits.commit.0) + || ram_left.is_some_and(|r| r < limits.ram.0) + || card_pct.is_some_and(|p| p >= limits.card_percent.0) + { + Level::Mild + } else { + Level::Normal + } +} + +fn on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_PRESSURE").is_none_or(|v| v != "0")) +} + +/// The level now (looked at again at most every 32 ms). +static LEVEL: AtomicU64 = AtomicU64::new(0); +static LOOKED: AtomicU64 = AtomicU64::new(0); +/// When an allocation was last refused (`crate::host::now_ms` + 1; 0: never). +static REFUSED_AT: AtomicU64 = AtomicU64::new(0); +/// Since the start: refused allocations; uploads not asked for while +/// backing off; looks at each level. +pub(crate) static COUNTS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +/// At the last look: MiB left to commit, MiB of free physical memory, the +/// card's budget and use in MiB. +static FIGURES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +fn refused_ago(now: u64) -> Option<u64> { + match REFUSED_AT.load(Relaxed) { + 0 => None, + at => Some(now.saturating_sub(at - 1)), + } +} + +/// How short of memory the host is now. +pub(crate) fn level() -> Level { + if !on() { + return Level::Normal; + } + let now = crate::host::now_ms(); + let looked = LOOKED.load(Relaxed); + if (looked == 0 || now >= looked + 32) && LOOKED.compare_exchange(looked, now.max(1), Relaxed, Relaxed).is_ok() { + look(now); + } + match LEVEL.load(Relaxed) { + 0 => Level::Normal, + 1 => Level::Mild, + _ => Level::Critical, + } +} + +fn look(now: u64) { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32; + // SAFETY: a sized structure. + let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0; + // (ullAvailPageFile: what the process may still commit, the limit an + // upload buffer or a staging buffer runs into first) + let (commit, ram) = if ok { (Some(m.ullAvailPageFile), Some(m.ullAvailPhys)) } else { (None, None) }; + let card = crate::host::host() + .and_then(|h| h.video_memory()) + .map(|[budget, used, ..]| (budget, used)); + let level = classify_with(limits(), commit, ram, card, refused_ago(now)); + LEVEL.store(level as u64, Relaxed); + COUNTS[2 + level as usize].fetch_add(1, Relaxed); + FIGURES[0].store(commit.unwrap_or(0) / MIB, Relaxed); + FIGURES[1].store(ram.unwrap_or(0) / MIB, Relaxed); + FIGURES[2].store(card.map_or(0, |c| c.0) / MIB, Relaxed); + FIGURES[3].store(card.map_or(0, |c| c.1) / MIB, Relaxed); +} + +/// The driver refused an allocation: critical for a while, uploads that +/// can wait back off, and the next sweep comes at once. +pub(crate) fn refused() { + if !on() { + return; + } + let now = crate::host::now_ms(); + let first = refused_ago(now).is_none_or(|ago| ago >= BACK_OFF_MS); + REFUSED_AT.store(now + 1, Relaxed); + COUNTS[0].fetch_add(1, Relaxed); + LEVEL.store(Level::Critical as u64, Relaxed); + crate::host::sweep_soon(); + if first { + crate::host::trail(|| "an allocation was refused: uploads that can wait back off for 500 ms".to_owned()); + } +} + +/// Whether uploads that can wait are not to be asked of the driver now +/// (half a second after a refusal); counts the one not asked. +pub(crate) fn backing_off() -> bool { + if !on() { + return false; + } + let off = refused_ago(crate::host::now_ms()).is_some_and(|ago| ago < BACK_OFF_MS); + if off { + COUNTS[1].fetch_add(1, Relaxed); + } + off +} + +/// The longest a sweep keeps idle memory at this level (`u64::MAX`: as the +/// sweep itself decides), for memory in the PC (`card` false) or the card. +pub(crate) fn idle_cap_ms(card: bool) -> u64 { + match (level(), card) { + (Level::Normal, _) => u64::MAX, + (Level::Mild, false) => 5_000, + (Level::Mild, true) => 2_500, + (Level::Critical, _) => 1_000, + } +} + +/// The share of its bytes a frame's texture pass takes at this level, in +/// quarters, and whether a backlog may take more (mild pressure leaves the +/// textures alone: cool_fox found that starving them on mild pressure left +/// surfaces black). +pub(crate) fn texture_pass_quarters() -> (u64, bool) { + match level() { + Level::Normal => (4, true), + Level::Mild => (4, true), + // (Not halved: on 6 and 8 GB cards the waiting textures were the + // black roads, buildings and people; only the catch-up goes.) + Level::Critical => (4, false), + } +} + +/// For the frame report: one line of what the levels did. +pub(crate) fn report() -> String { + let c = |i: usize| COUNTS[i].load(Relaxed); + let f = |i: usize| FIGURES[i].load(Relaxed); + format!( + "memory pressure: {:?} now ({} MB left to commit, {} MB free, card {} of {} MB); looks normal {} mild {} critical {}; \ + allocations refused {}, uploads held back after a refusal {}", + level(), + f(0), + f(1), + f(3), + f(2), + c(2), + c(3), + c(4), + c(0), + c(1) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn levels_follow_commit_memory_card_and_refusals() { + let plenty = (Some(20 * GIB), Some(16 * GIB), Some((8 * GIB, 4 * GIB)), None); + assert_eq!(classify(plenty.0, plenty.1, plenty.2, plenty.3), Level::Normal); + assert_eq!(classify(None, None, None, None), Level::Normal); + // Mild: under 4 GiB to commit, under 3 GiB free, the card 85% used. + assert_eq!(classify(Some(3 * GIB), plenty.1, plenty.2, None), Level::Mild); + assert_eq!(classify(plenty.0, Some(2 * GIB), plenty.2, None), Level::Mild); + assert_eq!(classify(plenty.0, plenty.1, Some((100, 85)), None), Level::Mild); + // Critical: under 1.5 GiB to commit, the card full, a refusal now. + assert_eq!(classify(Some(GIB), plenty.1, plenty.2, None), Level::Critical); + assert_eq!(classify(plenty.0, plenty.1, Some((100, 97)), None), Level::Critical); + assert_eq!(classify(plenty.0, plenty.1, plenty.2, Some(10)), Level::Critical); + // A refusal long ago no longer counts. + assert_eq!(classify(plenty.0, plenty.1, plenty.2, Some(5_000)), Level::Normal); + // A card with no budget said is no pressure. + assert_eq!(classify(plenty.0, plenty.1, Some((0, 5)), None), Level::Normal); + } + + #[test] + fn limits_come_from_the_variables() { + assert_eq!(Limits::from_vars(|_| None), Limits::DEFAULT); + let all_out = Limits::from_vars(|name| match name { + "VICTORY_PRESSURE_COMMIT_MB" => Some("400,200".to_owned()), + "VICTORY_PRESSURE_RAM_MB" => Some("300, 160".to_owned()), + "VICTORY_PRESSURE_CARD_PERCENT" => Some("98,99".to_owned()), + _ => None, + }); + assert_eq!(all_out.commit, (400 * MIB, 200 * MIB)); + assert_eq!(all_out.ram, (300 * MIB, 160 * MIB)); + assert_eq!(all_out.card_percent, (98, 99)); + // Mild never after critical. + let odd = Limits::from_vars(|name| match name { + "VICTORY_PRESSURE_RAM_MB" => Some("100,200".to_owned()), + "VICTORY_PRESSURE_CARD_PERCENT" => Some("99,90".to_owned()), + _ => None, + }); + assert_eq!((odd.ram, odd.card_percent), ((200 * MIB, 200 * MIB), (90, 90))); + let short = (Some(GIB), Some(500 * MIB), Some((100, 95)), None); + assert_eq!(classify(short.0, short.1, short.2, short.3), Level::Critical); + assert_eq!(classify_with(&all_out, short.0, short.1, short.2, short.3), Level::Normal); + assert_eq!(classify_with(&all_out, short.0, Some(100 * MIB), short.2, None), Level::Critical); + assert_eq!(classify_with(&all_out, short.0, Some(200 * MIB), short.2, None), Level::Mild); + assert_eq!(classify_with(&all_out, short.0, short.1, Some((100, 98)), None), Level::Mild); + // Not a number: the default pair. + assert_eq!(Limits::from_vars(|_| Some("x".to_owned())), Limits::DEFAULT); + } +} diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs index e2fba782e4..df3cf2ce1b 100644 --- a/crates/victory-gpu/src/primitive.rs +++ b/crates/victory-gpu/src/primitive.rs @@ -1,10 +1,9 @@ //! Console primitive types the host lacks. A rectangle list gives three //! corners per rectangle, the second the one between the other two, and -//! the hardware adds the fourth at `v0 + v2 - v1` (Grand Theft Auto VI's +//! the hardware adds the fourth at `v0 + v2 - v1` (the title's //! full-screen rectangles come as top left, bottom left, bottom right); on //! the host each rectangle becomes two triangles, with the fourth vertex -//! made from the other three on the CPU for direct draws and on the GPU for -//! indirect draws ([`crate::rectangles`]). +//! made from the other three on the CPU. //! //! shortcut: the fourth vertex is computed from vertex inputs, not from //! vertex shader outputs as the hardware does; that is the same for vertex @@ -12,282 +11,17 @@ //! [`components`] does not know keep the first vertex's value, and so do //! components past the end of the vertex (an element that reaches into the //! next one, which the layout allows). - -/// Console-only primitive topologies expanded into standard D3D12 triangle or -/// line list index buffers. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum ExpandedTopology { - TriangleFan, - LineLoop, - Quads, - QuadStrip, -} - -impl ExpandedTopology { - const TRIANGLE_FAN: u32 = 6; - const LINE_LOOP: u32 = 18; - const QUADS: u32 = 19; - const QUAD_STRIP: u32 = 20; - - /// Returns the expanded console topology kind, or `None` for standard PC - /// topologies and `RECTANGLES` (handled via vertex expansion). - pub(crate) fn from_console(topology: u32) -> Option<Self> { - match topology { - Self::TRIANGLE_FAN => Some(Self::TriangleFan), - Self::LINE_LOOP => Some(Self::LineLoop), - Self::QUADS => Some(Self::Quads), - Self::QUAD_STRIP => Some(Self::QuadStrip), - _ => None, - } - } - - /// Standard D3D12 primitive topology value (`LINELIST = 2`, `TRIANGLELIST = 4`). - pub(crate) fn host_topology(self) -> u32 { - match self { - Self::LineLoop => 2, - Self::TriangleFan | Self::Quads | Self::QuadStrip => 4, - } - } - - /// Maximum number of indices emitted for `count` input vertices or indices. - pub(crate) fn max_output_indices(self, count: u32) -> u32 { - match self { - Self::TriangleFan => count.saturating_sub(2).saturating_mul(3), - Self::LineLoop => { - if count >= 2 { - count.saturating_mul(2) - } else { - 0 - } - } - Self::Quads => (count / 4).saturating_mul(6), - Self::QuadStrip => { - if count >= 4 { - ((count - 2) / 2).saturating_mul(6) - } else { - 0 - } - } - } - } - - /// Expands `count` sequential 16-bit vertex indices starting at `start`. - pub(crate) fn expand_non_indexed_u16(self, count: u32, start: u16, dst: &mut [u16]) -> usize { - expand_indices( - self, - (0..count).map(|i| start.wrapping_add(i as u16)), - None, - start, - dst, - ) - } - - /// Expands `count` sequential 32-bit vertex indices starting at `start`. - pub(crate) fn expand_non_indexed_u32(self, count: u32, start: u32, dst: &mut [u32]) -> usize { - expand_indices( - self, - (0..count).map(|i| start.wrapping_add(i)), - None, - start, - dst, - ) - } - - /// Expands 16-bit indices from `src`, honoring optional strip-cut `cut` and - /// padding unused tail slots with degenerate primitives. - pub(crate) fn expand_indexed_u16( - self, - src: &[u16], - cut: Option<u16>, - fallback_pad: u16, - dst: &mut [u16], - ) -> usize { - expand_indices(self, src.iter().copied(), cut, fallback_pad, dst) - } - - /// Expands 32-bit indices from `src`, honoring optional strip-cut `cut` and - /// padding unused tail slots with degenerate primitives. - pub(crate) fn expand_indexed_u32( - self, - src: &[u32], - cut: Option<u32>, - fallback_pad: u32, - dst: &mut [u32], - ) -> usize { - expand_indices(self, src.iter().copied(), cut, fallback_pad, dst) - } -} - -fn expand_indices<T: Copy + Eq>( - kind: ExpandedTopology, - indices: impl IntoIterator<Item = T>, - cut: Option<T>, - fallback_pad: T, - dst: &mut [T], -) -> usize { - let mut written = 0usize; - let mut emit = |slice: &[T]| { - if written + slice.len() <= dst.len() { - dst[written..written + slice.len()].copy_from_slice(slice); - written += slice.len(); - } - }; - match kind { - ExpandedTopology::TriangleFan => { - let mut pivot = None; - let mut prev = None; - for v in indices { - if cut == Some(v) { - pivot = None; - prev = None; - continue; - } - match (pivot, prev) { - (None, _) => pivot = Some(v), - (Some(_), None) => prev = Some(v), - (Some(p), Some(q)) => { - emit(&[p, q, v]); - prev = Some(v); - } - } - } - } - ExpandedTopology::LineLoop => { - let mut first = None; - let mut prev = None; - let mut run_len = 0usize; - for v in indices { - if cut == Some(v) { - if run_len >= 2 - && let (Some(f), Some(p)) = (first, prev) - { - emit(&[p, f]); - } - first = None; - prev = None; - run_len = 0; - continue; - } - if let Some(p) = prev { - emit(&[p, v]); - } else { - first = Some(v); - } - prev = Some(v); - run_len += 1; - } - if run_len >= 2 - && let (Some(f), Some(p)) = (first, prev) - { - emit(&[p, f]); - } - } - ExpandedTopology::Quads => { - let mut q = [None; 3]; - let mut len = 0usize; - for v in indices { - if cut == Some(v) { - len = 0; - continue; - } - if len < 3 { - q[len] = Some(v); - len += 1; - } else if let [Some(v0), Some(v1), Some(v2)] = q { - emit(&[v0, v1, v2, v0, v2, v]); - len = 0; - } - } - } - ExpandedTopology::QuadStrip => { - let mut a = None; - let mut b = None; - let mut c = None; - for v in indices { - if cut == Some(v) { - a = None; - b = None; - c = None; - continue; - } - match (a, b, c) { - (None, _, _) => a = Some(v), - (Some(_), None, _) => b = Some(v), - (Some(_), Some(_), None) => c = Some(v), - (Some(v0), Some(v1), Some(v2)) => { - emit(&[v0, v1, v, v0, v, v2]); - a = Some(v2); - b = Some(v); - c = None; - } - } - } - } - } - if written < dst.len() { - let pad = if written > 0 { dst[0] } else { fallback_pad }; - dst[written..].fill(pad); - } - written -} +//! +//! A pipeline the title makes for rectangles completes them on the GPU +//! instead, in a geometry stage (`victory_shader::emit::rect_list_gs`): +//! from the vertex shader's outputs, whichever vertex the corner is, for +//! direct, indexed and indirect draws alike. This expansion is what is +//! left for a pipeline that could not get that stage. /// Expands `rects` rectangles of `stride`-byte vertices from `src` into six /// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both /// triangles turn the same way. `elements` are (byte offset, format). pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) { - if stride == 12 - && matches!( - elements, - [(0, 16), (8, 28 | 29 | 87 | 91)] | [(8, 28 | 29 | 87 | 91), (0, 16)] - ) - { - expand_position_color(src, dst, elements); - } else { - expand_rects_generic(src, dst, stride, elements); - } -} - -/// Packed float2 positions and four UNORM8 channels. This layout covers the -/// entire vertex, so the fourth vertex needs no initial copy or format lookup. -fn expand_position_color(src: &[u8], dst: &mut [u8], elements: &[(u32, u32)]) { - let (rects, _) = src.as_chunks::<36>(); - let (triangles, _) = dst.as_chunks_mut::<72>(); - for (rect, out) in rects.iter().zip(triangles) { - let (vertices, _) = rect.as_chunks::<12>(); - let [first, middle, last] = *vertices else { - unreachable!("three vertices per rectangle"); - }; - let mut position = [0.0f32; 2]; - let mut finite = true; - for (axis, result) in position.iter_mut().enumerate() { - let read = |vertex: &[u8; 12]| f32::from_le_bytes(vertex.as_chunks::<4>().0[axis]); - let (a, b, c) = (read(&first), read(&middle), read(&last)); - finite &= a.is_finite() & b.is_finite() & c.is_finite(); - *result = (a + c) - b; - } - if !finite { - // Use the generic calculation for NaNs and infinities, including - // the choice of NaN payload when more than one operand is a NaN. - expand_rects_generic(rect, out, 12, elements); - continue; - } - - out[..36].copy_from_slice(rect); - out[36..48].copy_from_slice(&first); - out[48..60].copy_from_slice(&last); - out[60..64].copy_from_slice(&position[0].to_le_bytes()); - out[64..68].copy_from_slice(&position[1].to_le_bytes()); - // Normalization and denormalization cancel. The f32 error is far - // below half a channel step, so the generic rounding gives this same - // integer except where both paths already clamp to 0 or 255. - for channel in 8..12 { - let sum = i16::from(first[channel]) + i16::from(last[channel]); - out[60 + channel] = (sum - i16::from(middle[channel])).clamp(0, 255) as u8; - } - } -} - -fn expand_rects_generic(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) { for (rect, out) in src .chunks_exact(3 * stride) .zip(dst.chunks_exact_mut(6 * stride)) @@ -315,8 +49,8 @@ fn expand_rects_generic(src: &[u8], dst: &mut [u8], stride: usize, elements: &[( } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Kind { +#[derive(Clone, Copy)] +enum Kind { F32, F16, Unorm8, @@ -324,7 +58,7 @@ pub(crate) enum Kind { } /// Component count and kind of the vertex formats rectangles use. -pub(crate) fn components(format: u32) -> Option<(usize, Kind)> { +fn components(format: u32) -> Option<(usize, Kind)> { Some(match format { 2 => (4, Kind::F32), 6 => (3, Kind::F32), @@ -341,7 +75,7 @@ pub(crate) fn components(format: u32) -> Option<(usize, Kind)> { } impl Kind { - pub(crate) fn bytes(self) -> usize { + fn bytes(self) -> usize { match self { Kind::F32 => 4, Kind::F16 | Kind::Unorm16 => 2, @@ -349,16 +83,6 @@ impl Kind { } } - /// Numeric code shared with [`crate::rectangles`]'s HLSL shader. - pub(crate) fn code(self) -> u32 { - match self { - Kind::F32 => 0, - Kind::F16 => 1, - Kind::Unorm16 => 2, - Kind::Unorm8 => 3, - } - } - fn read(self, at: &[u8], c: usize) -> f32 { let b = &at[c * self.bytes()..]; match self { @@ -501,115 +225,6 @@ mod tests { assert_eq!(dst[40..], vertex(4.0, 6.0)[..]); } - #[test] - fn packed_position_color_matches_generic_expansion() { - let mut src = packed_rectangles(4096); - // The first rectangle exercises signed zeros, a subnormal and - // overflow with finite operands. The second needs the nonfinite path. - for (vertex, position) in src.as_chunks_mut::<12>().0.iter_mut().zip([ - [-0.0, f32::MAX], - [0.0, f32::from_bits(1)], - [-0.0, f32::MAX], - [f32::from_bits(0x7fc0_0123), f32::INFINITY], - [1.0, f32::NEG_INFINITY], - [f32::from_bits(0xffc0_0456), f32::NEG_INFINITY], - ]) { - vertex[..4].copy_from_slice(&position[0].to_le_bytes()); - vertex[4..8].copy_from_slice(&position[1].to_le_bytes()); - } - // Underflow, exact zero, exact 255 and overflow in the same color. - src[8..12].copy_from_slice(&[0, 0, 255, 255]); - src[20..24].copy_from_slice(&[1, 255, 1, 0]); - src[32..36].copy_from_slice(&[0, 255, 1, 1]); - - src.extend_from_slice(&[0xaa; 35]); - for format in [28, 29, 87, 91] { - let layout = [(0, 16), (8, format)]; - let reversed = [(8, format), (0, 16)]; - for elements in [layout, reversed] { - for dst_len in [71, 4095 * 72 + 71, 4097 * 72 + 71] { - let mut expected = vec![0xcc; dst_len]; - let mut actual = expected.clone(); - expand_rects_generic(&src, &mut expected, 12, &elements); - expand_rects(&src, &mut actual, 12, &elements); - assert_eq!(actual, expected); - } - } - } - } - - #[test] - #[ignore = "release microbenchmark"] - fn benchmark_position_color_expansion() { - use std::hint::black_box; - use std::time::{Duration, Instant}; - - let elements = [(0, 16), (8, 28)]; - for count in [1, 64, 1024] { - let src = packed_rectangles(count); - let mut before = vec![0; count * 72]; - let mut after = before.clone(); - let iterations = 200_000 / count; - expand_rects_generic(&src, &mut before, 12, &elements); - expand_rects(&src, &mut after, 12, &elements); - assert_eq!(before, after); - - type Expand = fn(&[u8], &mut [u8], usize, &[(u32, u32)]); - let measure = |expand: Expand, dst: &mut [u8]| { - let start = Instant::now(); - for _ in 0..iterations { - expand( - black_box(&src), - black_box(dst), - black_box(12), - black_box(&elements), - ); - black_box(&*dst); - } - start.elapsed() - }; - let mut baseline = [Duration::ZERO; 9]; - let mut optimized = baseline; - for sample in 0..baseline.len() { - if sample % 2 == 0 { - baseline[sample] = measure(expand_rects_generic, &mut before); - optimized[sample] = measure(expand_rects, &mut after); - } else { - optimized[sample] = measure(expand_rects, &mut after); - baseline[sample] = measure(expand_rects_generic, &mut before); - } - } - assert_eq!(before, after); - baseline.sort_unstable(); - optimized.sort_unstable(); - let ns_per_rect = - |elapsed: Duration| elapsed.as_secs_f64() * 1e9 / (iterations * count) as f64; - let (base, opt) = (ns_per_rect(baseline[4]), ns_per_rect(optimized[4])); - println!( - "{count:4} rectangles: {base:.2} -> {opt:.2} ns/rect ({:.2}x)", - base / opt - ); - } - } - - fn packed_rectangles(count: usize) -> Vec<u8> { - let mut state = 42u32; - let mut next = || { - state ^= state << 13; - state ^= state >> 17; - state ^= state << 5; - state - }; - let mut src = Vec::with_capacity(count * 36); - for _ in 0..3 * count { - for _ in 0..2 { - src.extend_from_slice(&((next() as i32) as f32 / 65_536.0).to_le_bytes()); - } - src.extend_from_slice(&next().to_le_bytes()); - } - src - } - /// `half_to_f32` reads subnormals, so an f16 rectangle output must be /// able to write them back instead of flushing every one to zero. #[test] @@ -674,461 +289,4 @@ mod tests { } } } - - #[test] - fn expand_non_indexed_topologies() { - // QUADS: 2 quads + 1 trailing vertex ignored. - let mut out = vec![0u32; ExpandedTopology::Quads.max_output_indices(9) as usize]; - assert_eq!(out.len(), 12); - let n = ExpandedTopology::Quads.expand_non_indexed_u32(9, 10, &mut out); - assert_eq!(n, 12); - assert_eq!(out, [10, 11, 12, 10, 12, 13, 14, 15, 16, 14, 16, 17]); - - // QUAD_STRIP: 6 vertices -> 2 quads with consistent winding, 7th ignored. - let mut out = vec![0u16; ExpandedTopology::QuadStrip.max_output_indices(7) as usize]; - assert_eq!(out.len(), 12); - let n = ExpandedTopology::QuadStrip.expand_non_indexed_u16(7, 0, &mut out); - assert_eq!(n, 12); - assert_eq!(out, [0, 1, 3, 0, 3, 2, 2, 3, 5, 2, 5, 4]); - - // TRIANGLE_FAN: 5 vertices -> 3 triangles sharing pivot 0. - let mut out = vec![0u32; ExpandedTopology::TriangleFan.max_output_indices(5) as usize]; - assert_eq!(out.len(), 9); - assert_eq!( - ExpandedTopology::TriangleFan.expand_non_indexed_u32(5, 0, &mut out), - 9 - ); - assert_eq!(out, [0, 1, 2, 0, 2, 3, 0, 3, 4]); - assert_eq!(ExpandedTopology::TriangleFan.max_output_indices(2), 0); - - // LINE_LOOP: 4 vertices -> 4 segments closing 3 -> 0. - let mut out = vec![0u16; ExpandedTopology::LineLoop.max_output_indices(4) as usize]; - assert_eq!(out.len(), 8); - assert_eq!( - ExpandedTopology::LineLoop.expand_non_indexed_u16(4, 1, &mut out), - 8 - ); - assert_eq!(out, [1, 2, 2, 3, 3, 4, 4, 1]); - assert_eq!(ExpandedTopology::LineLoop.max_output_indices(1), 0); - } - - #[test] - fn expand_indexed_topologies_with_strip_cuts() { - // TRIANGLE_FAN (16-bit, 0xFFFF cut): two fans separated by cut + incomplete tail. - let src: [u16; 10] = [0, 1, 2, 3, u16::MAX, 10, 11, 12, u16::MAX, 20]; - let mut out = vec![0u16; ExpandedTopology::TriangleFan.max_output_indices(10) as usize]; - let n = ExpandedTopology::TriangleFan.expand_indexed_u16(&src, Some(u16::MAX), 0, &mut out); - assert_eq!(n, 9); - assert_eq!(&out[..9], [0, 1, 2, 0, 2, 3, 10, 11, 12]); - assert!(out[9..].iter().all(|&i| i == 0), "degenerate tail padding"); - - // QUAD_STRIP (32-bit, 0xFFFFFFFF cut): two 4-vertex strips separated by cut. - let src32: [u32; 9] = [0, 1, 2, 3, u32::MAX, 4, 5, 6, 7]; - let mut out32 = vec![0u32; ExpandedTopology::QuadStrip.max_output_indices(9) as usize]; - let n = - ExpandedTopology::QuadStrip.expand_indexed_u32(&src32, Some(u32::MAX), 0, &mut out32); - assert_eq!(n, 12); - assert_eq!(&out32[..12], [0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6]); - assert!(out32[12..].iter().all(|&i| i == 0)); - - // QUADS (16-bit cut discards incomplete 2-vertex quad before cut). - let qsrc: [u16; 7] = [0, 1, u16::MAX, 2, 3, 4, 5]; - let mut qout = vec![0u16; ExpandedTopology::Quads.max_output_indices(7) as usize]; - let n = ExpandedTopology::Quads.expand_indexed_u16(&qsrc, Some(u16::MAX), 0, &mut qout); - assert_eq!(n, 6); - assert_eq!(qout, [2, 3, 4, 2, 4, 5]); - - // LINE_LOOP (16-bit cut closes first loop before starting second). - let lsrc: [u16; 7] = [0, 1, 2, u16::MAX, 5, 6, 7]; - let mut lout = vec![0u16; ExpandedTopology::LineLoop.max_output_indices(7) as usize]; - let n = ExpandedTopology::LineLoop.expand_indexed_u16(&lsrc, Some(u16::MAX), 0, &mut lout); - assert_eq!(n, 12); - assert_eq!(&lout[..12], [0, 1, 1, 2, 2, 0, 5, 6, 6, 7, 7, 5]); - assert_eq!(&lout[12..], [0, 0]); - } - - #[cfg(windows)] - fn render_topology_test( - topology_type: windows::Win32::Graphics::Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE, - host_topology: u32, - strip_cut: windows::Win32::Graphics::Direct3D12::D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, - vertices: &[[f32; 2]], - draw_calls: &[(&[u16], i32)], - ) -> Option<Vec<[u8; 4]>> { - use windows::Win32::Foundation::RECT; - use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; - use windows::Win32::Graphics::Direct3D::{D3D_PRIMITIVE_TOPOLOGY, ID3DBlob}; - use windows::Win32::Graphics::Direct3D12::*; - use windows::Win32::Graphics::Dxgi::Common::*; - use windows::core::s; - - let host = crate::host::host()?; - const HLSL: &str = r#" -float4 vs_main(float2 pos : POSITION) : SV_Position { return float4(pos, 0.0, 1.0); } -float4 ps_main() : SV_Target { return float4(1.0, 1.0, 1.0, 1.0); } -"#; - let compile = |entry: windows::core::PCSTR, target: windows::core::PCSTR| -> Vec<u8> { - let mut blob: Option<ID3DBlob> = None; - // SAFETY: static shader source and entry point strings. - unsafe { - D3DCompile( - HLSL.as_ptr().cast(), - HLSL.len(), - s!("topology_test"), - None, - None, - entry, - target, - 0, - 0, - &mut blob, - None, - ) - .unwrap(); - let blob = blob.unwrap(); - std::slice::from_raw_parts( - blob.GetBufferPointer().cast::<u8>(), - blob.GetBufferSize(), - ) - .to_vec() - } - }; - let vs = compile(s!("vs_main"), s!("vs_5_0")); - let ps = compile(s!("ps_main"), s!("ps_5_0")); - - let rs_desc = D3D12_ROOT_SIGNATURE_DESC { - Flags: D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, - ..Default::default() - }; - let mut rs_blob: Option<ID3DBlob> = None; - // SAFETY: plain root signature, PSO, RT, and readback creation. - let (root, pso, rt, readback, vb, vb_gpu) = unsafe { - D3D12SerializeRootSignature(&rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut rs_blob, None) - .unwrap(); - let rs_blob = rs_blob.unwrap(); - let rs_bytes = std::slice::from_raw_parts( - rs_blob.GetBufferPointer().cast::<u8>(), - rs_blob.GetBufferSize(), - ); - let root: ID3D12RootSignature = host.device.CreateRootSignature(0, rs_bytes).unwrap(); - let elem = D3D12_INPUT_ELEMENT_DESC { - SemanticName: s!("POSITION"), - Format: DXGI_FORMAT_R32G32_FLOAT, - InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, - ..Default::default() - }; - let mut blend = D3D12_BLEND_DESC::default(); - blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; - let mut rast = D3D12_RASTERIZER_DESC { - FillMode: D3D12_FILL_MODE_SOLID, - CullMode: D3D12_CULL_MODE_BACK, - DepthClipEnable: true.into(), - ..Default::default() - }; - if topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE { - rast.CullMode = D3D12_CULL_MODE_NONE; - } - let mut pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - VS: D3D12_SHADER_BYTECODE { - pShaderBytecode: vs.as_ptr().cast(), - BytecodeLength: vs.len(), - }, - PS: D3D12_SHADER_BYTECODE { - pShaderBytecode: ps.as_ptr().cast(), - BytecodeLength: ps.len(), - }, - BlendState: blend, - SampleMask: u32::MAX, - RasterizerState: rast, - InputLayout: D3D12_INPUT_LAYOUT_DESC { - pInputElementDescs: &elem, - NumElements: 1, - }, - IBStripCutValue: strip_cut, - PrimitiveTopologyType: topology_type, - NumRenderTargets: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - ..Default::default() - }; - pso_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - let pso: ID3D12PipelineState = - host.device.CreateGraphicsPipelineState(&pso_desc).unwrap(); - - let rt_desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: 8, - Height: 8, - DepthOrArraySize: 1, - MipLevels: 1, - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, - ..Default::default() - }; - let def_heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; - let mut rt: Option<ID3D12Resource> = None; - host.device - .CreateCommittedResource( - &def_heap, - D3D12_HEAP_FLAG_NONE, - &rt_desc, - D3D12_RESOURCE_STATE_RENDER_TARGET, - None, - &mut rt, - ) - .unwrap(); - let rt = rt.unwrap(); - - let rb_desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: 256 * 8, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - ..Default::default() - }; - let rb_heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_READBACK, - ..Default::default() - }; - let mut readback: Option<ID3D12Resource> = None; - host.device - .CreateCommittedResource( - &rb_heap, - D3D12_HEAP_FLAG_NONE, - &rb_desc, - D3D12_RESOURCE_STATE_COPY_DEST, - None, - &mut readback, - ) - .unwrap(); - let readback = readback.unwrap(); - - let vb_bytes = std::mem::size_of_val(vertices) as u64; - let (vb, vb_ptr) = host.upload_buffer(vb_bytes).unwrap(); - std::ptr::copy_nonoverlapping( - vertices.as_ptr().cast::<u8>(), - vb_ptr, - vb_bytes as usize, - ); - let vb_gpu = vb.GetGPUVirtualAddress(); - (root, pso, rt, readback, vb, vb_gpu) - }; - - let list = host.new_list().unwrap(); - let rtv = host.rtv(Some(&rt), None); - // SAFETY: open command list, live resources, valid scratch index views. - unsafe { - let l = &list.list; - l.ClearRenderTargetView(rtv, &[0.0, 0.0, 0.0, 1.0], None); - l.OMSetRenderTargets(1, Some(&rtv), false, None); - l.RSSetViewports(&[D3D12_VIEWPORT { - Width: 8.0, - Height: 8.0, - MaxDepth: 1.0, - ..Default::default() - }]); - l.RSSetScissorRects(&[RECT { - right: 8, - bottom: 8, - ..Default::default() - }]); - l.SetGraphicsRootSignature(&root); - l.SetPipelineState(&pso); - l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host_topology as i32)); - l.IASetVertexBuffers( - 0, - Some(&[D3D12_VERTEX_BUFFER_VIEW { - BufferLocation: vb_gpu, - SizeInBytes: std::mem::size_of_val(vertices) as u32, - StrideInBytes: 8, - }]), - ); - for &(indices, base) in draw_calls { - let bytes = (indices.len() * 2) as u64; - let (ib_gpu, ib_ptr) = list.scratch(bytes).unwrap(); - std::ptr::copy_nonoverlapping( - indices.as_ptr().cast::<u8>(), - ib_ptr, - bytes as usize, - ); - l.IASetIndexBuffer(Some(&D3D12_INDEX_BUFFER_VIEW { - BufferLocation: ib_gpu, - SizeInBytes: bytes as u32, - Format: DXGI_FORMAT_R16_UINT, - })); - l.DrawIndexedInstanced(indices.len() as u32, 1, 0, base, 0); - } - l.ResourceBarrier(&[crate::host::transition( - &rt, - D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_COPY_SOURCE, - )]); - let to = D3D12_TEXTURE_COPY_LOCATION { - pResource: std::mem::transmute_copy(&readback), - Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { - Offset: 0, - Footprint: D3D12_SUBRESOURCE_FOOTPRINT { - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - Width: 8, - Height: 8, - Depth: 1, - RowPitch: 256, - }, - }, - }, - }; - let from = D3D12_TEXTURE_COPY_LOCATION { - pResource: std::mem::transmute_copy(&rt), - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: 0, - }, - }; - l.CopyTextureRegion(&to, 0, 0, 0, &from, None); - } - list.close(); - host.execute(&[&list]); - drop(vb); - - let mut data = std::ptr::null_mut(); - // SAFETY: `host.execute` waited for the GPU copy into `readback`. - let pixels = unsafe { - readback.Map(0, None, Some(&mut data)).unwrap(); - let mut out = Vec::with_capacity(64); - for y in 0..8usize { - let row = std::slice::from_raw_parts(data.cast::<u8>().add(y * 256), 32); - for x in 0..8usize { - out.push([row[x * 4], row[x * 4 + 1], row[x * 4 + 2], row[x * 4 + 3]]); - } - } - readback.Unmap(0, None); - out - }; - Some(pixels) - } - - #[cfg(windows)] - #[test] - fn quads_and_strip_cut_triangle_fan_render_with_backface_culling() { - use windows::Win32::Graphics::Direct3D12::*; - // Vertices in clockwise NDC order (front-facing under D3D12_CULL_MODE_BACK): - // 0..4: non-indexed QUADS covering left half (x: -1..0, y: -1..1). - // 4..8: indexed TRIANGLE_FAN #1 covering top-right (x: 0.25..1, y: 0.25..1). - // 8..11: indexed TRIANGLE_FAN #2 covering bottom-right (x: 0.25..1, y: -1..-0.25). - let vertices: [[f32; 2]; 11] = [ - [-1.0, 1.0], - [0.0, 1.0], - [0.0, -1.0], - [-1.0, -1.0], - [0.25, 1.0], - [1.0, 1.0], - [1.0, 0.25], - [0.25, 0.25], - [0.25, -0.25], - [1.0, -0.25], - [1.0, -1.0], - ]; - let mut quad_ib = vec![0u16; ExpandedTopology::Quads.max_output_indices(4) as usize]; - ExpandedTopology::Quads.expand_non_indexed_u16(4, 0, &mut quad_ib); - - let fan_src: [u16; 8] = [4, 5, 6, 7, u16::MAX, 8, 9, 10]; - let mut fan_ib = vec![0u16; ExpandedTopology::TriangleFan.max_output_indices(8) as usize]; - ExpandedTopology::TriangleFan.expand_indexed_u16(&fan_src, Some(u16::MAX), 0, &mut fan_ib); - - let Some(px) = render_topology_test( - D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - ExpandedTopology::Quads.host_topology(), - D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF, - &vertices, - &[(&quad_ib, 0), (&fan_ib, 0)], - ) else { - return; - }; - let at = |x: usize, y: usize| px[y * 8 + x][0]; - // Both triangles of the left-half quad must rasterize (not backface-culled). - assert_eq!(at(1, 1), 255, "quad first triangle"); - assert_eq!(at(1, 6), 255, "quad second triangle"); - // Both strip-cut-separated triangle fans on the right half must rasterize. - assert_eq!(at(6, 1), 255, "first triangle fan"); - assert_eq!(at(7, 6), 255, "second triangle fan after strip cut"); - // Middle gap between the two fans must stay black (strip cut did not bridge). - assert_eq!(at(6, 4), 0, "gap between strip-cut fans stays black"); - } - - #[cfg(windows)] - #[test] - fn quad_strip_and_line_loop_render_on_gpu() { - use windows::Win32::Graphics::Direct3D12::*; - // Indexed QUAD_STRIP with 6 vertices (2 quads, CW front-facing under CULL_MODE_BACK) - // covering the entire 8x8 target. - let strip_verts: [[f32; 2]; 6] = [ - [-1.0, -1.0], - [-1.0, 1.0], - [0.0, -1.0], - [0.0, 1.0], - [1.0, -1.0], - [1.0, 1.0], - ]; - let strip_src: [u16; 6] = [0, 1, 2, 3, 4, 5]; - let mut strip_ib = vec![0u16; ExpandedTopology::QuadStrip.max_output_indices(6) as usize]; - ExpandedTopology::QuadStrip.expand_indexed_u16(&strip_src, None, 0, &mut strip_ib); - - let Some(px) = render_topology_test( - D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - ExpandedTopology::QuadStrip.host_topology(), - D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, - &strip_verts, - &[(&strip_ib, 0)], - ) else { - return; - }; - let pat = |x: usize, y: usize| px[y * 8 + x][0]; - assert_eq!(pat(1, 1), 255, "quad strip quad 0"); - assert_eq!(pat(6, 6), 255, "quad strip quad 1"); - - // LINE_LOOP drawing the perimeter of pixel centers (1,1)->(6,1)->(6,6)->(1,6)->(1,1). - let to_ndc = |p: f32| (p + 0.5) / 8.0 * 2.0 - 1.0; - let loop_verts: [[f32; 2]; 4] = [ - [to_ndc(1.0), -to_ndc(1.0)], - [to_ndc(6.0), -to_ndc(1.0)], - [to_ndc(6.0), -to_ndc(6.0)], - [to_ndc(1.0), -to_ndc(6.0)], - ]; - let mut loop_ib = vec![0u16; ExpandedTopology::LineLoop.max_output_indices(4) as usize]; - ExpandedTopology::LineLoop.expand_non_indexed_u16(4, 0, &mut loop_ib); - - let Some(lpx) = render_topology_test( - D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, - ExpandedTopology::LineLoop.host_topology(), - D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, - &loop_verts, - &[(&loop_ib, 0)], - ) else { - return; - }; - let lat = |x: usize, y: usize| lpx[y * 8 + x][0]; - assert_eq!(lat(3, 1), 255, "top edge"); - assert_eq!(lat(6, 3), 255, "right edge"); - assert_eq!(lat(3, 6), 255, "bottom edge"); - assert_eq!(lat(1, 3), 255, "closing edge v3 -> v0"); - assert_eq!(lat(3, 3), 0, "interior stays black"); - } } diff --git a/crates/victory-gpu/src/profile.rs b/crates/victory-gpu/src/profile.rs new file mode 100644 index 0000000000..26792f4861 --- /dev/null +++ b/crates/victory-gpu/src/profile.rs @@ -0,0 +1,2961 @@ +//! Where the layer's threads spend their time: a sampling profiler +//! (`VICTORY_PROFILE=1`, diagnostics builds; off otherwise). +//! +//! The log's own counters say how long the phases of a frame take, not +//! what a thread does inside them: in the graphics driver, in a kernel +//! call, waiting for a lock. A thread of ours ([`run`]) looks, a thousand +//! times a second (`VICTORY_PROFILE_HZ`), at the threads that matter: +//! +//! * the submitting thread and the recording threads, which name +//! themselves by what they call ([`seen`]: [`crate::host::Host`]'s +//! submissions, the list calls); +//! * our workers, by the names we start them with (`victory-pipelines-N`, +//! `victory-wide-N`, `victory-late-wait`) and the title's main thread; +//! * the busiest of the other threads (the title's own). +//! +//! A look ([`Sampler::capture`]) suspends the thread, reads its registers +//! and copies the used part of its stack with the kernel's own read, and +//! lets it go: between the two nothing of ours takes a lock, allocates or +//! reads memory that may be gone. The stack is walked afterwards, in the +//! copy ([`Sampler::walk`]), by each image's unwind data (the Windows +//! loader registered it for title images too), every read checked to stay +//! inside the copy. A thread that has used no processor cycles since the +//! last look is where it was: it is not suspended again. +//! +//! Names are found when the report is written, not when a sample is +//! taken ([`Symbols`]): our executable through its PDB (inlined calls +//! too), system and driver code by export or `module+offset`, title code +//! as `title+offset` of the function's start. +//! +//! The report is written every `VICTORY_PROFILE_EVERY` seconds (30) and at +//! exit to `VICTORY_PROFILE_OUT` (`%TEMP%\victory_profile_<pid>.txt`), the +//! stacks for a flame graph beside it (`.folded`). Per kind of thread: +//! time by module, by function (own and with what it calls), where it +//! waited and for which of our functions, the hottest lines of ours. Times +//! are milliseconds per presented frame ([`frame`]). + +use std::cell::Cell; +use std::collections::HashMap; +use std::ffi::c_void; +use std::fmt::Write as _; +use std::hash::{BuildHasherDefault, Hasher}; +use std::path::PathBuf; +use std::ptr::{null, null_mut}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering::Relaxed}; +use std::time::{Duration, Instant}; + +use windows_sys::Win32::Foundation::{ + CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE, HMODULE, LocalFree, +}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64, GetThreadContext, IMAGEHLP_LINEW64, + IMAGEHLP_MODULEW64, ReadProcessMemory, RtlLookupFunctionEntry, RtlVirtualUnwind, SYMBOL_INFOW, + UNW_FLAG_NHANDLER, +}; +use windows_sys::Win32::System::LibraryLoader::{ + GetModuleFileNameW, GetModuleHandleW, GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, + LoadLibraryExA, +}; +use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; +use windows_sys::Win32::System::ProcessStatus::{ + K32EnumProcessModules, K32GetModuleInformation, MODULEINFO, +}; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, GetCurrentThread, GetCurrentThreadId, GetThreadDescription, GetThreadId, + GetThreadTimes, OpenThread, ResumeThread, SetThreadPriority, SuspendThread, THREAD_GET_CONTEXT, + THREAD_PRIORITY_TIME_CRITICAL, THREAD_QUERY_INFORMATION, THREAD_QUERY_LIMITED_INFORMATION, + THREAD_SUSPEND_RESUME, WaitForSingleObject, +}; + +#[link(name = "kernel32", kind = "raw-dylib")] +unsafe extern "system" { + /// The processor cycles a thread has used so far. + fn QueryThreadCycleTime(thread: HANDLE, cycles: *mut u64) -> i32; +} + +#[link(name = "ntdll", kind = "raw-dylib")] +unsafe extern "system" { + /// The thread of `process` after `thread` (null: the first), opened + /// with `access`; an NTSTATUS, not zero after the last. + fn NtGetNextThread( + process: HANDLE, + thread: HANDLE, + access: u32, + attributes: u32, + flags: u32, + next: *mut HANDLE, + ) -> i32; + /// `(thread, class, out, size, written)`: an NTSTATUS. + fn NtQueryInformationThread( + thread: HANDLE, + class: i32, + information: *mut c_void, + size: u32, + written: *mut u32, + ) -> i32; +} + +// --------------------------------------------------------------------- +// What the layer's threads tell the profiler. +// --------------------------------------------------------------------- + +/// 0: not asked yet, [`OFF`], [`ON`]. +static STATE: AtomicU8 = AtomicU8::new(0); +const OFF: u8 = 1; +const ON: u8 = 2; + +/// Frames presented since the profiler started. +static FRAMES: AtomicU64 = AtomicU64::new(0); + +/// What a thread was seen doing. +#[derive(Clone, Copy)] +pub(crate) enum Seen { + /// It called a submission ([`crate::host::Host`]). + Submit = 0, + /// It made a list call. + Record = 1, +} + +/// A thread that called [`seen`], and how often for each [`Seen`]. A line +/// of the cache each: the recording threads count here at every list call. +#[repr(align(64))] +struct Known { + thread: AtomicU32, + seen: [AtomicU64; 2], +} + +const KNOWN: usize = 64; +static KNOWN_THREADS: [Known; KNOWN] = [const { + Known { + thread: AtomicU32::new(0), + seen: [const { AtomicU64::new(0) }; 2], + } +}; KNOWN]; + +/// Submissions after which a thread is a submitting thread, and list calls +/// after which it is a recording thread: a thread that reads a texture +/// back once while the world loads is neither. +const SUBMITS: u64 = 8; +const LIST_CALLS: u64 = 64; + +thread_local! { + /// This thread's place in [`KNOWN_THREADS`], plus one; 0 before it has + /// one, 255 if there was none left. + static MINE: Cell<u8> = const { Cell::new(0) }; +} + +/// Whether the profiler runs; the first call reads `VICTORY_PROFILE` and +/// starts it. +#[inline] +fn on() -> bool { + match STATE.load(Relaxed) { + ON => true, + OFF => false, + _ => decide(), + } +} + +#[cold] +fn decide() -> bool { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let started = Config::from_env().is_some_and(start); + let state = if started { ON } else { OFF }; + STATE.store(state, Relaxed); + }); + STATE.load(Relaxed) == ON +} + +/// The calling thread was seen doing `what`: it is followed once it has +/// done so often enough. Costs a load when the profiler is off. +#[inline] +pub(crate) fn seen(what: Seen) { + if !on() { + return; + } + let mine = MINE.with(Cell::get); + let known = match mine { + 0 => match claim() { + Some(known) => known, + None => return, + }, + 255 => return, + at => &KNOWN_THREADS[usize::from(at) - 1], + }; + known.seen[what as usize].fetch_add(1, Relaxed); +} + +/// A place in [`KNOWN_THREADS`] for the calling thread. +#[cold] +fn claim() -> Option<&'static Known> { + // SAFETY: a plain query. + let id = unsafe { GetCurrentThreadId() }; + for (at, known) in KNOWN_THREADS.iter().enumerate() { + if known + .thread + .compare_exchange(0, id, Relaxed, Relaxed) + .is_ok() + { + known.seen[0].store(0, Relaxed); + known.seen[1].store(0, Relaxed); + MINE.with(|m| m.set(at as u8 + 1)); + return Some(known); + } + } + MINE.with(|m| m.set(255)); + None +} + +/// A frame was presented. +#[inline] +pub(crate) fn frame() { + if on() { + FRAMES.fetch_add(1, Relaxed); + } +} + +// --------------------------------------------------------------------- +// The switches. +// --------------------------------------------------------------------- + +/// The kinds of thread followed. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Role { + Submit, + Record, + Late, + Wide, + Pipelines, + TitleMain, + Busy, +} + +impl Role { + const ALL: [Role; 7] = [ + Role::Submit, + Role::Record, + Role::Late, + Role::Wide, + Role::Pipelines, + Role::TitleMain, + Role::Busy, + ]; + + /// As `VICTORY_PROFILE_THREADS` and the stacks file name it. + fn name(self) -> &'static str { + match self { + Role::Submit => "submit", + Role::Record => "record", + Role::Late => "late-wait", + Role::Wide => "wide", + Role::Pipelines => "pipelines", + Role::TitleMain => "title-main", + Role::Busy => "busy", + } + } + + fn says(self) -> &'static str { + match self { + Role::Submit => "SUBMITTING (threads that send lists to the card: Host::submit)", + Role::Record => "RECORDING (threads that make list calls and do not submit)", + Role::Late => "LATE WAIT (victory-late-wait: settles submissions sent ahead)", + Role::Wide => "WIDE WORKERS (victory-wide-N: copies and compares of title memory)", + Role::Pipelines => "PIPELINE WORKERS (victory-pipelines-N)", + Role::TitleMain => "TITLE MAIN (title-main)", + Role::Busy => "OTHER BUSY THREADS (the busiest threads with none of the roles above)", + } + } + + /// The role of a thread we named. + fn of_name(name: &str) -> Option<Role> { + if name.starts_with("victory-pipelines-") { + Some(Role::Pipelines) + } else if name.starts_with("victory-wide-") { + Some(Role::Wide) + } else if name == "victory-late-wait" { + Some(Role::Late) + } else if name == "title-main" { + Some(Role::TitleMain) + } else { + None + } + } +} + +/// Frames kept of a stack at most (`VICTORY_PROFILE_DEPTH` asks for fewer). +const MAX_DEPTH: usize = 96; + +#[derive(Clone)] +struct Config { + /// Looks per second. + hz: u32, + /// The report. + out: PathBuf, + /// Seconds between reports. + every: f64, + /// Seconds before the first look, and after how many more the last. + after: f64, + length: Option<f64>, + /// Frames kept of a stack, from the innermost. + depth: usize, + /// Bytes copied of a stack at most. + stack: usize, + /// Threads followed at most, and of those the busy ones with no role. + most: usize, + busy: usize, + /// The roles followed, by `Role as usize`. + roles: [bool; 7], + /// Whether calls the compiler inlined are shown as frames of their own. + inline: bool, + /// Whether a thread that used no cycles since the last look is taken + /// to be where it was. + reuse: bool, + /// The share of a thread's time it may stand still for our looks + /// (0: no limit): a thread whose looks cost more is looked at less + /// often. + budget: f64, + /// Microseconds a tick is put off by at most, a different time each + /// tick ([`Pace::wait`]). + jitter: u64, +} + +fn env_number(name: &str) -> Option<f64> { + std::env::var(name).ok()?.trim().parse().ok() +} + +impl Config { + fn new(hz: u32, out: PathBuf) -> Config { + Config { + hz, + out, + every: 30.0, + after: 0.0, + length: None, + depth: 48, + stack: 128 << 10, + most: 24, + busy: 6, + roles: [true; 7], + inline: true, + reuse: true, + budget: 0.03, + jitter: 250, + } + } + + /// `VICTORY_PROFILE=1` and the switches beside it; `None` without it. + fn from_env() -> Option<Config> { + if !std::env::var_os("VICTORY_PROFILE").is_some_and(|v| v == "1") { + return None; + } + let out = std::env::var_os("VICTORY_PROFILE_OUT").map_or_else( + || std::env::temp_dir().join(format!("victory_profile_{}.txt", std::process::id())), + PathBuf::from, + ); + let hz = env_number("VICTORY_PROFILE_HZ").map_or(1000.0, |v| v.clamp(1.0, 4000.0)); + let mut config = Config::new(hz as u32, out); + let seconds = |name: &str, least: f64| env_number(name).map(|v| v.max(least)); + config.every = seconds("VICTORY_PROFILE_EVERY", 1.0).unwrap_or(config.every); + config.after = seconds("VICTORY_PROFILE_AFTER", 0.0).unwrap_or(0.0); + config.length = seconds("VICTORY_PROFILE_FOR", 1.0); + let count = |name: &str, usual: usize, most: usize| { + env_number(name).map_or(usual, |v| (v.max(0.0) as usize).min(most)) + }; + config.depth = count("VICTORY_PROFILE_DEPTH", config.depth, MAX_DEPTH).max(4); + config.stack = count("VICTORY_PROFILE_STACK_KB", 128, 1024).max(4) << 10; + config.most = count("VICTORY_PROFILE_MAX_THREADS", config.most, 64).max(1); + config.busy = count("VICTORY_PROFILE_BUSY", config.busy, 32); + config.inline = std::env::var_os("VICTORY_PROFILE_INLINE").is_none_or(|v| v != "0"); + config.reuse = std::env::var_os("VICTORY_PROFILE_REUSE").is_none_or(|v| v != "0"); + config.budget = env_number("VICTORY_PROFILE_BUDGET") + .map_or(config.budget, |v| v.clamp(0.0, 100.0) / 100.0); + config.jitter = count("VICTORY_PROFILE_JITTER_US", 250, 2000) as u64; + if let Ok(list) = std::env::var("VICTORY_PROFILE_THREADS") { + let named: Vec<&str> = list.split(',').map(str::trim).collect(); + for role in Role::ALL { + config.roles[role as usize] = named.contains(&role.name()); + } + } + Some(config) + } +} + +// --------------------------------------------------------------------- +// Samples: a tree of calls per thread. +// --------------------------------------------------------------------- + +/// A hash for small keys of ours (addresses and indices), not for +/// anything a stranger chooses. +#[derive(Default, Clone, Copy)] +struct Fast(u64); + +impl Hasher for Fast { + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.write_u64(u64::from(b)); + } + } + fn write_u8(&mut self, v: u8) { + self.write_u64(u64::from(v)); + } + fn write_u32(&mut self, v: u32) { + self.write_u64(u64::from(v)); + } + fn write_u64(&mut self, v: u64) { + self.0 = (self.0.rotate_left(5) ^ v).wrapping_mul(0x517c_c1b7_2722_0a95); + } + fn write_usize(&mut self, v: usize) { + self.write_u64(v as u64); + } + fn finish(&self) -> u64 { + self.0 + } +} + +type FastMap<K, V> = HashMap<K, V, BuildHasherDefault<Fast>>; + +/// A frame as called from its parent's: `address` is the instruction the +/// thread was at (an innermost frame) or a byte inside the call that has +/// not returned (the others), so both lie in the function they belong to. +struct Node { + parent: u32, + address: u64, + /// Of the samples that ended here: microseconds of wall clock they + /// stand for, microseconds of those the thread was on a processor (by + /// its cycle counter), and how many they were. + wall: u64, + cpu: u64, + hits: u32, +} + +/// The address of the node that stands for the frames not kept, between +/// the thread's first frame and the outermost one kept. +const CUT: u64 = 1; +/// The address of the node samples go to once the trees are full. +const FULL: u64 = 2; + +/// The calls of one thread, each sample at the node of its innermost frame. +struct Tree { + nodes: Vec<Node>, + children: FastMap<(u32, u64), u32>, +} + +impl Tree { + fn new() -> Tree { + Tree { + nodes: vec![Node { + parent: 0, + address: 0, + wall: 0, + cpu: 0, + hits: 0, + }], + children: FastMap::default(), + } + } + + fn child(&mut self, parent: u32, address: u64) -> u32 { + *self.children.entry((parent, address)).or_insert_with(|| { + self.nodes.push(Node { + parent, + address, + wall: 0, + cpu: 0, + hits: 0, + }); + self.nodes.len() as u32 - 1 + }) + } + + /// The node of a stack, `frames` from the innermost; `whole` if they + /// reach the thread's first frame. With `room` false no node is made: + /// what is new goes to the [`FULL`] node. + fn place(&mut self, frames: &[u64], whole: bool, room: bool) -> u32 { + let mut at = 0; + if !whole { + at = self.child(0, CUT); + } + for &address in frames.iter().rev() { + at = match self.children.get(&(at, address)) { + Some(&next) => next, + None if room => self.child(at, address), + None => return self.child(0, FULL), + }; + } + at + } +} + +/// The trees' nodes together, at most (56 bytes each with their index). +const MOST_NODES: usize = 1_500_000; + +// --------------------------------------------------------------------- +// Looking at a thread. +// --------------------------------------------------------------------- + +/// `GetThreadContext` and `RtlVirtualUnwind` want the context 16-byte +/// aligned, and windows-sys declares it without that alignment. +#[repr(C, align(16))] +struct Aligned(CONTEXT); + +/// Zeroed bytes kept after the room for a stack's copy: what a frame's +/// unwinding reads past the copied part (a frame cut by the limit, a +/// return address that was none) is read from here. +const SLACK: usize = 2 << 20; +/// Copied of a stack that is not the thread's own (a fiber's) at most. +const FOREIGN: usize = 32 << 10; +/// What a thread needs open for [`Sampler::capture`], and to be asked +/// whether it has ended (`SYNCHRONIZE`). +const ACCESS: u32 = + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | 0x0010_0000; +/// Microseconds of processor time a waiting thread is taken to use at +/// most for being suspended and resumed (the kernel wakes it for both): +/// about 6 were measured. A thread that used no more since a look that +/// suspended it has not left its wait. +const SETTLING_US: f64 = 30.0; +/// The share of a suspension, as we time it (from asking for it to having +/// let go), that the thread really stands still: the rest is the kernel +/// reaching the thread and returning to us. Measured with threads whose +/// work is counted, eight of them always running: about 20 us of work +/// lost a look (1.8 to 2.1 % at 960 looks a second) for 25 to 28 us held. +const STOOD: f64 = 0.8; +/// A suspension counted as no longer than this in a thread's running +/// average (nanoseconds): the long ones are a thread that was not on a +/// processor when we asked, which costs it nothing. +const COST_MOST: f64 = 250_000.0; + +struct Thread { + id: u32, + handle: HANDLE, + name: String, + /// Where it started: what a thread without a name is told by. + start: u64, + role: Role, + /// Its stack's reservation: a stack pointer inside is the thread's own. + low: usize, + high: usize, + /// Its cycle counter at the last look, the node of that look, and + /// whether the thread was suspended for it. + cycles: u64, + last: Option<u32>, + stood: bool, + /// It is looked at every `every` ticks ([`Config::budget`]), next in + /// `turn` ticks; `owed` is the time since its last look + /// (microseconds), `cost` what a suspension of it takes (nanoseconds, + /// a running average). + every: u32, + turn: u32, + owed: u64, + cost: f64, + /// Bytes of its stack copied at a look; 0: all of it. Less once a + /// walk has shown how many the kept frames take. + want: usize, + tree: Tree, + /// Still running, as of the last [`Sampler::rescan`]. + alive: bool, + round: u64, + /// Looks: all, those answered without suspending it, those that + /// failed, and those whose stack did not reach its first frame. + looks: u64, + reused: u64, + missed: u64, + cut: u64, +} + +/// A thread with no role, watched for how busy it is. +struct Other { + handle: HANDLE, + cycles: u64, + name: String, + round: u64, +} + +struct Sampler { + config: Config, + me: u32, + threads: Vec<Thread>, + others: FastMap<u32, Other>, + round: u64, + scanned: Instant, + context: Box<Aligned>, + /// The copy of a stack: `config.stack + 16` bytes, then [`SLACK`]. + copy: *mut u8, + room: usize, + /// How far the copy has bytes that are not zero. + dirty: usize, + frames: [u64; MAX_DEPTH], + /// Cycles of the processor's counter per microsecond. + cycles_per_us: f64, + /// The cycles a waiting thread uses at most to be suspended and let + /// go again ([`SETTLING_US`]). + settling: u64, + clock: Instant, + /// The count of frames presented ([`FRAMES`]; a test's own). + presents: &'static AtomicU64, + /// The last tick, on `clock`, and the frame count then. + last: Duration, + frames_then: u64, + /// Since the start: ticks, late ones, microseconds they stand for, + /// frames presented meanwhile. + ticks: u64, + late: u64, + wall: u64, + presented: u64, + /// Suspensions: how many, their time together and the longest + /// (nanoseconds), and how many by length ([`held_class`]). + held: u64, + held_ns: u64, + held_longest: u64, + held_by: [u64; 256], + nodes: usize, + symbols: Option<Symbols>, +} + +impl Sampler { + fn new(config: Config) -> Sampler { + let room = config.stack + 16 + SLACK; + // SAFETY: fresh zeroed memory of ours, kept for the process's life. + let copy = unsafe { VirtualAlloc(null(), room, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) }; + assert!(!copy.is_null(), "no memory for the profiler's stack copy"); + let clock = Instant::now(); + let cycles_per_us = cycles_per_us(); + // SAFETY: a zeroed CONTEXT is valid. + let context = Box::new(Aligned(unsafe { std::mem::zeroed() })); + Sampler { + config, + // SAFETY: a plain query. + me: unsafe { GetCurrentThreadId() }, + threads: Vec::new(), + others: FastMap::default(), + round: 0, + scanned: clock, + context, + copy: copy.cast(), + room, + dirty: 0, + frames: [0; MAX_DEPTH], + cycles_per_us, + settling: (SETTLING_US * cycles_per_us) as u64, + clock, + presents: &FRAMES, + last: clock.elapsed(), + frames_then: FRAMES.load(Relaxed), + ticks: 0, + late: 0, + wall: 0, + presented: 0, + held: 0, + held_ns: 0, + held_longest: 0, + held_by: [0; 256], + nodes: 0, + symbols: None, + } + } + + /// The time under which `share` of the suspensions stayed, in + /// microseconds (to a quarter of a power of two). + fn held_within(&self, share: f64) -> f64 { + let mut left = (self.held as f64 * share) as u64; + for (class, &count) in self.held_by.iter().enumerate() { + if count > left { + // The class's upper end: its lower end as [`held_class`] + // gives it, plus its width. + let (bits, quarter) = (class / 4, class as u64 % 4); + let under = if bits < 2 { + class as u64 + 1 + } else { + (5 + quarter) << (bits - 2) + }; + return under as f64 / 1000.0; + } + left -= count; + } + self.held_longest as f64 / 1000.0 + } + + /// Time that passed while the sampler did something else (a report) is + /// nobody's: the next tick counts from now. + fn resync(&mut self) { + self.last = self.clock.elapsed(); + self.frames_then = self.presents.load(Relaxed); + } + + /// One look at every followed thread. + fn tick(&mut self) { + let now = self.clock.elapsed(); + let passed = now.saturating_sub(self.last).as_micros() as u64; + self.last = now; + let period = 1_000_000 / u64::from(self.config.hz.max(1)); + // A stall of ours is not the threads' time. + let weight = passed.min(20 * period); + self.late += u64::from(passed > 2 * period); + let frames = self.presents.load(Relaxed); + self.presented += frames.saturating_sub(self.frames_then); + self.frames_then = frames; + self.wall += weight; + self.ticks += 1; + for at in 0..self.threads.len() { + let thread = &mut self.threads[at]; + if !thread.alive { + continue; + } + // A thread looked at every few ticks: its look stands for all + // the time since its last one. + thread.owed += weight; + thread.turn = thread.turn.saturating_sub(1); + if thread.turn == 0 { + thread.turn = thread.every; + let weight = std::mem::take(&mut thread.owed); + self.look(at, weight); + } + } + } + + fn look(&mut self, at: usize, weight: u64) { + let reuse = self.config.reuse; + let thread = &mut self.threads[at]; + thread.looks += 1; + let mut cycles = 0; + // SAFETY: a thread handle of ours and a valid out pointer. + if unsafe { QueryThreadCycleTime(thread.handle, &mut cycles) } == 0 { + thread.missed += 1; + return; + } + let ran = cycles.saturating_sub(thread.cycles); + thread.cycles = cycles; + // It has not run since the last look: it is where it was. A + // thread that was suspended for that look ran to be suspended and + // let go, which is not running its own code. + let still = ran == 0 || thread.stood && ran <= self.settling; + let last = thread.last; + let node = match last { + Some(node) if still && reuse => { + thread.reused += 1; + thread.stood = false; + node + } + _ => { + let Some((got, held)) = self.capture(at) else { + self.threads[at].missed += 1; + self.threads[at].last = None; + return; + }; + let (frames, whole, used) = self.walk(at, got); + let room = self.nodes < MOST_NODES; + let (hz, budget) = (f64::from(self.config.hz), self.config.budget); + let deep = frames >= self.config.depth.min(MAX_DEPTH); + let thread = &mut self.threads[at]; + thread.stood = true; + // The kept frames took `used` bytes: that and a quarter more + // next time. A walk that ran out of copy first: all again. + thread.want = if deep { used + used / 4 + 1024 } else { 0 }; + // What a look costs the thread: about [`STOOD`] of the time we + // hold it (the rest is the kernel reaching it). Over the + // budget, it is looked at less often. + let held = (held as f64).min(COST_MOST); + thread.cost = if thread.cost == 0.0 { + held + } else { + thread.cost + (held - thread.cost) / 16.0 + }; + thread.every = if budget > 0.0 { + (STOOD * thread.cost * hz / 1e9 / budget) + .ceil() + .clamp(1.0, 32.0) as u32 + } else { + 1 + }; + let before = thread.tree.nodes.len(); + let node = thread.tree.place(&self.frames[..frames], whole, room); + self.nodes += thread.tree.nodes.len() - before; + thread.cut += u64::from(!whole); + node + } + }; + let cpu = ((ran as f64 / self.cycles_per_us) as u64).min(weight); + let thread = &mut self.threads[at]; + thread.last = Some(node); + let node = &mut thread.tree.nodes[node as usize]; + node.wall += weight; + node.cpu += cpu; + node.hits += 1; + } + + /// Suspends the thread, reads its registers into `self.context` and + /// copies its stack from the stack pointer up into `self.copy`, and + /// resumes it; the bytes copied, or `None` if it could not be looked + /// at (it ended). + /// + /// While the thread stands still it may hold any lock of the process + /// (the heap's, the loader's, the unwinder's tables'): nothing here + /// between the suspension and the resumption takes one or allocates. + /// The stack is read by the kernel (`ReadProcessMemory`), which fails + /// where a plain read would fault (a thread that is ending). + fn capture(&mut self, at: usize) -> Option<(usize, u64)> { + let thread = &self.threads[at]; + let (handle, low, high) = (thread.handle, thread.low, thread.high); + let context = &mut self.context.0; + context.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; + let limit = match thread.want { + 0 => self.config.stack, + want => want.min(self.config.stack), + }; + let began = Instant::now(); + // SAFETY: a thread of this process that is not this one; the + // context is aligned and ours; the copy has `limit + 16` bytes. + let (read, offset, got) = unsafe { + if SuspendThread(handle) == u32::MAX { + return None; + } + let read = GetThreadContext(handle, context) != 0; + let (mut offset, mut got) = (0, 0); + if read { + let rsp = context.Rsp as usize; + let want = if rsp >= low && rsp < high { + (high - rsp).min(limit) + } else { + limit.min(FOREIGN) + }; + // The copy keeps the stack's alignment: unwinding loads + // saved vector registers with aligned moves. + offset = rsp & 15; + ReadProcessMemory( + GetCurrentProcess(), + rsp as *const c_void, + self.copy.add(offset).cast(), + want, + &mut got, + ); + got = got.min(want); + } + ResumeThread(handle); + (read, offset, got) + }; + let held = began.elapsed().as_nanos() as u64; + self.held += 1; + self.held_ns += held; + self.held_longest = self.held_longest.max(held); + self.held_by[held_class(held).0] += 1; + if !read { + return None; + } + // What an earlier, longer copy left behind it. + let end = offset + got; + if end < self.dirty { + // SAFETY: inside the copy. + unsafe { self.copy.add(end).write_bytes(0, self.dirty - end) }; + } + self.dirty = end; + Some((got, held)) + } + + /// Walks the stack copied by [`Sampler::capture`] (`got` bytes from + /// the stack pointer in `self.context`) into `self.frames`, from the + /// innermost: the count, whether the thread's first frame was + /// reached, and the bytes of the copy the frames took. + /// + /// The thread runs again, so the walk reads the copy: the stack + /// pointer and every saved register that points into the copied part + /// of the stack are moved into the copy before each step (frame + /// pointers are such registers), and a step is taken only if all it + /// can read lies in the copy or the zeroes after it ([`frame_fits`]). + fn walk(&mut self, at: usize, got: usize) -> (usize, bool, usize) { + let (low, high) = (self.threads[at].low, self.threads[at].high); + let depth = self.config.depth.min(MAX_DEPTH); + let context = &mut self.context.0; + let lo = context.Rsp as usize; + let start = self.copy as usize + (lo & 15); + let end = start + got; + let limit = self.copy as usize + self.room; + let top = if lo >= low && lo < high { + high + } else { + lo + got + }; + let mut clipped = false; + self.frames[0] = context.Rip; + let mut frames = 1; + let (mut blind, mut last) = (0, 0); + while frames < depth { + // Into the copy: what points into the stack as it was. + for register in [ + &mut context.Rsp, + &mut context.Rbx, + &mut context.Rbp, + &mut context.Rsi, + &mut context.Rdi, + &mut context.R12, + &mut context.R13, + &mut context.R14, + &mut context.R15, + ] { + let value = *register as usize; + if value >= lo && value < top { + if value - lo < got { + *register = (start + (value - lo)) as u64; + } else { + // Above what was copied: reads there find zeroes. + *register = end as u64; + clipped = true; + } + } + } + let rsp = context.Rsp as usize; + // Out of the copy, or not upwards: the walk ends. + if rsp < start || rsp + 8 > end || rsp <= last { + break; + } + last = rsp; + let mut image = 0; + // SAFETY: looks up the unwind data covering `Rip`, if any. + let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) }; + if entry.is_null() { + // Code without unwind data is a leaf function (the + // system's call stubs are): its return address is at + // `rsp`. Twice in a row it is no stack of calls. + blind += 1; + if blind > 2 { + break; + } + // SAFETY: `rsp..rsp + 8` is inside the copy. + context.Rip = unsafe { (rsp as *const u64).read_unaligned() }; + context.Rsp += 8; + } else { + blind = 0; + // SAFETY: `entry` is `image`'s, as just looked up. + if !unsafe { frame_fits(image, entry.cast(), context, start, end, limit) } { + break; + } + let (mut data, mut frame) = (null_mut(), 0); + // SAFETY: `entry` belongs to `image`; the context is our + // aligned copy, and what the step reads is in our copy of + // the stack (checked above). + unsafe { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + image, + context.Rip, + entry, + context, + &mut data, + &mut frame, + null_mut(), + ) + }; + } + if context.Rip == 0 { + // The first frame's caller: none. (Zeroes read above a + // clipped copy look the same.) + return (frames, !clipped, last + 8 - start); + } + self.frames[frames] = context.Rip - 1; + frames += 1; + } + (frames, false, (last + 8).saturating_sub(start)) + } + + /// Follows the thread `id` as `role`; `handle`, if not null, is open + /// with [`ACCESS`] and becomes ours. + fn follow(&mut self, id: u32, role: Role, handle: HANDLE, name: Option<String>) { + if let Some(thread) = self.threads.iter_mut().find(|t| t.alive && t.id == id) { + // Seen doing more than it was followed for. + if (role as usize) < thread.role as usize { + thread.role = role; + } + thread.round = self.round; + if !handle.is_null() { + // SAFETY: ours, as the caller says. + unsafe { CloseHandle(handle) }; + } + return; + } + let handle = if handle.is_null() { + // SAFETY: opens a thread of this process by its id. + unsafe { OpenThread(ACCESS, 0, id) } + } else { + handle + }; + if handle.is_null() { + return; + } + if self.threads.iter().filter(|t| t.alive).count() >= self.config.most { + // SAFETY: opened above or given to us. + unsafe { CloseHandle(handle) }; + return; + } + let (low, high) = stack_of(handle); + let mut cycles = 0; + // SAFETY: a thread handle of ours and a valid out pointer. + unsafe { QueryThreadCycleTime(handle, &mut cycles) }; + self.threads.push(Thread { + id, + handle, + name: name.unwrap_or_else(|| thread_name(handle)), + start: start_of(handle), + role, + low, + high, + cycles, + last: None, + stood: false, + every: 1, + turn: 1, + owed: 0, + cost: 0.0, + want: 0, + tree: Tree::new(), + alive: true, + round: self.round, + looks: 0, + reused: 0, + missed: 0, + cut: 0, + }); + } + + /// Finds the threads to follow: those the hooks have seen, those with + /// a name of ours, and the busiest of the rest; and notes the ones + /// that ended. + fn rescan(&mut self) { + let passed = self.scanned.elapsed(); + self.scanned = Instant::now(); + self.round += 1; + let wanted = self.config.roles; + for known in &KNOWN_THREADS { + let id = known.thread.load(Relaxed); + if id == 0 || id == self.me { + continue; + } + let role = if known.seen[Seen::Submit as usize].load(Relaxed) >= SUBMITS { + Role::Submit + } else if known.seen[Seen::Record as usize].load(Relaxed) >= LIST_CALLS { + Role::Record + } else { + continue; + }; + if wanted[role as usize] { + self.follow(id, role, null_mut(), None); + } + } + // Every thread of the process: (cycles since the last scan, id) of + // those with no role. + let mut busy: Vec<(u64, u32)> = Vec::new(); + let mut previous: HANDLE = null_mut(); + loop { + let mut next = null_mut(); + // SAFETY: our own process; `previous` is null or a thread + // handle the last pass gave us, closed once passed on. + let status = unsafe { + let status = NtGetNextThread( + GetCurrentProcess(), + previous, + THREAD_QUERY_LIMITED_INFORMATION, + 0, + 0, + &mut next, + ); + if !previous.is_null() { + CloseHandle(previous); + } + status + }; + if status != 0 || next.is_null() { + break; + } + previous = next; + // SAFETY: a thread handle just opened. + let id = unsafe { GetThreadId(next) }; + if id == 0 || id == self.me { + continue; + } + if let Some(thread) = self.threads.iter_mut().find(|t| t.alive && t.id == id) { + thread.round = self.round; + continue; + } + let round = self.round; + let other = match self.others.entry(id) { + std::collections::hash_map::Entry::Occupied(o) => o.into_mut(), + std::collections::hash_map::Entry::Vacant(v) => { + // SAFETY: opens a thread of this process by its id. + let handle = unsafe { OpenThread(ACCESS, 0, id) }; + if handle.is_null() { + continue; + } + let mut cycles = 0; + // SAFETY: a thread handle of ours, a valid out pointer. + unsafe { QueryThreadCycleTime(handle, &mut cycles) }; + v.insert(Other { + handle, + cycles, + name: String::new(), + round, + }) + } + }; + other.round = round; + if other.name.is_empty() { + other.name = thread_name(other.handle); + } + if other.name == "victory-profile" { + continue; + } + // SAFETY: a thread handle of ours, opened with `SYNCHRONIZE`. + if unsafe { WaitForSingleObject(other.handle, 0) } == 0 { + continue; + } + if let Some(role) = Role::of_name(&other.name) { + if wanted[role as usize] + && let Some(other) = self.others.remove(&id) + { + self.follow(id, role, other.handle, Some(other.name)); + } + continue; + } + let mut cycles = 0; + // SAFETY: a thread handle of ours and a valid out pointer. + unsafe { QueryThreadCycleTime(other.handle, &mut cycles) }; + busy.push((cycles.saturating_sub(other.cycles), id)); + other.cycles = cycles; + } + // Threads that ended: no longer looked at; what was sampled stays. + // (A thread we hold a handle to is still listed after its end.) + let round = self.round; + // SAFETY: a thread handle of ours, opened with `SYNCHRONIZE`. + let ended = |handle: HANDLE| unsafe { WaitForSingleObject(handle, 0) } == 0; + for thread in self + .threads + .iter_mut() + .filter(|t| t.alive && (t.round != round || ended(t.handle))) + { + thread.alive = false; + // SAFETY: ours. + unsafe { CloseHandle(thread.handle) }; + thread.handle = null_mut(); + for known in &KNOWN_THREADS { + let _ = known + .thread + .compare_exchange(thread.id, 0, Relaxed, Relaxed); + } + } + self.others.retain(|_, other| { + let gone = other.round != round || ended(other.handle); + if gone { + // SAFETY: ours. + unsafe { CloseHandle(other.handle) }; + } + !gone + }); + // The busiest of the rest: a quarter of a processor or more. + if wanted[Role::Busy as usize] { + let least = (0.25 * passed.as_micros() as f64 * self.cycles_per_us) as u64; + busy.sort_unstable_by(|a, b| b.cmp(a)); + for (ran, id) in busy { + let followed = self + .threads + .iter() + .filter(|t| t.alive && t.role == Role::Busy) + .count(); + if ran < least.max(1) || followed >= self.config.busy { + break; + } + if let Some(other) = self.others.remove(&id) { + self.follow(id, Role::Busy, other.handle, Some(other.name)); + } + } + } + } +} + +/// Whether unwinding one frame of the function `entry` of the image at +/// `image` from `context` reads only our copy of a stack (`start..end`) +/// and the zeroes after it (to `limit`): the stack pointer, and the frame +/// pointer if the function has set one up, must lie in the copy, and what +/// the function's unwind codes take off the stack must fit in the zeroes. +/// +/// `RtlVirtualUnwind` trusts the registers it is given. Ours come from a +/// thread stopped anywhere, and a return address may be none (code +/// without unwind data in the middle of a stack): a frame pointer that +/// points nowhere would be read through. +/// +/// # Safety +/// `entry` is the function table entry of `image` for `context.Rip`. +unsafe fn frame_fits( + image: u64, + entry: *const [u32; 3], + context: &CONTEXT, + start: usize, + end: usize, + limit: usize, +) -> bool { + // SAFETY: the caller's entry, and the unwind data it names in its + // loaded image: a header of four bytes, `count` two-byte codes, and + // after them (made even) the entry of the function this one is a + // part of, if the header says so. + unsafe { + let [begin, finish, mut data] = entry.read_unaligned(); + let at = context + .Rip + .wrapping_sub(image) + .wrapping_sub(u64::from(begin)); + // The frame register the function itself names (its first part). + let mut pointer = 0; + // Bytes above the frame's base that unwinding may read: the + // return address, a machine frame's tail. + let mut reach = 64usize; + // Bases other than the stack pointer: frame pointers set up. + let mut bases = [0usize; 4]; + let mut based = 0; + for part in 0..8 { + if data & 1 != 0 { + return false; + } + let info = (image + u64::from(data)) as *const u8; + let [version, _prolog, count, frame] = info.cast::<[u8; 4]>().read(); + if !matches!(version & 7, 1 | 2) { + return false; + } + let chained = version >> 3 & 4 != 0; + if part == 0 { + pointer = frame & 15; + } + let codes = info.add(4); + let count = usize::from(count); + let slot = |i: usize| codes.add(2 * i).cast::<u16>().read_unaligned(); + let mut i = 0; + let (mut found, mut set) = (false, false); + while i < count { + let [offset, op] = codes.add(2 * i).cast::<[u8; 2]>().read(); + let (op, op_info) = (op & 15, usize::from(op >> 4)); + i += match op { + // A register pushed. + 0 => { + reach += 8; + 1 + } + // A large allocation: its size in the next one or two slots. + 1 if op_info == 0 => { + reach += usize::from(slot(i + 1)) * 8; + 2 + } + 1 => { + reach += usize::from(slot(i + 1)) | usize::from(slot(i + 2)) << 16; + 3 + } + // A small allocation. + 2 => { + reach += op_info * 8 + 8; + 1 + } + // The frame pointer set: done already if the thread is + // past that instruction, or in a later part of the function. + 3 => { + found = true; + set = part > 0 || chained || at >= u64::from(offset); + 1 + } + // Registers saved in the frame (near, far), an epilogue + // note and a spare code, vector registers saved. + 4 | 8 => 2, + 5 | 9 => 3, + 6 => 1, + 7 => 2, + // A machine frame. + 10 => { + reach += 48; + 1 + } + _ => return false, + }; + } + if frame & 15 != 0 && (set || !found || part > 0 || chained) { + let register = gpr(context, frame & 15) as usize; + let back = usize::from(frame >> 4) * 16; + if register < start + back || register > end || based == bases.len() { + return false; + } + bases[based] = register - back; + based += 1; + } + if !chained { + let rsp = context.Rsp as usize; + let code = image + u64::from(finish) - context.Rip; + return rsp >= start + && rsp < end + && reach <= SLACK + && rsp + reach <= limit + && bases[..based].iter().all(|base| base + reach <= limit) + && epilogue_fits(context, code as usize, pointer, start, end); + } + let parent = codes + .add(2 * ((count + 1) & !1)) + .cast::<[u32; 3]>() + .read_unaligned(); + data = parent[2]; + } + false + } +} + +/// Whether the instructions at `context.Rip` (`code` bytes of them are the +/// function's), if the unwinder takes them for the end of a function, +/// leave the stack pointer inside our copy of a stack (`start..end`). +/// `pointer` is the function's frame register (0: none). +/// +/// Where a thread stands at a function's last instructions, the +/// unwinder does not use the unwind codes: it runs those instructions +/// itself, an `add rsp, n` or a `lea rsp, [frame register + n]`, then the +/// `pop`s, then the return. An address that is no instruction's start can +/// read as a `pop rsp`, or as an `add` of any number: this reads the +/// bytes as the unwinder does and refuses what would take the stack +/// pointer out of the copy. It takes a little more for a function's end +/// than the unwinder does (any jump after the `pop`s, wherever it goes). +/// +/// # Safety +/// `code` bytes at `context.Rip` are readable. +unsafe fn epilogue_fits( + context: &CONTEXT, + code: usize, + pointer: u8, + start: usize, + end: usize, +) -> bool { + let rip = context.Rip as *const u8; + // Past the function's end reads as a breakpoint: nothing of an epilogue. + let byte = |i: usize| { + if i < code { + // SAFETY: inside the `code` bytes the caller says are readable. + unsafe { rip.add(i).read() } + } else { + 0xcc + } + }; + let number = |i: usize| i32::from_le_bytes([byte(i), byte(i + 1), byte(i + 2), byte(i + 3)]); + let moved = |from: u64, by: i32| (from as usize).wrapping_add(by as isize as usize); + let mut rsp = context.Rsp as usize; + let mut at = 0; + if byte(0) == 0x48 && byte(1) == 0x83 && byte(2) == 0xc4 { + // add rsp, n (a byte). + rsp = moved(context.Rsp, i32::from(byte(3) as i8)); + at = 4; + } else if byte(0) == 0x48 && byte(1) == 0x81 && byte(2) == 0xc4 { + // add rsp, n. + rsp = moved(context.Rsp, number(3)); + at = 7; + } else if byte(0) & 0xfe == 0x48 && byte(1) == 0x8d { + // lea rsp, [register + n]: taken only from the frame register. + let register = (byte(0) & 1) << 3 | byte(2) & 7; + let (near, far) = (byte(2) & 0xf8 == 0x60, byte(2) & 0xf8 == 0xa0); + if register != 0 && register == pointer && (near || far) { + let by = if near { + i32::from(byte(3) as i8) + } else { + number(3) + }; + rsp = moved(gpr(context, register), by); + at = if near { 4 } else { 7 }; + } + } + // The `pop`s. + let (mut pops, mut pops_rsp) = (0, false); + loop { + let (op, rex) = (byte(at), byte(at) & 0xf0 == 0x40); + let register = if rex { byte(at + 1) } else { op }; + if register & 0xf8 != 0x58 || pops == 64 { + break; + } + pops_rsp |= register & 7 == 4 && !(rex && op & 1 != 0); + at += if rex { 2 } else { 1 }; + pops += 1; + } + // A return or a jump: only then are the instructions before it run. + let leaves = matches!(byte(at), 0xc3 | 0xc2 | 0xeb | 0xe9) + || byte(at) == 0xf3 && byte(at + 1) == 0xc3 + || byte(at) == 0xff && byte(at + 1) == 0x25 + || byte(at) & 0xf0 == 0x40 && byte(at + 1) == 0xff && byte(at + 2) & 0x38 == 0x20; + !leaves || (!pops_rsp && pops < 64 && rsp >= start && rsp + 8 * (pops + 1) <= end) +} + +/// The class of a time in nanoseconds: four to a power of two (the +/// index), and the class's lower end. +fn held_class(ns: u64) -> (usize, u64) { + if ns < 4 { + return (ns as usize, ns); + } + let bits = 63 - ns.leading_zeros() as usize; + let quarter = ns >> (bits - 2) & 3; + (bits * 4 + quarter as usize, (4 + quarter) << (bits - 2)) +} + +/// The general register numbered `n` as unwind data numbers them. +fn gpr(context: &CONTEXT, n: u8) -> u64 { + match n & 15 { + 0 => context.Rax, + 1 => context.Rcx, + 2 => context.Rdx, + 3 => context.Rbx, + 4 => context.Rsp, + 5 => context.Rbp, + 6 => context.Rsi, + 7 => context.Rdi, + 8 => context.R8, + 9 => context.R9, + 10 => context.R10, + 11 => context.R11, + 12 => context.R12, + 13 => context.R13, + 14 => context.R14, + _ => context.R15, + } +} + +/// The processor counter's cycles per microsecond, measured. +fn cycles_per_us() -> f64 { + let began = Instant::now(); + // SAFETY: reads the processor's time stamp counter. + let from = unsafe { std::arch::x86_64::_rdtsc() }; + std::thread::sleep(Duration::from_millis(20)); + // SAFETY: as above. + let cycles = unsafe { std::arch::x86_64::_rdtsc() }.wrapping_sub(from); + (cycles as f64 / began.elapsed().as_micros().max(1) as f64).max(1.0) +} + +/// The reservation of a thread's stack, lowest address and end; (0, 0) if +/// it cannot be asked (the thread ended). +fn stack_of(thread: HANDLE) -> (usize, usize) { + /// `THREAD_BASIC_INFORMATION` (ntddk). + #[repr(C)] + struct Basic { + exit_status: i32, + teb: usize, + client_id: [usize; 2], + affinity: usize, + priority: i32, + base_priority: i32, + } + let mut basic = Basic { + exit_status: 0, + teb: 0, + client_id: [0; 2], + affinity: 0, + priority: 0, + base_priority: 0, + }; + // SAFETY: writes `basic`, whose layout and size are the system's. + let status = unsafe { + NtQueryInformationThread( + thread, + 0, + (&raw mut basic).cast(), + size_of::<Basic>() as u32, + null_mut(), + ) + }; + if status != 0 || basic.teb == 0 { + return (0, 0); + } + // The thread's block: the stack's end at +8, the start of its + // reservation at +0x1478. Read by the kernel: the thread may end. + let word = |at: usize| { + let (mut value, mut got) = (0usize, 0); + // SAFETY: reads eight bytes into `value`; fails if they are gone. + let read = unsafe { + ReadProcessMemory( + GetCurrentProcess(), + at as *const c_void, + (&raw mut value).cast(), + 8, + &mut got, + ) + }; + if read != 0 && got == 8 { value } else { 0 } + }; + let (high, low) = (word(basic.teb + 8), word(basic.teb + 0x1478)); + if low != 0 && low < high { + (low, high) + } else { + (0, 0) + } +} + +/// The address a thread started at; 0 if it cannot be asked. +fn start_of(thread: HANDLE) -> u64 { + let mut start = 0u64; + // SAFETY: writes one pointer-sized start address + // (`ThreadQuerySetWin32StartAddress` is 9). + unsafe { + NtQueryInformationThread(thread, 9, (&raw mut start).cast(), 8, null_mut()); + } + start +} + +fn thread_name(thread: HANDLE) -> String { + let mut text: *mut u16 = null_mut(); + // SAFETY: the system allocates the string; we free it with LocalFree. + unsafe { + if GetThreadDescription(thread, &mut text) < 0 || text.is_null() { + return String::new(); + } + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + let name = String::from_utf16_lossy(std::slice::from_raw_parts(text, len)); + LocalFree(text.cast()); + name + } +} + +// --------------------------------------------------------------------- +// Names, found when a report is written. +// --------------------------------------------------------------------- + +/// Whose code a frame is. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +enum Kind { + Ours = 0, + Driver = 1, + Direct3d = 2, + System = 3, + Title = 4, + Other = 5, +} + +const KINDS: [&str; 6] = [ + "ours", + "graphics driver", + "d3d12 / dxgi", + "ntdll + kernel", + "title", + "other", +]; + +/// The kind of a module by its file name (lower case). +fn kind_of(file: &str, ours: bool) -> Kind { + let starts = |list: &[&str]| list.iter().any(|p| file.starts_with(p)); + if ours { + Kind::Ours + } else if file.starts_with("victory-image-") { + Kind::Title + } else if starts(&["nv", "amd", "ati", "igd", "igc", "ig1", "ig9", "ig7", "ig8"]) { + Kind::Driver + } else if starts(&["d3d", "dxgi", "dxcore", "dxil", "dcomp", "dwmapi"]) { + Kind::Direct3d + } else if matches!( + file, + "ntdll.dll" | "kernelbase.dll" | "kernel32.dll" | "win32u.dll" + ) { + Kind::System + } else { + Kind::Other + } +} + +struct Module { + base: u64, + end: u64, + /// What its frames are named by: `title`, or its file name. + label: String, + kind: Kind, +} + +/// A function as the report names it. +struct Func { + name: String, + /// Of ours, but the language's runtime (`std::`, `core::`, `alloc::`). + runtime: bool, + /// A call that waits ([`waits`]). + wait: bool, +} + +/// What an address is. +struct Resolved { + /// The functions it is in, outermost first: more than one where the + /// compiler inlined calls (ours only). + funcs: Box<[u32]>, + kind: Option<Kind>, + /// Its source line (ours), an index into `Symbols::lines`. + line: Option<u32>, +} + +type SymFromAddr = unsafe extern "system" fn(HANDLE, u64, *mut u64, *mut SYMBOL_INFOW) -> i32; +type SymFromInline = + unsafe extern "system" fn(HANDLE, u64, u32, *mut u64, *mut SYMBOL_INFOW) -> i32; +type SymInlineQuery = + unsafe extern "system" fn(HANDLE, u64, u32, u64, u64, *mut u32, *mut u32) -> i32; +type SymLine = unsafe extern "system" fn(HANDLE, u64, *mut u32, *mut IMAGEHLP_LINEW64) -> i32; +type SymLineInline = + unsafe extern "system" fn(HANDLE, u64, u32, u64, *mut u32, *mut IMAGEHLP_LINEW64) -> i32; + +/// The system's symbol library (`dbghelp.dll`), loaded when the first +/// report is written: a build that does not profile does not load it. +struct DbgHelp { + process: HANDLE, + refresh: unsafe extern "system" fn(HANDLE) -> i32, + from_addr: SymFromAddr, + line: Option<SymLine>, + module: Option<unsafe extern "system" fn(HANDLE, u64, *mut IMAGEHLP_MODULEW64) -> i32>, + /// Inlined calls: how many at an address, their first context, a name + /// and a line by context. + inline: Option<( + unsafe extern "system" fn(HANDLE, u64) -> u32, + SymInlineQuery, + SymFromInline, + Option<SymLineInline>, + )>, +} + +/// A symbol with room for its name. +#[repr(C)] +struct Symbol { + info: SYMBOL_INFOW, + name: [u16; 1024], +} + +impl DbgHelp { + fn open() -> Option<DbgHelp> { + // SAFETY: loads the system's own dbghelp.dll and looks its + // functions up by name; each is called with the signature the + // system documents for it. The library's "process" is a second + // handle to ours, so its tables are not the ones Rust's own + // backtraces set up for the plain handle. + unsafe { + let library = LoadLibraryExA( + c"dbghelp.dll".as_ptr().cast(), + null_mut(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + ); + if library.is_null() { + return None; + } + macro_rules! find { + ($name:literal) => { + GetProcAddress(library, $name.as_ptr().cast()).map(|f| std::mem::transmute(f)) + }; + } + let get_options: unsafe extern "system" fn() -> u32 = find!(c"SymGetOptions")?; + let set_options: unsafe extern "system" fn(u32) -> u32 = find!(c"SymSetOptions")?; + let initialize: unsafe extern "system" fn(HANDLE, *const u16, i32) -> i32 = + find!(c"SymInitializeW")?; + let refresh = find!(c"SymRefreshModuleList")?; + let from_addr = find!(c"SymFromAddrW")?; + let inline = match ( + find!(c"SymAddrIncludeInlineTrace"), + find!(c"SymQueryInlineTrace"), + find!(c"SymFromInlineContextW"), + ) { + (Some(count), Some(query), Some(name)) => { + Some((count, query, name, find!(c"SymGetLineFromInlineContextW"))) + } + _ => None, + }; + let mut process = null_mut(); + let me = GetCurrentProcess(); + if DuplicateHandle(me, me, me, &mut process, 0, 0, DUPLICATE_SAME_ACCESS) == 0 { + return None; + } + // Names undecorated, lines loaded, a module's symbols read + // when first asked for, no dialogs. Symbols are looked for + // where the image says and beside our executable only: no + // symbol server is asked (`_NT_SYMBOL_PATH` is not used when + // a path is given). + const UNDNAME: u32 = 0x2; + const DEFERRED_LOADS: u32 = 0x4; + const LOAD_LINES: u32 = 0x10; + const FAIL_CRITICAL_ERRORS: u32 = 0x200; + const NO_PROMPTS: u32 = 0x80000; + set_options( + get_options() + | UNDNAME + | DEFERRED_LOADS + | LOAD_LINES + | FAIL_CRITICAL_ERRORS + | NO_PROMPTS, + ); + let folder = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|p| p.to_path_buf())) + .unwrap_or_default(); + let path: Vec<u16> = folder + .to_string_lossy() + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + if initialize(process, path.as_ptr(), 1) == 0 { + CloseHandle(process); + return None; + } + Some(DbgHelp { + process, + refresh, + from_addr, + line: find!(c"SymGetLineFromAddrW64"), + module: find!(c"SymGetModuleInfoW64"), + inline, + }) + } + } + + /// A symbol's name and address from a lookup that fills `symbol`. + fn named(lookup: impl FnOnce(*mut SYMBOL_INFOW) -> i32) -> Option<(String, u64)> { + // SAFETY: a zeroed symbol is valid; its header says how much room + // follows for the name, and the name read is inside that room. + unsafe { + let mut symbol: Box<Symbol> = Box::new(std::mem::zeroed()); + symbol.info.SizeOfStruct = size_of::<SYMBOL_INFOW>() as u32; + symbol.info.MaxNameLen = symbol.name.len() as u32; + // The whole of it: the name runs on past the header. + let whole = (&raw mut *symbol).cast::<SYMBOL_INFOW>(); + if lookup(whole) == 0 { + return None; + } + let len = ((*whole).NameLen as usize).min(symbol.name.len()); + let name = whole + .cast::<u8>() + .add(std::mem::offset_of!(SYMBOL_INFOW, Name)) + .cast::<u16>(); + let text = std::slice::from_raw_parts(name, len); + let end = text.iter().position(|&c| c == 0).unwrap_or(len); + Some((String::from_utf16_lossy(&text[..end]), (*whole).Address)) + } + } + + /// The symbol at or before `address`: its name and its own address. + fn symbol(&self, address: u64) -> Option<(String, u64)> { + let mut displacement = 0; + // SAFETY: the library's own call with a symbol of ours to fill. + Self::named(|symbol| unsafe { + (self.from_addr)(self.process, address, &mut displacement, symbol) + }) + } + + /// The functions `address` is in, outermost first (the calls the + /// compiler inlined there, if `inlined`), and the context of the + /// innermost for [`DbgHelp::line`]. + fn functions(&self, address: u64, inlined: bool) -> (Vec<String>, Option<u32>) { + if inlined && let Some((count, query, name, _)) = self.inline { + // SAFETY: the library's own calls, as documented: the count + // of inlined calls at an address, the context of the first, + // then a name per context; the last context is the function + // itself. + unsafe { + let inlines = count(self.process, address); + let (mut first, mut index) = (0, 0); + if inlines > 0 + && query( + self.process, + address, + 0, + address, + address, + &mut first, + &mut index, + ) != 0 + { + let mut names: Vec<String> = (first..=first + inlines) + .filter_map(|context| { + let mut displacement = 0; + Self::named(|symbol| { + name(self.process, address, context, &mut displacement, symbol) + }) + }) + .map(|(name, _)| name) + .collect(); + if !names.is_empty() { + names.reverse(); + return (names, Some(first)); + } + } + } + } + ( + self.symbol(address) + .into_iter() + .map(|(name, _)| name) + .collect(), + None, + ) + } + + /// The source file and line of `address` (of the inlined call with + /// `context`, if any). + fn line(&self, address: u64, context: Option<u32>) -> Option<(String, u32)> { + // SAFETY: the library's own calls with a line of ours to fill; + // the file name it points to is a string of its own. + unsafe { + let mut line: IMAGEHLP_LINEW64 = std::mem::zeroed(); + line.SizeOfStruct = size_of::<IMAGEHLP_LINEW64>() as u32; + let mut displacement = 0; + let found = match (context, self.inline.and_then(|i| i.3)) { + (Some(context), Some(by_context)) => { + by_context( + self.process, + address, + context, + 0, + &mut displacement, + &mut line, + ) != 0 + } + _ => false, + } || self.line.is_some_and(|by_address| { + by_address(self.process, address, &mut displacement, &mut line) != 0 + }); + if !found || line.FileName.is_null() { + return None; + } + let len = (0..1024) + .take_while(|&i| *line.FileName.add(i) != 0) + .count(); + let file = String::from_utf16_lossy(std::slice::from_raw_parts(line.FileName, len)); + Some((file, line.LineNumber)) + } + } + + /// Whether the module at `base` has its symbols from a PDB, and what + /// the library says it loaded. + fn has_pdb(&self, base: u64) -> (bool, String) { + let Some(module) = self.module else { + return (false, String::new()); + }; + // SAFETY: the library's own call with a sized structure to fill. + unsafe { + let mut info: Box<IMAGEHLP_MODULEW64> = Box::new(std::mem::zeroed()); + info.SizeOfStruct = size_of::<IMAGEHLP_MODULEW64>() as u32; + if module(self.process, base, &mut *info) == 0 { + return (false, String::new()); + } + let text = |chars: &[u16]| { + let end = chars.iter().position(|&c| c == 0).unwrap_or(chars.len()); + String::from_utf16_lossy(&chars[..end]) + }; + // SymPdb is 3 and SymDia 7. + (matches!(info.SymType, 3 | 7), text(&info.LoadedPdbName)) + } + } +} + +/// The start of the function `address` is in, by its image's unwind data +/// (the first part's, for a function in several); `None` for code that +/// has none. +fn function_start(address: u64) -> Option<u64> { + let mut image = 0; + // SAFETY: looks up the unwind data covering `address`, if any, and + // reads it in its loaded image: a part of a function names the entry + // of the function it belongs to after its codes. + unsafe { + let entry = RtlLookupFunctionEntry(address, &mut image, null_mut()); + if entry.is_null() { + return None; + } + let mut entry = entry.cast::<[u32; 3]>().read_unaligned(); + for _ in 0..8 { + if entry[2] & 1 != 0 { + break; + } + let info = (image + u64::from(entry[2])) as *const u8; + let [version, _, count, _] = info.cast::<[u8; 4]>().read(); + if version >> 3 & 4 == 0 { + break; + } + let after = info.add(4 + 2 * ((usize::from(count) + 1) & !1)); + entry = after.cast::<[u32; 3]>().read_unaligned(); + } + Some(image + u64::from(entry[0])) + } +} + +/// Whether a thread whose innermost frame is `name` waits there: the +/// kernel's waits, by their names in ntdll and win32u (`Nt` or `Zw`). +fn waits(name: &str) -> bool { + let function = name.rsplit('!').next().unwrap_or(name); + let Some(call) = function + .strip_prefix("Nt") + .or_else(|| function.strip_prefix("Zw")) + else { + return false; + }; + [ + "WaitFor", + "DelayExecution", + "RemoveIoCompletion", + "SignalAndWait", + "UserMsgWaitForMultipleObjects", + "UserGetMessage", + "UserWaitMessage", + "GdiDdDDIWaitFor", + ] + .iter() + .any(|wait| call.starts_with(wait)) +} + +/// What kind of wait the frames between a waiting call and the function +/// of ours that waited make it. +fn wait_kind(path: &[&str]) -> &'static str { + let has = |what: &str| path.iter().any(|name| name.contains(what)); + if has("SleepConditionVariable") || has("Condvar") { + "condition variable" + } else if has("SRWLock") { + "lock (SRW)" + } else if has("CriticalSection") { + "lock (critical section)" + } else if has("Mutex") || has("RwLock") || has("Once") { + "lock (ours)" + } else if has("park") { + "parked" + } else if has("Sleep") || has("sleep") || has("DelayExecution") { + "sleep" + } else if has("GdiDdDDIWaitFor") { + "graphics kernel" + } else if has("WaitOnAddress") || has("WaitForAlertByThreadId") { + "wait on address" + } else if has("IoCompletion") || has("GetQueuedCompletionStatus") { + "I/O completion" + } else if has("MsgWait") || has("GetMessage") || has("WaitMessage") { + "window messages" + } else if has("WaitForMultipleObjects") || has("WaitForSingleObject") { + "event or handle" + } else { + "other wait" + } +} + +struct Symbols { + dbghelp: Option<DbgHelp>, + inline: bool, + /// Loaded modules by base, as of the report being written. + modules: Vec<Module>, + /// Whether our executable's names come from its PDB, and which. + pdb: (bool, String), + funcs: Vec<Func>, + by_name: HashMap<String, u32>, + lines: Vec<String>, + by_line: HashMap<String, u32>, + resolved: Vec<Resolved>, + by_address: FastMap<u64, u32>, +} + +impl Symbols { + fn new(inline: bool) -> Symbols { + Symbols { + dbghelp: DbgHelp::open(), + inline, + modules: Vec::new(), + pdb: (false, String::new()), + funcs: Vec::new(), + by_name: HashMap::new(), + lines: Vec::new(), + by_line: HashMap::new(), + resolved: Vec::new(), + by_address: FastMap::default(), + } + } + + /// Lists the loaded modules anew (a report's first step). + fn refresh(&mut self) { + // SAFETY: plain queries of our own process with sized buffers. + unsafe { + if let Some(dbghelp) = &self.dbghelp { + (dbghelp.refresh)(dbghelp.process); + } + let me = GetCurrentProcess(); + let mut handles: Vec<HMODULE> = vec![null_mut(); 2048]; + let mut bytes = 0; + let size = (handles.len() * size_of::<HMODULE>()) as u32; + if K32EnumProcessModules(me, handles.as_mut_ptr(), size, &mut bytes) == 0 { + return; + } + handles.truncate(bytes as usize / size_of::<HMODULE>()); + let exe = GetModuleHandleW(null()); + let mut modules = Vec::with_capacity(handles.len()); + for handle in handles { + let mut info = MODULEINFO { + lpBaseOfDll: null_mut(), + SizeOfImage: 0, + EntryPoint: null_mut(), + }; + if K32GetModuleInformation(me, handle, &mut info, size_of::<MODULEINFO>() as u32) + == 0 + { + continue; + } + let mut path = [0u16; 520]; + let len = GetModuleFileNameW(handle, path.as_mut_ptr(), path.len() as u32); + let path = String::from_utf16_lossy(&path[..len as usize]); + let file = path.rsplit(['\\', '/']).next().unwrap_or(&path).to_owned(); + let kind = kind_of(&file.to_ascii_lowercase(), handle == exe); + let base = handle as u64; + modules.push(Module { + base, + end: base + u64::from(info.SizeOfImage), + label: file, + kind, + }); + } + modules.sort_by_key(|m| m.base); + // The title's images are named by their content: the largest + // is the title itself, the others its libraries. + let largest = modules + .iter() + .filter(|m| m.kind == Kind::Title) + .map(|m| m.end - m.base) + .max(); + for module in modules.iter_mut().filter(|m| m.kind == Kind::Title) { + module.label = if Some(module.end - module.base) == largest { + "title".to_owned() + } else { + let hash = module.label.trim_start_matches("victory-image-"); + format!("title-{}", &hash[..hash.len().min(6)]) + }; + } + self.modules = modules; + if let Some(dbghelp) = &self.dbghelp + && !self.pdb.0 + { + // The executable's symbols are read when first asked for. + dbghelp.symbol(function_start as *const () as u64); + self.pdb = dbghelp.has_pdb(exe as u64); + } + } + } + + fn func(&mut self, name: String, kind: Option<Kind>) -> u32 { + if let Some(&at) = self.by_name.get(&name) { + return at; + } + // (By the name before its type arguments: a closure of ours is one.) + let own_name = name.split('<').next().unwrap_or(&name); + let runtime = kind == Some(Kind::Ours) + && [ + "std::", "core::", "alloc::", "__rust", "__chkstk", "mem", "str", + ] + .iter() + .any(|p| own_name.starts_with(p)); + self.funcs.push(Func { + wait: waits(&name), + name: name.clone(), + runtime, + }); + self.by_name.insert(name, self.funcs.len() as u32 - 1); + self.funcs.len() as u32 - 1 + } + + /// What `address` is, as an index into `self.resolved`. + fn resolve(&mut self, address: u64) -> u32 { + if let Some(&at) = self.by_address.get(&address) { + return at; + } + let resolved = self.look_up(address); + self.resolved.push(resolved); + let at = self.resolved.len() as u32 - 1; + self.by_address.insert(address, at); + at + } + + fn look_up(&mut self, address: u64) -> Resolved { + let marker = match address { + CUT => Some("[frames not kept]"), + FULL => Some("[samples after the trees were full]"), + _ => None, + }; + if let Some(name) = marker { + let func = self.func(name.to_owned(), None); + return Resolved { + funcs: Box::new([func]), + kind: None, + line: None, + }; + } + let at = self.modules.partition_point(|m| m.base <= address); + let module = at + .checked_sub(1) + .map(|at| &self.modules[at]) + .filter(|m| address < m.end); + let Some(module) = module else { + let func = self.func("[code in no loaded module]".to_owned(), Some(Kind::Other)); + return Resolved { + funcs: Box::new([func]), + kind: Some(Kind::Other), + line: None, + }; + }; + let (base, kind, label) = (module.base, module.kind, module.label.clone()); + let start = function_start(address); + // By the function's start in its module: what code with no names + // (the title, the driver) is told apart by. + let plain = || match start { + Some(start) => format!("{label}+{:#x}", start - base), + None => format!("{label}+{:#x}", (address - base) & !15), + }; + let mut line = None; + let names = match (&self.dbghelp, kind) { + (_, Kind::Title) | (None, _) => vec![plain()], + (Some(dbghelp), Kind::Ours) if self.pdb.0 => { + let (names, context) = dbghelp.functions(address, self.inline); + line = dbghelp.line(address, context); + if names.is_empty() { + vec![plain()] + } else { + names + } + } + (Some(dbghelp), _) => { + // An export names the function only if it starts it: the + // nearest export below is some other function's. + let export = dbghelp.symbol(address).filter(|&(_, at)| match start { + Some(start) => at >= start && at <= address, + None => at <= address && address - at < 0x100, + }); + match export { + Some((name, _)) => { + let module = label.rsplit_once('.').map_or(&*label, |(stem, _)| stem); + vec![format!("{module}!{name}")] + } + None => vec![plain()], + } + } + }; + let funcs = names + .into_iter() + .map(|name| self.func(name, Some(kind))) + .collect(); + let line = line.map(|(file, line)| { + // The last three parts of the path: the crate, `src`, the file. + let mut parts: Vec<&str> = file.rsplit(['\\', '/']).take(3).collect(); + parts.reverse(); + let text = format!("{}:{line}", parts.join("\\")); + *self.by_line.entry(text.clone()).or_insert_with(|| { + self.lines.push(text); + self.lines.len() as u32 - 1 + }) + }); + Resolved { + funcs, + kind: Some(kind), + line, + } + } +} + +// --------------------------------------------------------------------- +// The report. +// --------------------------------------------------------------------- + +/// A function's time in a role, microseconds. +#[derive(Default, Clone, Copy)] +struct Row { + /// In the function itself, and of that on a processor. + own: u64, + cpu: u64, + /// In it and in what it called. + all: u64, +} + +/// What a role's threads did. +#[derive(Default)] +struct RoleReport { + threads: Vec<usize>, + wall: u64, + cpu: u64, + waiting: u64, + funcs: FastMap<u32, Row>, + /// By [`Kind`]: innermost frame's, the nearest frame's that is not the + /// system's, and with what it called. + modules: [[u64; 3]; 6], + /// (kind of wait, the function that waited, through whose code) to + /// microseconds. + waits: HashMap<(&'static str, u32, Option<Kind>), u64>, + lines: FastMap<(u32, u32), u64>, + /// Stacks as function indices, outermost first. + stacks: HashMap<Vec<u32>, u64>, +} + +/// A written report, and its numbers for the tests. +struct Report { + text: String, + folded: String, + #[cfg_attr(not(test), allow(dead_code))] + roles: Vec<RoleSummary>, +} + +/// A role's numbers as the tests ask for them (microseconds). +#[cfg_attr(not(test), allow(dead_code))] +struct RoleSummary { + role: Role, + wall: u64, + waiting: u64, + /// (name, own, with what it called), every function. + functions: Vec<(String, u64, u64)>, + /// (kind, the function that waited, time). + waits: Vec<(String, String, u64)>, +} + +/// The stacks written to the stacks file: those with this share of their +/// role's time or more; the rest go to one line per role. +const FOLD_LEAST: f64 = 0.00005; + +impl Sampler { + fn report(&mut self) -> Report { + let began = Instant::now(); + let inline = self.config.inline; + let stood = (self.held_within(0.5), self.held_within(0.99)); + let symbols = self.symbols.get_or_insert_with(|| Symbols::new(inline)); + symbols.refresh(); + // Every node's address, named. + let named: Vec<Vec<u32>> = self + .threads + .iter() + .map(|t| { + t.tree + .nodes + .iter() + .map(|n| symbols.resolve(n.address)) + .collect() + }) + .collect(); + let starts: Vec<u32> = self + .threads + .iter() + .map(|t| symbols.resolve(t.start)) + .collect(); + let symbols = &*symbols; + let mut roles: Vec<RoleReport> = Role::ALL.iter().map(|_| RoleReport::default()).collect(); + // Per thread: wall, on a processor, waiting (microseconds). + let mut per_thread = vec![[0u64; 3]; self.threads.len()]; + // Per thread: own time by function, for the one it is mostly in. + let mut mostly: Vec<FastMap<u32, u64>> = vec![FastMap::default(); self.threads.len()]; + let mut stamp = 0u32; + let mut seen = vec![0u32; symbols.funcs.len()]; + let mut path: Vec<(u32, Option<Kind>)> = Vec::new(); + for (t, thread) in self.threads.iter().enumerate() { + let role = &mut roles[thread.role as usize]; + role.threads.push(t); + let nodes = &thread.tree.nodes; + for (i, node) in nodes.iter().enumerate().skip(1) { + if node.wall == 0 { + continue; + } + // The stack, innermost first, inlined calls as frames. + path.clear(); + let mut at = i; + while at != 0 { + let resolved = &symbols.resolved[named[t][at] as usize]; + path.extend(resolved.funcs.iter().rev().map(|&f| (f, resolved.kind))); + at = nodes[at].parent as usize; + } + let (wall, cpu) = (node.wall, node.cpu); + role.wall += wall; + role.cpu += cpu; + per_thread[t][0] += wall; + per_thread[t][1] += cpu; + *mostly[t].entry(path[0].0).or_default() += wall; + let (leaf, leaf_kind) = path[0]; + let row = role.funcs.entry(leaf).or_default(); + row.own += wall; + row.cpu += cpu; + stamp += 1; + let mut kinds = [false; 6]; + // Every thread starts in the system's code: those outermost + // frames are not the system "with what it calls". + let start = path + .iter() + .rposition(|p| p.1.is_some_and(|k| k != Kind::System)); + for (at, &(func, kind)) in path.iter().enumerate() { + if seen[func as usize] != stamp { + seen[func as usize] = stamp; + role.funcs.entry(func).or_default().all += wall; + } + if let Some(kind) = kind + && start.is_some_and(|start| at <= start) + { + kinds[kind as usize] = true; + } + } + for (kind, &on) in kinds.iter().enumerate() { + role.modules[kind][2] += if on { wall } else { 0 }; + } + if let Some(kind) = leaf_kind { + role.modules[kind as usize][0] += wall; + } + // Whose time it is: the innermost frame that is not the + // system's (a kernel call is its caller's). + let owner = path + .iter() + .filter_map(|&(_, kind)| kind) + .find(|&kind| !matches!(kind, Kind::System | Kind::Other)) + .or(leaf_kind); + if let Some(kind) = owner { + role.modules[kind as usize][1] += wall; + } + let ours = |&(func, kind): &(u32, Option<Kind>)| { + kind == Some(Kind::Ours) && !symbols.funcs[func as usize].runtime + }; + if symbols.funcs[leaf as usize].wait { + role.waiting += wall; + per_thread[t][2] += wall; + // The function of ours that waited (the title's, on a + // thread with none of ours), and what lies between. + let caller = path + .iter() + .position(ours) + .or_else(|| path.iter().position(|p| p.1 == Some(Kind::Title))); + let between = &path[..caller.unwrap_or(path.len())]; + let names: Vec<&str> = between + .iter() + .map(|&(f, _)| &*symbols.funcs[f as usize].name) + .collect(); + let through = between.iter().filter_map(|&(_, kind)| kind).find(|kind| { + matches!( + kind, + Kind::Driver | Kind::Direct3d | Kind::Title | Kind::Other + ) + }); + let caller = caller.map_or(u32::MAX, |at| path[at].0); + *role + .waits + .entry((wait_kind(&names), caller, through)) + .or_default() += wall; + } + let resolved = &symbols.resolved[named[t][i] as usize]; + if let Some(line) = resolved.line { + *role.lines.entry((line, leaf)).or_default() += wall; + } + let stack: Vec<u32> = path.iter().rev().map(|&(f, _)| f).collect(); + *role.stacks.entry(stack).or_default() += wall; + } + } + + // Written out. + let frames = self.presented; + let seconds = self.wall as f64 / 1e6; + // Microseconds to the unit of the tables. + let (unit, per) = if frames > 0 { + ("ms a frame", 1000.0 * frames as f64) + } else { + ("ms a second", 1000.0 * seconds.max(1e-9)) + }; + let ms = |us: u64| us as f64 / per; + let share = |us: u64, of: u64| 100.0 * us as f64 / of.max(1) as f64; + let name = |func: u32| match symbols.funcs.get(func as usize) { + Some(func) => &*func.name, + None => "[no function of ours or the title's]", + }; + // For the tables: a long name's start and end (the stacks file has it whole). + let short = |func: u32, most: usize| { + let name = name(func); + let chars = name.chars().count(); + if chars <= most { + return name.to_owned(); + } + let head: String = name.chars().take(most * 2 / 3).collect(); + let tail: String = name.chars().skip(chars - most / 3).collect(); + format!("{head}...{tail}") + }; + let mut text = String::new(); + let mut folded = String::new(); + let mut summaries = Vec::new(); + let w = &mut text; + let _ = writeln!(w, "VIctory profile, process {}", std::process::id()); + let _ = writeln!( + w, + "sampled {seconds:.1} s in {} looks ({} asked a second, {:.2} ms between looks, {} late); \ + {frames} frames presented meanwhile{}", + self.ticks, + self.config.hz, + self.wall as f64 / 1000.0 / self.ticks.max(1) as f64, + self.late, + if frames > 0 { + format!( + " ({:.1} ms a frame)", + self.wall as f64 / 1000.0 / frames as f64 + ) + } else { + " (none: the tables are per second of sampling)".to_owned() + }, + ); + let alive = self.threads.iter().filter(|t| t.alive).count(); + let _ = writeln!( + w, + "{} threads followed ({alive} still running); a thread looked at stood still under {:.0} us \ + half the times, under {:.0} us 99 in 100, {:.0} us at longest, {:.1} us on average, {} \ + times; {} call sites kept{}", + self.threads.len(), + stood.0, + stood.1, + self.held_longest as f64 / 1000.0, + self.held_ns as f64 / 1000.0 / self.held.max(1) as f64, + self.held, + self.nodes, + if self.nodes >= MOST_NODES { + " (FULL: later new stacks are one line)" + } else { + "" + }, + ); + if self.config.budget > 0.0 { + let _ = writeln!( + w, + "a thread may stand still for looks {:.1} % of its time (VICTORY_PROFILE_BUDGET): one \ + whose looks cost more is looked at every 2nd, 3rd... tick while it runs (\"every\" \ + below); its samples stand for more time each, so the times stay right", + 100.0 * self.config.budget + ); + } + let (mine, since) = (own_cpu(), self.clock.elapsed()); + let _ = writeln!( + w, + "the sampler's thread used {:.1} % of one processor", + 100.0 * mine.as_secs_f64() / since.as_secs_f64().max(1e-9), + ); + let _ = writeln!( + w, + "names of ours: {}", + match (&symbols.dbghelp, &symbols.pdb) { + (None, _) => + "dbghelp.dll could not be used: every frame is module+offset".to_owned(), + (Some(_), (true, pdb)) => format!("from {pdb}"), + (Some(_), (false, _)) => + "NO PDB FOUND for the executable: its frames are module+offset of each \ + function's start (keep victory.pdb beside victory.exe)" + .to_owned(), + } + ); + let _ = writeln!(w); + let _ = writeln!( + w, + "How to read. Every number is {unit} unless it is a %. A role's time is its threads' \ + together: five recording threads can make more than a frame." + ); + let _ = writeln!( + w, + " own time with the function as the innermost frame; a call into the kernel \ + (ntdll!Nt..., win32u!Nt...) is the kernel working or waiting for that caller" + ); + let _ = writeln!(w, " with own time plus everything the function called"); + let _ = writeln!( + w, + " on cpu share of the own time the thread was on a processor (its cycle counter): \ + low means it stood there blocked" + ); + let _ = writeln!( + w, + " waiting samples whose innermost frame is one of the kernel's waits; under WAITS \ + they are given to the function of ours that waited" + ); + let _ = writeln!( + w, + " looks times a thread was sampled; not susp: of those, the ones answered without \ + suspending it (it had not run since the look before); cut: stacks that did not reach \ + the thread's first frame; look us: what a suspension of it takes" + ); + let _ = writeln!( + w, + " title+0x1234 is the title's function starting at that offset; \ + nvwgf2umx.dll+0x1234 a driver function with no name; [frames not kept] marks stacks \ + deeper than {} frames or {} KB", + self.config.depth, + self.config.stack >> 10, + ); + let _ = writeln!(w); + let _ = writeln!(w, "THREADS"); + let _ = writeln!( + w, + " {:<10} {:>7} {:<30} {:>9} {:>8} {:>9} {:>9} {:>8} {:>7} {:>7} {:>5} {:>8} mostly in (own time)", + "role", + "thread", + "name, or where it started", + unit, + "on cpu %", + "waiting %", + "looks", + "not susp", + "failed", + "cut", + "every", + "look us" + ); + for role in Role::ALL { + for &t in &roles[role as usize].threads { + let thread = &self.threads[t]; + let [wall, cpu, waiting] = per_thread[t]; + let said = if thread.name.is_empty() { + let start = &symbols.resolved[starts[t] as usize]; + format!("at {}", short(start.funcs[0], 27)) + } else { + thread.name.chars().take(30).collect::<String>() + }; + let top = mostly[t].iter().max_by_key(|&(&func, &us)| (us, func)); + let top = top.map_or(String::new(), |(&func, &us)| { + format!(" {} ({:.0} %)", short(func, 70), share(us, wall)) + }); + let _ = writeln!( + w, + " {:<10} {:>7} {:<30} {:>9.1} {:>8.1} {:>9.1} {:>9} {:>8} {:>7} {:>7} {:>5} {:>8.1}{}{top}", + role.name(), + thread.id, + said, + ms(wall), + share(cpu, wall), + share(waiting, wall), + thread.looks, + thread.reused, + thread.missed, + thread.cut, + thread.every, + thread.cost / 1000.0, + if thread.alive { "" } else { " (ended)" }, + ); + } + } + for role in Role::ALL { + let r = &roles[role as usize]; + if r.wall == 0 { + continue; + } + let _ = writeln!(w); + let _ = writeln!( + w, + "=== {} === {} thread{}: {:.1} {unit}, on a processor {:.1} ({:.0} %), waiting {:.1} ({:.0} %)", + role.says(), + r.threads.len(), + if r.threads.len() == 1 { "" } else { "s" }, + ms(r.wall), + ms(r.cpu), + share(r.cpu, r.wall), + ms(r.waiting), + share(r.waiting, r.wall), + ); + let _ = writeln!( + w, + " BY MODULE (own: the innermost frame's; for: system time given to the nearest \ + caller that is ours, the driver's, Direct3D's or the title's; with: anywhere on \ + the stack above the thread's start)" + ); + let _ = writeln!( + w, + " {:<18} {:>9} {:>6} {:>9} {:>6} {:>9} {:>6}", + "", "own", "%", "for", "%", "with", "%" + ); + for (kind, label) in KINDS.iter().enumerate() { + let [own, owner, all] = r.modules[kind]; + let _ = writeln!( + w, + " {:<18} {:>9.2} {:>6.1} {:>9.2} {:>6.1} {:>9.2} {:>6.1}", + label, + ms(own), + share(own, r.wall), + ms(owner), + share(owner, r.wall), + ms(all), + share(all, r.wall), + ); + } + let mut rows: Vec<(u32, Row)> = r.funcs.iter().map(|(&f, &row)| (f, row)).collect(); + let table = |w: &mut String, title: &str, rows: &[(u32, Row)]| { + let _ = writeln!(w, " {title}"); + let _ = writeln!( + w, + " {:>9} {:>6} {:>9} {:>6} {:>7} function", + "own", "%", "with", "%", "on cpu%" + ); + for &(func, row) in rows.iter().take(40) { + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {:>9.2} {:>6.1} {:>7} {}", + ms(row.own), + share(row.own, r.wall), + ms(row.all), + share(row.all, r.wall), + if row.own > 0 { + format!("{:.0}", share(row.cpu, row.own)) + } else { + "-".into() + }, + short(func, 150), + ); + } + }; + rows.sort_by(|a, b| b.1.own.cmp(&a.1.own).then(a.0.cmp(&b.0))); + let own = rows.iter().take_while(|row| row.1.own > 0).count(); + table(&mut *w, "FUNCTIONS BY OWN TIME (top 40)", &rows[..own]); + // Every stack of a thread has its start-up frames: they say nothing. + rows.retain(|&(func, _)| { + let func = &symbols.funcs[func as usize]; + let start = ["!RtlUserThreadStart", "!BaseThreadInitThunk"]; + !func.runtime && !start.iter().any(|s| func.name.ends_with(s)) + }); + rows.sort_by(|a, b| b.1.all.cmp(&a.1.all).then(a.0.cmp(&b.0))); + table( + &mut *w, + "FUNCTIONS WITH WHAT THEY CALL (top 40; without the thread's start and the language's runtime)", + &rows, + ); + let mut waits: Vec<_> = r.waits.iter().map(|(&key, &us)| (us, key)).collect(); + waits.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.1.cmp(&b.1.1))); + if !waits.is_empty() { + let _ = writeln!( + w, + " WAITS ({:.1} {unit}, {:.0} % of the role), by the function that waited", + ms(r.waiting), + share(r.waiting, r.wall) + ); + let _ = writeln!( + w, + " {:>9} {:>6} {:<24} {:<16} waited in", + "", "%", "kind", "inside" + ); + for &(us, (kind, caller, through)) in waits.iter().take(30) { + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {:<24} {:<16} {}", + ms(us), + share(us, r.wall), + kind, + through.map_or("-", |kind| KINDS[kind as usize]), + short(caller, 150), + ); + } + } + let mut lines: Vec<_> = r.lines.iter().map(|(&key, &us)| (us, key)).collect(); + lines.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + if !lines.is_empty() { + let _ = writeln!(w, " HOTTEST LINES OF OURS (own time)"); + for &(us, (line, func)) in lines.iter().take(25) { + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {} ({})", + ms(us), + share(us, r.wall), + symbols.lines[line as usize], + short(func, 100), + ); + } + } + let mut stacks: Vec<(&Vec<u32>, u64)> = + r.stacks.iter().map(|(s, &us)| (s, us)).collect(); + stacks.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + let fold = |stack: &[u32]| { + let mut line = String::from(role.name()); + for &func in stack { + line.push(';'); + line.extend(name(func).chars().map(|c| match c { + ';' => ':', + ' ' => '_', + c => c, + })); + } + line + }; + let _ = writeln!( + w, + " STACKS (the 12 heaviest of {}, their innermost 10 frames, {unit}; all of them \ + whole, in microseconds, in the .folded file)", + stacks.len() + ); + for &(stack, us) in stacks.iter().take(12) { + let from = stack.len().saturating_sub(10); + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {}{}", + ms(us), + share(us, r.wall), + if from > 0 { "... " } else { "" }, + stack[from..] + .iter() + .map(|&f| short(f, 60)) + .collect::<Vec<_>>() + .join(" > "), + ); + } + let least = (FOLD_LEAST * r.wall as f64) as u64; + let mut rest = 0; + for &(stack, us) in &stacks { + if us >= least { + let _ = writeln!(folded, "{} {us}", fold(stack)); + } else { + rest += us; + } + } + if rest > 0 { + let _ = writeln!( + folded, + "{};[stacks_under_{:.3}_%_each] {rest}", + role.name(), + 100.0 * FOLD_LEAST + ); + } + summaries.push(RoleSummary { + role, + wall: r.wall, + waiting: r.waiting, + functions: r + .funcs + .iter() + .map(|(&f, row)| (name(f).to_owned(), row.own, row.all)) + .collect(), + waits: waits + .iter() + .map(|&(us, (kind, caller, _))| (kind.to_owned(), name(caller).to_owned(), us)) + .collect(), + }); + } + let _ = writeln!(w); + let _ = writeln!( + w, + "(this report took {:.0} ms to write; sampling stood still meanwhile)", + began.elapsed().as_secs_f64() * 1000.0 + ); + Report { + text, + folded, + roles: summaries, + } + } + + /// Writes the report and the stacks file, each whole or not at all (a + /// process ended in the middle leaves the last ones). + fn write(&mut self) { + let report = self.report(); + let out = self.config.out.clone(); + let put = |file: PathBuf, text: &str| { + let mut partial = file.clone().into_os_string(); + partial.push(".part"); + std::fs::write(&partial, text).and_then(|()| std::fs::rename(&partial, &file)) + }; + let mut stacks = out.clone().into_os_string(); + stacks.push(".folded"); + let written = + put(out.clone(), &report.text).and_then(|()| put(stacks.into(), &report.folded)); + static SAID: AtomicBool = AtomicBool::new(false); + match written { + Ok(()) if !SAID.swap(true, Relaxed) => { + tracing::info!(file = %out.display(), "profile written (and again as the run goes on; the stacks for a flame graph are beside it, .folded)"); + } + Ok(()) => {} + Err(e) => tracing::warn!(error = %e, file = %out.display(), "profile not written"), + } + self.resync(); + } +} + +/// The processor time the calling thread has used. +fn own_cpu() -> Duration { + use windows_sys::Win32::Foundation::FILETIME; + let zero = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own thread and four valid out pointers. + unsafe { + GetThreadTimes( + GetCurrentThread(), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + }; + let ticks = |t: FILETIME| u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime); + Duration::from_nanos((ticks(kernel) + ticks(user)) * 100) +} + +// --------------------------------------------------------------------- +// The sampler's thread. +// --------------------------------------------------------------------- + +/// Asks the sampler to write its last report and end; set when it has. +static STOP: AtomicBool = AtomicBool::new(false); +static DONE: AtomicBool = AtomicBool::new(false); +/// The sampler's thread, as a handle: to see at exit whether it still runs. +static SAMPLER: std::sync::atomic::AtomicPtr<c_void> = + std::sync::atomic::AtomicPtr::new(null_mut()); + +unsafe extern "C" { + fn atexit(f: extern "C" fn()) -> i32; +} + +/// At process exit (registered after the loader's own exit function, so +/// run before it ends the other threads): the last report is written. +extern "C" fn at_exit() { + STOP.store(true, Relaxed); + let thread = SAMPLER.load(Relaxed); + let waiting = Instant::now(); + while !DONE.load(Relaxed) && waiting.elapsed() < Duration::from_secs(10) { + // SAFETY: the sampler's thread handle, never closed; signalled + // when the thread is gone, however it went. + if thread.is_null() || unsafe { WaitForSingleObject(thread, 5) } == 0 { + break; + } + } +} + +/// The sampler's clock: a timer of the system's finer kind, which fires +/// every period by itself where the period is whole milliseconds (a +/// sleep of a millisecond takes one and a half). +struct Pace { + timer: HANDLE, + period: Duration, + /// The timer fires by itself; otherwise it is set before each wait, + /// for `next`. + repeats: bool, + next: Instant, + /// Microseconds a tick is put off by at most, and the state of the + /// numbers that say by how much. + jitter: u64, + random: u64, +} + +impl Pace { + fn new(hz: u32, jitter: u64) -> Pace { + use windows_sys::Win32::System::Threading::{ + CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, CreateWaitableTimerExW, SetWaitableTimer, + }; + let hz = hz.max(1); + let period = Duration::from_secs_f64(1.0 / f64::from(hz)); + // SAFETY: makes a timer of ours (all access), unnamed. + let timer = unsafe { + CreateWaitableTimerExW( + null(), + null(), + CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, + 0x1f_0003, + ) + }; + let mut repeats = false; + if !timer.is_null() && hz <= 1000 && 1000 % hz == 0 { + // First in a period from now (100 ns units, negative: from + // now), then every period (milliseconds). + let first = -(period.as_nanos() as i64 / 100); + // SAFETY: our timer; no completion routine. + repeats = unsafe { + SetWaitableTimer(timer, &first, (1000 / hz) as i32, None, null(), 0) != 0 + }; + } + Pace { + timer, + period, + repeats, + next: Instant::now() + period, + // Less than the period, so ticks stay in order. + jitter: jitter.min(period.as_micros() as u64 / 2), + random: 0x9e37_79b9_7f4a_7c15, + } + } + + /// Waits for the next tick. + /// + /// The timer wakes us on the system's clock, and so are woken the + /// threads that sleep: looked at then, a thread that sleeps a + /// millisecond at a time is always just waking (a test's sleeping + /// thread was seen out of its wait 12 % of the time; it is 0.5 %). So + /// the look is put off by a time that differs from tick to tick, + /// spent spinning: no timer is that fine. + fn wait(&mut self) { + self.wait_for_timer(); + if self.jitter > 0 { + self.random ^= self.random << 13; + self.random ^= self.random >> 7; + self.random ^= self.random << 17; + let until = Instant::now() + Duration::from_micros(self.random % (self.jitter + 1)); + while Instant::now() < until { + std::hint::spin_loop(); + } + } + } + + fn wait_for_timer(&mut self) { + use windows_sys::Win32::System::Threading::{INFINITE, SetWaitableTimer}; + if self.repeats { + // SAFETY: our timer. + unsafe { WaitForSingleObject(self.timer, INFINITE) }; + return; + } + let now = Instant::now(); + if self.next > now { + let due = -((self.next - now).as_nanos() as i64 / 100).max(1); + // SAFETY: our timer, set to fire once and waited for. + let set = !self.timer.is_null() + && unsafe { SetWaitableTimer(self.timer, &due, 0, None, null(), 0) } != 0; + if set { + // SAFETY: our timer. + unsafe { WaitForSingleObject(self.timer, INFINITE) }; + } else { + std::thread::sleep(self.next - now); + } + } + // A tick that came late is not made up for: the next is a period on. + self.next = (self.next + self.period).max(Instant::now()); + } +} + +/// Starts the sampler; false if its thread could not be made. +fn start(config: Config) -> bool { + use std::os::windows::io::IntoRawHandle; + let says = format!( + "profiling (VICTORY_PROFILE=1): {} looks a second at the submitting, recording and worker \ + threads, the report in {} every {:.0} s and at exit", + config.hz, + config.out.display(), + config.every + ); + match std::thread::Builder::new() + .name("victory-profile".into()) + .spawn(move || run(config)) + { + Ok(thread) => { + SAMPLER.store(thread.into_raw_handle().cast(), Relaxed); + // SAFETY: registers a function with the host CRT's exit table. + unsafe { atexit(at_exit) }; + tracing::info!("{says}"); + true + } + Err(e) => { + tracing::warn!(error = %e, "no thread for the profiler"); + false + } + } +} + +fn run(config: Config) { + // Above the threads it looks at: a late look stretches a sample, and + // a sampler taken off its processor between suspending a thread and + // letting it go leaves that thread standing. It sleeps most of the time. + // SAFETY: a plain call on our own thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) }; + let wait = |seconds: f64| { + let until = Instant::now() + Duration::from_secs_f64(seconds); + while Instant::now() < until && !STOP.load(Relaxed) { + std::thread::sleep(Duration::from_millis(20)); + } + }; + wait(config.after); + let mut pace = Pace::new(config.hz, config.jitter); + let (every, length) = ( + Duration::from_secs_f64(config.every), + config.length.map(Duration::from_secs_f64), + ); + let mut sampler = Sampler::new(config); + sampler.rescan(); + sampler.resync(); + let began = Instant::now(); + let (mut scan, mut report) = (began + SCAN, began + every); + while !STOP.load(Relaxed) && length.is_none_or(|length| began.elapsed() < length) { + pace.wait(); + sampler.tick(); + let now = Instant::now(); + if now >= scan { + sampler.rescan(); + scan = now + SCAN; + } + if now >= report { + sampler.write(); + report = Instant::now() + every; + } + } + sampler.write(); + DONE.store(true, Relaxed); +} + +/// Between two searches for threads to follow. +const SCAN: Duration = Duration::from_secs(1); + +#[cfg(test)] +mod tests; diff --git a/crates/victory-gpu/src/profile/tests.rs b/crates/victory-gpu/src/profile/tests.rs new file mode 100644 index 0000000000..16c57243c1 --- /dev/null +++ b/crates/victory-gpu/src/profile/tests.rs @@ -0,0 +1,1005 @@ +//! The profiler on threads whose work is known. No graphics card is used. + +use super::*; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Mutex, mpsc}; + +fn config(hz: u32) -> Config { + Config::new(hz, std::env::temp_dir().join("victory_profile_test.txt")) +} + +/// Starts a thread running `work` and returns its id once it runs. +fn thread(work: impl FnOnce() + Send + 'static) -> (u32, std::thread::JoinHandle<()>) { + let (said, hears) = mpsc::channel(); + let running = std::thread::spawn(move || { + // SAFETY: a plain query. + said.send(unsafe { GetCurrentThreadId() }).unwrap(); + work(); + }); + (hears.recv().unwrap(), running) +} + +/// Looks at the followed threads for `time`, a look every `period`, with +/// `frames` presents spread over it. +fn sample(sampler: &mut Sampler, time: Duration, period: Duration, frames: &AtomicU64, each: u64) { + sampler.resync(); + let began = Instant::now(); + let mut looks = 0u64; + while began.elapsed() < time { + std::thread::sleep(period); + sampler.tick(); + looks += 1; + if each > 0 && looks.is_multiple_of(each) { + frames.fetch_add(1, Relaxed); + } + } +} + +#[inline(never)] +fn profile_test_spin_inner(stop: &AtomicBool) -> u64 { + let mut sum = 0u64; + while !stop.load(Relaxed) { + for i in 0..2000u64 { + sum = std::hint::black_box(sum.wrapping_mul(31).wrapping_add(i)); + } + } + sum +} + +#[inline(never)] +fn profile_test_spins(stop: &AtomicBool) -> u64 { + std::hint::black_box(profile_test_spin_inner(stop)).wrapping_add(1) +} + +#[inline(never)] +fn profile_test_sleeps(stop: &AtomicBool) -> u64 { + let mut naps = 0; + while !stop.load(Relaxed) { + std::thread::sleep(Duration::from_millis(5)); + naps = std::hint::black_box(naps + 1); + } + naps +} + +#[inline(never)] +fn profile_test_locks(lock: &Mutex<u64>) -> u64 { + let mut held = lock.lock().unwrap(); + *held += 1; + std::hint::black_box(*held) +} + +#[inline(never)] +fn profile_test_deep(left: u32, stop: &AtomicBool) -> u64 { + // A frame of a kilobyte, so a hundred of them pass any small limit. + let mut room = [0u64; 128]; + room[left as usize % 128] = u64::from(left); + let room = std::hint::black_box(room); + let below = if left == 0 { + profile_test_sleeps(stop) + } else { + profile_test_deep(left - 1, stop) + }; + std::hint::black_box(below.wrapping_add(room[3])) +} + +/// Whether `address` is committed code. +fn executable(address: u64) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid; the query reads + // the address space's bookkeeping, not `address`. + unsafe { + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(address as *const _, &mut info, size_of_val(&info)) != 0 + && info.State == MEM_COMMIT + && info.Protect & 0xf0 != 0 + && info.Protect & 0x100 == 0 + } +} + +fn own(role: &RoleSummary, what: &str) -> u64 { + role.functions + .iter() + .filter(|f| f.0.contains(what)) + .map(|f| f.1) + .sum() +} + +fn with(role: &RoleSummary, what: &str) -> u64 { + role.functions + .iter() + .filter(|f| f.0.contains(what)) + .map(|f| f.2) + .max() + .unwrap_or(0) +} + +fn role(report: &Report, role: Role) -> &RoleSummary { + report + .roles + .iter() + .find(|r| r.role == role) + .unwrap_or_else(|| panic!("no {role:?} in\n{}", report.text)) +} + +/// A busy loop in one function, a sleep in another, a wait for a lock in +/// a third: the report gives each thread's time to the right one, as +/// running or as waiting, and per frame. +#[test] +fn time_goes_to_the_function_that_spent_it() { + static PRESENTS: AtomicU64 = AtomicU64::new(0); + let stop = Arc::new(AtomicBool::new(false)); + let lock = Arc::new(Mutex::new(0u64)); + let held = lock.lock().unwrap(); + let (spinning, a) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_spins(&stop)); + } + }); + let (sleeping, b) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_sleeps(&stop)); + } + }); + let (locked, c) = thread({ + let lock = lock.clone(); + move || { + std::hint::black_box(profile_test_locks(&lock)); + } + }); + std::thread::sleep(Duration::from_millis(50)); + + let mut sampler = Sampler::new(config(1000)); + sampler.presents = &PRESENTS; + sampler.follow(spinning, Role::Submit, null_mut(), Some("spins".into())); + sampler.follow(sleeping, Role::Record, null_mut(), Some("sleeps".into())); + sampler.follow(locked, Role::Wide, null_mut(), Some("locks".into())); + assert_eq!(sampler.threads.len(), 3); + assert!( + sampler.threads.iter().all(|t| t.low != 0 && t.low < t.high), + "stack bounds" + ); + sample( + &mut sampler, + Duration::from_millis(1500), + Duration::from_millis(1), + &PRESENTS, + 20, + ); + let report = sampler.report(); + stop.store(true, Relaxed); + drop(held); + for running in [a, b, c] { + running.join().unwrap(); + } + println!("{}", report.text); + assert!(sampler.presented >= 20, "{} frames", sampler.presented); + assert!( + sampler.symbols.as_ref().is_some_and(|s| s.pdb.0), + "the test's PDB was not found" + ); + + // The busy loop: all of it in the inner function, called from the outer. + let spins = role(&report, Role::Submit); + assert!(spins.wall >= 1_200_000, "{} us sampled", spins.wall); + // (An unoptimised build calls the loop's own pieces; an optimised one + // has them inside it.) + let inner = with(spins, "profile_test_spin_inner"); + assert!( + inner * 100 >= spins.wall * 95, + "inner {inner} of {}", + spins.wall + ); + assert!(with(spins, "profile_test_spins") * 100 >= spins.wall * 95); + assert!(own(spins, "profile_test_spins") * 100 <= spins.wall * 5); + assert!( + spins.waiting * 100 <= spins.wall * 5, + "waiting {}", + spins.waiting + ); + // Every sample is some function's own time, once. + assert_eq!(spins.functions.iter().map(|f| f.1).sum::<u64>(), spins.wall); + + // The sleep: waiting, for the function that slept. + let sleeps = role(&report, Role::Record); + assert!( + sleeps.waiting * 100 >= sleeps.wall * 85, + "{} of {}", + sleeps.waiting, + sleeps.wall + ); + let (kind, caller, time) = &sleeps.waits[0]; + assert!( + kind == "sleep" && caller.contains("profile_test_sleeps"), + "{kind}, {caller}" + ); + assert!(time * 100 >= sleeps.waiting * 95); + + // The lock: waiting, for the function that wanted it. + let locks = role(&report, Role::Wide); + assert!( + locks.waiting * 100 >= locks.wall * 95, + "{} of {}", + locks.waiting, + locks.wall + ); + let (kind, caller, _) = &locks.waits[0]; + assert!( + kind == "lock (ours)" && caller.contains("profile_test_locks"), + "{kind}, {caller}" + ); + + // Per frame, and the stacks for a flame graph: outer before inner. + assert!(report.text.contains("ms a frame")); + let stack = report + .folded + .lines() + .find(|l| l.starts_with("submit;") && l.contains("profile_test_spin_inner")) + .unwrap_or_else(|| panic!("{}", report.folded)); + let (outer, inner) = ( + stack.find("profile_test_spins").unwrap(), + stack.find("profile_test_spin_inner").unwrap(), + ); + assert!(outer < inner, "{stack}"); + // The thread that waited the whole time was suspended once at most a + // few times: it had not run since the look before. + let waiting = sampler.threads.iter().find(|t| t.id == locked).unwrap(); + assert!( + waiting.reused * 10 >= waiting.looks * 9, + "{} of {}", + waiting.reused, + waiting.looks + ); +} + +/// A stack deeper than is kept, and one longer than is copied: the +/// innermost frames are still named, and the stack is marked as cut. +#[test] +fn deep_stacks_are_cut_not_lost() { + let stop = Arc::new(AtomicBool::new(false)); + let (deep, running) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_deep(150, &stop)); + } + }); + std::thread::sleep(Duration::from_millis(50)); + for (depth, stack) in [(24, 128 << 10), (MAX_DEPTH, 8 << 10)] { + static PRESENTS: AtomicU64 = AtomicU64::new(0); + let mut settings = config(500); + (settings.depth, settings.stack, settings.reuse) = (depth, stack, false); + let mut sampler = Sampler::new(settings); + sampler.presents = &PRESENTS; + sampler.follow(deep, Role::Busy, null_mut(), None); + sample( + &mut sampler, + Duration::from_millis(300), + Duration::from_millis(2), + &PRESENTS, + 0, + ); + let report = sampler.report(); + let thread = &sampler.threads[0]; + assert!( + thread.looks > 20 && thread.missed == 0, + "{} looks", + thread.looks + ); + assert_eq!( + thread.cut, thread.looks, + "depth {depth}, {stack} bytes copied" + ); + let busy = role(&report, Role::Busy); + assert!( + with(busy, "[frames not kept]") * 100 >= busy.wall * 99, + "{}", + report.text + ); + assert!( + with(busy, "profile_test_sleeps") * 100 >= busy.wall * 90, + "{}", + report.text + ); + assert!(report.text.contains("ms a second")); + } + stop.store(true, Relaxed); + running.join().unwrap(); +} + +/// Registers and stack bytes that mean nothing, at addresses inside real +/// code: the walk stops, and reads nothing outside its copy (a read +/// elsewhere would end the test with an access violation). +#[test] +fn stacks_that_mean_nothing_are_walked_without_a_fault() { + let mut symbols = Symbols::new(false); + symbols.refresh(); + let modules: Vec<(u64, u64)> = symbols.modules.iter().map(|m| (m.base, m.end)).collect(); + assert!(modules.len() > 3); + let mut sampler = Sampler::new(config(1000)); + // SAFETY: a plain query. + let me = unsafe { GetCurrentThreadId() }; + // A thread entry is all the walk needs; this one is never suspended. + sampler.follow(me, Role::Busy, null_mut(), None); + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + // Return instructions (bytes that read as one) in the modules' code. + let mut returns = Vec::new(); + while returns.len() < 20_000 { + let r = next(); + let (base, end) = modules[(r >> 32) as usize % modules.len()]; + let at = base + 0x1000 + r % (end - base - 0x1000).max(1); + if !executable(at) { + continue; + } + // SAFETY: committed code of a loaded module, as just asked, to + // the end of its page. + let bytes = + unsafe { std::slice::from_raw_parts(at as *const u8, 0x1000 - (at as usize & 0xfff)) }; + if let Some(ret) = bytes.iter().skip(16).position(|&b| b == 0xc3) { + returns.push(at + 16 + ret as u64); + } + } + let limit = sampler.config.stack; + let (mut walked, mut frames) = (0u64, 0u64); + let rounds = env_number("VICTORY_PROFILE_TEST_WALKS").map_or(60_000, |n| n as u64); + for round in 0..rounds { + let got = (next() as usize % limit) & !7; + // A pretended stack somewhere, or the thread's own range. + let rsp = if round.is_multiple_of(2) { + (0x7000_0000_0000u64 + (next() & 0xffff_fff0)) as usize + } else { + sampler.threads[0].low + 0x1000 + (next() as usize & 0xff8) + }; + let code = |r: u64| { + if r.is_multiple_of(3) { + // A few bytes before a return: where functions end. + return returns[(r >> 32) as usize % returns.len()] - (r >> 8 & 15); + } + let (base, end) = modules[(r >> 32) as usize % modules.len()]; + base + 0x1000 + r % (end - base - 0x1000).max(1) + }; + // The copy: words that are nothing, stack addresses, code addresses. + for at in (0..got).step_by(8) { + let r = next(); + let word = match r % 4 { + 0 => r, + 1 => (rsp + (next() as usize % (got + 4096))) as u64, + 2 => code(next()), + _ => r & 0xffff, + }; + // SAFETY: inside the copy. + unsafe { + sampler + .copy + .add((rsp & 15) + at) + .cast::<u64>() + .write_unaligned(word) + }; + } + let end = (rsp & 15) + got; + if end < sampler.dirty { + // SAFETY: inside the copy. + unsafe { sampler.copy.add(end).write_bytes(0, sampler.dirty - end) }; + } + sampler.dirty = end; + let context = &mut sampler.context.0; + for register in [ + &mut context.Rax, + &mut context.Rbx, + &mut context.Rcx, + &mut context.Rdx, + &mut context.Rbp, + &mut context.Rsi, + &mut context.Rdi, + &mut context.R8, + &mut context.R9, + &mut context.R10, + &mut context.R11, + &mut context.R12, + &mut context.R13, + &mut context.R14, + &mut context.R15, + ] { + let r = next(); + *register = match r % 3 { + 0 => r, + 1 => (rsp + (next() as usize % (got + 4096))) as u64, + _ => r & 0xfff, + }; + } + context.Rsp = rsp as u64; + context.Rip = code(next()); + let (count, _, used) = sampler.walk(0, got); + assert!(used <= got + 8, "{used} of {got}"); + walked += 1; + frames += count as u64; + } + println!("{walked} walks of stacks that mean nothing, {frames} frames"); + assert!(frames > walked); +} + +/// The walk of another thread's copied stack names the same callers as +/// the system's own walk of that thread by itself. +#[test] +fn the_walk_in_the_copy_is_the_systems_walk() { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + let (said, hears) = mpsc::channel(); + let (go, wait) = mpsc::channel::<()>(); + #[inline(never)] + fn profile_test_parked(said: &mpsc::Sender<Vec<u64>>, wait: &mpsc::Receiver<()>) -> u64 { + let mut own = [null_mut(); 32]; + // SAFETY: writes at most 32 return addresses into `own`. + let n = unsafe { RtlCaptureStackBackTrace(0, 32, own.as_mut_ptr(), null_mut()) }; + said.send(own[..usize::from(n)].iter().map(|&a| a as u64).collect()) + .unwrap(); + wait.recv().ok(); + std::hint::black_box(u64::from(n)) + } + let (parked, running) = thread(move || { + std::hint::black_box(profile_test_parked(&said, &wait)); + }); + let own = hears.recv().unwrap(); + std::thread::sleep(Duration::from_millis(50)); + let mut sampler = Sampler::new(config(1000)); + sampler.follow(parked, Role::Busy, null_mut(), None); + let (got, _) = sampler.capture(0).expect("the thread is looked at"); + let (frames, whole, used) = sampler.walk(0, got); + assert!(used > 64 && used <= got, "{used} of {got} bytes"); + let walked: Vec<u64> = sampler.frames[..frames].to_vec(); + go.send(()).unwrap(); + running.join().unwrap(); + assert!(whole, "{frames} frames"); + // The system's walk starts in the function that asked; ours deeper, in + // the wait. From that function's caller on they are the same calls + // (ours keeps the byte before each return address). + let callers: Vec<u64> = own[1..].iter().map(|a| a - 1).collect(); + assert!(callers.len() >= 3, "{own:x?}"); + let at = walked + .iter() + .position(|&a| a == callers[0]) + .unwrap_or_else(|| panic!("{walked:x?} {callers:x?}")); + assert_eq!( + &walked[at..], + &callers[..], + "ours {walked:x?}, the system's {own:x?}" + ); +} + +#[test] +fn names_say_what_waits_and_whose_code_it_is() { + assert!(waits("ntdll!NtWaitForSingleObject")); + assert!(waits("ntdll!ZwWaitForAlertByThreadId")); + assert!(waits("ntdll!NtDelayExecution")); + assert!(waits( + "win32u!NtGdiDdDDIWaitForSynchronizationObjectFromCpu" + )); + assert!(!waits("ntdll!NtQueryVirtualMemory")); + assert!(!waits("ntdll!NtYieldExecution")); + assert!(!waits("victory_gpu::host::Host::submit")); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForAlertByThreadId", + "ntdll!RtlAcquireSRWLockExclusive" + ]), + "lock (SRW)" + ); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForAlertByThreadId", + "ntdll.dll+0x1230", + "std::sys::sync::mutex::futex::Mutex::lock_contended" + ]), + "lock (ours)" + ); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForAlertByThreadId", + "std::sys::sync::condvar::futex::Condvar::wait" + ]), + "condition variable" + ); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForSingleObject", + "KERNELBASE!WaitForSingleObjectEx" + ]), + "event or handle" + ); + assert_eq!( + wait_kind(&["ntdll!NtDelayExecution", "KERNELBASE!SleepEx"]), + "sleep" + ); + assert_eq!(kind_of("nvwgf2umx.dll", false), Kind::Driver); + assert_eq!(kind_of("ntdll.dll", false), Kind::System); + assert_eq!(kind_of("d3d12core.dll", false), Kind::Direct3d); + assert_eq!( + kind_of("victory-image-0123456789abcdef.dll", false), + Kind::Title + ); + assert_eq!(kind_of("vcruntime140.dll", false), Kind::Other); + assert_eq!(kind_of("victory.exe", true), Kind::Ours); + assert_eq!(Role::of_name("victory-pipelines-3"), Some(Role::Pipelines)); + assert_eq!(Role::of_name("victory-wide-0"), Some(Role::Wide)); + assert_eq!(Role::of_name("victory-window"), None); +} + +#[test] +fn times_are_classed_four_to_a_power_of_two() { + assert_eq!(held_class(0), (0, 0)); + assert_eq!(held_class(3), (3, 3)); + assert_eq!(held_class(4), (8, 4)); + assert_eq!(held_class(7), (11, 7)); + assert_eq!(held_class(8), (12, 8)); + assert_eq!(held_class(9), (12, 8)); + assert_eq!(held_class(10), (13, 10)); + assert_eq!(held_class(20_000), (56, 16_384)); + let mut sampler = Sampler::new(config(1000)); + for ns in [1000, 20_000, 20_000, 20_000, 500_000] { + sampler.held += 1; + sampler.held_by[held_class(ns).0] += 1; + sampler.held_longest = sampler.held_longest.max(ns); + } + // The middle one of five is a 20 us one: its class ends at 20.48. + assert_eq!(sampler.held_within(0.5), 20.48); + assert_eq!(sampler.held_within(0.99), 524.288); +} + +#[test] +fn a_tree_keeps_each_call_site_once() { + let mut tree = Tree::new(); + // Innermost first: 3 called by 2 called by 1. + let a = tree.place(&[3, 2, 1], true, true); + let b = tree.place(&[3, 2, 1], true, true); + let c = tree.place(&[4, 2, 1], true, true); + assert_eq!(a, b); + assert_ne!(a, c); + assert_eq!(tree.nodes.len(), 5); + assert_eq!(tree.nodes[a as usize].parent, tree.nodes[c as usize].parent); + // A cut stack hangs under the marker, not under the first frame. + let cut = tree.place(&[3, 2, 1], false, true); + assert_ne!(cut, a); + assert_eq!(tree.nodes[1 + 4].address, CUT); + // With no room, what is new goes to the one node for it. + let nodes = tree.nodes.len(); + let full = tree.place(&[9, 8, 1], true, false); + assert_eq!(tree.nodes[full as usize].address, FULL); + assert_eq!(tree.nodes.len(), nodes + 1); + assert_eq!(tree.place(&[3, 2, 1], true, false), a); +} + +/// The hooks' own cost and the roles they give: a thread that submits is +/// followed as submitting once it has done so often enough. +#[test] +fn threads_are_followed_by_what_they_were_seen_doing() { + STATE.store(ON, Relaxed); + let stop = Arc::new(AtomicBool::new(false)); + let (submits, a) = thread({ + let stop = stop.clone(); + move || { + for _ in 0..SUBMITS { + seen(Seen::Submit); + } + for _ in 0..LIST_CALLS { + seen(Seen::Record); + } + profile_test_sleeps(&stop); + } + }); + let (records, b) = thread({ + let stop = stop.clone(); + move || { + seen(Seen::Submit); + for _ in 0..LIST_CALLS { + seen(Seen::Record); + } + profile_test_sleeps(&stop); + } + }); + let (named, c) = { + let stop = stop.clone(); + let (said, hears) = mpsc::channel(); + let running = std::thread::Builder::new() + .name("victory-wide-7".into()) + .spawn(move || { + // SAFETY: a plain query. + said.send(unsafe { GetCurrentThreadId() }).unwrap(); + profile_test_sleeps(&stop); + }) + .unwrap(); + (hears.recv().unwrap(), running) + }; + std::thread::sleep(Duration::from_millis(50)); + let mut settings = config(1000); + settings.busy = 0; + let mut sampler = Sampler::new(settings); + sampler.rescan(); + let role_of = |id: u32| sampler.threads.iter().find(|t| t.id == id).map(|t| t.role); + assert_eq!(role_of(submits), Some(Role::Submit)); + assert_eq!(role_of(records), Some(Role::Record)); + assert_eq!(role_of(named), Some(Role::Wide)); + assert!(sampler.threads.iter().all(|t| t.id != sampler.me)); + // A thread that ends is no longer looked at, and its place is free. + stop.store(true, Relaxed); + for running in [a, b, c] { + running.join().unwrap(); + } + sampler.rescan(); + sampler.rescan(); + assert!( + sampler + .threads + .iter() + .filter(|t| [submits, records, named].contains(&t.id)) + .all(|t| !t.alive) + ); + assert!( + KNOWN_THREADS + .iter() + .all(|k| ![submits, records].contains(&k.thread.load(Relaxed))) + ); + sampler.tick(); +} + +/// The sampler's own thread, as the game runs it: it finds a worker by +/// its name and a busy thread by its work, and writes the report and the +/// stacks file when its time is up. +#[test] +fn the_sampler_finds_threads_and_writes_its_files() { + let stop = Arc::new(AtomicBool::new(false)); + let named = { + let stop = stop.clone(); + std::thread::Builder::new() + .name("victory-pipelines-9".into()) + .spawn(move || { + profile_test_sleeps(&stop); + }) + .unwrap() + }; + let (_, busy) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_spins(&stop)); + } + }); + let folder = std::env::temp_dir().join(format!("victory_profile_test_{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let mut settings = config(500); + settings.out = folder.join("profile.txt"); + (settings.every, settings.length, settings.busy) = (1.2, Some(3.0), 2); + let out = settings.out.clone(); + std::thread::spawn(move || run(settings)).join().unwrap(); + stop.store(true, Relaxed); + named.join().unwrap(); + busy.join().unwrap(); + let text = std::fs::read_to_string(&out).unwrap(); + let mut stacks = out.clone().into_os_string(); + stacks.push(".folded"); + let folded = std::fs::read_to_string(&stacks).unwrap(); + let _ = std::fs::remove_dir_all(&folder); + println!("{text}"); + assert!(text.contains("=== PIPELINE WORKERS"), "{text}"); + assert!(text.contains("victory-pipelines-9")); + assert!(text.contains("=== OTHER BUSY THREADS"), "{text}"); + // The sleeping thread is seen sleeping: its wake-ups are on the same + // clock as the sampler's ticks, and are not what is sampled. + let pipelines = text.split("=== PIPELINE WORKERS").nth(1).unwrap(); + let waiting: f64 = pipelines + .split("waiting ") + .nth(1) + .and_then(|rest| rest.split('(').nth(1)) + .and_then(|rest| rest.split(' ').next()) + .and_then(|share| share.parse().ok()) + .unwrap_or_else(|| panic!("{pipelines}")); + assert!( + waiting >= 93.0, + "the sleeping thread waits {waiting} % of its time" + ); + assert!( + folded + .lines() + .any(|l| l.starts_with("busy;") && l.contains("profile_test_spin_inner")), + "{folded}" + ); + assert!( + folded + .lines() + .any(|l| l.starts_with("pipelines;") && l.contains("profile_test_sleeps")), + "{folded}" + ); + // Each stack line ends in its microseconds. + assert!(folded.lines().all(|l| { + l.rsplit(' ') + .next() + .is_some_and(|n| n.parse::<u64>().is_ok()) + })); + assert!(DONE.load(Relaxed)); +} + +/// Measures what the profiler costs the threads it looks at. Not a test +/// of anything: run it by name, in a release build: +/// `cargo test --profile diag -p victory-gpu --features diagnostics +/// profile::tests::what_looking_costs -- --ignored --nocapture`. +/// +/// Eight threads do work that is counted, one to a core and above the +/// priority other programs run at, so that a busy machine does not +/// decide the result; rounds with and without the profiler alternate. +#[test] +#[ignore = "a measurement, not a test"] +fn what_looking_costs() { + use windows_sys::Win32::System::Threading::{SetThreadAffinityMask, THREAD_PRIORITY_HIGHEST}; + #[repr(align(128))] + struct Count(AtomicU64); + const THREADS: usize = 8; + static COUNTS: [Count; THREADS] = [const { Count(AtomicU64::new(0)) }; THREADS]; + static STOP: AtomicBool = AtomicBool::new(false); + static WAITS: AtomicBool = AtomicBool::new(false); + + #[inline(never)] + fn profile_cost_work(depth: u32, count: &AtomicU64, seed: u64) -> u64 { + if depth > 0 { + return std::hint::black_box(profile_cost_work( + depth - 1, + count, + seed ^ u64::from(depth), + )) + 1; + } + let mut x = seed | 1; + while !STOP.load(Relaxed) { + for _ in 0..4096 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + } + count.fetch_add(1, Relaxed); + if WAITS.load(Relaxed) && x.is_multiple_of(64) { + // Now and then a wait, as a thread that waits for the card has. + std::thread::sleep(Duration::from_micros(500)); + } + } + x + } + + let pinned = std::thread::available_parallelism().map_or(1, |n| n.get()) >= 2 * THREADS; + let mut running = Vec::new(); + let mut ids = Vec::new(); + for (i, count) in COUNTS.iter().enumerate() { + let (id, thread) = thread(move || { + // SAFETY: plain calls on our own thread. + unsafe { + if pinned { + SetThreadAffinityMask(GetCurrentThread(), 1 << (2 * i)); + } + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); + } + std::hint::black_box(profile_cost_work(30, &count.0, i as u64 + 1)); + }); + ids.push(id); + running.push(thread); + } + std::thread::sleep(Duration::from_millis(200)); + // The parts of a look at a running thread, each timed on its own. + { + // SAFETY: a thread of this test, suspended and resumed in turn; the + // context is aligned; the copy is ours. + unsafe { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + let thread = OpenThread(ACCESS, 0, ids[0]); + let mut context = Box::new(Aligned(std::mem::zeroed())); + let mut copy = vec![0u8; 256 << 10]; + let mut parts: [Vec<u64>; 5] = Default::default(); + for _ in 0..3000 { + std::thread::sleep(Duration::from_micros(300)); + context.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; + let mut got = 0; + let t0 = Instant::now(); + SuspendThread(thread); + let t1 = Instant::now(); + GetThreadContext(thread, &mut context.0); + let t2 = Instant::now(); + ReadProcessMemory( + GetCurrentProcess(), + context.0.Rsp as *const c_void, + copy.as_mut_ptr().cast(), + 4096, + &mut got, + ); + let t3 = Instant::now(); + ResumeThread(thread); + let t4 = Instant::now(); + for (part, time) in + parts + .iter_mut() + .zip([t1 - t0, t2 - t1, t3 - t2, t4 - t3, t4 - t0]) + { + part.push(time.as_nanos() as u64); + } + } + CloseHandle(thread); + SetThreadPriority(GetCurrentThread(), 0); + let median = |part: &mut Vec<u64>| { + part.sort_unstable(); + ( + part[part.len() / 2] as f64 / 1000.0, + part[part.len() * 9 / 10] as f64 / 1000.0, + ) + }; + let [a, b, c, d, e] = parts.each_mut().map(median); + println!( + "a look at a running thread, 3000 of them, median (and 9 in 10 under), microseconds: \ + suspend {:.1} ({:.1}), read its registers {:.1} ({:.1}), copy 4 KB of stack {:.1} ({:.1}), \ + resume {:.1} ({:.1}), all {:.1} ({:.1})", + a.0, a.1, b.0, b.1, c.0, c.1, d.0, d.1, e.0, e.1 + ); + // The kernel's copy against a plain one, by size. + let source = vec![7u8; 256 << 10]; + for size in [4usize << 10, 16 << 10, 64 << 10, 128 << 10, 256 << 10] { + let (mut kernel, mut plain) = (Vec::new(), Vec::new()); + for _ in 0..400 { + let mut got = 0; + let t0 = Instant::now(); + ReadProcessMemory( + GetCurrentProcess(), + source.as_ptr().cast(), + copy.as_mut_ptr().cast(), + size, + &mut got, + ); + let t1 = Instant::now(); + std::ptr::copy_nonoverlapping( + source.as_ptr(), + std::hint::black_box(copy.as_mut_ptr()), + size, + ); + let t2 = Instant::now(); + kernel.push((t1 - t0).as_nanos() as u64); + plain.push((t2 - t1).as_nanos() as u64); + } + println!( + "a copy of {} KB: the kernel's {:.1} us, a plain one {:.1} us (medians of 400)", + size >> 10, + median(&mut kernel).0, + median(&mut plain).0 + ); + } + } + } + let total = || COUNTS.iter().map(|c| c.0.load(Relaxed)).sum::<u64>(); + let round = Duration::from_millis(1000); + let rounds = 9; + // The timer the sampler ticks by. + { + let mut pace = Pace::new(1000, 0); + let (began, mut longest, mut last) = (Instant::now(), Duration::ZERO, Instant::now()); + for _ in 0..2000 { + pace.wait(); + longest = longest.max(last.elapsed()); + last = Instant::now(); + } + println!( + "the timer: 2000 ticks of a millisecond took {:.1} ms, the longest {:.2} ms (repeating: {})", + began.elapsed().as_secs_f64() * 1000.0, + longest.as_secs_f64() * 1000.0, + pace.repeats + ); + } + for (what, waits, reuse, budget) in [ + ( + "8 threads always running, no limit on what looks may cost (VICTORY_PROFILE_BUDGET=0)", + false, + true, + 0.0, + ), + ( + "8 threads always running, the usual limit of 3 %", + false, + true, + 0.03, + ), + ( + "8 threads that run and wait, the usual limit", + true, + true, + 0.03, + ), + ( + "8 threads that run and wait, every look a suspension (VICTORY_PROFILE_REUSE=0), no limit", + true, + false, + 0.0, + ), + ] { + WAITS.store(waits, Relaxed); + std::thread::sleep(Duration::from_millis(300)); + for hz in [1000u32, 4000] { + let (mut without, mut with) = (Vec::new(), Vec::new()); + let (mut half, mut most, mut longest, mut looks, mut reused, mut late, mut used) = + (0.0f64, 0.0f64, 0.0f64, 0, 0, 0, 0.0); + let (mut ticks, mut every) = (0, 1); + for _ in 0..rounds { + // Without the profiler. + let (from, began) = (total(), Instant::now()); + std::thread::sleep(round); + without.push((total() - from) as f64 / began.elapsed().as_secs_f64()); + // With it, on a thread of its own as in the game. + let ids = ids.clone(); + let measured = std::thread::spawn(move || { + // SAFETY: a plain call on our own thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) }; + let mut settings = config(hz); + settings.reuse = reuse; + settings.budget = budget; + let mut sampler = Sampler::new(settings); + for &id in &ids { + sampler.follow(id, Role::Record, null_mut(), None); + } + sampler.resync(); + let mut pace = Pace::new(hz, 250); + let (cpu, from, began) = (own_cpu(), total(), Instant::now()); + while began.elapsed() < round { + pace.wait(); + sampler.tick(); + } + let rate = (total() - from) as f64 / began.elapsed().as_secs_f64(); + let used = (own_cpu() - cpu).as_secs_f64() / began.elapsed().as_secs_f64(); + let threads = &sampler.threads; + ( + rate, + used, + sampler.held_within(0.5), + sampler.held_within(0.99), + sampler.held_longest as f64 / 1000.0, + threads.iter().map(|t| t.looks).sum::<u64>(), + threads.iter().map(|t| t.reused).sum::<u64>(), + sampler.late, + threads.iter().map(|t| t.missed).sum::<u64>(), + sampler.ticks, + threads.iter().map(|t| t.every).max().unwrap_or(1), + ) + }) + .join() + .unwrap(); + with.push(measured.0); + used += measured.1 / rounds as f64; + half = half.max(measured.2); + most = most.max(measured.3); + longest = longest.max(measured.4); + looks += measured.5; + reused += measured.6; + late += measured.7; + assert_eq!(measured.8, 0, "looks that failed"); + ticks += measured.9; + every = every.max(measured.10); + } + let median = |values: &mut Vec<f64>| { + values.sort_by(f64::total_cmp); + values[values.len() / 2] + }; + let spread = |values: &[f64]| { + 100.0 * (values[values.len() - 1] - values[0]) / values[values.len() / 2] + }; + let (off, on) = (median(&mut without), median(&mut with)); + println!( + "{what}, {hz} looks a second: work done {:.2} % less with the profiler (medians of {rounds} \ + rounds of 1 s: {off:.0} against {on:.0} a second; the rounds without it differ by {:.1} %, \ + with it by {:.1} %); a suspension under {half:.0} us half the times, under {most:.0} us 99 \ + in 100, {longest:.0} us at longest; {ticks} ticks ({late} late), {looks} looks, {reused} \ + without a suspension, a thread looked at every {every} ticks at most; the sampler's \ + thread used {:.1} % of a processor", + 100.0 * (off - on) / off, + spread(&without), + spread(&with), + 100.0 * used, + ); + } + } + STOP.store(true, Relaxed); + for thread in running { + thread.join().unwrap(); + } +} diff --git a/crates/victory-gpu/src/query.rs b/crates/victory-gpu/src/query.rs index f3eb6b040f..b82af6691b 100644 --- a/crates/victory-gpu/src/query.rs +++ b/crates/victory-gpu/src/query.rs @@ -29,6 +29,13 @@ pub(crate) struct Desc { struct Heap { object: Object, desc: Desc, + /// With `VICTORY_OCCLUSION`: the host heap occlusion queries run in, made on first use (none for other kinds). + #[cfg(windows)] + host: std::sync::OnceLock<Option<windows::Win32::Graphics::Direct3D12::ID3D12QueryHeap>>, + /// Per query: 0 not on the host (answered "visible" as before), `list << 2 | 1` begun on the host in that host + /// list, 2 ended on the host. Made with the host heap. + #[cfg(windows)] + states: std::sync::OnceLock<Vec<std::sync::atomic::AtomicUsize>>, } /// Device method. @@ -46,10 +53,244 @@ pub(crate) extern "system" fn create( let heap = Box::new(Heap { object: Object::new(&FUNCTIONS), desc, + #[cfg(windows)] + host: std::sync::OnceLock::new(), + #[cfg(windows)] + states: std::sync::OnceLock::new(), }); object::hand_out(QUERY_HEAP, heap, iid, &HEAP_IIDS, out) } +/// Whether occlusion queries (console kinds 0 and 1) run on the host GPU and their results are resolved from it +/// (`VICTORY_OCCLUSION=1`; off by default: every one answers "visible", as before; `alt`: twenty seconds with, +/// twenty without, in turn, each change said in the log; decided at each `BeginQuery`). After Marvisak/VIctory +/// #3138 (FoxxoOwO), occlusion only. +#[cfg(windows)] +pub(crate) fn occlusion() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_OCCLUSION").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "occlusion queries run on the host GPU from now (VICTORY_OCCLUSION=alt): {}", + if on { "ON" } else { "off, every one answers visible as usual" } + ); + } + on + } + } +} + +/// Always counted: `BeginQuery` calls by console kind (0 occlusion, 1 binary, 2 timestamp, 3 statistics, 4 +/// other), queries ended on the host, queries resolved from the host, queries resolved as "visible". +pub(crate) static COUNTS: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; + +/// Counts a `BeginQuery` of `kind`; says the counts at every power of two of all of them (whether the title uses +/// queries at all decides whether this lever can matter). +pub(crate) fn counted(kind: u32) { + use std::sync::atomic::Ordering::Relaxed; + COUNTS[kind.min(4) as usize].fetch_add(1, Relaxed); + let all: u64 = (0..5).map(|k| COUNTS[k].load(Relaxed)).sum(); + if all.is_power_of_two() { + let c = COUNTS.each_ref().map(|a| a.load(Relaxed)); + tracing::info!( + "queries begun so far: {} occlusion, {} binary occlusion, {} timestamp, {} statistics, {} other; on the host (VICTORY_OCCLUSION): {} ended, {} resolved from it, {} resolved as visible", + c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7] + ); + } +} + +/// The host heap and per-query states of the console heap `this` (occlusion kinds only), made on first use. +#[cfg(windows)] +fn host_heap(this: This) -> Option<(&'static Heap, windows::Win32::Graphics::Direct3D12::ID3D12QueryHeap)> { + use windows::Win32::Graphics::Direct3D12::*; + if this.is_null() { + return None; + } + // SAFETY: the title passes one of our query heaps, alive while it uses it. + let heap: &'static Heap = unsafe { &*this.cast::<Heap>() }; + if heap.desc.kind > 1 || heap.desc.count == 0 { + return None; + } + let host = heap + .host + .get_or_init(|| { + let device = crate::host::host()?.device().clone(); + let mut made: Option<ID3D12QueryHeap> = None; + // SAFETY: plain object creation. + unsafe { + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_OCCLUSION, Count: heap.desc.count, NodeMask: 0 }, + &mut made, + ) + .ok()?; + } + made + }) + .clone()?; + heap.states.get_or_init(|| (0..heap.desc.count).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect()); + Some((heap, host)) +} + +#[cfg(windows)] +fn host_type(kind: u32) -> windows::Win32::Graphics::Direct3D12::D3D12_QUERY_TYPE { + use windows::Win32::Graphics::Direct3D12::*; + if kind == 1 { D3D12_QUERY_TYPE_BINARY_OCCLUSION } else { D3D12_QUERY_TYPE_OCCLUSION } +} + +/// `BeginQuery` of an occlusion query on `list`: begun on the host too, with the switch on. +#[cfg(windows)] +pub(crate) fn begin(list: &crate::host::HostList, this: This, kind: u32, index: u32) { + if kind > 1 || !occlusion() { + return; + } + let Some((heap, host)) = host_heap(this) else { return }; + let Some(state) = heap.states.get().and_then(|s| s.get(index as usize)) else { return }; + // SAFETY: an open list and our query heap; the index is inside it. + unsafe { list.list.BeginQuery(&host, host_type(kind), index) }; + state.store((list as *const _ as usize) << 2 | 1, std::sync::atomic::Ordering::Relaxed); + list.query_opened(host, kind, index, this as usize); +} + +/// `EndQuery` of an occlusion query on `list`: ended on the host if it was begun there in this same list (D3D12 +/// wants both in one list); one begun in another list is left to that list's close and answers "visible". +#[cfg(windows)] +pub(crate) fn end(list: &crate::host::HostList, this: This, kind: u32, index: u32) { + use std::sync::atomic::Ordering::Relaxed; + if kind > 1 { + return; + } + let Some((heap, host)) = host_heap(this) else { return }; + let Some(state) = heap.states.get().and_then(|s| s.get(index as usize)) else { return }; + let mine = (list as *const _ as usize) << 2 | 1; + let now = state.load(Relaxed); + if now == mine { + // SAFETY: an open list and our query heap; the query was begun in this list. + unsafe { list.list.EndQuery(&host, host_type(kind), index) }; + state.store(2, Relaxed); + list.query_closed(this as usize, index); + COUNTS[5].fetch_add(1, Relaxed); + } else if now & 3 == 1 { + state.store(0, Relaxed); + } +} + +/// At the close of `list`: queries begun on the host in it and not ended there are ended now (D3D12 wants it) and +/// answer "visible" (their state goes back to 0). +#[cfg(windows)] +pub(crate) fn close_open(open: Vec<(windows::Win32::Graphics::Direct3D12::ID3D12QueryHeap, u32, u32, usize)>, list: &crate::host::HostList) { + for (host, kind, index, console) in open { + // SAFETY: an open list and our query heap; the query was begun in this list. + unsafe { list.list.EndQuery(&host, host_type(kind), index) }; + if let Some((heap, _)) = host_heap(console as This) + && let Some(state) = heap.states.get().and_then(|s| s.get(index as usize)) + { + state.store(0, std::sync::atomic::Ordering::Relaxed); + } + } +} + +/// Read-back buffers of resolved queries, by slot, with the byte offset of the slot's result and the value written +/// if the read fails ([`result`]). +#[cfg(windows)] +static RESULTS: std::sync::Mutex<Option<std::collections::HashMap<u32, Back>>> = std::sync::Mutex::new(None); + +/// A slot of [`RESULTS`]: the read-back buffer, the result's byte offset in it, the value if it cannot be read. +#[cfg(windows)] +struct Back(windows::Win32::Graphics::Direct3D12::ID3D12Resource, u64, u64); +// SAFETY: D3D12 resources are free-threaded; the buffer is only mapped and read, behind the lock's hand-over. +#[cfg(windows)] +unsafe impl Send for Back {} +static NEXT_SLOT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// `ResolveQueryData` of `count` occlusion queries from `first` into title memory at `title` (8 bytes each): from +/// the host GPU if every one of them was begun and ended on the host, as `Written::Query` writes landing with the +/// list (as the "visible" answers did); false (the caller answers "visible") otherwise. +#[cfg(windows)] +pub(crate) fn resolve(list: &crate::host::HostList, this: This, kind: u32, first: u32, count: u32, title: u64) -> bool { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + if kind > 1 || count == 0 { + return false; + } + let Some((heap, host)) = host_heap(this) else { return false }; + let Some(states) = heap.states.get() else { return false }; + let all_ended = (first..first.saturating_add(count)).all(|i| states.get(i as usize).is_some_and(|s| s.load(Relaxed) == 2)); + if !all_ended { + COUNTS[7].fetch_add(u64::from(count), Relaxed); + return false; + } + let Some(device) = crate::host::host().map(|h| h.device().clone()) else { return false }; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(count) * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut back: Option<ID3D12Resource> = None; + // SAFETY: plain object creation. + if unsafe { device.CreateCommittedResource(&readback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back) }.is_err() { + return false; + } + let Some(back) = back else { return false }; + // SAFETY: an open list, our query heap (every query of the range ended), a read-back buffer of their size. + unsafe { list.list.ResolveQueryData(&host, host_type(kind), first, count, &back, 0) }; + let visible = if kind == 1 { 1 } else { 1 << 20 }; + let mut results = RESULTS.lock().unwrap_or_else(|e| e.into_inner()); + let results = results.get_or_insert_with(Default::default); + for i in 0..count { + let slot = NEXT_SLOT.fetch_add(1, Relaxed); + results.insert(slot, Back(back.clone(), u64::from(i) * 8, visible)); + list.defer_write(title.wrapping_add(u64::from(i) * 8) as *mut u8, crate::queue::Written::Query(slot), 8); + } + COUNTS[6].fetch_add(u64::from(count), Relaxed); + true +} + +/// The value of the resolved query in `slot` ([`resolve`]), once the list has run: read from its read-back buffer, +/// or "visible" if that fails. The slot is let go. +pub(crate) fn result(slot: u32) -> u64 { + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::D3D12_RANGE; + let entry = RESULTS.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|m| m.remove(&slot)); + let Some(Back(back, at, visible)) = entry else { return 1 << 20 }; + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: at as usize, End: at as usize + 8 }; + // SAFETY: a read-back buffer the list resolved into; it has run. + if unsafe { back.Map(0, Some(&range), Some(&mut data)) }.is_err() || data.is_null() { + return visible; + } + // SAFETY: the mapped buffer holds the slot's 8 bytes at `at`. + let value = unsafe { data.cast::<u8>().add(at as usize).cast::<u64>().read_unaligned() }; + // SAFETY: the same buffer, mapped above. + unsafe { back.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })) }; + value + } + #[cfg(not(windows))] + { + let _ = slot; + 1 << 20 + } +} + extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { object::answer( QUERY_HEAP, diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 6a1868eb79..4983cf1994 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -1,16 +1,11 @@ //! Command queues. Submitted lists run on the host GPU and are waited for, -//! so fence signals complete at once, unless the queue waits for a fence -//! value not reached yet: then its work is held back until it is (see -//! [`crate::timeline`]). +//! so fence signals complete at once. #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use crate::fence::Held; use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; -use crate::timeline::{Op, Timeline}; const QUEUE_IIDS: [Iid; 4] = [ guid( @@ -39,11 +34,926 @@ struct Queue { object: Object, kind: u32, desc: QueueDesc, - /// The work, in order, held back behind waits. - timeline: Arc<Timeline>, + /// What the queue was given after a wait for a fence that had not been + /// reached, in order; it runs when the fence gets there. + #[cfg(windows)] + held: std::sync::Mutex<Vec<Held>>, } const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10); +/// One thing a waiting queue holds back. +#[cfg(windows)] +enum Held { + /// The queue waits for the fence (its address) to reach the value. + Wait(usize, u64), + /// A list of the next submission waits for a memory value. + Value(crate::list::ValueWait), + /// A submission: the lists' host sides, taken from the title's lists + /// (which it may reset meanwhile), and the order they run in. + Run(Vec<crate::list::Detached>, Vec<usize>), + /// A signal of the queue's, due after what it holds before it. + Signal(usize, u64), + /// With [`behind`]: the submission at the head of the line is being + /// prepared and sent by our thread, with the line unlocked, so the + /// title can add to its end meanwhile; whatever is added stays behind + /// this (the line is not empty), signals too. + Running, + /// With [`present_behind`]: the title's present of a frame, due after + /// what the queue holds before it: the host texture shown, the state + /// the title's lists leave it in, and the frame's number. + Present(windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32, u64), +} + +/// Presents that are in a queue's line and have not run ([`Held::Present`]). +#[cfg(windows)] +static PRESENTS_HELD: AtomicU64 = AtomicU64::new(0); + +/// Whether a present goes behind the queue's line and returns at once +/// (`VICTORY_ASYNC_PRESENT=1`; needs [`behind`] and presents that do not +/// settle the flights, `crate::host::late_free_present`). +/// +/// Why: with [`behind`] our thread prepares and sends the submissions, but +/// the title's present still ran the line itself first, that is: it stood +/// until our thread had prepared every submission of the frame. Run 225's +/// frame log (the cell, 136 ms a frame): the title's render thread is 77 ms +/// of every frame inside the present waiting for that, using 3 ms of +/// processor itself, and only then begins to record the next frame (about +/// 57 ms), during which our thread has nothing to prepare. The two phases +/// ran one after the other. +/// +/// With the switch the present is one more thing in the line +/// ([`Held::Present`]): our thread shows the frame when it gets there, in +/// order, and the title records the next frame meanwhile. +/// +/// The title is one frame ahead at most: a present that finds the one +/// before it still in a line runs the old way (the lines first, then +/// itself), and so does a frame that is saved or listed, and a present +/// that finds its queue's line empty. A wait nothing ever meets is +/// therefore still forced, by the present after it. +/// +/// What it assumes, beyond what [`behind`] does: title memory a submission +/// reads stays as it was until the submission's fence is signalled, also +/// across the title's present. On the console the card reads that memory +/// when it runs the list, after the present call has returned. +/// +/// `VICTORY_ASYNC_PRESENT=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log, for measuring it in one scene. +#[cfg(windows)] +fn present_behind() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + let mode = *MODE.get_or_init(|| { + let asked = match std::env::var("VICTORY_ASYNC_PRESENT").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }; + let mode = if asked != 0 && behind() && crate::host::late_free_present() { asked } else { 0 }; + if mode != 0 { + tracing::info!("presents go behind the queue's line and return at once (VICTORY_ASYNC_PRESENT=1; alt: in turn)"); + } + mode + }); + match mode { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "presents behind the line from now (VICTORY_ASYNC_PRESENT=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// With [`present_behind`]: puts the present of the next frame behind what +/// the queue `this` holds. False if it has to run the old way. +#[cfg(windows)] +fn send_behind(this: This, planes: u32, plane_parameters: *const Plane) -> bool { + if this.is_null() || planes == 0 || PRESENTS_HELD.load(Ordering::Relaxed) != 0 { + return false; + } + let frame = FRAMES.load(Ordering::Relaxed) + 1; + // A frame that is saved or listed is read back at once. + #[cfg(feature = "diagnostics")] + if crate::capture::wanted(frame) || crate::capture::listed(frame) { + return false; + } + // SAFETY: the title passes `planes` plane descriptions. + let Some(plane) = (unsafe { plane_parameters.as_ref() }) else { + return false; + }; + if plane.count == 0 || plane.resources.is_null() { + return false; + } + // SAFETY: the plane lists `count` resources. + let resource = unsafe { *plane.resources }; + let Some(texture) = crate::resource::host_resource(resource) else { + return false; + }; + // The state the lists recorded so far leave the texture in: what our + // copy finds it in when it runs behind them (looked at, not changed). + const COPY_SOURCE: u32 = 0x800; + let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); + crate::resource::host_transition(resource, state); + let texture = texture.clone(); + let sent = hold(this, || { + PRESENTS_HELD.fetch_add(1, Ordering::Relaxed); + Held::Present(texture, state, frame) + }); + if sent { + PRESENTS_BEHIND.fetch_add(1, Ordering::Relaxed); + wake(); + } + sent +} + +/// Presents sent behind their queue's line since the start +/// ([`send_behind`]), for the line every 512 of them. +#[cfg(windows)] +static PRESENTS_BEHIND: AtomicU64 = AtomicU64::new(0); + +/// The queues that hold something (their addresses). +#[cfg(windows)] +static WAITING: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new()); + +#[cfg(windows)] +fn lock<T>(mutex: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Whether queues wait for fences. `VICTORY_QUEUE_WAIT=0`: they do not, +/// and every submission runs when it is made (as before). +#[cfg(windows)] +fn waits() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_WAIT").is_none_or(|v| v != "0")) +} + +/// Whether a submission is held list by list: the lists before the first +/// one whose wait for a memory value is not met run at once, and each list +/// that waits is held with the lists after it, behind its own waits. +/// Holding a submission whole made the title's queues wait for each other: +/// a graphics submission was held for a value a compute list writes, and +/// that compute list for a value an earlier list of the same graphics +/// submission writes. Nothing moved until the present forced it, and the +/// title reached its present only after waiting about 2.5 s, every frame +/// (runs 27-30: 2.4-2.9 s from the last submission to the present call, +/// 13-32 ms before waits were honoured; the frame's main graphics +/// submissions, 88 lists, ran forced, the compute lists before them). +/// On by default; `VICTORY_SPLIT_WAITS=0` holds whole submissions, as +/// before. +#[cfg(windows)] +fn split() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SPLIT_WAITS").is_none_or(|v| v != "0")) +} + +/// Whether a list is cut into host lists at its waits for memory values +/// (`crate::list::cut`), and a queue runs a submission part by part: it +/// stands at each wait until the value is in memory, with everything +/// recorded before the wait run and its bottom-of-pipe writes done, as on +/// the console. Held list by list ([`split`]) a wait still held its whole +/// list: the title's lists are chains of jobs, each behind a wait for a +/// value another queue's list writes in the middle of its own chain +/// (frame 858 of run 33: a compute list of 433 commands with 13 waits; +/// graphics lists of the form "341 dispatches, wait, draws"), so two lists +/// each waited for a write behind the other's wait and only the present +/// moved them, in the wrong order. +/// On by default where waits are honoured list by list; +/// `VICTORY_CUT_WAITS=0` holds whole lists, as before. +#[cfg(windows)] +pub(crate) fn cuts() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + waits() && split() && *ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WAITS").is_none_or(|v| v != "0")) +} + +/// Whether a present runs what queues still hold (on by default: a wait +/// is not kept across frames). `VICTORY_WAIT_FORCE=0` keeps it held: for +/// finding out whether the title's waits reach across its presents; a +/// wait nothing ever meets then stops the title for good. +#[cfg(windows)] +fn forces() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_FORCE").is_none_or(|v| v != "0")) +} + +/// A submission to a queue whose lists are cut at their waits ([`cuts`]). +/// The lists before the first one that waits run at once if the queue +/// holds nothing; the rest goes behind what the queue holds, part by part +/// (`crate::list::detach_parts`): the waits of a part, then its host +/// lists. [`release_held`] runs the queue's line as far as the values are +/// there, now and whenever a submission has run. +#[cfg(windows)] +fn submit_cut(this: This, lists: &[This]) { + let Some(host) = crate::host::host() else { + return; + }; + let first = if !behind() && lock(&queue(this).held).is_empty() { + lists + .iter() + .position(|&l| crate::list::cut_list(l)) + .unwrap_or(lists.len()) + } else { + 0 + }; + // A frame shot learns that its frame's lists are being submitted. + #[cfg(feature = "diagnostics")] + if crate::shot::recording() { + for &l in lists { + if let Some(h) = crate::list::host_list(l) { + crate::shot::submitted(h); + } + } + } + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let named: Vec<String> = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!( + "SUBMIT queue kind {:?} held {} lists {named:?} (the first {first} run at once, the rest part by part)", + Some(queue(this).kind), + first < lists.len() + ) + }); + if first > 0 && crate::host::late() { + // Sent to the card and not waited for: their host sides are taken + // from the title's lists (which it may reset before they have run) + // and come back, with their tables' slots, when they are settled. + let (taken, order) = crate::list::detach(&lists[..first]); + host.execute_late(taken, order); + } else if first > 0 { + let now: Vec<_> = lists[..first] + .iter() + .filter_map(|&l| crate::list::host_list(l)) + .collect(); + host.execute(&now); + // They have run: their descriptor tables' slots are free again, as + // on the path without cuts ([`execute`]). This path replaced that + // one without the call, so the lists that run at once kept their + // slots until the title's reset and the ring ran out as before + // (run 45: 3,143 of 15,942 tables refused in one frame). + crate::list::tables_done(&lists[..first]); + } + if first < lists.len() { + let parts = crate::list::detach_parts(&lists[first..]); + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + lists = lists.len(), + run_at_once = first, + parts = parts.len(), + waits = parts.iter().map(|p| p.0.len()).sum::<usize>(), + "a submission is given to its queue part by part (its lists wait for memory values)" + ); + } + { + let mut held = lock(&queue(this).held); + for (waits, taken, order) in parts { + held.extend(waits.into_iter().map(Held::Value)); + held.push(Held::Run(taken, order)); + } + } + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // What ran may be what another queue waits for, and what was just + // given to the queue may be free to run already. + release_held(false); +} + +/// A submission to a queue that honours waits, list by list ([`split`]). +/// shortcut: a wait still holds its whole list, not only the commands +/// after it; and lists named twice among those held stay in one piece. +#[cfg(windows)] +fn submit_split(this: This, lists: &[This]) { + let Some(host) = crate::host::host() else { + return; + }; + let by = crate::list::waits_by_list(lists); + // Behind what the queue already holds, nothing runs now. + let cut = if lock(&queue(this).held).is_empty() { + (0..lists.len()) + .find(|&i| by[i].iter().any(|w| !w.met())) + .unwrap_or(lists.len()) + } else { + 0 + }; + // A frame shot learns that its frame's lists are being submitted. + #[cfg(feature = "diagnostics")] + if crate::shot::recording() { + for &l in lists { + if let Some(h) = crate::list::host_list(l) { + crate::shot::submitted(h); + } + } + } + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let named: Vec<String> = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!( + "SUBMIT queue kind {:?} held {} lists {named:?} (the first {cut} run at once)", + Some(queue(this).kind), + cut < lists.len() + ) + }); + if cut > 0 { + let now: Vec<_> = lists[..cut] + .iter() + .filter_map(|&l| crate::list::host_list(l)) + .collect(); + host.execute(&now); + // They have run: their descriptor tables' slots are free again, as + // in `submit_cut` (which does this after the same call, for the + // same reason: the lists are not detached here, so nothing else + // gives their fresh tables' dynamic slots back before the title + // resets them). + crate::list::tables_done(&lists[..cut]); + } + if cut < lists.len() { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + lists = lists.len(), + run_at_once = cut, + waits = ?by[cut], + "lists of a submission are held for a memory value" + ); + } + let rest = &lists[cut..]; + // A list's host side can be taken once. + let twice = rest.iter().enumerate().any(|(i, l)| rest[..i].contains(l)); + let mut pieces: Vec<Held> = Vec::new(); + let mut from = cut; + while from < lists.len() { + // Up to the next list that waits for anything (met or not: it + // is looked at again when its turn comes). + let to = if twice { + lists.len() + } else { + (from + 1..lists.len()) + .find(|&i| !by[i].is_empty()) + .unwrap_or(lists.len()) + }; + let waits: Vec<crate::list::ValueWait> = by[from..to].concat(); + pieces.extend(waits.into_iter().map(Held::Value)); + let (taken, order) = crate::list::detach(&lists[from..to]); + pieces.push(Held::Run(taken, order)); + from = to; + } + lock(&queue(this).held).extend(pieces); + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // What ran may be what another queue waits for, and what was just held + // may be free to run already. + release_held(false); +} + +/// Adds `what()` to what the queue holds, if it holds anything (it waits +/// for a fence): whether it was added. +#[cfg(windows)] +fn hold(this: This, what: impl FnOnce() -> Held) -> bool { + if this.is_null() { + return false; + } + let mut held = lock(&queue(this).held); + if held.is_empty() { + return false; + } + held.push(what()); + true +} + +/// Runs what waiting queues hold as far as their fences have been reached +/// (`all`: all of it), each queue's in the order it was given. Called +/// where a fence may have moved: after a signal and after a submission (a +/// list's bottom-of-pipe write may be into a fence), never from inside +/// one. +#[cfg(windows)] +pub(crate) fn release_held(all: bool) { + if !all && behind() { + // A thread of ours runs what is free to run ([`behind`]). + wake(); + return; + } + release_held_now(all); +} + +/// Whether a submission is only put in its queue's line by the thread +/// that submits it, and prepared and sent by a thread of ours +/// (`VICTORY_ASYNC_SUBMIT=1`; needs flights and lists cut at their waits, +/// both defaults). +/// +/// Why: the profile of run 213 (292 ms a frame) has the title's render +/// thread inside `queue::execute` for 202 ms of every frame: 155 ms in +/// `Host::submit` (preparing: the copies of title memory, the write +/// watch, descriptors, textures; and waiting for flights), while its five +/// recording threads stand idle 78 % of the time and the card 43 %. The +/// title's thread does nothing with the result of that work: it only has +/// to be done before the lists run, in order. +/// +/// With the switch a submission's lists are taken from the title's lists +/// (as they already are when the queue holds anything) and put behind +/// the queue's line; one thread of ours ([`worker`]) runs the line in +/// order. A signal of the queue goes behind them, as it does behind +/// anything held. Everything that must see earlier submissions done runs +/// the line itself first: a present, and every submission of ours that +/// is waited for ([`before_sync`]). +/// +/// What it assumes: title memory a submission reads is not rewritten by +/// the title between its submit call and the moment our thread prepares +/// it, some milliseconds later. On the console the card reads that +/// memory when it runs the list, later still, so a title that rewrote it +/// earlier would be wrong there too. +#[cfg(windows)] +pub(crate) fn behind() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") && crate::host::late() && cuts(); + if on { + tracing::info!("submissions are prepared and sent by a thread of ours, not by the thread that submits (VICTORY_ASYNC_SUBMIT=1)"); + let _ = std::thread::Builder::new().name("victory-submit".into()).spawn(worker); + } + on + }) +} + +/// Whether there is something for [`worker`] to look at. +#[cfg(windows)] +static WORK: (std::sync::Mutex<bool>, std::sync::Condvar) = (std::sync::Mutex::new(false), std::sync::Condvar::new()); + +#[cfg(windows)] +fn wake() { + *lock(&WORK.0) = true; + WORK.1.notify_one(); +} + +/// The thread of [`behind`]: runs what queues hold as far as it is free +/// to run, each time something was added or a fence moved. +#[cfg(windows)] +fn worker() { + crate::framelog::keep_on_fast_cores("victory-submit"); + loop { + { + let mut work = lock(&WORK.0); + while !*work { + work = WORK.1.wait(work).unwrap_or_else(|e| e.into_inner()); + } + *work = false; + } + let started = std::time::Instant::now(); + let (user, kernel) = crate::framelog::thread_times(); + if crate::framelog::on() { + crate::framelog::add(crate::framelog::T::WorkerLooks, 1); + if crate::framelog::on_slow_core() { + crate::framelog::add(crate::framelog::T::WorkerSlow, 1); + } + } + release_held_now(false); + let (user_now, kernel_now) = crate::framelog::thread_times(); + crate::framelog::add(crate::framelog::T::WorkerUs, started.elapsed().as_micros() as u64); + crate::framelog::add(crate::framelog::T::WorkerUserUs, user_now.saturating_sub(user)); + crate::framelog::add(crate::framelog::T::WorkerKernelUs, kernel_now.saturating_sub(kernel)); + } +} + +#[cfg(windows)] +thread_local! { + /// This thread is inside [`release_held_now`]. + static RELEASING_HERE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// Whether parts that follow one another in the queues' lines go to the +/// host as one submission (`VICTORY_JOIN_PARTS=1`; `alt`: twenty seconds +/// with, twenty without, in turn, each change said in the log). Off by +/// default. Needs [`behind`]. +/// +/// Why: the title's lists wait for memory values (19 to 20 waits a frame +/// in the first rooms, each met by the bottom-of-pipe write of the part +/// before it), and every wait cuts a submission into parts: 29 host +/// submissions a frame from about 15 of the title's (run 238). Each part +/// is prepared on its own: 82 askings of the write watch, 666 refresh +/// steps, a heap sync, a merge under the flights in the air, and on the +/// card one list of ours that sends changed bytes and one that compares. +/// The title hands a frame over in one burst at the end of its recording, +/// then stands still until the line has finished it (its fence wait of +/// the next frame: run 238), so the parts are all in the lines when our +/// thread gets to them. +/// +/// With the switch the thread that runs the lines takes parts off them +/// in the order they would have run and gives them to the host together: +/// the same host lists in the same order, prepared once. Between two +/// parts a wait passes if memory meets it, if a write of a flight in the +/// air is known to meet it, or if a bottom-of-pipe write of a part taken +/// before it meets it (that part is ahead of it in the joined +/// submission, which is the order the wait asks for). A signal met +/// behind parts not sent yet is delivered right behind the joined +/// submission: never before the part it followed has run. Anything else +/// (a wait not known to be met, a present, the end of what is free to +/// run) sends what was taken first. At most [`join_most`] parts or +/// [`join_lists`] lists are joined, so that the card has work while the +/// next ones are prepared. Each queue with a part taken keeps the mark +/// [`Held::Running`] at the head of its line until the part is sent: +/// what the title gives the queue meanwhile, signals too, stays behind. +#[cfg(windows)] +fn join_parts() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + let mode = *MODE.get_or_init(|| { + let mode = match std::env::var("VICTORY_JOIN_PARTS").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }; + if mode != 0 { + tracing::info!( + "parts that follow one another in the queues' lines go to the host as one submission, at most {} parts or {} lists (VICTORY_JOIN_PARTS=1; alt: in turn)", + join_most(), + join_lists() + ); + } + mode + }); + match mode { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!("parts joined into one host submission from now (VICTORY_JOIN_PARTS=alt): {}", if on { "ON" } else { "off, as usual" }); + } + on + } + } +} + +/// The most parts joined into one host submission (`VICTORY_JOIN_MOST`, 4). +#[cfg(windows)] +fn join_most() -> usize { + static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_JOIN_MOST").ok().and_then(|v| v.parse().ok()).filter(|&n| n >= 1).unwrap_or(4)) +} + +/// The most host lists joined into one host submission (`VICTORY_JOIN_LISTS`, 48). +#[cfg(windows)] +fn join_lists() -> usize { + static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_JOIN_LISTS").ok().and_then(|v| v.parse().ok()).filter(|&n| n >= 1).unwrap_or(48)) +} + +/// With [`join_parts`]: parts taken off the queues' lines and not yet +/// given to the host, in the order they run. +#[cfg(windows)] +#[derive(Default)] +struct Joined { + lists: Vec<crate::list::Detached>, + order: Vec<usize>, + parts: usize, + /// Signals met behind those parts: delivered when the parts are sent. + signals: Vec<(usize, u64)>, + /// The queues with a part here: each has [`Held::Running`] at the + /// head of its line. + marked: Vec<usize>, +} + +#[cfg(windows)] +impl Joined { + fn is_empty(&self) -> bool { + self.parts == 0 + } + + /// One more part behind those taken: its lists keep their order. + fn add(&mut self, lists: Vec<crate::list::Detached>, order: Vec<usize>) { + let (lists, order) = join(std::mem::take(&mut self.lists), std::mem::take(&mut self.order), lists, order); + self.lists = lists; + self.order = order; + self.parts += 1; + } + + fn full(&self) -> bool { + self.parts >= join_most() || self.order.len() >= join_lists() + } + + /// Whether a bottom-of-pipe write of a part taken meets `wait`. + fn meets(&self, wait: &crate::list::ValueWait) -> bool { + let (address, bytes) = wait.place(); + self.order.iter().any(|&i| self.lists[i].host().will_write(address, bytes, |v| wait.holds_for(v))) + } +} + +#[cfg(windows)] +/// The things of one part behind those of another: `order` names places in +/// `lists`, so the second part's places move up by the first's count. +fn join<T>(mut lists: Vec<T>, mut order: Vec<usize>, more: Vec<T>, more_order: Vec<usize>) -> (Vec<T>, Vec<usize>) { + let base = lists.len(); + lists.extend(more); + order.extend(more_order.into_iter().map(|i| i + base)); + (lists, order) +} + +/// Parts joined, host submissions they went in, their lists, signals +/// delivered behind them, and waits passed for a write of a part taken. +#[cfg(windows)] +static JOINED: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +/// Gives the host what [`Joined`] holds, as one submission, delivers the +/// signals met behind it, and takes the marks off the lines. Called with +/// no line locked. +#[cfg(windows)] +fn send_joined(joined: &mut Joined) { + if joined.parts > 0 { + let (lists, order) = (std::mem::take(&mut joined.lists), std::mem::take(&mut joined.order)); + JOINED[0].fetch_add(joined.parts as u64, Ordering::Relaxed); + let sent = JOINED[1].fetch_add(1, Ordering::Relaxed) + 1; + JOINED[2].fetch_add(order.len() as u64, Ordering::Relaxed); + JOINED[3].fetch_add(joined.signals.len() as u64, Ordering::Relaxed); + if sent.is_multiple_of(2048) { + let n: Vec<u64> = JOINED.iter().map(|n| n.swap(0, Ordering::Relaxed)).collect(); + tracing::info!( + "parts joined (VICTORY_JOIN_PARTS=1): {} parts went to the host in {} submissions ({:.1} parts, {:.1} lists each), {} signals delivered behind them, {} waits passed for a write of a part not sent yet", + n[0], + n[1], + n[0] as f64 / n[1].max(1) as f64, + n[2] as f64 / n[1].max(1) as f64, + n[3], + n[4] + ); + } + match crate::host::host() { + Some(host) => host.execute_late(lists, order), + // (Not reached: parts are only taken with a host.) + None => crate::list::recycle(lists, &order), + } + joined.parts = 0; + } + // Behind what was just sent, in the order they were met. + for (fence, value) in joined.signals.drain(..) { + if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + } + for q in joined.marked.drain(..) { + // SAFETY: a live queue, as in the loop that marked it. + let line = unsafe { &(*(q as *const Queue)).held }; + let mut held = lock(line); + if matches!(held.first(), Some(Held::Running)) { + held.remove(0); + } + if held.is_empty() { + lock(&WAITING).retain(|&w| w != q); + } + } +} + +/// Before a submission of ours that is waited for, with [`behind`]: what +/// the queues hold and is free to run runs first, on this thread, so the +/// submission keeps its place behind them. +#[cfg(windows)] +pub(crate) fn before_sync() { + if behind() && !RELEASING_HERE.get() { + release_held_now(false); + } +} + +#[cfg(windows)] +fn release_held_now(all: bool) { + // One caller at a time, so a queue's submissions keep their order. + static RELEASING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + if lock(&WAITING).is_empty() { + return; + } + let _one = lock(&RELEASING); + let was_here = RELEASING_HERE.replace(true); + struct Leave(bool); + impl Drop for Leave { + fn drop(&mut self) { + RELEASING_HERE.set(self.0); + } + } + let _leave = Leave(was_here); + // Parts taken and not sent yet ([`join_parts`]): none when the lines + // are forced, and none is left when this returns. + let joining = !all && behind() && crate::host::late() && crate::host::host().is_some() && join_parts(); + let mut joined = Joined::default(); + loop { + let queues = lock(&WAITING).clone(); + let mut moved = false; + for q in queues { + // SAFETY: a live queue: one released is taken off the list. + let line = unsafe { &(*(q as *const Queue)).held }; + let mut held = lock(line); + loop { + // A queue with a part in `joined` has our mark at the head + // of its line: what is looked at is behind the mark. + let base = usize::from(joined.marked.contains(&q)); + match held.get(base) { + None | Some(Held::Running) => break, + Some(&Held::Wait(fence, value)) + if !all && crate::fence::completed(fence as This) < value => + { + break; + } + // With parts taken and not sent: only what is known + // without a wait for the card. A wait that stays is + // looked at again when the parts have been sent. + Some(Held::Value(wait)) if !all && !joined.is_empty() => { + if !wait.met() && !crate::host::late_met_known(wait) { + if !joined.meets(wait) { + break; + } + JOINED[4].fetch_add(1, Ordering::Relaxed); + } + } + Some(Held::Value(wait)) if !all && !value_met(wait) => break, + // The frame is shown behind the parts taken: they are + // sent first. + Some(Held::Present(..)) if !joined.is_empty() => break, + Some(_) => {} + } + match held.remove(base) { + Held::Wait(..) | Held::Running => {} + Held::Value(wait) => { + // Passed at a present without being met: what the + // queue stood at. + if all && !value_met(&wait) { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 16 { + tracing::warn!( + queue = format_args!("{q:#x}"), + ?wait, + "a wait for a memory value was not met at a present: the queue runs on" + ); + } + } + } + Held::Run(lists, order) => { + #[cfg(feature = "diagnostics")] + crate::capture::op(q, || { + format!( + "RUN held submission of {} lists (forced {all})", + order.len() + ) + }); + // Diagnostics: the part behind this one stands at + // waits that are met already, so the two could have + // been one host submission (one wait for the card, + // each range shaders write compared once). + #[cfg(feature = "diagnostics")] + { + let waits = held.iter().take_while(|h| matches!(h, Held::Value(_))).count(); + if waits > 0 + && matches!(held.get(waits), Some(Held::Run(..))) + && held[..waits].iter().all(|h| matches!(h, Held::Value(w) if w.met())) + { + crate::copystat::add(crate::copystat::C::PartsTogether, 1); + } + } + if joining { + // Taken, to go with the parts that follow it. + // The line stays open behind our mark. + if !joined.marked.contains(&q) { + held.insert(0, Held::Running); + joined.marked.push(q); + } + joined.add(lists, order); + if joined.full() { + drop(held); + send_joined(&mut joined); + held = lock(line); + } + moved = true; + continue; + } + if crate::host::late() + && let Some(host) = crate::host::host() + { + // Not waited for: the host keeps the lists + // until they are settled. + if behind() && !all { + // The line is open while this part is + // prepared and sent: only this thread takes + // from its head (one releaser at a time). + held.insert(0, Held::Running); + drop(held); + host.execute_late(lists, order); + held = lock(line); + if matches!(held.first(), Some(Held::Running)) { + held.remove(0); + } + } else { + host.execute_late(lists, order); + } + } else { + let ran = { + let runs: Vec<&crate::host::HostList> = + order.iter().map(|&i| lists[i].host()).collect(); + match crate::host::host() { + Some(host) => { + host.execute(&runs); + true + } + None => false, + } + }; + // They have run: their host lists are used again. + if ran { + crate::list::recycle(lists, &order); + } + } + if all { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Forced, 1); + static ONCE: AtomicBool = AtomicBool::new(false); + if !ONCE.swap(true, Ordering::Relaxed) { + tracing::warn!( + "a queue still held a submission at a present: its fence was not reached" + ); + } + } + } + Held::Present(texture, state, frame) => { + let show = || { + if let Some(host) = crate::host::host() { + let _ = host.present(&texture, state, frame, None); + } + }; + if all { + show(); + } else { + // The line is open while the frame is shown, + // as it is while a submission is prepared. + held.insert(0, Held::Running); + drop(held); + show(); + held = lock(line); + if matches!(held.first(), Some(Held::Running)) { + held.remove(0); + } + } + PRESENTS_HELD.fetch_sub(1, Ordering::Relaxed); + } + // Behind what was sent to the card and not waited + // for, if anything was. + Held::Signal(fence, value) => { + if !joined.is_empty() { + // Behind parts not sent yet: with them. + joined.signals.push((fence, value)); + } else if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + } + } + moved = true; + } + if held.is_empty() { + lock(&WAITING).retain(|&w| w != q); + } + } + if !moved { + if joined.is_empty() { + break; + } + // Nothing more is free to run behind the parts taken: they go + // to the host, and what stood at a wait is looked at again. + send_joined(&mut joined); + } + } +} + +/// Whether a queue may pass `wait`: memory holds the value, or, with +/// submissions sent to the card without a wait (`crate::host::late`), it +/// will once those in the air have run. +#[cfg(windows)] +fn value_met(wait: &crate::list::ValueWait) -> bool { + wait.met() || (crate::host::late() && crate::host::late_met(wait)) +} + fn queue<'a>(this: This) -> &'a Queue { // SAFETY: called from queue methods only. unsafe { &*this.cast::<Queue>() } @@ -68,7 +978,8 @@ pub(crate) extern "system" fn create( }, kind: desc.kind, desc, - timeline: Arc::default(), + #[cfg(windows)] + held: Default::default(), }); object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out) } @@ -115,39 +1026,94 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT ) } extern "system" fn release(this: This) -> u32 { - object::release_boxed::<Queue>(this) + let left = object::release_boxed::<Queue>(this); + #[cfg(windows)] + if left == 0 { + lock(&WAITING).retain(|&q| q != this as usize); + } + left } -/// Runs the lists' host lists and waits for them (decision 0007), once -/// the queue's waits before them are reached. +/// Runs the lists' host lists and waits for them (decision 0007). A queue +/// that waits for a fence keeps them until the fence is reached. extern "system" fn execute(this: This, count: u32, lists: *const This) { + #[cfg(windows)] + let started = std::time::Instant::now(); + execute_now(this, count, lists); + #[cfg(windows)] + { + let us = started.elapsed().as_micros() as u64; + crate::framelog::add(crate::framelog::T::ExecuteUs, us); + crate::framelog::here(crate::framelog::H::ExecuteUs, us); + } +} + +fn execute_now(this: This, count: u32, lists: *const This) { if lists.is_null() { return; } #[cfg(windows)] - if crate::host::host().is_some() { - crate::watch::new_submission(); - crate::descriptor::resync_title_writes(); + if let Some(host) = crate::host::host() { // SAFETY: the title passes `count` lists. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; - // Held until they run: the title may reset its lists before. + if cuts() && !this.is_null() { + submit_cut(this, lists); + return; + } + if waits() && split() && !this.is_null() { + submit_split(this, lists); + return; + } + // A list that waits for a memory value not there yet: the queue + // holds the submission, as it does behind a fence. + if waits() && !this.is_null() { + let unmet = crate::list::unmet_waits(lists); + if !unmet.is_empty() { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value"); + } + lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value)); + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + } + let kept = hold(this, || { + let (taken, order) = crate::list::detach(lists); + Held::Run(taken, order) + }); + // Diagnostics: the order submissions are made in, next to the + // commands of the frame's `ops` file (which are in recording order). + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let kind = (!this.is_null()).then(|| queue(this).kind); + // The lists as the frame's other lines name them (their host sides). + let named: Vec<String> = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!("SUBMIT queue kind {kind:?} held {kept} lists {named:?}") + }); + if kept { + return; + } let host_lists: Vec<_> = lists .iter() .filter_map(|&l| crate::list::host_list(l)) .collect(); - queue(this).timeline.submit(Op::Run(Box::new(move || { - if let Some(host) = crate::host::host() { - let runs: Vec<_> = host_lists.iter().map(|l| &**l).collect(); - host.execute(&runs); - for list in host_lists { - if let Ok(orphan) = std::sync::Arc::try_unwrap(list) { - host.recycle_list(orphan); - } - } - } - }))); + host.execute(&host_lists); + crate::list::tables_done(lists); + // What the lists wrote at the bottom of the pipe may be a fence + // another queue waits for. + release_held(false); return; } + let _ = this; static ONCE: AtomicBool = AtomicBool::new(false); if !ONCE.swap(true, Ordering::Relaxed) { tracing::warn!(count, "command lists submitted; no host GPU runs them"); @@ -179,26 +1145,81 @@ extern "system" fn signal2_x( } /// Markers and events only matter to profilers. extern "system" fn marker(_: This) {} -/// Signals once the queue's work before it has run. extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } - let fence = Held::new(fence); - queue(this) - .timeline - .submit(Op::Run(Box::new(move || fence.signal(value)))); - S_OK + #[cfg(all(windows, feature = "diagnostics"))] + crate::fence::pace::signal_called(fence as usize, value); + // A queue that waits signals after what it holds. + #[cfg(windows)] + if hold(this, || Held::Signal(fence as usize, value)) { + return S_OK; + } + // Behind the submissions sent to the card and not waited for: the + // fence is set when they are settled. + #[cfg(windows)] + if crate::host::late_signal(fence as usize, value) { + return S_OK; + } + let _ = this; + crate::fence::signal(fence, value) } -/// Holds the queue's later work back until the fence reaches `value`; the -/// caller does not wait. +/// From here on the queue runs nothing it is given until `fence` reaches +/// `value`: how the console orders work between queues (the title's +/// compute queue waits for the depth the graphics queue draws). Our +/// submissions run when they are made, so a wait for a value already +/// reached is nothing; otherwise what the queue is given next is held +/// ([`Held`]) until a signal or a list's bottom-of-pipe write gets the +/// fence there. extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } - queue(this) - .timeline - .submit(Op::Wait(Held::new(fence), value)); + #[cfg(windows)] + if !this.is_null() { + let now = crate::fence::completed(fence); + // Whether the title uses this at all (the first calls). + { + static CALLS: AtomicU64 = AtomicU64::new(0); + if CALLS.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!(kind = queue(this).kind, now, value, "a queue is told to wait for a fence"); + } + } + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind)); + let behind = { + let mut held = lock(&queue(this).held); + let behind = !held.is_empty() || now < value; + if behind && waits() { + held.push(Held::Wait(fence as usize, value)); + } + behind + }; + if behind { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + now, + value, + held = waits(), + "a queue waits for a fence not reached yet" + ); + } + } + if behind && waits() { + { + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // The fence may have got there meanwhile. + release_held(false); + } + } + let _ = (this, value); S_OK } /// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]). @@ -221,12 +1242,15 @@ pub(crate) enum Written { GpuTimestamp, /// The CPU's performance counter. SystemTimestamp, + /// A query result the host GPU resolved into a read-back buffer + /// (`crate::query::resolve`, `VICTORY_OCCLUSION`): read when written, + /// which is once the list has run. + Query(u32), } impl Written { - /// Stores the low `bytes` (4 or 8) of the value at `at`; returns the - /// queues it woke, to run with no lock held. - pub(crate) fn write(self, at: *mut u8, bytes: usize) -> crate::fence::Woken { + /// Stores the low `bytes` (4 or 8) of the value at `at`. + pub(crate) fn write(self, at: *mut u8, bytes: usize) { let value = match self { Written::Value(v) => v, Written::GpuTimestamp => { @@ -235,27 +1259,16 @@ impl Written { (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64 } Written::SystemTimestamp => system_timestamp(), + Written::Query(slot) => crate::query::result(slot), }; // SAFETY: the title names writable GPU memory (unified with ours). - // Use atomic Release stores when aligned so concurrent readers (such - // as a fence's `AtomicU64` value) observe them without a data race. unsafe { if bytes == 4 { - if (at as usize).is_multiple_of(align_of::<AtomicU32>()) { - (*at.cast::<AtomicU32>()).store(value as u32, Ordering::Release); - } else { - at.cast::<u32>().write_unaligned(value as u32); - std::sync::atomic::fence(Ordering::Release); - } - } else if (at as usize).is_multiple_of(align_of::<AtomicU64>()) { - (*at.cast::<AtomicU64>()).store(value, Ordering::Release); + at.cast::<u32>().write_unaligned(value as u32); } else { at.cast::<u64>().write_unaligned(value); - std::sync::atomic::fence(Ordering::Release); } } - // A write at a fence's GPU address moves its value. - crate::fence::written(at as usize, bytes) } } @@ -289,39 +1302,67 @@ extern "system" fn present( plane_parameters: *const Plane, _parameters: *const u8, ) -> HRESULT { - // Read now: the parameters are the title's, maybe on its stack. The - // frame is shown in the queue's order, after the work before it. - if planes > 1 { - // A console can put a UI plane over a scene plane (Series S: a - // 1080p scene under a 4K UI); only the first is shown here. Once, - // so a run shows whether a title needs the planes composited. - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(planes, "a present with several planes: only the first is shown"); - }); + #[cfg(windows)] + let presenting = std::time::Instant::now(); + let hr = present_now(this, planes, plane_parameters); + #[cfg(windows)] + { + crate::framelog::add(crate::framelog::T::PresentUs, presenting.elapsed().as_micros() as u64); + crate::framelog::frame(); + #[cfg(feature = "diagnostics")] + crate::fence::pace::frame(); } - let plane = if planes > 0 { - // SAFETY: the title passes `planes` plane descriptions. - unsafe { plane_parameters.as_ref() } - } else { - None - }; - let resource = plane - .filter(|plane| plane.count > 0 && !plane.resources.is_null()) - // SAFETY: the plane lists `count` resources. - .map(|plane| unsafe { *plane.resources }) - .filter(|resource| !resource.is_null()) - .map(object::Held::new); - queue(this) - .timeline - .submit(Op::Run(Box::new(move || show(resource)))); - S_OK + hr } -/// A present, once the queue's work before it has run: counts the frame -/// and shows the plane's first resource. -fn show(resource: Option<object::Held>) { +fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESULT { + #[cfg(windows)] + let presenting = std::time::Instant::now(); + #[cfg(all(windows, feature = "diagnostics"))] + crate::copystat::present_begins(); + #[cfg(all(windows, feature = "diagnostics"))] + crate::profile::frame(); + // With `present_behind`: the frame is shown by our thread, behind what + // the queue holds, and nothing is run or waited for here. + #[cfg(windows)] + let sent_behind = present_behind() && send_behind(this, planes, plane_parameters); + #[cfg(not(windows))] + let _ = this; + // Submissions sent to the card and not waited for are settled first, + // and what that frees runs in its own order, before anything is forced. + #[cfg(windows)] + if sent_behind { + } else if crate::host::late() && !crate::host::late_free_present() { + // (With `behind`: what the queues hold runs here first, and what + // it sent is settled with the rest.) + if behind() { + release_held_now(false); + } + crate::host::settle_for_present(); + release_held_now(false); + crate::host::settle_for_present(); + } else if crate::host::late() { + // The present is sent ahead too: what waits for a value a flight + // will write runs behind that flight, and nothing is settled here. + release_held_now(false); + } + // shortcut: what a queue still holds at a present runs now, whatever + // its fence: a wait is not kept across frames. + #[cfg(windows)] + if !sent_behind { + release_held(forces()); + } + #[cfg(windows)] + crate::framelog::add(crate::framelog::T::PresentLineUs, presenting.elapsed().as_micros() as u64); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; + #[cfg(windows)] + if sent_behind && PRESENTS_BEHIND.load(Ordering::Relaxed).is_multiple_of(512) { + tracing::info!( + frame, + behind = PRESENTS_BEHIND.load(Ordering::Relaxed), + "presents sent behind their queue's line so far (VICTORY_ASYNC_PRESENT=1); the others ran the old way" + ); + } if frame.is_power_of_two() { let (draws, dispatches) = crate::list::take_counts(); #[cfg(windows)] @@ -351,18 +1392,44 @@ fn show(resource: Option<object::Held>) { } } #[cfg(all(windows, feature = "diagnostics"))] - if crate::capture::listed(frame) { - crate::capture::dump_targets(frame); + { + crate::capture::frame_drew(frame, crate::draw::drawn()); + crate::renderdoc::frame_drew(frame, crate::draw::drawn()); + crate::shot::present(frame, crate::draw::drawn()); + if crate::capture::listed(frame) { + crate::capture::dump_targets(frame); + } } #[cfg(windows)] - if let Some(resource) = resource.as_ref().map(object::Held::get) + if !sent_behind + && planes > 0 + // SAFETY: the title passes `planes` plane descriptions. + && let Some(plane) = unsafe { plane_parameters.as_ref() } + && plane.count > 0 + && !plane.resources.is_null() + // SAFETY: the plane lists `count` resources. + && let resource = unsafe { *plane.resources } && let Some(texture) = crate::resource::host_resource(resource) && let Some(host) = crate::host::host() { const COPY_SOURCE: u32 = 0x800; let state = crate::resource::host_transition(resource, COPY_SOURCE) .map_or(COPY_SOURCE, |(_, before)| before); - let shown = host.present(texture, state, frame); + // A second plane (the title's interface over its game image, in + // its Series S mode) is drawn over the first: `crate::over`. Each + // plane's description is 0x48 bytes and starts as the first does. + const READABLE: u32 = 0x80; + // SAFETY: the title passes `planes` plane descriptions. + let second = unsafe { second_plane(planes, plane_parameters, resource) } + .and_then(|r| Some((r, crate::resource::host_resource(r)?))); + let over = second.map(|(r, t)| { + let was = crate::resource::host_transition(r, READABLE).map_or(READABLE, |(_, before)| before); + (r, t, was) + }); + let shown = host.present(texture, state, frame, over.map(|(_, t, was)| (t, was))); + if let Some((r, _, was)) = over { + crate::resource::host_transition(r, was); + } crate::resource::host_transition(resource, state); #[cfg(feature = "diagnostics")] blinks(frame, resource, state, shown); @@ -370,8 +1437,77 @@ fn show(resource: Option<object::Held>) { let _ = shown; } #[cfg(not(windows))] - let _ = resource; + let _ = (planes, plane_parameters); + S_OK } +/// The bytes from one plane's description to the next in a present. +const PLANE_STRIDE: usize = 0x48; + +/// The first resource of a present's second plane, if it has one that is not +/// the first plane's (`first`): what is drawn over the first. +/// +/// # Safety +/// `parameters` is null or points at `planes` plane descriptions, +/// [`PLANE_STRIDE`] bytes apart, each listing `count` resources. +unsafe fn second_plane(planes: u32, parameters: *const Plane, first: This) -> Option<This> { + if planes < 2 || parameters.is_null() { + return None; + } + // SAFETY: the caller's: a second description follows the first. + let plane = unsafe { &*parameters.cast::<u8>().add(PLANE_STRIDE).cast::<Plane>() }; + if plane.count == 0 || plane.resources.is_null() { + return None; + } + // SAFETY: the caller's: the plane lists `count` resources. + let resource = unsafe { *plane.resources }; + (!resource.is_null() && resource != first).then_some(resource) +} + +#[cfg(test)] +mod plane_tests { + use super::*; + + /// Two plane descriptions as a title lays them out, [`PLANE_STRIDE`] + /// bytes apart, the second naming `count` resources at `resources`. + fn two(count: u32, resources: *const This) -> [u64; 2 * PLANE_STRIDE / 8] { + let mut words = [0u64; 2 * PLANE_STRIDE / 8]; + let second = PLANE_STRIDE / 8; + words[second] = 7; // frame token + words[second + 1] = u64::from(count); + words[second + 2] = resources as u64; + words + } + + #[test] + fn the_second_plane_is_chosen_only_when_it_names_another_resource() { + let (a, b) = (0x1000 as This, 0x2000 as This); + let other = [b]; + let same = [a]; + let none = [std::ptr::null::<crate::object::Object>()]; + // SAFETY: each description is a whole local array laid out as the + // title's; resource lists are local arrays of one. + unsafe { + let with_other = two(1, other.as_ptr()); + let p = with_other.as_ptr().cast::<Plane>(); + assert_eq!(second_plane(2, p, a), Some(b)); + // One plane, or no descriptions at all: nothing over the first. + assert_eq!(second_plane(1, p, a), None); + assert_eq!(second_plane(0, p, a), None); + assert_eq!(second_plane(2, std::ptr::null(), a), None); + // The same resource twice is not drawn over itself. + let with_same = two(1, same.as_ptr()); + assert_eq!(second_plane(2, with_same.as_ptr().cast(), a), None); + // An empty plane, a plane without a list, a null resource. + let empty = two(0, other.as_ptr()); + assert_eq!(second_plane(2, empty.as_ptr().cast(), a), None); + let unlisted = two(1, std::ptr::null()); + assert_eq!(second_plane(2, unlisted.as_ptr().cast(), a), None); + let with_null = two(1, none.as_ptr()); + assert_eq!(second_plane(2, with_null.as_ptr().cast(), a), None); + } + } +} + /// Diagnostics: logs a presented frame that is black after one that was /// not, with what was presented and how many draws ran since. #[cfg(all(windows, feature = "diagnostics"))] @@ -427,27 +1563,14 @@ pub(crate) struct PageBatch { /// Bytes per mapped page. const PAGE: u64 = 64 << 10; -/// One page-mapping operation captured from a batch at submission time. -#[derive(Clone, Copy)] -enum PageOp { - /// Map `len` consecutive pool bytes from `source` at `at`. - Copy { at: u64, source: u64, len: u64 }, - /// Map the single pool page at `source` repeatedly `count` times from `at`. - Fill { at: u64, source: u64, count: u64 }, - /// Unmap `len` bytes at `at`. - Unmap { at: u64, len: u64 }, - /// Out-of-bounds pool index, overflow, or unknown range kind. - Invalid, -} - /// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps /// pages of a pool (memory the title mapped physical pages into) at the -/// batches' addresses. Grand Theft Auto VI streams textures into pool pages +/// batches' addresses. The title streams textures into pool pages /// and maps them into its tiled heap this way (title+0xf2c470, ranges of -/// one constant page or of unmapped pages). Runs through the queue's -/// timeline so a held-back queue updates mappings after its earlier work. +/// one constant page or of unmapped pages). Done at once: every earlier +/// submission has run. extern "system" fn copy_page_mappings( - this: This, + _: This, count: u32, batches: *const PageBatch, pool: u64, @@ -460,15 +1583,15 @@ extern "system" fn copy_page_mappings( if batches.is_null() && count > 0 { return E_INVALIDARG; } - // Read now: the batch and range arrays belong to the title (often on its - // stack) and may be reused before a held-back queue runs them. let batches = (count > 0).then(|| { // SAFETY: the title passes `count` batches. unsafe { std::slice::from_raw_parts(batches, count as usize) } }); - let mut ops = Vec::new(); + let mut ok = true; + // The remapping meter: what the title asks for, by kind of range. + crate::framelog::add(crate::framelog::T::PageMapCalls, 1); for b in batches.into_iter().flatten() { - if b.ranges.is_null() || b.count == 0 { + if b.ranges.is_null() { continue; } // SAFETY: each batch holds `count` ranges. @@ -476,56 +1599,36 @@ extern "system" fn copy_page_mappings( let mut at = b.destination; for r in ranges { let len = u64::from(r.count) * PAGE; - let Some(next) = at.checked_add(len) else { - ops.push(PageOp::Invalid); - break; - }; let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages); - let source = || pool.checked_add(u64::from(r.start) * PAGE); - match r.kind { - 0 if inside(r.count) => match source() { - Some(source) => ops.push(PageOp::Copy { at, source, len }), - None => ops.push(PageOp::Invalid), - }, - 1 if inside(1) => match source() { - Some(source) => ops.push(PageOp::Fill { - at, - source, - count: u64::from(r.count), - }), - None => ops.push(PageOp::Invalid), - }, - 2 => ops.push(PageOp::Unmap { at, len }), - 3 => {} - _ => ops.push(PageOp::Invalid), + let source = pool + u64::from(r.start) * PAGE; + { + use crate::framelog::{T, add}; + let counted = match r.kind { + 0 => Some((T::PageMapRanges0, T::PageMapPages0)), + 1 => Some((T::PageMapRanges1, T::PageMapPages1)), + 2 => Some((T::PageMapRanges2, T::PageMapPages2)), + _ => None, + }; + if let Some((ranges, pages)) = counted { + add(ranges, 1); + add(pages, u64::from(r.count)); + } } - at = next; + ok &= match r.kind { + 0 if inside(r.count) => map(at, source, len), + 1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)), + 2 => map(at, 0, len), + 3 => true, + _ => false, + }; + at += len; } } - queue(this).timeline.submit(Op::Run(Box::new(move || { - apply_page_mappings(map, pool, &ops) - }))); - S_OK -} - -fn apply_page_mappings(map: crate::resource::PageMapper, pool: u64, ops: &[PageOp]) { - let mut ok = true; - for &op in ops { - ok &= match op { - PageOp::Copy { at, source, len } => map(at, source, len), - PageOp::Fill { at, source, count } => { - (0..count).all(|k| map(at + k * PAGE, source, PAGE)) - } - PageOp::Unmap { at, len } => map(at, 0, len), - PageOp::Invalid => false, - }; - } if !ok { static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed") - }); + ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed")); } + S_OK } extern "system" fn desc(this: This, out: *mut QueueDesc) { @@ -559,7 +1662,7 @@ const METHODS: [(usize, *const ()); 15] = [ /// Newer titles' queues have two more methods before Signal, which moved /// from 0x70 to 0x80: every slot from 0x70 on is two later (taken here as /// starting exactly at 0x70, the methods before it kept in place). -/// Inferred from Grand Theft Auto VI's calls: Signal 0x80 `(fence, +/// Inferred from the title's calls: Signal 0x80 `(fence, /// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume /// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count, /// lists, token, flags)` (title+0x24821dd). @@ -581,32 +1684,24 @@ const fn queue_table(newer: bool) -> [*const (); 36] { static FUNCTIONS: Table<36> = Table(queue_table(false)); static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true)); -#[cfg(test)] -pub(crate) fn test_queue() -> (This, usize) { - let desc = QueueDesc { - kind: 0, - priority: 0, - flags: 0, - nodes: 0, - }; - let mut q = std::ptr::null(); - assert_eq!( - create(std::ptr::null(), &desc, &QUEUE_IIDS[0], &mut q), - S_OK - ); - // SAFETY: one of our queues; its first field is the table. - let table = unsafe { *q.cast::<*const *const ()>() }; - let signal_slot = if table == NEWER_FUNCTIONS.0.as_ptr() { - 0x80 - } else { - 0x70 - }; - (q, signal_slot) -} - #[cfg(test)] mod tests { use super::*; + + #[cfg(windows)] + #[test] + fn joined_parts_keep_their_lists_and_their_order() { + // a part of three lists run as 2, 0, 1; then one of two run as 1, 0; then one of one + let (lists, order) = join(vec!["a0", "a1", "a2"], vec![2, 0, 1], vec!["b0", "b1"], vec![1, 0]); + let (lists, order) = join(lists, order, vec!["c0"], vec![0]); + assert_eq!(lists, ["a0", "a1", "a2", "b0", "b1", "c0"]); + let run: Vec<&str> = order.iter().map(|&i| lists[i]).collect(); + assert_eq!(run, ["a2", "a0", "a1", "b1", "b0", "c0"], "each part's lists in its own order, the parts one after the other"); + // a part with a list named twice, and an empty one + let (lists, order) = join(vec!["a0"], vec![0, 0], Vec::new(), Vec::new()); + let (lists, order) = join(lists, order, vec!["b0"], vec![0, 0]); + assert_eq!(order.iter().map(|&i| lists[i]).collect::<Vec<_>>(), ["a0", "a0", "b0", "b0"]); + } use crate::object::slot; /// Where a queue's signal is: newer layouts have it two slots later. @@ -650,292 +1745,7 @@ mod tests { assert_eq!(slot::<extern "system" fn(This) -> u32>(q, 0x10)(q), 0); } - /// Two queues: the first waits for a value the second signals later. - /// The first queue's signal after its wait must not complete before. - #[test] - fn work_after_a_wait_runs_once_the_other_queue_signals() { - type Call = extern "system" fn(This, This, u64) -> HRESULT; - let null = std::ptr::null(); - let desc = QueueDesc { - kind: 0, - priority: 0, - flags: 0, - nodes: 0, - }; - let (mut waits, mut signals) = (null, null); - assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut waits), S_OK); - assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut signals), S_OK); - let fence_iid = &crate::fence::FENCE_IIDS[0]; - let (mut ready, mut done) = (null, null); - assert_eq!( - crate::fence::create(null, 0, 0, fence_iid, &mut ready), - S_OK - ); - assert_eq!(crate::fence::create(null, 0, 0, fence_iid, &mut done), S_OK); - let completed = |f: This| slot::<extern "system" fn(This) -> u64>(f, 0x40)(f); - - let signal = |q: This| slot::<Call>(q, signal_slot(q)); - let wait = |q: This| slot::<Call>(q, signal_slot(q) + 8); - assert_eq!(wait(waits)(waits, ready, 1), S_OK); - assert_eq!(signal(waits)(waits, done, 1), S_OK); - assert_eq!(completed(done), 0, "ran before the value was reached"); - - assert_eq!(signal(signals)(signals, ready, 1), S_OK); - assert_eq!(completed(done), 1); - // Not held any more: work runs when submitted again. - assert_eq!(signal(waits)(waits, done, 2), S_OK); - assert_eq!(completed(done), 2); - - let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); - for object in [waits, signals, ready, done] { - assert_eq!(release(object), 0); - } - } - - /// A present submitted after a wait must not run until the wait is - /// reached, must read its stack plane parameters at submission time and - /// must keep its resource alive until it runs. - #[test] - fn present_runs_after_a_queues_wait() { - type Sync = extern "system" fn(This, This, u64) -> HRESULT; - type Present = extern "system" fn(This, u32, *const Plane, *const u8) -> HRESULT; - let null = std::ptr::null(); - let desc = QueueDesc { - kind: 0, - priority: 0, - flags: 0, - nodes: 0, - }; - let (mut waits, mut signals) = (null, null); - assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut waits), S_OK); - assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut signals), S_OK); - let fence_iid = &crate::fence::FENCE_IIDS[0]; - let (mut ready, mut done) = (null, null); - assert_eq!( - crate::fence::create(null, 0, 0, fence_iid, &mut ready), - S_OK - ); - assert_eq!(crate::fence::create(null, 0, 0, fence_iid, &mut done), S_OK); - let resource = crate::resource::test_buffer(256); - - let signal = |q: This| slot::<Sync>(q, signal_slot(q)); - let wait = |q: This| slot::<Sync>(q, signal_slot(q) + 8); - let present = |q: This| slot::<Present>(q, signal_slot(q) + 0x80); - let completed = |f: This| slot::<extern "system" fn(This) -> u64>(f, 0x40)(f); - let add_ref = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x08)(o); - let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); - - let before = FRAMES.load(Ordering::Relaxed); - assert_eq!(wait(waits)(waits, ready, 1), S_OK); - { - // Caller's plane parameters may live on its stack and be gone - // before the queue wakes. - let resources = Box::new([resource]); - let plane = Box::new(Plane { - token: 1, - count: 1, - resources: resources.as_ptr(), - }); - assert_eq!(present(waits)(waits, 1, &*plane, std::ptr::null()), S_OK); - } - assert_eq!(signal(waits)(waits, done, 1), S_OK); - - assert_eq!( - FRAMES.load(Ordering::Relaxed), - before, - "presented before the wait was reached" - ); - assert_eq!(completed(done), 0); - // The queued present holds a reference of its own. - assert_eq!(add_ref(resource), 3); - assert_eq!(release(resource), 2); - - assert_eq!(signal(signals)(signals, ready, 1), S_OK); - assert_eq!(FRAMES.load(Ordering::Relaxed), before + 1); - assert_eq!(completed(done), 1); - assert_eq!(release(resource), 0, "present gave back its reference"); - - // Not held any more: present runs at once. - assert_eq!( - present(waits)(waits, 0, std::ptr::null(), std::ptr::null()), - S_OK - ); - assert_eq!(FRAMES.load(Ordering::Relaxed), before + 2); - - for object in [waits, signals, ready, done] { - assert_eq!(release(object), 0); - } - } - - /// Page mappings submitted after a wait must not run until the wait is - /// reached, and must capture caller-owned batch/range arrays at call time. - #[test] - fn page_mappings_run_after_a_queues_wait() { - use std::sync::Mutex; - - static CALLS: Mutex<Vec<(u64, u64, u64)>> = Mutex::new(Vec::new()); - fn record(to: u64, from: u64, len: u64) -> bool { - CALLS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .push((to, from, len)); - true - } - crate::resource::use_page_mapper(record); - - type Sync = extern "system" fn(This, This, u64) -> HRESULT; - type CopyPages = extern "system" fn(This, u32, *const PageBatch, u64, u32, u32) -> HRESULT; - let null = std::ptr::null(); - let desc = QueueDesc { - kind: 0, - priority: 0, - flags: 0, - nodes: 0, - }; - let (mut waits, mut signals) = (null, null); - assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut waits), S_OK); - assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut signals), S_OK); - let fence_iid = &crate::fence::FENCE_IIDS[0]; - let (mut ready, mut done) = (null, null); - assert_eq!( - crate::fence::create(null, 0, 0, fence_iid, &mut ready), - S_OK - ); - assert_eq!(crate::fence::create(null, 0, 0, fence_iid, &mut done), S_OK); - - let signal = |q: This| slot::<Sync>(q, signal_slot(q)); - let wait = |q: This| slot::<Sync>(q, signal_slot(q) + 8); - let copy_pages = |q: This| slot::<CopyPages>(q, signal_slot(q) + 0x78); - let completed = |f: This| slot::<extern "system" fn(This) -> u64>(f, 0x40)(f); - let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); - - let pool = 0x1000_0000_u64; - let dst = 0x2000_0000_u64; - CALLS.lock().unwrap().clear(); - assert_eq!(wait(waits)(waits, ready, 1), S_OK); - { - // Heap-allocated so they are freed before the queue wakes. - let ranges = Box::new([ - PageRange { - kind: 0, - start: 1, - count: 2, - }, - PageRange { - kind: 1, - start: 3, - count: 2, - }, - PageRange { - kind: 2, - start: 0, - count: 1, - }, - PageRange { - kind: 3, - start: 0, - count: 1, - }, - ]); - let batch = Box::new(PageBatch { - destination: dst, - count: ranges.len() as u32, - ranges: ranges.as_ptr(), - }); - assert_eq!(copy_pages(waits)(waits, 1, &*batch, pool, 4, 0), S_OK); - } - assert_eq!(signal(waits)(waits, done, 1), S_OK); - - assert!( - CALLS.lock().unwrap().is_empty(), - "page mappings ran before the wait was reached" - ); - assert_eq!(completed(done), 0); - - assert_eq!(signal(signals)(signals, ready, 1), S_OK); - assert_eq!(completed(done), 1); - assert_eq!( - *CALLS.lock().unwrap(), - vec![ - (dst, pool + PAGE, 2 * PAGE), - (dst + 2 * PAGE, pool + 3 * PAGE, PAGE), - (dst + 3 * PAGE, pool + 3 * PAGE, PAGE), - (dst + 4 * PAGE, 0, PAGE), - ] - ); - - // Not held any more: runs at once. - CALLS.lock().unwrap().clear(); - let range = PageRange { - kind: 2, - start: 0, - count: 1, - }; - let batch = PageBatch { - destination: dst, - count: 1, - ranges: &range, - }; - assert_eq!(copy_pages(waits)(waits, 1, &batch, pool, 4, 0), S_OK); - assert_eq!(*CALLS.lock().unwrap(), vec![(dst, 0, PAGE)]); - - for object in [waits, signals, ready, done] { - assert_eq!(release(object), 0); - } - } - - /// A queue held back behind a fence whose memory is written directly - /// (bypassing `Signal` and bottom-of-pipe writes) wakes without needing - /// another submission on that queue. - #[test] - fn direct_memory_write_wakes_held_queue() { - type Sync = extern "system" fn(This, This, u64) -> HRESULT; - let null = std::ptr::null(); - let desc = QueueDesc { - kind: 0, - priority: 0, - flags: 0, - nodes: 0, - }; - let mut waits = null; - assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut waits), S_OK); - let fence_iid = &crate::fence::FENCE_IIDS[0]; - let (mut ready, mut done) = (null, null); - assert_eq!( - crate::fence::create(null, 0, 0, fence_iid, &mut ready), - S_OK - ); - assert_eq!(crate::fence::create(null, 0, 0, fence_iid, &mut done), S_OK); - - let signal = |q: This| slot::<Sync>(q, signal_slot(q)); - let wait = |q: This| slot::<Sync>(q, signal_slot(q) + 8); - let completed = |f: This| slot::<extern "system" fn(This) -> u64>(f, 0x40)(f); - let address = |f: This| slot::<extern "system" fn(This) -> u64>(f, 0x60)(f) as usize; - let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); - - assert_eq!(wait(waits)(waits, ready, 4), S_OK); - assert_eq!(signal(waits)(waits, done, 1), S_OK); - assert_eq!(completed(done), 0); - - // SAFETY: `address(ready)` is the fence's `AtomicU64` value. - unsafe { (*(address(ready) as *const AtomicU64)).store(4, Ordering::Release) }; - - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); - while completed(done) < 1 && std::time::Instant::now() < deadline { - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert_eq!( - completed(done), - 1, - "held queue did not wake on direct write" - ); - - for object in [waits, ready, done] { - assert_eq!(release(object), 0); - } - } - - /// Grand Theft Auto VI's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`. + /// The title's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`. #[test] fn console_queues_are_created_as_on_pc() { let null = std::ptr::null(); @@ -964,18 +1774,12 @@ mod tests { #[test] fn timestamps_and_values_are_written() { let mut at = [0u64; 2]; - Written::Value(0x1_0000_0002) - .write(at.as_mut_ptr().cast(), 4) - .run(); + Written::Value(0x1_0000_0002).write(at.as_mut_ptr().cast(), 4); assert_eq!(at[0], 2); - Written::GpuTimestamp - .write(at[1..].as_mut_ptr().cast(), 8) - .run(); + Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8); let first = at[1]; std::thread::sleep(std::time::Duration::from_millis(2)); - Written::GpuTimestamp - .write(at[1..].as_mut_ptr().cast(), 8) - .run(); + Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8); assert!(at[1] > first); } } diff --git a/crates/victory-gpu/src/queue2.rs b/crates/victory-gpu/src/queue2.rs new file mode 100644 index 0000000000..6d016d270e --- /dev/null +++ b/crates/victory-gpu/src/queue2.rs @@ -0,0 +1,1047 @@ +//! More queues on the card, for copies only (`VICTORY_QUEUE2`; off by +//! default): work of ours that does not depend on the order of the title's +//! draws goes to a copy queue of its own and no longer stands in the one +//! direct queue behind them. A copy queue runs on the card's copy engine, +//! beside the engine that draws. +//! +//! Two lanes, each a copy queue with a fence of its own, so that one never +//! stands behind the other: +//! +//! - **down** (bit 1): the fetch of the pieces shaders wrote in copies in +//! the card's memory (`Host::relay_card_back`, `Host::card_back`). With +//! the relay that fetch stood behind every flight sent since: 114-157 ms +//! a frame of the landing thread's 176-229 (run 118). +//! - **up** (bit 2): the title bytes that changed on the CPU's side of such +//! copies cross to the card's memory (`Host::card_before`), into a +//! landing buffer of ours there; the direct queue waits for them and +//! moves them on into the copies, inside the card's memory. +//! +//! What is synchronised, and with what: +//! +//! - A job of a lane may wait for fences of the direct queue +//! ([`Lane::send`]'s `after`: `ID3D12CommandQueue::Wait` on the lane's +//! queue). A fetch names the fence value behind the last flight it lands, +//! so it runs after that flight's lists and its compare. +//! - The direct queue waits for a job of the up lane ([`Second::hold`]: +//! `Wait` on the direct queue for the lane's fence), so nothing sent to +//! the direct queue afterwards runs before the bytes have landed. +//! - No wait can stand for ever: a job only ever waits for a value already +//! signalled on the direct queue, and the direct queue only for a job +//! already sent, so each wait's partner lies ahead of it in its queue. +//! - Only buffers go through the lanes. A buffer needs no state change for +//! a copy queue (it is promoted from the common state and falls back to +//! it), and it may be READ on one queue while another queue's work on it +//! is in the air; a texture may not, which is why no texture goes this +//! way. +//! - No lane WRITES a buffer that the direct queue's work in the air +//! names: the host's debug layer calls that an error ("not safe to start +//! write GPU operations now on this Command Queue", seen on the software +//! adapter with a first draft that copied title bytes straight into the +//! copies). Hence the landing buffers ([`Second::landing`]): each is +//! written by one job of the up lane and read by the direct queue behind +//! its wait for that job, and is given out again only when the card has +//! passed that read. The copies themselves change only on the direct +//! queue, in its order, as before. +//! - With the relay the sends of title bytes are numbered +//! (`crate::host::QUEUE_ORDER`). The direct queue signals each number +//! behind its send ([`Second::sent_up`]), and a fetch on the down lane +//! takes for "the sends ahead of me" those the card has finished +//! ([`Second::order_done`]). A later send that the card happens to run +//! before the fetch is left out by the merge as one that came after +//! (`Shadow::card_merge_relay`): the title's bytes stand, as they would. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::Interface; + +/// `VICTORY_QUEUE2`, a sum of bits; unset or 0: off, everything goes +/// through the one direct queue as before. +/// +/// - 1: fetches of what shaders wrote to copies in the card's memory go to +/// a copy queue (the gain is with `VICTORY_RELAY=1`/`2`; without the +/// relay nothing else is queued when they run, so it only shows that +/// the path works); +/// - 2: the title bytes sent up to copies in the card's memory cross from +/// the PC's memory on a copy queue, into landing buffers in the card's +/// memory ([`landing_most`] says how much of it), and the direct queue +/// moves them on from there. +/// +/// Read once, when the first submission asks. +pub(crate) fn bits() -> u32 { + static BITS: OnceLock<u32> = OnceLock::new(); + *BITS.get_or_init(|| std::env::var("VICTORY_QUEUE2").ok().and_then(|v| v.trim().parse::<u32>().ok()).unwrap_or(0) & 3) +} + +/// The most bytes of landing buffers in the card's memory, for title +/// bytes on their way to copies there (`VICTORY_QUEUE2_LANDING_MB`, 96; +/// a frame sent up 45-76 MB in runs 116-120, and a buffer is free again as +/// soon as the card has run the submission it was for). A send that finds +/// no room goes straight from the PC's memory on the direct queue, as +/// without the switch; the frame line counts those. +fn landing_most() -> u64 { + static MOST: OnceLock<u64> = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_QUEUE2_LANDING_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(96) << 20 + }) +} + +/// A buffer in the card's memory that title bytes land in. +struct Landing { + buffer: ID3D12Resource, + size: u64, + /// The value of the host's fence that the card passes after the direct + /// queue's last read of the buffer: free once it is reached. + until: u64, +} + +/// Which landing buffer (its size, and the fence value it is held until) +/// takes `bytes` when the host's fence has reached `completed`: the +/// smallest free one that holds them. +fn pick_landing(landings: &[(u64, u64)], bytes: u64, completed: u64) -> Option<usize> { + landings + .iter() + .enumerate() + .filter(|&(_, &(size, until))| until <= completed && size >= bytes) + .min_by_key(|&(_, &(size, _))| size) + .map(|(at, _)| at) +} + +/// An allocator and a list of the copy type. +pub(crate) type CopyList = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); + +/// Since the last frame-rate line, of one lane: jobs, their bytes, +/// microseconds the lane had a job (sent and not finished: its time on the +/// card and its waits for the direct queue's fences), microseconds a thread +/// of ours stood waiting for its jobs. +#[derive(Default)] +pub(crate) struct LaneStats { + pub(crate) jobs: AtomicU64, + pub(crate) bytes: AtomicU64, + pub(crate) busy_us: AtomicU64, + pub(crate) waited_us: AtomicU64, +} + +struct LaneState { + /// Jobs sent: the last value signalled on the lane's fence. + sent: u64, + /// Lists not in use, each with the job it last ran in: free for the + /// next job once the card has run that one. + spare: Vec<(u64, CopyList)>, + /// To the lane's clock: a job and when it was sent. + clock: Option<Sender<(u64, Instant)>>, +} + +/// A copy queue with a fence of its own; its jobs run in the order sent. +pub(crate) struct Lane { + device: ID3D12Device, + queue: ID3D12CommandQueue, + /// Signalled on `queue` behind each job with the job's number. + fence: ID3D12Fence, + state: Mutex<LaneState>, + pub(crate) stats: LaneStats, +} + +// SAFETY: D3D12 devices, queues, fences, allocators and lists are +// free-threaded objects; the lists are recorded by the thread that took +// them and otherwise touched under `state`. +unsafe impl Send for Lane {} +// SAFETY: as above. +unsafe impl Sync for Lane {} + +fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A lane's busy time grows by the stretch from `sent` (or from when the +/// job before it finished, `before`, if that was later: the lane was busy +/// with that one until then) to `done`. Returns the microseconds. +fn busy_stretch(before: Option<Instant>, sent: Instant, done: Instant) -> u64 { + let from = before.map_or(sent, |b| b.max(sent)); + done.saturating_duration_since(from).as_micros() as u64 +} + +impl Lane { + fn new(device: &ID3D12Device, name: &str) -> windows::core::Result<Lane> { + // SAFETY: plain object creation with valid descriptions. + unsafe { + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + ..Default::default() + })?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let wide: Vec<u16> = format!("victory copy queue ({name})").encode_utf16().chain([0]).collect(); + let _ = queue.SetName(windows::core::PCWSTR(wide.as_ptr())); + Ok(Lane { + device: device.clone(), + queue, + fence, + state: Mutex::new(LaneState { + sent: 0, + spare: Vec::new(), + clock: None, + }), + stats: LaneStats::default(), + }) + } + } + + /// Starts the lane's clock: a thread that waits for each job in turn + /// and adds up how long the lane had one ([`LaneStats::busy_us`]). + fn clocked(&'static self, name: &str) { + let (tx, rx) = channel(); + let started = std::thread::Builder::new().name(format!("victory-queue2-{name}")).spawn(move || self.watch(&rx)); + match started { + Ok(_) => lock(&self.state).clock = Some(tx), + Err(e) => tracing::warn!(error = %e, "no thread for a copy queue's clock: its milliseconds stay 0"), + } + } + + fn watch(&self, jobs: &Receiver<(u64, Instant)>) { + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + return; + }; + let mut before = None; + while let Ok((job, sent)) = jobs.recv() { + if self.wait(job, event).is_err() { + return; + } + let done = Instant::now(); + self.stats.busy_us.fetch_add(busy_stretch(before, sent, done), Ordering::Relaxed); + before = Some(done); + } + } + + /// An open list of the copy type: one whose last job the card has run, + /// or a new one. + pub(crate) fn list(&self) -> windows::core::Result<CopyList> { + // SAFETY: a plain query; a list is reset only when the job it ran + // in is done; plain object creation otherwise. + unsafe { + let done = self.fence.GetCompletedValue(); + let free = { + let mut state = lock(&self.state); + state.spare.iter().position(|(job, _)| *job <= done).map(|at| state.spare.swap_remove(at).1) + }; + if let Some((allocator, list)) = free { + allocator.Reset()?; + list.Reset(&allocator, None)?; + return Ok((allocator, list)); + } + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?; + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?; + Ok((allocator, list)) + } + } + + /// Closes `list` (from [`Lane::list`], with copies recorded) and sends + /// it as the lane's next job, of `bytes` bytes. The job runs behind + /// the lane's earlier jobs and not before each fence of `after` (fences + /// of other queues) has reached its value: every value must have been + /// signalled on its queue already. Returns the job's number, for + /// [`Lane::wait`], [`Lane::done`] and [`Second::hold`]. + pub(crate) fn send(&self, list: CopyList, after: &[(&ID3D12Fence, u64)], bytes: u64) -> windows::core::Result<u64> { + // SAFETY: an open list of ours; the lane's queue and fence; live + // fences of the same device. + unsafe { + list.1.Close()?; + let lists = [Some(list.1.cast::<ID3D12CommandList>()?)]; + // One job at a time from its waits to its signal: the jobs' + // numbers are the order they run in. + let mut state = lock(&self.state); + for &(fence, value) in after { + // (A fence is at 0 before anything is signalled on it: + // nothing to wait for.) + if value != 0 { + self.queue.Wait(fence, value)?; + } + } + self.queue.ExecuteCommandLists(&lists); + state.sent += 1; + let job = state.sent; + self.queue.Signal(&self.fence, job)?; + state.spare.push((job, list)); + if let Some(clock) = &state.clock { + let _ = clock.send((job, Instant::now())); + } + self.stats.jobs.fetch_add(1, Ordering::Relaxed); + self.stats.bytes.fetch_add(bytes, Ordering::Relaxed); + Ok(job) + } + } + + /// Whether the card has run `job`. + pub(crate) fn done(&self, job: u64) -> bool { + // SAFETY: a plain query. + unsafe { self.fence.GetCompletedValue() >= job } + } + + /// Waits on this thread, with its `event`, until the card has run + /// `job`. + pub(crate) fn wait(&self, job: u64, event: HANDLE) -> windows::core::Result<()> { + // SAFETY: the lane's fence and the caller's event. + unsafe { + if self.fence.GetCompletedValue() < job { + self.fence.SetEventOnCompletion(job, event)?; + WaitForSingleObject(event, INFINITE); + } + } + Ok(()) + } +} + +/// The copy queues and what ties them to the direct queue. +pub(crate) struct Second { + bits: u32, + device: ID3D12Device, + /// The landing buffers made so far ([`Second::landing`]). + landings: Mutex<Vec<Landing>>, + /// The landing buffers' bytes alive; since the last frame-rate line, + /// the sends that found no room in them. + pub(crate) landing: [AtomicU64; 2], + /// Fetches (bit 1). + pub(crate) down: Lane, + /// Sends of title bytes to copies in the card's memory (bit 2). + pub(crate) up: Lane, + /// Signalled on the DIRECT queue behind each numbered send of title + /// bytes, with its number ([`Second::sent_up`]). + order: ID3D12Fence, + /// Signalled on the DIRECT queue just ahead of each wait for the up + /// lane ([`Second::hold`]), for the clock: when the direct queue got + /// there. Behind the lock: the holds made so far, and the way to the + /// thread that times them. + reached: ID3D12Fence, + holds: Mutex<(u64, Option<Sender<(u64, u64)>>)>, + /// Since the last frame-rate line: waits of the direct queue for the up + /// lane, those of them at which it stood, and for how many + /// microseconds. + pub(crate) held: [AtomicU64; 3], +} + +// SAFETY: fences (free-threaded) and lanes. +unsafe impl Send for Second {} +// SAFETY: as above. +unsafe impl Sync for Second {} + +impl Second { + /// The lanes on `device`. `bits` as [`bits`]. + pub(crate) fn new(device: &ID3D12Device, bits: u32) -> windows::core::Result<Second> { + // SAFETY: plain fences on the device. + unsafe { + Ok(Second { + bits, + device: device.clone(), + landings: Mutex::new(Vec::new()), + landing: [const { AtomicU64::new(0) }; 2], + down: Lane::new(device, "down")?, + up: Lane::new(device, "up")?, + order: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?, + reached: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?, + holds: Mutex::new((0, None)), + held: [const { AtomicU64::new(0) }; 3], + }) + } + } + + /// Starts the clocks: the lanes' and the one that times the direct + /// queue's waits ([`Second::held`]). + pub(crate) fn clocked(&'static self) { + self.down.clocked("down"); + self.up.clocked("up"); + let (tx, rx) = channel(); + match std::thread::Builder::new().name("victory-queue2-holds".into()).spawn(move || self.watch_holds(&rx)) { + Ok(_) => lock(&self.holds).1 = Some(tx), + Err(e) => tracing::warn!(error = %e, "no thread to time the direct queue's waits for the copy queue: they stay 0"), + } + } + + /// Whether fetches go to the down lane. + pub(crate) fn fetches(&self) -> bool { + self.bits & 1 != 0 + } + + /// Whether title bytes go up through the up lane. + pub(crate) fn uploads(&self) -> bool { + self.bits & 2 != 0 + } + + /// A buffer in the card's memory for `bytes` title bytes on their way + /// up, for a job of the up lane to write and the direct queue to read + /// behind its wait for that job ([`Second::hold`]). `completed`: the + /// value the host's fence has reached; `until`: the value it reaches + /// when the card has run that read (the next one signalled behind + /// it). The buffer is not given out again before then, so no job + /// writes it while anything in the air names it. `None`: no room under + /// [`landing_most`], or no memory; the caller sends the bytes the old + /// way. + pub(crate) fn landing(&self, bytes: u64, completed: u64, until: u64) -> Option<ID3D12Resource> { + let mut landings = lock(&self.landings); + let sizes: Vec<(u64, u64)> = landings.iter().map(|l| (l.size, l.until)).collect(); + if let Some(at) = pick_landing(&sizes, bytes, completed) { + landings[at].until = until; + return Some(landings[at].buffer.clone()); + } + // A new one; free ones that are too small make room for it (the + // card has passed their last use: nothing names them). + let size = bytes.next_multiple_of(1 << 20); + let alive = |landings: &[Landing]| landings.iter().map(|l| l.size).sum::<u64>(); + if alive(&landings) + size > landing_most() { + landings.retain(|l| l.until > completed); + } + let made = if alive(&landings) + size > landing_most() { + None + } else { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation of a buffer in the card's memory. + let made = unsafe { + self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + }; + match (made, buffer) { + (Ok(()), Some(buffer)) => { + let wide: Vec<u16> = "victory landing buffer (title bytes on their way up)".encode_utf16().chain([0]).collect(); + // SAFETY: a live buffer and a terminated string. + let _ = unsafe { buffer.SetName(windows::core::PCWSTR(wide.as_ptr())) }; + landings.push(Landing { + buffer: buffer.clone(), + size, + until, + }); + Some(buffer) + } + _ => None, + } + }; + self.landing[0].store(alive(&landings), Ordering::Relaxed); + if made.is_none() { + self.landing[1].fetch_add(1, Ordering::Relaxed); + } + made + } + + /// The numbered send `number` of title bytes has just gone to `direct` + /// (or there was nothing to send under that number): the number is + /// signalled behind it. + pub(crate) fn sent_up(&self, direct: &ID3D12CommandQueue, number: u64) { + // SAFETY: a live queue and our fence. + let _ = unsafe { direct.Signal(&self.order, number) }; + } + + /// The last numbered send of title bytes the card has finished: every + /// send up to it is in what a fetch sent from now on brings down. + pub(crate) fn order_done(&self) -> u64 { + // SAFETY: a plain query. + unsafe { self.order.GetCompletedValue() } + } + + /// Makes `direct` wait for `job` of the up lane: nothing sent to it + /// from now on runs before the card has run the job. The job must have + /// been sent ([`Lane::send`]). + pub(crate) fn hold(&self, direct: &ID3D12CommandQueue, job: u64) -> windows::core::Result<()> { + let mut holds = lock(&self.holds); + holds.0 += 1; + // SAFETY: a live queue and our fences. + unsafe { + // For the clock only: the moment the queue gets to the wait. + let _ = direct.Signal(&self.reached, holds.0); + direct.Wait(&self.up.fence, job)?; + } + self.held[0].fetch_add(1, Ordering::Relaxed); + if let Some(clock) = &holds.1 { + let _ = clock.send((holds.0, job)); + } + Ok(()) + } + + /// Times the holds, in the order they were made: from the moment the + /// direct queue got to one until the job it waits for is done. (While + /// it stands at one it gets to no later one, so one thread sees each + /// in time.) + fn watch_holds(&self, holds: &Receiver<(u64, u64)>) { + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + return; + }; + while let Ok((hold, job)) = holds.recv() { + // SAFETY: our fence and this thread's event. + unsafe { + if self.reached.GetCompletedValue() < hold { + if self.reached.SetEventOnCompletion(hold, event).is_err() { + return; + } + WaitForSingleObject(event, INFINITE); + } + } + if self.up.done(job) { + continue; + } + let standing = Instant::now(); + if self.up.wait(job, event).is_err() { + return; + } + self.held[1].fetch_add(1, Ordering::Relaxed); + self.held[2].fetch_add(standing.elapsed().as_micros() as u64, Ordering::Relaxed); + } + } +} + +/// The copy queues, made at the first ask if [`bits`] says so; `None` when +/// the switch is off or they could not be made (everything then goes +/// through the direct queue, as before). +pub(crate) fn second() -> Option<&'static Second> { + static SECOND: OnceLock<Option<Second>> = OnceLock::new(); + static CLOCKS: std::sync::Once = std::sync::Once::new(); + if bits() == 0 { + return None; + } + let second = SECOND + .get_or_init(|| { + let host = crate::host::host()?; + match Second::new(&host.device, bits()) { + Ok(second) => { + tracing::info!( + fetches = second.fetches(), + uploads = second.uploads(), + landing_mb = landing_most() >> 20, + "copy queues on the card beside the direct queue (VICTORY_QUEUE2={})", + bits() + ); + Some(second) + } + Err(e) => { + tracing::warn!(error = %e, "no copy queues (VICTORY_QUEUE2): everything goes through the direct queue"); + None + } + } + }) + .as_ref()?; + CLOCKS.call_once(|| second.clocked()); + Some(second) +} + +/// For the frame-rate line: what the copy queues did per frame since the +/// last one. "On their queue" is from a job's send to its end with each +/// moment counted once: its time on the card and any wait of its queue +/// for the direct queue's fences. The direct queue "stood" at a wait if +/// the job was not done when it got there. +pub(crate) fn line(frames: f64) { + let Some(second) = second() else { + return; + }; + let take = |a: &AtomicU64| a.swap(0, Ordering::Relaxed) as f64 / frames; + let ms = |a: &AtomicU64| take(a) / 1000.0; + let mb = |a: &AtomicU64| take(a) / (1 << 20) as f64; + let (down, up) = (&second.down.stats, &second.up.stats); + let (down_jobs, down_mb, down_busy, down_waited) = (take(&down.jobs), mb(&down.bytes), ms(&down.busy_us), ms(&down.waited_us)); + let (up_jobs, up_mb, up_busy) = (take(&up.jobs), mb(&up.bytes), ms(&up.busy_us)); + let [holds, stood, stood_us] = [0, 1, 2].map(|i| take(&second.held[i])); + let (landing_mb, no_room) = (second.landing[0].load(Ordering::Relaxed) >> 20, take(&second.landing[1])); + tracing::info!( + "the copy queues per frame (VICTORY_QUEUE2={}): fetches of what shaders wrote: {down_jobs:.1} jobs, {down_mb:.1} MB, \ + {down_busy:.1} ms on their queue, our threads stood {down_waited:.1} ms waiting for them; title bytes sent up: \ + {up_jobs:.1} jobs, {up_mb:.1} MB, {up_busy:.1} ms on their queue; the direct queue was told to wait for them \ + {holds:.1} times and stood at {stood:.1} of those for {:.1} ms in all; landing buffers on the card: {landing_mb} MB, \ + {no_room:.1} sends found no room in them and went through the direct queue (VICTORY_QUEUE2_LANDING_MB)", + second.bits, + stood_us / 1000.0 + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + use windows::core::s; + + /// A lane's busy time counts each moment once: a job sent while the + /// one before it still ran adds only what came after that one. + #[test] + fn a_lanes_busy_time_counts_each_moment_once() { + let t = Instant::now(); + let at = |ms: u64| t + std::time::Duration::from_millis(ms); + // Alone: from the send to the end. + assert_eq!(busy_stretch(None, at(10), at(14)), 4_000); + // Sent at 10 while the job before ran until 12: 12 to 14. + assert_eq!(busy_stretch(Some(at(12)), at(10), at(14)), 2_000); + // Sent after the one before had finished: from the send. + assert_eq!(busy_stretch(Some(at(5)), at(10), at(14)), 4_000); + // (The clock's own lateness never makes a stretch negative.) + assert_eq!(busy_stretch(Some(at(20)), at(10), at(14)), 0); + } + + /// A landing buffer is given out again only when the card has passed + /// its last use, and the smallest one that holds the bytes is taken. + #[test] + fn a_landing_buffer_is_free_when_the_card_has_passed_its_use() { + // (size, held until this value of the host's fence) + let landings = [(4 << 20, 10), (1 << 20, 12), (2 << 20, 7), (8 << 20, 7)]; + // The card is at 9: the third and fourth are free. + assert_eq!(pick_landing(&landings, 1 << 20, 9), Some(2)); + assert_eq!(pick_landing(&landings, 3 << 20, 9), Some(3)); + assert_eq!(pick_landing(&landings, 9 << 20, 9), None); + // At 10 the first is free too, and is the smallest for 3 MiB. + assert_eq!(pick_landing(&landings, 3 << 20, 10), Some(0)); + // At 6 none is: a use that the card has not passed holds its buffer. + assert_eq!(pick_landing(&landings, 1, 6), None); + // The value itself frees it (the signal is behind the read). + assert_eq!(pick_landing(&landings, 1, 7), Some(2)); + assert_eq!(pick_landing(&[], 1, u64::MAX), None); + } + + /// A shader of the direct queue that takes a while and then stores a + /// dword: `at` (bytes) gets `value`. + const SLOW_STORE: &str = r#" +#define RS "RootConstants(num32BitConstants=3, b0), UAV(u0)" +cbuffer What : register(b0) { uint at; uint value; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint h = value; + [loop] + for (uint i = 0; i < spin; i++) { + h = (h ^ memory.Load((i & 63u) * 4u)) * 0x01000193u; + } + memory.Store(at, value + (h & 0u)); +} +"#; + + /// The software adapter with a direct queue and the copy queues. + struct Warp { + device: ID3D12Device, + direct: ID3D12CommandQueue, + /// The direct queue's fence and the last value signalled on it. + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + second: &'static Second, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// Direct lists sent and not waited for yet. + flown: Vec<CopyList>, + } + + impl Warp { + fn new(bits: u32) -> Option<Warp> { + // SAFETY: plain DXGI and D3D12 set-up on the software adapter. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option<ID3D12Device> = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let direct: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + // The clocks' threads live as long as the process: the + // queues of a test are kept for them. + let second: &'static Second = Box::leak(Box::new(Second::new(&device, bits).expect("copy queues on WARP"))); + second.clocked(); + let mut code: Option<ID3DBlob> = None; + D3DCompile( + SLOW_STORE.as_ptr().cast(), + SLOW_STORE.len(), + s!("slow store"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + None, + ) + .expect("the test's shader compiles"); + let code = code?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes).ok()?; + let pso: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + }) + .ok()?; + Some(Warp { + device, + direct, + fence, + submitted: 0, + event, + second, + root, + pso, + flown: Vec::new(), + }) + } + } + + /// A buffer as the host makes them: in the card's own memory + /// (`Host::uav_buffer`), or in the PC's memory and mapped + /// (`Host::shared_buffer`). + fn buffer(&self, size: u64, mapped: bool) -> (ID3D12Resource, *mut u8) { + let heap = if mapped { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + } + } else { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + } + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation, and a mapping of CPU-visible memory. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .expect("a test buffer"); + let buffer = buffer.expect("a test buffer"); + if mapped { + buffer.Map(0, None, Some(&mut data)).expect("a mapping"); + } + (buffer, data.cast()) + } + } + + /// Sends a list of the direct queue made by `record`, with a + /// signal behind it, and does not wait: the value signalled. + fn fly(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> u64 { + // SAFETY: plain creation; an open list of ours; our queue and + // fence. + unsafe { + let allocator: ID3D12CommandAllocator = + self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("an allocator"); + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).expect("a list"); + record(&list); + list.Close().expect("the list closes"); + self.direct.ExecuteCommandLists(&[Some(list.cast().expect("a command list"))]); + self.submitted += 1; + self.direct.Signal(&self.fence, self.submitted).expect("a signal"); + self.flown.push((allocator, list)); + } + self.submitted + } + + /// A direct list that stores `value` at byte `at` of `memory` + /// after `spin` steps. + fn store(&mut self, memory: &ID3D12Resource, at: u32, value: u32, spin: u32) -> u64 { + let (root, pso) = (self.root.clone(), self.pso.clone()); + // SAFETY: a live buffer with unordered access; the shader's + // own root signature. + self.fly(|list| unsafe { + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + let constants = [at, value, spin]; + list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.SetComputeRootUnorderedAccessView(1, memory.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + }) + } + + /// Waits for everything sent to the direct queue and the lanes. + fn land(&mut self) { + // SAFETY: our fence and event. + unsafe { + self.fence.SetEventOnCompletion(self.submitted, self.event).expect("a wait"); + WaitForSingleObject(self.event, INFINITE); + } + for lane in [&self.second.down, &self.second.up] { + let last = lock(&lane.state).sent; + lane.wait(last, self.event).expect("a wait"); + } + assert!( + // SAFETY: a plain query. + unsafe { self.device.GetDeviceRemovedReason() }.is_ok(), + "the software adapter lost the device" + ); + self.flown.clear(); + } + } + + /// The dwords of a mapped buffer. + fn dwords(data: *mut u8, at: usize, n: usize) -> Vec<u32> { + // SAFETY: the caller's mapping holds them. + (0..n).map(|i| unsafe { data.cast::<u32>().add(at + i).read_volatile() }).collect() + } + + /// What shaders wrote, read back through the down lane, is what the + /// direct queue reads back: the same bytes of a buffer in the card's + /// memory come down both ways, and the lane's copy is behind the fence + /// of the submission that wrote them without any wait of ours between. + #[test] + fn warp_a_fetch_through_the_copy_queue_brings_what_the_direct_queue_brings() { + let Some(mut warp) = Warp::new(1) else { + return; + }; + const DWORDS: usize = 4096; + let bytes = (DWORDS * 4) as u64; + let (card, _) = warp.buffer(bytes, false); + let (down_direct, direct_data) = warp.buffer(bytes, true); + let (down_lane, lane_data) = warp.buffer(bytes, true); + for round in 1..=3u32 { + // "Shader writes": a few dwords, each by a dispatch. + let mut behind = 0; + for i in 0..24u32 { + behind = warp.store(&card, (i * 163 % DWORDS as u32) * 4, round * 1000 + i, 20_000); + } + // Through the lane, behind the writes' fence; no wait of ours. + let second = warp.second; + let list = second.down.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&down_lane, 0, &card, 0, bytes) }; + let job = second.down.send(list, &[(&warp.fence, behind)], bytes).expect("the fetch is sent"); + // And through the direct queue, as before. + // SAFETY: an open list; live buffers. + warp.fly(|list| unsafe { list.CopyBufferRegion(&down_direct, 0, &card, 0, bytes) }); + second.down.wait(job, warp.event).expect("the fetch is waited for"); + assert!(second.down.done(job)); + warp.land(); + let (direct, lane) = (dwords(direct_data, 0, DWORDS), dwords(lane_data, 0, DWORDS)); + assert_eq!(direct, lane, "round {round}: the two ways brought different bytes"); + for i in 0..24u32 { + assert_eq!(lane[(i * 163 % DWORDS as u32) as usize], round * 1000 + i, "round {round}, write {i}"); + } + } + assert_eq!(warp.second.down.stats.jobs.load(Ordering::Relaxed), 3); + } + + /// Ordering under the fences, nothing waited for on the CPU: write k + /// goes to the direct queue with a signal behind it, and fetch k, sent + /// at once to the lane behind that signal, must hold writes 1..=k + /// (later writes may or may not be in it: they are newer, never + /// older). Sixteen of each are in the air together. + #[test] + fn warp_a_fetch_behind_a_fence_holds_everything_sent_before_that_fence() { + let Some(mut warp) = Warp::new(1) else { + return; + }; + const N: usize = 16; + let bytes = (N * 4) as u64; + let (card, _) = warp.buffer(64 << 10, false); + let (down, data) = warp.buffer(bytes * N as u64, true); + let second = warp.second; + for k in 0..N { + let behind = warp.store(&card, (k * 4) as u32, 0xA000 + k as u32, 60_000); + let list = second.down.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers; the slot is inside. + unsafe { list.1.CopyBufferRegion(&down, k as u64 * bytes, &card, 0, bytes) }; + second.down.send(list, &[(&warp.fence, behind)], bytes).expect("the fetch is sent"); + } + warp.land(); + for k in 0..N { + let slot = dwords(data, k * N, N); + for (i, &got) in slot.iter().enumerate().take(k + 1) { + assert_eq!(got, 0xA000 + i as u32, "fetch {k} ran before write {i}, which was sent before its fence"); + } + for (i, &got) in slot.iter().enumerate().skip(k + 1) { + assert!(got == 0 || got == 0xA000 + i as u32, "fetch {k} holds {got:#x} for write {i}"); + } + } + } + + /// Title bytes sent up through the up lane are there when the direct + /// queue goes on: each of sixteen sends is followed, with no wait of + /// ours, by a direct list that reads the buffer back, and each read + /// holds its own send and all before it. Each send is made late on + /// purpose (it stands behind a slow list of the direct queue), so the + /// read would come first if the direct queue did not wait. The + /// numbered sends are signalled in order, and the clock saw the holds. + #[test] + fn warp_the_direct_queue_goes_on_only_when_what_was_sent_up_is_there() { + let Some(mut warp) = Warp::new(3) else { + return; + }; + const N: usize = 16; + const PART: u64 = 64 << 10; + let (staging, staged) = warp.buffer(PART * N as u64, true); + // A buffer in the card's memory per send: the lane writes one that + // nothing in the air names yet (as it writes landing buffers). + let cards: Vec<ID3D12Resource> = (0..N).map(|_| warp.buffer(PART, false).0).collect(); + let (other, _) = warp.buffer(64 << 10, false); + // What each read brings: the first dword of every part. + let (down, data) = warp.buffer((N * N * 4) as u64, true); + let second = warp.second; + for k in 0..N { + // The title's bytes of part k (the CPU's side of the copy). + for i in 0..(PART as usize / 4) { + // SAFETY: inside the mapping; nothing on the card reads + // part k before the send below. + unsafe { staged.cast::<u32>().add(k * (PART as usize / 4) + i).write_volatile(0xB000 + k as u32) }; + } + let slow = warp.store(&other, 0, k as u32, 80_000); + let list = second.up.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&cards[k], 0, &staging, k as u64 * PART, PART) }; + let job = second.up.send(list, &[(&warp.fence, slow)], PART).expect("the bytes are sent up"); + second.hold(&warp.direct, job).expect("the direct queue waits"); + second.sent_up(&warp.direct, k as u64 + 1); + // SAFETY: an open list; live buffers; the slots are inside. + warp.fly(|list| unsafe { + for (part, card) in cards.iter().enumerate().take(k + 1) { + list.CopyBufferRegion(&down, ((k * N + part) * 4) as u64, card, 0, 4); + } + }); + } + warp.land(); + assert_eq!(second.order_done(), N as u64); + for k in 0..N { + let read = dwords(data, k * N, N); + for (part, &got) in read.iter().enumerate().take(k + 1) { + assert_eq!(got, 0xB000 + part as u32, "the direct queue's read {k} ran before send {part} was on the card"); + } + } + assert_eq!(second.held[0].load(Ordering::Relaxed), N as u64); + assert_eq!(second.up.stats.bytes.load(Ordering::Relaxed), PART * N as u64); + } + + /// The way title bytes go up with bit 2, as `Host::card_before` does + /// it: a job of the up lane brings them into a landing buffer while a + /// slow list of the direct queue is still running, the direct queue + /// waits for the job and then copies from the landing buffer into the + /// copy. A shader's store to the same bytes, sent before, must lose to + /// them (the copy changes in the direct queue's order, as on one + /// queue), and what a fetch through the down lane brings is what the + /// direct queue reads. Twelve rounds in the air together, each with a + /// landing buffer of its own until the card has passed its use. + #[test] + fn warp_title_bytes_reach_the_copy_through_a_landing_buffer_in_the_direct_queues_order() { + let Some(mut warp) = Warp::new(3) else { + return; + }; + const N: usize = 12; + let (staging, staged) = warp.buffer(64 << 10, true); + let (card, _) = warp.buffer(64 << 10, false); + let (down, data) = warp.buffer((N * 4) as u64, true); + let (down_lane, lane_data) = warp.buffer((N * 4) as u64, true); + let second = warp.second; + let mut landings = Vec::new(); + for k in 0..N { + let at = (k * 256) as u64; + // SAFETY: inside the mapping; read by the card only through + // the job below. + unsafe { staged.add(at as usize).cast::<u32>().write_volatile(0xC000 + k as u32) }; + // A shader's (slow) store to the same dword, sent first. + warp.store(&card, at as u32, 0xDEAD_0000 + k as u32, 80_000); + // SAFETY: a plain query. + let completed = unsafe { warp.fence.GetCompletedValue() }; + let landing = second.landing(4, completed, warp.submitted + 1).expect("a landing buffer"); + let list = second.up.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&landing, 0, &staging, at, 4) }; + let job = second.up.send(list, &[], 4).expect("the bytes are sent up"); + second.hold(&warp.direct, job).expect("the direct queue waits"); + // SAFETY: an open list; live buffers. + let read = warp.fly(|list| unsafe { + list.CopyBufferRegion(&card, at, &landing, 0, 4); + list.CopyBufferRegion(&down, (k * 4) as u64, &card, at, 4); + }); + let list = second.down.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&down_lane, (k * 4) as u64, &card, at, 4) }; + second.down.send(list, &[(&warp.fence, read)], 4).expect("the fetch is sent"); + landings.push(landing.as_raw() as usize); + } + warp.land(); + let want: Vec<u32> = (0..N).map(|k| 0xC000 + k as u32).collect(); + assert_eq!(dwords(data, 0, N), want, "the title's bytes did not reach the copy behind the shader's store"); + assert_eq!(dwords(lane_data, 0, N), want, "the copy queue's fetch differs from the direct queue's"); + // No buffer was given out while its last use was in the air: one + // given to two rounds was free in between. + landings.sort_unstable(); + landings.dedup(); + assert!(!landings.is_empty() && landings.len() <= N); + // Everything has run: the next ask takes one of them, makes none. + let alive = second.landing[0].load(Ordering::Relaxed); + // SAFETY: a plain query. + let completed = unsafe { warp.fence.GetCompletedValue() }; + let again = second.landing(4, completed, warp.submitted + 1).expect("a landing buffer"); + assert!(landings.contains(&(again.as_raw() as usize))); + assert_eq!(second.landing[0].load(Ordering::Relaxed), alive); + } + + /// Lists of a lane come back for the next job once the card has run + /// the job they were in, and not before. + #[test] + fn warp_a_lanes_lists_are_used_again_only_after_their_job() { + let Some(mut warp) = Warp::new(1) else { + return; + }; + let (card, _) = warp.buffer(64 << 10, false); + let (down, _) = warp.buffer(64 << 10, true); + let second = warp.second; + // A job that cannot run yet: it waits for a fence value the direct + // queue reaches only after a slow store. + let behind = warp.store(&card, 0, 1, 400_000); + let first = second.down.list().expect("a copy list"); + let first_list = first.1.as_raw(); + // SAFETY: an open copy list; live buffers. + unsafe { first.1.CopyBufferRegion(&down, 0, &card, 0, 64) }; + let job = second.down.send(first, &[(&warp.fence, behind)], 64).expect("sent"); + if !second.down.done(job) { + // Still in the air: the next list is another one. + let next = second.down.list().expect("a copy list"); + assert_ne!(next.1.as_raw(), first_list, "a list was reset while its job had not run"); + second.down.send(next, &[], 0).expect("sent"); + } + warp.land(); + // Everything has run: a list of before comes back. + let again = second.down.list().expect("a copy list"); + let spare_left = lock(&second.down.state).spare.len(); + assert!(spare_left <= 1, "lists that have run are taken before new ones are made"); + second.down.send(again, &[], 0).expect("sent"); + warp.land(); + } +} diff --git a/crates/victory-gpu/src/rectangles.rs b/crates/victory-gpu/src/rectangles.rs deleted file mode 100644 index 441d5eb8b3..0000000000 --- a/crates/victory-gpu/src/rectangles.rs +++ /dev/null @@ -1,1276 +0,0 @@ -//! GPU-side expansion of indirect rectangle-list draws (the console's -//! topology 17, `ExecuteIndirect` kind 0). Direct rectangle draws expand -//! their vertices on the CPU ([`crate::primitive::expand_rects`]); indirect -//! draws only know their vertex counts on the GPU, so after -//! [`crate::indirect::clamp_uav`] bounds each record, two compute passes of -//! ours run before `ExecuteIndirect`: -//! -//! 1. `rect_rewrite` reads each live record (skipping records at or past the -//! title's count, 0-instance draws, and records whose source vertices -//! `start..start + 3 * rects` reach past any bound per-vertex vertex -//! buffer), allocates `rects * 6` output vertices from a list-owned -//! scratch buffer with an atomic counter, and writes a packed 16-byte -//! `D3D12_DRAW_ARGUMENTS` copy into a list-owned arguments buffer. The -//! title's arguments are left as the clamp made them. -//! 2. `rect_expand` runs once per per-vertex input slot, writing -//! `(v0, v1, v2, v0, v2, v3)` into that slot's scratch region with -//! `v3 = v0 + v2 - v1` for the formats and in-stride components that -//! [`crate::primitive::expand_rects`] computes. -//! -//! Both passes read structured buffers of words and take root signatures -//! built here, so Wine's HLSL compiler (vkd3d-shader, no raw buffer -//! methods or embedded root signatures) builds them too. -//! -//! `ExecuteIndirect` then reads our arguments (with the title's count, if -//! any) and the expanded vertices; transitions afterwards return the scratch -//! buffers to unordered access, so the next indirect rectangle draw of the -//! list reuses the whole scratch. -//! -//! shortcut: the per-list vertex scratch has a fixed capacity of 8 MiB -//! ([`RECT_SCRATCH_BYTES`]), shared by the records of one draw; records whose -//! expanded vertices do not fit draw nothing. Raise it if a single indirect -//! draw needs more. -//! -//! shortcut: as in [`crate::primitive`], the fourth corner is computed from -//! vertex inputs rather than vertex shader outputs; formats unknown to -//! [`crate::primitive::components`] and components past the vertex stride -//! keep the first vertex's bytes. A pipeline without per-vertex inputs (one -//! that builds its corners from the vertex id) gets `6 * rects` vertices from -//! 0, as a direct draw does. With inputs, the vertex id is the expanded one -//! from the allocated start, whose order between records may change from run -//! to run. Vertex strides not a multiple of 4 are padded up to 4 bytes in the -//! scratch (and bound with that stride), so threads never share a 32-bit word -//! across vertices. -//! -//! The rewrite pass bounds counts and instances itself, as the clamp does, so -//! it stays safe whether or not the clamp writes its results back in place. - -use std::sync::Arc; - -use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -use windows::Win32::Graphics::Direct3D::ID3DBlob; -use windows::Win32::Graphics::Direct3D12::*; -use windows::core::s; - -use crate::draw::VertexView; -use crate::host::{HostList, host, transition}; -use crate::indirect::uav_barrier; -use crate::pipeline::host::{HostPipeline, Input}; -use crate::primitive; -use crate::shadow::Shadow; - -/// Per-list GPU-writable vertex scratch capacity (8 MiB), reused per draw. -pub(crate) const RECT_SCRATCH_BYTES: u64 = 8 << 20; - -/// Maximum records supported by one 1D `[numthreads(64, 1, 1)]` pass. -const MAX_RECORDS: u32 = 65535 * 64; - -/// Maximum thread groups per dispatch dimension (D3D12 spec). -const MAX_GROUPS_PER_DIM: u32 = 65535; - -/// One per-vertex input element passed to `rect_expand` (8 bytes). -#[repr(C)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) struct Element { - /// Byte offset inside the source (and destination) vertex. - pub(crate) offset: u32, - /// Low byte: [`primitive::Kind::code`]; bits 8..32: component count inside - /// the vertex stride (1..=4). - pub(crate) packed: u32, -} - -/// Scratch layout for one per-vertex input slot inside the list's vertex -/// scratch buffer. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) struct SlotLayout { - pub(crate) slot: u32, - /// 16-byte aligned byte offset from the start of the scratch buffer. - pub(crate) dst_offset: u64, - /// 4-byte aligned stride in the scratch buffer. - pub(crate) dst_stride: u32, - /// Total byte size of this slot's scratch region (`vert_capacity * dst_stride`). - pub(crate) dst_size: u32, -} - -/// Builds the GPU element table for `slot` with vertex `stride`, matching -/// [`crate::primitive::expand_rects`]. Returns `(has_per_vertex, elements)`: -/// `has_per_vertex` is true when the pipeline has at least one per-vertex input -/// on `slot` (even if none of its formats are recognized, in which case the -/// slot is still expanded with `v3 = v0`). -pub(crate) fn slot_elements(inputs: &[Input], slot: u32, stride: u32) -> (bool, Vec<Element>) { - let mut has_per_vertex = false; - let mut out = Vec::new(); - let stride = stride as usize; - for e in inputs { - if e.slot != slot || e.per_instance { - continue; - } - has_per_vertex = true; - let Some((n, kind)) = primitive::components(e.format) else { - continue; - }; - let inside = stride.saturating_sub(e.offset as usize) / kind.bytes(); - let count = n.min(inside) as u32; - if count == 0 { - continue; - } - out.push(Element { - offset: e.offset, - packed: kind.code() | (count << 8), - }); - } - (has_per_vertex, out) -} - -/// Lays out disjoint, 16-byte aligned scratch regions for every per-vertex -/// `(slot, src_stride)` inside `capacity_bytes`, sharing one vertex index space -/// `0..vert_capacity`. Returns `(vert_capacity, layouts)`, with `vert_capacity` -/// rounded down to a multiple of 6 (whole rectangles). Returns `None` if a -/// stride is zero or not even one rectangle (6 vertices) fits. -pub(crate) fn scratch_layout( - slots: &[(u32, u32)], - capacity_bytes: u64, -) -> Option<(u32, Vec<SlotLayout>)> { - if slots.is_empty() { - return Some((0, Vec::new())); - } - let mut dst_strides = Vec::with_capacity(slots.len()); - let mut total_stride: u64 = 0; - for &(_, src_stride) in slots { - if src_stride == 0 { - return None; - } - let dst_stride = src_stride.checked_next_multiple_of(4)?; - dst_strides.push(dst_stride); - total_stride = total_stride.checked_add(u64::from(dst_stride))?; - } - // Without alignment padding at most this many vertices fit; the padding - // between slots (under 16 bytes each) then costs at most a few - // rectangles, so step down until the padded layout fits. - let mut vert_capacity = - ((capacity_bytes / total_stride / 6) * 6).min(u64::from(u32::MAX) / 6 * 6); - let layouts = loop { - if vert_capacity < 6 { - return None; - } - if let Some(layouts) = place(slots, &dst_strides, vert_capacity, capacity_bytes) { - break layouts; - } - vert_capacity -= 6; - }; - Some((vert_capacity as u32, layouts)) -} - -/// The slots' regions for `verts` vertices each, 16-byte aligned one after -/// the other, if they end within `capacity_bytes`. -fn place( - slots: &[(u32, u32)], - dst_strides: &[u32], - verts: u64, - capacity_bytes: u64, -) -> Option<Vec<SlotLayout>> { - let mut cursor = 0u64; - let mut layouts = Vec::with_capacity(slots.len()); - for (&(slot, _), &dst_stride) in slots.iter().zip(dst_strides) { - let dst_offset = cursor.next_multiple_of(16); - let dst_size = verts.checked_mul(u64::from(dst_stride))?; - let end = dst_offset.checked_add(dst_size)?; - if end > capacity_bytes { - return None; - } - layouts.push(SlotLayout { - slot, - dst_offset, - dst_stride, - dst_size: u32::try_from(dst_size).ok()?, - }); - cursor = end; - } - Some(layouts) -} - -/// The vertex index bound shared across all bound per-vertex slots: a record's -/// `start..start + 3 * rects` lies inside every slot iff it lies inside -/// `0..max_source_vertices`. Empty `bounds` (no per-vertex slots) returns -/// `u32::MAX`. -pub(crate) fn max_source_vertices(bounds: &[(u64, u32)]) -> u32 { - bounds - .iter() - .map(|&(size, stride)| { - if stride == 0 { - 0 - } else { - (size / u64::from(stride)).min(u64::from(u32::MAX)) as u32 - } - }) - .min() - .unwrap_or(u32::MAX) -} - -/// 2D dispatch grid `(x, y)` covering `records` thread groups with each -/// dimension within D3D12's 65,535-group limit. -pub(crate) fn dispatch_grid(records: u32) -> (u32, u32) { - if records == 0 { - return (0, 0); - } - let x = records.min(MAX_GROUPS_PER_DIM); - let y = records.div_ceil(x); - (x, y) -} - -const REWRITE_SOURCE: &str = r#" -cbuffer Params : register(b0) { - uint records; - uint src_stride; - uint has_count; - uint max_src_verts; - uint vert_capacity; - uint need_verts; - uint pad0; - uint pad1; -}; -RWStructuredBuffer<uint> src_args : register(u0); -RWStructuredBuffer<uint> count_buf : register(u1); -RWStructuredBuffer<uint> alloc : register(u2); -RWStructuredBuffer<uint> dst_args : register(u3); - -[numthreads(64, 1, 1)] -void main(uint3 id : SV_DispatchThreadID) { - uint r = id.x; - if (r >= records) return; - uint dst_at = r * 16u; - if (has_count != 0u) { - uint live = count_buf[(0u) >> 2]; - if (r >= live) { - { uint4 _v = uint4(0u, 0u, 0u, 0u); dst_args[(dst_at) >> 2] = _v.x; dst_args[((dst_at) >> 2) + 1u] = _v.y; dst_args[((dst_at) >> 2) + 2u] = _v.z; dst_args[((dst_at) >> 2) + 3u] = _v.w; } - return; - } - } - uint4 rec = uint4(src_args[(r * src_stride) >> 2], src_args[((r * src_stride) >> 2) + 1u], src_args[((r * src_stride) >> 2) + 2u], src_args[((r * src_stride) >> 2) + 3u]); - // The clamp's bounds again: 2^24 vertices, 2^26 vertex instances. - rec.x = min(rec.x, 1u << 24); - rec.y = min(rec.y, (1u << 26) / max(rec.x, 1u)); - uint rects = rec.x / 3u; - uint src_verts = rects * 3u; - uint out_verts = rects * 6u; - uint out_start = 0u; - if (rects == 0u || rec.y == 0u || rec.z > max_src_verts || src_verts > max_src_verts - rec.z) { - out_verts = 0u; - } else if (need_verts != 0u) { - if (out_verts > vert_capacity) { - out_verts = 0u; - } else { - uint before; - InterlockedAdd(alloc[(0u) >> 2], out_verts, before); - if (before >= vert_capacity || out_verts > vert_capacity - before) { - out_verts = 0u; - } else { - out_start = before; - } - } - } - { uint4 _v = uint4(out_verts, rec.y, out_start, rec.w); dst_args[(dst_at) >> 2] = _v.x; dst_args[((dst_at) >> 2) + 1u] = _v.y; dst_args[((dst_at) >> 2) + 2u] = _v.z; dst_args[((dst_at) >> 2) + 3u] = _v.w; } -} -"#; - -const EXPAND_SOURCE: &str = r#" -cbuffer Params : register(b0) { - uint records; - uint src_stride; - uint grid_x; - uint vb_src_bias; - uint vb_src_stride; - uint vb_dst_stride; - uint elem_count; - uint pad0; -}; -StructuredBuffer<uint> elems : register(t0); -RWStructuredBuffer<uint> src_args : register(u0); -RWStructuredBuffer<uint> dst_args : register(u1); -RWStructuredBuffer<uint> src_vb : register(u2); -RWStructuredBuffer<uint> dst_vb : register(u3); - -uint load_u8(uint pos) { - uint w = src_vb[(pos & ~3u) >> 2]; - return (w >> ((pos & 3u) * 8u)) & 0xffu; -} - -uint load_u16(uint pos) { - uint rem = pos & 3u; - uint w0 = src_vb[(pos & ~3u) >> 2]; - if (rem <= 2u) { - return (w0 >> (rem * 8u)) & 0xffffu; - } - uint w1 = src_vb[((pos & ~3u) + 4u) >> 2]; - return ((w0 >> 24u) | (w1 << 8u)) & 0xffffu; -} - -uint load_u32(uint pos) { - uint rem = pos & 3u; - uint w0 = src_vb[(pos & ~3u) >> 2]; - if (rem == 0u) { - return w0; - } - uint w1 = src_vb[((pos & ~3u) + 4u) >> 2]; - return (w0 >> (rem * 8u)) | (w1 << ((4u - rem) * 8u)); -} - -void store_u8(uint pos, uint val) { - uint aligned = pos & ~3u; - uint shift = (pos & 3u) * 8u; - uint w = dst_vb[(aligned) >> 2]; - w = (w & ~(0xffu << shift)) | ((val & 0xffu) << shift); - dst_vb[(aligned) >> 2] = w; -} - -void store_u16(uint pos, uint val) { - uint rem = pos & 3u; - if (rem <= 2u) { - uint aligned = pos & ~3u; - uint shift = rem * 8u; - uint w = dst_vb[(aligned) >> 2]; - w = (w & ~(0xffffu << shift)) | ((val & 0xffffu) << shift); - dst_vb[(aligned) >> 2] = w; - } else { - store_u8(pos, val & 0xffu); - store_u8(pos + 1u, (val >> 8u) & 0xffu); - } -} - -void store_u32(uint pos, uint val) { - uint rem = pos & 3u; - if (rem == 0u) { - dst_vb[(pos) >> 2] = val; - } else { - uint aligned = pos & ~3u; - uint shift = rem * 8u; - uint inv = (4u - rem) * 8u; - uint mask = (1u << shift) - 1u; - uint w0 = dst_vb[(aligned) >> 2]; - w0 = (w0 & mask) | (val << shift); - dst_vb[(aligned) >> 2] = w0; - uint w1 = dst_vb[(aligned + 4u) >> 2]; - w1 = (w1 & ~mask) | (val >> inv); - dst_vb[(aligned + 4u) >> 2] = w1; - } -} - -void copy_vertex(uint src_off, uint dst_off) { - uint full = vb_src_stride & ~3u; - for (uint b = 0u; b < full; b += 4u) { - dst_vb[(dst_off + b) >> 2] = load_u32(src_off + b); - } - uint rem = vb_src_stride & 3u; - if (rem != 0u) { - uint w = 0u; - for (uint k = 0u; k < rem; k++) { - w |= load_u8(src_off + full + k) << (k * 8u); - } - dst_vb[(dst_off + full) >> 2] = w; - } -} - -float half_to_f32(uint h) { - uint sgn = (h >> 15u) << 31u; - uint ex = (h >> 10u) & 0x1fu; - uint man = h & 0x3ffu; - if (ex == 0u) { - if (man == 0u) return asfloat(sgn); - float v = (float)man * (1.0f / 16777216.0f); - return sgn != 0u ? -v : v; - } - if (ex == 31u) { - return asfloat(sgn | 0x7f800000u | (man << 13u)); - } - return asfloat(sgn | ((ex + 112u) << 23u) | (man << 13u)); -} - -uint f32_to_half(float v) { - uint bits = asuint(v); - uint sgn = (bits >> 16u) & 0x8000u; - int ex = (int)((bits >> 23u) & 0xffu) - 127 + 15; - uint man = bits & 0x7fffffu; - if (ex >= 31) return sgn | 0x7c00u; - if (ex <= 0) return sgn; - // Added, not or-ed: a rounding carry out of the mantissa raises the - // exponent (as #260 does for primitive.rs). - return sgn | (((uint)ex << 10u) + ((man + 0x1000u) >> 13u)); -} - -float read_comp(uint kind, uint pos) { - if (kind == 0u) return asfloat(load_u32(pos)); - if (kind == 1u) return half_to_f32(load_u16(pos)); - if (kind == 2u) return (float)load_u16(pos) / 65535.0f; - return (float)load_u8(pos) / 255.0f; -} - -void write_comp(uint kind, uint pos, float v) { - if (kind == 0u) { - store_u32(pos, asuint(v)); - } else if (kind == 1u) { - store_u16(pos, f32_to_half(v)); - } else if (kind == 2u) { - store_u16(pos, (uint)(saturate(v) * 65535.0f + 0.5f)); - } else { - store_u8(pos, (uint)(saturate(v) * 255.0f + 0.5f)); - } -} - -[numthreads(64, 1, 1)] -void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { - uint r = gid.y * grid_x + gid.x; - if (r >= records) return; - uint out_verts = dst_args[(r * 16u) >> 2]; - uint rects = out_verts / 6u; - if (rects == 0u) return; - uint dst_start = dst_args[(r * 16u + 8u) >> 2]; - uint src_start = src_args[(r * src_stride + 8u) >> 2]; - - for (uint rect = gtid.x; rect < rects; rect += 64u) { - uint v0_src = vb_src_bias + (src_start + rect * 3u) * vb_src_stride; - uint v1_src = v0_src + vb_src_stride; - uint v2_src = v1_src + vb_src_stride; - uint d = (dst_start + rect * 6u) * vb_dst_stride; - - copy_vertex(v0_src, d); - copy_vertex(v1_src, d + vb_dst_stride); - copy_vertex(v2_src, d + vb_dst_stride * 2u); - copy_vertex(v0_src, d + vb_dst_stride * 3u); - copy_vertex(v2_src, d + vb_dst_stride * 4u); - uint v3_dst = d + vb_dst_stride * 5u; - copy_vertex(v0_src, v3_dst); - - for (uint e = 0u; e < elem_count; e++) { - uint2 desc = uint2(elems[(e * 8u) >> 2], elems[((e * 8u) >> 2) + 1u]); - uint offset = desc.x; - uint kind = desc.y & 0xffu; - uint comp_count = desc.y >> 8u; - uint comp_bytes = kind == 0u ? 4u : (kind == 3u ? 1u : 2u); - for (uint c = 0u; c < comp_count; c++) { - uint at = offset + c * comp_bytes; - float a = read_comp(kind, v0_src + at); - float b = read_comp(kind, v1_src + at); - float f = read_comp(kind, v2_src + at); - write_comp(kind, v3_dst + at, a + f - b); - } - } - } -} -"#; - -struct Pass { - root: ID3D12RootSignature, - pso: ID3D12PipelineState, -} - -struct Shaders { - rewrite: Pass, - expand: Pass, -} - -// SAFETY: D3D12 objects are free-threaded. -unsafe impl Send for Shaders {} -// SAFETY: as above. -unsafe impl Sync for Shaders {} - -fn shaders() -> Option<&'static Shaders> { - static SHADERS: std::sync::OnceLock<Option<Shaders>> = std::sync::OnceLock::new(); - SHADERS - .get_or_init(|| match make() { - Ok(s) => Some(s), - Err(e) => { - tracing::warn!(error = %e, "no rectangle expander: indirect rectangles dropped"); - None - } - }) - .as_ref() -} - -fn compile_blob( - name: windows::core::PCSTR, - source: &str, -) -> Result<ID3DBlob, (windows::core::Error, String)> { - let mut code: Option<ID3DBlob> = None; - let mut errors: Option<ID3DBlob> = None; - // SAFETY: the source and names live through the call; out pointers are ours. - let compiled = unsafe { - D3DCompile( - source.as_ptr().cast(), - source.len(), - name, - None, - None, - s!("main"), - s!("cs_5_1"), - 0, - 0, - &mut code, - Some(&mut errors), - ) - }; - if let Err(e) = compiled { - let mut msg = String::new(); - if let Some(errors) = errors { - // SAFETY: the blob's own bytes. - let text = unsafe { - std::slice::from_raw_parts( - errors.GetBufferPointer().cast::<u8>(), - errors.GetBufferSize(), - ) - }; - msg = String::from_utf8_lossy(text).into_owned(); - tracing::warn!("rectangle expander: {msg}"); - } - return Err((e, msg)); - } - code.ok_or_else(|| (windows::core::Error::empty(), String::new())) -} - -/// A pass's root signature: eight constants (b0), then `srvs` root SRVs -/// (t0...) and `uavs` root UAVs (u0...), in that order. Built here since -/// Wine's compiler (vkd3d-shader) embeds none in the shader; for the same -/// compiler the passes read structured buffers of words, not raw buffers. -fn root_signature( - device: &ID3D12Device, - srvs: u32, - uavs: u32, -) -> windows::core::Result<ID3D12RootSignature> { - let view = |kind, register| D3D12_ROOT_PARAMETER { - ParameterType: kind, - Anonymous: D3D12_ROOT_PARAMETER_0 { - Descriptor: D3D12_ROOT_DESCRIPTOR { - ShaderRegister: register, - RegisterSpace: 0, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }; - let mut params = vec![D3D12_ROOT_PARAMETER { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, - Anonymous: D3D12_ROOT_PARAMETER_0 { - Constants: D3D12_ROOT_CONSTANTS { - ShaderRegister: 0, - RegisterSpace: 0, - Num32BitValues: 8, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }]; - params.extend((0..srvs).map(|r| view(D3D12_ROOT_PARAMETER_TYPE_SRV, r))); - params.extend((0..uavs).map(|r| view(D3D12_ROOT_PARAMETER_TYPE_UAV, r))); - let desc = D3D12_ROOT_SIGNATURE_DESC { - NumParameters: params.len() as u32, - pParameters: params.as_ptr(), - ..Default::default() - }; - let mut blob: Option<ID3DBlob> = None; - // SAFETY: the description and its parameters live through the calls. - unsafe { - D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None)?; - let blob = blob.ok_or_else(windows::core::Error::empty)?; - device.CreateRootSignature( - 0, - std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()), - ) - } -} - -fn compile_pass( - device: &ID3D12Device, - name: windows::core::PCSTR, - source: &str, - (srvs, uavs): (u32, u32), -) -> windows::core::Result<Pass> { - let code = compile_blob(name, source).map_err(|(e, _)| e)?; - let root = root_signature(device, srvs, uavs)?; - // SAFETY: the blob's own bytes. - unsafe { - let bytes = - std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); - let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: bytes.as_ptr().cast(), - BytecodeLength: bytes.len(), - }, - ..Default::default() - })?; - Ok(Pass { root, pso }) - } -} - -fn make() -> windows::core::Result<Shaders> { - let device = &host().ok_or_else(windows::core::Error::empty)?.device; - let rewrite = compile_pass(device, s!("rect_rewrite"), REWRITE_SOURCE, (0, 4))?; - let expand = compile_pass(device, s!("rect_expand"), EXPAND_SOURCE, (1, 4))?; - Ok(Shaders { rewrite, expand }) -} - -/// Rewritten indirect arguments and expanded vertex buffer views produced by -/// [`expand`], ready to transition around `ExecuteIndirect`. -pub(crate) struct Prepared { - pub(crate) args_buf: ID3D12Resource, - vert_buf: Option<ID3D12Resource>, - views: Vec<(u32, D3D12_VERTEX_BUFFER_VIEW)>, - counter: Option<ID3D12Resource>, -} - -impl Prepared { - /// Transitions the rewritten arguments, expanded vertex scratch and - /// optional count buffer for `ExecuteIndirect`, and binds the expanded - /// per-vertex buffer views (overriding the title's slots after `prepare`). - pub(crate) fn before_draw(&self, list: &HostList) { - let mut barriers = Vec::with_capacity(3); - barriers.push(transition( - &self.args_buf, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - )); - if let Some(vb) = &self.vert_buf { - barriers.push(transition( - vb, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, - )); - } - if let Some(counter) = &self.counter { - barriers.push(transition( - counter, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - )); - } - // SAFETY: an open list and live buffers owned by the list or shadows. - unsafe { - list.list.ResourceBarrier(&barriers); - for &(slot, view) in &self.views { - list.list.IASetVertexBuffers(slot, Some(&[view])); - } - } - } - - /// Restores the scratch buffers and optional count buffer to unordered - /// access so subsequent passes and draws can reuse them. - pub(crate) fn after_draw(&self, list: &HostList) { - let mut barriers = Vec::with_capacity(3); - barriers.push(transition( - &self.args_buf, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )); - if let Some(vb) = &self.vert_buf { - barriers.push(transition( - vb, - D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )); - } - if let Some(counter) = &self.counter { - barriers.push(transition( - counter, - D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )); - } - // SAFETY: an open list and live buffers owned by the list or shadows. - unsafe { list.list.ResourceBarrier(&barriers) }; - } -} - -struct SlotWork { - slot: u32, - shadow: Arc<Shadow>, - address: u64, - size: u32, - src_stride: u32, - elements: Vec<Element>, -} - -/// Clamps the title's indirect draw arguments (`kind == 0`) and records our -/// rectangle-expansion compute passes on `list`. On `Err(reason)` nothing was -/// recorded onto the host list; on `Ok(prepared)` the compute pipeline and root -/// signature were replaced and the caller binds its graphics state, calls -/// [`Prepared::before_draw`], executes indirect with stride 16 on -/// `prepared.args_buf`, and calls [`Prepared::after_draw`]. -pub(crate) fn expand( - list: &HostList, - pipeline: &HostPipeline, - vertices: &[VertexView; 32], - (args, arguments, stride, max): (&Arc<Shadow>, u64, u32, u32), - counter: Option<(&Arc<Shadow>, u64)>, -) -> Result<Prepared, &'static str> { - if stride < 16 || !stride.is_multiple_of(4) || !args.gpu(arguments).is_multiple_of(4) { - return Err("rectangle arguments unaligned or short"); - } - if max > MAX_RECORDS { - return Err("too many indirect rectangle records"); - } - if let Some((s, at)) = counter - && !s.gpu(at).is_multiple_of(4) - { - return Err("rectangle count buffer not 4-byte aligned"); - } - - let mut work = Vec::new(); - let mut bounds = Vec::new(); - for slot in 0..32u32 { - let v = vertices[slot as usize]; - let (has_per_vertex, elements) = slot_elements(&pipeline.inputs, slot, v.stride); - if !has_per_vertex { - continue; - } - if v.address == 0 || v.stride == 0 || v.size == 0 { - return Err("rectangle vertex buffer missing"); - } - let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { - return Err("rectangle vertex buffer outside title memory"); - }; - let effective = u64::from(v.size) - .min(shadow.left(v.address)) - .min(u64::from(u32::MAX - 3)); - bounds.push((effective, v.stride)); - work.push(SlotWork { - slot, - shadow, - address: v.address, - size: v.size, - src_stride: v.stride, - elements, - }); - } - - let slot_strides: Vec<(u32, u32)> = work.iter().map(|w| (w.slot, w.src_stride)).collect(); - let Some((vert_capacity, layouts)) = scratch_layout(&slot_strides, RECT_SCRATCH_BYTES) else { - return Err("rectangle vertex stride exceeds scratch capacity"); - }; - let max_src_verts = max_source_vertices(&bounds); - - let Some(s) = shaders() else { - return Err("rectangle expander shader unavailable"); - }; - let args_bytes = u64::from(max).max(1) * 16; - let Some(dst_args_buf) = list.rect_args(args_bytes) else { - return Err("rectangle rewritten-arguments allocation failed"); - }; - let Some(alloc_gpu) = list.rect_counter() else { - return Err("rectangle counter allocation failed"); - }; - let vert_buf = if work.is_empty() { - None - } else { - Some( - list.rect_vertices(RECT_SCRATCH_BYTES) - .ok_or("rectangle vertex scratch allocation failed")?, - ) - }; - - // Upload per-slot element tables before recording any GPU work. - let mut elem_gpus = Vec::with_capacity(work.len()); - for w in &work { - let byte_len = (w.elements.len().max(1) * size_of::<Element>()) as u64; - let Some((gpu, ptr)) = list.scratch(byte_len) else { - return Err("rectangle element upload allocation failed"); - }; - if !w.elements.is_empty() { - // SAFETY: `ptr` is freshly allocated 256-byte-aligned upload memory - // for this list of at least `byte_len` bytes. - unsafe { - std::ptr::copy_nonoverlapping( - w.elements.as_ptr().cast::<u8>(), - ptr, - w.elements.len() * size_of::<Element>(), - ); - } - } - elem_gpus.push(gpu); - } - - // Refresh title buffers at submission time. - let args_len = u64::from(stride) * u64::from(max.max(1)); - args.refresh(list, arguments, args_len); - if let Some((c, at)) = counter { - c.refresh(list, at, 4); - } - for w in &work { - w.shadow.refresh(list, w.address, u64::from(w.size)); - } - - let src_args_gpu = args.gpu(arguments); - if !crate::indirect::clamp_uav(list, src_args_gpu, (0, stride, max)) { - return Err("rectangle clamp unavailable"); - } - - // SAFETY: live D3D12 resources. - let dst_args_gpu = unsafe { dst_args_buf.GetGPUVirtualAddress() }; - let count_gpu = counter.map_or(src_args_gpu, |(c, at)| c.gpu(at)); - let rewrite_consts = [ - max, - stride, - u32::from(counter.is_some()), - max_src_verts, - vert_capacity, - u32::from(!work.is_empty()), - 0, - 0, - ]; - let l = &list.list; - // SAFETY: an open list; our shaders and live list-owned/shadow buffers. - unsafe { - l.SetComputeRootSignature(&s.rewrite.root); - l.SetPipelineState(&s.rewrite.pso); - l.SetComputeRoot32BitConstants(0, 8, rewrite_consts.as_ptr().cast(), 0); - l.SetComputeRootUnorderedAccessView(1, src_args_gpu); - l.SetComputeRootUnorderedAccessView(2, count_gpu); - l.SetComputeRootUnorderedAccessView(3, alloc_gpu); - l.SetComputeRootUnorderedAccessView(4, dst_args_gpu); - l.Dispatch(max.div_ceil(64), 1, 1); - } - - let mut views = Vec::with_capacity(work.len()); - if let Some(vb) = &vert_buf { - // SAFETY: live buffer. - let dst_vb_base = unsafe { vb.GetGPUVirtualAddress() }; - let (grid_x, grid_y) = dispatch_grid(max); - // SAFETY: an open list; our shaders and live buffers. - unsafe { - // Make rewritten arguments visible to the vertex-expansion dispatches. - l.ResourceBarrier(&[uav_barrier()]); - l.SetComputeRootSignature(&s.expand.root); - l.SetPipelineState(&s.expand.pso); - l.SetComputeRootUnorderedAccessView(2, src_args_gpu); - l.SetComputeRootUnorderedAccessView(3, dst_args_gpu); - for ((w, layout), elem_gpu) in work.iter().zip(&layouts).zip(elem_gpus) { - let raw_src_gpu = w.shadow.gpu(w.address); - let src_bias = (raw_src_gpu & 3) as u32; - let src_vb_gpu = raw_src_gpu & !3; - let dst_vb_gpu = dst_vb_base + layout.dst_offset; - let expand_consts = [ - max, - stride, - grid_x, - src_bias, - w.src_stride, - layout.dst_stride, - w.elements.len() as u32, - 0, - ]; - l.SetComputeRoot32BitConstants(0, 8, expand_consts.as_ptr().cast(), 0); - l.SetComputeRootShaderResourceView(1, elem_gpu); - l.SetComputeRootUnorderedAccessView(4, src_vb_gpu); - l.SetComputeRootUnorderedAccessView(5, dst_vb_gpu); - l.Dispatch(grid_x, grid_y, 1); - views.push(( - layout.slot, - D3D12_VERTEX_BUFFER_VIEW { - BufferLocation: dst_vb_gpu, - SizeInBytes: layout.dst_size, - StrideInBytes: layout.dst_stride, - }, - )); - } - } - } - - Ok(Prepared { - args_buf: dst_args_buf, - vert_buf, - views, - counter: counter.map(|(c, _)| c.buffer.clone()), - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn input(slot: u32, offset: u32, format: u32, per_instance: bool) -> Input { - Input { - slot, - offset, - format, - per_instance, - } - } - - #[test] - fn slot_elements_filters_and_clips_to_stride() { - let inputs = [ - input(0, 0, 16, false), // R32G32_FLOAT (2x4 = 8 bytes) - input(0, 8, 28, false), // R8G8B8A8_UNORM (4x1 = 4 bytes) - input(0, 4, 2, false), // R32G32B32A32_FLOAT clipped to 2 comps in 12-byte stride - input(0, 12, 28, false), // past stride -> dropped - input(0, 0, 42, false), // R32_UINT (unknown to primitive::components) -> dropped - input(1, 0, 16, true), // per-instance -> ignored - input(2, 0, 42, false), // unknown only -> still has_per_vertex = true, 0 elements - ]; - let (has0, elems0) = slot_elements(&inputs, 0, 12); - assert!(has0); - assert_eq!( - elems0, - vec![ - Element { - offset: 0, - packed: primitive::Kind::F32.code() | (2 << 8), - }, - Element { - offset: 8, - packed: primitive::Kind::Unorm8.code() | (4 << 8), - }, - Element { - offset: 4, - packed: primitive::Kind::F32.code() | (2 << 8), - }, - ] - ); - let (has1, elems1) = slot_elements(&inputs, 1, 16); - assert!(!has1); - assert!(elems1.is_empty()); - - let (has2, elems2) = slot_elements(&inputs, 2, 4); - assert!(has2); - assert!(elems2.is_empty()); - } - - #[test] - fn scratch_layout_handles_multi_slot_and_alignment() { - assert_eq!(scratch_layout(&[], 1024), Some((0, Vec::new()))); - assert_eq!(scratch_layout(&[(0, 0)], 1024), None); - assert_eq!(scratch_layout(&[(0, 16)], 64), None); // 6*16=96 > 64 - - // Two slots: stride 6 (padded to 8) and stride 12 (already multiple of 4). - let (cap, layouts) = scratch_layout(&[(0, 6), (3, 12)], 1024).unwrap(); - assert_eq!(cap % 6, 0); - assert!(cap >= 6); - assert_eq!(layouts.len(), 2); - assert_eq!(layouts[0].slot, 0); - assert_eq!(layouts[0].dst_offset, 0); - assert_eq!(layouts[0].dst_stride, 8); - assert_eq!(layouts[0].dst_size, cap * 8); - assert_eq!(layouts[1].slot, 3); - assert_eq!(layouts[1].dst_offset % 16, 0); - assert!(layouts[1].dst_offset >= u64::from(layouts[0].dst_size)); - assert_eq!(layouts[1].dst_stride, 12); - assert_eq!(layouts[1].dst_size, cap * 12); - assert!(layouts[1].dst_offset + u64::from(layouts[1].dst_size) <= 1024); - - // Two slots that fit exactly, with no padding needed between them: - // 6 vertices of 8 bytes, then 6 of 12 (48 is 16-byte aligned). - let (cap, layouts) = scratch_layout(&[(0, 8), (1, 12)], 120).unwrap(); - assert_eq!(cap, 6); - assert_eq!(layouts[1].dst_offset, 48); - // Padding is counted where it is needed: 6 * 4 = 24 bytes, then 16-byte - // alignment to 32, then 6 * 4 more; 55 bytes are too few, 56 enough. - assert_eq!(scratch_layout(&[(0, 4), (1, 4)], 55), None); - let (cap, layouts) = scratch_layout(&[(0, 4), (1, 4)], 56).unwrap(); - assert_eq!((cap, layouts[1].dst_offset), (6, 32)); - } - - #[test] - fn max_source_vertices_takes_minimum_across_slots() { - assert_eq!(max_source_vertices(&[]), u32::MAX); - assert_eq!(max_source_vertices(&[(120, 12), (80, 16)]), 5); - assert_eq!(max_source_vertices(&[(100, 0), (80, 16)]), 0); - } - - #[test] - fn dispatch_grid_respects_d3d12_limit() { - assert_eq!(dispatch_grid(0), (0, 0)); - assert_eq!(dispatch_grid(1), (1, 1)); - assert_eq!(dispatch_grid(65535), (65535, 1)); - let (x, y) = dispatch_grid(65536); - assert!(x <= 65535 && y <= 65535); - assert!(u64::from(x) * u64::from(y) >= 65536); - } - - /// Both rectangle-expansion compute shaders compile with the system's - /// compiler and the host device accepts them. - #[test] - fn rectangle_expander_builds() { - if host().is_none() { - return; // no host GPU here - } - assert!(shaders().is_some()); - } - - /// Both HLSL shaders compile with `D3DCompile`, Wine's (vkd3d-shader) - /// too: structured buffers of words, no embedded root signature. - #[test] - fn hlsl_compiles() { - if let Err((e, msg)) = compile_blob(s!("rect_rewrite"), REWRITE_SOURCE) { - panic!("rect_rewrite HLSL failed ({e}): {msg}"); - } - if let Err((e, msg)) = compile_blob(s!("rect_expand"), EXPAND_SOURCE) { - panic!("rect_expand HLSL failed ({e}): {msg}"); - } - } - - /// End-to-end GPU test: runs `rect_rewrite` and `rect_expand` on synthetic - /// vertex data covering F32, F16, Unorm16, Unorm8, unknown formats and - /// elements past the stride, plus count-buffer and out-of-bounds records, - /// and verifies the output byte-for-byte against `primitive::expand_rects`. - #[test] - fn gpu_expansion_matches_cpu_expand_rects() { - let Some(host) = host() else { - return; // no host GPU here - }; - let Some(s) = shaders() else { - panic!("rectangle expander shaders failed to build on a live host"); - }; - let list = host.new_list().expect("host command list"); - - // Synthetic 24-byte vertex layout: - // 0: R32G32_FLOAT (8 bytes) - // 8: R16G16_FLOAT (4 bytes) - // 12: R16G16_UNORM (4 bytes) - // 16: R8G8B8A8_UNORM (4 bytes) - // 20: R32_UINT (4 bytes, unknown -> must keep v0's bytes) - // 24: R8G8B8A8_UNORM (past stride -> ignored) - const STRIDE: usize = 24; - let vertex = |x: f32, y: f32, u: u16, v: u16, n0: u16, n1: u16, rgba: [u8; 4], tag: u32| { - let mut out = Vec::with_capacity(STRIDE); - out.extend(x.to_le_bytes()); - out.extend(y.to_le_bytes()); - out.extend(u.to_le_bytes()); - out.extend(v.to_le_bytes()); - out.extend(n0.to_le_bytes()); - out.extend(n1.to_le_bytes()); - out.extend(rgba); - out.extend(tag.to_le_bytes()); - out - }; - // 3 rectangles (9 vertices total): - // Rect 0: standard full-screen quad - // Rect 1: negative/clamped colors and negative half-floats - // Rect 2: used by record 1 starting at vertex 6 - let src_bytes: Vec<u8> = [ - // Rect 0 (verts 0..3) - vertex( - -1.0, - 1.0, - 0x0000, - 0x0000, - 0, - 10000, - [0, 50, 200, 255], - 0x1122_3344, - ), - vertex( - -1.0, - -1.0, - 0x0000, - 0x3c00, - 10000, - 30000, - [100, 100, 100, 255], - 0x5566_7788, - ), - vertex( - 1.0, - -1.0, - 0x3c00, - 0x3c00, - 40000, - 50000, - [150, 200, 50, 255], - 0x99aa_bbcc, - ), - // Rect 1 (verts 3..6) - vertex( - 0.25, - 0.5, - 0x3800, - 0xc000, - 50000, - 1000, - [220, 10, 128, 64], - 0xdead_beef, - ), - vertex( - 0.25, - -0.5, - 0x3c00, - 0xbc00, - 10000, - 20000, - [50, 200, 250, 200], - 0xcafe_babe, - ), - vertex( - 2.5, - -0.5, - 0x4000, - 0x3e00, - 60000, - 5000, - [200, 20, 10, 100], - 0x0102_0304, - ), - // Rect 2 (verts 6..9) - vertex( - 10.0, - 20.0, - 0x3e00, - 0x4200, - 12345, - 54321, - [10, 20, 30, 40], - 0xaabb_ccdd, - ), - vertex( - 10.0, - 30.0, - 0x4000, - 0x4400, - 22222, - 11111, - [50, 60, 70, 80], - 0x1234_5678, - ), - vertex( - 40.0, - 30.0, - 0x4200, - 0x4000, - 33333, - 22222, - [90, 80, 70, 60], - 0x8765_4321, - ), - ] - .concat(); - assert_eq!(src_bytes.len(), 9 * STRIDE); - - let inputs = [ - input(0, 0, 16, false), - input(0, 8, 34, false), - input(0, 12, 35, false), - input(0, 16, 28, false), - input(0, 20, 42, false), - input(0, 24, 28, false), - ]; - let raw_elements: Vec<(u32, u32)> = inputs.iter().map(|i| (i.offset, i.format)).collect(); - let (has_pv, gpu_elems) = slot_elements(&inputs, 0, STRIDE as u32); - assert!(has_pv); - - // 5 indirect records, count buffer = 4 (record 4 must not allocate): - // 0: 6 verts (2 rects) from 0, 1 instance - // 1: 3 verts (1 rect) from 6, 3 instances, start_instance 7 - // 2: out of bounds (start 8, 3 verts > 9) -> count' = 0 - // 3: 0 instances (3 verts, 0 instances) -> count' = 0 - // 4: past live count (3 verts, 1 instance) -> count' = 0 - let records: [[u32; 4]; 5] = [ - [6, 1, 0, 0], - [3, 3, 6, 7], - [3, 1, 8, 0], - [3, 0, 0, 0], - [3, 1, 0, 0], - ]; - let (src_args_buf, src_args_ptr) = host.shared_buffer(256).expect("src_args"); - let (count_buf, count_ptr) = host.shared_buffer(256).expect("count"); - let (alloc_buf, alloc_ptr) = host.shared_buffer(256).expect("alloc"); - let (dst_args_buf, dst_args_ptr) = host.shared_buffer(256).expect("dst_args"); - let (src_vb_buf, src_vb_ptr) = host.shared_buffer(4096).expect("src_vb"); - let (dst_vb_buf, dst_vb_ptr) = host.shared_buffer(4096).expect("dst_vb"); - let (elem_gpu, elem_ptr) = list.scratch(256).expect("elems"); - - // SAFETY: freshly mapped host buffers of sufficient size. - unsafe { - std::ptr::copy_nonoverlapping( - records.as_ptr().cast::<u8>(), - src_args_ptr, - size_of_val(&records), - ); - (count_ptr as *mut u32).write(4); - (alloc_ptr as *mut u32).write(0); - std::ptr::write_bytes(dst_args_ptr, 0xaa, 256); - std::ptr::copy_nonoverlapping(src_bytes.as_ptr(), src_vb_ptr, src_bytes.len()); - std::ptr::write_bytes(dst_vb_ptr, 0x55, 4096); - std::ptr::copy_nonoverlapping( - gpu_elems.as_ptr().cast::<u8>(), - elem_ptr, - gpu_elems.len() * size_of::<Element>(), - ); - - let rewrite_consts = [5u32, 16, 1, 9, 64, 1, 0, 0]; - let l = &list.list; - l.SetComputeRootSignature(&s.rewrite.root); - l.SetPipelineState(&s.rewrite.pso); - l.SetComputeRoot32BitConstants(0, 8, rewrite_consts.as_ptr().cast(), 0); - l.SetComputeRootUnorderedAccessView(1, src_args_buf.GetGPUVirtualAddress()); - l.SetComputeRootUnorderedAccessView(2, count_buf.GetGPUVirtualAddress()); - l.SetComputeRootUnorderedAccessView(3, alloc_buf.GetGPUVirtualAddress()); - l.SetComputeRootUnorderedAccessView(4, dst_args_buf.GetGPUVirtualAddress()); - l.Dispatch(1, 1, 1); - - l.ResourceBarrier(&[uav_barrier()]); - - let expand_consts = [ - 5u32, - 16, - 5, - 0, - STRIDE as u32, - STRIDE as u32, - gpu_elems.len() as u32, - 0, - ]; - l.SetComputeRootSignature(&s.expand.root); - l.SetPipelineState(&s.expand.pso); - l.SetComputeRoot32BitConstants(0, 8, expand_consts.as_ptr().cast(), 0); - l.SetComputeRootShaderResourceView(1, elem_gpu); - l.SetComputeRootUnorderedAccessView(2, src_args_buf.GetGPUVirtualAddress()); - l.SetComputeRootUnorderedAccessView(3, dst_args_buf.GetGPUVirtualAddress()); - l.SetComputeRootUnorderedAccessView(4, src_vb_buf.GetGPUVirtualAddress()); - l.SetComputeRootUnorderedAccessView(5, dst_vb_buf.GetGPUVirtualAddress()); - l.Dispatch(5, 1, 1); - } - list.close(); - host.execute(&[&list]); - - // SAFETY: execution finished; buffers are mapped and readable. - let (out_recs, allocated, gpu_out) = unsafe { - let mut out = [[0u32; 4]; 5]; - std::ptr::copy_nonoverlapping( - dst_args_ptr, - out.as_mut_ptr().cast::<u8>(), - size_of_val(&out), - ); - let allocated = (alloc_ptr as *const u32).read(); - let gpu_out = std::slice::from_raw_parts(dst_vb_ptr, 4096).to_vec(); - (out, allocated, gpu_out) - }; - - // Total allocated vertices: 12 (record 0) + 6 (record 1) = 18. - assert_eq!(allocated, 18); - assert_eq!(out_recs[0][0], 12); - assert_eq!(out_recs[0][1], 1); - assert_eq!(out_recs[0][3], 0); - assert_eq!(out_recs[1][0], 6); - assert_eq!(out_recs[1][1], 3); - assert_eq!(out_recs[1][3], 7); - assert_eq!(out_recs[2][0], 0); - assert_eq!(out_recs[3][0], 0); - assert_eq!(out_recs[4], [0, 0, 0, 0]); - - // Compare expanded vertices byte-for-byte with primitive::expand_rects. - let mut expected0 = vec![0u8; 12 * STRIDE]; - primitive::expand_rects( - &src_bytes[0..6 * STRIDE], - &mut expected0, - STRIDE, - &raw_elements, - ); - let start0 = out_recs[0][2] as usize * STRIDE; - assert_eq!(&gpu_out[start0..start0 + 12 * STRIDE], &expected0[..]); - - let mut expected1 = vec![0u8; 6 * STRIDE]; - primitive::expand_rects( - &src_bytes[6 * STRIDE..9 * STRIDE], - &mut expected1, - STRIDE, - &raw_elements, - ); - let start1 = out_recs[1][2] as usize * STRIDE; - assert_eq!(&gpu_out[start1..start1 + 6 * STRIDE], &expected1[..]); - } -} diff --git a/crates/victory-gpu/src/renderdoc.rs b/crates/victory-gpu/src/renderdoc.rs new file mode 100644 index 0000000000..3cdb39fecb --- /dev/null +++ b/crates/victory-gpu/src/renderdoc.rs @@ -0,0 +1,154 @@ +//! Diagnostics: one frame of the title captured with RenderDoc. +//! +//! `VICTORY_RENDERDOC=<full path of renderdoc.dll>` loads RenderDoc into +//! this process before the host device is made (its documented +//! in-application use: it hooks the graphics interfaces created after it +//! is loaded). `VICTORY_RENDERDOC_AT=<n>` (150 by default) then asks it for +//! the frame `n` presents after the first frame of 500 draws or more, and +//! `VICTORY_RENDERDOC_OUT` names the capture files (by default +//! `victory_rdc\frame` under the temporary folder). +//! +//! Nothing is loaded unless the variable gives the full path of a file: a +//! bare name is refused, so neither the current folder nor the title's is +//! ever searched for it. + +use std::ffi::c_void; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// RenderDoc's in-application interface: a table of function pointers +/// (`RENDERDOC_API_1_1_2` of its `renderdoc_app.h`), by address. +struct Api(usize); + +/// `void SetCaptureFilePathTemplate(const char *)`. +const SET_CAPTURE_FILE_PATH_TEMPLATE: usize = 11; +/// `uint32_t GetNumCaptures(void)`. +const GET_NUM_CAPTURES: usize = 13; +/// `void TriggerCapture(void)`: the next presented frame is captured. +const TRIGGER_CAPTURE: usize = 15; +/// `eRENDERDOC_API_Version_1_1_2`. +const VERSION_1_1_2: i32 = 10102; + +impl Api { + /// The table's entry `index` as a function of type `F`. + /// + /// # Safety + /// `index` is an entry of the 1.1.2 table and `F` its signature. + unsafe fn entry<F: Copy>(&self, index: usize) -> F { + let table = self.0 as *const usize; + // SAFETY: by the caller; the table lives as long as the module, + // which is never unloaded. + unsafe { std::mem::transmute_copy::<usize, F>(&*table.add(index)) } + } +} + +static API: OnceLock<Option<Api>> = OnceLock::new(); + +/// Whether RenderDoc was loaded into this run ([`load`]): the host device +/// is then RenderDoc's, and what a driver keeps for its own device (the +/// pipeline library's blob) is neither read nor written by this run. +pub(crate) fn loaded() -> bool { + API.get().is_some_and(Option::is_some) +} + +/// Loads RenderDoc when `VICTORY_RENDERDOC` names its DLL by full path. +/// Called before the host device is made. +pub(crate) fn load() { + API.get_or_init(|| { + let path = std::path::PathBuf::from(std::env::var_os("VICTORY_RENDERDOC")?); + if !path.is_absolute() || !path.is_file() { + tracing::warn!( + path = %path.display(), + "VICTORY_RENDERDOC: not the full path of a file; RenderDoc is not loaded" + ); + return None; + } + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_WITH_ALTERED_SEARCH_PATH, LoadLibraryExW, + }; + let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect(); + // SAFETY: a NUL-terminated full path, named by the user. + let module = + unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), LOAD_WITH_ALTERED_SEARCH_PATH) }; + if module.is_null() { + tracing::warn!(path = %path.display(), "VICTORY_RENDERDOC: the DLL does not load"); + return None; + } + // SAFETY: a loaded module and a NUL-terminated name. + let get = unsafe { GetProcAddress(module, c"RENDERDOC_GetAPI".as_ptr().cast()) }?; + // SAFETY: the export's documented signature, + // `int RENDERDOC_GetAPI(RENDERDOC_Version, void **)`. + let get = unsafe { + std::mem::transmute::< + unsafe extern "system" fn() -> isize, + unsafe extern "C" fn(i32, *mut *mut c_void) -> i32, + >(get) + }; + let mut table: *mut c_void = std::ptr::null_mut(); + // SAFETY: a valid out pointer. + if unsafe { get(VERSION_1_1_2, &mut table) } != 1 || table.is_null() { + tracing::warn!("VICTORY_RENDERDOC: the DLL does not give its interface 1.1.2"); + return None; + } + let api = Api(table as usize); + let out = std::env::var_os("VICTORY_RENDERDOC_OUT") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| std::env::temp_dir().join("victory_rdc").join("frame")); + if let Some(folder) = out.parent() { + let _ = std::fs::create_dir_all(folder); + } + if let Ok(name) = std::ffi::CString::new(out.to_string_lossy().as_bytes()) { + // SAFETY: the entry's signature; a NUL-terminated string it copies. + unsafe { + api.entry::<unsafe extern "C" fn(*const std::ffi::c_char)>(SET_CAPTURE_FILE_PATH_TEMPLATE)( + name.as_ptr(), + ); + } + } + tracing::info!( + path = %path.display(), + out = %out.display(), + at = at(), + "RenderDoc loaded: it captures one frame of the world" + ); + Some(api) + }); +} + +/// How many presents after the first world frame the capture is asked for. +fn at() -> u64 { + static AT: OnceLock<u64> = OnceLock::new(); + *AT.get_or_init(|| { + std::env::var("VICTORY_RENDERDOC_AT") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(150) + }) +} + +/// At the present of `frame`, with `drawn` draws run on the host so far. +pub(crate) fn frame_drew(frame: u64, drawn: u64) { + let Some(api) = API.get().and_then(|a| a.as_ref()) else { + return; + }; + static LAST: AtomicU64 = AtomicU64::new(0); + static WORLD: AtomicU64 = AtomicU64::new(u64::MAX); + let before = LAST.swap(drawn, Relaxed); + if drawn.saturating_sub(before) >= 500 { + let _ = WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed); + } + let world = WORLD.load(Relaxed); + if world == u64::MAX { + return; + } + if frame == world + at() { + // SAFETY: the entry's signature. + unsafe { api.entry::<unsafe extern "C" fn()>(TRIGGER_CAPTURE)() }; + tracing::info!(frame, "RenderDoc is asked for the next frame"); + } else if frame == world + at() + 8 { + // SAFETY: the entry's signature. + let captures = unsafe { api.entry::<unsafe extern "C" fn() -> u32>(GET_NUM_CAPTURES)() }; + tracing::info!(captures, "RenderDoc captures made so far"); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index c99a445796..b09ea6fc77 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -107,6 +107,9 @@ pub(crate) struct AllocationInfo { const _: () = assert!(size_of::<HeapProperties>() == 20); const _: () = assert!(size_of::<HeapDesc>() == 48); +// placed_resource_words copies the two field spans on either side of the padding. +const _: () = assert!(std::mem::offset_of!(ResourceDesc, alignment) == 8); +const _: () = assert!(std::mem::offset_of!(ResourceDesc, flags) == 48); const _: () = assert!(size_of::<ResourceDesc>() == 56); const BUFFER: u32 = 1; @@ -178,8 +181,8 @@ fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> { && let Some(t) = texture_layout(desc) { // As the console: the layout's own alignment unless more is asked - // (4 KiB for 4 KiB modes, where PC says 64 KiB). Grand Theft Auto - // VI keeps these sizes in its texture tables, and its streaming + // (4 KiB for 4 KiB modes, where PC says 64 KiB). + // The title keeps these sizes in its texture tables, and its streaming // asserts when they disagree with the streamed layout. let alignment = desc.alignment.max(t.alignment); if !alignment.is_power_of_two() { @@ -237,26 +240,343 @@ pub(crate) fn pc_format(format: u32) -> u32 { } } -/// The format a render target or unordered-access texture of `format` is -/// made in on the host, and that render target views and pipelines name, -/// for formats PC D3D12 forbids as one or the other: `R16G16B16A16_FLOAT` -/// (10) for `R9G9B9E5_SHAREDEXP` (67), and `R8G8B8A8_UNORM` (28), the same -/// channels with more bits, for `B5G5R5A1_UNORM` (86, no unordered access) -/// and `B4G4R4A4_UNORM` (115, no render target); else [`pc_format`]. -/// Textures only sampled keep their format. The host refused these -/// textures outright before (upstream #735, #741): the title's resource was -/// null. +/// The format of a texture the host GPU renders to or writes as unordered +/// access, for the title's `format`. The console's GPU does both with the +/// 16-bit colour formats B5G5R5A1 (86) and B4G4R4A4 (115), and +/// the title has full-screen targets in both; a host that refuses either use +/// (NVIDIA) refused the whole texture, so every pass that wrote it drew +/// nothing. There 8-bit RGBA stands in: the same channels in the same +/// order, every 4-bit level exact and every 5-bit level within 1/510. +/// The title also renders to R9G9B9E5 (67), which no PC GPU does: 16-bit +/// float RGBA stands in, with at least R9G9B9E5's precision and range. +/// The title's pipelines and views of such targets name the stand-in too +/// ([`view_format`], the host view checks). +/// shortcut: copies between such a target and a texture the title fills +/// itself in the 16-bit format are skipped ([`stands_in`]); convert them +/// if a pass turns out to need one. pub(crate) fn target_format(format: u32) -> u32 { - const R9G9B9E5_SHAREDEXP: u32 = 67; - const RGBA16_FLOAT: u32 = 10; - const B5G5R5A1_UNORM: u32 = 86; - const B4G4R4A4_UNORM: u32 = 115; - const RGBA8_UNORM: u32 = 28; - match pc_format(format) { - R9G9B9E5_SHAREDEXP => RGBA16_FLOAT, - B5G5R5A1_UNORM | B4G4R4A4_UNORM => RGBA8_UNORM, - format => format, + const STAND_INS: [(u32, u32); 3] = [(86, 28), (115, 28), (67, 10)]; + let Some(i) = STAND_INS.iter().position(|&(f, _)| f == format) else { + return format; + }; + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::*; + static REFUSED: std::sync::OnceLock<[bool; 3]> = std::sync::OnceLock::new(); + let refused = REFUSED.get_or_init(|| { + STAND_INS.map(|(f, to)| { + let Some(host) = crate::host::host() else { + return false; + }; + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(f as i32), + ..Default::default() + }; + // SAFETY: a plain query into our own structure. + let asked = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_FORMAT_SUPPORT, + (&raw mut support).cast(), + size_of_val(&support) as u32, + ) + }; + let both = D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 + | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0; + let refused = asked.is_err() || support.Support1.0 & both != both; + if refused { + tracing::info!( + format = f, + stand_in = to, + "the host does not render to this format: a stand-in is used" + ); + } + refused + }) + }); + if refused[i] { + return STAND_INS[i].1; + } + } + format +} + +/// Whether the host copy of the title texture `this` is in a stand-in +/// format ([`target_format`]): its texels are not laid out as the title's. +#[cfg(windows)] +pub(crate) fn stands_in(this: This) -> bool { + if this.is_null() { + return false; + } + let own = pc_format(resource(this).desc.format); + target_format(own) != own + && host_resource(this) + // SAFETY: a live resource. + .is_some_and(|host| unsafe { host.GetDesc() }.Format.0 as u32 == target_format(own)) +} + +/// Depth textures the title also asks unordered access for (the console +/// allows both; the host copy loses the unordered access): how many were +/// made, and how often such a texture was bound as the depth target, +/// cleared as depth, and asked for an unordered access view the host could +/// not give. Measured to decide what such textures need (a colour twin, or +/// to be colour textures altogether). +pub(crate) static DEPTH_UNORDERED: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Whether the title asked for both depth and unordered access for `this`. +#[cfg(windows)] +pub(crate) fn depth_and_unordered(this: This) -> bool { + !this.is_null() && resource(this).desc.flags & 6 == 6 +} + +/// The colour twin of a depth texture the title also writes as unordered +/// access. The console allows both on one texture; the host gives a depth +/// texture no unordered access, so shaders write a colour texture of the +/// same size and format family instead, and one is copied into the other +/// when a side is used after the other was written +/// (`HostList::twin_use`). +/// shortcut: whole textures are copied, not the mips and slices written. +/// A depth texture with a stencil plane gets a twin for each plane ( +/// the title's tiled lighting writes each pixel's material class into +/// the depth plane and masks into the stencil plane, then draws each class +/// with the depth test "equal"): the stencil plane's is copied through a +/// buffer, the depth plane's is drawn into the plane by a pass of ours +/// (`HostList::pass_plane`). Unordered access views of a multisampled +/// texture stay null. +#[cfg(windows)] +pub(crate) struct Twin { + /// The colour texture and the state it is in, as a host copy's. + pub(crate) colour: std::sync::Arc<HostTexture>, + /// Which side lacks what the other was written last, after the lists + /// submitted so far: bit 0 the depth texture, bit 1 the twin. + pub(crate) behind: std::sync::atomic::AtomicU32, + /// For a depth texture with a stencil plane, `colour` is the twin of + /// that plane (8 bits a texel) and this the buffer the two are copied + /// through: no colour format shares a family with a depth-stencil + /// format, but the host copies between a buffer and one plane. + pub(crate) through: Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource>, + /// For a depth texture with a stencil plane: the twin of its depth + /// plane, 16 bits a texel for the console's 16-bit depth-stencil + /// formats and a 32-bit float otherwise. No host colour format holds + /// the bits of a 24-bit depth plane, so the two are not copied: a pass + /// draws the twin into the plane. + pub(crate) plane: Option<std::sync::Arc<HostTexture>>, +} + +#[cfg(windows)] +impl Drop for Twin { + fn drop(&mut self) { + TWINS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Colour twins alive, depth textures with unordered access left without +/// one, and the copies recorded into depth textures and into twins since +/// the last frame-rate line. +#[cfg(windows)] +pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Depth planes drawn from their twins by the pass since the last +/// frame-rate line; and since the start, how often a depth plane's twin +/// lacked what was written to the plane (not given to it), and how often a +/// depth plane was used in the list that had written its twin, before the +/// pass (which runs when the list closes). +#[cfg(windows)] +pub(crate) static PLANES: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// The colour twin of title texture `this`, if it has one. +#[cfg(windows)] +pub(crate) fn twin(this: This) -> Option<std::sync::Arc<Twin>> { + if this.is_null() { + return None; + } + hosted(this, true).and_then(|made| made.1) +} + +/// The twin's texture, for the unordered access views of `this`. +#[cfg(windows)] +pub(crate) fn twin_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (_, twin) = hosted(this, true)?; + // SAFETY: as in `host_resource`: the twin lives as long as the host + // copy, which a depth texture keeps until the title releases it. + twin.map(|t| unsafe { &*std::ptr::from_ref(&t.colour.texture) }) +} + +/// The texture of the twin of the depth plane of `this`, a depth texture +/// with a stencil plane, for the unordered access views of that plane. +#[cfg(windows)] +pub(crate) fn twin_plane_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (_, twin) = hosted(this, true)?; + let twin = twin?; + // SAFETY: as in `twin_resource`. + twin.plane + .as_ref() + .map(|p| unsafe { &*std::ptr::from_ref(&p.texture) }) +} + +/// The colour twin for a texture described by `desc` whose host copy is +/// `depth`, if the title asks for depth and unordered access both and the +/// host can copy between the two: the same size, mips and slices in the +/// depth format's typeless family (R16 for 16-bit depth, R32 for 32-bit), +/// or R8 for the stencil plane of a format that has one, with unordered +/// access only. A format with a stencil plane gets a twin for its depth +/// plane too, R16 for the console's 16-bit depth-stencil formats and R32 +/// otherwise. `VICTORY_DEPTH_TWINS=0` makes none (such views stay null), +/// `VICTORY_DEPTH_TWINS=stencil` only those of formats with a stencil +/// plane, `VICTORY_DEPTH_TWINS=nodepth` none for the depth planes of such +/// formats. +#[cfg(windows)] +fn twin_texture( + desc: &ResourceDesc, + depth: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, +) -> Option<std::sync::Arc<Twin>> { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + const DEPTH_AND_UNORDERED: u32 = 6; + const UNORDERED: u32 = 4; + const UNORDERED_ACCESS: u32 = 0x8; + // R32 and R16 typeless: the families of the depth formats of one plane. + const ONE_PLANE: [u32; 2] = [39, 53]; + if desc.dimension == BUFFER || desc.flags & DEPTH_AND_UNORDERED != DEPTH_AND_UNORDERED { + return None; + } + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_none_or(|v| v != "0")) { + return None; + } + // R32G8X24 and R24G8 typeless: depth with a stencil plane, whose twin + // is R8 typeless. + const WITH_STENCIL: [u32; 2] = [19, 44]; + const R8_TYPELESS: u32 = 60; + let typeless = family(pc_format(desc.format)); + let stencil = WITH_STENCIL.contains(&typeless); + static STENCIL_ONLY: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let stencil_only = *STENCIL_ONLY + .get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_some_and(|v| v == "stencil")); + if !stencil && stencil_only { + return None; + } + if !(stencil || ONE_PLANE.contains(&typeless)) || desc.sample_count > 1 { + TWINS[1].fetch_add(1, Relaxed); + return None; + } + let host = crate::host::host()?; + let mut d = *desc; + d.layout = 0; + d.alignment = 0; + d.flags = UNORDERED; + d.format = if stencil { R8_TYPELESS } else { typeless }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut texture: Option<ID3D12Resource> = None; + // SAFETY: the description has the host layout, as in `host_texture`; + // the out pointer is ours. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32), + None, + &mut texture, + ) + }; + if let Err(e) = made { + tracing::warn!(error = %e, desc = ?d, "no colour twin for a depth texture"); } + let Some(texture) = texture else { + TWINS[1].fetch_add(1, Relaxed); + return None; + }; + crate::host::name(&texture, || { + format!("depth twin {}x{} f{}", d.width, d.height, d.format) + }); + // The buffer a stencil plane and its twin are copied through: as big + // as the plane's mips and slices laid out for a copy (they follow the + // depth plane's in the texture's subresources). + let through = if stencil { + // SAFETY: a live texture. + let of = unsafe { depth.GetDesc() }; + let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize); + let mut bytes = 0; + // SAFETY: a plain query; the out pointer is ours. + unsafe { + host.device.GetCopyableFootprints( + &of, + planes, + planes, + 0, + None, + None, + None, + Some(&mut bytes), + ); + } + let Some(buffer) = host.uav_buffer(bytes) else { + TWINS[1].fetch_add(1, Relaxed); + return None; + }; + Some(buffer) + } else { + None + }; + // The twin of the depth plane of a format with a stencil plane: R16 + // typeless (53) for the console's 16-bit depth-stencil formats (118 to + // 120), whose shaders write 16-bit steps, R32 typeless (39) otherwise. + static NO_PLANE: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let no_plane = *NO_PLANE + .get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_some_and(|v| v == "nodepth")); + let plane = if stencil && !no_plane { + d.format = if (118..=120).contains(&desc.format) { + 53 + } else { + 39 + }; + let mut texture: Option<ID3D12Resource> = None; + // SAFETY: as for the first twin. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32), + None, + &mut texture, + ) + }; + if let Err(e) = made { + tracing::warn!(error = %e, desc = ?d, "no twin for a depth plane"); + } + texture.map(|texture| { + crate::host::name(&texture, || { + format!("depth plane twin {}x{} f{}", d.width, d.height, d.format) + }); + std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS)) + }) + } else { + None + }; + TWINS[0].fetch_add(1, Relaxed); + Some(std::sync::Arc::new(Twin { + colour: std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS)), + behind: std::sync::atomic::AtomicU32::new(0), + through, + plane, + })) } /// The typeless format of a format's family (itself if it has none). @@ -295,27 +615,20 @@ pub(crate) fn family(format: u32) -> u32 { } } -/// sRGB formats and their linear twins: 8-bit color, then BC1, BC2, BC3 -/// and BC7. -pub(crate) const SRGB: [(u32, u32); 7] = [ - (29, 28), - (91, 87), - (93, 88), - (72, 71), - (75, 74), - (78, 77), - (99, 98), -]; +/// sRGB formats and their linear twins. +pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)]; /// The format a view of a title texture must name when its host copy is /// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if /// the host copy is typed. #[cfg(windows)] pub(crate) fn view_format(this: This) -> Option<u32> { + // First: a view of no resource (a typed null view) has none. let host = host_resource(this)?; let own = pc_format(resource(this).desc.format); // SAFETY: a live resource. let format = unsafe { host.GetDesc() }.Format.0 as u32; + // A stand-in target is typed. (format != own && format != target_format(own)).then_some(own) } @@ -348,34 +661,37 @@ fn mip_count(desc: &ResourceDesc) -> u32 { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct PlacedFootprint { pub(crate) offset: u64, - pub(crate) format: u32, - pub(crate) width: u32, - pub(crate) height: u32, - pub(crate) depth: u32, - pub(crate) row_pitch: u32, + format: u32, + width: u32, + height: u32, + depth: u32, + row_pitch: u32, } impl PlacedFootprint { - /// `(lines, row_bytes, total_bytes)` spanned in a buffer: every row - /// pitched but the last. - pub(crate) fn layout(&self) -> Option<(u64, u64, u64)> { + /// The bytes it spans in a buffer: every row pitched but the last. + pub(crate) fn bytes(&self) -> Option<u64> { let (element, block) = element(self.format)?; - let lines = u64::from(self.height) - .div_ceil(block) - .checked_mul(u64::from(self.depth))?; - let row_bytes = u64::from(self.width).div_ceil(block).checked_mul(element)?; - if lines == 0 { - return Some((0, row_bytes, 0)); - } - let total = u64::from(self.row_pitch) - .checked_mul(lines - 1)? - .checked_add(row_bytes)?; - Some((lines, row_bytes, total)) + let lines = u64::from(self.height).div_ceil(block) * u64::from(self.depth); + let last = u64::from(self.width).div_ceil(block) * element; + Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last) } - /// The bytes it spans in a buffer: every row pitched but the last. - pub(crate) fn bytes(&self) -> Option<u64> { - self.layout().map(|(_, _, total)| total) + /// For a read back through a host buffer: this footprint at offset 0 + /// with its rows pitched as the host wants them (multiples of 256 + /// bytes), then the bytes that buffer needs, the bytes of a row, the + /// rows, and the title's own pitch. + pub(crate) fn host_rows(&self) -> Option<(PlacedFootprint, [u64; 4])> { + let (element, block) = element(self.format)?; + let lines = (u64::from(self.height).div_ceil(block) * u64::from(self.depth)).max(1); + let row = u64::from(self.width).div_ceil(block) * element; + let pitch = row.max(1).next_multiple_of(256); + let host = PlacedFootprint { + offset: 0, + row_pitch: u32::try_from(pitch).ok()?, + ..*self + }; + Some((host, [pitch * lines, row, lines, u64::from(self.row_pitch)])) } } const _: () = assert!(size_of::<PlacedFootprint>() == 32); @@ -615,7 +931,7 @@ static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync:: /// Committed resources get their memory from the title's general /// allocator, as on the console, where titles hook it to place graphics -/// memory themselves (Grand Theft Auto VI places its back buffers in a +/// memory themselves (the title places its back buffers in a /// block of its own and checks they fill it). The runtime names it before /// the device exists. pub fn use_allocator(alloc: AllocRoutine, free: FreeRoutine) { @@ -691,6 +1007,12 @@ impl Memory { .ok_or(E_INVALIDARG)?; // SAFETY: the size is non-zero. let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?; + // The big ones are named in the log: the memory line counts our own + // allocations by size, and these are the title's memory given out + // of ours (a heap it made through the device, a descriptor heap). + if info.size >= 32 << 20 { + tracing::info!(mb = info.size >> 20, at = ?ptr, "memory for the title from our allocator (a heap or a descriptor heap)"); + } Ok(Memory { ptr, layout, @@ -792,36 +1114,10 @@ struct Resource { heap_flags: u32, backing: Backing, /// Textures also live on the host GPU (decision 0007); buffers do not - /// yet. Made on first use (a view, a target, a copy, a barrier), not - /// at creation: a texture the title makes and never has the GPU use - /// costs no host memory (the world makes thousands; their host copies - /// took about 9 GB, past an 8 GB card's budget, 2026-11-24). - #[cfg(windows)] - host: std::sync::OnceLock<Option<std::sync::Arc<HostTexture>>>, - /// The creation state and clear value the host copy is made with. + /// yet. With, for a depth texture the title also writes as unordered + /// access, the colour texture shaders write instead ([`Twin`]). #[cfg(windows)] - made_with: (u32, Option<[u32; 5]>), -} - -#[cfg(windows)] -impl Resource { - /// The host copy, made now if this is its first use. - fn host(&self) -> Option<&std::sync::Arc<HostTexture>> { - self.host - .get_or_init(|| { - let (state, clear) = self.made_with; - let clear = clear - .as_ref() - .map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::<c_void>()); - let texture = host_texture(&self.desc, state, clear)?; - let state = crate::host::legal_state(&texture, crate::host::texture_state(state)); - Some(std::sync::Arc::new(HostTexture { - texture, - state: state.into(), - })) - }) - .as_ref() - } + host: Hosted, } /// A title texture's host copy and the state it is in. The title's barriers @@ -834,182 +1130,1304 @@ impl Resource { pub(crate) struct HostTexture { pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, pub(crate) state: std::sync::atomic::AtomicU32, + /// The bytes the host gives it. + bytes: u64, + /// Whether its contents come from title memory ([`fills`]): counted in + /// [`KINDS`] while it lives. + filled: bool, + /// Made without memory of its own (`crate::tiles`): the tiles its + /// levels have been given. Its `bytes` are 0: what it holds of the card + /// is counted there. + pub(crate) tiled: Option<crate::tiles::Tiled>, } -/// Moves the host texture to `wanted` (a host texture state); the host -/// resource and the state it leaves, if that is a change. +/// What a title texture has on the host: its host copy and, for a depth +/// texture shaders also write, the colour twin. #[cfg(windows)] -pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> { - use windows::core::Interface; - let host = resource(this).host()?; - let before = host - .state - .swap(wanted, std::sync::atomic::Ordering::Relaxed); - (before != wanted).then(|| (host.texture.as_raw(), before)) +type Made = (std::sync::Arc<HostTexture>, Option<std::sync::Arc<Twin>>); + +/// A title texture's host side. The host copy is made when something first +/// uses the texture, not when the title creates it: the title +/// had created 3,871 textures (9.2 GB on the host) before its world's first +/// frame, of which a frame's lists name some hundreds (run 23), on a card +/// with 12 GB. A title texture is memory the title has either way; its host +/// copy is the card's. +#[cfg(windows)] +struct Hosted { + /// The host copy (and twin) once made. Taken out again only by + /// [`let_go_idle`] and when the title releases the resource. + made: std::sync::Mutex<Option<Made>>, + /// The state and clear value the title created the texture with. + state: u32, + clear: Option<[u32; 5]>, + /// When the host copy was last asked for (`crate::host::moment`), + /// written under `made`'s lock. + used: std::sync::atomic::AtomicU64, + /// The host refused to make it: not tried again. + refused: std::sync::atomic::AtomicBool, + /// When the card last had no room for it (`crate::host::moment`; 0: + /// never): it is tried again on a use after [`NO_ROOM_AGAIN_MS`] + /// ([`NoTexture::ForNow`]). + no_room: std::sync::atomic::AtomicU64, + /// Its host copy was let go as idle once. + gone: std::sync::atomic::AtomicBool, + /// A texture of [`PLACED_TEXTURES`]. + placed: std::sync::atomic::AtomicBool, } -/// The host GPU's copy of a title resource, if it has one. +/// Counts for the memory line: host copies of textures the title fills +/// alive and their bytes; such copies let go as idle since the start and +/// their bytes; made again after that and their bytes; and host copies made +/// since the start. #[cfg(windows)] -pub(crate) fn host_resource<'a>( - this: This, -) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { - if this.is_null() { - return None; - } - resource(this).host().map(|h| &h.texture) +pub(crate) static KINDS: [std::sync::atomic::AtomicU64; 7] = + [const { std::sync::atomic::AtomicU64::new(0) }; 7]; + +/// Every title texture alive (not buffers), by address: for the sweep and +/// the memory line. A texture leaves the table before it is freed. +#[cfg(windows)] +static TEXTURES: std::sync::Mutex<std::collections::BTreeSet<usize>> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + +#[cfg(windows)] +fn textures() -> std::sync::MutexGuard<'static, std::collections::BTreeSet<usize>> { + TEXTURES.lock().unwrap_or_else(|e| e.into_inner()) } -/// A title texture's host copy, shared, for a list to hold. +/// A title texture held alive ([`hold`]). #[cfg(windows)] -pub(crate) fn host_copy(this: This) -> Option<std::sync::Arc<HostTexture>> { - if this.is_null() { - return None; +pub(crate) struct Held(This); + +#[cfg(windows)] +impl Held { + /// The texture the handle keeps alive. + pub(crate) fn get(&self) -> This { + self.0 } - resource(this).host().cloned() } -/// A host texture like the title's: same description, in GPU memory, -/// without the console's layout and flags. #[cfg(windows)] -fn host_texture( - desc: &ResourceDesc, - state: u32, - clear: *const c_void, -) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> { - use windows::Win32::Graphics::Direct3D12::*; - const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access - if desc.dimension == BUFFER { - return None; - } - let host = crate::host::host()?; - let mut d = *desc; - d.layout = 0; - d.alignment = 0; - d.flags &= PC_FLAGS; - // PC refuses depth targets that are also unordered-access (the console - // allows both; Grand Theft Auto VI's shadow maps ask for it). - // shortcut: the host copy loses UAV use; give it a second view-only - // copy if draws write it as a UAV. - const DEPTH: u32 = 2; - const UNORDERED: u32 = 4; - if d.flags & DEPTH != 0 { - d.flags &= !UNORDERED; +impl Drop for Held { + fn drop(&mut self) { + crate::object::release_boxed::<Resource>(self.0); } - const RENDER_TARGET: u32 = 1; - d.format = if d.flags & (RENDER_TARGET | UNORDERED) != 0 { - target_format(d.format) - } else { - pc_format(d.format) - }; - const DENY_SHADER_RESOURCE: u32 = 8; - if d.flags & DENY_SHADER_RESOURCE == 0 - && let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format) +} + +/// Holds title texture `this` alive, for work on a thread the title knows +/// nothing of. `None` if it is no texture, or is being released. +#[cfg(windows)] +pub(crate) fn hold(this: This) -> Option<Held> { + // A texture leaves the table before it is freed, under this lock. + let all = textures(); + (all.contains(&(this as usize)) && crate::object::add_ref_alive(this)).then(|| Held(this)) +} + +/// The title textures the host renders to or writes (targets, depth, +/// unordered access), by the address of their memory: what a view the +/// title places in that memory in another format shows ([`alias_of`]). A +/// texture leaves the table before it is freed. +#[cfg(windows)] +static TARGETS_AT: std::sync::Mutex<std::collections::BTreeMap<u64, usize>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// For `this`, a texture made for a view the title placed in memory +/// ([`texture_at`]): the title texture the host writes that lies in the +/// same memory, if there is one of the same size, levels and layers with +/// texels of the same width. The console reads such a texture through the +/// view as it is +/// (the title packs light as R9G9B9E5 into R32_UINT textures +/// with compute shaders, which cannot write R9G9B9E5, and samples them +/// through R9G9B9E5 views placed at the textures' addresses: the sky, the +/// sky and light probes, the bounced light the lighting pass adds). On the +/// host the two are two textures and what the shaders wrote exists in one +/// of them only: the other was filled from title memory, which nothing +/// writes, so everything read through such a view was black. +/// Textures of several levels or layers count too (the screen probes' +/// light atlas has four levels, the camera's sky light cache six layers, +/// the cloud and sky tables are volumes): only textures of one level and +/// one layer were found at first, and the programs behind the others read +/// the title's unwritten memory - the sky light cache's second stage wrote +/// all zeros from a first stage that held light (run 88). +/// `VICTORY_ALIAS_COPY=0`: none is found, as before; `=1`: only textures +/// of one level and one layer, as at first. +#[cfg(windows)] +pub(crate) fn alias_of(this: This) -> Option<Held> { + use std::sync::atomic::Ordering::Relaxed; + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if this.is_null() + || !*ON.get_or_init(|| std::env::var_os("VICTORY_ALIAS_COPY").is_none_or(|v| v != "0")) { - d.format = typeless; - } - // The host has no sRGB unordered access: such textures are typeless, - // their unordered access views plain UNORM. - if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) { - d.format = family(d.format); + return None; } - // The clear value names the format too: format, then color or depth - // and stencil (5 words). - let clear_value = (!clear.is_null()).then(|| { - // SAFETY: the title passes a whole clear value. - let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() }; - value[0] = if d.flags & (RENDER_TARGET | UNORDERED) != 0 { - target_format(value[0]) - } else { - pc_format(value[0]) - }; - value - }); - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; - let mut texture: Option<ID3D12Resource> = None; - let create = |d: &ResourceDesc, texture: &mut Option<ID3D12Resource>| { - // A clear value is only legal on render targets and depth. - let clear = clear_value - .as_ref() - .filter(|_| d.flags & (1 | DEPTH) != 0) - .map(|v| std::ptr::from_ref(v).cast()); - // SAFETY: the description has the host layout (checked size, same - // fields); the out pointer is ours. - unsafe { - host.device.CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - std::ptr::from_ref(d).cast(), - D3D12_RESOURCE_STATES(crate::host::legal_for( - d.flags, - crate::host::texture_state(state), - ) as i32), - // The same layout: format, then color or depth and stencil. - clear, - texture, - ) - } + static WHOLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let whole = + *WHOLE.get_or_init(|| std::env::var_os("VICTORY_ALIAS_COPY").is_none_or(|v| v != "1")); + let r = resource(this); + // A level count of 0 asks for a full chain: not counted here. + let one = |d: &ResourceDesc| { + d.dimension != BUFFER + && d.mip_levels >= 1 + && d.depth_or_array_size >= 1 + && (whole || (d.mip_levels == 1 && d.depth_or_array_size == 1)) + && d.sample_count <= 1 }; - let mut made = create(&d, &mut texture); - // Not every host GPU offers every use of every format (NVIDIA: no - // unordered access to BGRA8, no B4G4R4A4 render targets, where the - // console's AMD GPU has both). Give up the uses the host refuses, UAV - // first; the views the host cannot make are skipped as for depth. - for drop in [UNORDERED, 1] { - if made.is_ok() || d.flags & drop == 0 { - continue; - } - let mut fewer = d; - fewer.flags &= !drop; - let mut retry: Option<ID3D12Resource> = None; - if create(&fewer, &mut retry).is_ok() { - tracing::warn!(desc = ?d, dropped = drop, "host texture without a use the host refuses"); - d = fewer; - texture = retry; - made = Ok(()); - } else if drop == UNORDERED { - d = fewer; // also try with neither - } - } - if let Err(e) = made { - tracing::warn!(error = %e, desc = ?d, "no host texture"); - } - if let Some(t) = &texture { - crate::host::name(t, || { - format!( - "texture {}x{} f{} flags {:#x}", - d.width, d.height, d.format, d.flags - ) - }); + if !r.host.placed.load(Relaxed) || !fills(&r.desc) || !one(&r.desc) { + return None; } - texture + // Under the table's lock: a texture leaves it before it is freed. + let targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); + let other = *targets.get(&(r.data() as u64))? as This; + let o = resource(other); + const DEPTH: u32 = 0x2; + let same = one(&o.desc) + && o.desc.dimension == r.desc.dimension + && o.desc.width == r.desc.width + && o.desc.height == r.desc.height + && o.desc.mip_levels == r.desc.mip_levels + && o.desc.depth_or_array_size == r.desc.depth_or_array_size + && o.desc.flags & DEPTH == 0 + && target_format(o.desc.format) == o.desc.format + && element(o.desc.format).is_some_and(|e| e.1 == 1 && Some(e) == element(r.desc.format)); + // Try 6.15, after cool_fox 94f35b7f (cccw, #1336): held alive under the + // table's lock. The bare pointer outlived the lock, and the title's + // recording threads may release the texture before the draw copies + // from it: a use after free, or a copy from the next texture made at + // that address (garbage on screen). One being released is not given. + (same && crate::object::add_ref_alive(other)).then(|| Held(other)) } -/// A texture's console memory and description; `None` for buffers. -pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { - if this.is_null() { - return None; - } - let r = resource(this); - (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc)) +/// Whether host copies are made on first use. On by default; +/// `VICTORY_LAZY_TEXTURES=0` makes each when the title creates its texture, +/// as before. +#[cfg(windows)] +fn lazy() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_TEXTURES").is_none_or(|v| v != "0")) } -/// A buffer's host memory and size; `None` for textures. -pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> { - if this.is_null() { - return None; +/// Whether a texture described by `desc` takes its contents from title +/// memory: one the host neither renders to nor writes (no target, depth or +/// unordered access flag). Its host copy can be made again from that +/// memory; any other texture's contents exist on the host alone. +#[cfg(windows)] +fn fills(desc: &ResourceDesc) -> bool { + const TARGET_DEPTH_UNORDERED: u32 = 0x7; + desc.dimension != BUFFER && desc.flags & TARGET_DEPTH_UNORDERED == 0 +} + +/// Whether the title fills texture `this` itself ([`fills`]). +#[cfg(windows)] +pub(crate) fn title_fills(this: This) -> bool { + !this.is_null() && fills(&resource(this).desc) +} + +/// Whether `this` is a texture whose host copy is not made yet (and may +/// still be): a descriptor slot written with a view of it waits +/// (`crate::descriptor::make_waiting`). +#[cfg(windows)] +pub(crate) fn host_waits(this: This) -> bool { + if this.is_null() || !lazy() { + return false; } let r = resource(this); - (r.desc.dimension == BUFFER).then(|| (r.data(), r.desc.width)) + r.desc.dimension != BUFFER + && !r.host.refused.load(std::sync::atomic::Ordering::Relaxed) + && r.host.made.lock().unwrap_or_else(|e| e.into_inner()).is_none() } -impl Resource { - fn data(&self) -> *mut u8 { - match self.backing { - Backing::Committed(ref memory) => memory.ptr.as_ptr(), - // SAFETY: placement checked the range lies inside the heap. +/// The host side of title texture `this`: made now if it is not there and +/// `make` says so. `None` for buffers and for textures the host refuses. +#[cfg(windows)] +fn hosted(this: This, make: bool) -> Option<Made> { + use std::sync::atomic::Ordering::Relaxed; + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + if made.is_none() { + if !make || r.host.refused.load(Relaxed) { + return None; + } + // The card had no room for it a moment ago: not asked again on + // every use (`NO_ROOM_AGAIN_MS`). + let no_room = r.host.no_room.load(Relaxed); + if no_room != 0 && !crate::host::long_ago(no_room, NO_ROOM_AGAIN_MS, 0) { + return None; + } + let clear = r + .host + .clear + .as_ref() + .map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::<c_void>()); + // Levels on demand (`crate::tiles`): a texture the title places in + // memory and fills, of a megabyte or more, that does not hold all + // its levels now, is made without memory and given it level by + // level. It does not hold them all if its memory is not all + // mapped, if the next texture starts inside its span, or if a + // view of it starts below level 0. Every other texture, and this + // one if the card will not have it so, is made as before. + const TEXTURE_2D: u32 = 3; + let mut tiled = None; + let mut texture = None; + let shape_fits = fills(&r.desc) + && r.desc.dimension == TEXTURE_2D + && r.desc.depth_or_array_size == 1 + && r.desc.mip_levels > 1 + && r.desc.sample_count <= 1; + // (Texture objects too, on a card where texture quality drops the + // largest levels: `crate::tiles::top_dropped`.) + if shape_fits && (r.host.placed.load(Relaxed) || crate::tiles::by_quality()) && crate::tiles::wanted() { + let bytes = footprint(&r.desc).map_or(0, |f| f.size); + let start = r.data() as u64; + // What the upload can read: a console layout, no XOR mode + // (`crate::texture` `staging`). + let readable = texture_layout(&r.desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor()); + // On a card where texture quality drops the largest levels + // (`crate::tiles::top_dropped`), every such texture of a + // megabyte or more is made level by level, whole or not: made + // whole it took all its levels' memory at once. + let partly = readable + && (SQUEEZING.get() + || bytes >= crate::tiles::floor() + && (crate::tiles::by_quality() + || !crate::texture::committed(r.data().cast_const(), bytes as usize) + || crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some() + || crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0))); + let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true).ok() } else { None }; + let cut = reserved + .as_ref() + .zip(crate::host::host()) + .and_then(|(t, host)| crate::tiles::Tiled::make(&host.device, t, u32::from(r.desc.mip_levels))); + // (Both or neither: a reserved texture the card will not cut + // into tiles is dropped here, and the old kind is made below.) + if cut.is_some() { + tiled = cut; + texture = reserved; + } + } + // On a card without room ([`squeezing`]): a large copy that would + // take all of its memory at once is not made now (and not refused: + // the slot waits for room). + if texture.is_none() && SQUEEZING.get() && footprint(&r.desc).map_or(0, |f| f.size) > crate::tiles::floor() { + return None; + } + let texture = match texture { + Some(texture) => Ok(texture), + None => host_texture(&r.desc, r.host.state, clear), + }; + let texture = match texture { + Ok(texture) => texture, + Err(NoTexture::Refused) => { + r.host.refused.store(true, Relaxed); + return None; + } + // Upstream VIctory #3198: a placed texture whose host texture + // could not be made kept that answer for the run (its resource + // stays in `PLACED_TEXTURES`), so a texture first asked for while + // the card was full read black to the end. Out of room is not a + // refusal: the texture is made on a later use. + Err(NoTexture::ForNow) => { + r.host.no_room.store(crate::host::moment().max(1), Relaxed); + NOT_MADE_FOR_NOW.fetch_add(1, Relaxed); + return None; + } + }; + if r.host.no_room.swap(0, Relaxed) != 0 { + MADE_AFTER_NO_ROOM.fetch_add(1, Relaxed); + } + let twin = twin_texture(&r.desc, &texture); + // One line per depth texture with unordered access: its address is + // the one target dumps and the captured frame's list of commands + // name. + if r.desc.flags & 6 == 6 { + tracing::info!( + resource = ?this, + desc = ?r.desc, + twin = twin.is_some(), + "depth texture with unordered access" + ); + } + let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state)); + let mut host = match tiled { + Some(tiled) => HostTexture::new_tiled(texture, state, tiled), + None => HostTexture::new(texture, state), + }; + host.filled = fills(&r.desc); + if host.filled { + KINDS[0].fetch_add(1, Relaxed); + KINDS[1].fetch_add(host.bytes, Relaxed); + } + if r.host.gone.load(Relaxed) { + KINDS[4].fetch_add(1, Relaxed); + KINDS[5].fetch_add(host.bytes, Relaxed); + } + KINDS[6].fetch_add(1, Relaxed); + *made = Some((std::sync::Arc::new(host), twin)); + // Slots the title wrote with views of it while it had no host copy + // are made before the next submission runs. + crate::descriptor::texture_made(this as usize); + } + r.host.used.store(crate::host::moment(), Relaxed); + made.clone() +} + +/// The host copy of title texture `this` if it is made, without making it +/// (for diagnostics, which must not count as a use). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn host_made<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (host, _) = hosted(this, false)?; + // SAFETY: as in `host_resource`. + Some(unsafe { &*std::ptr::from_ref(&host.texture) }) +} + +/// Whether more host copies of textures the title fills may be made for +/// shaders that pick textures by index (`draw.rs` `heap_textures`): always +/// up to `FLOOR` bytes of them, beyond that while the card's memory in use +/// by this process is under nine tenths of the budget the system gives it +/// ([`room_percent`] says another share; `VICTORY_TEXTURE_BUDGET_MB` sets a +/// limit on those copies' bytes instead). Past the budget the system moves +/// the card's memory into the PC's, which ended runs 20 and 24. +#[cfg(windows)] +pub(crate) fn room() -> bool { + use std::sync::atomic::Ordering::Relaxed; + const FLOOR: u64 = 2 << 30; + const WITHOUT_BUDGET: u64 = 4 << 30; + static LIMIT: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?; + mb.trim().parse::<u64>().ok().map(|mb| mb << 20) + }); + // (With the tiles of the copies made level by level, whose own bytes + // count as none: `crate::tiles`.) + let filled = KINDS[1].load(Relaxed) + crate::tiles::given_total(); + if let Some(limit) = limit { + return filled < limit; + } + if filled < FLOOR { + return true; + } + match crate::host::host().and_then(|h| h.video_memory()) { + // What is kept for card copies of title buffers not made yet + // (`crate::shadow::card_room_kept`), for the render targets a + // world makes in its first frame ([`targets_room_kept`]) and, Try + // 6.16, for windows that shaders would otherwise read from the + // PC's memory (`crate::shadow::windows_room_kept`) counts as used. + Some([budget, used, ..]) => { + used + crate::shadow::card_room_kept() + targets_room_kept(budget) + crate::shadow::windows_room_kept(budget) + < budget / 100 * room_percent() + } + None => filled < WITHOUT_BUDGET, + } +} + +/// Whether a card without [`room`] still has some for small copies of +/// textures (`crate::tiles::small_tiles`): its memory in use under 97 % of +/// the system's budget. Past the budget the system moves the card's memory +/// into the PC's. +#[cfg(windows)] +pub(crate) fn squeeze_room() -> bool { + if crate::tiles::small_tiles() == 0 || !crate::tiles::wanted() { + return false; + } + match crate::host::host().and_then(|h| h.video_memory()) { + // Up to the budget itself (it was 97 %): past 97 % every new + // texture stayed black for the rest of the run on 6 and 8 GB cards + // (2026-11-25 and 11-26 reports: 17,000 to 27,000 waiting, none + // squeezed); its small levels are a few hundred KiB. + // And past it by an eighth: a few hundred KiB a texture that the + // system may move into the PC's memory draw slowly; left without + // any they draw black (2026-11-26 report: the card stood at 5,626 + // to 5,837 MB of a 5,153 MB budget, nothing was squeezed). + Some([budget, used, ..]) => used < budget + budget / 8, + None => false, + } +} + +// Set while the pass over textures picked by index makes a host copy on a +// card without room ([`squeezing`]): such a copy is made level by level +// whatever it holds, and a large one that cannot be is not made now. +#[cfg(windows)] +thread_local! { + static SQUEEZING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// Runs `f`, in which host copies of textures are made as for a card +/// without room but with some below its hard line ([`squeeze_room`]): +/// two-dimensional ones with levels are made level by level (the small +/// levels get memory, `crate::tiles::Tiled::uploaded_small`), others of +/// more than `crate::tiles::floor` bytes are not made. +#[cfg(windows)] +pub(crate) fn squeezing<R>(f: impl FnOnce() -> R) -> R { + SQUEEZING.set(true); + let r = f(); + SQUEEZING.set(false); + r +} + +/// The bytes of the card's memory the texture queue leaves free for +/// render targets and other host copies the host itself writes that are +/// not made yet: `VICTORY_CARD_ROOM_FOR_TARGETS_MB` (3,072; 0: none, as +/// before) less what such copies hold now. +/// +/// Measured (runs 193, 197, 198): 652 MB of them before the world, 2,255 +/// to 2,352 MB right after its first frame, 2,800 to 3,100 MB two minutes +/// on, none of them idle (run 198's census). They are made with no room +/// test, in the same frame as the card copies of title buffers (762 MB), +/// after the texture queue has filled the card to its line with textures +/// written while the world loaded (7.3 GB of them at the first world frame +/// of run 193, of which 2.3 GB were let go again within 13 seconds). The +/// card then stood at 99 to 100.5 % of its budget, buffer copies were +/// turned down for good (31 of 95 made: the frame 355 ms where 95 give +/// 238), and the queue was refused from the first world frame on. With +/// their room kept, the queue stops that much earlier while the world +/// loads and gets it back as the targets are made. +/// +/// The 3,072 MB were measured on Series X with a 12 GB card. Unless the +/// variable says otherwise it is 1,536 MB on Series S (render targets of +/// 1280x720 and less), and never more than 35 % of the card's `budget`: on a +/// 6 GB card (budget 5,153 MB, 2026-11-26 report) the 3,072 MB left the +/// textures some 1,500 MB, and 27,000 of them waited, drawn black. +#[cfg(windows)] +pub(crate) fn targets_room_kept(budget: u64) -> u64 { + use std::sync::atomic::Ordering::Relaxed; + static MOST: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new(); + let asked = *MOST.get_or_init(|| { + std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_MB") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .map(|mb| mb.min(8192) << 20) + }); + let most = asked.unwrap_or_else(|| { + let console = if crate::console::current() == crate::console::Console::SeriesS { 1536 << 20 } else { 3072 << 20 }; + console.min(budget / 100 * 35) + }); + // Every host texture's bytes less those of the copies the title fills. + let targets = HOST_TEXTURES[1].load(Relaxed).saturating_sub(KINDS[1].load(Relaxed)); + most.saturating_sub(targets) +} + +/// [`room`] as it was at most a tenth of a second ago, for a question +/// asked of many textures a frame ([`room`] asks the system each time). +#[cfg(windows)] +pub(crate) fn room_lately() -> bool { + use std::sync::atomic::Ordering::Relaxed; + // The tenth of a second of the last asking, counted from 1, and its + // answer in the lowest bit. + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let tenth = crate::host::now_ms() / 100 + 1; + let last = LAST.load(Relaxed); + if last >> 1 == tenth { + return last & 1 != 0; + } + let room = room(); + LAST.store((tenth << 1) | u64::from(room), Relaxed); + room +} + +/// The share of the card's budget, in percent, up to which host copies of +/// textures picked by index are made ([`room`]): 90 unless +/// `VICTORY_TEXTURE_ROOM_PERCENT` says another (50 to 99; 97 before Try +/// 6.12, whose all-out mode asks for 99). At 90 about a +/// tenth of the budget, 1,020 MB of 10,200, stays unused while thousands of +/// textures wait (runs 170-174); the card copies of title buffers from +/// 1 MiB up take 449 MB more of the card than before (941 against 492), +/// and 94 gives the textures about that much back. +#[cfg(windows)] +fn room_percent() -> u64 { + static PERCENT: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *PERCENT.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_ROOM_PERCENT") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .map_or(90, |percent| percent.clamp(50, 99)) + }) +} + +/// For the card accounting line ([`card_accounting`]): the title texture +/// made for a view of memory at `address` with the resource description +/// `desc`, if there is one ([`texture_at`] makes it; this does not). +#[cfg(windows)] +pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option<This> { + // Without the filler words and with them: whichever `texture_at` keeps. + let mut key = *desc; + key[1] = 0; + key[13] = 0; + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This) +} + +/// For the card accounting line: whether title texture `this` has a host +/// copy now (2), had one that was let go and not made again (1), or never +/// had one (0); the bytes (its host copy's on the card, or without one +/// what its console layout takes in title memory); and where its title +/// memory is. `None` for buffers. Not a use of the texture. +#[cfg(windows)] +pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> { + use std::sync::atomic::Ordering::Relaxed; + if this.is_null() { + return None; + } + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let memory = r.data() as u64; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + Some(match made.as_ref() { + Some((host, _)) => (2, host.bytes, memory), + None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory), + }) +} + +/// One line of where the card's memory is and what the queue of textures +/// picked by index would need (`VICTORY_CARD_ACCOUNTING=1`; `draw.rs` +/// `card_accounting` says when, and hands over the queue's side: `room` +/// as the pass found it, `due` its counts, `never` and `gone` the memory +/// of the due textures without a host copy). The line holds +/// - the host copies of textures the title fills that are alive: how +/// many, their bytes, and the bytes of the levels whose title memory is +/// not mapped (a host copy is made with every level of the description; +/// a texture streaming in has its small levels only). A copy's bytes +/// are shared out to its levels by their texels, so that part is an +/// estimate; +/// - the due slots: how many, and their textures by what they have on +/// the card (a host copy alive: no card memory needed; never one; one +/// that was let go), with the bytes the last two would need and how +/// much of their memory is mapped now; +/// - the host copies let go, made again and made since the line before. +/// +/// The textures are noted under the table's lock (their memory, their +/// description, their copy's bytes: about a millisecond for 18,000) and +/// the kernel is asked about their memory on a thread of its own, after +/// the lock is given back: one question for a texture that is all there +/// (up to 256 pages each; 18,000 textures of 5.5 GB are 1.4 million +/// pages, some 20,000 questions), one per level and array slice more for +/// one that is not. Not measured: a tenth to half a second is expected, +/// and the line says what it took. No line is begun while one is walking. +#[cfg(windows)] +pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, gone: Vec<(u64, u64)>) { + use std::sync::atomic::Ordering::Relaxed; + static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + // Host copies let go and their bytes, made again and their bytes, and + // made in all, at the line before. + static BEFORE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + if WALKING.swap(true, Relaxed) { + return; + } + let began = std::time::Instant::now(); + // (The last: made level by level, its bytes are those of its tiles.) + let mut copies: Vec<(usize, ResourceDesc, u64, bool)> = Vec::new(); + // Textures the title fills without a host copy: never one, one let go. + let mut without = [0u64; 2]; + { + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + if !fills(&r.desc) { + continue; + } + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + match made.as_ref() { + Some((host, _)) => copies.push(match &host.tiled { + Some(tiled) => (r.data() as usize, r.desc, tiled.given_bytes(), true), + None => (r.data() as usize, r.desc, host.bytes, false), + }), + None => without[usize::from(r.host.gone.load(Relaxed))] += 1, + } + } + } + let kinds = KINDS.each_ref().map(|k| k.load(Relaxed)); + let mut since = [0u64; 5]; + for ((slot, now), before) in since.iter_mut().zip([kinds[2], kinds[3], kinds[4], kinds[5], kinds[6]]).zip(&BEFORE) { + *slot = now.saturating_sub(before.swap(now, Relaxed)); + } + let video = crate::host::host().and_then(|h| h.video_memory()); + let noted_us = began.elapsed().as_micros() as u64; + let walk = move || { + fn texels(m: &texture::Mip) -> u64 { + u64::from(m.width) * u64::from(m.height) * u64::from(m.depth) + } + let began = std::time::Instant::now(); + // Copies; their bytes; the bytes of levels not mapped; copies with + // a level not mapped; with the largest level not mapped; with no + // level mapped; copies without a console layout (not asked). + let mut c = [0u64; 7]; + // Of the copies: made level by level, and the bytes of their tiles. + let mut on_demand = [0u64; 2]; + for &(memory, desc, bytes, by_level) in &copies { + c[0] += 1; + c[1] += bytes; + if by_level { + on_demand[0] += 1; + on_demand[1] += bytes; + continue; + } + let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else { + c[6] += 1; + continue; + }; + if layout.size == 0 || crate::texture::committed(memory as *const u8, layout.size as usize) { + continue; + } + c[3] += 1; + // Every slice holds the whole chain: the levels of the tail in + // its first block, the others after it from the smallest up + // (`victory_formats::texture::Layout`). + let mips = &layout.mips; + let tail = (layout.first_tail_mip as usize).min(mips.len()); + let there = |from: u64, to: u64| { + (0..u64::from(layout.slices)).all(|slice| { + let at = memory as u64 + slice * layout.slice_size + from; + crate::texture::committed(at as *const u8, (to - from) as usize) + }) + }; + let all: u64 = mips.iter().map(texels).sum::<u64>().max(1); + let (mut missing, mut any) = (0u64, false); + for (level, m) in mips.iter().enumerate().take(tail) { + let end = if level == 0 { layout.slice_size } else { mips[level - 1].offset }; + if end <= m.offset { + continue; + } + if there(m.offset, end) { + any = true; + } else { + missing += texels(m); + c[4] += u64::from(level == 0); + } + } + if tail < mips.len() { + if there(0, layout.alignment.min(layout.slice_size).max(1)) { + any = true; + } else { + missing += mips[tail..].iter().map(texels).sum::<u64>(); + } + } + c[2] += (u128::from(bytes) * u128::from(missing) / u128::from(all)) as u64; + c[5] += u64::from(!any); + } + // Of the due textures without a host copy: how many; the bytes of + // their memory; with all of it mapped, and those bytes; with part + // of it mapped, and the bytes that are; with none of it mapped. + let mapped = |list: &[(u64, u64)]| { + let mut n = [0u64; 7]; + for &(at, len) in list { + n[0] += 1; + n[1] += len; + let there = crate::texture::mapped_bytes(at as *const u8, len as usize); + if len > 0 && there >= len { + n[2] += 1; + n[3] += len; + } else if there > 0 { + n[4] += 1; + n[5] += there; + } else { + n[6] += 1; + } + } + n + }; + let (never, gone) = (mapped(&never), mapped(&gone)); + let [budget_mb, used_mb] = video.map_or([0, 0], |v| [v[0] >> 20, v[1] >> 20]); + let [copies_n, copies_mb, unmapped_mb, partly, largest, nothing, unknown] = + [c[0], c[1] >> 20, c[2] >> 20, c[3], c[4], c[5], c[6]]; + let [without_never, without_gone] = without; + let [due_slots, due_uploaded, due_other, alive_n, alive_mb] = [due[0], due[1], due[2], due[3], due[4] >> 20]; + let [never_n, never_mb, never_whole, never_whole_mb, never_part, never_part_mb, never_none] = + [never[0], never[1] >> 20, never[2], never[3] >> 20, never[4], never[5] >> 20, never[6]]; + let [gone_n, gone_mb, gone_whole, gone_whole_mb, gone_part, gone_part_mb, gone_none] = + [gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]]; + let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]]; + let walk_ms = began.elapsed().as_millis() as u64; + let [by_level_n, by_level_mb] = [on_demand[0], on_demand[1] >> 20]; + tracing::info!( + "card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \ + fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \ + with such a level, {largest} of them the largest level, {nothing} with no level mapped; {unknown} without a console layout, not \ + asked); title textures without a host copy: {without_never} never had one, {without_gone} had one let go; due slots: \ + {due_slots} ({due_uploaded} uploaded before, {due_other} of nothing the title fills), their textures: {alive_n} with a host \ + copy alive ({alive_mb} MB, no card memory needed); {never_n} that never had one ({never_mb} MB of title memory: {never_whole} \ + all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \ + copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \ + {gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \ + {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own; of the host \ + copies {by_level_n} are made level by level and hold {by_level_mb} MB of tiles (in the MB alive, not in the levels not mapped)" + ); + WALKING.store(false, Relaxed); + }; + if std::thread::Builder::new().name("card accounting".into()).spawn(walk).is_err() { + WALKING.store(false, Relaxed); + } +} + +/// Lets go of the host copies of textures the title fills that nothing +/// names any more: placed textures were never released (one host texture +/// per address and description ever viewed: 18,639 of them, 2.5 GB, after +/// nine minutes of run 24), nor those of texture objects before the title +/// released them. A host copy goes when +/// - the title fills the texture ([`fills`]) and the host never copied +/// into it: its contents are in title memory; +/// - only the resource holds it: no list not yet reset names it (a list +/// holds the copies of the textures it uses, `HostList::transition`); +/// - only the host copy holds the host texture: no descriptor slot views +/// it (a slot keeps what it views, `HostHeap::kept`), so no shader can +/// read it through a slot made earlier, by a table or by an index; +/// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames. +/// +/// The next use makes the host copy anew and uploads the title's memory +/// again (its staging state goes with it). The title resource stays: its +/// address is what views and lists name. +/// shortcut: [`host_resource`] hands out the host texture without holding +/// it; a thread that asked for it and has not yet recorded its use (which +/// makes the list or the slot hold it) is protected by that idle time alone. +/// Every caller uses it at once, within the title's call. +/// Called before a submission starts, by the thread that submits. +/// `VICTORY_TEXTURE_SWEEP=0` lets nothing go. +#[cfg(windows)] +pub(crate) fn let_go_idle() { + use std::sync::atomic::Ordering::Relaxed; + const IDLE_FRAMES: u64 = 4; + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { + return; + } + let idle_ms = crate::host::vram_idle_ms(crate::host::host().and_then(|h| h.video_memory())) + .min(crate::pressure::idle_cap_ms(true)); + // For the trail (`crate::host::trail`): how many went, their bytes, + // and the first one. + let (mut went, mut bytes, mut first) = (0u64, 0u64, None); + let all = textures(); + for &at in all.iter() { + // SAFETY: a texture leaves the table before it is freed, under the + // lock held here (`Drop for Resource`). + let r = unsafe { &*(at as *const Resource) }; + if !fills(&r.desc) || crate::texture::host_wrote(at) { + continue; + } + let gone = { + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let idle = made.as_ref().is_some_and(|(host, _)| { + crate::host::long_ago(r.host.used.load(Relaxed), idle_ms, IDLE_FRAMES) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1 + }); + if idle { + // Under the lock: the next use must not find the staging + // state of the texture let go (it says "uploaded"). + crate::texture::unstage(at as This); + made.take() + } else { + None + } + }; + if let Some((host, _)) = gone { + r.host.gone.store(true, Relaxed); + KINDS[2].fetch_add(1, Relaxed); + KINDS[3].fetch_add(host.bytes, Relaxed); + went += 1; + bytes += host.bytes; + if first.is_none() { + first = Some(at); + } + crate::host::retire(host); + } + } + if went > 0 { + crate::host::trail(|| { + format!( + "sweep: {went} host copies of textures the title fills let go ({} KiB), each held by its title texture alone (no list, no slot); the first: title texture {:#x}", + bytes >> 10, + first.unwrap_or(0) + ) + }); + } +} + +/// For the memory line: the host copies the sweep never lets go +/// ([`let_go_idle`] takes only copies of textures the title fills that the +/// host never copied into), by what would say they are dead weight. A +/// count and the bytes (twins included) of: the copies the host renders to +/// or writes; of them, those whose title memory is not mapped now (its +/// first page); those nothing has used for 30 seconds and 60 frames and +/// that no list and no slot holds; those that are both; the copies of +/// textures the title fills that the host copied into; and, of the first, +/// the placed ones. Render-target copies grew from 2,319 MB at the world's +/// first frame to 3,075 MB 150 s later in run 197 and never shrank, while +/// 26,517 copies of filled textures were let go to stay under the card's +/// line. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn targets_census() -> [u64; 12] { + use std::sync::atomic::Ordering::Relaxed; + let mut c = [0u64; 12]; + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let Some((host, twin)) = made.as_ref() else { + continue; + }; + let copied_into = host.filled && crate::texture::host_wrote(at); + if host.filled && !copied_into { + continue; + } + let bytes = host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes); + let mut add = |i: usize| { + c[i] += 1; + c[i + 1] += bytes; + }; + if copied_into { + add(8); + continue; + } + add(0); + let placed = r.host.placed.load(Relaxed); + // Its first page: what is there of a texture starts there. + let unmapped = placed && !crate::texture::committed(r.data().cast_const(), 1); + let idle = crate::host::long_ago(r.host.used.load(Relaxed), 30_000, 60) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1; + if unmapped { + add(2); + } + if idle { + add(4); + } + if unmapped && idle { + add(6); + } + if placed { + add(10); + } + } + c +} + +/// For the memory line: title textures with a host copy the host renders +/// to or writes and those copies' bytes (twins included); title textures +/// without a host copy and the bytes of title memory they are; host copies +/// of textures the title fills and their bytes; of all title textures, +/// the placed ones with a host copy; the bytes of the twins alone (the +/// layer's own: the console has no second texture for a depth texture +/// shaders write); and, of the host copies of placed textures the title +/// fills, the bytes of those whose title memory is not mapped any more and +/// of those a descriptor slot still shows (the card holds a texture the +/// title has given up for as long as a slot shows it). The last two are +/// estimates from every 16th such texture: asking Windows about the memory +/// of all 16,000 takes too long. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn census() -> [u64; 10] { + const EVERY: u64 = 16; + let mut count = [0u64; 10]; + let mut placed_filled = 0u64; + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + match made.as_ref() { + Some((host, twin)) => { + let kind = if host.filled { 4 } else { 0 }; + count[kind] += 1; + count[kind + 1] += host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes); + count[7] += twin.as_ref().map_or(0, |t| t.colour.bytes); + let placed = r.host.placed.load(std::sync::atomic::Ordering::Relaxed); + if placed { + count[6] += 1; + } + if placed && host.filled { + placed_filled += 1; + // Its first page: a texture's smallest mips lie there, + // and are mapped first and unmapped last. + if placed_filled.is_multiple_of(EVERY) && !crate::texture::committed(r.data().cast_const(), 1) { + count[8] += host.bytes * EVERY; + if crate::host::references(&host.texture) > 1 { + count[9] += host.bytes * EVERY; + } + } + } + } + None => { + count[2] += 1; + count[3] += footprint(&r.desc).map_or(0, |f| f.size); + } + } + } + count +} + +/// Host textures alive (the title's and the twins) and the bytes the host +/// gives them, for the memory line. +#[cfg(windows)] +pub(crate) static HOST_TEXTURES: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The bytes the host allocates for `texture`. +#[cfg(windows)] +fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> u64 { + let Some(host) = crate::host::host() else { + return 0; + }; + // SAFETY: plain queries on a live resource and device. + unsafe { + let desc = texture.GetDesc(); + host.device.GetResourceAllocationInfo(0, &[desc]).SizeInBytes + } +} + +#[cfg(windows)] +impl HostTexture { + fn new(texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32) -> HostTexture { + use std::sync::atomic::Ordering::Relaxed; + let bytes = host_bytes(&texture); + HOST_TEXTURES[0].fetch_add(1, Relaxed); + HOST_TEXTURES[1].fetch_add(bytes, Relaxed); + HostTexture { + texture, + state: std::sync::atomic::AtomicU32::new(state), + bytes, + filled: false, + tiled: None, + } + } + + /// A texture made without memory of its own (`crate::tiles`): counted + /// as a host texture of no bytes. + fn new_tiled( + texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, + state: u32, + tiled: crate::tiles::Tiled, + ) -> HostTexture { + HOST_TEXTURES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + HostTexture { + texture, + state: std::sync::atomic::AtomicU32::new(state), + bytes: 0, + filled: false, + tiled: Some(tiled), + } + } +} + +#[cfg(windows)] +impl Drop for HostTexture { + fn drop(&mut self) { + use std::sync::atomic::Ordering::Relaxed; + HOST_TEXTURES[0].fetch_sub(1, Relaxed); + HOST_TEXTURES[1].fetch_sub(self.bytes, Relaxed); + if self.filled { + KINDS[0].fetch_sub(1, Relaxed); + KINDS[1].fetch_sub(self.bytes, Relaxed); + } + } +} + +/// How many textures placed in title memory have a resource of ours +/// (never released), for the memory line. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn placed_textures() -> u64 { + PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).len() as u64 +} + +/// Moves the host texture to `wanted` (a host texture state); the host +/// resource and the state it leaves, if that is a change. +#[cfg(windows)] +pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> { + use windows::core::Interface; + let (host, _) = hosted(this, true)?; + let before = host + .state + .swap(wanted, std::sync::atomic::Ordering::Relaxed); + (before != wanted).then(|| (host.texture.as_raw(), before)) +} + +/// The host GPU's copy of a title resource, if it has one: made now if +/// this is the texture's first use ([`Hosted`]). Asking is a use; what must +/// not count as one asks `host_made`. +#[cfg(windows)] +pub(crate) fn host_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (host, _) = hosted(this, true)?; + // SAFETY: the resource holds the host copy until the title releases it + // (lists and slots that name the texture hold it past that), or until + // `let_go_idle` takes it: only from a texture the title fills, that no + // list and no slot holds and that nothing asked for in seconds (the + // asking just made is noted under the same lock). + Some(unsafe { &*std::ptr::from_ref(&host.texture) }) +} + +/// A title texture's host copy, shared, for a list to hold. +#[cfg(windows)] +pub(crate) fn host_copy(this: This) -> Option<std::sync::Arc<HostTexture>> { + if this.is_null() { + return None; + } + hosted(this, true).map(|made| made.0) +} + +/// Why [`host_texture`] made no host texture. +#[cfg(windows)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum NoTexture { + /// The host will not make this description: not asked again. + Refused, + /// The card had no room then (`E_OUTOFMEMORY`), or there was no host + /// yet: asked again on a later use (upstream VIctory #3198). + ForNow, +} + +/// How long a texture the card had no room for waits before it is asked +/// for again ([`Hosted::no_room`]): each ask is a `CreateCommittedResource`. +#[cfg(windows)] +const NO_ROOM_AGAIN_MS: u64 = 1000; + +/// Host textures not made for lack of room, and made on a later use after +/// that (for the memory line). +#[cfg(windows)] +pub(crate) static NOT_MADE_FOR_NOW: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +#[cfg(windows)] +pub(crate) static MADE_AFTER_NO_ROOM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// What a failed host texture creation means for the texture: only a card +/// out of memory is worth asking again. +#[cfg(windows)] +fn no_texture(code: HRESULT) -> NoTexture { + if code == E_OUTOFMEMORY { NoTexture::ForNow } else { NoTexture::Refused } +} + +/// A host texture like the title's: same description, in GPU memory, +/// without the console's layout and flags. +#[cfg(windows)] +fn host_texture( + desc: &ResourceDesc, + state: u32, + clear: *const c_void, +) -> Result<windows::Win32::Graphics::Direct3D12::ID3D12Resource, NoTexture> { + host_texture_as(desc, state, clear, false) +} + +/// [`host_texture`]; `reserved`: without memory of its own, to be given +/// tiles level by level (`crate::tiles`). +#[cfg(windows)] +fn host_texture_as( + desc: &ResourceDesc, + state: u32, + clear: *const c_void, + reserved: bool, +) -> Result<windows::Win32::Graphics::Direct3D12::ID3D12Resource, NoTexture> { + use windows::Win32::Graphics::Direct3D12::*; + const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access + if desc.dimension == BUFFER { + return Err(NoTexture::Refused); + } + let host = crate::host::host().ok_or(NoTexture::ForNow)?; + let mut d = *desc; + d.layout = 0; + d.alignment = 0; + d.flags &= PC_FLAGS; + // PC refuses depth targets that are also unordered-access (the console + // allows both; the title's shadow maps ask for it). + // The host copy loses the unordered access: shaders write a colour + // twin instead ([`Twin`]). + const DEPTH: u32 = 2; + const UNORDERED: u32 = 4; + if d.flags & DEPTH != 0 { + if d.flags & UNORDERED != 0 { + DEPTH_UNORDERED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + d.flags &= !UNORDERED; + } + d.format = pc_format(d.format); + const TARGET: u32 = 1; + if d.flags & (TARGET | UNORDERED) != 0 { + d.format = target_format(d.format); + } + const DENY_SHADER_RESOURCE: u32 = 8; + if d.flags & DENY_SHADER_RESOURCE == 0 + && let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format) + { + d.format = typeless; + } + // The host has no sRGB unordered access: such textures are typeless, + // their unordered access views plain UNORM. + if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) { + d.format = family(d.format); + } + // The clear value names the format too: format, then color or depth + // and stencil (5 words). + let clear_value = (!clear.is_null()).then(|| { + // SAFETY: the title passes a whole clear value. + let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() }; + value[0] = pc_format(value[0]); + if d.flags & (TARGET | UNORDERED) != 0 { + value[0] = target_format(value[0]); + } + value + }); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut texture: Option<ID3D12Resource> = None; + let made = if reserved { + // The card's own layout of 64 KiB tiles, which a reserved texture + // must have. + d.layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE.0 as u32; + // SAFETY: as below; a texture the title fills has no clear value. + unsafe { + host.device.CreateReservedResource( + (&raw const d).cast(), + D3D12_RESOURCE_STATES( + crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, + ), + None, + &mut texture, + ) + } + } else { + // SAFETY: the description has the host layout (checked size, same + // fields); the out pointer is ours. + unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES( + crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, + ), + // The same layout: format, then color or depth and stencil. + clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), + &mut texture, + ) + } + }; + if let Err(e) = made { + let why = no_texture(e.code().0); + // Out of room may come back each second for many textures: its + // first and then every power-of-two-th line only. + static NO_ROOM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = (why == NoTexture::ForNow) + .then(|| NO_ROOM.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1); + if n.is_none_or(u64::is_power_of_two) { + tracing::warn!(error = %e, desc = ?d, reserved, ?why, times = n, "no host texture"); + } + return Err(why); + } + let texture = texture.ok_or(NoTexture::Refused)?; + crate::host::name(&texture, || { + format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) + }); + Ok(texture) +} + +/// The host copy of title texture `this` if it is made and was made +/// without memory of its own (`crate::tiles`); it is not made here. +#[cfg(windows)] +pub(crate) fn host_tiled(this: This) -> Option<OnDemand> { + if this.is_null() || !crate::tiles::wanted() { + return None; + } + hosted(this, false).map(|(host, _)| host).filter(|host| host.tiled.is_some()).map(OnDemand) +} + +/// The first level a view of title texture `this` may show, if its host +/// copy is made level by level and some level is held and has memory +/// (`crate::tiles::Tiled::first_shown`). +#[cfg(windows)] +pub(crate) fn first_shown(this: This) -> Option<u32> { + host_tiled(this)?.tiled()?.first_shown() +} + +/// A host copy made without memory of its own (`crate::tiles`), as a +/// submission-time step of a list holds it. +#[cfg(windows)] +pub(crate) struct OnDemand(std::sync::Arc<HostTexture>); + +// SAFETY: the host texture is named only in queue calls, which any thread +// may make; what it has been given is behind a lock of its own. +#[cfg(windows)] +unsafe impl Send for OnDemand {} +// SAFETY: as above. +#[cfg(windows)] +unsafe impl Sync for OnDemand {} + +#[cfg(windows)] +impl OnDemand { + pub(crate) fn tiled(&self) -> Option<&crate::tiles::Tiled> { + self.0.tiled.as_ref() + } + + /// [`crate::tiles::Tiled::uploaded`]; `memory`: where the texture's + /// title memory starts (its slots are made again if the first level + /// they may show changed). + /// Held levels get tiles only while the card has room ([`room`]). + /// Returns whether a level is still without its tiles: the caller + /// records the upload again later. + pub(crate) fn uploaded(&self, held: u32, memory: u64) -> bool { + let Some(tiled) = &self.0.tiled else { + return false; + }; + let room = room(); + let (changed, waiting) = if !room && squeeze_room() { + tiled.uploaded_small(&self.0.texture, held) + } else { + tiled.uploaded(&self.0.texture, held, room) + }; + if changed { + crate::descriptor::host::levels_changed(memory); + } + if tiled.blurred() { + crate::descriptor::host::blurred(memory); + } + if waiting { + crate::tiles::STATS[9].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + waiting + } + + /// [`crate::tiles::Tiled::card_wrote`]; `memory` as above. + pub(crate) fn card_wrote(&self, levels: u32, memory: u64) { + if let Some(tiled) = &self.0.tiled + && tiled.card_wrote(&self.0.texture, levels) + { + crate::descriptor::host::levels_changed(memory); + } + } +} + +/// A texture's console memory and description; `None` for buffers. +pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { + if this.is_null() { + return None; + } + let r = resource(this); + (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc)) +} + +/// A buffer's host memory and size; `None` for textures. +pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> { + if this.is_null() { + return None; + } + let r = resource(this); + (r.desc.dimension == BUFFER).then(|| (r.data(), r.desc.width)) +} + +impl Resource { + fn data(&self) -> *mut u8 { + match self.backing { + Backing::Committed(ref memory) => memory.ptr.as_ptr(), + // SAFETY: placement checked the range lies inside the heap. Backing::Placed { heap, offset } => unsafe { (*heap.cast::<Heap>()) .memory @@ -1030,7 +2448,7 @@ fn resource<'a>(this: This) -> &'a Resource { // The creation methods' own arguments, passed on. #[allow(clippy::too_many_arguments)] fn hand_out_resource( - mut desc: ResourceDesc, + desc: ResourceDesc, heap: HeapProperties, heap_flags: u32, backing: Backing, @@ -1039,18 +2457,8 @@ fn hand_out_resource( iid: *const Iid, out: *mut This, ) -> HRESULT { - if desc.dimension != BUFFER && desc.mip_levels == 0 { - desc.mip_levels = mip_count(&desc) as u16; - } #[cfg(not(windows))] let _ = (state, clear); - // The clear value is the caller's only during the call. - #[cfg(windows)] - let made_with = ( - state, - // SAFETY: the title passes a whole clear value (5 words) or null. - (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() }), - ); let resource = Box::new(Resource { object: Object::new(&RESOURCE_FUNCTIONS), desc, @@ -1058,10 +2466,35 @@ fn hand_out_resource( heap_flags, backing, #[cfg(windows)] - host: std::sync::OnceLock::new(), - #[cfg(windows)] - made_with, + host: Hosted { + made: std::sync::Mutex::new(None), + state, + // SAFETY: the title passes a whole clear value (the format, + // then color or depth and stencil: 5 words) or null. + clear: (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() }), + used: std::sync::atomic::AtomicU64::new(0), + refused: std::sync::atomic::AtomicBool::new(false), + no_room: std::sync::atomic::AtomicU64::new(0), + gone: std::sync::atomic::AtomicBool::new(false), + placed: std::sync::atomic::AtomicBool::new(false), + }, }); + // The host copy waits for the texture's first use ([`Hosted`]). + #[cfg(windows)] + if desc.dimension != BUFFER { + let at = std::ptr::from_ref::<Resource>(&resource) as usize; + textures().insert(at); + crate::texback::replaced(resource.data() as usize); + if !fills(&desc) { + TARGETS_AT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(resource.data() as u64, at); + } + if !lazy() { + let _ = hosted(at as This, true); + } + } #[cfg(windows)] if desc.dimension == BUFFER { let at = std::ptr::from_ref::<Resource>(&resource) as usize; @@ -1073,12 +2506,30 @@ fn hand_out_resource( #[cfg(windows)] impl Drop for Resource { fn drop(&mut self) { - #[cfg(feature = "diagnostics")] - if self + // Out of the table of textures first: the sweep looks at the ones + // in it, under its lock. + if self.desc.dimension != BUFFER { + let address = std::ptr::from_ref::<Resource>(self) as usize; + crate::texback::released(address); + textures().remove(&address); + if !fills(&self.desc) { + let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); + let at = self.data() as u64; + if targets.get(&at) == Some(&(std::ptr::from_ref::<Resource>(self) as usize)) { + targets.remove(&at); + } + } + } + let made = self .host - .get() - .and_then(Option::as_ref) - .is_some_and(|h| std::sync::Arc::strong_count(h) > 1) + .made + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .take(); + #[cfg(feature = "diagnostics")] + if made + .as_ref() + .is_some_and(|(h, _)| std::sync::Arc::strong_count(h) > 1) { // Before lists held their textures, this freed a texture that // lists not yet run still named (a GPU page fault). @@ -1092,9 +2543,13 @@ impl Drop for Resource { ); } } - // A running submission may still read the host copy. - if let Some(host) = self.host.take().flatten() { + // A running submission may still read the host copy (and a depth + // texture's colour twin). + if let Some((host, twin)) = made { crate::host::retire(host); + if let Some(twin) = twin { + crate::host::retire(twin); + } } crate::texture::forget(std::ptr::from_ref::<Resource>(self) as usize); crate::descriptor::forget(std::ptr::from_ref::<Resource>(self) as usize); @@ -1147,7 +2602,7 @@ pub(crate) extern "system" fn create_committed( ) } -/// Device method 0x3f8, inferred from Grand Theft Auto VI's calls +/// Device method 0x3f8, inferred from the title's calls /// (title+0x193e1b4: its back buffers, heap flag "allow display"): the /// committed resource creation of the enhanced-barrier interfaces, /// `(heap, heap flags, desc1, initial layout, clear value, protected @@ -1210,7 +2665,7 @@ pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HR } /// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11` -/// additions. From Grand Theft Auto VI's call: a resource at a virtual +/// additions. From the title's call: a resource at a virtual /// address the title mapped itself, `(address, desc1, initial barrier /// layout, clear value, iid, out)`, as `CreatePlacedResourceX` with /// enhanced barriers. GPU addresses are CPU addresses, so the resource is @@ -1260,21 +2715,127 @@ pub(crate) extern "system" fn create_at_address( } /// Textures the title placed in its own memory and views without a -/// resource object (device 0x230, Grand Theft Auto VI's streamed and +/// resource object (device 0x230, the title's streamed and /// interface textures), by address and description: a resource at that /// address, made the first time a draw reads one. -/// shortcut: never released (one host texture per distinct address and -/// description viewed); release them when the title unmaps or reuses the -/// memory once streaming grows VRAM use. +/// The resource is kept for the run (views and lists name its address); +/// its host texture is let go when nothing names it any more +/// ([`let_go_idle`]) and made again on the next use. #[cfg(windows)] static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; 14]), usize>> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +/// The placed textures asked for with filler words set, as asked +/// (address and description): for [`PLACED_TWINS`]. +#[cfg(windows)] +static PLACED_RAW: std::sync::Mutex<std::collections::BTreeSet<(u64, [u32; 14])>> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + +/// Placed textures asked for a second time with other filler words in +/// their description: each was a second resource and host copy before the +/// filler was left out of the key ([`texture_at`]). +#[cfg(windows)] +static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// See [`PLACED_TWINS`] (read by the diagnostics build's memory line). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn placed_filler_twins() -> u64 { + PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Width, height and format of texture `this` (`None` for a buffer), for +/// `crate::texback`'s kinds. +#[cfg(windows)] +pub(crate) fn texture_kind(this: This) -> Option<(u64, u32, u32)> { + if this.is_null() { + return None; + } + let r = resource(this); + const TEXTURE_2D: u32 = 3; + (r.desc.dimension == TEXTURE_2D && r.desc.sample_count <= 1) + .then_some((r.desc.width, r.desc.height, r.desc.format)) +} + +/// Texture `this`'s console layout (one plane), where it lies in title +/// memory and the bytes that layout takes, for `crate::texback`; `None` for +/// a buffer or a texture with planes. +#[cfg(windows)] +pub(crate) fn title_texture(this: This) -> Option<(victory_formats::texture::Layout, usize, usize)> { + if this.is_null() { + return None; + } + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let t = texture_layout(&r.desc)?; + let [plane] = &t.planes[..] else { + return None; + }; + Some((plane.layout.clone(), r.data() as usize, t.size as usize)) +} + +/// The bytes of title memory a texture with the resource description +/// `desc` (as words) takes where the title placed it; `None` for a buffer +/// and for a description without a size. +#[cfg(windows)] +pub(crate) fn placed_bytes(desc: &[u32; 14]) -> Option<u64> { + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() }; + if d.dimension == BUFFER { + return None; + } + footprint(&d).map(|f| f.size) +} + +/// The resource [`texture_at`] made for a texture placed at `address` with +/// the description `desc`, if it has made one: never made here (for the +/// frame listing, which must not count as a use). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option<This> { + let mut key = *desc; + key[1] = 0; + key[13] = 0; + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?; + Some(*found as This) +} + /// The resource for a texture placed at `address` with the resource /// description `desc` (as words), made on first use. #[cfg(windows)] pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { + // Words 1 and 13 of the description are the filler of its layout + // (after the dimension, and at the end): the title leaves there what + // its stack held, and two views of one texture that differed only in + // them each got a resource and a host copy of their own, on a card + // that fills at world entry. They are not part of what a texture is. + // `VICTORY_PLACED_FILLER=1`: kept in the key, as before. + static KEPT: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let raw = *desc; + let mut key = *desc; + if !*KEPT.get_or_init(|| std::env::var_os("VICTORY_PLACED_FILLER").is_some_and(|v| v == "1")) { + key[1] = 0; + key[13] = 0; + } + let desc = &key; let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + // How many resources the filler alone would have added (a count for + // the log: `placed_filler_twins`). + if raw != key { + let mut seen = PLACED_RAW.lock().unwrap_or_else(|e| e.into_inner()); + if seen.insert((address, raw)) { + let others = seen.range((address, [0; 14])..=(address, [u32::MAX; 14])).filter(|(_, r)| { + let mut blank = *r; + blank[1] = 0; + blank[13] = 0; + blank == key + }); + if others.count() > 1 { + PLACED_TWINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + } if let Some(&r) = map.get(&(address, *desc)) { return Some(r as This); } @@ -1297,7 +2858,12 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { return None; } map.insert((address, *desc), out as usize); - resource(out).host().is_some().then_some(out) + crate::texture::placed_in_host_written(address, desc); + resource(out) + .host + .placed + .store(true, std::sync::atomic::Ordering::Relaxed); + Some(out) } pub(crate) extern "system" fn create_placed( @@ -1371,12 +2937,8 @@ extern "system" fn map(this: This, _sub: u32, _read: *const c_void, out: *mut *m extern "system" fn unmap(_: This, _sub: u32, _written: *const c_void) {} extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) { if !out.is_null() { - let mut desc = resource(this).desc; - if desc.dimension != BUFFER && desc.mip_levels == 0 { - desc.mip_levels = mip_count(&desc) as u16; - } // SAFETY: checked non-null; the title passes room for a description. - unsafe { out.write(desc) }; + unsafe { out.write(resource(this).desc) }; } } /// Device method `GetCustomHeapProperties`, returning its struct through a @@ -1476,43 +3038,6 @@ static RESOURCE_FUNCTIONS: Table<32> = { Table(f) }; -#[cfg(test)] -pub(crate) fn test_buffer(width: u64) -> This { - let heap = HeapProperties { - kind: 1, - cpu_pages: 0, - pool: 0, - creation_nodes: 0, - visible_nodes: 0, - }; - let desc = ResourceDesc { - dimension: BUFFER, - alignment: 0, - width, - height: 1, - depth_or_array_size: 1, - mip_levels: 1, - format: 0, - sample_count: 1, - sample_quality: 0, - layout: 1, - flags: 0, - }; - let mut out = std::ptr::null(); - let hr = create_committed( - std::ptr::null(), - &heap, - 0, - &desc, - 0, - std::ptr::null(), - &RESOURCE_IIDS[0], - &mut out, - ); - assert_eq!(hr, S_OK); - out -} - #[cfg(test)] mod tests { use super::*; @@ -1622,7 +3147,7 @@ mod tests { slot::<Custom>(device, 0xd0)(&mut p, device, 1, 1); assert_eq!(p.cpu_pages, 1, "default: not CPU-visible"); - // 0x428: a buffer over memory the title owns, as GTA VI asks. + // 0x428: a buffer over memory the title owns, as the title asks. type At = extern "system" fn( This, u64, @@ -1717,245 +3242,82 @@ mod tests { info, AllocationInfo { size: KIB_64 + size(&descs[1]).unwrap(), - alignment: KIB_64 - } - ); - allocation_info(&mut info, std::ptr::null(), 0, 1, &texture(1, 1, 999, 1)); - assert_eq!(info.size, u64::MAX); - } - - #[cfg(windows)] - #[test] - fn a_missing_resource_has_no_default_view_format() { - assert_eq!(view_format(std::ptr::null()), None); - } - - #[test] - fn upload_footprints_follow_the_pc_rules() { - let null = std::ptr::null(); - let mut layouts = [NO_FOOTPRINT; 2]; - let (mut rows, mut sizes, mut total) = ([0; 2], [0; 2], 0); - let mut footprints = |desc: &ResourceDesc, first, count| { - let (l, r, s) = (layouts.as_mut_ptr(), rows.as_mut_ptr(), sizes.as_mut_ptr()); - copyable_footprints(null, desc, first, count, 0, l, r, s, &mut total); - (layouts, rows, sizes, total) - }; - // 100x60 RGBA8, 2 mips: 400-byte rows pitched to 512. - let (l, r, s, t) = footprints(&texture(100, 60, 28, 2), 0, 2); - assert_eq!((l[0].row_pitch, r[0], s[0]), (512, 60, 400)); - // Mip 1 (50x30, 200-byte rows) starts after 59 pitched rows and one - // packed row, rounded up to 512. - assert_eq!(l[1].offset, (512 * 59 + 400u64).next_multiple_of(512)); - assert_eq!((l[1].width, l[1].height, r[1]), (50, 30, 30)); - assert_eq!(t, l[1].offset + 256 * 29 + 200); - // BC1: rows of 4x4 blocks, 8 bytes each. - let (_, r, s, _) = footprints(&texture(64, 64, 71, 1), 0, 1); - assert_eq!((r[0], s[0]), (16, 128)); - let (_, _, _, t) = footprints(&texture(64, 64, 71, 1), 1, 1); - assert_eq!(t, u64::MAX, "no second subresource"); - } - - /// The title may view a texture as sRGB or linear whichever format it - /// made it in, as the console allows: a shader reads 0x80 as 0.216 - /// through the sRGB view, 0.502 through the linear one, and in the - /// texture's own format through a view without a description. - #[cfg(windows)] - #[test] - fn srgb_and_linear_views_of_one_texture_read_their_own_curve() { - use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; - use windows::Win32::Graphics::Direct3D::ID3DBlob; - use windows::Win32::Graphics::Direct3D12::*; - use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; - use windows::core::s; - let Some(host) = crate::host::host() else { - return; // no host GPU here - }; - const SOURCE: &str = r#" -#define RS "DescriptorTable(SRV(t0, numDescriptors=3)), UAV(u0)" -Texture2D<float4> as_srgb : register(t0); -Texture2D<float4> as_linear : register(t1); -Texture2D<float4> as_own : register(t2); -RWByteAddressBuffer reads : register(u0); -[RootSignature(RS)] -[numthreads(1, 1, 1)] -void main() { - int3 at = int3(1, 2, 0); - float3 r = float3(as_srgb.Load(at).r, as_linear.Load(at).r, as_own.Load(at).r); - reads.Store3(0, asuint(r)); -} -"#; - let mut blob: Option<ID3DBlob> = None; - // SAFETY: the source and names live through the call; the out - // pointer is ours. - unsafe { - D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), - s!("views"), - None, - None, - s!("main"), - s!("cs_5_1"), - 0, - 0, - &mut blob, - None, - ) - .unwrap() - }; - let blob = blob.unwrap(); - // SAFETY: the blob's own bytes. - let code = unsafe { - std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()) - }; - // SAFETY: plain object creation; the root signature is inside the - // shader. - let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { - let root: ID3D12RootSignature = host.device.CreateRootSignature(0, code).unwrap(); - let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: code.as_ptr().cast(), - BytecodeLength: code.len(), - }, - ..Default::default() - }; - let pso = host.device.CreateComputePipelineState(&desc).unwrap(); - (root, pso) - }; - let host_buffer = |kind: D3D12_HEAP_TYPE, flags, state| { - let mut b: Option<ID3D12Resource> = None; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: 256, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: flags, - ..Default::default() - }; - let heap = D3D12_HEAP_PROPERTIES { - Type: kind, - ..Default::default() - }; - // SAFETY: plain creation of a buffer. - unsafe { - host.device - .CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - &desc, - state, - None, - &mut b, - ) - .unwrap() - }; - b.unwrap() - }; - // The texture made in `own`, its memory filled with `block`: what - // the shader reads through the title's views in `views` (sRGB, - // linear) and through one without a description. - let read = |own: u32, views: [u32; 2], block: &[u8]| -> [f32; 3] { - let null = std::ptr::null(); - let mut image = null; - let desc = texture(4, 4, own, 1); - let iid = &RESOURCE_IIDS[0]; - assert_eq!( - create_committed(null, &PROPERTIES, 0, &desc, 0, null.cast(), iid, &mut image), - S_OK - ); - // Every element alike, so the layout does not matter. - let size = footprint(&desc).unwrap().size as usize; - // SAFETY: the texture's memory, `size` bytes. - let memory = unsafe { std::slice::from_raw_parts_mut(resource(image).data(), size) }; - for (i, b) in memory.iter_mut().enumerate() { - *b = block[i % block.len()]; - } - let mut slots = [0u64; 3 * 4]; - let base = slots.as_mut_ptr() as u64; - let at = |i: u32| base + 32 * u64::from(i); - // 2D, the default component mapping, one mip. - let mapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - let srv = |format| [format, 4, mapping, 0, 0, 1, 0, 0, 0, 0]; - crate::descriptor::create_srv(null, image, &srv(views[0]), at(0)); - crate::descriptor::create_srv(null, image, &srv(views[1]), at(1)); - crate::descriptor::create_srv(null, image, null.cast(), at(2)); - let heap = crate::descriptor::host::HostHeap::new(false, 3).unwrap(); - for i in 0..3 { - assert!(heap.mirror(i, at(i), true).is_some()); - } - let out = host_buffer( - D3D12_HEAP_TYPE_DEFAULT, - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_COMMON, - ); - let back = host_buffer( - D3D12_HEAP_TYPE_READBACK, - D3D12_RESOURCE_FLAG_NONE, - D3D12_RESOURCE_STATE_COPY_DEST, - ); - let list = host.new_list().unwrap(); - crate::texture::upload(&list, image, host_resource(image).unwrap()); - const NON_PIXEL_SHADER_RESOURCE: u32 = 0x40; - crate::list::ensure_state(&list, image, NON_PIXEL_SHADER_RESOURCE); - // SAFETY: an open list; our pipeline, heap and live resources. - unsafe { - let l = &list.list; - l.SetComputeRootSignature(&root); - l.SetPipelineState(&pso); - l.SetDescriptorHeaps(&[Some(heap.heap.clone())]); - l.SetComputeRootDescriptorTable(0, heap.heap.GetGPUDescriptorHandleForHeapStart()); - l.SetComputeRootUnorderedAccessView(1, out.GetGPUVirtualAddress()); - l.Dispatch(1, 1, 1); - l.ResourceBarrier(&[crate::host::transition( - &out, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_COPY_SOURCE, - )]); - l.CopyBufferRegion(&back, 0, &out, 0, 12); - } - list.close(); - host.execute(&[&list]); - let mut mapped = std::ptr::null_mut(); - // SAFETY: the copy finished (execute waits); it wrote 12 bytes. - let read = unsafe { - let range = D3D12_RANGE { Begin: 0, End: 12 }; - back.Map(0, Some(&range), Some(&mut mapped)).unwrap(); - mapped.cast::<[f32; 3]>().read_unaligned() - }; - assert_eq!(slot::<Release>(image, 0x10)(image), 0); - read - }; - let to_linear = |c: f32| ((c + 0.055) / 1.055).powf(2.4); - // 0x80 in every channel of 8-bit color; a BC1 block of one color, - // red 16 of 31 (132 of 255 when expanded to 8 bits first). - const RGBA: &[u8] = &[0x80]; - const BC1: &[u8] = &[0x00, 0x80, 0x00, 0x80, 0, 0, 0, 0]; - let cases = [ - (28, 29, 128.0 / 255.0, 0.002f32, RGBA), - (87, 91, 128.0 / 255.0, 0.002, RGBA), - (71, 72, 16.0 / 31.0, 0.01, BC1), - ]; - let mut wrong = Vec::new(); - for (linear, srgb, unorm, near, block) in cases { - for own in [linear, srgb] { - let curve = to_linear(unorm); - let wanted = [curve, unorm, if own == srgb { curve } else { unorm }]; - let got = read(own, [srgb, linear], block); - if got.iter().zip(wanted).any(|(g, w)| (g - w).abs() > near) { - wrong.push(format!( - "texture {own}, views {srgb}/{linear}/none: read {got:?}, wanted {wanted:?}" - )); - } + alignment: KIB_64 } + ); + allocation_info(&mut info, std::ptr::null(), 0, 1, &texture(1, 1, 999, 1)); + assert_eq!(info.size, u64::MAX); + } + + #[test] + fn upload_footprints_follow_the_pc_rules() { + let null = std::ptr::null(); + let mut layouts = [NO_FOOTPRINT; 2]; + let (mut rows, mut sizes, mut total) = ([0; 2], [0; 2], 0); + let mut footprints = |desc: &ResourceDesc, first, count| { + let (l, r, s) = (layouts.as_mut_ptr(), rows.as_mut_ptr(), sizes.as_mut_ptr()); + copyable_footprints(null, desc, first, count, 0, l, r, s, &mut total); + (layouts, rows, sizes, total) + }; + // 100x60 RGBA8, 2 mips: 400-byte rows pitched to 512. + let (l, r, s, t) = footprints(&texture(100, 60, 28, 2), 0, 2); + assert_eq!((l[0].row_pitch, r[0], s[0]), (512, 60, 400)); + // Mip 1 (50x30, 200-byte rows) starts after 59 pitched rows and one + // packed row, rounded up to 512. + assert_eq!(l[1].offset, (512 * 59 + 400u64).next_multiple_of(512)); + assert_eq!((l[1].width, l[1].height, r[1]), (50, 30, 30)); + assert_eq!(t, l[1].offset + 256 * 29 + 200); + // BC1: rows of 4x4 blocks, 8 bytes each. + let (_, r, s, _) = footprints(&texture(64, 64, 71, 1), 0, 1); + assert_eq!((r[0], s[0]), (16, 128)); + let (_, _, _, t) = footprints(&texture(64, 64, 71, 1), 1, 1); + assert_eq!(t, u64::MAX, "no second subresource"); + } + + /// Upstream VIctory #3198: only a card out of memory is asked again; any + /// other failure is a refusal for good. + #[cfg(windows)] + #[test] + fn only_a_card_without_room_is_asked_again() { + assert_eq!(no_texture(E_OUTOFMEMORY), NoTexture::ForNow); + assert_eq!(no_texture(E_INVALIDARG), NoTexture::Refused); + assert_eq!(no_texture(0x887A_0005_u32 as i32), NoTexture::Refused); // device removed + } + + /// A texture the card had no room for is not refused: once its wait is + /// over, the next use makes its host copy; a refused one stays refused. + #[cfg(windows)] + #[test] + fn a_texture_without_room_is_made_on_a_later_use() { + use std::sync::atomic::Ordering::Relaxed; + if crate::host::host().is_none() { + return; // no host GPU here } - assert!(wrong.is_empty(), "{wrong:#?}"); + let null = std::ptr::null(); + let mut image = null; + let rgba = texture(4, 4, 28, 1); + assert_eq!( + create_committed(null, &PROPERTIES, 0, &rgba, 0, null.cast(), &RESOURCE_IIDS[0], &mut image), + S_OK + ); + let r = resource(image); + // As `hosted` leaves a texture the card had no room for just now: + // not asked again yet, but still waited for (not refused). + *r.host.made.lock().unwrap() = None; + r.host.no_room.store(crate::host::moment().max(1), Relaxed); + assert!(hosted(image, true).is_none(), "asked again only after NO_ROOM_AGAIN_MS"); + assert!(host_waits(image), "a texture without room still waits for its host copy"); + // After the wait, the next use makes it. + std::thread::sleep(std::time::Duration::from_millis(NO_ROOM_AGAIN_MS + 200)); + assert!(hosted(image, true).is_some(), "made on a later use"); + assert_eq!(r.host.no_room.load(Relaxed), 0); + // Refused: never again. + *r.host.made.lock().unwrap() = None; + r.host.no_room.store(0, Relaxed); + r.host.refused.store(true, Relaxed); + assert!(hosted(image, true).is_none()); + assert!(!host_waits(image)); + crate::object::release_boxed::<Resource>(image); } /// A 4x4 texture filled from a title buffer through our list and queue, @@ -1965,8 +3327,7 @@ void main() { fn buffer_data_reaches_the_host_texture() { use windows::Win32::Graphics::Direct3D12::*; let Some(host) = crate::host::host() else { - eprintln!("Skipping texture readback: no usable host D3D12 device"); - return; + return; // no host GPU here }; let null = std::ptr::null(); let iid = &RESOURCE_IIDS[0]; @@ -2157,319 +3518,774 @@ void main() { } } - #[cfg(windows)] + /// An earlier title-memory upload must not suppress a later alias copy + /// from a GPU-written probe atlas into the same sampled texture. + #[cfg(all(windows, feature = "diagnostics"))] #[test] - fn copy_texture_region_reads_back_into_title_buffer() { - if crate::host::host().is_none() { + fn alias_after_title_upload_copies_the_gpu_atlas() { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + + let Some(host) = crate::host::host() else { return; - } + }; let null = std::ptr::null(); - let iid = &RESOURCE_IIDS[0]; - let tex_desc = ResourceDesc { - dimension: 3, // Texture2D - alignment: 0, - width: 4, - height: 4, - depth_or_array_size: 1, - mip_levels: 1, - format: 28, // R8G8B8A8_UNORM - sample_count: 1, - sample_quality: 0, - layout: 0, - flags: 0, + let mut source = null; + let mut view = null; + let source_desc = ResourceDesc { + flags: 4, + ..texture(4, 4, 42, 1) }; - let (mut image, mut upload_buf, mut dst_aligned, mut dst_packed, mut dst_crop) = - (null, null, null, null, null); assert_eq!( create_committed( - null, - &PROPERTIES, - 0, - &tex_desc, - 0, - null.cast(), - iid, - &mut image + null, &PROPERTIES, 0, &source_desc, 0, null.cast(), &RESOURCE_IIDS[0], &mut source, ), S_OK ); assert_eq!( - create_committed( - null, - &PROPERTIES, - 0, - &buffer(1024), - 0, - null.cast(), - iid, - &mut upload_buf + create_at_address( + null, resource(source).data() as u64, &texture(4, 4, 67, 1), 0, + null.cast(), &RESOURCE_IIDS[0], &mut view, ), S_OK ); + resource(view).host.placed.store(true, Relaxed); + assert_eq!(alias_of(view).map(|held| held.get()), Some(source)); + let written = host_resource(source).unwrap(); + let sampled = host_resource(view).unwrap(); + let (upload, data) = host.upload_buffer(1024).unwrap(); + let seed = host.new_list().unwrap(); + let packed_light = 0x8c02_0100_u32; + // SAFETY: four rows of four texels in the upload's 1024 mapped bytes. + unsafe { + for row in 0..4 { + for x in 0..4 { + data.add(row * 256 + x * 4).cast::<u32>().write_unaligned(packed_light); + } + } + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(written), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: written.GetDesc().Format, + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + crate::list::ensure_state(&seed, source, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + seed.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + seed.close(); + host.execute(&[&seed]); + + let list = host.new_list().unwrap(); + crate::texture::upload(&list, view, sampled); + assert!(crate::texture::alias(&list, view, source)); + crate::list::ensure_state(&list, view, D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32); + let (readback, rows) = crate::capture::read_back(&host.device, &list.list, sampled).unwrap(); + list.close(); + host.execute(&[&list]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the completed copy contains at least one 32-bit texel. + let actual = unsafe { + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let texel = mapped.cast::<u8>().add(rows.Offset as usize).cast::<u32>().read_unaligned(); + readback.Unmap(0, None); + texel + }; + resource_release(view); + resource_release(source); + assert_eq!(actual, packed_light, "the sampled texture kept the CPU upload instead of the GPU atlas"); + } + + /// A 16-bit depth texture the title also asks unordered access for gets + /// a colour twin, and the host copies one into the other, both ways: a + /// pattern put into the twin is copied to the depth texture, the twin + /// is overwritten with zeros, and the pattern comes back from the depth + /// texture. A copy the host does not allow ends the test (with the + /// debug layer's message under `VICTORY_D3D12_DEBUG=1` in a diagnostics + /// build). + #[cfg(windows)] + #[test] + fn a_depth_texture_and_its_twin_copy_into_each_other() { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 55, 1) + }; + let mut depth = null; assert_eq!( create_committed( null, &PROPERTIES, 0, - &buffer(2048), - 0, + &desc, + DEPTH_WRITE, null.cast(), - iid, - &mut dst_aligned + &RESOURCE_IIDS[0], + &mut depth ), S_OK ); - assert_eq!( - create_committed( - null, - &PROPERTIES, - 0, - &buffer(256), - 0, - null.cast(), - iid, - &mut dst_packed - ), - S_OK + let host_depth = host_resource(depth).unwrap(); + let Some(twin) = twin_resource(depth) else { + return; // twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) }; + // Both R16 typeless: one a depth texture, one with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (53, 2)); + assert_eq!((t.Format.0, t.Flags.0), (53, 4)); + + // Four rows of four 16-bit texels, 256 bytes apart as copies place + // them: the pattern, then as many zeros. + let mut pattern = vec![0u8; 1024]; + for row in 0..4 { + for b in 0..8 { + pattern[row * 256 + b] = (1 + row * 8 + b) as u8; + } + } + let (upload, data) = host.upload_buffer(2048).unwrap(); + // SAFETY: the buffer's mapping, 2048 bytes. + unsafe { + std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024); + std::ptr::write_bytes(data.add(1024), 0, 1024); + } + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option<ID3D12Resource> = None; + // SAFETY: plain creation of a readback buffer. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + + // A texture's one subresource; the four rows of a buffer at `offset`. + let whole = |texture: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let rows = |buffer: &ID3D12Resource, offset: u64| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(53), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let (written, tested, source, dest) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, ); + let moved = crate::host::transition; + let list = host.new_list().unwrap(); + // SAFETY: an open list and live resources; the two textures are one + // size in one format family. + unsafe { + let l = &list.list; + // The pattern into the twin, the twin into the depth texture. + l.ResourceBarrier(&[moved(twin, written, dest), moved(host_depth, tested, dest)]); + l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 0), None); + l.ResourceBarrier(&[moved(twin, dest, source)]); + l.CopyResource(host_depth, twin); + // Zeros over the twin, then the depth texture back into it. + l.ResourceBarrier(&[moved(twin, source, dest)]); + l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 1024), None); + l.ResourceBarrier(&[moved(host_depth, dest, source)]); + l.CopyResource(twin, host_depth); + // The twin read back; both textures to the states they had. + l.ResourceBarrier(&[moved(twin, dest, source)]); + l.CopyTextureRegion(&rows(&readback, 0), 0, 0, 0, &whole(twin), None); + l.ResourceBarrier(&[ + moved(twin, source, written), + moved(host_depth, source, tested), + ]); + } + list.close(); + host.execute(&[&list]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copies finished (execute waits); the buffer is 1024 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 1024, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::<u8>(), 1024) + }; + for row in 0..4 { + let at = row * 256; + assert_eq!(read[at..at + 8], pattern[at..at + 8], "row {row}"); + } + } + + /// A depth texture with a stencil plane that the title also asks + /// unordered access for gets a twin of the stencil plane, and what + /// shaders write there is in the stencil plane once the list is closed: + /// a pattern put into the twin is read back from the plane. + #[cfg(windows)] + #[test] + fn a_stencil_planes_twin_reaches_the_plane() { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 45, 1) + }; + let mut depth = null; assert_eq!( create_committed( null, &PROPERTIES, 0, - &buffer(1024), - 0, + &desc, + DEPTH_WRITE, null.cast(), - iid, - &mut dst_crop + &RESOURCE_IIDS[0], + &mut depth ), S_OK ); + let host_depth = host_resource(depth).unwrap(); + let Some(twin) = twin_resource(depth) else { + return; // twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) }; + // R24G8 typeless with depth, R8 typeless with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (44, 2)); + assert_eq!((t.Format.0, t.Flags.0), (60, 4)); - // Fill a 4x4 RGBA8 pattern (row_pitch 256): pixel (x, y) = [x*40+1, y*50+2, (x+y)*20+3, 0xff]. - let (up_ptr, _) = buffer_bytes(upload_buf).unwrap(); - // SAFETY: upload_buf holds 1024 bytes. - let up = unsafe { std::slice::from_raw_parts_mut(up_ptr, 1024) }; - for y in 0..4usize { - for x in 0..4usize { - let at = y * 256 + x * 4; - up[at..at + 4].copy_from_slice(&[ - (x * 40 + 1) as u8, - (y * 50 + 2) as u8, - ((x + y) * 20 + 3) as u8, - 0xff, - ]); + // Four rows of four texels, 256 bytes apart as copies place them. + let mut pattern = vec![0u8; 1024]; + for row in 0..4 { + for b in 0..4 { + pattern[row * 256 + b] = (1 + row * 4 + b) as u8; } } - - let queue_iid = guid( - 0x0ec870a6, - 0x5d7e, - 0x4c22, - [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], - ); - let allocator_iid = guid( - 0x6102dee4, - 0xaf59, - 0x4b09, - [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], - ); - let list_iid = guid( - 0x5b160d0f, - 0xac1b, - 0x4185, - [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], - ); - let (mut queue, mut allocator, mut list) = (null, null, null); - let queue_desc = [0u32; 4]; - assert_eq!( - crate::queue::create(null, queue_desc.as_ptr().cast(), &queue_iid, &mut queue), - S_OK - ); - assert_eq!( - crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator), - S_OK - ); - assert_eq!( - crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list), - S_OK - ); - - #[repr(C)] - struct Location { - resource: This, - kind: u32, - footprint: PlacedFootprint, - } - type Copy = extern "system" fn( - This, - *const Location, - u32, - u32, - u32, - *const Location, - *const [u32; 6], - ); - let copy = slot::<Copy>(list, 0x80); - - let full_rows = PlacedFootprint { - offset: 0, - format: 28, - width: 4, - height: 4, - depth: 1, - row_pitch: 256, + let (upload, data) = host.upload_buffer(1024).unwrap(); + // SAFETY: the buffer's mapping, 1024 bytes. + unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) }; + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() }; - let tex_loc = Location { - resource: image, - kind: 0, - footprint: PlacedFootprint { - offset: 0, - ..full_rows + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + // Room for the rows as the host places them (512 bytes apart + // for the stencil plane on NVIDIA, not 256). + Width: 4096, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() }; - let up_loc = Location { - resource: upload_buf, - kind: 1, - footprint: full_rows, - }; - // 1) Buffer -> Texture upload. - copy(list, &tex_loc, 0, 0, 0, &up_loc, std::ptr::null()); - - // 2) Texture -> Buffer readback at non-zero offset (256), 256-aligned row pitch. - let aligned_loc = Location { - resource: dst_aligned, - kind: 1, - footprint: PlacedFootprint { - offset: 256, - ..full_rows + let mut readback: Option<ID3D12Resource> = None; + // SAFETY: plain creation of a readback buffer. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + // How the host lays the stencil plane (subresource 1) out in a buffer. + let mut plane = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + // SAFETY: a plain query writing one footprint. + unsafe { + host.device + .GetCopyableFootprints(&d, 1, 1, 0, Some(&mut plane), None, None, None); + } + let pattern_rows = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(60), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, }, }; - copy(list, &aligned_loc, 0, 0, 0, &tex_loc, std::ptr::null()); - // 3) Texture -> Buffer readback with unaligned row_pitch (16 bytes, packed). - let packed_loc = Location { - resource: dst_packed, - kind: 1, - footprint: PlacedFootprint { - offset: 32, - format: 28, - width: 4, - height: 4, - depth: 1, - row_pitch: 16, + // A subresource of a texture; rows of a buffer. + let whole = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index, }, }; - copy(list, &packed_loc, 0, 0, 0, &tex_loc, std::ptr::null()); + let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: placed, + }, + } + }; + let (written, source, dest) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let moved = crate::host::transition; - // 4) Texture -> Buffer sub-box readback: 2x2 crop from (1, 1) to (3, 3). - let crop_box = [1u32, 1, 0, 3, 3, 1]; - let crop_loc = Location { - resource: dst_crop, - kind: 1, - footprint: PlacedFootprint { - offset: 0, - format: 28, - width: 2, - height: 2, - depth: 1, - row_pitch: 256, - }, + // The pattern into the twin, where a shader would write it. + let fill = host.new_list().unwrap(); + // SAFETY: an open list and live resources. + unsafe { + let l = &fill.list; + l.ResourceBarrier(&[moved(twin, written, dest)]); + l.CopyTextureRegion(&whole(twin, 0), 0, 0, 0, &rows(&upload, pattern_rows), None); + l.ResourceBarrier(&[moved(twin, dest, written)]); + } + fill.close(); + host.execute(&[&fill]); + + // A list in which a shader writes the twin: closing it copies the + // twin into the stencil plane. + let list = host.new_list().unwrap(); + assert!(list.twin_use(depth, true, true)); + list.twins_written(); + list.close(); + host.execute(&[&list]); + + // The stencil plane read back from the state the list left it in. + let state = host_copy(depth).unwrap().state.load(Relaxed); + let state = D3D12_RESOURCE_STATES(state as i32); + let back = host.new_list().unwrap(); + // SAFETY: an open list and live resources; a whole subresource. + unsafe { + let l = &back.list; + l.ResourceBarrier(&[moved(host_depth, state, source)]); + let (to, from) = (rows(&readback, plane), whole(host_depth, 1)); + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + l.ResourceBarrier(&[moved(host_depth, source, state)]); + } + back.close(); + host.execute(&[&back]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copies finished (execute waits); the buffer is 4096 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 4096, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::<u8>(), 4096) }; - copy(list, &crop_loc, 0, 0, 0, &tex_loc, &crop_box); + let pitch = plane.Footprint.RowPitch as usize; + for row in 0..4 { + let (at, from) = (row * pitch, row * 256); + assert_eq!(read[at..at + 4], pattern[from..from + 4], "row {row}"); + } + } - // 5) Console formats 118..=120 (3 B/texel) map to 4-byte PC formats - // (45..=47): skipped cleanly without breaking Close() or touching dst. - let mut dst_d16s8 = null; + /// The depth plane of a depth-stencil texture is drawn from the plane's + /// twin when the list that wrote the twin closes: class numbers are put + /// into the twin of a texture in the console's 16-bit depth-stencil + /// format, and draws with the depth test "equal" at the depth the + /// title's lighting computes for a class (the number times the float + /// nearest 1/65535) then cover the texels of that class and no other. + #[cfg(windows)] + #[test] + fn a_depth_planes_twin_is_drawn_into_the_plane() { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + use windows::core::s; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 118, 1) + }; + let mut depth = null; assert_eq!( create_committed( null, &PROPERTIES, 0, - &buffer(1024), - 0, + &desc, + DEPTH_WRITE, null.cast(), - iid, - &mut dst_d16s8 + &RESOURCE_IIDS[0], + &mut depth ), S_OK ); - let d16s8_loc = Location { - resource: dst_d16s8, - kind: 1, - footprint: PlacedFootprint { - offset: 0, - format: 118, - width: 4, - height: 4, - depth: 1, - row_pitch: 256, - }, + let host_depth = host_resource(depth).unwrap(); + let Some(plane) = twin_plane_resource(depth) else { + return; // these twins are turned off }; - copy(list, &d16s8_loc, 0, 0, 0, &tex_loc, std::ptr::null()); + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), plane.GetDesc()) }; + // R24G8 typeless with depth, R16 typeless with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (44, 2)); + assert_eq!((t.Format.0, t.Flags.0), (53, 4)); - assert_eq!( - slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list), - S_OK + // Four rows of four class numbers (16 bits each), 256 bytes apart + // as copies place them. 128 and 129 are the classes whose 24-bit + // depth lies nearest a half step. + const CLASSES: [u16; 16] = [ + 8, 65, 128, 129, 65, 8, 129, 128, 0, 255, 65, 64, 129, 130, 8, 65, + ]; + let mut pattern = vec![0u8; 1024]; + for (i, class) in CLASSES.into_iter().enumerate() { + let at = i / 4 * 256 + i % 4 * 2; + pattern[at..at + 2].copy_from_slice(&class.to_le_bytes()); + } + let (upload, data) = host.upload_buffer(1024).unwrap(); + // SAFETY: the buffer's mapping, 1024 bytes. + unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) }; + let buffer = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut made: Option<ID3D12Resource> = None; + // SAFETY: plain creation of a buffer. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + state, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() + }; + let readback = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + // The colour target the draws cover: 4x4, 8 bits a texel. + let target = { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(61), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut made: Option<ID3D12Resource> = None; + // SAFETY: plain creation of a texture. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() + }; + let rows_of = |format: i32| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(format), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }; + // A texture's one subresource; rows of a buffer. + let whole = |texture: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: placed, + }, + } + }; + let (written, source, dest, tested, drawn) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_RENDER_TARGET, ); - slot::<extern "system" fn(This, u32, *const This)>(queue, 0x50)(queue, 1, &list); + let moved = crate::host::transition; - // Verify 256-aligned readback at offset 256 (leading 256 bytes untouched). - let (al_ptr, _) = buffer_bytes(dst_aligned).unwrap(); - // SAFETY: dst_aligned holds 2048 bytes. - let al = unsafe { std::slice::from_raw_parts(al_ptr, 2048) }; - assert!( - al[..256].iter().all(|&b| b == 0), - "bytes before offset touched" - ); - for row in 0..4 { - let at = 256 + row * 256; - assert_eq!( - al[at..at + 16], - up[row * 256..row * 256 + 16], - "aligned row {row}" - ); + // The class numbers into the twin, where a shader would write them. + let fill = host.new_list().unwrap(); + // SAFETY: an open list and live resources. + unsafe { + let l = &fill.list; + l.ResourceBarrier(&[moved(plane, written, dest)]); + l.CopyTextureRegion(&whole(plane), 0, 0, 0, &rows(&upload, rows_of(53)), None); + l.ResourceBarrier(&[moved(plane, dest, written)]); } + fill.close(); + host.execute(&[&fill]); - // Verify unaligned packed readback (row_pitch 16, offset 32). - let (pk_ptr, _) = buffer_bytes(dst_packed).unwrap(); - // SAFETY: dst_packed holds 256 bytes. - let pk = unsafe { std::slice::from_raw_parts(pk_ptr, 256) }; - assert!( - pk[..32].iter().all(|&b| b == 0), - "bytes before packed offset touched" + // A list in which a shader writes the twins: closing it draws the + // depth plane's twin into the plane. + let list = host.new_list().unwrap(); + assert!(list.twin_use(depth, true, true)); + list.twins_written(); + list.close(); + host.execute(&[&list]); + + // The draws: a triangle over the target at the depth of a class, + // as the title's lighting places its rectangles. + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants = 1, b0)" +cbuffer Drawn : register(b0) { uint number; }; +[RootSignature(RS)] +float4 corner(uint i : SV_VertexID) : SV_Position { + float z = float(number) * asfloat(0x37800080); + return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, z, 1.0); +} +float4 lit() : SV_Target { return 1.0; } +"#; + let vs = crate::host::compile(SOURCE, s!("corner"), s!("vs_5_1")).unwrap(); + let ps = crate::host::compile(SOURCE, s!("lit"), s!("ps_5_1")).unwrap(); + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 0xf; + let mut formats = [DXGI_FORMAT(0); 8]; + formats[0] = DXGI_FORMAT(61); + // SAFETY: plain creation; the description points at live data. + let (signature, pipeline) = unsafe { + let signature: ID3D12RootSignature = + host.device.CreateRootSignature(0, &vs[..]).unwrap(); + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&signature), + VS: code(&vs[..]), + PS: code(&ps[..]), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // As the title's lighting: test "equal", nothing written. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + DSVFormat: DXGI_FORMAT(45), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = + host.device.CreateGraphicsPipelineState(&desc).unwrap(); + (signature, pipeline) + }; + let state = host_copy(depth).unwrap().state.load(Relaxed); + let state = D3D12_RESOURCE_STATES(state as i32); + let colour = host.rtv(Some(&target), None); + let depth_view = host.dsv( + host_depth, + Some(&D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT(45), + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + ..Default::default() + }), ); - for row in 0..4 { - let at = 32 + row * 16; - assert_eq!( - pk[at..at + 16], - up[row * 256..row * 256 + 16], - "packed row {row}" - ); + let back = host.new_list().unwrap(); + // SAFETY: an open list and live resources and views. + unsafe { + let l = &back.list; + if state != tested { + l.ResourceBarrier(&[moved(host_depth, state, tested)]); + } + l.ClearRenderTargetView(colour, &[0.0; 4], None); + l.SetGraphicsRootSignature(&signature); + l.SetPipelineState(&pipeline); + l.OMSetRenderTargets(1, Some(&colour), false, Some(&depth_view)); + l.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: 4.0, + Height: 4.0, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: 4, + bottom: 4, + }]); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); + // Classes 65 and 129 are drawn; the others are not. + for class in [65u32, 129] { + l.SetGraphicsRoot32BitConstant(0, class, 0); + l.DrawInstanced(3, 1, 0, 0); + } + l.ResourceBarrier(&[moved(&target, drawn, source)]); + let (to, from) = (rows(&readback, rows_of(61)), whole(&target)); + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); } - - // Verify 2x2 sub-box crop from (1, 1)..(3, 3). - let (cr_ptr, _) = buffer_bytes(dst_crop).unwrap(); - // SAFETY: dst_crop holds 1024 bytes. - let cr = unsafe { std::slice::from_raw_parts(cr_ptr, 1024) }; - for row in 0..2 { - let src_at = (row + 1) * 256 + 4; // x=1, y=row+1 - let dst_at = row * 256; - assert_eq!( - cr[dst_at..dst_at + 8], - up[src_at..src_at + 8], - "crop row {row}" - ); + back.close(); + host.execute(&[&back]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 1024, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::<u8>(), 1024) + }; + for (i, class) in CLASSES.into_iter().enumerate() { + let covered = read[i / 4 * 256 + i % 4] != 0; + let drawn = matches!(class, 65 | 129); + assert_eq!(covered, drawn, "texel {i}, class {class}"); } - - // Verify skipped 118..=120 readback left its buffer untouched. - let (d16_ptr, _) = buffer_bytes(dst_d16s8).unwrap(); - // SAFETY: dst_d16s8 holds 1024 bytes. - let d16 = unsafe { std::slice::from_raw_parts(d16_ptr, 1024) }; - assert!( - d16.iter().all(|&b| b == 0), - "mismatched format 118 buffer touched" - ); } #[test] @@ -2530,167 +4346,4 @@ void main() { assert_eq!(slot::<Release>(heap, 0x10)(heap), 1); assert_eq!(slot::<Release>(placed, 0x10)(placed), 0); } - - #[test] - fn r9g9b9e5_target_format_substitutes_rgba16f() { - assert_eq!(pc_format(67), 67); - assert_eq!(target_format(67), 10); - assert_eq!(target_format(28), 28); - assert_eq!(target_format(118), 45); - } - - #[test] - fn small_unorm_targets_substitute_rgba8() { - assert_eq!(target_format(86), 28); - assert_eq!(target_format(115), 28); - // Sampled copies keep their format; B5G6R5 renders on PC. - assert_eq!(pc_format(86), 86); - assert_eq!(target_format(85), 85); - } - - #[cfg(windows)] - #[test] - fn substituted_render_target_and_uav_textures_create_on_host() { - if crate::host::host().is_none() { - return; - } - let tex_desc = |flags: u32| ResourceDesc { - dimension: 3, // TEXTURE2D - alignment: 0, - width: 64, - height: 64, - depth_or_array_size: 1, - mip_levels: 1, - format: 67, // DXGI_FORMAT_R9G9B9E5_SHAREDEXP - sample_count: 1, - sample_quality: 0, - layout: 0, - flags, - }; - for (format, flags, expected_host_format) in [ - (67, 0, 67), - (67, 4, 10), - (67, 5, 10), - // B5G5R5A1 has no unordered access on PC, B4G4R4A4 no render - // target (upstream #735). - (86, 0, 86), - (86, 5, 28), - (115, 1, 28), - ] { - let d = ResourceDesc { - format, - ..tex_desc(flags) - }; - let mut out = std::ptr::null(); - let hr = create_committed( - std::ptr::null(), - &PROPERTIES, - 0, - &d, - 0, - std::ptr::null(), - &RESOURCE_IIDS[0], - &mut out, - ); - assert_eq!(hr, S_OK, "format {format} flags {flags}"); - let host = host_resource(out).expect("host texture created"); - // SAFETY: a live host texture. - let got = unsafe { host.GetDesc() }.Format.0 as u32; - assert_eq!(got, expected_host_format, "format {format} flags {flags}"); - assert_eq!(view_format(out), None, "format {format} flags {flags}"); - assert_eq!(slot::<Release>(out, 0x10)(out), 0); - } - } - - #[test] - fn auto_size_textures_normalize_mip_levels_in_get_desc() { - let null = std::ptr::null(); - let get_desc = |desc: &ResourceDesc| -> ResourceDesc { - let mut res = null; - let hr = create_committed( - null, - &PROPERTIES, - 0, - desc, - 0, - null.cast(), - &RESOURCE_IIDS[0], - &mut res, - ); - assert_eq!(hr, S_OK); - let mut out = std::mem::MaybeUninit::<ResourceDesc>::uninit(); - slot::<extern "system" fn(This, *mut ResourceDesc)>(res, 0x50)(res, out.as_mut_ptr()); - assert_eq!(slot::<Release>(res, 0x10)(res), 0); - // SAFETY: initialized by resource_desc. - unsafe { out.assume_init() } - }; - - // 4x4 2D texture with auto mips (0) -> 3 mips (4x4, 2x2, 1x1) - let t2d = ResourceDesc { - dimension: 3, - width: 4, - height: 4, - depth_or_array_size: 1, - mip_levels: 0, - format: 28, // DXGI_FORMAT_R8G8B8A8_UNORM - layout: 0, - ..buffer(0) - }; - assert_eq!(get_desc(&t2d).mip_levels, 3); - - // 2D texture array (e.g. 6 slices) with auto mips (0) -> array size does not inflate mips - let t2d_array = ResourceDesc { - dimension: 3, - width: 4, - height: 4, - depth_or_array_size: 6, - mip_levels: 0, - format: 28, - layout: 0, - ..buffer(0) - }; - assert_eq!(get_desc(&t2d_array).mip_levels, 3); - - // Explicit 2-mip control -> stays 2 - let t2d_explicit = ResourceDesc { - dimension: 3, - width: 4, - height: 4, - depth_or_array_size: 1, - mip_levels: 2, - format: 28, - layout: 0, - ..buffer(0) - }; - assert_eq!(get_desc(&t2d_explicit).mip_levels, 2); - - // 1D texture with auto mips (0) -> 256 gives 9 mips - let t1d = ResourceDesc { - dimension: 2, - width: 256, - height: 1, - depth_or_array_size: 1, - mip_levels: 0, - format: 28, - layout: 0, - ..buffer(0) - }; - assert_eq!(get_desc(&t1d).mip_levels, 9); - - // 3D volume texture with auto mips (0) -> 16x8x32 gives 6 mips (max dimension 32) - let t3d = ResourceDesc { - dimension: 4, - width: 16, - height: 8, - depth_or_array_size: 32, - mip_levels: 0, - format: 28, - layout: 0, - ..buffer(0) - }; - assert_eq!(get_desc(&t3d).mip_levels, 6); - - // Ordinary buffer -> stays 1 mip - assert_eq!(get_desc(&buffer(256)).mip_levels, 1); - } } diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs index 10368e9a94..d5f5c064cb 100644 --- a/crates/victory-gpu/src/root.rs +++ b/crates/victory-gpu/src/root.rs @@ -147,7 +147,7 @@ type Deserialize = /// `d3d12_xs!D3D12CreateRootSignatureDeserializer`: our blobs are the /// host's serialization, so the host's deserializer reads them, and its /// object (IUnknown, then the description getter) is laid out as the -/// console's. Grand Theft Auto VI's upscaler asks with the PC interface id. +/// console's. The title's upscaler asks with the PC interface id. pub extern "system" fn create_deserializer( blob: *const u8, size: usize, @@ -203,6 +203,25 @@ extern "system" fn release(this: This) -> u32 { object::release_boxed::<RootSignature>(this) } +/// The serialized form of `this` if it is one of our root signatures (its +/// function table is ours): the device methods 0x1c8 / 0x218 name one by +/// pointer in a description of the title's. The table word is read through +/// the kernel first, so a pointer that is not one of ours is never touched. +#[cfg(windows)] +pub(crate) fn blob(this: This) -> Option<Vec<u8>> { + let mut first = [0u8; 8]; + if this.is_null() || !crate::host::read_into(this.cast(), &mut first) { + return None; + } + if usize::from_le_bytes(first) != FUNCTIONS.0.as_ptr() as usize { + return None; + } + // SAFETY: one of ours (its table): a live `RootSignature` while the + // title holds the description that names it. + let root = unsafe { &*this.cast::<RootSignature>() }; + Some(root.blob.clone()) +} + /// IUnknown 3, object 4, device child 1. static FUNCTIONS: Table<24> = { let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 24>()); diff --git a/crates/victory-gpu/src/sampler.rs b/crates/victory-gpu/src/sampler.rs index 83826f6ea2..a87886361b 100644 --- a/crates/victory-gpu/src/sampler.rs +++ b/crates/victory-gpu/src/sampler.rs @@ -42,62 +42,147 @@ impl Fields { 2 => 3, _ => u32::from(compares), }; + // Anisotropic with point mips stays so where the card can do it + // (avm 011735ff, upstream e45bacd/23fc8a5/7dfa86f): it was made + // linear between levels, which the console does not do. let filter = if aniso { - 0x55 + host_filter(0x54 | u32::from(self.mip == 2)) } else { linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2) }; - let (min_lod, max_lod) = if self.mip == 0 { - // Without a mip filter the console samples mip 0 only. - (0.0, 0.0) - } else { - let min_lod = finite_lod(self.min_lod, 0.0); - let max_lod = finite_lod(self.max_lod, min_lod).max(min_lod); - (min_lod, max_lod) - }; D3D12_SAMPLER_DESC { Filter: D3D12_FILTER((reduction << 7 | filter) as i32), - AddressU: address_mode(self.address[0]), - AddressV: address_mode(self.address[1]), - AddressW: address_mode(self.address[2]), - MipLODBias: if self.bias.is_nan() { - 0.0 - } else { - self.bias - .clamp(D3D12_MIP_LOD_BIAS_MIN, D3D12_MIP_LOD_BIAS_MAX) - }, + AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32), + MipLODBias: self.bias, MaxAnisotropy: if aniso { self.anisotropy.clamp(1, 16) } else { 1 }, - ComparisonFunc: if reduction == 1 { - D3D12_COMPARISON_FUNC(self.compare as i32) + ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32), + BorderColor: self.border, + MinLOD: self.min_lod, + // Without a mip filter the console samples mip 0 only. + MaxLOD: if self.mip == 0 { + self.min_lod } else { - D3D12_COMPARISON_FUNC_NEVER + self.max_lod }, - BorderColor: self.border, - MinLOD: min_lod, - MaxLOD: max_lod, } } } -/// Maps a console address mode (`1..=5`) to host D3D12, falling back to `CLAMP`. -fn address_mode(mode: u32) -> D3D12_TEXTURE_ADDRESS_MODE { - match mode { - 1..=5 => D3D12_TEXTURE_ADDRESS_MODE(mode as i32), - _ => D3D12_TEXTURE_ADDRESS_MODE_CLAMP, +/// Try 5.8, sharper surfaces (what PC drivers' and other emulators' +/// "anisotropic filtering override" and upscalers' LOD bias do): +/// - a sampler that filters linearly between levels (a textured surface, +/// not a data lookup: no point filter, no comparison, no minimum or +/// maximum) and has levels to filter between is made anisotropic, 16x +/// (`VICTORY_ANISO`, 1 to 16; 1: as the title asked). Roads, walls and +/// pavements seen at an angle are sampled from their sharp levels along +/// the line of sight instead of the blurred ones trilinear picks; +/// - the same samplers get a negative level bias where the title renders +/// smaller than the screen (`crate::dxgi::render_scale`): log2 of the +/// scale, -0.42 at 75 %, as DLSS, FSR and XeSS ask of the titles that use +/// them, so textures keep the sharpness of the screen's size +/// (`VICTORY_LOD_BIAS` sets the bias, in hundredths: -50 is -0.5). +pub(crate) fn enhance(desc: &mut D3D12_SAMPLER_DESC) { + let (aniso, bias) = enhancement(); + desc.Filter = D3D12_FILTER(host_filter(desc.Filter.0 as u32) as i32); + let filter = desc.Filter.0 as u32; + // Reduction (bits 7-8) plain; mip linear (bit 0) and min linear (bit + // 4), or anisotropic already (bit 6). + let plain = filter >> 7 == 0; + let trilinear = filter & 0x11 == 0x11 || filter & 0x40 != 0; + if !plain || !trilinear || desc.MaxLOD <= desc.MinLOD { + return; + } + if aniso > 1 { + // An anisotropic filter keeps its own mip filter (point mips where + // the card has them: [`host_filter`]); trilinear ones become + // anisotropic. + if filter & 0x40 == 0 { + desc.Filter = D3D12_FILTER_ANISOTROPIC; + } + desc.MaxAnisotropy = desc.MaxAnisotropy.max(aniso); + } + if bias != 0.0 { + desc.MipLODBias = (desc.MipLODBias + bias).clamp(-16.0, 15.99); } } -/// Sanitizes an LOD bound for D3D12, substituting `fallback` for `NaN` and clamping infinities. -fn finite_lod(value: f32, fallback: f32) -> f32 { - if value.is_nan() { - fallback - } else { - value.clamp(-D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX) +/// Whether the card filters anisotropically with point mips +/// (`D3D12_OPTIONS19`, optional): asked once the device is there. +pub(crate) fn aniso_point_mip() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if let Some(&on) = ON.get() { + return on; } + let Some(host) = crate::host::host() else { return false }; + *ON.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + // SAFETY: the feature query writes the structure of the given size. + // Older runtimes may not recognize OPTIONS19; that means no support. + let on = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS19, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_ok() + && options.AnisoFilterWithPointMipSupported.as_bool(); + tracing::info!(on, "anisotropic filtering with point mips on the card (D3D12_OPTIONS19)"); + on + }) +} + +/// A host filter the card takes: anisotropic with point mips becomes +/// anisotropic with linear mips where the card lacks it (reduction bits +/// kept). +pub(crate) fn host_filter(filter: u32) -> u32 { + if filter & !0x180 == 0x54 && !aniso_point_mip() { filter | 1 } else { filter } +} + +/// The same for a static sampler of a root signature. +pub(crate) fn enhance_static(filter: &mut u32, max_anisotropy: &mut u32, bias: &mut f32, min_lod: f32, max_lod: f32) { + let mut desc = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER(*filter as i32), + MaxAnisotropy: *max_anisotropy, + MipLODBias: *bias, + MinLOD: min_lod, + MaxLOD: max_lod, + ..Default::default() + }; + enhance(&mut desc); + *filter = host_filter(desc.Filter.0 as u32); + *max_anisotropy = desc.MaxAnisotropy; + *bias = desc.MipLODBias; +} + +/// The anisotropy and level bias of [`enhance`]. +fn enhancement() -> (u32, f32) { + static ONCE: std::sync::OnceLock<(u32, f32)> = std::sync::OnceLock::new(); + *ONCE.get_or_init(|| { + let aniso = std::env::var("VICTORY_ANISO") + .ok() + .and_then(|v| v.trim().parse::<u32>().ok()) + .map_or(16, |n| n.clamp(1, 16)); + let bias = std::env::var("VICTORY_LOD_BIAS") + .ok() + .and_then(|v| v.trim().parse::<i32>().ok()) + .map_or_else( + || (crate::dxgi::render_scale() as f32 / 100.0).log2(), + |h| h.clamp(-300, 300) as f32 / 100.0, + ); + tracing::info!( + anisotropy = aniso, + lod_bias = bias, + "sharper surfaces: textured samplers made anisotropic, level bias for the render scale (VICTORY_ANISO, VICTORY_LOD_BIAS)" + ); + (aniso, bias) + }) } /// The console's sampler description (27 words): flags, magnification, @@ -145,76 +230,4 @@ mod tests { w[16] = 1; assert_eq!(console(&w).Filter.0, 0x5); } - - #[test] - fn mip_none_forces_base_level_and_inverted_lod_range_clamps() { - let mut w = [0u32; 27]; - w[3] = 0; // mip none - w[9] = 3.0f32.to_bits(); - w[10] = 8.0f32.to_bits(); - let d = console(&w); - assert_eq!((d.MinLOD, d.MaxLOD), (0.0, 0.0)); - - w[3] = 2; // linear mips - w[9] = 4.0f32.to_bits(); - w[10] = 1.0f32.to_bits(); - let d = console(&w); - assert_eq!((d.MinLOD, d.MaxLOD), (4.0, 4.0)); - - w[9] = f32::NAN.to_bits(); - w[10] = f32::INFINITY.to_bits(); - let d = console(&w); - assert_eq!((d.MinLOD, d.MaxLOD), (0.0, D3D12_FLOAT32_MAX)); - - w[9] = 2.5f32.to_bits(); - w[10] = f32::NAN.to_bits(); - let d = console(&w); - assert_eq!((d.MinLOD, d.MaxLOD), (2.5, 2.5)); - - w[9] = f32::NEG_INFINITY.to_bits(); - w[10] = f32::NEG_INFINITY.to_bits(); - let d = console(&w); - assert_eq!( - (d.MinLOD, d.MaxLOD), - (-D3D12_FLOAT32_MAX, -D3D12_FLOAT32_MAX) - ); - } - - #[test] - fn bias_address_and_comparison_stay_in_host_bounds() { - let mut w = [0u32; 27]; - w[6..9].copy_from_slice(&[0, 6, 3]); - w[11] = 24.0f32.to_bits(); - w[16] = 99; - let d = console(&w); - assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MAX); - assert_eq!( - [d.AddressU, d.AddressV, d.AddressW], - [D3D12_TEXTURE_ADDRESS_MODE_CLAMP; 3] - ); - assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER); - - w[11] = (-24.0f32).to_bits(); - w[5] = 1; // minimum reduction - w[16] = 4; // less-or-equal, ignored when reduction != 1 - let d = console(&w); - assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MIN); - assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER); - - w[11] = f32::NAN.to_bits(); - w[5] = 0; // plain mode, reduction == 1 from compare == 4 - w[6..9].copy_from_slice(&[1, 4, 5]); - w[16] = 4; - let d = console(&w); - assert_eq!(d.MipLODBias, 0.0); - assert_eq!( - [d.AddressU, d.AddressV, d.AddressW], - [ - D3D12_TEXTURE_ADDRESS_MODE_WRAP, - D3D12_TEXTURE_ADDRESS_MODE_BORDER, - D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, - ] - ); - assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL); - } } diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 16dbd7e899..3ee9465d20 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -1,101 +1,304 @@ //! Translated shaders kept on disk (decision 0003): under the configured -//! cache folder, keyed by the container's content and by the VIctory build -//! that translated it (the BLAKE3 of our executable), so a rebuilt -//! translator never serves an old translation. Entries go through +//! cache folder, keyed by the container's content and by the translator +//! that translated it (its source fingerprint and settings, see `build`), so +//! a changed translator never serves an old translation. Entries go through //! `victory-pipeline`'s content-addressed cache, which writes them //! atomically; an entry that does not read back is translated again. //! //! The entry is our own encoding of [`HostShader`]: a field added to it //! must be added to `encode` and `decode` too (entries of older builds //! are ignored anyway). +//! +//! Try 6.16, the disk: each build of the translator keys its translations +//! afresh (`build`), so every new version translated the title's 25,746 +//! shaders again (the 6.15 prepare log: "2879 already cached, 25749 +//! translated now") and filed them beside every older version's, which +//! nothing read again and nothing removed: about a gigabyte more of the +//! cache folder with each update. Now each build key has a folder of its +//! own (`b-` and 16 hex digits) with a stamp of when a run last used it, +//! and a while after the start the folders of all but the +//! `VICTORY_SHADER_CACHE_KEEP` (2 unless set; 0: none removed) most +//! recently used builds go, as do the entries of the flat layout before +//! 6.16 (folders of two hex digits). A folder used in the last hour stays +//! whatever its rank. -use std::path::PathBuf; -use std::sync::OnceLock; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; use victory_pipeline::{Cache, Converter}; use victory_shader::emit::{HostShader, StaticSampler, UserData}; +use victory_shader::resource::RootIndexedView; use victory_shader::{HwStage, RootType}; -static CACHE: OnceLock<Cache> = OnceLock::new(); +/// The cache folder ([`use_shader_cache`]), absolute. +static ROOT: OnceLock<PathBuf> = OnceLock::new(); +/// The caches of the build keys met so far, each in its folder under +/// [`ROOT`] ([`cache_for`]): one or two a run. +static CACHES: Mutex<Vec<([u8; 32], Cache)>> = Mutex::new(Vec::new()); static HITS: AtomicU64 = AtomicU64::new(0); static MISSES: AtomicU64 = AtomicU64::new(0); -/// Keeps translated shaders in `dir` from now on. +/// The file in a build's folder that says when a run last used it +/// (seconds since 1970, as text). +const USED: &str = "used"; + +/// A folder used within this many seconds is never removed. +const RECENT_S: u64 = 3600; + +/// Keeps translated shaders in `dir` from now on, each build's in a folder +/// of its own; the folders of older builds are removed a while after the +/// start ([`prune`]). pub fn use_shader_cache(dir: PathBuf) { - match Cache::open(dir) { - Ok(cache) => { - let _ = CACHE.set(cache); + match Cache::open(&dir) { + Ok(_) => { + let root = std::path::absolute(&dir).unwrap_or(dir); + if ROOT.set(root.clone()).is_ok() { + prune_later(root); + } } Err(e) => tracing::warn!(error = %e, "no shader cache"), } } -/// Shaders found in the cache and translated since the start. -pub(crate) fn counts() -> (u64, u64) { - (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) +/// How many of the most recently used builds' folders are kept +/// (`VICTORY_SHADER_CACHE_KEEP`; 2 unless set; 0: nothing is removed). +fn keep() -> usize { + std::env::var("VICTORY_SHADER_CACHE_KEEP").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2) } -/// What identifies this build: the BLAKE3 of our executable file and of -/// the translation settings it runs with (the loop and spin-wait limits, -/// which `VICTORY_SHADER_LOOP_LIMIT` and `VICTORY_SHADER_SPIN_LIMIT` change -/// at run time, and whether the host device runs 64-lane waves, known once -/// it is created). -fn build() -> &'static [u8; 32] { - static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); - BUILD.get_or_init(|| { - let exe = std::env::current_exe().and_then(std::fs::read); - let limit = victory_shader::emit::loop_limit(); - if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { - tracing::warn!( - limit, - "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner" - ); +/// The folder of a build key's translations. +fn build_folder(build: &[u8; 32]) -> String { + let mut name = String::from("b-"); + for b in &build[..8] { + name.push_str(&format!("{b:02x}")); + } + name +} + +fn now_s() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()) +} + +/// The cache of `build`'s translations, its folder made and stamped as +/// used at the first ask of this run; none without a cache folder. +fn cache_for(build: &[u8; 32]) -> Option<Cache> { + let root = ROOT.get()?; + let mut caches = CACHES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, cache)) = caches.iter().find(|(b, _)| b == build) { + return Some(cache.clone()); + } + let dir = root.join(build_folder(build)); + match Cache::open(&dir) { + Ok(cache) => { + let _ = std::fs::write(dir.join(USED), now_s().to_string()); + caches.push((*build, cache.clone())); + Some(cache) + } + Err(e) => { + static WARNED: std::sync::Once = std::sync::Once::new(); + WARNED.call_once(|| tracing::warn!(error = %e, dir = %dir.display(), "no shader cache folder for this build")); + None } - let spin = victory_shader::emit::spin_limit(); - if spin != victory_shader::emit::DEFAULT_SPIN_LIMIT { - tracing::warn!( - spin, - "VICTORY_SHADER_SPIN_LIMIT: spin-wait loops stop at this count" + } +} + +/// [`prune`] on a thread of its own, 90 seconds after the start: by then +/// this run has stamped the folders it uses, and removing a gigabyte of +/// small files takes nothing from the loading. +fn prune_later(root: PathBuf) { + let keep = keep(); + if keep == 0 { + return; + } + let spawned = std::thread::Builder::new().name("victory-shader-cache-tidy".into()).spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(90)); + let (builds, flat) = prune(&root, keep, now_s()); + if builds + flat > 0 { + tracing::info!( + builds, + flat, + keep, + "shader cache: translations of older builds removed (VICTORY_SHADER_CACHE_KEEP; each version translates the game's shaders again)" ); } - match exe { - Ok(mut bytes) => { - bytes.extend_from_slice(&limit.to_le_bytes()); - bytes.extend_from_slice(&spin.to_le_bytes()); - bytes.push(u8::from(victory_shader::emit::host_wave64())); - *blake3::hash(&bytes).as_bytes() + }); + if let Err(e) = spawned { + tracing::warn!(error = %e, "no thread to remove older builds' translations"); + } +} + +/// Removes from the cache folder `root` the folders of builds other than +/// the `keep` most recently used and those used in the last hour (`now` +/// in seconds since 1970), and the folders of the flat layout before Try +/// 6.16 (two hex digits). Other files and folders stay. Returns how many +/// build folders and flat folders went. +fn prune(root: &Path, keep: usize, now: u64) -> (usize, usize) { + let Ok(entries) = std::fs::read_dir(root) else { + return (0, 0); + }; + let mut builds = Vec::new(); + let mut flat = 0; + for e in entries.flatten() { + let path = e.path(); + if !path.is_dir() { + continue; + } + let name = e.file_name().to_string_lossy().into_owned(); + if name.len() == 2 && name.bytes().all(|b| b.is_ascii_hexdigit()) { + if std::fs::remove_dir_all(&path).is_ok() { + flat += 1; } - Err(e) => { - // Without it no entry can be trusted: a fresh key per run. - tracing::warn!(error = %e, "cannot read our executable; shader cache unused"); - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default(); - *blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes() + } else if name.len() == 18 && name.starts_with("b-") && name[2..].bytes().all(|b| b.is_ascii_hexdigit()) { + let used = std::fs::read_to_string(path.join(USED)).ok().and_then(|t| t.trim().parse::<u64>().ok()).unwrap_or(0); + builds.push((used, path)); + } + } + builds.sort_by_key(|b| std::cmp::Reverse(b.0)); + let mut gone = 0; + for (used, path) in builds.into_iter().skip(keep) { + if now.saturating_sub(used) > RECENT_S && std::fs::remove_dir_all(&path).is_ok() { + gone += 1; + } + } + (gone, flat) +} + +/// Shaders found in the cache and translated since the start. +pub(crate) fn counts() -> (u64, u64) { + (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) +} + +/// What identifies the translation, besides the container: the shader +/// crate's fingerprint (its source, every switch it reads, the host facts the +/// device gave it, the loop limit, barrier waits and clean-up passes) and +/// this file's encoding of the result. Not the whole executable any more: a +/// rebuild that leaves the translator alone keeps its translations (each new +/// build used to translate the title's thousands of shaders again, which kept +/// the first minutes of every test run short of pipelines). +/// `VICTORY_SHADER_CACHE_KEY=exe` restores the old key (the executable's hash). +/// Worked out per lookup, so a translation made before the device said its +/// wave size is never filed under the later key. +fn build() -> [u8; 32] { + static WARNED: std::sync::Once = std::sync::Once::new(); + let limit = victory_shader::emit::loop_limit(); + if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { + WARNED.call_once(|| tracing::warn!(limit, "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner")); + } + static EXE: OnceLock<Option<[u8; 32]>> = OnceLock::new(); + let exe = EXE.get_or_init(|| { + if std::env::var_os("VICTORY_SHADER_CACHE_KEY").is_some_and(|v| v == "exe") { + match std::env::current_exe().and_then(std::fs::read) { + Ok(bytes) => Some(*blake3::hash(&bytes).as_bytes()), + Err(e) => { + tracing::warn!(error = %e, "cannot read our executable; keying on the translator"); + None + } } + } else { + None } - }) + }); + let mut h = blake3::Hasher::new(); + h.update(b"victory shader cache key 2\0"); + if let Some(exe) = exe { + h.update(exe); + } + h.update(&victory_shader::emit::translation_fingerprint()); + // The list this file reads for the translator (`translate_listed`): the + // shader crate's fingerprint does not see it. + h.update(b"VICTORY_WAVE_WIDE_ONLY="); + if let Some(value) = std::env::var_os("VICTORY_WAVE_WIDE_ONLY") { + h.update(value.as_encoded_bytes()); + } + h.update(include_bytes!("shader_cache.rs")); + *h.finalize().as_bytes() +} + +/// A container translated with the wave-wide form allowed when its hash is +/// on `VICTORY_WAVE_WIDE_ONLY` (16-hex-digit hashes as the log names +/// shaders, comma separated; unset or empty: none). Off by default: two +/// programs that moved to that form were in a submission that lost the card +/// (runs 121-124, not proven the cause). After commit a416e392 of pull +/// request #823 (Felix2180), whose list is the four refused programs +/// 5dc3b25986622949 and 6f225b641c5b0708 (the water's transmission +/// volumetrics), 369cbe906ea72764 (particle visibility) and +/// 2cc4c197ee29e291 (the reflection pass's tiling). For runs and the offline +/// warm-up alike, which share the cache. +fn translate_listed(c: &[u8]) -> Result<HostShader, String> { + static LIST: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new(); + let list = LIST.get_or_init(|| { + std::env::var("VICTORY_WAVE_WIDE_ONLY") + .unwrap_or_default() + .split(',') + .map(|h| h.trim().to_lowercase()) + .filter(|h| !h.is_empty() && h != "none") + .collect() + }); + let hash = blake3::hash(c).to_hex(); + let wide = list.iter().any(|h| hash.starts_with(h.as_str())); + let program = program_hash(c); + victory_shader::emit::for_program(&program, || victory_shader::emit::with_wave_wide(wide, || victory_shader::emit::translate(c))) + .map_err(|e| e.to_string()) +} + +/// The offline warm-up (`victory translate --warm`): `container` is +/// translated into the cache unless it is there already. `Ok(true)`: it +/// was translated now. Needs [`use_shader_cache`] and the same host facts +/// the run will have (`victory_shader::emit::translation_fingerprint`). +pub fn warm(container: &[u8]) -> Result<bool, String> { + let build = build(); + let cache = cache_for(&build).ok_or("no shader cache")?; + let ran = AtomicBool::new(false); + let translate = |c: &[u8]| { + ran.store(true, Ordering::Relaxed); + translate_listed(c) + }; + cached(&cache, &build, victory_shader::emit::host_uses_wave32(), container, translate).map(|_| ran.load(Ordering::Relaxed)) +} + +/// Fills the cache ahead of a run (`victory prepare`): the container's +/// translation as this executable makes it in a run on this PC (the host's +/// wave width and view heap limit, found as a run finds them), taken from +/// the cache or made and stored now. Whether it translates. +/// +/// A rebuilt VIctory keys its translations afresh, so the first world +/// visit after every update translated each shader again while the title +/// waited for it (draws dropped, objects see-through); prepared, a run +/// finds them all. +pub fn prepare(container: &[u8]) -> bool { + crate::descriptor::host::probe_view_limit(); + host_shader(container).is_ok() +} + +/// Translations found in the cache and made, since the start. +pub fn prepared_counts() -> (u64, u64) { + counts() } /// The translation of a console shader container, from the cache when /// there is one. pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> { - let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); - match CACHE.get() { - Some(cache) => cached(cache, build(), container, translate), + let translate = translate_listed; + let build = build(); + match cache_for(&build) { + Some(cache) => cached(&cache, &build, victory_shader::emit::host_uses_wave32(), container, translate), None => translate(container), } } -/// The cache entry's converter: the build and the container in, the +/// The hash the log names a shader by (`pipeline.rs`: the first 16 hex +/// digits of the container's BLAKE3), which the translator's per-program +/// switches take (`victory_shader::emit::for_program`). +fn program_hash(container: &[u8]) -> String { + blake3::hash(container).to_hex()[..16].to_owned() +} + +/// The cache entry's converter: the build, host wave mode and container in, the /// encoded translation out. `ran` tells a miss from a hit. struct Translate<F> { translate: F, ran: AtomicBool, - /// The translation it ran worked: a cache error after that is the - /// cache's (it could not keep the entry), not the shader's. - translated: AtomicBool, } impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Translate<F> { @@ -103,13 +306,12 @@ impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Tra "shader.dxil" } fn version(&self) -> u32 { - // The build fingerprint in the input does the versioning. - 1 + // Version 1 did not distinguish translations made for 32-lane hosts. + 2 } fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>> { self.ran.store(true, Ordering::Relaxed); - let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?; - self.translated.store(true, Ordering::Relaxed); + let shader = (self.translate)(&input[33..]).map_err(anyhow::Error::msg)?; Ok(encode(&shader)) } } @@ -117,26 +319,19 @@ impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Tra fn cached( cache: &Cache, build: &[u8; 32], + wave32: bool, container: &[u8], translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync, ) -> Result<HostShader, String> { - let input = [&build[..], container].concat(); + let input = [&build[..], &[u8::from(wave32)], container].concat(); let converter = Translate { translate, ran: AtomicBool::new(false), - translated: AtomicBool::new(false), }; for _ in 0..2 { - let path = match cache.get_or_convert(&converter, &input) { - Ok(path) => path, - // A full disk, a file in the way, a scanner holding the new - // entry: the shader is still good, only not kept. - Err(e) if converter.translated.load(Ordering::Relaxed) => { - tracing::warn!(error = format!("{e:#}"), "shader cache entry not written"); - break; - } - Err(e) => return Err(format!("{e:#}")), - }; + let path = cache + .get_or_convert(&converter, &input) + .map_err(|e| format!("{e:#}"))?; if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) { let (counter, what) = if converter.ran.load(Ordering::Relaxed) { (&MISSES, "translated and cached") @@ -229,10 +424,27 @@ fn encode(s: &HostShader) -> Vec<u8> { word(&mut out, v); } } - for slots in [&s.root_cbvs, &s.root_srvs] { + for slots in [&s.root_cbvs, &s.root_srvs, &s.root_uavs] { word(&mut out, slots.len() as u32); out.extend(slots); } + word(&mut out, s.root_indexed_views.len() as u32); + for view in &s.root_indexed_views { + for value in [ + u32::from(view.table_slot), + u32::from(view.constant_slot), + view.constant_dword, + view.byte_offset, + u32::from(view.shift), + ] { + word(&mut out, value); + } + } + word(&mut out, s.half_views.len() as u32); + for &(slot, dword) in &s.half_views { + word(&mut out, u32::from(slot)); + word(&mut out, dword); + } out } @@ -289,6 +501,23 @@ fn decode(bytes: &[u8]) -> Option<HostShader> { } let root_cbvs = r.list()?; let root_srvs = r.list()?; + let root_uavs = r.list()?; + let n = r.word()? as usize; + let mut root_indexed_views = Vec::with_capacity(n.min(256)); + for _ in 0..n { + root_indexed_views.push(RootIndexedView { + table_slot: u8::try_from(r.word()?).ok()?, + constant_slot: u8::try_from(r.word()?).ok()?, + constant_dword: r.word()?, + byte_offset: r.word()?, + shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?, + }); + } + let n = r.word()? as usize; + let mut half_views = Vec::with_capacity(n.min(256)); + for _ in 0..n { + half_views.push((u8::try_from(r.word()?).ok()?, r.word()?)); + } r.0.is_empty().then_some(HostShader { stage, dxil, @@ -297,6 +526,9 @@ fn decode(bytes: &[u8]) -> Option<HostShader> { static_samplers, root_cbvs, root_srvs, + root_uavs, + root_indexed_views, + half_views, }) } @@ -323,6 +555,15 @@ mod tests { ])], root_cbvs: vec![2], root_srvs: vec![0, 3], + root_uavs: vec![1], + root_indexed_views: vec![RootIndexedView { + table_slot: 1, + constant_slot: 2, + constant_dword: 3, + byte_offset: 32, + shift: 5, + }], + half_views: vec![(0, 8), (4, 0)], } } @@ -337,43 +578,90 @@ mod tests { runs.fetch_add(1, Ordering::Relaxed); Ok(shader()) }; - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(cached(&cache, &build, false, container, translate), Ok(shader())); + assert_eq!(cached(&cache, &build, false, container, translate), Ok(shader())); assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk"); // Another build translates again. - assert_eq!(cached(&cache, &[8; 32], container, translate), Ok(shader())); + assert_eq!(cached(&cache, &[8; 32], false, container, translate), Ok(shader())); assert_eq!(runs.load(Ordering::Relaxed), 2); // A damaged entry is a miss, translated and stored again. for e in walk(dir.path()) { std::fs::write(e, b"VSH1 broken").unwrap(); } - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(cached(&cache, &build, false, container, translate), Ok(shader())); assert_eq!(runs.load(Ordering::Relaxed), 3); - assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(cached(&cache, &build, false, container, translate), Ok(shader())); assert_eq!(runs.load(Ordering::Relaxed), 3); // Failures are not stored. let fail = |_: &[u8]| Err::<HostShader, _>("unsupported".to_owned()); - assert!(cached(&cache, &build, b"other", fail).is_err()); + assert!(cached(&cache, &build, false, b"other", fail).is_err()); } #[test] - fn a_cache_that_cannot_keep_an_entry_still_gives_the_translation() { + fn reopening_the_cache_preserves_each_host_wave_translation() { let dir = tempfile::tempdir().unwrap(); - let cache = Cache::open(dir.path()).unwrap(); - // A file where every entry's folder would go: nothing can be written. - for shard in 0..=0xff_u8 { - std::fs::write(dir.path().join(format!("{shard:02x}")), b"").unwrap(); + let input = b"synthetic wave reduction"; + let runs = AtomicU64::new(0); + for wave32 in [false, true, false, true] { + let cache = Cache::open(dir.path()).unwrap(); + let mut expected = shader(); + expected.stage = HwStage::Cs; + expected.dxil.push(if wave32 { 32 } else { 64 }); + let result = cached(&cache, &[7; 32], wave32, input, |container| { + assert_eq!(container, input); + runs.fetch_add(1, Ordering::Relaxed); + Ok(expected.clone()) + }); + assert_eq!(result, Ok(expected)); } - let translate = |_: &[u8]| Ok(shader()); - let container = b"a console container".as_slice(); - assert_eq!(cached(&cache, &[7; 32], container, translate), Ok(shader())); - // A shader that does not translate still fails, with its own error. - let fail = |_: &[u8]| Err::<HostShader, _>("unsupported".to_owned()); - let error = cached(&cache, &[7; 32], b"other", fail).unwrap_err(); - assert!(error.contains("unsupported"), "{error}"); + assert_eq!(runs.load(Ordering::Relaxed), 2); + } + + #[test] + fn older_builds_folders_are_removed() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let now = 1_000_000; + let make = |name: &str, used: Option<u64>| { + let d = root.join(name); + std::fs::create_dir_all(d.join("ab")).unwrap(); + std::fs::write(d.join("ab").join("cdef"), b"VSH1").unwrap(); + if let Some(used) = used { + std::fs::write(d.join(USED), used.to_string()).unwrap(); + } + }; + make("b-0000000000000001", Some(now)); + make("b-0000000000000002", Some(now - 10_000)); + make("b-0000000000000003", Some(now - 20_000)); + make("b-0000000000000004", Some(now - 100)); + make("b-0000000000000005", None); + // The flat layout before 6.16, and things that are not the cache's. + std::fs::create_dir_all(root.join("7f")).unwrap(); + std::fs::write(root.join("7f").join("0123"), b"VSH1").unwrap(); + std::fs::create_dir_all(root.join("pipelines")).unwrap(); + std::fs::write(root.join("notes.txt"), b"x").unwrap(); + + assert_eq!(prune(root, 1, now), (3, 1)); + let left: std::collections::BTreeSet<String> = + std::fs::read_dir(root).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + // The newest, and the one used within the hour, stay. + let want: std::collections::BTreeSet<String> = + ["b-0000000000000001", "b-0000000000000004", "pipelines", "notes.txt"].iter().map(|s| s.to_string()).collect(); + assert_eq!(left, want); + // Nothing more to do. + assert_eq!(prune(root, 1, now), (0, 0)); + } + + #[test] + fn a_build_folder_is_named_by_its_key() { + let mut key = [0u8; 32]; + key[0] = 0xab; + key[7] = 0x01; + key[8] = 0xff; + assert_eq!(build_folder(&key), "b-ab00000000000001"); } fn walk(dir: &std::path::Path) -> Vec<PathBuf> { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 64f2684aa3..88ebbcb041 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -16,7 +16,7 @@ //! indexed heaps keep what their first use copied. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; @@ -40,86 +40,3115 @@ pub(crate) struct Shadow { /// Ranges shaders of a submission not yet copied back may be writing: /// title memory there is older than the copy. pending: Mutex<Vec<(usize, usize)>>, - /// The copy's bytes before the submission ran, from an offset on, - /// covering the ranges its shaders write: what the GPU wrote differs. - before: Mutex<Before>, + /// With [`relay`]: how many submissions not yet copied back declared + /// each range of `pending` ([`Flights`]). Locked inside `pending`'s + /// lock. + flights: Mutex<Flights>, + /// The copy's bytes before the submission ran, for the ranges its + /// shaders write (`pending`), each at its offset in the copy: what the + /// GPU wrote differs. Room for the whole copy; only those ranges' bytes + /// are set (and read). + before: Mutex<Option<Vec<u8>>>, + /// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot + /// hold the copy's bytes as they are now, and whether the snapshot is + /// counted in [`KEPT_BYTES`]. + kept: Mutex<(Vec<bool>, bool)>, + /// When the copy was last asked for (`crate::host::moment`): a window + /// outside buffers nothing asked for in a while, and nothing holds, is + /// let go ([`let_go_idle`]). + used: AtomicU64, + /// The lowest and highest title address asked for in the copy (a + /// window is 4 MiB whatever was asked: measured for the memory line). + asked: [AtomicU64; 2], + /// Asks for the copy that gave no length (root views: they read from + /// their address to the copy's end, whatever lies there). + unsized_asks: AtomicU64, + /// A number no other copy has had. Its address is no name for a copy: + /// one let go and another made may share it. + id: u64, + /// With [`cards`], for a big title buffer: `buffer` is in the card's + /// own memory, and this is the rest of the copy. + card: Option<Card>, + /// A window of title memory outside buffers, not a title buffer's copy. + window: bool, + /// Refreshes that brought title bytes into the copy, so far: the title + /// writes the memory (`crate::host`'s copy-back of only what is read). + title_in: AtomicU64, + /// A window whose one buffer is in a GPU upload heap ([`window_upload`]): + /// its bytes, counted with the windows on the card. + uploaded: u64, + /// With `crate::inplace`: not a copy at all. `buffer` is placed in a + /// heap opened on the title memory itself, so shaders read and write + /// the title's own bytes and nothing is copied either way. The heap, + /// and the bytes from the buffer's first byte to `start` (the heap + /// begins on a 64 KiB line; a title buffer need not). + place: Option<(windows::Win32::Graphics::Direct3D12::ID3D12Heap, u64)>, } +/// What a copy in the card's memory ([`cards`]) has beside the buffer +/// shaders see. +struct Card { + /// The CPU's side, in the PC's memory: what `data` maps. Title memory + /// is copied into it as into any copy, and what changed in it goes to + /// the card's side before the next submission. + staging: ID3D12Resource, + /// The card side's bytes as they were when the submission's shaders + /// started, in the card's memory too: made when shader writes are + /// first declared for the copy, and compared with the card's side, on + /// the card, after each submission that declares some. + before: Mutex<Option<ID3D12Resource>>, + /// Offsets of the copy whose bytes changed on the CPU's side and have + /// not gone to the card's side yet. + dirty: Mutex<Vec<(usize, usize)>>, + /// With [`relay`]: the offsets that went from `dirty` to the card's + /// side, each with the number of the send that took it + /// ([`card_dirty`]), kept until a fetch sent after it has been merged. + /// Locked inside `dirty`'s lock. + sent: Mutex<Vec<(usize, usize, u64)>>, + /// The buffers' bytes (the title buffer's, rounded up to 64 KiB). + size: u64, + /// The shaders' side is in the PC's memory too ([`pc_card_for`]). + in_pc: bool, + /// The copy itself, for [`CHANGED`]: set once it is shared. + me: std::sync::OnceLock<std::sync::Weak<Shadow>>, +} + +/// Whether the host copies of big title buffers are in the card's own +/// memory (on by default since run 75 showed it holds: the BVH skinning +/// list went from 50.5 to 4.5 ms on the card; `VICTORY_CARD_BUFFERS=0` +/// keeps every copy in the PC's memory, as before. Read when a copy is +/// made, so it takes a fresh start). +/// +/// Every host copy was a buffer in the PC's memory that the card reads +/// and writes over the bus, so that our code can fill it and compare it. +/// The title's shaders read almost all their buffer data from a few big +/// title buffers (in the gameplay frame of run 69, 190-330 MB of distinct +/// ranges of the 174 MB heap per list against 0-13 MB elsewhere), and a +/// skinning dispatch of ONE group of 32 threads took 1.8 ms on the card +/// (run 70): the time of some 170 loads one after the other, not of the +/// arithmetic. +/// +/// With the switch, a title buffer of [`card_limits`]' size or more has two +/// sides. Shaders see `Shadow::buffer`, in the card's memory. The CPU's +/// side (`Card::staging`, what `Shadow::data` maps) takes title memory as +/// before, and the ranges that changed in it are copied to the card's side +/// before each submission (`Host::card_before`). What shaders wrote is +/// found on the card: after the submission's lists a compute pass of ours +/// compares each declared range, by 64 KiB piece, with the card side's +/// bytes from before (`Card::before`), and only the pieces that differ are +/// fetched and merged into title memory, byte by byte as +/// [`Shadow::copy_back`] does (`Host::card_back`, [`Shadow::card_merge`]). +/// No snapshot is taken and nothing is compared on the CPU for such a copy. +/// +/// What it assumes is what [`keeps`] assumes: shaders write a copy only in +/// ranges declared as written. A write outside them is seen by later +/// shaders, as before, and goes back to the title the next time a declared +/// range holds its piece (before: never). +pub(crate) fn cards() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_BUFFERS").is_none_or(|v| v != "0")) +} + +/// Default `(min_mb, max_mb)` for [`card_limits`] chosen from the adapter's +/// local VRAM budget (`DXGI_QUERY_VIDEO_MEMORY_INFO.Budget`), in bytes. +/// +/// - Unknown (`None`, e.g. WARP) or `<= 14 GiB` (8–12 GB cards): `(16, 512)` MiB, +/// matching the original 12 GB baseline. +/// - `> 14 GiB` and `< 20 GiB` (16 GB cards): `(4, 2048)` MiB. +/// - `>= 20 GiB` (24–32+ GB cards): `(1, (budget_mb / 4).min(8192))` MiB, +/// capping at 25% of local budget (at most 8 GiB) so "before" twins (up to 2x) +/// still leave headroom for textures and render targets. +fn default_card_limits_mb(local_vram_budget: Option<u64>) -> (u64, u64) { + let Some(budget_bytes) = local_vram_budget else { + return (16, 512); + }; + let budget_mb = budget_bytes >> 20; + const FOURTEEN_GIB_MB: u64 = 14 * 1024; + const TWENTY_GIB_MB: u64 = 20 * 1024; + if budget_mb <= FOURTEEN_GIB_MB { + (16, 512) + } else if budget_mb < TWENTY_GIB_MB { + (4, 2048) + } else { + (1, (budget_mb / 4).min(8192)) + } +} + +/// Resolve `(min_bytes, max_bytes)` from the adapter's local VRAM budget and +/// optional explicit MiB overrides from `VICTORY_CARD_BUFFERS_MIN_MB` / +/// `VICTORY_CARD_BUFFERS_MB`. +fn resolve_card_limits( + local_vram_budget: Option<u64>, + min_mb_override: Option<u64>, + max_mb_override: Option<u64>, +) -> (u64, u64) { + let (default_min_mb, default_max_mb) = default_card_limits_mb(local_vram_budget); + let min_bytes = (min_mb_override.unwrap_or(default_min_mb) << 20).max(1 << 20); + let max_bytes = max_mb_override.unwrap_or(default_max_mb) << 20; + (min_bytes, max_bytes) +} + +/// The smallest title buffer whose copy goes to the card's memory, and the +/// most bytes of such copies (their "before" twins not counted: a copy +/// shaders write takes its size twice), both in bytes: +/// `VICTORY_CARD_BUFFERS_MIN_MB` and `VICTORY_CARD_BUFFERS_MB`. +/// Defaults scale with the adapter's local VRAM budget (16 MiB / 512 MiB on +/// `<= 14 GiB` cards, 4 MiB / 2048 MiB on 16 GB cards, 1 MiB / up to 8192 MiB +/// on `>= 20 GiB` cards), and explicit env vars always override. +fn card_limits() -> (u64, u64) { + static LIMITS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + *LIMITS.get_or_init(|| { + let env_mb = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<u64>().ok()); + let vram_budget = crate::host::host().and_then(|h| h.video_memory()).map(|[budget, ..]| budget); + let (min_bytes, max_bytes) = resolve_card_limits( + vram_budget, + env_mb("VICTORY_CARD_BUFFERS_MIN_MB"), + env_mb("VICTORY_CARD_BUFFERS_MB"), + ); + tracing::info!( + vram_budget_mb = vram_budget.map(|b| b >> 20), + card_buffers_min_mb = min_bytes >> 20, + card_buffers_max_mb = max_bytes >> 20, + "card buffer limits" + ); + (min_bytes, max_bytes) + }) +} + +/// Title buffers' host copies made since the start, by where they went +/// and by size: in the card's memory; in the PC's memory of 64 KiB (the +/// least a copy is), up to 256 KiB, up to 1 MiB, larger; each as (copies, +/// bytes). Said with the memory lines ([`placed_line`]). +static PLACED: [[AtomicU64; 2]; 5] = [const { [const { AtomicU64::new(0) }; 2] }; 5]; + +fn placed_count(size: u64, on_card: bool) { + let class = match (on_card, size) { + (true, _) => 0, + (false, ..=0x1_0000) => 1, + (false, ..=0x4_0000) => 2, + (false, ..=0x10_0000) => 3, + _ => 4, + }; + PLACED[class][0].fetch_add(1, Ordering::Relaxed); + PLACED[class][1].fetch_add(size, Ordering::Relaxed); +} + +/// Where title buffers' host copies went, since the start (a line with +/// the frame-rate line, when a copy was made since the last one). +pub(crate) fn placed_line() { + static SAID: AtomicU64 = AtomicU64::new(0); + let v: Vec<(u64, u64)> = PLACED.iter().map(|c| (c[0].load(Ordering::Relaxed), c[1].load(Ordering::Relaxed))).collect(); + let made: u64 = v.iter().map(|c| c.0).sum(); + if SAID.swap(made, Ordering::Relaxed) == made { + return; + } + let mb = |b: u64| b as f64 / (1 << 20) as f64; + tracing::info!( + "title buffers' host copies made so far, by where shaders read them: {} in the card's memory {:.0} MB; in the PC's memory (read over the bus): {} of 64 KiB {:.0} MB, {} up to 256 KiB {:.0} MB, {} up to 1 MiB {:.0} MB, {} larger {:.0} MB (the least size for the card: {} KiB; VICTORY_CARD_BUFFERS_MIN_KB)", + v[0].0, + mb(v[0].1), + v[1].0, + mb(v[1].1), + v[2].0, + mb(v[2].1), + v[3].0, + mb(v[3].1), + v[4].0, + mb(v[4].1), + card_limits().0 >> 10, + ); +} + +/// Bytes alive of copies' card sides, and of their "before" twins. +static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// Whether the texture queue leaves room on the card for the card copies +/// of title buffers that are not made yet +/// (`VICTORY_CARD_ROOM_FOR_BUFFERS=1`; off by default). +/// +/// The copies are made in one burst when the world loads (run 189: 94 of +/// its 95 within two seconds, right before the first world frame), and +/// [`card_for`] makes one only while the card is under eight tenths of its +/// budget. That held as long as the textures picked by index filled the +/// card after the burst. Since the texture queue keeps packed neighbours +/// (52b8060) it fills the card while the world loads: 85% and more at the +/// burst in runs 190 to 192, so one copy of 95 was made, the CPU looked +/// for shader writes in 600 to 720 MB a frame where it had been 30, and +/// the frame went from about 240 to 370-470 ms. +/// +/// With the switch, the texture queue's rule (`resource::room`) counts the +/// part of [`card_limits`]' second number that no copy has taken yet as +/// used, and a copy may be made up to nine tenths of the budget: the room +/// it takes was kept for it. After the burst what is kept is what the +/// burst left of the limit (87 MB of 1,024 in run 189). +/// +/// On by default from the build after run 199 +/// (`VICTORY_CARD_ROOM_FOR_BUFFERS=0`: off, as before). Run 193 had it on and still made 31 copies of 95: the copies +/// and the world's render targets (+1,603 MB) arrive in the same first +/// world frame and raced for the 448 MB left under the line, and a copy +/// turned down is not asked for again (`lookup` asks once), while its room +/// went on being kept (616 MB to the end of the run). So now: the texture +/// queue also keeps room for the targets (`resource::targets_room_kept`), +/// a copy is made up to 97 hundredths of the budget (its room was kept), +/// and the room of a copy turned down is given up ([`CARD_REFUSED`]). +fn card_room_kept_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_none_or(|v| v != "0")) +} + +/// Title buffers big enough for a copy in the card's memory that were +/// turned down for want of room, since the start, and their bytes: their +/// copies stay in the PC's memory for as long as the title keeps the +/// buffers, so no room is kept for them any more. +static CARD_REFUSED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The bytes of the card's memory the texture queue leaves free for card +/// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with +/// the switch off or without card copies. +pub(crate) fn card_room_kept() -> u64 { + if !card_room_kept_on() || !cards() { + return 0; + } + card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed)) +} + +/// The copies in the card's memory. +static CARDED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new()); + +/// The copies in the card's memory whose CPU side changed since +/// [`card_dirty`] last took their ranges: each is put here when its list of +/// changed offsets goes from empty to not empty (`Shadow::card_changed`). +/// +/// Why: [`card_dirty`] walked every copy in the card's memory at every +/// submission, two locks each, to find the few that changed. With every +/// title buffer's copy on the card (`VICTORY_CARD_BUFFERS_MIN_KB=64`) there +/// are about 3,900 of them and 10 to 18 submissions a frame. +static CHANGED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new()); + +/// Whether [`card_dirty`] takes the changed copies from [`CHANGED`] +/// (`VICTORY_CARD_CHANGED_LIST=1`; `alt`: twenty seconds so, twenty the walk +/// over every copy, in turn, each change said in the log). Off by default +/// until a game run has carried it. Both give the same ranges of the same +/// copies; the order of the copies may differ. +fn changed_list() -> bool { + /// 0 the walk, 1 the list, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_CARD_CHANGED_LIST").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "the changed copies in the card's memory are taken from a list from now (VICTORY_CARD_CHANGED_LIST=alt): {}", + if on { "ON" } else { "off, every copy is walked as usual" } + ); + } + on + } + } +} + +/// Whether [`CHANGED`] is kept at all (the switch is set to `1` or `alt`). +fn changed_kept() -> bool { + static KEPT: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *KEPT.get_or_init(|| std::env::var("VICTORY_CARD_CHANGED_LIST").is_ok_and(|v| v == "1" || v == "alt")) +} + +/// Since the last frame line: bytes copied to card sides and the ranges +/// they were; pieces compared on the card, pieces fetched and their +/// bytes; the waits for the card the fetches added and their microseconds. +pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + +/// [`CARD_STATS`], taken; then the copies in the card's memory, their +/// bytes and their "before" twins' bytes. +pub(crate) fn card_stats() -> [u64; 10] { + let mut out = [0u64; 10]; + for (i, stat) in CARD_STATS.iter().enumerate() { + out[i] = stat.swap(0, Ordering::Relaxed); + } + out[7] = { + let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); + if changed_kept() { + // (The walk over every copy drops the ones that are gone.) + carded.retain(|w| w.strong_count() > 0); + } + carded.iter().filter(|w| w.strong_count() > 0).count() as u64 + }; + out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + + WINDOW_BAR_BYTES.load(Ordering::Relaxed); + out[9] = CARD_BYTES[1].load(Ordering::Relaxed); + out +} + +/// The bytes of the hashes kept on the card for a copy of `size` bytes: 16 +/// for each 64 KiB piece (a copy that does not start on a piece boundary +/// has one piece more). +pub(crate) fn card_hash_bytes(size: u64) -> u64 { + (size / PIECE as u64 + 2) * 16 +} + +/// Whether refreshes of copies in the card's memory send only the bytes +/// that changed ([`Shadow::copy_same_skipped`]; `VICTORY_SAME_SKIP=0`: every +/// page the title wrote, as before). +fn same_skips() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SAME_SKIP").is_none_or(|v| v != "0")) +} + +/// Bytes the title wrote again unchanged, not sent to the card +/// ([`Shadow::copy_same_skipped`]), since the frame line last took them. +static SAME_SKIPPED: AtomicU64 = AtomicU64::new(0); + +/// For the frame line: [`SAME_SKIPPED`], taken. +pub(crate) fn same_skipped() -> u64 { + SAME_SKIPPED.swap(0, Ordering::Relaxed) +} + +/// Bytes alive of shaders' sides of copies in the PC's memory ([`pc_card_for`]). +static PC_CARD_BYTES: AtomicU64 = AtomicU64::new(0); + +/// See [`PC_CARD_BYTES`] (for the frame line). +pub(crate) fn pc_card_bytes() -> u64 { + PC_CARD_BYTES.load(Ordering::Relaxed) +} + +/// `VICTORY_PC_CARD_MB` (768 unless set; 0 turns it off) and +/// `VICTORY_PC_CARD_MIN_MB` (4): the most bytes of [`pc_card_for`]'s +/// buffers, and the smallest title buffer that gets one. +fn pc_card_limits() -> (u64, u64) { + static LIMITS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + *LIMITS.get_or_init(|| { + let env_mb = |name: &str, or: u64| std::env::var(name).ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(or); + let limits = (env_mb("VICTORY_PC_CARD_MIN_MB", 4).max(1) << 20, env_mb("VICTORY_PC_CARD_MB", 768) << 20); + tracing::info!( + min_mb = limits.0 >> 20, + most_mb = limits.1 >> 20, + "copies whose shaders' side is in the PC's memory, compared on the card" + ); + limits + }) +} + +/// For a title buffer whose copy [`card_for`] does not put in the card's +/// memory (smaller than its least, or the card full): the shaders' side in +/// the PC's memory, with everything else of a card copy. The CPU's side +/// stays the bytes from before the submission, so what shaders wrote is +/// found by the card's hash compare and only the pieces that differ come +/// back, where every submission took a snapshot of every range its +/// shaders may write and compared it on the CPU: 340-370 MB snapshotted +/// and 70-230 MB compared a frame (2026-11-24 reports), with the card's +/// 512 MiB of copies full after ten buffers. What changes on the CPU's +/// side goes over by the card's copy, not the CPU. Costs the PC's memory +/// twice for those buffers, up to [`pc_card_limits`]. +fn pc_card_for(size: u64) -> Option<ID3D12Resource> { + let (least, most) = pc_card_limits(); + if !cards() || size < least || size >= 1 << 30 || most == 0 { + return None; + } + let host = host()?; + if !host.card_ready() { + return None; + } + if PC_CARD_BYTES.fetch_add(size, Ordering::Relaxed) + size > most { + PC_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + return None; + } + let buffer = host.shared_buffer(size).map(|(buffer, _)| buffer); + if buffer.is_none() { + PC_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + } + buffer +} + +/// A buffer of `size` bytes in the card's memory for a title buffer's +/// copy, if the copy is to be there: [`cards`] is on, the size is within +/// [`card_limits`] and below 1 GiB (the compare counts in 32 bits), and the +/// host has what it takes (`Host::card_ready`). +fn card_for(size: u64) -> Option<ID3D12Resource> { + if !cards() { + return None; + } + let (least, most) = card_limits(); + if size < least || size >= 1 << 30 { + return None; + } + let host = host()?; + if !host.card_ready() { + return None; + } + // Only while the card has room: with this copy on it, a fifth of the + // budget the system gives us must still be free. Copies are made when + // the world loads, before the textures fill the card; the texture + // queue's own rule (`resource::room`: nine tenths of the budget) counts + // them, so the card's use stays where it was and the textures' share + // shrinks by the copies' bytes, at most `card_limits`' second number. + // (With `card_room_kept_on` the texture queue kept this copy's room + // free, and the copy may go up to the queue's own line.) + let hundredths = if card_room_kept_on() { 97 } else { 80 }; + if let Some([budget, used, ..]) = host.video_memory() + && used + size > budget / 100 * hundredths + { + // Said, with the numbers it was decided by: run 193 made 31 copies + // of 95 and no line named the others. The first 64, then every + // 32nd. + let n = CARD_REFUSED[0].fetch_add(1, Ordering::Relaxed) + 1; + let bytes = CARD_REFUSED[1].fetch_add(size, Ordering::Relaxed) + size; + if n <= 64 || n.is_multiple_of(32) { + tracing::info!( + "no card copy for a title buffer of {} KiB: the card has {} MB in use of a budget of {} MB and a copy is made up to \ + {} MB; the copies made hold {} MB of at most {} MB; {} buffers turned down so far ({} MB), frame {}", + size >> 10, + used >> 20, + budget >> 20, + (budget / 100 * hundredths) >> 20, + CARD_BYTES[0].load(Ordering::Relaxed) >> 20, + most >> 20, + n, + bytes >> 20, + crate::frame::current() + ); + } + return None; + } + if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most { + CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); + return None; + } + let buffer = host.uav_buffer(size); + if buffer.is_none() { + CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); + } + buffer +} + +/// The most bytes of windows outside buffers whose copies go to the card's +/// memory (`VICTORY_CARD_WINDOWS_MB`; 0, the default, none). +/// +/// Windows are two thirds of the PC memory the card shares (run 104: 861 +/// windows, 3,552 MB of 5,400), and every draw that takes vertices, indices +/// or constants from the title's own allocator reads them over the bus. +/// Shaders write none of them (run 91: "0.0 MB compared in 0 ranges of +/// windows"), so a window on the card needs only what a card copy has +/// already: the CPU's side takes title memory as before, and what changed +/// in it goes up before each submission. No hashes, no compare, no fetch, +/// unless a shader does declare a write to it one day. +/// +/// A window goes to the card while there is room under this number and +/// while a fifth of the card's budget is free, as title buffers do +/// (`card_for`): textures keep their room, and once they have filled the +/// card later windows stay where they are. The CPU's side stays in the PC's +/// memory, so the memory shared with the card does not shrink by this +/// alone; what moves is what shaders read. +fn window_card_most() -> u64 { + static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_CARD_WINDOWS_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0) << 20 + }) +} + +/// Bytes alive of windows' card sides ([`window_card_most`]). +static WINDOW_CARD_BYTES: AtomicU64 = AtomicU64::new(0); + +/// Whether windows that go to the card's memory are one buffer in a GPU +/// upload heap, which the CPU fills directly (`VICTORY_WINDOW_UPLOAD=1`; +/// off by default), where the device has such heaps +/// (`Host::gpu_upload_buffer`). +/// +/// A window on the card ([`window_card_most`]) is two buffers: the CPU's +/// side in the PC's memory, which takes title memory as before, and the +/// card's side, which a list of ours brings up to date before each +/// submission (`Host::card_before`: its copies are part of "our +/// send-and-hash lists", 11 to 14 ms of the card's frame in runs 270 and +/// 271). No shader writes a window (run 91, and every run since: "0.0 MB +/// compared in 0 ranges of windows"), so nothing is ever looked for in one +/// or fetched from one: the CPU's side is only a stop on the way. With +/// the card's memory mapped through a resizable BAR the stop goes: title +/// memory is copied into the card's memory where shaders read it, with no +/// second buffer in the PC's memory and no copy on the card. The same +/// limits hold as for windows on the card (the most asked, the card's +/// room), and a window turned down or not makeable stays in the PC's +/// memory as before. +fn window_upload() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOW_UPLOAD").is_some_and(|v| v == "1")) +} + +/// A window's buffer in a GPU upload heap and where it is mapped, if +/// [`window_upload`] says so and a window of `size` bytes may go to the +/// card ([`window_card_room`]). +fn window_upload_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> { + if window_bar_most() > 0 { + return window_bar_for(size); + } + if !window_upload() || !host()?.gpu_upload() { + return None; + } + if !window_card_room(size, "in a GPU upload heap:") { + return None; + } + let made = host()?.gpu_upload_buffer(size); + if made.is_none() { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + } + made +} + +/// The most bytes of windows outside buffers that go to the card's memory +/// through a resizable BAR on their own (`VICTORY_WINDOWS_BAR_MB`; 0, the +/// default, none): one buffer in a GPU upload heap the CPU fills and shaders +/// read, with no CPU side in the PC's memory, no copy to send and no list of +/// changes, and without `VICTORY_CARD_WINDOWS_MB` or card copies on. +/// +/// Try 6.13, ported from trustno1-coder/VIctory-NVIDIA cda4987a and 85a529b6 +/// (Indy2l; GPL-3.0-or-later). Measured there on an RTX 3060 PC with 16 GB of +/// RAM: the `0x8007000E` out-of-memory and the driver fault about a minute in +/// went away, the memory shared with the card stayed at 4.4 GB instead of +/// growing to 7.5, and the frame rate went from 1.6-3 to 10-12. Where the +/// device has no GPU upload heaps (resizable BAR off in the firmware) nothing +/// changes. Windows go there while a fifth of the card's budget is free. +/// Try's script sets 3072 on PCs with less than 24 GB of RAM. +fn window_bar_most() -> u64 { + static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + let most = std::env::var("VICTORY_WINDOWS_BAR_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0); + // (`VICTORY_GPU_UPLOAD=0`, as after a lost card: none either.) + let most = if std::env::var_os("VICTORY_GPU_UPLOAD").is_some_and(|v| v == "0") { 0 } else { most }; + if most > 0 { + tracing::info!( + most_mb = most, + supported = host().is_some_and(|h| h.gpu_upload()), + "windows outside buffers in the card's memory through a resizable BAR (VICTORY_WINDOWS_BAR_MB; nothing changes where GPU upload heaps are not supported)" + ); + } + most << 20 + }) +} + +/// Bytes alive of windows in the card's memory through a BAR +/// ([`window_bar_most`]). +static WINDOW_BAR_BYTES: AtomicU64 = AtomicU64::new(0); + +/// Bytes alive of windows whose only buffer is in the PC's memory (neither +/// in place, nor through the BAR, nor on the card): shaders read those +/// across the bus at every read. +static WINDOW_PC_BYTES: AtomicU64 = AtomicU64::new(0); + +/// Try 6.16: whether the texture queue keeps room on the card for windows +/// (`VICTORY_WINDOWS_ROOM=0`: off, as before), and windows may then go to +/// the card up to [`window_line`]'s 96 % of its budget rather than 80 %. +/// +/// Why: in the 6.15 report (RTX 4050 Laptop, 6 GB, all-out) the card stood +/// at 5,050 to 5,100 MB of a 5,153 MB budget for the whole world, filled by +/// the texture queue (`VICTORY_TEXTURE_ROOM_PERCENT=99`) before the windows +/// asked: windows through the BAR stopped at 117 (436 MB), and from then on +/// every window was turned down for the card's room (768 of them; "so far 0 +/// on the card" for `VICTORY_CARD_WINDOWS_MB`), so their only buffer was in +/// the PC's memory, which shaders read across the laptop's bus at every +/// read. The card was 58 to 72 % busy over frames of 300 to 420 ms: about +/// 200 ms of card work a frame for 4,500 draws at 1280x720. In the 6.13 +/// port's measurements (trustno1-coder cda4987a, RTX 3060) windows in the +/// card's memory were the step from 1.6-3 to 10-12 fps. Textures can wait +/// and be drawn soft (texture quality, the rush); a window read from the +/// PC's memory slows every draw that reads it. +fn windows_room_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOWS_ROOM").is_none_or(|v| v != "0")) +} + +/// The line under which windows go to the card's memory, of a card whose +/// budget is `budget` bytes ([`windows_room_on`]). +fn window_line(budget: u64) -> u64 { + if windows_room_on() { budget / 100 * 96 } else { budget / 10 * 8 } +} + +/// The most bytes the texture queue keeps for windows on a card whose +/// budget is `budget` (`VICTORY_WINDOWS_ROOM_MB`; unset: a quarter of the +/// budget, about 1,290 MB of a 6 GB card's 5,153). +fn windows_room_most(budget: u64) -> u64 { + static MB: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new(); + let asked = *MB.get_or_init(|| std::env::var("VICTORY_WINDOWS_ROOM_MB").ok().and_then(|v| v.trim().parse::<u64>().ok())); + asked.map_or(budget / 4, |mb| mb << 20) +} + +/// The room kept: what windows may take on the card (through the BAR and +/// as card copies, at most [`windows_room_most`]) less what they hold +/// there now. Pure, for testing. +fn windows_room_left(may: u64, most: u64, alive: u64) -> u64 { + may.min(most).saturating_sub(alive) +} + +/// The bytes of the card's memory the texture queue leaves free for windows +/// not made yet ([`windows_room_on`]): 0 with the switch off or where no +/// window can go to the card (no BAR and no card windows asked for). +pub(crate) fn windows_room_kept(budget: u64) -> u64 { + if !windows_room_on() { + return 0; + } + let Some(host) = host() else { return 0 }; + let bar = if host.gpu_upload() { window_bar_most() } else { 0 }; + let card = if cards() { window_card_most() } else { 0 }; + let alive = WINDOW_BAR_BYTES.load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed); + windows_room_left(bar + card, windows_room_most(budget), alive) +} + +/// For the frame line, every few seconds: where the windows' bytes are. +pub(crate) fn windows_line() { + let bar = WINDOW_BAR_BYTES.load(Ordering::Relaxed); + let card = WINDOW_CARD_BYTES.load(Ordering::Relaxed); + let pc = WINDOW_PC_BYTES.load(Ordering::Relaxed); + if bar + card + pc == 0 { + return; + } + let kept = host().and_then(|h| h.video_memory()).map_or(0, |[budget, ..]| windows_room_kept(budget)); + tracing::info!( + "windows outside buffers alive: {} MB in the card's memory through the BAR, {} MB as copies on the card, {} MB only in the PC's memory (read across the bus); \ + room the texture queue keeps for more on the card {} MB (VICTORY_WINDOWS_ROOM=0: none, windows only under 80 % of the card)", + bar >> 20, + card >> 20, + pc >> 20, + kept >> 20 + ); +} + +/// A window's buffer of `size` bytes in a GPU upload heap and where it is +/// mapped, if it is to be there ([`window_bar_most`]). +fn window_bar_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let host = host()?; + if !host.gpu_upload() { + return None; + } + static COUNTS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + let say = |which: usize, what: &str| { + let n = COUNTS[which].fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(256) { + tracing::info!( + "windows through the BAR (VICTORY_WINDOWS_BAR_MB={}): {what} one of {} KiB; so far {} there ({} MB), {} turned down for the card's room, {} for the most asked", + window_bar_most() >> 20, + size >> 10, + COUNTS[0].load(Ordering::Relaxed), + WINDOW_BAR_BYTES.load(Ordering::Relaxed) >> 20, + COUNTS[1].load(Ordering::Relaxed), + COUNTS[2].load(Ordering::Relaxed) + ); + } + }; + if let Some([budget, used, ..]) = host.video_memory() + && used + size > window_line(budget) + { + say(1, "no room on the card for"); + return None; + } + if WINDOW_BAR_BYTES.fetch_add(size, Ordering::Relaxed) + size > window_bar_most() { + WINDOW_BAR_BYTES.fetch_sub(size, Ordering::Relaxed); + say(2, "the most is reached at"); + return None; + } + let made = host.gpu_upload_buffer(size); + if made.is_none() { + WINDOW_BAR_BYTES.fetch_sub(size, Ordering::Relaxed); + } else { + say(0, "put"); + } + made +} + +/// A buffer in the card's memory for a window of `size` bytes, if it is to +/// be there ([`window_card_most`]). +fn window_card_for(size: u64) -> Option<ID3D12Resource> { + if !window_card_room(size, "on the card:") { + return None; + } + let buffer = host()?.uav_buffer(size); + if buffer.is_none() { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + } + buffer +} + +/// Whether a window of `size` bytes may go to the card's memory +/// ([`window_card_most`], the card's room); if so its bytes are counted +/// there from now, and the caller makes the buffer (or takes them off +/// again). `how` is the word for the log. +fn window_card_room(size: u64, how: &str) -> bool { + let most = window_card_most(); + if most == 0 || !cards() { + return false; + } + let Some(host) = host() else { return false }; + if !host.card_ready() { + return false; + } + // Windows that went to the card, and those turned down for the card's + // room or for the most asked: said at the first of each and then now + // and again, so a run shows what the switch did. + static COUNTS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + let say = |which: usize, what: &str| { + let n = COUNTS[which].fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(64) { + tracing::info!( + "windows outside buffers and the card's memory (VICTORY_CARD_WINDOWS_MB={}): {what} one of {} KiB; so far {} on the card ({} MB), {} turned down for the card's room, {} for the most asked", + most >> 20, + size >> 10, + COUNTS[0].load(Ordering::Relaxed), + WINDOW_CARD_BYTES.load(Ordering::Relaxed) >> 20, + COUNTS[1].load(Ordering::Relaxed), + COUNTS[2].load(Ordering::Relaxed) + ); + } + }; + if let Some([budget, used, ..]) = host.video_memory() + && used + size > window_line(budget) + { + say(1, "no room on the card for"); + return false; + } + if WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed) + size > most { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + say(2, "the most is reached at"); + return false; + } + say(0, how); + true +} + +/// The copies in the card's memory whose CPU side changed since they were +/// last asked: each with the changed offsets, in order and joined where +/// they touch. The ranges are taken: the caller copies them to the card's +/// side (`Host::card_before`). +/// +/// With [`relay`], `sent_as` is the number of the send that takes them +/// (`crate::host`'s order of the queue): each range is noted with it, in +/// the same lock that took it, so that a merge of pieces fetched before +/// that send knows the card did not hold these bytes yet +/// ([`Shadow::card_merge_relay`]). Notes of sends that every fetch still to +/// be merged came after are dropped. +pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc<Shadow>, Vec<(usize, usize)>)> { + let mut out = Vec::new(); + if changed_kept() { + // Taken either way: the walk takes every changed copy's ranges, so + // what the list holds then names copies with nothing left to take. + let changed = std::mem::take(&mut *CHANGED.lock().unwrap_or_else(|e| e.into_inner())); + if changed_list() { + let fetched = RELAY_FETCHED.load(Ordering::Acquire); + for weak in changed { + let Some(shadow) = weak.upgrade() else { + continue; + }; + let ranges = shadow.card.as_ref().map(|c| take_dirty(c, fetched, sent_as)).unwrap_or_default(); + if !ranges.is_empty() { + out.push((shadow, joined(ranges))); + } + } + return out; + } + } + let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); + let fetched = RELAY_FETCHED.load(Ordering::Acquire); + carded.retain(|weak| { + let Some(shadow) = weak.upgrade() else { + return false; + }; + let ranges = shadow.card.as_ref().map(|c| take_dirty(c, fetched, sent_as)).unwrap_or_default(); + if !ranges.is_empty() { + out.push((shadow, joined(ranges))); + } + true + }); + out +} + +/// Takes a copy's changed offsets for the send numbered `sent_as` +/// ([`card_dirty`]); with [`relay`] they are noted as sent, and the notes of +/// sends that every fetch still to be merged came after (`fetched`) go. +fn take_dirty(c: &Card, fetched: u64, sent_as: u64) -> Vec<(usize, usize)> { + let mut dirty = c.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let ranges = std::mem::take(&mut *dirty); + if relay() { + let mut sent = c.sent.lock().unwrap_or_else(|e| e.into_inner()); + sent.retain(|s| s.2 > fetched); + sent.extend(ranges.iter().map(|&(a, b)| (a, b, sent_as))); + } + ranges +} + +/// Ranges in order, those that overlap or touch as one. +fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for (from, to) in ranges { + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + out +} + +/// Runs of pieces to hash again (`Host::card_before`), those that overlap +/// or touch as one, in order: every piece of `runs` is in the result once +/// and no other piece is. Ranges sent up lie close together (514 a frame +/// for 87 MB in run 102), and each had a pass of its own over its pieces, +/// so a piece that held several ranges was hashed once for each. +pub(crate) fn joined_piece_runs(mut runs: Vec<CardSpan>) -> Vec<CardSpan> { + runs.sort_unstable_by_key(|r| r.first); + let mut out: Vec<CardSpan> = Vec::with_capacity(runs.len()); + for run in runs { + match out.last_mut() { + Some(last) if run.first <= last.first + last.pieces => { + last.pieces = last.pieces.max(run.first + run.pieces - last.first); + last.to = last.to.max(run.to); + } + _ => out.push(run), + } + } + out +} + +/// A declared range of a copy in the card's memory, as the compare on the +/// card takes it: its offsets in the copy, its first 64 KiB piece (pieces +/// are cut at multiples of 64 KiB of title memory; piece 0 holds offset +/// 0), how many pieces hold it, and where the copy starts in piece 0. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct CardSpan { + pub(crate) from: u32, + pub(crate) to: u32, + pub(crate) first: u32, + pub(crate) pieces: u32, + pub(crate) skew: u32, +} + +/// [`CardSpan`] for offsets `[from, to)` (`from < to`) of a copy of title +/// memory from `start` on. +fn card_span_of(start: usize, from: usize, to: usize) -> CardSpan { + let pieces = pieces_of(start, from, to); + CardSpan { + from: from as u32, + to: to as u32, + first: pieces.start as u32, + pieces: pieces.len() as u32, + skew: (start % PIECE) as u32, + } +} + +/// The offsets of piece `i` of `span` that lie in the span, for a copy of +/// `len` bytes of title memory from `start` on: what is fetched and merged +/// of a piece the compare found differing. +fn card_piece_of(start: usize, len: usize, span: &CardSpan, i: u32) -> (usize, usize) { + let (lo, hi) = piece_at(start, len, (span.first + i) as usize); + (lo.max(span.from as usize), hi.min(span.to as usize)) +} + +#[cfg(test)] +mod card_tests { + use super::{CardSpan, PIECE, card_piece_of, card_span_of, joined, joined_piece_runs, window_line, windows_room_left}; + + /// Try 6.16: the room kept for windows is what they may take, at most + /// the cap, less what they hold; never below nothing. + #[test] + fn windows_room_is_what_they_may_still_take() { + const MB: u64 = 1 << 20; + // 6.15's card: BAR windows up to 1,804 MB and card windows 512, + // a quarter of a 5,153 MB budget as the cap; 436 MB made. + assert_eq!(windows_room_left(2316 * MB, 5153 * MB / 4, 436 * MB), 5153 * MB / 4 - 436 * MB); + assert_eq!(windows_room_left(300 * MB, 1000 * MB, 100 * MB), 200 * MB); + assert_eq!(windows_room_left(300 * MB, 1000 * MB, 400 * MB), 0); + assert_eq!(windows_room_left(0, 1000 * MB, 0), 0); + // With the switch on (the default) windows go up to 96 % of the card. + assert_eq!(window_line(1000 * MB), 960 * MB); + } + + /// Joined runs hold every piece of the runs given, once, and no other. + #[test] + fn piece_runs_join_without_losing_or_adding_pieces() { + let run = |first: u32, pieces: u32| CardSpan { + from: first * 65536, + to: (first + pieces) * 65536, + first, + pieces, + skew: 7, + }; + let runs = vec![run(40, 1), run(3, 2), run(4, 1), run(5, 3), run(40, 1), run(9, 1), run(41, 2), run(100, 1)]; + let mut wanted: Vec<u32> = runs.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + wanted.sort_unstable(); + wanted.dedup(); + let joined = joined_piece_runs(runs); + let got: Vec<u32> = joined.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + assert_eq!(got, wanted); + assert_eq!(joined.iter().map(|r| (r.first, r.pieces)).collect::<Vec<_>>(), [(3, 5), (9, 1), (40, 3), (100, 1)]); + assert!(joined.iter().all(|r| r.skew == 7)); + assert!(joined_piece_runs(Vec::new()).is_empty()); + } + + /// The offsets the compare's shader takes for a piece (`CARD_COMPARE` + /// in host.rs), before it widens them to 16 bytes. + fn shader_piece(span: &CardSpan, i: u32) -> (u32, u32) { + let piece = span.first + i; + let lo = piece * 65536; + let lo = if lo > span.skew { lo - span.skew } else { 0 }; + let hi = (piece + 1) * 65536 - span.skew; + (lo.max(span.from), hi.min(span.to)) + } + + /// The pieces of a span cover it without gaps, and the shader's + /// arithmetic names the same bytes as ours. + #[test] + fn the_shader_and_the_merge_cut_the_same_pieces() { + for start in [0usize, 4096, PIECE - 16, PIECE, 3 * PIECE + 0x1f00, 0xd_b790_df00] { + let len = 5 * PIECE + 4096; + for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] { + let span = card_span_of(start, from, to); + let mut at = from; + for i in 0..span.pieces { + let (lo, hi) = card_piece_of(start, len, &span, i); + assert_eq!(lo, at, "{start:#x} {from} {to} piece {i}"); + assert!(hi > lo && hi - lo <= PIECE); + assert_eq!(shader_piece(&span, i), (lo as u32, hi as u32), "{start:#x} {from} {to} piece {i}"); + at = hi; + } + assert_eq!(at, to, "{start:#x} {from} {to}"); + } + } + } + + /// The fetch inside flights (`CARD_FETCH` in host.rs) copies each piece + /// from `inflight_piece_from` on: what the merge takes of the piece lies + /// in that slot. + #[test] + fn a_piece_fetched_in_flight_fits_its_slot() { + let slot = crate::host::INFLIGHT_SLOT as usize; + for start in [0usize, 4096, 7, PIECE - 16, PIECE - 3, 3 * PIECE + 0x1f09, 0xd_b790_df00] { + let len = 5 * PIECE + 4096; + for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] { + let span = card_span_of(start, from, to); + for i in 0..span.pieces { + let (lo, hi) = card_piece_of(start, len, &span, i); + let at = crate::host::inflight_piece_from(&span, i); + assert_eq!(at % 16, 0); + assert!(lo >= at && hi - at <= slot, "{start:#x} {from} {to} piece {i}: {lo}..{hi} from {at}"); + } + } + } + } + + /// The slots are a power of two, one per 64 KiB asked, within the + /// shader's 32-bit offsets. + #[test] + fn inflight_slots_are_a_power_of_two() { + use crate::host::{INFLIGHT_SLOT, inflight_slots}; + assert_eq!(inflight_slots(64 << 20), 1024); + assert_eq!(inflight_slots(100 << 20), 1024); + assert_eq!(inflight_slots(1), 1); + assert_eq!(inflight_slots(1 << 20), 16); + let most = inflight_slots(u64::MAX); + assert!(most.is_power_of_two() && u64::from(most) * INFLIGHT_SLOT <= 1 << 32); + } + + /// Tickets drawn and landed in order, the mark raised as the landing + /// raises it (every ticket a landed flight drew), through the counter's + /// wrap with the slots the default gives: no two tickets in the air + /// that got a slot share one, slots are still given after the wrap, and + /// the mark follows the counter. + #[test] + fn inflight_tickets_never_share_a_slot_across_the_wrap() { + use crate::host::{inflight_gets_slot, inflight_raise, inflight_slots}; + let slots = inflight_slots(64 << 20); + let mut landed = u32::MAX - 3000; + let mut next = landed; + // Flights of 1 to 700 flagged pieces, up to three in the air: + // (tickets drawn, those that got a slot). + let mut air: std::collections::VecDeque<(Vec<u32>, Vec<u32>)> = Default::default(); + let mut after_wrap = 0; + for flight in 0..40u32 { + let drawn: Vec<u32> = (0..1 + flight * 37 % 700).map(|i| next.wrapping_add(i)).collect(); + next = next.wrapping_add(drawn.len() as u32); + let slotted: Vec<u32> = drawn.iter().copied().filter(|&k| inflight_gets_slot(k, landed, slots)).collect(); + after_wrap += slotted.iter().filter(|&&k| k < 1 << 20).count(); + air.push_back((drawn, slotted)); + let mut used: Vec<u32> = air.iter().flat_map(|a| a.1.iter()).map(|k| k % slots).collect(); + let n = used.len(); + used.sort_unstable(); + used.dedup(); + assert_eq!(used.len(), n, "flight {flight}: two tickets in the air share a slot"); + if air.len() == 3 + && let Some((drawn, _)) = air.pop_front() + { + for k in drawn { + landed = inflight_raise(landed, k); + } + } + } + while let Some((drawn, _)) = air.pop_front() { + for k in drawn { + landed = inflight_raise(landed, k); + } + } + assert!(next < 1 << 20, "the counter wrapped"); + assert!(after_wrap > 0, "slots after the wrap"); + assert_eq!(landed, next); + // Raised in wrapping order, never back. + assert_eq!(inflight_raise(u32::MAX - 1, u32::MAX), 0); + assert_eq!(inflight_raise(5, 2), 5); + assert_eq!(inflight_raise(u32::MAX - 1, 3), 4); + assert!(!inflight_gets_slot(3, 4, 8)); + } + + /// Flights 5, 6, 7 in the air with the fetch inside flights: 5 lands + /// the old way with the queue's count at 7. The title's byte that went + /// up in send 7 must still be told apart when 6 lands from its slot + /// (its merge leaves out sends after 6), so send 7's note must outlive + /// the mark (`card_dirty` keeps notes above it, `card_merge_relay` + /// leaves out those above its "fetched after"). + #[test] + fn a_fetch_the_old_way_keeps_the_notes_flights_in_the_air_need() { + use crate::host::fallback_fetched_mark; + let notes = [5u64, 6, 7]; + let mark = fallback_fetched_mark(true, 7, Some(5)); + let kept: Vec<u64> = notes.iter().copied().filter(|&s| s > mark).collect(); + assert!(kept.iter().any(|&s| s > 6), "send 7's note was dropped before flight 6 merged"); + assert_eq!(mark, 5); + // Without the switch every later merge fetches after 7: as before. + assert_eq!(fallback_fetched_mark(false, 7, Some(5)), 7); + assert_eq!(fallback_fetched_mark(true, 7, None), 0); + } + + /// Changed ranges are joined where they overlap or touch, and only there. + #[test] + fn ranges_join_where_they_touch() { + assert_eq!(joined(vec![(8, 12), (0, 4), (4, 6), (10, 20), (30, 31)]), [(0, 6), (8, 20), (30, 31)]); + assert!(joined(Vec::new()).is_empty()); + } +} + +/// Whether the copy-back of what shaders wrote runs on a thread of its own, +/// beside the submitting thread and outside the submission lock +/// (`VICTORY_RELAY=1` or `2`; off by default; not with kept snapshots, +/// [`keeps`]). `crate::host::relay` says what it does; here it changes +/// what a copy keeps: +/// +/// - the ranges shaders may be writing are counted per submission +/// ([`Flights`]): a range two flights declared stays closed to refreshes +/// until both have been copied back; +/// - the merge of what the card wrote never stores into memory the card +/// may be writing ([`merge_piece`]): what it learns goes into title +/// memory and into the copy's reference (the snapshot, or the CPU's side +/// of a copy in the card's memory), under that reference's lock; +/// - what goes up to a copy in the card's memory is numbered +/// ([`card_dirty`]), so that a merge can tell the title's bytes the card +/// had not received from bytes the card wrote. +pub(crate) fn relay() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + // On by default (stage 2, `crate::host::relay_exact`); `VICTORY_RELAY=0` + // turns it off, `=1` asks for the first stage. + // The crate's own tests run without it unless they ask: several of + // them look at title memory right after a submission, which the + // relay's landing thread may still be writing. + *ON.get_or_init(|| std::env::var("VICTORY_RELAY").map_or(!cfg!(test), |v| v == "1" || v == "2") && !keeps()) +} + +/// The submission being prepared (its number among those started): what +/// [`Shadow::writing`] counts a declared range for ([`Flights`]). +static PREPARED: AtomicU64 = AtomicU64::new(0); + +/// A submission's preparing begins (`crate::host`, under the submission +/// lock). +pub(crate) fn preparing(number: u64) { + PREPARED.store(number, Ordering::Relaxed); +} + +/// With [`relay`]: the number of the last send of changed ranges to the +/// card (`crate::host`'s order of the queue) that every fetch still to be +/// merged came after. Notes of sends up to it are of no use any more. +static RELAY_FETCHED: AtomicU64 = AtomicU64::new(0); + +/// A fetch sent after send `number` is the oldest one that may still be +/// merged ([`RELAY_FETCHED`]). +pub(crate) fn relay_fetched(number: u64) { + RELAY_FETCHED.fetch_max(number, Ordering::AcqRel); +} + +/// With [`relay`]: how many submissions that are not copied back yet +/// declared each range shaders may be writing (range, count, the last +/// submission that declared it). +/// +/// Without it a range declared by two flights was one entry, and the end +/// of the first flight's copy-back removed it while the second was still +/// writing: the next refresh would have put title bytes over what the +/// second flight's shaders were writing. #[derive(Default)] -struct Before { - snapshot: Option<(usize, Vec<u8>)>, - unchanged: UnchangedPages, +struct Flights(Vec<((usize, usize), u32, u64)>); + +impl Flights { + /// Submission `number` declares `range`: counted once for it, however + /// often it declares it. + fn declare(&mut self, range: (usize, usize), number: u64) { + match self.0.iter_mut().find(|f| f.0 == range) { + Some(f) => { + if f.2 != number { + f.1 += 1; + f.2 = number; + } + } + None => self.0.push((range, 1, number)), + } + } + + /// One submission that declared `ranges` (each once) is copied back: + /// the ranges no other submission still holds. + fn done(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> { + let mut free = Vec::new(); + for range in ranges { + match self.0.iter().position(|f| f.0 == *range) { + Some(at) => { + self.0[at].1 = self.0[at].1.saturating_sub(1); + if self.0[at].1 == 0 { + self.0.swap_remove(at); + free.push(*range); + } + } + // Not counted (declared before anything counted): free. + None => free.push(*range), + } + } + free + } +} + +/// The relay's merge of a stretch of a copy ([`relay`]). `now` is what the +/// card's memory holds, read once; `held` is the copy's reference for the +/// stretch (its snapshot, or the CPU's side of a copy in the card's +/// memory): what the card's memory held when it was last looked at; +/// `title` is title memory as just read. Every byte the card changed +/// (`now` differs from `held`) goes into `title` and into `held`; every +/// other byte of both stays as it is, so a byte the title wrote and the +/// card did not keeps the title's value. Whether `title` changed. +/// +/// Nothing is stored into `now`'s source: the card may be writing it for a +/// later flight at this moment, and a store there, even of the value just +/// read, could undo that write. (The merge of a waited-for submission +/// stores every byte of a differing stretch back into the copy.) +fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { + let mut differs = 0u8; + for ((n, h), t) in now.iter().zip(held.iter_mut()).zip(title.iter_mut()) { + let wrote = if *n != *h { 0xffu8 } else { 0 }; + let merged = (*t & !wrote) | (*n & wrote); + differs |= merged ^ *t; + *t = merged; + *h = (*h & !wrote) | (*n & wrote); + } + differs != 0 +} + +/// `[from, to)` without the ranges of `skip`, in order. +pub(crate) fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + skip.sort_unstable(); + let mut out = Vec::new(); + let mut at = from; + for (a, b) in skip { + if b <= at { + continue; + } + if a >= to { + break; + } + if a > at { + out.push((at, a)); + } + at = at.max(b); + } + if at < to { + out.push((at, to)); + } + out +} + +/// The runs of 4-byte words of title memory (cut on its addresses; +/// `read` and `merged` are of the memory at `address`) that hold a byte in +/// which `merged` differs from `read`, as (offset, bytes) in order to +/// `put`. A shader stores words, so these are what the card wrote; every +/// other byte of `merged` is the title's as it was read. +fn word_runs(address: usize, read: &[u8], merged: &[u8], mut put: impl FnMut(usize, usize)) { + let n = read.len().min(merged.len()); + let mut i = 0; + while i < n { + // Equal bytes are passed over, 32 at a time while they last. + match first_difference(&read[i..n], &merged[i..n]) { + Some(d) => i += d, + None => break, + } + // From the word that holds this byte (or the stretch's first + // byte) to the end of the last word in a row that holds one. + let first = i - ((address + i) & 3).min(i); + let mut end = first; + while end < n { + let word = (((address + end) | 3) + 1 - address).min(n); + if read[end..word] == merged[end..word] { + break; + } + end = word; + } + put(first, end - first); + i = end; + } +} + +/// Whether the merges that write a stretch of title memory back +/// ([`Shadow::relay_merge`], [`Shadow::card_merge`], +/// [`Shadow::card_merge_relay`]) look, right before that write, for title +/// bytes it is about to put back to older values (`VICTORY_MERGE_RACE=1`; +/// off by default). Logging only: [`merge_race`]. +fn merge_race_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MERGE_RACE").is_some_and(|v| v == "1")) +} + +/// [`merge_race`]'s sums. Of frame `frame`, and in `total` since the +/// start: stretches written back, their bytes, title bytes put back to +/// older values, bytes the title and the card both changed, stretches with +/// either, the runs a write of the card's words alone makes +/// ([`word_runs`]) and their bytes. `said`: the frame's first stretches +/// with either. `quiet`: frames since the last line. +struct MergeRace { + frame: u64, + now: [u64; 7], + said: Vec<String>, + total: [u64; 7], + quiet: u64, +} + +static MERGE_RACE: Mutex<MergeRace> = + Mutex::new(MergeRace { frame: 0, now: [0; 7], said: Vec::new(), total: [0; 7], quiet: 0 }); + +/// With [`merge_race_on`], right before a merge writes `merged` over title +/// memory at `address` (a stretch of the copy of the title buffer `copy`: +/// start and bytes): title memory is read once more and compared with +/// `read`, what the merge read of it before. A byte that changed in +/// between and that the write-back stores with its value as first read +/// (the card did not change it) is a title byte put back to an older +/// value; one the write-back stores with the card's byte is one both +/// changed. Only bytes the write-back stores are looked at. Summed per +/// frame; a line for every frame that has any, and one every 100 frames +/// whatever it holds, so that "none" is said, not assumed. +/// +/// A lower bound: a title write that lands after this read (while the +/// write-back itself runs) is not seen, nor one that wrote a byte and then +/// its old value again. Costs one more read and two compares of every +/// stretch written back, on the thread that merges. +fn merge_race(read: Option<&[u8]>, copy: (u64, u64), address: usize, merged: &[u8], which: &'static str) { + if !merge_race_on() { + return; + } + let Some(read) = read else { + return; + }; + let n = read.len().min(merged.len()); + let (read, merged) = (&read[..n], &merged[..n]); + let mut runs: Vec<(usize, usize)> = Vec::new(); + word_runs(address, read, merged, |off, len| runs.push((off, len))); + let whole = [(0, n)]; + let looked: &[(usize, usize)] = &whole; + let mut again = vec![0u8; n]; + let (mut put_back, mut both, mut first) = (0u64, 0u64, None); + if crate::host::read_into(address as *const u8, &mut again) { + for &(off, len) in looked { + for i in off..off + len { + if again[i] == read[i] || again[i] == merged[i] { + continue; + } + if merged[i] == read[i] { + put_back += 1; + first.get_or_insert(i); + } else { + both += 1; + } + } + } + } + let frame = crate::frame::current(); + let mut race = MERGE_RACE.lock().unwrap_or_else(|e| e.into_inner()); + if race.frame != frame { + race.quiet += 1; + if race.now[4] > 0 || race.quiet >= 100 { + tracing::info!( + frame = race.frame, + stretches = race.now[0], + stretch_bytes = race.now[1], + put_back = race.now[2], + both_changed = race.now[3], + stretches_hit = race.now[4], + word_runs = race.now[5], + word_run_bytes = race.now[6], + stretches_since_start = race.total[0], + stretch_bytes_since_start = race.total[1], + put_back_since_start = race.total[2], + both_changed_since_start = race.total[3], + stretches_hit_since_start = race.total[4], + word_runs_since_start = race.total[5], + word_run_bytes_since_start = race.total[6], + first = ?race.said, + "merge race: title bytes that changed between a merge's read of title memory and its write-back of what shaders wrote, in this frame (VICTORY_MERGE_RACE=1)" + ); + race.quiet = 0; + } + race.frame = frame; + race.now = [0; 7]; + race.said.clear(); + } + let hit = u64::from(put_back + both > 0); + let run_bytes: u64 = runs.iter().map(|r| r.1 as u64).sum(); + let add = [1, n as u64, put_back, both, hit, runs.len() as u64, run_bytes]; + for (i, v) in add.iter().enumerate() { + race.now[i] += v; + race.total[i] += v; + } + if hit > 0 && race.said.len() < 8 { + race.said.push(format!( + "{which}: copy {:#x}+{:#x} stretch {address:#x}+{n:#x}: {put_back} put back (first at {:#x}), {both} both changed", + copy.0, + copy.1, + address + first.unwrap_or(0) + )); + } +} + +#[cfg(test)] +mod relay_tests { + use super::{Flights, changed_runs, merge_piece, outside}; + + /// A range two flights declared is free only when both are done, in + /// either order; a submission that declares it many times counts once. + #[test] + fn a_range_stays_closed_until_every_flight_that_declared_it_is_done() { + let (a, b) = ((0x1000, 0x2000), (0x1800, 0x3000)); + let mut flights = Flights::default(); + for _ in 0..3 { + flights.declare(a, 7); + } + flights.declare(b, 7); + flights.declare(a, 8); + // Flight 7 lands: `a` is still flight 8's, `b` was only flight 7's. + assert_eq!(flights.done(&[a, b]), vec![b]); + // Declared again meanwhile by a third. + flights.declare(a, 9); + assert_eq!(flights.done(&[a]), vec![]); + assert_eq!(flights.done(&[a]), vec![a]); + assert!(flights.0.is_empty()); + // The later flight first: the same. + flights.declare(a, 1); + flights.declare(a, 2); + assert_eq!(flights.done(&[a]), vec![]); + assert_eq!(flights.done(&[a]), vec![a]); + // A range never counted is free at once. + assert_eq!(flights.done(&[b]), vec![b]); + } + + /// The merge moves exactly the bytes the card changed, into title + /// memory and into the reference, and stores nothing else. + #[test] + fn the_merge_stores_only_what_the_card_changed() { + let held0: Vec<u8> = (0..200u32).map(|i| (i * 5 + 1) as u8).collect(); + let mut now = held0.clone(); + for at in [0usize, 3, 4, 5, 64, 199] { + now[at] ^= 0x33; + } + // The title wrote other bytes meanwhile, and one the card wrote too. + let mut title = held0.clone(); + for at in [1usize, 5, 100] { + title[at] = 0xee; + } + let title0 = title.clone(); + let mut held = held0.clone(); + assert!(merge_piece(&now, &mut held, &mut title)); + for at in 0..200 { + if now[at] != held0[at] { + assert_eq!((title[at], held[at]), (now[at], now[at]), "the card's byte at {at}"); + } else { + assert_eq!((title[at], held[at]), (title0[at], held0[at]), "untouched at {at}"); + } + } + // Again with nothing new: nothing changes and nothing is reported. + let (title1, held1) = (title.clone(), held.clone()); + assert!(!merge_piece(&now, &mut held, &mut title)); + assert_eq!((title, held), (title1, held1)); + } + + #[test] + fn ranges_are_cut_out() { + assert_eq!(outside(10, 50, vec![]), vec![(10, 50)]); + assert_eq!(outside(10, 50, vec![(0, 10), (50, 60)]), vec![(10, 50)]); + assert_eq!(outside(10, 50, vec![(30, 35), (0, 12), (34, 40), (48, 99)]), vec![(12, 30), (40, 48)]); + assert_eq!(outside(10, 50, vec![(0, 99)]), vec![]); + } + + /// A model of a copy in the PC's memory under the relay: the card + /// writes `copy` directly; `snap` is the snapshot; `title` is title + /// memory. Flight A and flight B declare overlapping ranges and both + /// are in the air; the title's CPU writes in between and its bytes are + /// put in beside the flights' (`merge_under_writes`: into the copy and + /// the snapshot); A lands while B is still writing; then B lands. + #[test] + fn two_flights_overlapping_ranges_and_a_cpu_write_in_between() { + const N: usize = 64; + let base: Vec<u8> = (0..N as u32).map(|i| i as u8).collect(); + let (mut copy, mut title) = (base.clone(), base.clone()); + // A declares [0, 40), B declares [24, 64): each byte's snapshot is + // taken when the first range that holds it is declared. + let (a, b) = ((0usize, 40usize), (24usize, 64usize)); + let mut snap = base.clone(); + // The card runs A: writes 4..12 and 30..34. + for at in (4..12).chain(30..34) { + copy[at] = 0xa0; + } + // The title's CPU writes 8..10 (over A's bytes), 20 and 50, after + // A's refresh: the next submission's preparing finds them against + // the snapshot and puts them in, into the copy and the snapshot. + for at in [8usize, 9, 20, 50] { + title[at] = 0x77; + } + for (at, n) in changed_runs(&title, &snap) { + copy[at..at + n].copy_from_slice(&title[at..at + n]); + snap[at..at + n].copy_from_slice(&title[at..at + n]); + } + // The card starts B: it has written 32..36 so far, over A's 32..34. + for at in 32..36 { + copy[at] = 0xb0; + } + // A lands (B still on the card): its range is merged. The copy is + // read once and not written. + let seen = copy.clone(); + { + let mut t = title[a.0..a.1].to_vec(); + assert!(merge_piece(&seen[a.0..a.1], &mut snap[a.0..a.1], &mut t)); + title[a.0..a.1].copy_from_slice(&t); + } + assert_eq!(copy, seen, "the merge stores nothing into the copy"); + // A's bytes are in title memory, except where the title wrote + // after A's shaders did (8, 9: the title's); B's first bytes came + // along; nothing of B's range beyond A's was touched. + for at in (4..8).chain(10..12).chain(30..32) { + assert_eq!(title[at], 0xa0, "A's byte at {at}"); + } + assert_eq!((title[8], title[9], title[20], title[50]), (0x77, 0x77, 0x77, 0x77)); + for at in 32..36 { + assert_eq!(title[at], 0xb0, "B's byte so far at {at}"); + } + // The card finishes B: 36..44. + for at in 36..44 { + copy[at] = 0xb1; + } + // The title's CPU writes 40 after B's shader did: found against + // the snapshot at the next preparing, which is before B lands. + title[40] = 0x55; + for (at, n) in changed_runs(&title[b.0..b.1], &snap[b.0..b.1]) { + let at = at + b.0; + copy[at..at + n].copy_from_slice(&title[at..at + n]); + snap[at..at + n].copy_from_slice(&title[at..at + n]); + } + // B lands. + let seen = copy.clone(); + { + let mut t = title[b.0..b.1].to_vec(); + assert!(merge_piece(&seen[b.0..b.1], &mut snap[b.0..b.1], &mut t)); + title[b.0..b.1].copy_from_slice(&t); + } + // B's results are there, never replaced by A's older ones. + for at in 32..36 { + assert_eq!(title[at], 0xb0); + } + for at in (36..40).chain(41..44) { + assert_eq!(title[at], 0xb1, "B's byte at {at}"); + } + assert_eq!(title[40], 0x55, "the title wrote it last"); + // In the declared ranges the copy, the snapshot and title memory + // now agree byte for byte: nothing is left to hand back, and + // nothing was lost. + assert_eq!(copy[a.0..b.1], title[a.0..b.1]); + assert_eq!(snap[a.0..b.1], title[a.0..b.1]); + // A third merge finds nothing. + let mut t = title.clone(); + assert!(!merge_piece(©, &mut snap, &mut t)); + } + + /// A model of a copy in the card's memory under the relay: `card` is + /// the card's side, `cpu` the CPU's side, `title` title memory. The + /// title's changed bytes go into the CPU's side at once and up to the + /// card with a later send; pieces fetched before that send must not + /// take the card's older bytes there for something the card wrote. + #[test] + fn title_bytes_not_yet_on_the_card_are_not_taken_for_shader_writes() { + const N: usize = 48; + let base: Vec<u8> = (0..N as u32).map(|i| (i + 100) as u8).collect(); + let (mut card, mut cpu, mut title) = (base.clone(), base.clone(), base.clone()); + // Flight A's shaders write 10..14 on the card. + for at in 10..14 { + card[at] = 0xa0; + } + // The title's CPU writes 12 (over A's) and 30; the preparing of + // the next submission puts both into the CPU's side and notes them + // to go up (send 5). They are not on the card yet. + title[12] = 0x77; + title[30] = 0x78; + let mut noted = Vec::new(); + for (at, n) in changed_runs(&title, &cpu) { + cpu[at..at + n].copy_from_slice(&title[at..at + n]); + noted.push((at, at + n, 5u64)); + } + // A's pieces are fetched after send 4, before send 5: the fetch + // holds A's bytes and the card's old bytes at 12 and 30. + let fetched = card.clone(); + let fetched_after = 4u64; + // Send 5 goes up behind it. + for &(a, b, _) in ¬ed { + card[a..b].copy_from_slice(&cpu[a..b]); + } + // The merge leaves out what went up after the fetch. + let skip: Vec<(usize, usize)> = noted.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)).collect(); + let mut changed = false; + for (a, b) in outside(0, N, skip) { + let mut t = title[a..b].to_vec(); + changed |= merge_piece(&fetched[a..b], &mut cpu[a..b], &mut t); + title[a..b].copy_from_slice(&t); + } + assert!(changed); + // A's bytes arrived; the title's two writes stand, in title memory + // and on both sides of the copy. + for at in [10usize, 11, 13] { + assert_eq!((title[at], cpu[at]), (0xa0, 0xa0)); + } + assert_eq!((title[12], cpu[12], card[12]), (0x77, 0x77, 0x77)); + assert_eq!((title[30], cpu[30], card[30]), (0x78, 0x78, 0x78)); + assert_eq!(card, cpu); + assert_eq!(card, title); + // Without the leaving out, the card's old byte at 30 would have + // been taken for a shader write and put over the title's. + let mut wrong_title = title.clone(); + let mut wrong_cpu = cpu.clone(); + merge_piece(&fetched, &mut wrong_cpu, &mut wrong_title); + assert_eq!(wrong_title[30], base[30]); + } +} + +/// Snapshot memory kept for reuse (already touched, so no page faults). +static POOL: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new()); + +/// An empty buffer with room for `n` bytes, from the pool if it has one +/// of about that size: a small copy's snapshot took the 174 MB buffer kept +/// for the big heap's, which then got another, until eight of them were +/// reserved (1.4 GB in run 24). +fn pooled(n: usize) -> Vec<u8> { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let most = n.saturating_mul(4).max(1 << 20); + let fit = pool + .iter() + .enumerate() + .filter(|(_, v)| v.capacity() >= n && v.capacity() <= most) + .min_by_key(|(_, v)| v.capacity()) + .map(|(i, _)| i); + let mut v = match fit { + Some(i) => pool.swap_remove(i), + None => Vec::with_capacity(n), + }; + v.clear(); + v +} + +/// Returns a snapshot buffer to the pool: at most 8 kept, the largest, and +/// of those the largest one and the next ones up to `KEPT` bytes in all. +fn give_back(v: Vec<u8>) { + const KEPT: usize = 512 << 20; + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + pool.push(v); + pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); + pool.truncate(8); + let (mut seen, mut total) = (0, 0usize); + pool.retain(|v| { + seen += 1; + total = total.saturating_add(v.capacity()); + seen == 1 || total <= KEPT + }); +} + +const NOT_WATCHED: u8 = 2; + +/// [`Shadow::update_free`]'s counter (fps41 round 8): refreshes that copied +/// nothing are also looked at for being known unchanged before asking +/// (`VICTORY_REFRESH_COUNT=1`; off by default: the look takes the +/// journal's and the guards' locks once more a refresh). +#[cfg(feature = "diagnostics")] +fn refresh_count() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_COUNT").is_some_and(|v| v == "1")) +} + +// Fixed-size equality compiles to two SIMD comparisons on Windows x64. +// Only the first or last unequal chunk needs a byte-wise search. +const DIFF_CHUNK: usize = 32; + +/// Where `a` and `b` first differ within their common length. +fn first_difference(a: &[u8], b: &[u8]) -> Option<usize> { + let len = a.len().min(b.len()); + let (a_chunks, a_tail) = a[..len].as_chunks::<DIFF_CHUNK>(); + let (b_chunks, b_tail) = b[..len].as_chunks::<DIFF_CHUNK>(); + let (offset, a, b) = match a_chunks.iter().zip(b_chunks).position(|(x, y)| x != y) { + Some(i) => (i * DIFF_CHUNK, &a_chunks[i][..], &b_chunks[i][..]), + None => (len - a_tail.len(), a_tail, b_tail), + }; + a.iter().zip(b).position(|(x, y)| x != y).map(|i| offset + i) +} + +/// Where `a` and `b` last differ within their common length. +fn last_difference(a: &[u8], b: &[u8]) -> Option<usize> { + let len = a.len().min(b.len()); + let (a_chunks, a_tail) = a[..len].as_chunks::<DIFF_CHUNK>(); + let (b_chunks, b_tail) = b[..len].as_chunks::<DIFF_CHUNK>(); + if let Some(i) = a_tail.iter().zip(b_tail).rposition(|(x, y)| x != y) { + return Some(len - a_tail.len() + i); + } + let chunk = a_chunks.iter().zip(b_chunks).rposition(|(x, y)| x != y)?; + a_chunks[chunk] + .iter() + .zip(&b_chunks[chunk]) + .rposition(|(x, y)| x != y) + .map(|i| chunk * DIFF_CHUNK + i) +} + +#[cfg(test)] +mod difference_tests { + use super::{first_difference, last_difference}; + + /// The chunk searches agree with a byte-wise scan across chunk boundaries. + #[test] + fn differences_are_found_as_byte_by_byte() { + let base: Vec<u8> = (0..98u32).map(|i| (i * 7 + 3) as u8).collect(); + for len in [0, 1, 31, 32, 33, 63, 64, 65, 97] { + let a = &base[1..1 + len]; + let same = a.to_vec(); + assert_eq!(first_difference(&same, a), None); + assert_eq!(last_difference(&same, a), None); + for at in 0..len { + for other in at..len { + let mut b = a.to_vec(); + b[at] ^= 0x80; + b[other] ^= 0x01; + let first = a.iter().zip(&b).position(|(x, y)| x != y); + let last = a.iter().zip(&b).rposition(|(x, y)| x != y); + assert_eq!(first_difference(a, &b), first, "{len} {at} {other}"); + assert_eq!(last_difference(a, &b), last, "{len} {at} {other}"); + } + } + } + } + + #[test] + fn differences_ignore_bytes_past_the_shorter_slice() { + let a = [0; 65]; + let mut b = [0; 67]; + b[65] = 1; + assert_eq!(first_difference(&a, &b), None); + assert_eq!(last_difference(&b, &a), None); + b[32] = 1; + b[64] = 1; + assert_eq!(first_difference(&b, &a), Some(32)); + assert_eq!(last_difference(&a, &b), Some(64)); + } +} + +/// The unit shader writes are looked for and put back in. +const PIECE: usize = 64 << 10; + +/// Copies `len` bytes, on several threads if they are many: a snapshot of +/// the world's big heap is 100-170 MB per submission, 2-4 GB a frame, and +/// one thread copies some 8 GB/s. +/// +/// # Safety +/// Both ranges are valid for `len` bytes and do not overlap. +unsafe fn copy_wide(src: *const u8, dst: *mut u8, len: usize) { + const PER_THREAD: usize = 16 << 20; + let threads = (len / PER_THREAD).clamp(1, 6); + if threads == 1 { + // SAFETY: the caller's. + unsafe { std::ptr::copy_nonoverlapping(src, dst, len) }; + return; + } + let (src, dst, each) = (src as usize, dst as usize, len.div_ceil(threads)); + std::thread::scope(|s| { + for i in 0..threads { + let at = (i * each).min(len); + let n = each.min(len - at); + s.spawn(move || { + // SAFETY: a part of the caller's ranges. + unsafe { std::ptr::copy_nonoverlapping((src + at) as *const u8, (dst + at) as *mut u8, n) }; + }); + } + }); +} + +/// Whether the snapshots of a submission's shader-written ranges, and the +/// compare that finds what the shaders wrote, run on several threads +/// across ranges (`VICTORY_WIDE_BACK=1`; off by default). +/// +/// Both ran range by range on the submitting thread, a range on several +/// threads only if it was 16 MiB or more. The ranges left on the CPU's side +/// since the big buffers went to the card are small and many: in run 86, +/// 7,024 declared ranges a frame, 375 MB of them compared after the card +/// ran in 563 pieces of work, none of 16 MiB: 51 ms a frame of snapshots +/// and 35 ms of comparing, one thread, bound by one core's memory speed. +/// +/// With the switch a submission's snapshots are noted as it is prepared +/// and taken together when its refreshes are done, just before it goes to +/// the card ([`take_snapshots`]), and the compares of everything declared +/// run together after the card ([`find_all`]), both cut into pieces of +/// work of about 1 MiB for a few threads that are kept ([`wide`]). The +/// bytes taken and the bytes compared are the same ones: a range's bytes +/// cannot change between the moment it is declared and the end of the +/// preparing (a declared range is left alone by every refresh, the title's +/// own copies write title memory and not the copy, and the card runs the +/// lists only afterwards). +pub(crate) fn wide_back() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + // On by default; `VICTORY_WIDE_BACK=0` turns it off. + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_BACK").is_none_or(|v| v != "0")) +} + +type Job = Box<dyn FnOnce() + Send>; + +/// Threads kept for [`wide`]: what they are to do, and the word that there +/// is something. +struct Workers { + jobs: Mutex<std::collections::VecDeque<Job>>, + more: std::sync::Condvar, +} + +fn workers() -> &'static Workers { + static WORKERS: std::sync::OnceLock<Workers> = std::sync::OnceLock::new(); + static STARTED: std::sync::Once = std::sync::Once::new(); + let workers = WORKERS.get_or_init(|| Workers { + jobs: Mutex::new(std::collections::VecDeque::new()), + more: std::sync::Condvar::new(), + }); + STARTED.call_once(|| { + let n = wide_threads(); + let raise = wide_priority(); + tracing::info!(threads = n, above_normal = raise, "threads for wide work (VICTORY_WIDE_THREADS, VICTORY_WIDE_PRIORITY)"); + for i in 0..n { + let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || { + let workers = WORKERS.get().expect("made above"); + if raise { + raise_this_thread(); + } + loop { + let job = { + let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(job) = jobs.pop_front() { + break job; + } + jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner()); + } + }; + job(); + } + }); + } + }); + workers +} + +/// How many kept threads [`wide`] work runs on (`VICTORY_WIDE_THREADS`, +/// 1 to 32). Try 6.0: by default all of the CPU's threads but two (the +/// submitting thread and the title's), at least 2 and at most 16 (8 since 6.8). It was a +/// quarter of them, at most 6: on a 16-thread CPU the copy-back, the +/// refreshes and the snapshots of a world frame (100-150 MB of compares, +/// 280 ms of landing in the 2026-11-26 report) ran on 4 threads while +/// 10 stood idle. Try 6.8: at most 8, as the heap worker, the texture +/// pass and the parallel refreshes have threads of their own now (and a +/// 12-thread laptop with an RTX 3050 copied back faster on 8 than on 10). +pub(crate) fn wide_threads() -> usize { + static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + *N.get_or_init(|| { + let cores = std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get); + wide_threads_for(std::env::var("VICTORY_WIDE_THREADS").ok().as_deref(), cores) + }) +} + +fn wide_threads_for(setting: Option<&str>, cores: usize) -> usize { + match setting.and_then(|v| v.trim().parse::<usize>().ok()) { + Some(n) => n.clamp(1, 32), + None => cores.saturating_sub(2).clamp(2, 8), + } +} + +/// Whether the kept threads run above normal priority +/// (`VICTORY_WIDE_PRIORITY=0`: no). Their work is what the submitting +/// thread waits for; at normal priority Windows shared their cores with +/// the title's own busy threads, and with the shader compilers. +fn wide_priority() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_PRIORITY").is_none_or(|v| v != "0")) +} + +/// Raises the calling thread to above normal priority. +pub(crate) fn raise_this_thread() { + // SAFETY: a plain call on our own thread. + unsafe { + use windows::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL}; + let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); + } +} + +#[cfg(test)] +mod wide_thread_tests { + use super::wide_threads_for; + + #[test] + fn wide_threads_scale_with_the_cpu() { + assert_eq!(wide_threads_for(None, 4), 2); + assert_eq!(wide_threads_for(None, 12), 8); + assert_eq!(wide_threads_for(None, 8), 6); + assert_eq!(wide_threads_for(None, 32), 8); + assert_eq!(wide_threads_for(Some("3"), 32), 3); + assert_eq!(wide_threads_for(Some("0"), 8), 1); + assert_eq!(wide_threads_for(Some("x"), 8), 6); + } +} + +/// Runs `jobs` on the kept threads and on this one, and returns when all +/// of them are done. The jobs copy and compare memory; they do not panic. +fn wide(jobs: Vec<Job>) { + if jobs.len() < 2 { + for job in jobs { + job(); + } + return; + } + let workers = workers(); + let left = Arc::new((Mutex::new(jobs.len()), std::sync::Condvar::new())); + { + let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); + for job in jobs { + let left = left.clone(); + queue.push_back(Box::new(move || { + job(); + let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner()); + *n -= 1; + if *n == 0 { + left.1.notify_all(); + } + })); + } + } + workers.more.notify_all(); + loop { + let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); + match job { + Some(job) => job(), + None => break, + } + } + let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner()); + while *n > 0 { + n = left.1.wait(n).unwrap_or_else(|e| e.into_inner()); + } +} + +/// [`wide`], for the host's own work on host copies (a submission's +/// refreshes, the merge of what shaders wrote to card copies). +pub(crate) fn wide_run(jobs: Vec<Box<dyn FnOnce() + Send>>) { + wide(jobs); +} + +/// About this many bytes to a piece of work for [`wide`]: 256 KiB (1 MiB +/// before), so that a submission's typical 1.5-2 MB of snapshots and +/// copy-back fans out over all the workers instead of two (lepotane/ +/// VIctory-leonida c6c9da9f; Try 6.11). +const WIDE_JOB: usize = 256 << 10; + +/// With [`wide_back`]: the snapshots noted while a submission is prepared +/// (from, to, bytes), taken by [`take_snapshots`]. +static SNAPS: Mutex<Vec<(usize, usize, usize)>> = Mutex::new(Vec::new()); + +/// With [`wide_back`], when a submission's refreshes are done and before +/// its lists go to the card: takes the snapshots [`Shadow::writing`] noted. +/// Nothing to do without the switch. +pub(crate) fn take_snapshots() { + let snaps = std::mem::take(&mut *SNAPS.lock().unwrap_or_else(|e| e.into_inner())); + if snaps.is_empty() { + return; + } + wide(copy_jobs(snaps)); +} + +/// `copies` (from, to, bytes) as pieces of work of about [`WIDE_JOB`] +/// bytes each: long ones cut, short ones together. +fn copy_jobs(copies: Vec<(usize, usize, usize)>) -> Vec<Job> { + let mut jobs: Vec<Job> = Vec::new(); + let mut group: Vec<(usize, usize, usize)> = Vec::new(); + let mut bytes = 0; + let flush = |group: &mut Vec<(usize, usize, usize)>, jobs: &mut Vec<Job>| { + let group = std::mem::take(group); + if !group.is_empty() { + jobs.push(Box::new(move || { + for (src, dst, len) in group { + // SAFETY: the caller's ranges: a host copy's mapping and + // its snapshot, which do not overlap. + unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) }; + } + })); + } + }; + for (src, dst, len) in copies { + let mut at = 0; + while at < len { + let n = (WIDE_JOB - bytes).min(len - at); + group.push((src + at, dst + at, n)); + at += n; + bytes += n; + if bytes >= WIDE_JOB { + flush(&mut group, &mut jobs); + bytes = 0; + } + } + } + flush(&mut group, &mut jobs); + jobs +} + +/// With [`wide_back`]: for each of `work` (a copy not in the card's memory +/// and a range `[address, end)` its shaders may have written, declared and +/// not yet done), the 64 KiB pieces that differ from the snapshot, as +/// [`Shadow::copy_back_with`] takes them; found on several threads. +pub(crate) fn find_all(work: &[(Arc<Shadow>, usize, usize)]) -> Vec<Vec<(usize, usize)>> { + let scans = work + .iter() + .map(|(shadow, address, end)| { + let (from, to) = shadow.inside(*address, end.saturating_sub(*address)); + // The snapshot's memory stays until the range is done with + // (`copy_back_done`), which comes after this. + match shadow.before.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + Some(before) => (shadow.data as usize, before.as_ptr() as usize, shadow.start as usize, from, to), + None => (0, 0, 0, 0, 0), + } + }) + .collect(); + find_pieces(scans) +} + +/// For each of `scans` (where a copy's bytes are, where its snapshot's +/// are, the title address the copy starts at, offsets from and to): the +/// 64 KiB pieces (cut at multiples of 64 KiB of title memory, as +/// [`Shadow::differing`] cuts them) of `[from, to)` whose bytes differ, as +/// (offset, bytes) in order. On several threads ([`wide`]), in pieces of +/// work of about [`WIDE_JOB`] bytes that hold whole pieces. +fn find_pieces(scans: Vec<(usize, usize, usize, usize, usize)>) -> Vec<Vec<(usize, usize)>> { + // What a job finds: (which scan, its place among that scan's jobs, the + // pieces). + type Found = Vec<(usize, usize, Vec<(usize, usize)>)>; + // A job's part of a scan: the scan, then which and place. + type Part = (usize, usize, usize, usize, usize, usize, usize); + let found: Arc<Mutex<Found>> = Arc::default(); + let mut jobs: Vec<Job> = Vec::new(); + let mut group: Vec<Part> = Vec::new(); + let mut bytes = 0; + let flush = |group: &mut Vec<Part>, jobs: &mut Vec<Job>| { + let group = std::mem::take(group); + if group.is_empty() { + return; + } + let found = found.clone(); + jobs.push(Box::new(move || { + let mut mine: Found = Vec::with_capacity(group.len()); + for (data, before, start, from, to, which, place) in group { + let mut pieces = Vec::new(); + let mut at = from; + while at < to { + let n = (PIECE - (start + at) % PIECE).min(to - at); + // SAFETY: inside the copy's mapping and its snapshot + // (which holds the copy's bytes at the copy's offsets); + // nothing writes either while a submission's results + // are compared. + let (now, old) = unsafe { + ( + std::slice::from_raw_parts((data + at) as *const u8, n), + std::slice::from_raw_parts((before + at) as *const u8, n), + ) + }; + if now != old { + pieces.push((at, n)); + } + at += n; + } + mine.push((which, place, pieces)); + } + found.lock().unwrap_or_else(|e| e.into_inner()).extend(mine); + })); + }; + let count = scans.len(); + for (which, (data, before, start, from, to)) in scans.into_iter().enumerate() { + let (mut at, mut place) = (from, 0); + while at < to { + // Cut where pieces end, so that every job sees whole pieces. + let room = (WIDE_JOB - bytes).max(PIECE); + let mut next = (at + room).min(to); + if next < to { + next -= (start + next) % PIECE; + if next <= at { + next = (at + PIECE - (start + at) % PIECE).min(to); + } + } + group.push((data, before, start, at, next, which, place)); + bytes += next - at; + place += 1; + at = next; + if bytes >= WIDE_JOB { + flush(&mut group, &mut jobs); + bytes = 0; + } + } + } + flush(&mut group, &mut jobs); + wide(jobs); + let mut found = std::mem::take(&mut *found.lock().unwrap_or_else(|e| e.into_inner())); + found.sort_unstable_by_key(|f| (f.0, f.1)); + let mut out = vec![Vec::new(); count]; + for (which, _, pieces) in found { + out[which].extend(pieces); + } + out } -/// Pages already compared in full against this submission's snapshot. -#[derive(Default)] -struct UnchangedPages { - start: usize, - end: usize, - pages: Vec<bool>, +/// Since the last frame-rate line, of the shader-written ranges looked for +/// on the CPU (copies not in the card's memory): bytes snapshotted in +/// windows outside buffers and in title buffers' copies; bytes compared in +/// windows, in buffers' copies, and of those in copies of 1 MiB or more; +/// ranges compared in windows and in buffers' copies. +static BACK_CLASS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + +/// For the frame-rate line: where the CPU's search for shader writes goes +/// (per frame). A copy of a title buffer can go to the card's memory, +/// where the card does the search (`VICTORY_CARD_BUFFERS_MIN_MB`); a +/// window outside buffers cannot as the code stands. +pub(crate) fn back_line(frames: f64) { + let c: Vec<f64> = BACK_CLASS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if c.iter().all(|&v| v == 0.0) { + return; + } + let mb = |v: f64| v / (1 << 20) as f64; + tracing::info!( + "shader writes looked for on the CPU per frame: {:.1} MB compared in {:.0} ranges of windows outside buffers ({:.1} MB \ + snapshotted), {:.1} MB in {:.0} ranges of title buffers' copies ({:.1} MB snapshotted), of them {:.1} MB in copies \ + of 1 MiB or more (VICTORY_CARD_BUFFERS_MIN_MB=1 would have the card look there)", + mb(c[2]), + c[5], + mb(c[0]), + mb(c[3]), + c[6], + mb(c[1]), + mb(c[4]), + ); } -impl UnchangedPages { - fn begin(&mut self, start: usize, end: usize) { - if self.pages.is_empty() { - self.start = start; - self.end = end; - self.pages.resize(end.div_ceil(PAGE) - start / PAGE, false); +#[cfg(test)] +mod wide_tests { + use super::{Job, PIECE, WIDE_JOB, copy_jobs, find_pieces, wide}; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Every job runs once, however many there are, and `wide` returns + /// only when all have. + #[test] + fn all_jobs_run_before_wide_returns() { + for n in [0usize, 1, 2, 7, 300] { + let ran = Arc::new(AtomicUsize::new(0)); + let jobs: Vec<Job> = (0..n) + .map(|i| { + let ran = ran.clone(); + Box::new(move || { + ran.fetch_add(i + 1, Ordering::Relaxed); + }) as Job + }) + .collect(); + wide(jobs); + assert_eq!(ran.load(Ordering::Relaxed), n * (n + 1) / 2, "{n} jobs"); } } - fn differs(&mut self, address: usize, current: &[u8], before: &[u8]) -> bool { - let page = address / PAGE; - let unchanged = &mut self.pages[page - self.start / PAGE]; - if *unchanged { - return false; + /// Copies cut into jobs copy every byte once: long ones, short ones + /// and empty ones. + #[test] + fn copies_cut_into_jobs_copy_the_same_bytes() { + let len = 3 * WIDE_JOB + 12345; + let src: Vec<u8> = (0..len).map(|i| (i * 31 + i / 977) as u8).collect(); + let mut dst = vec![0u8; len]; + let (s, d) = (src.as_ptr() as usize, dst.as_mut_ptr() as usize); + // Ranges of the buffer, each to the same offsets of the other. + let cuts = [0, 1, 1, 4096, 70_000, WIDE_JOB + 3, 2 * WIDE_JOB + 3, 2 * WIDE_JOB + 9, len]; + let copies: Vec<(usize, usize, usize)> = cuts.windows(2).map(|w| (s + w[0], d + w[0], w[1] - w[0])).collect(); + let jobs = copy_jobs(copies); + assert!(jobs.len() >= 3); + wide(jobs); + assert!(src == dst); + } + + /// The pieces found on several threads are the ones a walk piece by + /// piece finds, for copies that start anywhere in a 64 KiB piece of + /// title memory and ranges that start and end anywhere. + #[test] + fn pieces_found_wide_are_those_found_one_by_one() { + let len = 5 * WIDE_JOB / 2 + 777; + let old: Vec<u8> = (0..len).map(|i| (i * 7 + i / 513) as u8).collect(); + let mut now = old.clone(); + // Changes: single bytes at piece edges, a run across two pieces, + // the last byte, and nothing in between. + for at in [0usize, 1, PIECE - 1, PIECE, 3 * PIECE + 5, WIDE_JOB - 1, WIDE_JOB, WIDE_JOB + PIECE / 2, 2 * WIDE_JOB + 9, len - 1] { + now[at] ^= 0x5a; } - if current != before { - return true; + for byte in &mut now[9 * PIECE - 40..9 * PIECE + 40] { + *byte ^= 0x01; } - // A later range can touch bytes a partial comparison missed. At - // the edges, only bytes covered by the snapshot can be compared. - *unchanged = address == (page * PAGE).max(self.start) - && address + current.len() == ((page + 1) * PAGE).min(self.end); - false + let (data, before) = (now.as_ptr() as usize, old.as_ptr() as usize); + let mut scans = Vec::new(); + let mut wanted = Vec::new(); + for start in [0usize, 4096, PIECE - 16, 0xd_b790_df00] { + for (from, to) in [(0, len), (0, 1), (1, 2), (PIECE - 1, PIECE + 1), (3 * PIECE, 3 * PIECE), (12345, len - 1), (WIDE_JOB - 3, 2 * WIDE_JOB + 10)] { + scans.push((data, before, start, from, to)); + let mut pieces = Vec::new(); + let mut at = from; + while at < to { + let n = (PIECE - (start + at) % PIECE).min(to - at); + if now[at..at + n] != old[at..at + n] { + pieces.push((at, n)); + } + at += n; + } + wanted.push(pieces); + } + } + // A scan of nothing (a range whose snapshot is gone). + scans.push((0, 0, 0, 0, 0)); + wanted.push(Vec::new()); + assert_eq!(find_pieces(scans), wanted); } +} - fn clear(&mut self) { - self.pages.clear(); +/// What [`Shadow::copy_back`] does with a piece that differs from the +/// snapshot: `host` is the copy's bytes there, `old` the snapshot's. From +/// the first byte that differs to the last, title memory is read into +/// `title` (scratch, sized to that stretch) by `read` (the stretch's offset +/// in the piece, where to), the GPU's bytes are put in and `host` takes the +/// result. The stretch's offset in the piece and its length if that changed +/// title memory; none if nothing differs or title memory is not there. +/// `runs` takes the runs of the stretch (offsets into `title`, lengths) +/// whose bytes are the GPU's and differ from the title's as read: only +/// those are to be written, so a title write that lands between the read +/// and the write elsewhere in the stretch stays (upstream VIctory #2009). +/// `mask` is scratch. +fn back_piece( + host: &mut [u8], + old: &[u8], + title: &mut Vec<u8>, + mask: &mut Vec<u8>, + runs: &mut Vec<(usize, usize)>, + read: impl FnOnce(usize, &mut [u8]) -> bool, +) -> Option<(usize, usize)> { + runs.clear(); + // From the first byte that differs to the last: title memory is read + // and written there only (a shader that sets a few words of a piece + // cost a read, a walk and a write of all 64 KiB of it). + let first = first_difference(host, old)?; + let last = last_difference(host, old).unwrap_or(first); + let n = last + 1 - first; + let (host, old) = (&mut host[first..=last], &old[first..=last]); + title.clear(); + title.resize(n, 0); + if !read(first, title) { + return None; } + // Title memory with the GPU's bytes put in; the copy takes the title's + // bytes in turn. + // Without a branch, so the loop runs many bytes at a time: the GPU's + // byte where the copy's byte is not what it was before the submission + // and the title left its byte as it was, else the title's. (With the + // two searches above this was 44 ms a frame for 970 pieces.) + // Where the shader and the title both changed a byte while the GPU ran, + // the title's stays: the shader computed its byte from the copy's older + // data (one cleared a bit of a record the title had already replaced, + // and copying it back broke the title's object: an access violation + // through 0xffffffff00000000; PalmVIDev e0b70476, VIctory f39c6c2). + mask.clear(); + mask.resize(n, 0); + let mut differs = 0u8; + for (((t, h), o), m) in title.iter_mut().zip(host.iter_mut()).zip(old).zip(mask.iter_mut()) { + let gpu = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 }; + let merged = (*t & !gpu) | (*h & gpu); + *m = merged ^ *t; + differs |= *m; + *t = merged; + *h = merged; + } + if differs == 0 { + return None; + } + let mut i = 0; + while i < n { + while i < n && mask[i] == 0 { + i += 1; + } + let start = i; + while i < n && mask[i] != 0 { + i += 1; + } + if i > start { + runs.push((start, i - start)); + } + } + Some((first, n)) } -/// Snapshot memory kept for reuse (already touched, so no page faults). -static POOL: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new()); +/// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages +/// compared, changed runs put in, and their bytes. +static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; -/// An empty buffer with room for `n` bytes, from the pool if it has one. -fn pooled(n: usize) -> Vec<u8> { - let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); - let fit = pool - .iter() - .enumerate() - .filter(|(_, v)| v.capacity() >= n) - .min_by_key(|(_, v)| v.capacity()) - .map(|(i, _)| i); - let mut v = match fit { - Some(i) => pool.swap_remove(i), - None => Vec::with_capacity(n), +/// Why [`Shadow::merge_under_writes`] gave up (the flights are then +/// settled whole, 64 to 94 ms each in run 282), since they were last +/// taken: the copy's memory is not watched; the write tracking had no +/// answer for the range; more changed runs than `VICTORY_MERGE_RUNS` +/// leaves; a copy in PC memory without its snapshot. +static MERGE_GAVE_UP: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// [`MERGE_GAVE_UP`], taken. +pub(crate) fn merge_gave_up() -> [u64; 4] { + [0, 1, 2, 3].map(|i| MERGE_GAVE_UP[i].swap(0, Ordering::Relaxed)) +} + +/// [`MERGED`], taken. +pub(crate) fn merged_stats() -> [u64; 3] { + [0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed)) +} + +/// Since the last frame-rate line, why [`Shadow::merge_under_writes`] left +/// the flights to be settled: the compare without a journal over its +/// budget, no snapshot, the changed runs over theirs; then pages compared +/// with no journal to say which were written. +static MERGE_SETTLES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// [`MERGE_SETTLES`], taken. +pub(crate) fn merge_settle_stats() -> [u64; 4] { + [0, 1, 2, 3].map(|i| MERGE_SETTLES[i].swap(0, Ordering::Relaxed)) +} + +/// Bytes of title memory a submission may compare page by page where no +/// write-watch journal says what the title wrote +/// (`VICTORY_MERGE_UNWATCHED_MB`, 64; 0: settle as before). In the +/// 2026-11-25 reports every frame settled its fifteen flights for title +/// memory changed under shader writes, 400 ms a frame waiting for the +/// card, while the pages put in were three and the bytes none: the +/// journal could not say, so everything waited. Comparing reads memory at +/// several GB/s: 64 MB is a few milliseconds. +pub(crate) fn merge_unwatched_bytes() -> usize { + static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("VICTORY_MERGE_UNWATCHED_MB") + .ok() + .and_then(|v| v.trim().parse::<usize>().ok()) + .unwrap_or(64) + << 20 + }) +} + +/// `runs` (in order) with those a gap of `gap` bytes or fewer apart made +/// one run, the gap's bytes included. +fn joined_over(runs: Vec<(usize, usize)>, gap: usize) -> Vec<(usize, usize)> { + if gap == 0 || runs.len() < 2 { + return runs; + } + let mut out: Vec<(usize, usize)> = Vec::with_capacity(runs.len()); + for (at, n) in runs { + match out.last_mut() { + Some(last) if at - (last.0 + last.1) <= gap => last.1 = at + n - last.0, + _ => out.push((at, n)), + } + } + out +} + +/// The gap, in bytes, over which the title bytes put into a copy in the +/// card's memory under flights' shader writes are joined into one run +/// (`VICTORY_MERGE_GAP`, 0 to 64; 0 by default: only the bytes the title +/// changed go up, as before). +/// +/// Run 219: the title rewrites some hundred pages of its big buffer a +/// frame while flights that may write that buffer are in the air, and +/// byte by byte the new content differs from the old in 38,000 runs a +/// frame (equal bytes in between, mostly zeros), far over the 512 runs a +/// submission may send, so the flights were settled twice a frame, 50 ms +/// of the submitting thread. Joined over small gaps the same pages are a +/// few runs. +/// +/// What it gives up: a gap byte is equal in title memory and on the CPU +/// side of the copy, and goes up with its run. If a flight in the air +/// wrote exactly that byte on the card (a shader store within `gap` bytes +/// between two bytes the title changed in the same frame), the store is +/// overwritten with the old value, and no compare finds it. Exact (0) is +/// the default for that reason. +fn merge_gap() -> usize { + static GAP: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + *GAP.get_or_init(|| std::env::var("VICTORY_MERGE_GAP").ok().and_then(|v| v.trim().parse::<usize>().ok()).map_or(0, |n| n.min(64))) +} + +/// Whether a refresh of a copy in the card's memory stores and sends on +/// only the bytes that differ from the copy's CPU side +/// (`VICTORY_COPY_CHANGED=1`; `alt`: twenty seconds with, twenty without, +/// in turn, each change said in the log). Off by default. +/// +/// Why: the write watch and the guards say which pages the title wrote +/// to, 4 KiB or 64 KiB at a time, not which bytes changed. A refresh +/// copied every such page into the copy's CPU side and noted all of it +/// for the card: about 78 MB a frame crossed to the card and their 64 KiB +/// pieces were hashed again there (the layer's "sync" lists, 13 to 20 ms +/// of the card a frame), for pages of which the title had changed a few +/// bytes, or had written the same bytes again. The CPU side holds what +/// the card's side holds outside the ranges shaders are writing (which a +/// refresh leaves alone), so bytes that are equal there need not go. +fn copy_changed() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_COPY_CHANGED").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "copies in the card's memory are refreshed by what differs from now (VICTORY_COPY_CHANGED=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// Since the start, with [`copy_changed`]: bytes of title memory read, +/// bytes that went on, their stretches, and the refreshes. +static COPY_CHANGED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// The chunk a refresh by what differs compares at a time +/// ([`changed_chunks`]): whole chunks go on, so that the compare is the +/// machine's compare of two blocks and a refresh makes a few stretches, +/// not forty (run 254: found byte by byte, the stretches cost the +/// submitting thread more than the card gained). A chunk holds at most +/// this many equal bytes beside a changed one: four times the gap the +/// merges under flights join by, which is why this form is not used for +/// ranges a flight's shaders are writing (they never come here: a refresh +/// leaves them alone, and `Shadow::copy_stale` is given whole pages). +const COPY_CHANGED_CHUNK: usize = 256; + +/// The stretches of `now` that differ from `was` (of one length), in +/// whole chunks of `chunk` bytes (the last one shorter), as (offset, +/// bytes) in order, chunks side by side made one stretch. +fn changed_chunks(now: &[u8], was: &[u8], chunk: usize) -> Vec<(usize, usize)> { + let n = now.len().min(was.len()); + let mut out: Vec<(usize, usize)> = Vec::new(); + let mut at = 0; + while at < n { + let len = chunk.min(n - at); + if now[at..at + len] != was[at..at + len] { + match out.last_mut() { + Some(last) if last.0 + last.1 == at => last.1 += len, + _ => out.push((at, len)), + } + } + at += len; + } + out +} + +/// The runs of bytes where `now` differs from `was` (of one length), as +/// (offset, bytes) in order: every differing byte is in a run and no equal +/// byte is. +fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { + if changed_runs_wide_on() { changed_runs_wide(now, was) } else { changed_runs_bytes(now, was) } +} + +/// Which form [`changed_runs`] takes: the wide one unless +/// `VICTORY_CHANGED_RUNS=0` (the walk byte by byte, as before); +/// `VICTORY_CHANGED_RUNS=alt`: twenty seconds wide, twenty byte by byte, in +/// turn, each change said in the log, so that one run measures both in the +/// same scene. Both forms give the same runs for the same bytes (the test +/// `changed_runs_are_the_ones_a_walk_byte_by_byte_finds`). +fn changed_runs_wide_on() -> bool { + /// 0 byte by byte, 1 wide, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_CHANGED_RUNS").as_deref() { + Ok("0") => 0, + Ok("alt") => 2, + _ => 1, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "changed runs are found 64 bytes at a time from now (VICTORY_CHANGED_RUNS=alt): {}", + if on { "ON" } else { "off, byte by byte as before" } + ); + } + on + } + } +} + +/// [`changed_runs`] as it was: equal bytes eight at a time, differing bytes +/// one by one. +fn changed_runs_bytes(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { + let n = now.len().min(was.len()); + let mut runs = Vec::new(); + let mut i = 0; + while i < n { + // Equal bytes, eight at a time while they last. + while i + 8 <= n && now[i..i + 8] == was[i..i + 8] { + i += 8; + } + while i < n && now[i] == was[i] { + i += 1; + } + if i >= n { + break; + } + let first = i; + while i < n && now[i] != was[i] { + i += 1; + } + runs.push((first, i - first)); + } + runs +} + +/// [`changed_runs`] 64 bytes at a time: one mask of the bytes that differ +/// (four 16-byte compares), and the runs read off the masks. Every byte is +/// read once. Timed on 48 MB against the walk (2026-11-25, this PC): all +/// equal 4.3 against 4.3 ms; all differing 4 against 12; one byte in 64 +/// differing 14 against 21; 12 of every 16 differing 24 against 34. (A form +/// that compared 64 equal bytes and then walked eight at a time was slower +/// than the walk in the last two, by a fifth: it never ran in a game.) +#[cfg(target_arch = "x86_64")] +fn changed_runs_wide(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { + use core::arch::x86_64::{__m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8}; + let n = now.len().min(was.len()); + let (now, was) = (&now[..n], &was[..n]); + let mut runs = Vec::with_capacity(64); + // The first byte of a run not yet ended. + let mut open: Option<usize> = None; + let mut base = 0; + while base + 64 <= n { + // Bit `k`: byte `base + k` differs. + let mut differ = 0u64; + for part in 0..4 { + let at = base + 16 * part; + // SAFETY: `at + 16 <= base + 64 <= n`, the length of both + // slices; the loads are unaligned ones. SSE2 is part of x86-64. + let equal = unsafe { + let a = _mm_loadu_si128(now.as_ptr().add(at).cast::<__m128i>()); + let b = _mm_loadu_si128(was.as_ptr().add(at).cast::<__m128i>()); + _mm_movemask_epi8(_mm_cmpeq_epi8(a, b)) as u32 & 0xffff + }; + differ |= u64::from(!equal & 0xffff) << (16 * part); + } + if differ == 0 { + if let Some(first) = open.take() { + runs.push((first, base - first)); + } + } else if differ != u64::MAX || open.is_none() { + let mut at = 0u32; + while at < 64 { + match open { + None => { + // The next byte that differs, if any. + let skip = (differ >> at).trailing_zeros(); + if skip >= 64 - at { + break; + } + at += skip; + open = Some(base + at as usize); + } + Some(first) => { + // The next byte that is equal, if any. + let skip = (!differ >> at).trailing_zeros(); + if skip >= 64 - at { + break; + } + at += skip; + runs.push((first, base + at as usize - first)); + open = None; + } + } + } + } + base += 64; + } + for i in base..n { + match (open, now[i] != was[i]) { + (None, true) => open = Some(i), + (Some(first), false) => { + runs.push((first, i - first)); + open = None; + } + _ => {} + } + } + if let Some(first) = open { + runs.push((first, n - first)); + } + runs +} + +#[cfg(not(target_arch = "x86_64"))] +fn changed_runs_wide(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { + changed_runs_bytes(now, was) +} + +#[cfg(test)] +mod merge_tests { + use super::{PIECE, back_piece, changed_chunks, changed_runs, changed_runs_bytes, changed_runs_wide}; + + #[test] + fn changed_chunks_hold_every_changed_byte() { + let was: Vec<u8> = (0..2000u32).map(|i| (i * 31 + 7) as u8).collect(); + for changes in [vec![], vec![0usize], vec![1999], vec![255, 256], vec![5, 300, 301, 1024, 1990]] { + let mut now = was.clone(); + for &at in &changes { + now[at] ^= 0x5A; + } + for chunk in [1usize, 64, 256, 4096] { + let stretches = changed_chunks(&now, &was, chunk); + let mut put = was.clone(); + for &(at, n) in &stretches { + assert!(at % chunk == 0 && n > 0 && at + n <= now.len()); + put[at..at + n].copy_from_slice(&now[at..at + n]); + } + assert_eq!(put, now, "{changes:?} chunk {chunk}"); + // No stretch without a changed byte in each of its chunks, and none touching the next. + assert!(stretches.windows(2).all(|w| w[0].0 + w[0].1 < w[1].0)); + let chunks: usize = stretches.iter().map(|s| s.1.div_ceil(chunk)).sum(); + let mut changed: Vec<usize> = changes.iter().map(|c| c / chunk).collect(); + changed.dedup(); + assert_eq!(chunks, changed.len(), "{changes:?} chunk {chunk}"); + } + } + assert_eq!(changed_chunks(&[1, 2, 3], &[1, 2, 4], 256), [(0, 3)], "a last chunk shorter than the others"); + } + + #[test] + fn a_piece_put_back_reads_only_its_stretch() { + let old: Vec<u8> = (0..PIECE).map(|i| (i * 7 + i / 251) as u8).collect(); + // The title wrote 7 and 40,000 since the snapshot; the GPU wrote 5, + // 9 and 40,000 (the GPU's byte wins where both wrote). + let mut title_memory = old.clone(); + title_memory[7] ^= 0x11; + title_memory[40_000] ^= 0x22; + let mut host = old.clone(); + for at in [5, 9] { + host[at] ^= 0x33; + } + let gpu = host.clone(); + let mut scratch = Vec::new(); + let (mut mask, mut runs) = (Vec::new(), Vec::new()); + let mut asked = None; + let read = |first: usize, into: &mut [u8]| { + asked = Some((first, into.len())); + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((5, 5))); + assert_eq!(asked, Some((5, 5))); + let mut wanted = title_memory[5..10].to_vec(); + wanted[0] = gpu[5]; + wanted[4] = gpu[9]; + assert_eq!(scratch, wanted); + assert_eq!(host[5..10], wanted); + // Only the GPU's two bytes are written back (upstream #2009). + assert_eq!(runs, [(0, 1), (4, 1)]); + // The copy outside the stretch is left as it was. + assert!(host[..5] == gpu[..5] && host[10..] == gpu[10..]); + assert!(scratch.capacity() < PIECE / 2, "scratch of {} bytes for a stretch of 5", scratch.capacity()); + + // Nothing differs: title memory is not read. + let mut same = old.clone(); + assert_eq!(back_piece(&mut same, &old, &mut scratch, &mut mask, &mut runs, |_, _| unreachable!()), None); + // Title memory not there: nothing to write, the copy unchanged. + let mut host = gpu.clone(); + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, _| false), None); + assert!(host == gpu); + // The GPU wrote what the title holds already: nothing to write. + let mut title_memory = old.clone(); + title_memory[5] = gpu[5]; + title_memory[9] = gpu[9]; + let mut host = gpu.clone(); + let read = |first: usize, into: &mut [u8]| { + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), None); + // A whole piece changed: the scratch grows to it. + let mut host: Vec<u8> = old.iter().map(|b| !b).collect(); + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, into| into.len() == PIECE), Some((0, PIECE))); + assert_eq!(scratch.len(), PIECE); + } + + /// A byte the shader and the title both changed while the GPU ran keeps + /// the title's (the shader computed it from the copy's older data); a + /// byte only the shader changed goes back, and only such bytes are in + /// the runs to write (PalmVIDev e0b70476, upstream #2009). + #[test] + fn a_byte_both_changed_keeps_the_titles_and_only_gpu_bytes_are_written() { + let old = vec![1u8, 2, 3, 4, 5, 6]; + let mut host = old.clone(); + host[1] = 20; // the GPU alone + host[3] = 40; // both + host[4] = 50; // the GPU alone + let mut title_memory = old.clone(); + title_memory[3] = 44; + title_memory[5] = 66; // the title alone + let (mut scratch, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new()); + let read = |first: usize, into: &mut [u8]| { + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((1, 4))); + assert_eq!(scratch, [20, 3, 44, 50], "the title's byte where both changed"); + assert_eq!(host[1..5], [20, 3, 44, 50], "the copy takes the result"); + assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only"); + } + + /// The runs are the ones a walk byte by byte finds, for lengths around + /// the steps of eight and sixty-four the compare takes, and for bytes + /// that differ one here and there, in stretches, and nearly everywhere. + #[test] + fn changed_runs_are_the_ones_a_walk_byte_by_byte_finds() { + let by_bytes = |now: &[u8], was: &[u8]| { + let mut runs: Vec<(usize, usize)> = Vec::new(); + for i in 0..now.len().min(was.len()) { + if now[i] != was[i] { + match runs.last_mut() { + Some(last) if last.0 + last.1 == i => last.1 += 1, + _ => runs.push((i, 1)), + } + } + } + runs + }; + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for case in 0..20_000u32 { + let n = match case % 4 { + 0 => (next() % 20) as usize, + 1 => 56 + (next() % 20) as usize, + 2 => 120 + (next() % 20) as usize, + _ => (next() % 700) as usize, + } + if case % 97 == 0 { 4096 + (next() % 300) as usize } else { 0 }; + let was: Vec<u8> = (0..n).map(|_| next() as u8).collect(); + let mut now = was.clone(); + // One byte in `rarity` differs; some cases also get a stretch + // that differs throughout, and some differ nearly everywhere. + let rarity = [1, 2, 3, 9, 40, 300][(next() % 6) as usize]; + for b in now.iter_mut() { + if next() % rarity == 0 { + *b ^= 1 + (next() % 255) as u8; + } + } + if n > 0 && next() % 3 == 0 { + let from = (next() as usize) % n; + let to = (from + (next() % 90) as usize).min(n); + for b in &mut now[from..to] { + *b = !*b; + } + } + // (A byte may also keep a zero difference inside a stretch.) + assert_eq!(changed_runs_wide(&now, &was), by_bytes(&now, &was), "case {case}, {n} bytes"); + assert_eq!(changed_runs_bytes(&now, &was), by_bytes(&now, &was), "case {case}, {n} bytes (byte by byte)"); + } + // Runs that begin, end and go on at the edges of the 64-byte steps. + for n in [63usize, 64, 65, 127, 128, 129, 191, 192, 193, 256] { + for (from, to) in [(0, n), (0, 64.min(n)), (63.min(n), 65.min(n)), (64.min(n), n), (1, n - 1), (n - 1, n), (0, 1)] { + let was = vec![7u8; n]; + let mut now = was.clone(); + for b in &mut now[from..to] { + *b = 9; + } + assert_eq!(changed_runs_wide(&now, &was), by_bytes(&now, &was), "{n} bytes, {from}..{to}"); + // And the same with every other byte. + let now: Vec<u8> = (0..n).map(|i| if i % 2 == 0 && (from..to).contains(&i) { 9 } else { 7 }).collect(); + assert_eq!(changed_runs_wide(&now, &was), by_bytes(&now, &was), "{n} bytes, every other of {from}..{to}"); + } + } + // Slices of unlike lengths: the shorter one's bytes. + assert_eq!(changed_runs_wide(&[1, 2, 3, 4, 5, 6, 7, 8, 9], &[1, 2, 0]), vec![(2, 1)]); + assert_eq!(changed_runs_bytes(&[1, 2, 3, 4, 5, 6, 7, 8, 9], &[1, 2, 0]), vec![(2, 1)]); + } + + /// The runs hold exactly the bytes that differ: putting them into the + /// old bytes gives the new ones, and no run holds an equal byte. + #[test] + fn changed_runs_are_exactly_the_bytes_that_differ() { + let was: Vec<u8> = (0..300u32).map(|i| (i * 13 + 5) as u8).collect(); + for changes in [vec![], vec![0], vec![299], vec![7, 8, 9], vec![7, 9], vec![15, 16, 17, 23, 24, 64, 65, 66, 67, 68, 69, 70, 71, 72, 298, 299]] { + let mut now = was.clone(); + for &at in &changes { + now[at] ^= 0x41; + } + let runs = changed_runs(&now, &was); + let mut put = was.clone(); + let mut held = Vec::new(); + for &(at, n) in &runs { + assert!(n > 0); + put[at..at + n].copy_from_slice(&now[at..at + n]); + held.extend(at..at + n); + } + assert_eq!(put, now, "{changes:?}"); + assert_eq!(held, changes, "{changes:?}"); + // Runs do not touch: two that did would be one. + assert!(runs.windows(2).all(|w| w[0].0 + w[0].1 < w[1].0), "{changes:?}"); + } + assert!(changed_runs(&[], &[]).is_empty()); + } +} + +/// Host copies alive (also those only a list, a descriptor pass or a +/// snapshot still holds) and the bytes of title memory they copy. +static LIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +impl Drop for Shadow { + fn drop(&mut self) { + if self.place.is_some() { + // Never counted with the copies (`Shadow::placed`). + crate::inplace::gone(self.window, self.len); + return; + } + LIVE[0].fetch_sub(1, Ordering::Relaxed); + LIVE[1].fetch_sub(self.len, Ordering::Relaxed); + if self.kept.get_mut().unwrap_or_else(|e| e.into_inner()).1 { + KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } + let window = self.window; + if window && self.uploaded == 0 && self.card.is_none() { + WINDOW_PC_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } + if self.uploaded != 0 { + // (Counted where `window_upload_for` counted it.) + if window_bar_most() > 0 { + WINDOW_BAR_BYTES.fetch_sub(self.uploaded, Ordering::Relaxed); + } else { + WINDOW_CARD_BYTES.fetch_sub(self.uploaded, Ordering::Relaxed); + } + } + if let Some(card) = &mut self.card { + if window { + WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed); + } else if card.in_pc { + PC_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed); + } else { + CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed); + } + if card.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() { + CARD_BYTES[1].fetch_sub(card_hash_bytes(card.size), Ordering::Relaxed); + } + } + } +} + +/// Whether a copy's snapshot is kept from one submission to the next and +/// only the pieces that changed in between are taken again +/// (`VICTORY_KEEP_SNAPSHOTS=1`; off by default). +/// +/// A snapshot is the copy's bytes before a submission, to find what its +/// shaders wrote. Taken anew for every submission it is 1,050 MB of copying +/// a frame (72-86 ms in gameplay, runs 61 and 62) for buffers of which +/// 100 MB changed. Kept, a piece of it is taken again only after something +/// changed the copy there: a refresh from title memory ([`Shadow::copy`]), +/// shader writes found after a submission, or the bytes put back then +/// ([`Shadow::copy_back`]). +/// +/// What it assumes, and why it is not on by default: that nothing else +/// writes a copy. A shader that writes a buffer through a view we did not +/// declare as written (we declare the unordered-access views of shaders +/// that can store) changes the copy unseen; with a fresh snapshot that +/// write is simply never put back, with a kept one it would be taken for a +/// write of a later submission and put back then, over whatever the title +/// wrote there since. +fn keeps() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_SNAPSHOTS").is_some_and(|v| v == "1")) +} + +/// Bytes of the snapshots kept, and the most that may be. +static KEPT_BYTES: AtomicU64 = AtomicU64::new(0); +/// `VICTORY_KEEP_SNAPSHOTS_MB`, 256 unless set (it was 768: run 80, with +/// kept snapshots beside copies in the card's memory, ran the PC out of +/// memory in 27 s; kept snapshots are the PC's memory, all of it resident). +fn kept_most() -> u64 { + static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_KEEP_SNAPSHOTS_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(256) << 20 + }) +} + +/// The 64 KiB pieces, cut at multiples of 64 KiB of title memory, that +/// hold offsets `[from, to)` of a copy of memory from `start` on +/// (`from < to`); piece 0 holds offset 0. +fn pieces_of(start: usize, from: usize, to: usize) -> std::ops::Range<usize> { + let first = start / PIECE; + (start + from) / PIECE - first..(start + to - 1) / PIECE - first + 1 +} + +/// The offsets that piece `piece` holds of a copy of `len` bytes of memory +/// from `start` on. +fn piece_at(start: usize, len: usize, piece: usize) -> (usize, usize) { + let first = start / PIECE; + let lo = ((first + piece) * PIECE).saturating_sub(start); + let hi = ((first + piece + 1) * PIECE - start).min(len); + (lo, hi) +} + +#[cfg(test)] +mod piece_tests { + use super::{PIECE, piece_at, pieces_of}; + + /// The pieces cover a copy without gaps, each cut where the compare + /// cuts (at multiples of 64 KiB of title memory). + #[test] + fn pieces_cover_the_copy_as_the_compare_cuts_it() { + for start in [0usize, 1, 4096, PIECE - 1, PIECE, PIECE + 77, 5 * PIECE + 12345] { + for len in [1usize, 100, PIECE - 1, PIECE, PIECE + 1, 3 * PIECE + 500] { + let count = pieces_of(start, 0, len).end; + let mut at = 0; + for piece in 0..count { + let (lo, hi) = piece_at(start, len, piece); + assert_eq!(lo, at, "{start} {len} {piece}"); + // As `Shadow::differing` cuts: to the next multiple. + let n = (PIECE - (start + at) % PIECE).min(len - at); + assert_eq!(hi, at + n, "{start} {len} {piece}"); + assert_eq!(pieces_of(start, lo, hi), piece..piece + 1); + assert_eq!(pieces_of(start, hi - 1, hi), piece..piece + 1); + at = hi; + } + assert_eq!(at, len, "{start} {len}"); + assert_eq!(pieces_of(start, 0, len), 0..count); + } + } + } +} + +/// The pages of `[a, e)` (title addresses, `a < e`) that a copy whose +/// first page is `base` must take from title memory before it holds the +/// title's bytes: those it never took (`copied` 0), whether or not the +/// title wrote them since tracking began, and those `written` (as +/// `crate::watch::writes` gives it, by page in order) shows written after +/// the copy took them. As [`Shadow::copy_stale`] decides it. +/// +/// [`Shadow::stale_under_writes`] and [`Shadow::merge_under_writes`] looked +/// at `written` alone, so a page of a range shaders may be writing that the +/// copy never took, and the title had not written lately, was neither +/// merged nor a reason to settle; the refresh leaves such ranges alone, and +/// shaders read zeros there (fxceless/victory-fork#206: missing geometry +/// with `VICTORY_LATE_WAIT`/`VICTORY_RELAY`). +fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec<usize> { + (a / PAGE..e.div_ceil(PAGE)) + .filter(|&page| page >= base) + .filter(|&page| match copied.get(page - base) { + None => false, + Some(0) => true, + Some(&at) => written + .binary_search_by_key(&page, |&(p, _)| p) + .is_ok_and(|i| written[i].1 > at), + }) + .collect() +} + +#[cfg(test)] +mod stale_tests { + use super::*; + + #[test] + fn pages_never_taken_are_stale_written_or_not() { + let base = 0x100; + let copied = [5, 0, 5, 5]; + let at = |page: usize| page * PAGE; + // Page 0x101 was never taken; page 0x102 was written after it was + // taken, page 0x103 before. + let written = [(0x102, 6), (0x103, 4)]; + assert_eq!(stale_pages_in(base, &copied, at(0x100), at(0x104), &written), [0x101, 0x102]); + // Part of a page counts as the page; pages outside the copy do not. + assert_eq!(stale_pages_in(base, &copied, at(0x101) + 8, at(0x101) + 16, &[]), [0x101]); + assert!(stale_pages_in(base, &copied, at(0x104), at(0x106), &[(0x104, 9)]).is_empty()); + } +} + +/// Copies of windows outside buffers let go since the start, and their +/// bytes. +static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// For the memory line: the windows let go since the start and their +/// bytes, and of the bytes of the windows alive, how many lie between the +/// lowest and the highest address ever asked for in each. +#[cfg(feature = "diagnostics")] +pub(crate) fn windows() -> [u64; 3] { + let asked: u64 = { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + loose + .values() + .map(|s| { + let low = s.asked[0].load(Ordering::Relaxed); + let high = s.asked[1].load(Ordering::Relaxed); + high.saturating_sub(low) + }) + .sum() }; - v.clear(); - v + [LET_GO[0].load(Ordering::Relaxed), LET_GO[1].load(Ordering::Relaxed), asked] } -/// Returns a snapshot buffer to the pool (at most 8 kept, the largest). -fn give_back(v: Vec<u8>) { - let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); - pool.push(v); - if pool.len() > 8 { - pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); - pool.truncate(8); +/// For the memory line, of the windows alive: the bytes of their pages +/// ever copied from title memory (the rest of each window is memory the +/// host zeroed and nothing read: what a window made no bigger than what is +/// read would not hold); the windows a descriptor slot shows and their +/// bytes (they stay until the title writes the slot again); the windows a +/// list or a pass over the heap holds and their bytes; the windows asked +/// for without a length (root views, which keep the 4 MiB grid) and their +/// bytes; and the window grid in bytes ([`window`]). +#[cfg(feature = "diagnostics")] +pub(crate) fn window_use() -> [u64; 8] { + let mut out = [0u64; 8]; + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + for s in loose.values() { + let copied = s.copied.lock().unwrap_or_else(|e| e.into_inner()); + let pages = copied.iter().filter(|&&at| at != 0).count() as u64; + out[0] += (pages * PAGE as u64).min(s.len); + if crate::host::references(&s.buffer) > 1 { + out[1] += 1; + out[2] += s.len; + } + if Arc::strong_count(s) > 1 { + out[3] += 1; + out[4] += s.len; + } + if s.unsized_asks.load(Ordering::Relaxed) > 0 { + out[5] += 1; + out[6] += s.len; + } } + out[7] = window(); + out } -const NOT_WATCHED: u8 = 2; +/// Lets go of the copies of windows outside buffers that nothing names any +/// more. They were never freed, and the world's streaming keeps asking for +/// new ones: 648 windows (2.8 GB) when the cutscene began, 974 (4.3 GB) +/// eight minutes later (run 24). A window goes when +/// - only the table of windows holds its copy: no list not yet reset reads +/// or writes it, no pass over the heap keeps its range, no submission is +/// comparing it; +/// - only the copy holds its host buffer: no descriptor slot views it (a +/// slot keeps the buffer it views, `HostHeap::kept`), so no draw can read +/// it through a slot made earlier; +/// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames. +/// +/// The next read of that memory makes a new copy and copies the window +/// again. Called before a submission starts, by the thread that submits. +pub(crate) fn let_go_idle() { + const IDLE_FRAMES: u64 = 4; + let gone: Vec<Arc<Shadow>> = { + // Held from the look to the removal: `loose` hands a copy out + // under the same lock, so none is handed out in between. + let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + if map.is_empty() { + return; + } + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()).min(crate::pressure::idle_cap_ms(false)); + let idle = |s: &Arc<Shadow>| { + Arc::strong_count(s) == 1 + && crate::host::long_ago(s.used.load(Ordering::Relaxed), idle_ms, IDLE_FRAMES) + && crate::host::references(&s.buffer) == 1 + }; + let keys: Vec<(u64, u64)> = map.iter().filter(|(_, s)| idle(s)).map(|(key, _)| *key).collect(); + // Counted before they leave the table, with its lock held, and + // each looked at AGAIN after the count ([`TABLES_CHANGED`]): a + // thread that took one from its own memory of asks before the + // count moved holds it by now, and it stays. + if !keys.is_empty() { + tables_changed(); + } + let mut gone = Vec::new(); + for key in keys { + if map.get(&key).is_some_and(&idle) { + gone.extend(map.remove(&key)); + } + } + gone + }; + if !gone.is_empty() { + let (went, bytes) = (gone.len(), gone.iter().map(|s| s.len).sum::<u64>()); + crate::host::trail(|| { + format!("sweep: {went} host copies of windows of title memory let go ({} KiB), held by no list and no slot", bytes >> 10) + }); + } + for shadow in gone { + LET_GO[0].fetch_add(1, Ordering::Relaxed); + LET_GO[1].fetch_add(shadow.len, Ordering::Relaxed); + // Nothing runs now and nothing names it: freed at once unless a + // submission is running after all. + crate::host::retire(shadow); + } +} + +/// For the memory line: host copies alive and their bytes, of them the +/// windows of memory outside buffers and their bytes, and the snapshot +/// buffers kept for reuse and the bytes they reserve. +#[cfg(feature = "diagnostics")] +pub(crate) fn memory() -> [u64; 6] { + let (windows, window_bytes) = { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + // Each copy once: a window may stand under several keys. + let mut seen = std::collections::HashSet::new(); + let bytes: u64 = loose + .values() + .filter(|s| seen.insert(Arc::as_ptr(s) as usize)) + .map(|s| s.len) + .sum(); + (seen.len() as u64, bytes) + }; + let (kept, kept_bytes) = { + let pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + (pool.len() as u64, pool.iter().map(|v| v.capacity() as u64).sum::<u64>()) + }; + [ + LIVE[0].load(Ordering::Relaxed), + LIVE[1].load(Ordering::Relaxed), + windows, + window_bytes, + kept, + kept_bytes, + ] +} // SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping // written only on the submitting thread. @@ -133,14 +3162,65 @@ impl Shadow { self.gpu + (address - self.start) } + /// The title memory the copy is of: its start and length. + pub(crate) fn span(&self) -> (u64, u64) { + (self.start, self.len) + } + + /// The offset of a title address in the copy, if it lies in it. + pub(crate) fn offset_in(&self, address: u64) -> Option<u64> { + address.checked_sub(self.start).filter(|&at| at < self.len) + } + /// Bytes from a title address to the buffer's end. pub(crate) fn left(&self, address: u64) -> u64 { (self.start + self.len).saturating_sub(address) } + /// Whether the memory behind the copy turned out not to be write-watched: + /// every refresh then copies its whole range. + pub(crate) fn unwatched(&self) -> bool { + self.watched.load(Ordering::Relaxed) == NOT_WATCHED + } + + /// The copy's own number (see the field). + pub(crate) fn id(&self) -> u64 { + self.id + } + /// Offset of a title address from the buffer's start. pub(crate) fn offset(&self, address: u64) -> u64 { - address - self.start + address - self.start + self.place.as_ref().map_or(0, |place| place.1) + } + + /// The GPU buffer and the offset in it of `[address, address + len)`, + /// when all of it is inside the copy: what a copy on the host GPU names + /// (pablogonz12/Scarlight #86). The buffer is the one shaders read and + /// write: the placed resource of memory in place, the card's side of a + /// copy in the card's memory, the copy itself otherwise. + pub(crate) fn gpu_range(&self, address: usize, len: usize) -> Option<(ID3D12Resource, u64)> { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + if len == 0 || address < start || address.checked_add(len)? > end { + return None; + } + Some((self.buffer.clone(), self.offset(address as u64))) + } + + /// Title memory `[start, start + len)` in place: `placed` is a buffer + /// over it in a heap opened on it. Shaped as a copy so that everything + /// that binds, views or keeps a copy works on it unchanged; what + /// copies does nothing ([`Shadow::update`], [`Shadow::gpu_writes`]). + fn placed(placed: crate::inplace::Placed, start: u64, len: u64, window: bool) -> Shadow { + crate::host::name(&placed.buffer, || format!("title memory {start:#x}+{len:#x} in place")); + let mut shadow = Shadow::new(placed.buffer, start as *mut u8, placed.gpu, start, len); + // Not a copy: not counted with them, and nothing asks what the + // title wrote there. + LIVE[0].fetch_sub(1, Ordering::Relaxed); + LIVE[1].fetch_sub(len, Ordering::Relaxed); + *shadow.watched.get_mut() = NOT_WATCHED; + shadow.window = window; + shadow.place = Some((placed.heap, placed.bias)); + shadow } /// Brings `len` bytes at `address` up to date when `list` is submitted, @@ -152,6 +3232,8 @@ impl Shadow { fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow { let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64; + LIVE[0].fetch_add(1, Ordering::Relaxed); + LIVE[1].fetch_add(len, Ordering::Relaxed); Shadow { buffer, data, @@ -161,7 +3243,21 @@ impl Shadow { copied: Mutex::new(vec![0; pages as usize]), watched: AtomicU8::new(0), pending: Mutex::default(), + flights: Mutex::default(), before: Mutex::default(), + kept: Mutex::default(), + used: AtomicU64::new(crate::host::moment()), + asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)], + unsized_asks: AtomicU64::new(0), + id: { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) + }, + card: None, + window: false, + title_in: AtomicU64::new(0), + uploaded: 0, + place: None, } } @@ -182,48 +3278,130 @@ impl Shadow { /// before the submission (a copy per declared range and submission); /// a GPU-side dirty mask would save that if big ranges make it slow. pub(crate) fn gpu_writes(self: &Arc<Self>, list: &HostList, address: u64, len: u64) { + // The list's prelude takes no record of this copy from here on + // (`crate::indirect::gather_by_copy`); a copy in place is written + // by the shaders as any other. + list.gather_wrote(self.id); + // In place the shaders write title memory itself: no snapshot, no + // compare, nothing to copy back, and no wait on its account. + // shortcut: another host copy of the same bytes (a title buffer + // inside this one with a copy of its own, a texture in it) is not + // told: the card's writes are not seen by write watching. + if self.place.is_some() { + return; + } let len = len.min(self.left(address)); list.defer_gpu_write(self, address as usize, len as usize); } /// At submission, after the range's refresh: a submitted list's shaders /// write this range. Its bytes are kept to tell later what the GPU wrote: - /// one snapshot per copy and submission, grown to cover every range the - /// submission declares (the world declares overlapping views of its - /// 174 MB heap dozens of times), in reused memory (fresh snapshots cost - /// ~2.3 million page faults per world frame). + /// one snapshot per copy and submission, each byte taken once, when the + /// first range holding it is declared (the world declares overlapping + /// views of its 174 MB heap dozens of times, from different offsets: a + /// snapshot grown to cover each was copied whole every time), in reused + /// memory (fresh snapshots cost ~2.3 million page faults per world + /// frame). pub(crate) fn writing(&self, address: usize, len: usize) { - self.pending - .lock() - .unwrap_or_else(|e| e.into_inner()) - .push((address, address + len)); - let (from, to) = self.inside(address, len); - // SAFETY: inside the mapping. - let host = - |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; + if self.place.is_some() { + return; + } + let range = (address, address + len); + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + // With the copy-back on its own thread: counted for this submission + // (once), whether or not an earlier one still holds the range. + if relay() { + self.flights.lock().unwrap_or_else(|e| e.into_inner()).declare(range, PREPARED.load(Ordering::Relaxed)); + } + // Dispatches declare the same ranges thousands of times. + if pending.contains(&range) { + return; + } + // In the card's memory: no snapshot. What shaders wrote is found on + // the card (`Host::card_before` reads the declared ranges from the + // lists). + if self.card.is_some() { + pending.push(range); + return; + } + // The parts no declared range holds yet: their bytes are taken now, + // just after the range's refresh (a part declared earlier has not + // been refreshed since, and keeps the bytes taken then). + let mut parts = vec![self.inside(address, len)]; + for &(a, e) in pending.iter() { + let (a, e) = self.inside(a, e - a); + let mut rest = Vec::with_capacity(parts.len() + 1); + for (from, to) in parts { + if e <= from || a >= to { + rest.push((from, to)); + continue; + } + if from < a { + rest.push((from, a)); + } + if e < to { + rest.push((e, to)); + } + } + parts = rest; + } + pending.push(range); + let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum(); + BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed); + let total = self.len as usize; let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let before = &mut before.snapshot; - let (start, end) = match &*before { - Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)), - None => (from, to), - }; - if let Some((at, bytes)) = &*before - && (*at, at + bytes.len()) == (start, end) - { + let snapshot = before.get_or_insert_with(|| pooled(total)); + if keeps() { + // Piece by piece, and only the pieces not known current. A + // piece the part holds whole is current from now on; of a + // piece it holds partly only the part's bytes are taken, as + // without the switch, and it is taken again next time (the + // rest of it may belong to a range declared earlier, whose + // bytes stay as they were taken). + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if kept.0.is_empty() { + kept.0 = vec![false; self.pieces(0, total.max(1)).end]; + } + for (from, to) in parts { + if from >= to { + continue; + } + for piece in self.pieces(from, to) { + if kept.0[piece] { + continue; + } + let (lo, hi) = self.piece(piece); + let whole = from <= lo && hi <= to; + let (lo, hi) = (lo.max(from), hi.min(to)); + // SAFETY: as below; `hi <= total`. + unsafe { + std::ptr::copy_nonoverlapping(self.data.add(lo), snapshot.as_mut_ptr().add(lo), hi - lo); + } + kept.0[piece] = whole; + } + } + return; + } + if wide_back() { + // Noted, and taken with the submission's other snapshots when + // its refreshes are done (`take_snapshots`): the range is + // declared from here on, so nothing changes its bytes before + // then. The snapshot's memory stays where it is until the + // range is done with (`copy_back_done`). + let mut snaps = SNAPS.lock().unwrap_or_else(|e| e.into_inner()); + let (data, snapshot) = (self.data as usize, snapshot.as_mut_ptr() as usize); + snaps.extend(parts.into_iter().filter(|&(from, to)| from < to).map(|(from, to)| (data + from, snapshot + from, to - from))); return; } - // Parts newly covered from the copy, the rest as it was taken. - let mut grown = pooled(end - start); - match before.take() { - Some((at, bytes)) => { - grown.extend_from_slice(host(start, at)); - grown.extend_from_slice(&bytes); - grown.extend_from_slice(host(at + bytes.len(), end)); - give_back(bytes); + for (from, to) in parts { + if from < to { + // SAFETY: the copy's mapping and the snapshot's allocation + // (`pooled`) both hold `total` bytes, and `to <= total`. + unsafe { + copy_wide(self.data.add(from), snapshot.as_mut_ptr().add(from), to - from); + } } - None => grown.extend_from_slice(host(start, end)), } - *before = Some((start, grown)); } /// After the submission ran: copies the bytes its shaders wrote back @@ -232,92 +3410,612 @@ impl Shadow { /// command memory shares the big GPU heap with what shaders write), and /// putting back the copy's older bytes there broke the title's own /// records (a fence list read as -1, title+0x4e9b54a). Returns the bytes - /// written. + /// written. The range must lie in ranges declared with + /// [`Shadow::writing`] and not yet done: `Host::execute` passes the + /// union of a submission's ranges, each byte once, then calls + /// [`Shadow::copy_back_done`]. pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize { - let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let Before { - snapshot, - unchanged, - } = &mut *before; + self.copy_back_with(address, len, None) + } + + /// [`Shadow::copy_back`]; `found`, if given, is the pieces of the range + /// that differ from the snapshot, found beforehand ([`find_all`]). + pub(crate) fn copy_back_with(&self, address: usize, len: usize, found: Option<Vec<(usize, usize)>>) -> usize { + if self.place.is_some() { + return 0; + } + let snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); let mut written = 0; let (from, to) = self.inside(address, len); let start = self.start as usize; - if let Some((taken, before)) = &*snapshot - && *taken <= from - && to <= taken + before.len() + self.compared(from, to); + if let Some(before) = &*snapshot && from < to { - unchanged.begin(start + taken, start + taken + before.len()); - let before = &before[from - taken..to - taken]; + // SAFETY: `writing` set the snapshot's bytes of every declared + // range, at the copy's offsets. + let before = unsafe { std::slice::from_raw_parts(before.as_ptr().add(from), to - from) }; // By 64 KiB piece: the copy compared with its bytes before the - // submission, title memory read only where the GPU wrote. - // An unchanged page is never modified by copy-back, so later - // overlapping ranges can skip it for the rest of the submission. - let mut title = None; - let mut synced = Vec::new(); - let mut at = from; - while at < to { - let n = (PAGE - (start + at) % PAGE).min(to - at); + // submission (on several threads: gigabytes a frame, bound by + // memory speed), title memory read only where the GPU wrote. + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + let differing = match found { + Some(found) => found, + None => self.differing(from, to, before), + }; + #[cfg(feature = "diagnostics")] + let syncing = { + use crate::copystat::{C, add}; + add(C::BackScanUs, scanning.elapsed().as_micros() as u64); + add(C::BackDiffer, differing.len() as u64); + std::time::Instant::now() + }; + // Where the copy changes (the GPU wrote, and below the title's + // bytes come in), a kept snapshot is no longer current. + for &(at, n) in &differing { + self.changed(at, at + n); + } + // Sized to each stretch read (`back_piece`): a zeroed 64 KiB per + // range, most of whose ranges differ nowhere, was most of the + // work for small ranges. + let (mut title, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new()); + for (at, n) in differing { // SAFETY: inside the mapping; only the submitting thread // writes it. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; let old = &before[at - from..at - from + n]; - if unchanged.differs(start + at, host, old) - && let title = &mut title.get_or_insert_with(|| vec![0u8; PAGE])[..n] - && crate::host::read_into((start + at) as *const u8, title) - { - // Title memory with the GPU's bytes put in; the copy - // takes the title's bytes in turn. - let mut changed = false; - for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) { - if *h != *o && *t != *h { - *t = *h; - changed = true; + let read = |first: usize, title: &mut [u8]| crate::host::read_into((start + at + first) as *const u8, title); + let Some((first, n)) = back_piece(host, old, &mut title, &mut mask, &mut runs, read) else { + continue; + }; + let at = at + first; + crate::host::shaders_write(start + at, &title[..n.min(title.len())]); + crate::watch::writing(start + at, n); + // Only the GPU's bytes (upstream #2009): the rest of the + // stretch is the title's as read, and a title write landing + // there since stays. + for &(off, len) in &runs { + crate::host::write_mapped((start + at + off) as *mut u8, title[off..].as_ptr(), len); + written += len; + } + } + // Our write shows as a title write at the copy's next refresh, + // which copies those pages once more (some dozens of MB a + // frame). Asking about the whole range here, to note them + // current, cost more: 19-31 askings a frame over 110-174 MB of + // view memory, each a walk of its guards. + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackSyncUs, syncing.elapsed().as_micros() as u64); + } + written + } + + /// Offsets `[from, to)` of the copy are compared with the snapshot: for + /// the frame line's counts. + fn compared(&self, from: usize, to: usize) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackCompared, (to - from) as u64); + let (bytes, ranges) = if self.window { (2, 5) } else { (3, 6) }; + BACK_CLASS[bytes].fetch_add((to - from) as u64, Ordering::Relaxed); + BACK_CLASS[ranges].fetch_add(1, Ordering::Relaxed); + if !self.window && self.len >= 1 << 20 { + BACK_CLASS[4].fetch_add((to - from) as u64, Ordering::Relaxed); + } + } + + /// [`relay`]: the declared range `[address, address + len)` of a copy + /// in the PC's memory is about to be looked through + /// (`crate::shadow::find_all`) by the thread that settles: counted as + /// [`Shadow::copy_back_with`] counts it. + pub(crate) fn relay_compared(&self, address: usize, len: usize) { + let (from, to) = self.inside(address, len); + self.compared(from, to); + } + + /// [`relay`], for a copy in the PC's memory: offsets `[at, at + n)` + /// are a 64 KiB piece of a declared range that differed from the + /// snapshot when it was looked through. What the card wrote there + /// since the snapshot was last brought up goes into title memory, from + /// the first to the last such byte, and into the snapshot, so that the + /// next flight's merge finds only what the card writes from now on. + /// The copy is read once and never written: a later flight's shaders + /// may be writing it at this moment. Under the snapshot's lock, which + /// [`Shadow::merge_under_writes`] holds while it reads title memory + /// and puts the title's bytes into the copy and the snapshot: the two + /// never see each other half done. `now` and `title` are scratch + /// memory. Returns the bytes written to title memory. + pub(crate) fn relay_merge(&self, at: usize, n: usize, now: &mut Vec<u8>, title: &mut Vec<u8>) -> usize { + let start = self.start as usize; + if self.card.is_some() || n == 0 || at + n > self.len as usize { + return 0; + } + let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let Some(before) = snapshot.as_mut() else { + return 0; + }; + now.clear(); + now.reserve(n); + // SAFETY: inside the copy's mapping (checked above), read into + // room just reserved; the card may write the mapping meanwhile, and + // each byte read is one it held at some moment. + unsafe { + std::ptr::copy_nonoverlapping(self.data.add(at), now.as_mut_ptr(), n); + now.set_len(n); + } + // SAFETY: the snapshot's allocation holds the copy's length + // (`writing`), and these offsets are in a range declared and not + // done with, whose bytes it holds; nothing else touches them + // without the lock held here. + let held = unsafe { std::slice::from_raw_parts_mut(before.as_mut_ptr().add(at), n) }; + let Some(first) = first_difference(now, held) else { + return 0; + }; + let last = last_difference(now, held).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (now, held) = (&now[first..=last], &mut held[first..=last]); + title.clear(); + title.resize(n, 0); + // Who touched the page since its last store is looked at before our + // own read of it (`VICTORY_BACK_READS`): counted only. + #[cfg(feature = "diagnostics")] + let _reads_as = crate::backreads::reading_as(crate::backreads::MERGE, self.id); + #[cfg(feature = "diagnostics")] + crate::backreads::before(start + at); + // Title memory not there: looked at again when the next flight + // that declared the range lands (the snapshot stays as it is). + if !crate::host::read_into((start + at) as *const u8, title) { + return 0; + } + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = merge_race_on().then(|| title.clone()); + if !merge_piece(now, held, title) { + return 0; + } + crate::host::shaders_write(start + at, &title[..]); + if self.put_back_own(start + at, &title[..]) { + #[cfg(feature = "diagnostics")] + crate::backreads::stored(self.id, (self.start, self.len), start + at, n, true); + return n; + } + crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "pc relay"); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + #[cfg(feature = "diagnostics")] + crate::backreads::stored(self.id, (self.start, self.len), start + at, n, false); + n + } + + /// With `crate::inplace::back_own` (`VICTORY_BACK_OWN_VIEW=1`): stores + /// what a merge made of title memory `[at, at + bytes.len())` (inside + /// one 64 KiB page, as every merged stretch is) through a view of our + /// own, tells the journal, and notes the page current for this copy if + /// it was current before: the copy holds the same bytes (the merge put + /// them into both), so the next refresh need not take the page again. + /// The guards are not touched: a title write to the page still faults + /// and is reported at a later asking, which every copy then takes, + /// this one too. False with nothing done if the switch is off or the + /// memory cannot be written that way (the caller writes as before). + fn put_back_own(&self, at: usize, bytes: &[u8]) -> bool { + /// Since the start: stretches and bytes stored this way, pages + /// noted current for their copy, stretches written the old way; + /// and with `VICTORY_BACK_OWN_CHECK=1`: stores the title's own + /// address did not show afterwards, pages noted current whose + /// CPU side in the copy differs from title memory, and those of + /// them whose guard was clean (a hole in the rule: a title write + /// on its way leaves the guard open). + static OWN_WRITES: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + static CHECK: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let check = *CHECK.get_or_init(|| std::env::var_os("VICTORY_BACK_OWN_CHECK").is_some_and(|v| v == "1")); + if !crate::inplace::back_own() { + return false; + } + let Some(shown) = crate::inplace::write_own(at, bytes) else { + OWN_WRITES[3].fetch_add(1, Ordering::Relaxed); + return false; + }; + if check { + // The title's own address must show what went in through ours. + let mut back = vec![0u8; bytes.len()]; + if crate::host::read_into(at as *const u8, &mut back) && back != bytes { + OWN_WRITES[4].fetch_add(1, Ordering::Relaxed); + } + } + let page = at / PAGE; + let others: Vec<usize> = shown.iter().map(|&a| a / PAGE).filter(|&p| p != page).collect(); + let (before, now) = crate::watch::wrote_own(page, &others); + // A placed texture there changed with no descriptor written (what + // `crate::watch::writing` tells the texture table on the old way). + crate::descriptor::host::remapped(at, bytes.len()); + let base = self.start as usize / PAGE; + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(taken) = page.checked_sub(base).and_then(|i| copied.get_mut(i)) + && *taken != 0 + && *taken >= before + { + *taken = (*taken).max(now); + OWN_WRITES[2].fetch_add(1, Ordering::Relaxed); + // A copy in the card's memory only: its CPU side is never + // written by the card, so it must equal title memory now. + if check && self.card.is_some() { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (lo, hi) = ((page * PAGE).max(start), ((page + 1) * PAGE).min(end)); + if lo < hi { + let mut title = vec![0u8; hi - lo]; + // SAFETY: inside the copy's mapping; read only. + let held = unsafe { std::slice::from_raw_parts(self.data.add(lo - start).cast_const(), hi - lo) }; + if crate::host::read_into(lo as *const u8, &mut title) && title != held { + OWN_WRITES[5].fetch_add(1, Ordering::Relaxed); + if crate::watch::clean(page) { + OWN_WRITES[6].fetch_add(1, Ordering::Relaxed); + } } - *h = *t; - } - if changed { - crate::watch::writing(start + at, n); - crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); - written += n; } - synced.push((start + at) / PAGE); } - at += n; } - // Pages made equal to title memory are current in the copy, so - // our own write is not taken for the title's; others keep what - // they had (a title write there shows at the next refresh). - let (first, last) = ((start + from).div_ceil(PAGE), (start + to) / PAGE); - if first < last - && !synced.is_empty() - && self.watched.load(Ordering::Relaxed) != NOT_WATCHED - && let Some((now, _)) = crate::watch::writes(first * PAGE, last * PAGE, true) - { - let base = start / PAGE; - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - for page in synced.into_iter().filter(|p| (first..last).contains(p)) { - copied[page - base] = now; + } + OWN_WRITES[1].fetch_add(bytes.len() as u64, Ordering::Relaxed); + let n = OWN_WRITES[0].fetch_add(1, Ordering::Relaxed) + 1; + if n.is_multiple_of(16384) { + tracing::info!( + "what shaders wrote, stored through views of our own (VICTORY_BACK_OWN_VIEW=1), since the start: {n} stretches {} MB, {} pages noted current for the copy that wrote them (not copied in again), {} stretches written the old way; with VICTORY_BACK_OWN_CHECK=1: {} stores the title's address did not show, {} pages noted current whose CPU side differs from title memory, {} of those with the guard clean", + OWN_WRITES[1].load(Ordering::Relaxed) >> 20, + OWN_WRITES[2].load(Ordering::Relaxed), + OWN_WRITES[3].load(Ordering::Relaxed), + OWN_WRITES[4].load(Ordering::Relaxed), + OWN_WRITES[5].load(Ordering::Relaxed), + OWN_WRITES[6].load(Ordering::Relaxed) + ); + } + true + } + + /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory) of + /// `[from, to)` of the copy that differ from `before` (the bytes from + /// `from` on), as (offset, bytes) in order; compared on several threads + /// when the range is big. + fn differing(&self, from: usize, to: usize, before: &[u8]) -> Vec<(usize, usize)> { + let (start, data) = (self.start as usize, self.data as usize); + let scan = |a: usize, b: usize| -> Vec<(usize, usize)> { + let mut found = Vec::new(); + let mut at = a; + while at < b { + let n = (PIECE - (start + at) % PIECE).min(b - at); + // SAFETY: inside the mapping, which nothing writes while a + // submission's results are compared. + let host = unsafe { std::slice::from_raw_parts((data + at) as *const u8, n) }; + if host != &before[at - from..at - from + n] { + found.push((at, n)); } + at += n; + } + found + }; + const PER_THREAD: usize = 16 << 20; + let threads = ((to - from) / PER_THREAD).clamp(1, 8); + if threads == 1 { + return scan(from, to); + } + // Cut on piece boundaries, so that every thread sees whole pieces. + let cut = |i: usize| { + if i == threads { + return to; } + let at = from + (to - from) / threads * i; + (at - (start + at) % PIECE).max(from) + }; + let scan = &scan; + std::thread::scope(|s| { + let parts: Vec<_> = (0..threads) + .map(|i| { + let (a, b) = (cut(i), cut(i + 1)); + s.spawn(move || scan(a, b)) + }) + .collect(); + parts + .into_iter() + .flat_map(|part| match part.join() { + Ok(found) => found, + Err(panic) => std::panic::resume_unwind(panic), + }) + .collect() + }) + } + + /// After [`Shadow::copy_back`] of a submission's ranges: every submitted + /// step that declared one of `ranges` (`(address, end)`, as declared) is + /// done with it (one submission runs at a time), and the snapshot with + /// the last range. + /// + /// With [`relay`] several submissions may hold a range: `ranges` are + /// those of one of them (each once), and a range is done with when the + /// last submission that declared it is ([`Flights`]). + pub(crate) fn copy_back_done(&self, ranges: &[(usize, usize)]) { + if self.place.is_some() { + return; } - // Every submitted step that declared the range is done with it (one - // submission runs at a time), and the snapshot with the last range. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); - pending.retain(|&r| r != (address, address + len)); - if pending.is_empty() - && let Some((_, bytes)) = snapshot.take() - { - unchanged.clear(); + if relay() { + let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges); + pending.retain(|r| !free.contains(r)); + } else { + pending.retain(|r| !ranges.contains(r)); + } + if !pending.is_empty() || self.card.is_some() { + return; + } + if keeps() { + // Kept for the next submission, if it is worth it (a megabyte + // or more) and there is room. + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if !kept.1 && self.len >= 1 << 20 { + if KEPT_BYTES.fetch_add(self.len, Ordering::Relaxed) + self.len <= kept_most() { + kept.1 = true; + } else { + KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } + } + if kept.1 { + return; + } + // Given back: nothing of it is current next time. (The lock + // on the pieces ends here: `copy_back` takes it while it holds + // the snapshot's.) + kept.0.clear(); + } + if let Some(bytes) = self.before.lock().unwrap_or_else(|e| e.into_inner()).take() { give_back(bytes); } - written + } + + /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory, as + /// [`Shadow::differing`] cuts them) that hold offsets `[from, to)` of + /// the copy; `from < to`. + fn pieces(&self, from: usize, to: usize) -> std::ops::Range<usize> { + pieces_of(self.start as usize, from, to) + } + + /// The offsets in the copy that piece `piece` holds. + fn piece(&self, piece: usize) -> (usize, usize) { + piece_at(self.start as usize, self.len as usize, piece) + } + + /// The copy's bytes at offsets `[from, to)` change: a kept snapshot is + /// not current there any more. + fn changed(&self, from: usize, to: usize) { + if !keeps() || from >= to { + return; + } + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if kept.0.is_empty() { + return; + } + for piece in self.pieces(from, to) { + kept.0[piece] = false; + } + } + + /// Whether shaders of a submission not yet copied back may be writing + /// the copy. + pub(crate) fn writes_pending(&self) -> bool { + !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + + /// Whether [`Shadow::update`] of `[address, address + len)` would leave + /// title bytes behind: a range shaders may be writing holds a page the + /// title wrote since the copy last took it. The answer comes from the + /// write-watch journal alone, as the submission's one asking left it + /// (`crate::watch::asked`); where the journal cannot say (memory not + /// write-watched, a range not asked about) it is yes. A page the copy + /// never took whole counts as written if the title ever wrote it. + /// + /// For submissions sent to the card without a wait + /// (`crate::host::late`): the ranges are those of flights in the air, + /// which are then settled before this refresh. + pub(crate) fn stale_under_writes(&self, address: usize, len: usize) -> bool { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return false; + } + let busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|&&(a, e)| a < to && e > from) + .map(|&(a, e)| (a.max(from), e.min(to))) + .collect(); + if busy.is_empty() { + return false; + } + if self.watched.load(Ordering::Relaxed) == NOT_WATCHED { + return true; + } + let base = start / PAGE; + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) { + Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(), + None => true, + }) + } + + /// Where [`Shadow::stale_under_writes`] says yes: puts the bytes the + /// title changed into the copy, in the ranges shaders may be writing, + /// and only those bytes, so that what the shaders write beside them + /// stays (`crate::host::late_exact`). For each page of such a range + /// that the title wrote since the copy last took it, title memory as + /// it is now is compared with what the copy held when the range was + /// given to the shaders: the copy's CPU side for a copy in the card's + /// memory (the changed runs go up before the next submission, each a + /// copy of its own bytes, `runs_left` of them at most), the snapshot + /// for the others (the changed bytes go into the copy and into the + /// snapshot, so the compare after the card ran takes them for the + /// title's and not the shaders'). + /// + /// Whether the caller must still settle the flights: the journal + /// cannot say what was written, a snapshot is missing, or `runs_left` + /// ran out. Pages done before that stay done. + pub(crate) fn merge_under_writes( + &self, + address: usize, + len: usize, + runs_left: &mut usize, + unwatched_left: &mut usize, + ) -> bool { + #[cfg(feature = "diagnostics")] + let _reads_as = crate::backreads::reading_as(crate::backreads::UNDER, self.id); + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return false; + } + let busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|&&(a, e)| a < to && e > from) + .map(|&(a, e)| (a.max(from), e.min(to))) + .collect(); + if busy.is_empty() { + return false; + } + let unwatched = self.watched.load(Ordering::Relaxed) == NOT_WATCHED; + let base = start / PAGE; + let mut title = vec![0u8; PAGE]; + for (a, e) in busy { + // As the refresh itself asks (`update_free`): the journal if + // the submission's asking covered the range, else the kernel, + // else the guards. The journal alone said nothing for copies + // of view memory, which is guarded and not write-watched, and + // those were all of run 99's cases: the flights were settled + // 4-5 times a frame for "0 pages looked at". + let journal = if unwatched { None } else { crate::watch::writes(a, e, true) }; + // Where nothing can say which pages the title wrote, every page + // of the range is compared ([`merge_unwatched_bytes`]): the + // reference holds what the copy held when the range went to the + // shaders, and the copy-back changes title memory and it + // together, so what differs is the title's. + let (now, stale): (Option<u64>, Vec<usize>) = match journal { + Some((now, written)) => { + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + (Some(now), stale_pages_in(base, &copied, a, e, &written)) + } + None => { + if e - a > *unwatched_left { + MERGE_SETTLES[0].fetch_add(1, Ordering::Relaxed); + return true; + } + *unwatched_left -= e - a; + let pages: Vec<usize> = (a / PAGE..e.div_ceil(PAGE)).collect(); + MERGE_SETTLES[3].fetch_add(pages.len() as u64, Ordering::Relaxed); + (None, pages) + } + }; + for page in stale { + let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e)); + if lo >= hi { + continue; + } + let n = hi - lo; + let title = &mut title[..n]; + // The lock of the copy's reference (the snapshot, or the + // CPU's side of a copy in the card's memory), from before + // title memory is read until the title's bytes are in: with + // the copy-back on its own thread ([`relay`]) that thread + // puts what the card wrote into title memory and into the + // reference under the same lock, and a page read before + // such a merge and compared after it would take the card's + // bytes for the title's. + let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); + // A page that is not there is left as it is, and looked at + // again next time. + if !crate::host::read_into(lo as *const u8, title) { + continue; + } + MERGED[0].fetch_add(1, Ordering::Relaxed); + let at = lo - start; + if self.card.is_some() { + // SAFETY: inside the mapping of the copy's CPU side, + // which only the submitting thread writes. + let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; + let runs = joined_over(changed_runs(title, held), merge_gap()); + if runs.len() > *runs_left { + MERGE_SETTLES[2].fetch_add(1, Ordering::Relaxed); + MERGE_GAVE_UP[2].fetch_add(1, Ordering::Relaxed); + return true; + } + *runs_left -= runs.len(); + for (r, m) in runs { + held[r..r + m].copy_from_slice(&title[r..r + m]); + self.card_changed(at + r, at + r + m); + MERGED[1].fetch_add(1, Ordering::Relaxed); + MERGED[2].fetch_add(m as u64, Ordering::Relaxed); + } + } else { + let Some(snapshot) = before.as_mut() else { + MERGE_SETTLES[1].fetch_add(1, Ordering::Relaxed); + MERGE_GAVE_UP[3].fetch_add(1, Ordering::Relaxed); + return true; + }; + // SAFETY: the snapshot's allocation holds the copy's + // bytes at the copy's offsets (`writing`), and these + // are in a declared range. + let held = unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) }; + for (r, m) in changed_runs(title, held) { + // SAFETY: inside the copy's mapping. The card may be + // writing the copy beside these bytes; they are + // written here and nothing around them. + unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; + held[r..r + m].copy_from_slice(&title[r..r + m]); + MERGED[1].fetch_add(1, Ordering::Relaxed); + MERGED[2].fetch_add(m as u64, Ordering::Relaxed); + } + } + drop(before); + // Taken, if the range holds all of the page that is in the + // copy; else the rest of it is the refresh's, which notes + // only whole pages, and the page is looked at again. (With + // no journal there is no time to note.) + if let Some(now) = now + && (page * PAGE).max(start) >= a + && ((page + 1) * PAGE).min(end) <= e + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(at) = copied.get_mut(page - base) { + *at = now; + } + } + } + } + false } /// At submission: copies what changed of `[address, address + len)` /// since it was last copied (all of it if the memory is not /// write-watched). Returns the bytes copied. pub(crate) fn update(&self, address: usize, len: usize) -> usize { + let bytes = self.update_inner(address, len); + if bytes > 0 { + self.title_in.fetch_add(1, Ordering::Relaxed); + } + bytes + } + + /// Refreshes so far that brought title bytes into the copy. + pub(crate) fn title_ins(&self) -> u64 { + self.title_in.load(Ordering::Relaxed) + } + + /// [`Shadow::update`]'s copy. + fn update_inner(&self, address: usize, len: usize) -> usize { + // In place: the card reads title memory itself. + if self.place.is_some() { + return 0; + } let (start, end) = (self.start as usize, (self.start + self.len) as usize); let (from, to) = (address.max(start), (address + len).min(end)); if from >= to { @@ -355,9 +4053,47 @@ impl Shadow { /// shader writes. fn update_free(&self, from: usize, to: usize) -> usize { if self.watched.load(Ordering::Relaxed) != NOT_WATCHED { + // The light refresh (`VICTORY_LIGHT_REFRESH`): nothing of the + // range was written that the copy does not hold, and the + // journal says so with nothing asked. + if crate::watch::light() && self.nothing_new(from, to) { + self.refresh_check(from, to); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Checked, (to - from) as u64); + add(C::Unchanged, (to - from) as u64); + } + return 0; + } + // The counter of fps41 round 8: copied nothing or something, + // and (with `VICTORY_REFRESH_COUNT=1`) whether it was known + // unchanged before asking. Looked at before the asking, which + // changes the guards and the journal. + #[cfg(feature = "diagnostics")] + let (asking, known) = (std::time::Instant::now(), refresh_count() && self.unchanged_known(from, to)); if let Some((now, written)) = crate::watch::writes(from, to, true) { self.watched.store(1, Ordering::Relaxed); - let copied = self.copy_stale(from, to, now, &written); + // With `VICTORY_DIRTY_4K`: the 4 KiB pages the kernel found, read before the copy's lock. + let subs = crate::watch::subpages(from, to); + let copied = self.copy_stale(from, to, now, &written, &subs); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + let us = asking.elapsed().as_micros() as u64; + if copied == 0 { + add(C::RefreshNone, 1); + add(C::RefreshNoneUs, us); + if known { + add(C::RefreshKnown, 1); + add(C::RefreshKnownUs, us); + } + } else { + add(C::RefreshSome, 1); + add(C::RefreshSomeUs, us); + } + } + self.refresh_check(from, to); #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; @@ -368,18 +4104,114 @@ impl Shadow { } self.watched.store(NOT_WATCHED, Ordering::Relaxed); } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::WholeBytes, (to - from) as u64); + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); self.copy(from, to); + #[cfg(feature = "diagnostics")] + crate::copystat::whole(from, to - from, started.elapsed().as_micros() as u64); to - from } + /// Whether a refresh of `[from, to)` would copy nothing, known before + /// asking (`crate::watch::unchanged_known`); `false` for a copy not + /// known to be watched yet. + #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] + fn unchanged_known(&self, from: usize, to: usize) -> bool { + if self.watched.load(Ordering::Relaxed) != 1 { + return false; + } + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + crate::watch::unchanged_known(from, to, self.start as usize / PAGE, &copied) + } + + /// Whether [`Shadow::update_free`] of `[from, to)` would copy nothing, + /// known without asking the kernel or the guards + /// (`crate::watch::nothing_new`): the memory is watched, every page of + /// the range was taken, and none was noted written after it was. + /// `false` if the refresh would have to ask. + fn nothing_new(&self, from: usize, to: usize) -> bool { + if self.watched.load(Ordering::Relaxed) != 1 { + return false; + } + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + crate::watch::nothing_new(from, to, self.start as usize / PAGE, &copied) + } + + /// Diagnostic (`VICTORY_REFRESH_CHECK=1`; off by default): after a + /// refresh of `[from, to)` that trusted the write watch or the guards, + /// the first 256 bytes of every 64 KiB block of it are read from title + /// memory and compared with the copy. A block that differs on three + /// refreshes in a row was changed with nothing to tell of it (a write + /// through another view of its pages, as DirectStorage's page + /// destinations make) and the card reads old bytes there: said with + /// the copy and the address. One that differs once is a write of the + /// title's that arrived between the refresh and the look. + fn refresh_check(&self, from: usize, to: usize) { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1")) { + return; + } + const SAMPLE: usize = 256; + // Blocks found differing: how many refreshes in a row. + static DIFFERING: Mutex<Option<std::collections::HashMap<usize, u32>>> = Mutex::new(None); + static SAID: AtomicU64 = AtomicU64::new(0); + let start = self.start as usize; + let mut title = [0u8; SAMPLE]; + let mut at = from; + while at < to { + let n = SAMPLE.min(to - at); + if crate::host::read_into(at as *const u8, &mut title[..n]) { + // SAFETY: `[from, to)` lies inside the buffer (`update`), + // so these bytes are inside the copy's mapping. + let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) }; + let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(Default::default); + if copy == &title[..n] { + map.remove(&at); + } else { + let times = map.entry(at).or_insert(0); + *times += 1; + if *times == 3 { + let said = SAID.fetch_add(1, Ordering::Relaxed) + 1; + if said <= 64 || said.is_power_of_two() { + tracing::warn!( + said, + copy = self.id, + copy_start = format_args!("{start:#x}"), + copy_bytes = self.len, + address = format_args!("{at:#x}"), + refreshed = format_args!("{from:#x}..{to:#x}"), + on_the_card = self.card.is_some(), + window = self.window, + "a host copy of title memory is stale after its refresh, three times in a row: the memory changed with nothing to tell of it (VICTORY_REFRESH_CHECK=1)" + ); + } + } + } + } + // The first bytes of the next 64 KiB block. + at = (at / PAGE + 1) * PAGE; + } + } + /// Copies the pages of `[from, to)` written after their last copy /// (`written`: last writes by page, in page order; `now`: this /// asking), whole pages within the buffer. - fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize { + /// + /// `subs` ([`crate::watch::subpages`], `VICTORY_DIRTY_4K`): for a page the kernel's write watch found written, + /// the 4 KiB pages its last asking found and the asking before that which found the page written. A copy that + /// took the page at or after that earlier asking copies only those 4 KiB pages: the others have not been written + /// since it took them (`crate::watch::dirty4k`). + fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)], subs: &[(usize, u64, u64, u16)]) -> usize { + const KERNEL_PAGE: usize = 4096; + let narrow = !subs.is_empty() && crate::watch::dirty4k(); let base = self.start as usize / PAGE; let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); let mut writes = written.iter().peekable(); - let (mut bytes, mut run) = (0, None); + let mut subs = subs.iter().peekable(); + let (mut bytes, mut run): (_, Option<usize>) = (0, None); let last = (to - 1) / PAGE; for page in from / PAGE..=last { let write = match writes.peek() { @@ -389,34 +4221,476 @@ impl Shadow { } _ => 0, }; + while subs.peek().is_some_and(|s| s.0 < page) { + subs.next(); + } + // The page's entry, if it stands for the asking the refresh was given for the page. + let sub = subs.peek().filter(|s| s.0 == page && s.1 == write && write != 0).map(|s| (s.2, s.3)); let at = &mut copied[page - base]; if *at == 0 || write > *at { + let taken = *at; // A page only partly in the range is copied in part: it // stays stale for the rest. let (start, end) = (self.start as usize, (self.start + self.len) as usize); if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { *at = now; } + // Only the 4 KiB pages written since the copy took the page: the asking before the last one that + // found it written came no later than the copy's taking. + let found = sub.filter(|&(before, _)| taken != 0 && before <= taken).map(|(_, bits)| bits); + if crate::watch::dirty4k_kept() { + crate::watch::dirty4k_count(found, narrow && found.is_some()); + } + if narrow && let Some(bits) = found { + if let Some(first) = run.take() { + bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to)); + } + let mut k = 0; + while k < PAGE / KERNEL_PAGE { + if bits & (1 << k) == 0 { + k += 1; + continue; + } + let a = k; + while k < PAGE / KERNEL_PAGE && bits & (1 << k) != 0 { + k += 1; + } + let (lo, hi) = ((page * PAGE + a * KERNEL_PAGE).max(from), (page * PAGE + k * KERNEL_PAGE).min(to)); + if lo < hi { + bytes += self.copy(lo, hi); + } + } + continue; + } run.get_or_insert(page); } else if let Some(first) = run.take() { bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to)); } } - // Cut to the range: next to it shaders may be writing the copy. - if let Some(first) = run { - bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to)); + // Cut to the range: next to it shaders may be writing the copy. + if let Some(first) = run { + bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to)); + } + bytes + } + + /// Copies title memory `[from, to)`, cut to the buffer, into the copy. + fn copy(&self, from: usize, to: usize) -> usize { + #[cfg(feature = "diagnostics")] + let _reads_as = crate::backreads::reading_as(crate::backreads::REFRESH, self.id); + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (from.max(start), to.min(end)); + if from >= to { + return 0; + } + if self.card.is_some() && copy_changed() && self.copy_changed(from, to) { + return to - from; + } + if self.card.is_some() + && same_skips() + && let Some(copied) = self.copy_same_skipped(from, to) + { + return copied; + } + // SAFETY: inside the mapping (`from` and `to` are within the buffer). + let at = unsafe { self.data.add(from - start) }; + crate::host::copy_mapped(at, from as *const u8, to - from, false); + // After the bytes are in: a snapshot taken meanwhile is not current. + self.changed(from - start, to - start); + self.card_changed(from - start, to - start); + to - from + } + + /// [`Shadow::copy`] of a copy in the card's memory ([`same_skips`]): + /// title memory `[from, to)` (within the buffer) is read aside, and only + /// the 4 KiB runs that differ from the CPU's side go into it and to the + /// card. Write watching tells which pages the title wrote, not whether + /// their bytes changed, and titles write the same constants again frame + /// after frame; each such page went up to the card and was hashed there + /// again. `None` if title memory there could not all be read (then it + /// is copied as before). The bytes that went in. + fn copy_same_skipped(&self, from: usize, to: usize) -> Option<usize> { + const RUN: usize = 4096; + thread_local! { + static ASIDE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; + } + let start = self.start as usize; + let n = to - from; + ASIDE.with_borrow_mut(|aside| { + aside.clear(); + aside.resize(n, 0); + if !crate::host::read_into(from as *const u8, aside) { + return None; + } + let mut copied = 0; + let mut put = |a: usize, b: usize| { + // SAFETY: `[a, b)` lies in `[from, to)`, inside the buffer + // and so inside the mapping; `aside` holds `[from, to)`. + unsafe { std::ptr::copy_nonoverlapping(aside.as_ptr().add(a - from), self.data.add(a - start), b - a) }; + self.changed(a - start, b - start); + self.card_changed(a - start, b - start); + copied += b - a; + }; + let mut run: Option<usize> = None; + let mut at = from; + while at < to { + let next = ((at / RUN + 1) * RUN).min(to); + // SAFETY: as above; read only. + let held = unsafe { std::slice::from_raw_parts(self.data.add(at - start), next - at) }; + if *held != aside[at - from..next - from] { + run.get_or_insert(at); + } else if let Some(first) = run.take() { + put(first, at); + } + at = next; + } + if let Some(first) = run { + put(first, to); + } + SAME_SKIPPED.fetch_add((n - copied) as u64, Ordering::Relaxed); + Some(copied) + }) + } + + /// [`Shadow::copy`] for a copy in the card's memory, with + /// [`copy_changed`]: title memory `[from, to)` (inside the buffer) is + /// read beside the copy's CPU side and only the stretches that differ + /// are stored there and noted for the card. False with nothing done if + /// title memory could not be read whole (the caller copies as before). + fn copy_changed(&self, from: usize, to: usize) -> bool { + thread_local! { + static NOW: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; + } + let (start, n) = (self.start as usize, to - from); + NOW.with(|now| { + let mut now = now.borrow_mut(); + if now.len() < n { + now.resize(n, 0); + } + if !crate::host::read_into(from as *const u8, &mut now[..n]) { + return false; + } + // SAFETY: inside the copy's mapping (`from` and `to` are within + // the buffer); nothing else writes the CPU side of these bytes + // while a refresh has them (a refresh is one thread's). + let held = unsafe { std::slice::from_raw_parts(self.data.add(from - start).cast_const(), n) }; + let stretches = changed_chunks(&now[..n], held, COPY_CHANGED_CHUNK); + let mut sent = 0; + for &(at, len) in &stretches { + // SAFETY: as above; the stretch lies inside both. + unsafe { std::ptr::copy_nonoverlapping(now.as_ptr().add(at), self.data.add(from - start + at), len) }; + // After the bytes are in: a snapshot taken meanwhile is not current. + self.changed(from - start + at, from - start + at + len); + self.card_changed(from - start + at, from - start + at + len); + sent += len; + } + COPY_CHANGED[0].fetch_add(n as u64, Ordering::Relaxed); + COPY_CHANGED[1].fetch_add(sent as u64, Ordering::Relaxed); + COPY_CHANGED[2].fetch_add(stretches.len() as u64, Ordering::Relaxed); + let calls = COPY_CHANGED[3].fetch_add(1, Ordering::Relaxed) + 1; + if calls.is_multiple_of(65536) { + tracing::info!( + "copies in the card's memory, refreshed by what differs (VICTORY_COPY_CHANGED=1), since the start: {calls} refreshes read {} MB of title memory the title had written to; {} MB of it differed from the copy and went on to the card, in {} stretches", + COPY_CHANGED[0].load(Ordering::Relaxed) >> 20, + COPY_CHANGED[1].load(Ordering::Relaxed) >> 20, + COPY_CHANGED[2].load(Ordering::Relaxed) + ); + } + true + }) + } + + /// Whether shaders read and write this copy in the card's own memory + /// ([`cards`]). + pub(crate) fn carded(&self) -> bool { + self.card.is_some() + } + + /// The title memory the copy is of, as (start, end). + pub(crate) fn title_span(&self) -> (usize, usize) { + (self.start as usize, (self.start + self.len) as usize) + } + + /// Whether title bytes are on their way to the card's side of the copy + /// (changed on the CPU's side and not sent yet, or sent and not past a + /// merged fetch): the title writes this copy. + pub(crate) fn title_writes_card(&self) -> bool { + let Some(card) = &self.card else { + return false; + }; + let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + !dirty.is_empty() || !card.sent.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + + /// The CPU side's bytes at offsets `[from, to)` changed: they go to the + /// card's side before the next submission. + fn card_changed(&self, from: usize, to: usize) { + let Some(card) = &self.card else { + return; + }; + if from >= to { + return; + } + let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let first = dirty.is_empty(); + match dirty.last_mut() { + Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)), + _ => dirty.push((from, to)), + } + drop(dirty); + // From none to some: [`card_dirty`] finds the copy in the list. (A + // copy changed again before its ranges are taken is in it already; + // one whose ranges the walk took may be in it with nothing to take.) + if first + && changed_kept() + && let Some(me) = card.me.get() + { + CHANGED.lock().unwrap_or_else(|e| e.into_inner()).push(me.clone()); + } + } + + /// Of a copy in the card's memory: the CPU's side (PC memory), the + /// card side's bytes from before if made yet, and their size. + pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option<ID3D12Resource>, u64)> { + let card = self.card.as_ref()?; + let before = card.before.lock().unwrap_or_else(|e| e.into_inner()).clone(); + Some((&card.staging, before, card.size)) + } + + /// The bytes of the copy the card's hashes cover: with + /// `VICTORY_CARD_HASH_LEN=1` the title buffer's own, rounded up to the + /// hash's 16-byte step; else the copy's whole buffer, as before (the + /// short form has not run in a game yet, so it is not the default). A copy's buffer is the title + /// buffer rounded up to 64 KiB, and one thread walked all of a piece: for + /// a title buffer of 288 bytes, 4,096 steps where 18 hold everything + /// that can go back to the title (the pieces fetched are cut to the + /// title buffer too, [`Shadow::card_piece`]). With every title buffer's + /// copy on the card (`VICTORY_CARD_BUFFERS_MIN_KB=64`) run 275 had 160 + /// more hash passes and 300 more compare passes a frame over such + /// copies, and the send-and-hash lists took 19.7 ms of the card a frame + /// where they had taken 10.9. + pub(crate) fn card_hashed(&self) -> Option<u64> { + static WHOLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let size = self.card.as_ref()?.size; + if *WHOLE.get_or_init(|| std::env::var_os("VICTORY_CARD_HASH_LEN").is_none_or(|v| v != "1")) { + return Some(size); + } + Some(self.len.next_multiple_of(16).min(size)) + } + + /// Shader writes are declared for a copy in the card's memory: makes + /// its "before" twin with `make` (bytes to buffer) if it has none. + /// Whether one was made now: the caller fills it, whole, from the + /// card's side before the submission's lists run. Without one (no + /// memory) every piece of a declared range is fetched. + pub(crate) fn card_make_before(&self, make: impl FnOnce(u64) -> Option<ID3D12Resource>) -> bool { + let Some(card) = &self.card else { + return false; + }; + let mut before = card.before.lock().unwrap_or_else(|e| e.into_inner()); + if before.is_some() { + return false; + } + *before = make(card.size); + if before.is_some() { + CARD_BYTES[1].fetch_add(card_hash_bytes(card.size), Ordering::Relaxed); + } + before.is_some() + } + + /// The declared range `[address, end)` as the compare on the card + /// takes it; `None` if none of it lies in the copy. + pub(crate) fn card_span(&self, address: usize, end: usize) -> Option<CardSpan> { + let (from, to) = self.inside(address, end.saturating_sub(address)); + (from < to).then(|| card_span_of(self.start as usize, from, to)) + } + + /// The pieces that hold offsets `[from, to)` of the copy (cut to it), + /// as the card's hashing takes them. + pub(crate) fn card_run(&self, from: usize, to: usize) -> CardSpan { + let to = to.min(self.len as usize); + card_span_of(self.start as usize, from.min(to.saturating_sub(1)), to) + } + + /// The offsets of piece `i` of `span` that lie in the span. + pub(crate) fn card_piece(&self, span: &CardSpan, i: u32) -> (usize, usize) { + card_piece_of(self.start as usize, self.len as usize, span, i) + } + + /// The walls trace (`crate::host::walls_trace`): a piece of `fetched` + /// bytes of this copy came back from the card and `written` of them + /// went into title memory. Summed per buffer and logged once a frame: + /// which shader-written buffers the title's CPU could see fresh in + /// that frame, and how much of each changed. + pub(crate) fn walls_merged(&self, fetched: usize, written: usize) { + if !crate::host::walls_trace() { + return; + } + static SEEN: Mutex<(u64, BTreeMap<u64, (u64, u32, u64, u64)>)> = Mutex::new((0, BTreeMap::new())); + let frame = crate::frame::current(); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.0 != frame { + let buffers: Vec<String> = seen + .1 + .iter() + .map(|(at, v)| format!("{at:#x}+{:#x}: {} pieces, {} fetched, {} written", v.0, v.1, v.2, v.3)) + .take(32) + .collect(); + if !buffers.is_empty() { + tracing::info!( + frame = seen.0, + count = seen.1.len(), + buffers = ?buffers, + "walls trace: shader-written card buffers merged into title memory in this frame" + ); + } + seen.1.clear(); + seen.0 = frame; + } + let entry = seen.1.entry(self.start).or_insert((self.len, 0, 0, 0)); + entry.1 += 1; + entry.2 += fetched as u64; + entry.3 += written as u64; + } + + /// After a submission, for a copy in the card's memory: `gpu` is what + /// the card's side holds at offset `at` on, in a piece the compare + /// found differing. The bytes shaders wrote (those that differ from the + /// CPU's side, which is what the card's side held when they started) + /// go into title memory, from the first to the last of them, as + /// [`Shadow::copy_back`] puts them; the CPU's side takes the result and + /// sends it up before the next submission. `title` is scratch memory. + /// Returns the bytes written to title memory. + pub(crate) fn card_merge(&self, at: usize, gpu: &[u8], title: &mut Vec<u8>) -> usize { + let start = self.start as usize; + if self.card.is_none() || at + gpu.len() > self.len as usize { + return 0; } - bytes + // SAFETY: inside the mapping (checked above); only the submitting + // thread writes it. + let old = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) }; + let Some(first) = first_difference(gpu, old) else { + return 0; + }; + let last = last_difference(gpu, old).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (gpu, old) = (&gpu[first..=last], &mut old[first..=last]); + title.clear(); + title.resize(n, 0); + let mut written = 0; + if crate::host::read_into((start + at) as *const u8, title) { + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = merge_race_on().then(|| title.clone()); + // As in `copy_back`: the card's byte where it is not what it + // was before the submission, else the title's. + let mut differs = 0u8; + for ((t, g), o) in title.iter_mut().zip(gpu).zip(old.iter_mut()) { + let wrote = if *g != *o { 0xffu8 } else { 0 }; + let merged = (*t & !wrote) | (*g & wrote); + differs |= merged ^ *t; + *t = merged; + *o = merged; + } + if differs != 0 { + crate::host::shaders_write(start + at, &title[..]); + crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card"); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + written = n; + } + } else { + // Title memory is not mapped there: the copy keeps what the + // card wrote, as before. + old.copy_from_slice(gpu); + } + // The card's side and its "before" take the result. + self.card_changed(at, at + n); + written } - /// Copies title memory `[from, to)`, cut to the buffer, into the copy. - fn copy(&self, from: usize, to: usize) -> usize { - let (start, end) = (self.start as usize, (self.start + self.len) as usize); - let (from, to) = (from.max(start), to.min(end)); - // SAFETY: inside the mapping (`from` and `to` are within the buffer). - let at = unsafe { self.data.add(from - start) }; - crate::host::copy_mapped(at, from as *const u8, to - from, false); - to - from + /// [`relay`], for a copy in the card's memory: `gpu` is what the + /// card's side held at offset `at` on when a fetch sent after send + /// `fetched_after` (`crate::host`'s order of the queue) ran, in a piece + /// the compare found differing. The bytes that differ from the CPU's + /// side are what shaders wrote; they go into title memory, from the + /// first to the last of them, and into the CPU's side. Nothing is sent + /// up afterwards (the card holds these bytes or newer ones: sending + /// them up could undo a later flight's write), and the title's other + /// bytes are left to the refresh. + /// + /// Left out: bytes of the CPU's side that hold title bytes the card + /// had not received when the fetch ran, those still to go up and those + /// that went up with a later send. There the card's side is the older + /// one, and taking it for a shader's write would put it over what the + /// title wrote. Under the CPU side's lock (the snapshot's, which such + /// a copy has no other use for), as [`Shadow::merge_under_writes`]. + /// `title` is scratch memory. Returns the bytes written to title + /// memory. + pub(crate) fn card_merge_relay(&self, at: usize, gpu: &[u8], fetched_after: u64, title: &mut Vec<u8>) -> usize { + let start = self.start as usize; + let Some(card) = &self.card else { + return 0; + }; + if at + gpu.len() > self.len as usize { + return 0; + } + let _side = self.before.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: inside the mapping (checked above). The offsets are in a + // range declared and not done with, which no refresh writes; what + // does write it (the title's bytes put in under shader writes) + // holds the lock held here. + let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) }; + let Some(first) = first_difference(gpu, held) else { + return 0; + }; + let last = last_difference(gpu, held).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (gpu, held) = (&gpu[first..=last], &mut held[first..=last]); + let skip: Vec<(usize, usize)> = { + let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner()); + dirty + .iter() + .copied() + .chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1))) + .filter(|&(a, b)| a < at + n && b > at) + .collect() + }; + title.clear(); + title.resize(n, 0); + // Who touched the page since its last store is looked at before our + // own read of it (`VICTORY_BACK_READS`): counted only. + #[cfg(feature = "diagnostics")] + let _reads_as = crate::backreads::reading_as(crate::backreads::MERGE, self.id); + #[cfg(feature = "diagnostics")] + crate::backreads::before(start + at); + let mapped = crate::host::read_into((start + at) as *const u8, title); + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = (mapped && merge_race_on()).then(|| title.clone()); + let mut changed = false; + for (a, b) in outside(at, at + n, skip) { + let (a, b) = (a - at, b - at); + // Title memory that is not mapped: the CPU's side keeps what + // the card wrote, as before; `title` is scratch then. + changed |= merge_piece(&gpu[a..b], &mut held[a..b], &mut title[a..b]); + } + if !mapped || !changed { + return 0; + } + crate::host::shaders_write(start + at, &title[..]); + if self.put_back_own(start + at, &title[..]) { + #[cfg(feature = "diagnostics")] + crate::backreads::stored(self.id, (self.start, self.len), start + at, n, true); + return n; + } + crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card relay"); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + #[cfg(feature = "diagnostics")] + crate::backreads::stored(self.id, (self.start, self.len), start + at, n, false); + n } } @@ -434,23 +4708,312 @@ fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> { /// A title buffer exists at `start` (`len` bytes). pub(crate) fn register(resource: usize, start: u64, len: u64) { - buffers().insert( + let mut map = buffers(); + map.insert( (start, resource), Entry { end: start + len, shadow: None, }, ); + // After the insert, with the table's lock still held ([`TABLES_CHANGED`]; + // fork pull request #1245: said before it, a thread that asked between + // the two kept the old table's answer under the new count for good). + tables_changed(); } /// The title released it; lists that still hold its copy keep it alive. pub(crate) fn unregister(resource: usize, start: u64) { - buffers().remove(&(start, resource)); + let mut map = buffers(); + tables_changed(); + map.remove(&(start, resource)); +} + +/// The title buffer holding `address`, as (start, length), without making +/// its copy (diagnostics: which buffer a dropped program's root view names). +#[cfg(feature = "diagnostics")] +pub(crate) fn extent(address: u64) -> Option<(u64, u64)> { + buffers() + .range(..=(address, usize::MAX)) + .rev() + .take(64) + .find(|(_, e)| e.end > address) + .map(|(k, e)| (k.0, e.end - k.0)) +} + +/// Title memory `[at, at + len)` is about to show something else or be +/// given up: what is in place there (`crate::inplace`) is taken out of the +/// tables, so that the next ask makes a copy or opens the memory anew, and +/// goes when no list and no slot holds it any more. Returns how many. +pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { + let end = at.saturating_add(len); + let mut gone: Vec<Arc<Shadow>> = Vec::new(); + { + let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let keys: Vec<(u64, u64)> = map + .range((at.saturating_sub(WINDOW), 0)..(end, 0)) + .filter(|(key, shadow)| shadow.place.is_some() && key.0 + key.1 > at) + .map(|(key, _)| *key) + .collect(); + if !keys.is_empty() { + tables_changed(); + } + gone.extend(keys.into_iter().filter_map(|key| map.remove(&key))); + } + { + // As `lookup` finds a buffer: among the 256 that start below. + let mut map = buffers(); + let placed = |entry: &Entry| entry.end > at && entry.shadow.as_ref().is_some_and(|s| s.place.is_some()); + if map.range(..(end, 0)).rev().take(256).any(|(_, entry)| placed(entry)) { + tables_changed(); + for (_, entry) in map.range_mut(..(end, 0)).rev().take(256) { + if placed(entry) { + gone.extend(entry.shadow.take()); + } + } + } + } + let n = gone.len() as u64; + for shadow in gone { + crate::host::retire(shadow); + } + n +} + +/// For the in-place census (`crate::inplace`): the title buffers (start, +/// bytes, false) and the windows outside buffers that have a copy (start, +/// bytes, true). +pub(crate) fn spans() -> Vec<(u64, u64, bool)> { + let mut spans: Vec<(u64, u64, bool)> = buffers().iter().map(|(key, entry)| (key.0, entry.end - key.0, false)).collect(); + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + spans.extend(loose.keys().map(|&(start, len)| (start, len, true))); + spans } /// The copy of the innermost title buffer holding `[address, address + -/// len)`, made on first use. +/// len)`, made on first use. A `len` of 0 or 1 is an ask without a length +/// (a root view: the caller reads on to the copy's end). pub(crate) fn find(address: u64, len: u64) -> Option<Arc<Shadow>> { + lookup(address, len, false) +} + +/// As [`find`], for a copy that exists already: `None` without making one, so +/// a title copy does not give every buffer it names a host copy (and a buffer +/// in the card's memory a mirror in it). pablogonz12/Scarlight #86. +pub(crate) fn peek(address: u64, len: u64) -> Option<Arc<Shadow>> { + let end = address.checked_add(len.max(1))?; + let map = buffers(); + let key = map + .range(..=(address, usize::MAX)) + .rev() + .take(64) + .find(|(_, e)| e.end >= end) + .map(|(k, _)| *k); + let Some(key) = key else { + // Memory outside buffers: a window that is there and holds it. + drop(map); + return LOOSE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .find(|&(&(start, len), _)| start <= address && end <= start + len) + .map(|(_, shadow)| shadow.clone()); + }; + map.get(&key).and_then(|e| e.shadow.clone()) +} + +/// As [`find`], for an ask that is done with the copy when its list has +/// run (a draw's vertex and index buffers, indirect arguments): outside +/// buffer objects it takes a window that is there already and holds the +/// range ([`holder`]), and makes one of its own only if none does. +/// +/// [`find`] names a window by the ask alone, which a descriptor slot needs +/// (the slot shows the window its view found when it was made, and the +/// pass that brings it up to date must find the same one). A draw needs no +/// such thing: it binds the copy it found and brings that copy up to date. +/// Named by the ask alone, every draw's range was a window of its own +/// wherever the windows are cut finer than 4 MiB: draws that bind +/// different ranges of the same memory then each copied their range, and +/// windows nothing asked for again for ten seconds were let go and made +/// (and copied) anew. Run 71, on a 256 KiB grid: 350 MB copied per frame +/// against 120 MB, 7,087 write-watch askings against 2,600, and 5,263 +/// windows (4.5 GB) let go in two minutes against 393 in a whole run. +pub(crate) fn find_any(address: u64, len: u64) -> Option<Arc<Shadow>> { + // With whole windows (the default) there is one window to a cell and + // nothing to choose: exactly `find`. + if !fine() { + return find(address, len); + } + lookup(address, len, true) +} + +/// Counts the changes of the tables [`lookup`] reads that can change what an +/// ask finds: a buffer registered or released, a copy taken out of a table, +/// a window made. A thread's remembered answers ([`FOUND`]) are from one +/// count. +/// +/// The order that makes a thread's remembered answer safe with no lock on +/// a remembered ask: a copy that LEAVES a table is counted before it +/// leaves, an entry that COMES is counted after it is in, both with the +/// table's lock held; and a thread that finds a remembered answer looks at +/// the count again before it uses it ([`lookup`]). So an answer used was +/// the tables' own at the moment of that second look, or a moment before +/// a change that had not been made yet: what an ask of the tables just +/// ahead of the change would have found. The idle sweep, which lets go +/// only what nobody holds, looks at each copy's holders again after it +/// counted: the thread took its handle and then read the count, the sweep +/// counts and then reads the holders, so one of the two sees the other. +/// (That last step leans on the processor: the handle's count is the +/// standard library's, whose orderings are not ours to choose; on x86-64, +/// the only processor the layer runs on, taking a handle and adding to the +/// count are both locked instructions, which is what it needs.) +static TABLES_CHANGED: AtomicU64 = AtomicU64::new(0); + +fn tables_changed() { + TABLES_CHANGED.fetch_add(1, Ordering::SeqCst); +} + +#[cfg(test)] +mod registration_tests { + use super::{TABLES_CHANGED, buffers, register, unregister}; + use std::sync::{Barrier, atomic::Ordering}; + use std::time::{Duration, Instant}; + + /// A registration that waits for the table's lock has not counted yet: + /// who reads the old table reads it under the old count (fork pull + /// request #1245's test). + #[test] + fn a_pending_registration_invalidates_readers_of_the_old_table() { + // No card: the address of a stack slot is the key. + let slot = 0u64; + let start = (&raw const slot) as u64; + let resource = start as usize; + let table = buffers(); + let initial = TABLES_CHANGED.load(Ordering::Acquire); + let ready = Barrier::new(2); + let observed = std::thread::scope(|scope| { + scope.spawn(|| { + ready.wait(); + register(resource, start, 8); + }); + ready.wait(); + // Time for a writer that counted before taking the lock to + // show it; a right one stays blocked all the while. + let deadline = Instant::now() + Duration::from_millis(50); + while TABLES_CHANGED.load(Ordering::Acquire) == initial && Instant::now() < deadline { + std::thread::yield_now(); + } + let count = TABLES_CHANGED.load(Ordering::Acquire); + assert!(!table.contains_key(&(start, resource))); + drop(table); + count + }); + let committed = TABLES_CHANGED.load(Ordering::Acquire); + unregister(resource, start); + assert_ne!(committed, observed, "the old table still has the current count"); + } +} + +/// Since the last frame line: asks answered from a thread's own memory of +/// them, and asks that went to the tables. +pub(crate) static LOOKUPS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// Whether a thread remembers what its asks found (fork pull request +/// #1237; `VICTORY_LOOKUP_CACHE=1`). +/// +/// Every bind of a draw asks for the host copy of each buffer it reads: +/// under the tables' one lock, among the 64 buffers that start below the +/// address, then, for memory outside buffers, under the windows' lock. The +/// title's six recording threads spent 54 ms a frame there together in the +/// prologue cell (`VICTORY_PROFILE`), and asked for the same ranges again +/// and again. A thread now keeps what each ask (address, length, kind) +/// found, weakly (a copy nothing else holds can still be let go), for as +/// long as the tables have not changed ([`TABLES_CHANGED`]). +/// +/// Here: OFF unless `VICTORY_LOOKUP_CACHE=1` until a run of ours has carried +/// it (the pull request has it on by default); `alt`: twenty seconds with, +/// twenty without, in turn, each change said in the log. +fn lookup_cache() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_LOOKUP_CACHE").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a thread remembers what its asks for a buffer's host copy found from now (VICTORY_LOOKUP_CACHE=alt): {}", + if on { "ON" } else { "off, every ask goes to the tables as usual" } + ); + } + on + } + } +} + +/// The most asks a thread remembers before it starts again. +const FOUND_MOST: usize = 8192; + +type Found = std::collections::HashMap<(u64, u64, bool), std::sync::Weak<Shadow>>; + +thread_local! { + /// What this thread's asks found, and the count of table changes they + /// are from. + static FOUND: std::cell::RefCell<(u64, Found)> = std::cell::RefCell::new((u64::MAX, Found::new())); +} + +fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { + if !lookup_cache() { + return lookup_tables(address, len, any); + } + let changes = TABLES_CHANGED.load(Ordering::Acquire); + let found = FOUND.with(|f| { + let f = &mut *f.borrow_mut(); + if f.0 != changes { + f.1.clear(); + f.0 = changes; + } + f.1.get(&(address, len, any)).and_then(std::sync::Weak::upgrade) + }); + // (The count again: a copy the sweep is taking out of its table at + // this moment can still be alive for the weak handle.) + if let Some(shadow) = found.filter(|_| TABLES_CHANGED.load(Ordering::SeqCst) == changes) { + LOOKUPS[0].fetch_add(1, Ordering::Relaxed); + if shadow.window { + // As `loose` notes an ask of a window it hands out. + shadow.used.store(crate::host::moment(), Ordering::Relaxed); + shadow.asked[0].fetch_min(address, Ordering::Relaxed); + shadow.asked[1].fetch_max(address.saturating_add(len.max(1)), Ordering::Relaxed); + if len <= 1 { + shadow.unsized_asks.fetch_add(1, Ordering::Relaxed); + } + } + return Some(shadow); + } + LOOKUPS[1].fetch_add(1, Ordering::Relaxed); + let shadow = lookup_tables(address, len, any)?; + FOUND.with(|f| { + let f = &mut *f.borrow_mut(); + // (from the count read before the tables were: a change since + // clears it at the next ask) + if f.0 == changes { + if f.1.len() >= FOUND_MOST { + f.1.clear(); + } + f.1.insert((address, len, any), Arc::downgrade(&shadow)); + } + }); + Some(shadow) +} + +fn lookup_tables(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { let end = address.checked_add(len.max(1))?; let mut map = buffers(); let key = map @@ -461,15 +5024,56 @@ pub(crate) fn find(address: u64, len: u64) -> Option<Arc<Shadow>> { .map(|(k, _)| *k); let Some(key) = key else { drop(map); - return loose(address, end); + return loose(address, end, len <= 1, any); }; let entry = map.get_mut(&key)?; if entry.shadow.is_none() { let len = entry.end - key.0; // Rounded up so that views ending in the buffer's last 256 bytes fit. // Shaders write some buffers (unordered access), so not upload memory. - let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(1 << 16))?; + let size = len.next_multiple_of(1 << 16); + // In place, if asked for and the memory can be opened + // (`crate::inplace::place_for`): the buffer is the title's own + // memory. Not the big ones `cards` puts in the card's memory: those + // are read too often to stay in the PC's. + let big = cards() && size >= card_limits().0; + if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) { + entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); + return entry.shadow.clone(); + } + let (buffer, data) = host()?.shared_buffer(size)?; crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0)); + // A big one, with `cards`: shaders get a buffer in the card's own + // memory, and the one just made is the CPU's side. + let sides = match card_for(size) { + Some(on_card) => Some((on_card, false)), + None => pc_card_for(size).map(|in_pc| (in_pc, true)), + }; + let (buffer, card) = match sides { + Some((on_card, in_pc)) => { + crate::host::name(&on_card, || { + format!("title buffer {:#x}+{len:#x}, shaders' side{}", key.0, if in_pc { " in the PC's memory" } else { " on the card" }) + }); + tracing::info!( + start = format_args!("{:#x}", key.0), + len, + in_pc, + "a buffer's host copy is in the card's memory (in_pc: its shaders' side in the PC's, compared on the card)" + ); + let card = Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size, + in_pc, + me: std::sync::OnceLock::new(), + }; + (on_card, Some(card)) + } + None => (buffer, None), + }; + placed_count(size, card.is_some()); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; if len >= 16 << 20 { @@ -485,30 +5089,226 @@ pub(crate) fn find(address: u64, len: u64) -> Option<Arc<Shadow>> { "buffer copied to the host" ); } - entry.shadow = Some(Arc::new(Shadow::new(buffer, data, gpu, key.0, len))); + let mut shadow = Shadow::new(buffer, data, gpu, key.0, len); + shadow.card = card; + let shadow = Arc::new(shadow); + if let Some(card) = &shadow.card { + let _ = card.me.set(Arc::downgrade(&shadow)); + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + } + entry.shadow = Some(shadow); } entry.shadow.clone() } -/// Titles also use memory outside any buffer object as GPU memory (Grand -/// Theft Auto VI's interface vertices, from its own allocator). Such memory +/// Titles also use memory outside any buffer object as GPU memory ( +/// the title's interface vertices, from its own allocator). Such memory /// gets copies of the aligned windows it touches. -/// shortcut: copies of windows are never freed; key them to the title's -/// allocations if memory use grows. +/// A window nothing names any more is let go ([`let_go_idle`]). +/// shortcut: a window is 4 MiB however little of it is read (the memory +/// line says how much was ever asked for, and how much was ever copied); +/// [`window`] cuts the windows of asks that give a length on a finer grid. const WINDOW: u64 = 4 << 20; +/// The grid the windows of asks with a length are cut on, in bytes: 4 MiB +/// unless `VICTORY_WINDOW_KB` names a smaller power of two (64 at least). +/// A window is the PC's memory, all of it, however little of it is read: +/// 803 windows held 3.3 GB in run 60's gameplay, and all that was ever +/// asked for in them lay within 1.6 GB. On a grid of 1 MiB or 256 KiB a +/// window ends nearer to what is read. An ask without a length keeps the +/// 4 MiB grid whatever is set: a root view reads from its address to its +/// window's end, and mesh streams bound that way reach megabytes. +/// shortcut: the default stays 4 MiB until a run with the memory line's +/// window counts has shown what the finer grids give; the same memory +/// asked for with different ranges then lies in more than one window. +fn window() -> u64 { + static GRID: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *GRID.get_or_init(|| { + let kb = std::env::var("VICTORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::<u64>().ok()); + grid(kb) + }) +} + +/// The window grid in bytes for a setting in KiB: a power of two from +/// 64 KiB to 4 MiB, 4 MiB for anything else. +fn grid(kb: Option<u64>) -> u64 { + match kb { + Some(kb) if kb.is_power_of_two() && (64..=4096).contains(&kb) => kb << 10, + _ => WINDOW, + } +} + +/// The window (start, bytes) of title memory for an ask of `[address, +/// end)` on a grid of `grid` bytes. +fn window_of(address: u64, end: u64, grid: u64) -> (u64, u64) { + let start = address & !(grid - 1); + (start, end.next_multiple_of(grid) - start) +} + +/// Whether the window of an ask without a length begins at the ask instead +/// of at the 4 MiB line below it. Such an ask (a root view) reads from its +/// address to the end of its 4 MiB cell; what lies below the lowest +/// address ever asked for in the cell is memory the host zeroed and nothing +/// reads (513 of run 65's 782 windows were asked for that way, 2,052 MB; +/// of all windows' 3,236 MB, 1,988 MB were ever copied). With this on, the +/// window is the cell's tail from the ask's step on ([`TAIL_STEP`]); an ask +/// lower in the cell later makes a longer tail, which every ask from then +/// on takes, and the shorter one goes when nothing holds it any more. +/// shortcut: off unless `VICTORY_WINDOW_TAILS=1`. A longer tail is another +/// host buffer than the shorter one: what was bound to the shorter stays +/// right only because every list brings up to date the copy it bound +/// (`draw.rs` keeps a root view's copy with its slot). It pays only +/// together with `VICTORY_WINDOW_KB` below 4096: on the 4 MiB grid an ask +/// with a length in the same cell makes the whole cell's window, and the +/// tail is that. +fn tails() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOW_TAILS").is_some_and(|v| v == "1")) +} + +/// Tails begin on multiples of this. A longer tail is a new host buffer, +/// filled from title memory from its first byte to its last: begun on the +/// 64 KiB page of each ask, a cell whose asks came from the top down made +/// up to 63 of them, one after the other (part of run 71's copies). On +/// this step it is 15 at most, and a tail holds up to 192 KiB it did not +/// need. +const TAIL_STEP: u64 = 256 << 10; + +/// The window (start, bytes) a tail ask at `address` makes: from the ask's +/// step ([`TAIL_STEP`]) to the end of its 4 MiB cell. +fn tail_of(address: u64, end: u64) -> (u64, u64) { + let (cell, len) = window_of(address, end, WINDOW); + let start = address & !(TAIL_STEP - 1); + (start, cell + len - start) +} + +/// Of `windows` (start, bytes), the one an ask of `[address, end)` that +/// may take any window takes ([`find_any`]): the longest that holds the +/// whole range. +fn holder(windows: impl Iterator<Item = (u64, u64)>, address: u64, end: u64) -> Option<(u64, u64)> { + windows + .filter(|&(start, bytes)| start <= address && start + bytes >= end) + .max_by_key(|&(start, bytes)| (bytes, std::cmp::Reverse(start))) +} + +/// Whether windows may be smaller than their 4 MiB cell (a finer grid, or +/// tails): only then is there more than one window to choose from. +fn fine() -> bool { + tails() || window() < WINDOW +} + +/// For the memory line: the bytes of title memory the windows alive lie +/// over (each byte once), beside the windows' own bytes in +/// [`memory`]: the difference is memory that is in more than one window, +/// which is copied once for each. +#[cfg(feature = "diagnostics")] +pub(crate) fn window_cover() -> u64 { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + cover(loose.keys().copied()) +} + +/// The bytes `windows` (start, bytes; in order of start) lie over, each +/// byte once. +#[cfg_attr(not(any(test, feature = "diagnostics")), allow(dead_code))] +fn cover(windows: impl Iterator<Item = (u64, u64)>) -> u64 { + let (mut covered, mut reached) = (0, 0); + for (start, bytes) in windows { + let end = start + bytes; + if end > reached { + covered += end - start.max(reached); + reached = end; + } + } + covered +} + +/// Of `windows` (start, bytes; in order), the longest tail a tail ask at +/// `address` can take: the first that begins in the ask's cell at or below +/// the ask's page and ends where the cell ends. +fn longest_tail(windows: impl Iterator<Item = (u64, u64)>, address: u64, end: u64) -> Option<(u64, u64)> { + let (cell, len) = window_of(address, end, WINDOW); + let step = address & !(TAIL_STEP - 1); + windows + .filter(|&(start, bytes)| start >= cell && start <= step && start + bytes == cell + len) + .min() +} + /// Copies of title memory outside buffers, by (start, length). static LOOSE: Mutex<BTreeMap<(u64, u64), Arc<Shadow>>> = Mutex::new(BTreeMap::new()); -fn loose(address: u64, end: u64) -> Option<Arc<Shadow>> { - let start = address & !(WINDOW - 1); - let len = end.next_multiple_of(WINDOW) - start; +fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Shadow>> { let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let (cell, _) = window_of(address, end, WINDOW); + let named = window_of(address, end, if unsized_ask { WINDOW } else { window() }); + let (start, len) = if unsized_ask && tails() { + let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key); + longest_tail(there, address, end).unwrap_or_else(|| tail_of(address, end)) + } else if any && fine() && !unsized_ask { + // The windows that begin in the ask's cell at or below the ask (one + // that begins in a cell below and reaches this far is passed over: + // the ask then makes its own). + let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key); + holder(there, address, end).unwrap_or(named) + } else { + named + }; + // Under the lock, with the handing out: see `let_go_idle`. + let note = |shadow: &Shadow| { + shadow.used.store(crate::host::moment(), Ordering::Relaxed); + shadow.asked[0].fetch_min(address, Ordering::Relaxed); + shadow.asked[1].fetch_max(end, Ordering::Relaxed); + if unsized_ask { + shadow.unsized_asks.fetch_add(1, Ordering::Relaxed); + } + }; if let Some(shadow) = map.get(&(start, len)) { + note(shadow); return Some(shadow.clone()); } + // In place, if asked for and the window's memory can be opened: the + // window is the title's own memory, with nothing to copy. + if let Some(placed) = crate::inplace::place_for(start, len, true) { + let shadow = Arc::new(Shadow::placed(placed, start, len, true)); + note(&shadow); + map.insert((start, len), shadow.clone()); + tables_changed(); + return Some(shadow); + } + // In a GPU upload heap, if asked for and there is room: one buffer in + // the card's memory, which the CPU fills and shaders read. + if let Some((buffer, data)) = window_upload_for(len) { + crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} in a GPU upload heap")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.window = true; + shadow.uploaded = len; + let shadow = Arc::new(shadow); + note(&shadow); + map.insert((start, len), shadow.clone()); + tables_changed(); + return Some(shadow); + } let (buffer, data) = host()?.shared_buffer(len)?; crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}")); + // With room for windows on the card (`window_card_most`): shaders get a + // buffer there, and the one just made is the CPU's side. + let (buffer, card) = match window_card_for(len) { + Some(on_card) => { + crate::host::name(&on_card, || format!("title memory {start:#x}+{len:#x} on the card")); + let card = Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size: len, + in_pc: false, + me: std::sync::OnceLock::new(), + }; + (on_card, Some(card)) + } + None => (buffer, None), + }; // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; tracing::debug!( @@ -516,11 +5316,334 @@ fn loose(address: u64, end: u64) -> Option<Arc<Shadow>> { len, "loose memory copied to the host" ); - let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len)); + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.window = true; + if card.is_none() { + WINDOW_PC_BYTES.fetch_add(len, Ordering::Relaxed); + } + shadow.card = card; + let shadow = Arc::new(shadow); + if let Some(card) = &shadow.card { + let _ = card.me.set(Arc::downgrade(&shadow)); + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + } + note(&shadow); map.insert((start, len), shadow.clone()); + tables_changed(); + Some(shadow) +} + +/// Copies of single buffer views' own bytes ([`exact`]), by (start, +/// bytes), each with the asking that last took it; and the askings so far. +#[allow(clippy::type_complexity)] +static EXACT: Mutex<(u64, BTreeMap<(u64, u64), (Arc<Shadow>, u64)>)> = Mutex::new((0, BTreeMap::new())); + +/// Since the last frame line: askings for such copies, and copies made. +static EXACT_STATS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// A copy of the title memory `[address, address + len)` that starts at +/// `address` itself: for a buffer view whose bytes do not start on an +/// element of the copy its buffer has (`descriptor/host.rs` `own_bytes`). +/// A host view counts its first element from its buffer's start; a console +/// view starts at any address, and the title places views at ring +/// positions inside its big GPU heap. Such a view was refused and its slot +/// read zeros ("buffer view not on an element of its host copy", in every +/// run; upstream VIctory 86a5ed6 found its meshlet culling constants and +/// colour-bake parameter blocks among them and gives each a copy of its +/// own bytes, as here). +/// +/// The copy is brought up to date and written back like any other (a list +/// refreshes the copy its view's slot shows, `buffer_copy`). Kept by +/// (start, bytes) for as long as a list or a slot holds it; of the others, +/// those not asked for lately go once there are many (ring positions +/// change every frame). +pub(crate) fn exact(address: u64, len: u64) -> Option<Arc<Shadow>> { + /// Copies kept before the idle ones are looked for, and the askings an + /// idle one stays for. + const MANY: usize = 256; + const LATELY: u64 = 512; + if len == 0 { + return None; + } + EXACT_STATS[0].fetch_add(1, Ordering::Relaxed); + let mut guard = EXACT.lock().unwrap_or_else(|e| e.into_inner()); + let (tick, map) = &mut *guard; + *tick += 1; + let now = *tick; + if let Some((shadow, used)) = map.get_mut(&(address, len)) { + *used = now; + shadow.used.store(crate::host::moment(), Ordering::Relaxed); + return Some(shadow.clone()); + } + if map.len() >= MANY { + // Held by the map alone (no list), its buffer by the copy alone (no + // slot shows it), and not asked for lately. + map.retain(|_, (shadow, used)| { + Arc::strong_count(shadow) > 1 || crate::host::references(&shadow.buffer) > 1 || *used + LATELY > now + }); + } + let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?; + crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let shadow = Arc::new(Shadow::new(buffer, data, gpu, address, len)); + map.insert((address, len), (shadow.clone(), now)); + EXACT_STATS[1].fetch_add(1, Ordering::Relaxed); Some(shadow) } +/// With the frame line: the buffer views that got a copy of their own +/// bytes ([`exact`]), per frame over `frames`, and the copies kept now. +/// Nothing while there are none. +pub(crate) fn exact_line(frames: f64) { + let [asked, made] = [0, 1].map(|i| EXACT_STATS[i].swap(0, Ordering::Relaxed)); + if asked == 0 { + return; + } + let kept = EXACT.lock().unwrap_or_else(|e| e.into_inner()).1.len(); + tracing::info!( + "buffer views off their copy's elements (they were refused and read zeros; VICTORY_VIEW_OWN_COPY=0 refuses them again): \ + {:.1} asked for per frame, {:.1} copies of their own bytes made per frame, {kept} kept", + asked as f64 / frames, + made as f64 / frames + ); +} + +#[cfg(test)] +mod window_tests { + use super::{ + WINDOW, cover, default_card_limits_mb, grid, holder, longest_tail, resolve_card_limits, + tail_of, window_of, + }; + + #[test] + fn card_limits_scale_with_local_vram_budget() { + const GIB: u64 = 1 << 30; + const MIB: u64 = 1 << 20; + + // Unknown (WARP / query failure) and <= 14 GiB keep the 12 GB baseline. + assert_eq!(default_card_limits_mb(None), (16, 512)); + assert_eq!(default_card_limits_mb(Some(8 * GIB)), (16, 512)); + assert_eq!(default_card_limits_mb(Some(12 * GIB)), (16, 512)); + assert_eq!(default_card_limits_mb(Some(14 * GIB)), (16, 512)); + + // 16 GB tier (> 14 GiB, < 20 GiB). + assert_eq!(default_card_limits_mb(Some(15 * GIB)), (4, 2048)); + assert_eq!(default_card_limits_mb(Some(16 * GIB)), (4, 2048)); + + // 24–32+ GB tier (>= 20 GiB): 1 MiB min, 25% of budget capped at 8192 MiB. + assert_eq!(default_card_limits_mb(Some(20 * GIB)), (1, 5120)); + assert_eq!(default_card_limits_mb(Some(24 * GIB)), (1, 6144)); + assert_eq!(default_card_limits_mb(Some(32 * GIB)), (1, 8192)); + assert_eq!(default_card_limits_mb(Some(48 * GIB)), (1, 8192)); + + // Explicit env overrides always win, and min is clamped to at least 1 MiB. + assert_eq!(resolve_card_limits(Some(32 * GIB), Some(8), Some(4096)), (8 * MIB, 4096 * MIB)); + assert_eq!(resolve_card_limits(Some(12 * GIB), Some(0), Some(1024)), (MIB, 1024 * MIB)); + assert_eq!(resolve_card_limits(None, None, None), (16 * MIB, 512 * MIB)); + } + + /// An ask that may take any window takes the longest that holds all of + /// it, and none that holds only a part. + #[test] + fn an_ask_takes_the_longest_window_that_holds_it() { + let cell = 0xd_1200_0000u64; + let (ask, end) = (cell + 0x9_0000, cell + 0xb_0000); + assert_eq!(holder([].into_iter(), ask, end), None); + let there = [ + (cell, 0x4_0000), // ends below the ask + (cell + 0x8_0000, 0x2_0000), // holds its first half only + (cell + 0x8_0000, 0x4_0000), // holds it + (cell + 0x4_0000, 0x10_0000), // holds it, longer + (cell + 0xa_0000, 0x40_0000), // begins above it + ]; + assert_eq!(holder(there.into_iter(), ask, end), Some((cell + 0x4_0000, 0x10_0000))); + // Of two as long, the one that begins lower. + let two = [(cell + 0x8_0000, 0x8_0000), (cell + 0x4_0000, 0x8_0000)]; + assert_eq!(holder(two.into_iter(), ask, end), Some((cell + 0x4_0000, 0x8_0000))); + } + + /// What windows lie over counts each byte once. + #[test] + fn overlapping_windows_cover_their_memory_once() { + assert_eq!(cover([].into_iter()), 0); + let apart = [(0x10_0000u64, 0x4_0000u64), (0x20_0000, 0x4_0000)]; + assert_eq!(cover(apart.into_iter()), 0x8_0000); + // One inside another, one overlapping its end, one touching. + let over = [ + (0x10_0000u64, 0x10_0000u64), + (0x14_0000, 0x4_0000), + (0x1c_0000, 0x8_0000), + (0x24_0000, 0x4_0000), + ]; + assert_eq!(cover(over.into_iter()), 0x18_0000); + } + + /// A tail runs from the ask's page to the end of its 4 MiB cell, and an + /// ask takes the longest tail there is that holds it. + #[test] + fn tails_run_to_the_cells_end_and_the_longest_is_taken() { + let cell = 0xd_1200_0000u64; + let ask = cell + 0x12_3456; + assert_eq!(tail_of(ask, ask + 1), (cell + 0x10_0000, WINDOW - 0x10_0000)); + // The cell's first page: the whole cell, the window there always was. + assert_eq!(tail_of(cell + 0xffff, cell + 0x1_0000), (cell, WINDOW)); + let end = cell + WINDOW; + let tail = |from: u64| (cell + from, WINDOW - from); + // Nothing there, or only tails that begin above the ask. + assert_eq!(longest_tail([].into_iter(), ask, ask + 1), None); + assert_eq!(longest_tail([tail(0x20_0000)].into_iter(), ask, ask + 1), None); + // The longest of those that hold the ask; windows that do not reach + // the cell's end (cut on a finer grid for asks with a length) and + // windows of other cells are not tails. + let there = [ + (cell - WINDOW, WINDOW), + (cell, 0x4_0000), + tail(0x8_0000), + tail(0x10_0000), + (cell + 0x10_0000, 0x4_0000), + tail(0x20_0000), + ]; + assert_eq!(longest_tail(there.into_iter(), ask, ask + 1), Some(tail(0x8_0000))); + let (start, bytes) = tail(0x8_0000); + assert!(start <= ask && start + bytes == end); + // The whole cell's window is the longest tail of all. + let with_whole = [(cell, WINDOW), tail(0x8_0000)]; + assert_eq!(longest_tail(with_whole.into_iter(), ask, ask + 1), Some((cell, WINDOW))); + } + + /// The setting takes powers of two from 64 KiB to 4 MiB; anything else + /// leaves the grid as it was. + #[test] + fn the_grid_is_a_power_of_two_or_the_default() { + assert_eq!(grid(None), WINDOW); + assert_eq!(grid(Some(4096)), WINDOW); + assert_eq!(grid(Some(1024)), 1 << 20); + assert_eq!(grid(Some(256)), 256 << 10); + assert_eq!(grid(Some(64)), 64 << 10); + for bad in [0, 32, 100, 1000, 8192] { + assert_eq!(grid(Some(bad)), WINDOW, "{bad}"); + } + } + + /// A window holds its ask and is cut on the grid; on the default grid + /// it is the window there always was. + #[test] + fn windows_hold_their_ask_on_the_grid() { + let (address, end) = (0xd_1234_5678u64, 0xd_1234_5678u64 + 0x9000); + assert_eq!(window_of(address, end, WINDOW), (0xd_1200_0000, 4 << 20)); + assert_eq!(window_of(address, end, 1 << 20), (0xd_1230_0000, 1 << 20)); + assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 256 << 10)); + // An ask across a grid line takes both cells. + let end = address + 0x4_0000; + assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 512 << 10)); + for g in [64u64 << 10, 256 << 10, 1 << 20, WINDOW] { + let (start, len) = window_of(address, end, g); + assert!(start <= address && start + len >= end); + assert!(start % g == 0 && len % g == 0); + } + } +} + +#[cfg(test)] +mod card_merge_tests { + use super::{Card, Shadow}; + use std::sync::Mutex; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + + /// A plain buffer on the software adapter: what a copy's `buffer` and + /// its card's `staging` are; the merge never touches them. + fn warp_buffer() -> Option<ID3D12Resource> { + // SAFETY: plain DXGI and D3D12 creation calls on the software adapter. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let mut device: Option<ID3D12Device> = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut device).ok()?; + let device = device?; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 64 << 10, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .ok()?; + buffer + } + } + + /// The mixed landing the fetch inside flights must survive, on a real + /// copy in the card's memory and its merge (`Shadow::card_merge_relay`): + /// flights 5, 6, 7 in the air; 5 lands the old way with the queue's + /// count at 7; the title wrote a byte that went up in send 7 into a + /// piece flight 6's shaders write; 6 then lands from its own slot, which + /// holds that byte as it was before send 7. The notes of sends are + /// dropped as `card_dirty` drops them, below the mark the old-way fetch + /// sets (`crate::host::fallback_fetched_mark`): with the mark at the + /// landed plans' send the title's byte survives and the shader's write + /// lands; with the mark at the fetch's count (as before the fix) the + /// title's byte is put back to the card's older one. + #[test] + fn a_title_byte_sent_after_a_flight_survives_its_slot() { + let (Some(buffer), Some(staging)) = (warp_buffer(), warp_buffer()) else { + return; + }; + const LEN: usize = 64 << 10; + let (title_byte, shader_byte) = (100usize, 200usize); + let content: Vec<u8> = (0..LEN).map(|i| (i * 7 + 3) as u8).collect(); + let land = |mark: u64| -> Vec<u8> { + let mut title = content.clone(); + let mut side = content.clone(); + // The title's byte, refreshed into the CPU's side and sent up in send 7. + title[title_byte] ^= 0x5a; + side[title_byte] = title[title_byte]; + let mut shadow = Shadow::new(buffer.clone(), side.as_mut_ptr(), 0, title.as_ptr() as u64, LEN as u64); + shadow.card = Some(Card { + staging: staging.clone(), + before: Mutex::new(None), + dirty: Mutex::default(), + sent: Mutex::new(vec![(title_byte, title_byte + 1, 7)]), + // 0: no card bytes counted (`Drop` takes them off again). + size: 0, + in_pc: false, + me: std::sync::OnceLock::new(), + }); + // As `card_dirty` with the mark set by the old-way fetch. + if let Some(card) = &shadow.card { + card.sent.lock().unwrap().retain(|s| s.2 > mark); + } + // Flight 6's slot: the card's bytes behind its lists, before send 7. + let mut slot = content.clone(); + slot[shader_byte] ^= 0xc3; + let written = shadow.card_merge_relay(0, &slot, 6, &mut Vec::new()); + assert!(written > 0); + drop(shadow); + title + }; + let fixed = land(crate::host::fallback_fetched_mark(true, 7, Some(5))); + assert_eq!(fixed[title_byte], content[title_byte] ^ 0x5a, "the title's byte was lost"); + assert_eq!(fixed[shader_byte], content[shader_byte] ^ 0xc3, "the shader's write did not land"); + // The mark at the fetch's count: the note of send 7 is gone and the + // older card byte is taken for a shader's write. + let before = land(7); + assert_eq!(before[title_byte], content[title_byte]); + } +} + /// For device-removed reports: the copy of title memory whose host range /// starts closest below host GPU address `va`, and where `va` is in it. pub(crate) fn near(va: u64) -> String { @@ -552,140 +5675,3 @@ pub(crate) fn near(va: u64) -> String { } text } - -#[cfg(test)] -mod tests { - use super::*; - use std::ops::Range; - - #[test] - fn partial_match_leaves_unchecked_bytes_visible() { - let mut unchanged = UnchangedPages::default(); - let before = vec![0; PAGE]; - let mut host = before.clone(); - host[PAGE - 1] = 1; - unchanged.begin(PAGE, 2 * PAGE); - - assert!(!unchanged.differs(PAGE, &host[..4], &before[..4])); - assert!(!unchanged.pages[0]); - assert!(unchanged.differs(PAGE, &host, &before)); - assert!(!unchanged.pages[0]); - } - - #[test] - fn snapshot_edges_are_cacheable_and_survive_later_ranges() { - let mut unchanged = UnchangedPages::default(); - unchanged.begin(PAGE - 3, PAGE + 4); - assert!(!unchanged.differs(PAGE - 3, &[1; 3], &[1; 3])); - assert!(!unchanged.differs(PAGE, &[2; 4], &[2; 4])); - assert_eq!(unchanged.pages, [true, true]); - - unchanged.begin(PAGE - 3, PAGE + 4); - assert!(!unchanged.differs(PAGE - 2, &[1; 2], &[1; 2])); - assert!(!unchanged.differs(PAGE + 1, &[2; 2], &[2; 2])); - assert_eq!(unchanged.pages, [true, true]); - } - - #[test] - fn next_submission_checks_the_same_page_again() { - let mut unchanged = UnchangedPages::default(); - unchanged.begin(0, 4); - assert!(!unchanged.differs(0, &[0; 4], &[0; 4])); - unchanged.clear(); - unchanged.begin(0, 4); - assert!(unchanged.differs(0, &[0, 0, 0, 1], &[0; 4])); - } - - // Both versions walk exactly the same declared ranges, in their - // original order. Only the page comparison differs. - fn scan( - host: &[u8], - before: &[u8], - ranges: &[Range<usize>], - mut differs: impl FnMut(usize, &[u8], &[u8]) -> bool, - ) -> usize { - let mut changed = 0; - for range in ranges { - let mut at = range.start; - while at < range.end { - let n = (PAGE - at % PAGE).min(range.end - at); - changed += usize::from(differs(at, &host[at..at + n], &before[at..at + n])); - at += n; - } - } - changed - } - - #[test] - fn overlapping_ranges_match_uncached_comparisons() { - let before = vec![0; 4 * PAGE]; - let mut host = before.clone(); - for at in [2, PAGE - 1, PAGE + 5, 3 * PAGE + 7] { - host[at] = 1; - } - let ranges = [ - 0..4, - 2..2 * PAGE + 3, - PAGE - 2..4 * PAGE, - 2 * PAGE..3 * PAGE, - ]; - let uncached = scan(&host, &before, &ranges, |_, host, before| host != before); - let mut unchanged = UnchangedPages::default(); - unchanged.begin(0, before.len()); - let cached = scan(&host, &before, &ranges, |at, host, before| { - unchanged.differs(at, host, before) - }); - assert_eq!(uncached, 6); - assert_eq!(cached, uncached); - assert_eq!(unchanged.pages, [false, false, true, false]); - } - - // cargo test --release -p victory-gpu benchmark_overlapping_copy_back -- --ignored --nocapture - #[test] - #[ignore = "synthetic CPU release benchmark"] - fn benchmark_overlapping_copy_back() { - use std::hint::black_box; - use std::time::{Duration, Instant}; - - const SIZE: usize = 128 << 20; - let before = vec![0xA5; SIZE]; - let mut host = before.clone(); - for page in (0..SIZE / PAGE).step_by(64) { - host[page * PAGE + PAGE / 2] ^= 0xFF; - } - let ranges: Vec<_> = (0..24).map(|i| i * PAGE + i..SIZE - i * 13).collect(); - let mut baseline = [Duration::ZERO; 5]; - let mut cached = [Duration::ZERO; 5]; - let mut unchanged = UnchangedPages::default(); - for (baseline, cached) in baseline.iter_mut().zip(&mut cached) { - let started = Instant::now(); - let expected = scan( - black_box(&host), - black_box(&before), - black_box(&ranges), - |_, host, before| host != before, - ); - *baseline = started.elapsed(); - - unchanged.clear(); - let started = Instant::now(); - unchanged.begin(0, before.len()); - let actual = scan( - black_box(&host), - black_box(&before), - black_box(&ranges), - |at, host, before| unchanged.differs(at, host, before), - ); - *cached = started.elapsed(); - assert_eq!(actual, expected); - } - baseline.sort_unstable(); - cached.sort_unstable(); - println!( - "median of five runs, 24 overlapping ranges across 128 MiB: {:?} -> {:?} ({:.1}x)", - baseline[2], - cached[2], - baseline[2].as_secs_f64() / cached[2].as_secs_f64(), - ); - } -} diff --git a/crates/victory-gpu/src/shot.rs b/crates/victory-gpu/src/shot.rs new file mode 100644 index 0000000000..d248e5c46f --- /dev/null +++ b/crates/victory-gpu/src/shot.rs @@ -0,0 +1,1086 @@ +//! Diagnostics: one frame taken apart, by the layer itself ("frame shot"). +//! +//! A frame debugger from outside (RenderDoc) wraps the host device and +//! hooks the process: run 263 ended ten seconds in, inside the hook of a +//! streaming program's game capture on that wrapped device, and the driver +//! refused the pipeline library made for the real one. Nothing of that +//! kind happens here: no library is loaded, the device is the one every run +//! uses, and the only commands added are the two kinds the layer records in +//! every run already (a copy of a texture into a read-back buffer, as the +//! saved pictures are made, and a timestamp, as the card meter's). +//! +//! `VICTORY_SHOT=<folder>` switches it on. A shot is taken of the frame +//! after a present at which +//! * the file `take` is found in that folder (it is removed; the script +//! `shot.ps1` makes it), or +//! * the frame is one of `VICTORY_SHOT_AT` (comma-separated, counted from +//! the first frame of 500 draws or more, as `VICTORY_RENDERDOC_AT`). +//! +//! Of that frame the shot keeps, in `<folder>\shot-<frame>-<hhmmss>` (the +//! time of day it began, UTC): +//! * `events.txt`: every draw, dispatch, copy, submission and drop in the +//! order recorded, with the list it was recorded into, the thread, and +//! the place of its timestamp (the lines of `capture::op`: shaders, +//! targets, states, what is read); +//! * `stamps.txt`: the card's clock before each of those commands, so the +//! time to the next one in the same list is that command's; +//! * `snap-*.png`: what a texture held where it left a state shaders +//! write in (render target, depth write, unordered access): the picture +//! a pass left. The title gives its textures' states in a form without +//! states (enhanced barriers), so the layer moves every texture itself, +//! and that is where the copies are made: inside a list +//! (`HostList::transition`) and between lists, in the list that runs +//! before each one (`HostList::prelude`). `snaps.txt` lists them; +//! * `info.txt`, and `done` when everything is written. +//! +//! **Pictures come in parts.** With the title running the PC has one to +//! four gigabytes free (run 269: 3.6 GB in the opening cutscene, 0.9 GB in +//! the first room), and a frame's targets are more than that. A place +//! where a picture can be taken is named by its texture and how many +//! times the texture left a written state before in the frame: the same +//! name in every frame that is built the same way. The shot's own frame +//! takes as many as fit in half of the memory that is free above 0.7 GB +//! (`VICTORY_SHOT_MB` at most, 1024 unless said); when they are written and +//! their buffers gone, a later frame takes the ones still missing, and so +//! on until none is, or a frame gets none. The lines and times are all of +//! the first frame, and are taken even when there is no room for any +//! picture; a picture says which frame it is of. +//! +//! The pictures are read two seconds and eight frames after their frame +//! (every list of it has long run) and written by a thread of their own on +//! the slow cores. Multisampled textures and volumes are not copied; of an +//! array the first six slices' first level; a texture at most eight times +//! a frame; at most `VICTORY_SHOT_MAX` (12) shots a run. + +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering::Relaxed}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +const IDLE: u8 = 0; +const RECORDING: u8 = 1; +const PENDING: u8 = 2; +const SAVING: u8 = 3; +static PHASE: AtomicU8 = AtomicU8::new(IDLE); +/// Whether the frame being recorded keeps its lines and times (a shot's +/// first frame; the later ones only take pictures). +static LINES: AtomicBool = AtomicBool::new(false); + +/// Which frame of which shot is being taken (1, 2, ...): what a list holds +/// for a shot belongs to one. +static SHOT_ID: AtomicU32 = AtomicU32::new(0); + +/// Timestamps of a shot, and how many a list takes at a time. +const SLOTS: u32 = 131_072; +const BLOCK: u32 = 128; +/// The next free timestamp of the shot being taken. +static NEXT: AtomicU32 = AtomicU32::new(0); + +/// Lines a shot holds at most. +const MAX_EVENTS: usize = 400_000; +/// Copies of one texture in a frame. +const REPEATS: u32 = 8; +/// Frames a shot takes its pictures in, at most. +const MAX_PARTS: u32 = 48; +/// When this many lists recorded for a shot's frame have been submitted, +/// the frame is the title's to finish: lists begun from then on are the +/// next frame's (the title records it while the layer still runs this +/// one: run 269's first shot held frame 0x781 and, behind its submissions, +/// all of 0x782), and the present that follows ends the shot's frame. A +/// present before that is of a frame recorded before the shot began, and +/// the shot goes on through it, three presents at most. +const FRAME_LISTS: u32 = 20; +/// Lists of the frame being recorded that the title has submitted. +static SUBMITTED: AtomicU32 = AtomicU32::new(0); + +/// Whether the title has begun to submit the frame being recorded. +fn closing() -> bool { + SUBMITTED.load(Relaxed) >= frame_lists() +} + +/// [`FRAME_LISTS`], or `VICTORY_SHOT_LISTS` if set. The title may go on +/// beginning lists of a frame long after its first twenty are submitted: +/// shot-1785-012256 (run 287) had 34 lists submitted before the frame's +/// lighting lists were begun, took those for the next frame's and holds +/// none of their commands. A number no frame reaches keeps every list +/// begun until the shot's last present (three presents at most): more +/// than one frame, with nothing of it left out. +fn frame_lists() -> u32 { + static LISTS: OnceLock<u32> = OnceLock::new(); + *LISTS.get_or_init(|| number("VICTORY_SHOT_LISTS", u64::from(FRAME_LISTS)).min(u64::from(u32::MAX)) as u32) +} + +/// The title submits `list`, while a shot records. +pub(crate) fn submitted(list: &crate::host::HostList) { + let mark = *list.shot_mark.lock().unwrap_or_else(|e| e.into_inner()); + if mark.0 != 0 && mark.0 == SHOT_ID.load(Relaxed) { + SUBMITTED.fetch_add(1, Relaxed); + } +} +/// Memory left alone (MB), and the least a frame's pictures need. +const RESERVE_MB: u64 = 700; +const LEAST_MB: u64 = 48; +/// The host state copies are read in. +const COPY_SOURCE: u32 = 0x800; + +/// The folder shots go to, if the tool is on. +fn folder() -> Option<&'static PathBuf> { + static FOLDER: OnceLock<Option<PathBuf>> = OnceLock::new(); + FOLDER + .get_or_init(|| { + let folder = PathBuf::from(std::env::var_os("VICTORY_SHOT")?); + if !folder.is_absolute() { + tracing::warn!(folder = %folder.display(), "VICTORY_SHOT is not a full path: no frame shots"); + return None; + } + if let Err(e) = std::fs::create_dir_all(&folder) { + tracing::warn!(error = %e, folder = %folder.display(), "the folder for frame shots could not be made: none are taken"); + return None; + } + tracing::info!( + folder = %folder.display(), + at = ?at(), + "frame shots are on (VICTORY_SHOT): one is taken when the file `take` appears in the folder, and at the frames of VICTORY_SHOT_AT" + ); + Some(folder) + }) + .as_ref() +} + +fn number(name: &str, default: u64) -> u64 { + std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default) +} + +/// `VICTORY_SHOT_AT`: frames counted from the first one of 500 draws. +fn at() -> &'static [u64] { + static AT: OnceLock<Vec<u64>> = OnceLock::new(); + AT.get_or_init(|| { + std::env::var("VICTORY_SHOT_AT").unwrap_or_default().split(',').filter_map(|f| f.trim().parse().ok()).collect() + }) +} + +/// The read-back memory (MB) a frame of a shot may take now. +fn room_mb() -> u64 { + (crate::framelog::free_mb().saturating_sub(RESERVE_MB) / 2).min(number("VICTORY_SHOT_MB", 1024)) +} + +/// A line of the shot. +struct Event { + list: usize, + thread: u32, + /// The place of the timestamp recorded before the command, or none. + stamp: u32, + text: String, +} + +/// A picture of the shot, still in its read-back buffer. +struct Snap { + /// How many times its texture left a written state before in the + /// frame. + occurrence: u32, + name: String, + buffer: ID3D12Resource, + footprint: D3D12_SUBRESOURCE_FOOTPRINT, + bytes: u64, + /// The title's texture (or, unknown, the host copy), its own size and + /// format, the slice copied, and the states it left and went to. + texture: usize, + width: u64, + height: u32, + format: i32, + slice: u32, + before: u32, + after: u32, +} + +/// What a shot carries from one of its frames to the next. +#[derive(Clone, Default)] +struct Carry { + /// The shot's first frame (its folder's name) and why it was taken. + first: u64, + why: String, + /// The time of day (UTC, `hhmmss`) the shot began: the rest of its + /// folder's name. (Two runs' shots of the same frame number went into + /// one folder: runs 270 and 273, `shot-1864`.) + began: u32, + /// Frames taken so far; pictures saved and failed in them. + parts: u32, + saved: u32, + failed: u32, + /// The places done: host copy, occurrence, slice. + done: std::collections::HashSet<(usize, u32, u32)>, + /// Of the first frame: lines, draws and dispatches, presents, places. + lines: usize, + work: u32, + presents: u32, + places: u32, + not_taken: u32, + read_back_mb: u64, +} + +impl Carry { + /// `shot-<first frame>-<hhmmss>`. + fn folder_name(&self) -> String { + format!("shot-{}-{:06}", self.first, self.began) + } +} + +/// The time of day now, UTC, as the number `hhmmss`. +fn hhmmss() -> u32 { + let s = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() % 86_400) as u32; + (s / 3600) * 10_000 + (s / 60 % 60) * 100 + s % 60 +} + +struct Shot { + id: u32, + /// The frame this part is of. + frame: u64, + carry: Carry, + presents: u32, + /// Draws and dispatches among its lines. + work: u32, + events: Vec<Event>, + snaps: Vec<Snap>, + /// Read-back bytes so far, and the most allowed. + bytes: u64, + budget: u64, + /// Places met so far in this frame; how many are left for a later + /// frame; the ones never taken (repeats, too large). + places: u32, + later: u32, + not_taken: u32, + /// Times a texture (host copy) left a written state so far. + per_texture: std::collections::HashMap<usize, u32>, + /// The title's texture by host copy. + titles: std::collections::HashMap<usize, usize>, + /// The ranges of timestamps lists resolved: first place and count. + resolved: Vec<(u32, u32)>, + /// When recording ended, and the frame's number. + stopped: Option<(std::time::Instant, u64)>, +} + +// SAFETY: host objects (free-threaded), handed from the recording threads +// to the one that writes the shot out, behind a lock. +unsafe impl Send for Shot {} + +static SHOT: Mutex<Option<Shot>> = Mutex::new(None); +/// A shot between two of its frames. +static WAITING: Mutex<Option<Carry>> = Mutex::new(None); + +/// The timestamps' heap and where they are read back. +struct Clock { + heap: ID3D12QueryHeap, + back: ID3D12Resource, + /// The read-back buffer's bytes, mapped for good. + mapped: usize, + frequency: u64, +} + +// SAFETY: host objects (free-threaded) and a mapping that is only read. +unsafe impl Send for Clock {} +// SAFETY: as above. +unsafe impl Sync for Clock {} + +static CLOCK: OnceLock<Option<Clock>> = OnceLock::new(); + +fn make_clock() -> Option<Clock> { + if std::env::var_os("VICTORY_SHOT_TIMES").is_some_and(|v| v == "0") { + return None; + } + let host = crate::host::host()?; + let device = host.device(); + let mut heap: Option<ID3D12QueryHeap> = None; + let mut back: Option<ID3D12Resource> = None; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(SLOTS) * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + // SAFETY: plain object creation; the buffer is mapped once and stays so + // (the card meter's heap and buffer, made the same way). + unsafe { + device + .CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: SLOTS, NodeMask: 0 }, &mut heap) + .ok()?; + device + .CreateCommittedResource(&readback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back) + .ok()?; + let (heap, back) = (heap?, back?); + let mut mapped = std::ptr::null_mut(); + back.Map(0, None, Some(&mut mapped)).ok()?; + let frequency = host.timestamp_frequency(); + if mapped.is_null() || frequency == 0 { + return None; + } + Some(Clock { heap, back, mapped: mapped as usize, frequency }) + } +} + +/// Whether a frame is being recorded for a shot. One load: asked at every +/// state change of a texture in every diagnostics run. +pub(crate) fn recording() -> bool { + PHASE.load(Relaxed) == RECORDING +} + +/// Whether the frame being recorded keeps its lines ([`line`]). Asked at +/// every noted command of every diagnostics run. +pub(crate) fn keeping_lines() -> bool { + recording() && LINES.load(Relaxed) +} + +thread_local! { + /// The timestamp [`stamp`] recorded for the line this thread is about + /// to give to [`line`]. + static STAMP: std::cell::Cell<u32> = const { std::cell::Cell::new(u32::MAX) }; + /// The line this thread is about to give to [`line`] is of a list of + /// the next frame ([`stamp`]): not kept. + static NEXT_FRAME: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A fresh block of timestamps, if any are left. +fn take_block() -> Option<u32> { + let base = NEXT.fetch_add(BLOCK, Relaxed); + (base <= SLOTS - BLOCK).then_some(base) +} + +/// Resolves `count` timestamps from `base` in `list` and notes the range. +fn resolve(list: &ID3D12GraphicsCommandList, clock: &Clock, id: u32, base: u32, count: u32) { + // SAFETY: an open list, our heap and our read-back buffer; the places + // are the block's own, and each was ended in this list before. + unsafe { list.ResolveQueryData(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, base, count, &clock.back, u64::from(base) * 8) }; + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = shot.as_mut().filter(|s| s.id == id) { + s.resolved.push((base, count)); + } +} + +/// Before a command of the title is recorded into `list`, while a shot +/// records: the list is marked as one of the shot's frame, and in a frame +/// that keeps its lines the card's clock goes into the list here, for the +/// line that follows ([`line`]). +pub(crate) fn stamp(list: &crate::host::HostList) { + if !recording() { + return; + } + let id = SHOT_ID.load(Relaxed); + { + let mut mark = list.shot_mark.lock().unwrap_or_else(|e| e.into_inner()); + if mark.0 != id { + // A list begun after the frame's lists were submitted is the + // next frame's. + if closing() { + NEXT_FRAME.set(true); + return; + } + let lines = SHOT.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map_or(0, |s| s.events.len()); + *mark = (id, lines as u32); + } + } + if !LINES.load(Relaxed) { + return; + } + let Some(Some(clock)) = CLOCK.get() else { + return; + }; + let mut block = list.shot_block.lock().unwrap_or_else(|e| e.into_inner()); + let (base, used, of) = *block; + let end = |slot: u32| { + // SAFETY: an open list and a place of our heap. + unsafe { list.list.EndQuery(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, slot) }; + }; + let slot = if used == 0 || of != id { + let Some(base) = take_block() else { return }; + *block = (base, 1, id); + base + } else if used == BLOCK - 1 { + // The block's last place ends it; the command opens the next. + end(base + used); + resolve(&list.list, clock, id, base, BLOCK); + let Some(next) = take_block() else { + *block = (0, 0, 0); + return; + }; + *block = (next, 1, id); + next + } else { + *block = (base, used + 1, id); + base + used + }; + end(slot); + STAMP.set(slot); +} + +/// `list` is about to be closed: the block of timestamps it holds is ended +/// and resolved. +pub(crate) fn close(list: &crate::host::HostList) { + let mut block = list.shot_block.lock().unwrap_or_else(|e| e.into_inner()); + let (base, used, of) = std::mem::take(&mut *block); + if used == 0 || of != SHOT_ID.load(Relaxed) { + return; + } + let Some(Some(clock)) = CLOCK.get() else { + return; + }; + // SAFETY: an open list and a place of our heap (a block always keeps + // its last place for this). + unsafe { list.list.EndQuery(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, base + used) }; + resolve(&list.list, clock, of, base, used + 1); +} + +/// A list of the layer's own (the one that runs before a title list, the +/// one that sends changed bytes to the card and hashes them, the one that +/// compares) begins in `cmd`, while a shot's first frame records: the +/// card's clock, for [`span_end`]. The title's commands are a part of the +/// card's frame; these are the rest of it. +pub(crate) fn span_begin(cmd: &ID3D12GraphicsCommandList) -> u32 { + if !keeping_lines() { + return u32::MAX; + } + let Some(Some(clock)) = CLOCK.get() else { + return u32::MAX; + }; + let slot = NEXT.fetch_add(2, Relaxed); + if slot > SLOTS - 2 { + return u32::MAX; + } + // SAFETY: an open list and a place of our heap. + unsafe { cmd.EndQuery(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, slot) }; + slot +} + +/// The list [`span_begin`] timed ends here; `what` is its line, for the +/// title list `list` or none. +pub(crate) fn span_end(cmd: &ID3D12GraphicsCommandList, slot: u32, list: usize, what: impl FnOnce() -> String) { + if slot == u32::MAX { + return; + } + let Some(Some(clock)) = CLOCK.get() else { + return; + }; + // SAFETY: an open list, our heap and read-back buffer, the two places + // `span_begin` took. + unsafe { + cmd.EndQuery(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, slot + 1); + cmd.ResolveQueryData(&clock.heap, D3D12_QUERY_TYPE_TIMESTAMP, slot, 2, &clock.back, u64::from(slot) * 8); + } + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { return }; + if s.carry.parts != 0 || s.events.len() >= MAX_EVENTS { + return; + } + s.resolved.push((slot, 2)); + // SAFETY: a plain query. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + s.events.push(Event { list, thread, stamp: slot, text: what() }); +} + +/// A line of `capture::op`, while a shot's first frame records. +pub(crate) fn line(list: usize, text: &str) { + let stamp = STAMP.replace(u32::MAX); + if NEXT_FRAME.replace(false) { + return; + } + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { return }; + if s.stopped.is_some() || s.carry.parts != 0 || s.events.len() >= MAX_EVENTS { + return; + } + if ["draw ", "indexed ", "mesh ", "indirect ", "dispatch "].iter().any(|k| text.starts_with(k)) { + s.work += 1; + } + // SAFETY: a plain query. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + s.events.push(Event { list, thread, stamp, text: text.to_owned() }); +} + +/// Whether pictures of host format `format` can be shown +/// (`capture::to_rgba`'s formats, by the texture's own format). +fn shows(format: i32) -> bool { + matches!(format, 1..=2 | 9..=16 | 19..=65 | 87..=93) +} + +/// `list` says which title texture a host copy is of, while a shot +/// records (pictures are named after the title's texture, as the lines +/// name targets). +pub(crate) fn known(copy: usize, title: usize) { + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = shot.as_mut() { + s.titles.insert(copy, title); + } +} + +/// Whether `list` was recorded in the frame of the shot being taken, and +/// if so the line its recording began at: for the list that runs before it +/// at submission ([`leaves`] there), which may be made after the frame's +/// present. +pub(crate) fn of_the_frame(list: &crate::host::HostList) -> Option<u32> { + if !matches!(PHASE.load(Relaxed), RECORDING | PENDING) { + return None; + } + let mark = *list.shot_mark.lock().unwrap_or_else(|e| e.into_inner()); + (mark.0 != 0 && mark.0 == SHOT_ID.load(Relaxed)).then_some(mark.1) +} + +/// Whether a move from host state `before` to `after` takes a texture out +/// of a state shaders write in (render target, unordered access, depth +/// write): a place for a picture. +pub(crate) fn might_leave(before: u32, after: u32) -> bool { + const WRITES: u32 = 0x4 | 0x8 | 0x10; + before & WRITES != 0 && before != after && before != COPY_SOURCE +} + +/// Host texture `copy` is about to be moved from state `before` to `after` +/// by commands recorded into `cmd`: either the title's list `recording` +/// itself, or (`begins`: the line that list's recording began at) the list +/// that runs before it at submission. If the texture leaves a state +/// shaders write in, this is a place for a picture: where one is taken, +/// the texture is moved to the copy-source state, copied, and moved back +/// to `before` here, so the caller's own move is recorded as in any +/// other frame (a caller may read "no change of state" as "not used +/// since": the alias copies of `crate::texture` do). +pub(crate) fn leaves( + cmd: &ID3D12GraphicsCommandList, + list: usize, + recording: Option<&crate::host::HostList>, + begins: Option<u32>, + copy: &std::sync::Arc<crate::resource::HostTexture>, + before: u32, + after: u32, +) { + if !might_leave(before, after) { + return; + } + let texture = ©.texture; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + if d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || d.SampleDesc.Count > 1 || !shows(d.Format.0) { + return; + } + let Some(host) = crate::host::host() else { return }; + let key = std::sync::Arc::as_ptr(copy) as usize; + let slices = if d.DepthOrArraySize <= 6 { u32::from(d.DepthOrArraySize) } else { 1 }; + // In the title's own list the copy gets a timestamp of its own, so + // its time is not the command's before it. (A list of the next frame + // has no places.) + if let Some(recording) = recording { + stamp(recording); + if NEXT_FRAME.replace(false) { + return; + } + } + let stamp = STAMP.replace(u32::MAX); + // SAFETY: a plain query. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + // Which place this is: the texture's n-th in the frame. + let (occurrence, title) = { + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { return }; + let met = s.per_texture.entry(key).or_default(); + *met += 1; + (*met - 1, s.titles.get(&key).copied().unwrap_or(key)) + }; + let most = number("VICTORY_SHOT_MB", 1024) << 20; + let mut moved = false; + for slice in 0..slices { + let sub = slice * u32::from(d.MipLevels); + let mut total = 0u64; + // SAFETY: a live device; outputs for one subresource. + unsafe { host.device().GetCopyableFootprints(&d, sub, 1, 0, None, None, None, Some(&mut total)) }; + // Whether the place's picture is taken in this frame; the line of + // a frame that keeps lines says which. + { + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { break }; + let first = s.carry.parts == 0; + if first { + s.places += 1; + } + let what = format!( + "texture {title:#x} n {occurrence} slice {slice} {}x{} f{} leaves state {before:#x} for {after:#x}{}", + d.Width, + d.Height, + d.Format.0, + begins.map_or(String::new(), |b| format!(" at the start of the recording that begins at line {b}")) + ); + let say = |s: &mut Shot, word: &str, why: &str| { + if first && s.events.len() < MAX_EVENTS { + s.events.push(Event { list, thread, stamp: if slice == 0 { stamp } else { u32::MAX }, text: format!("{word} {what}{why}") }); + } + }; + // The same in every frame: a texture's ninth place on, and a + // picture larger than a frame may ever take. + if occurrence >= REPEATS { + if first { + s.not_taken += 1; + } + say(s, "SNAP-NOT", " (the texture's ninth place or later)"); + continue; + } + if total == 0 || total > most { + if first { + s.not_taken += 1; + } + say(s, "SNAP-NOT", " (too large)"); + continue; + } + if s.carry.done.contains(&(key, occurrence, slice)) { + // Taken by an earlier frame of the shot. + continue; + } + if s.bytes + total > s.budget { + s.later += 1; + say(s, "SNAP-LATER", ""); + continue; + } + s.bytes += total; + s.carry.done.insert((key, occurrence, slice)); + say(s, "SNAP", ""); + } + if !moved { + // SAFETY: an open list and a live texture in state `before`. + unsafe { + cmd.ResourceBarrier(&[crate::host::transition( + texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(COPY_SOURCE as i32), + )]); + } + moved = true; + } + let Some((buffer, footprint)) = crate::capture::read_back_of(host.device(), cmd, texture, sub) else { + continue; + }; + let name = format!("snap-{title:x}-n{occurrence}-s{slice}-{}x{}-f{}", d.Width, d.Height, d.Format.0); + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { break }; + s.snaps.push(Snap { + occurrence, + name, + buffer, + footprint: footprint.Footprint, + bytes: total, + texture: title, + width: d.Width, + height: d.Height, + format: d.Format.0, + slice, + before, + after, + }); + } + if moved { + // SAFETY: an open list and a live texture in the copy-source state. + unsafe { + cmd.ResourceBarrier(&[crate::host::transition( + texture, + D3D12_RESOURCE_STATES(COPY_SOURCE as i32), + D3D12_RESOURCE_STATES(before as i32), + )]); + } + } +} + +/// The first frame of 500 draws or more, for `VICTORY_SHOT_AT`. +static WORLD: AtomicU64 = AtomicU64::new(u64::MAX); + +/// Why a shot is taken of the frame after `frame`, if one is. +fn trigger(folder: &std::path::Path, frame: u64) -> Option<String> { + let world = WORLD.load(Relaxed); + if world != u64::MAX && at().contains(&(frame + 1 - world)) { + return Some(format!("frame {} after the first one of 500 draws (VICTORY_SHOT_AT)", frame + 1 - world)); + } + // The file is looked for at every fourth present. + if frame.is_multiple_of(4) { + let take = folder.join("take"); + if take.exists() { + // A file that cannot be removed would ask again at once. + return match std::fs::remove_file(&take) { + Ok(()) => Some("asked for (the file `take`)".to_string()), + Err(e) => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(error = %e, "the file `take` could not be removed: no frame shot for it")); + None + } + }; + } + } + None +} + +/// At the present of `frame`, on the thread that presents; `drawn` is the +/// number of draws run on the host so far. +pub(crate) fn present(frame: u64, drawn: u64) { + let Some(folder) = folder() else { return }; + static LAST: AtomicU64 = AtomicU64::new(0); + if drawn.saturating_sub(LAST.swap(drawn, Relaxed)) >= 500 { + let _ = WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed); + } + match PHASE.load(Relaxed) { + IDLE => { + let waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(carry) = waiting { + // The next frame of a shot: one built like its first (the + // title's frames come in pairs: an even number of frames on). + if (frame + 1 - carry.first).is_multiple_of(2) { + *WAITING.lock().unwrap_or_else(|e| e.into_inner()) = None; + arm(frame + 1, carry, folder); + } + } else if let Some(why) = trigger(folder, frame) { + static TAKEN: AtomicU32 = AtomicU32::new(0); + let most = number("VICTORY_SHOT_MAX", 12); + if u64::from(TAKEN.fetch_add(1, Relaxed)) >= most { + tracing::warn!(most, "frame shot not taken: the run has its most already (VICTORY_SHOT_MAX)"); + } else { + arm(frame + 1, Carry { first: frame + 1, why, began: hhmmss(), ..Default::default() }, folder); + } + } + } + RECORDING => { + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = shot.as_mut() else { + PHASE.store(IDLE, Relaxed); + return; + }; + s.presents += 1; + // The frame's own present is the one after its lists were + // submitted. + let goes_on = !closing() && s.presents < 3; + if s.carry.parts == 0 { + let text = format!( + "PRESENT frame {frame}: {} draws and dispatches recorded since the shot began{}", + s.work, + if goes_on { "; the shot goes on through the next frame" } else { "" } + ); + s.events.push(Event { list: 0, thread: 0, stamp: u32::MAX, text }); + } + if !goes_on { + s.stopped = Some((std::time::Instant::now(), frame)); + PHASE.store(PENDING, Relaxed); + tracing::info!( + frame, + part = s.carry.parts, + lines = s.events.len(), + places = s.places, + pictures = s.snaps.len(), + for_later = s.later, + read_back_mb = s.bytes >> 20, + "frame shot: a frame is recorded; its pictures are read in two seconds" + ); + } + } + PENDING => { + let mut shot = SHOT.lock().unwrap_or_else(|e| e.into_inner()); + let ready = shot + .as_ref() + .and_then(|s| s.stopped) + .is_some_and(|(when, of)| when.elapsed() >= std::time::Duration::from_secs(2) && frame >= of + 8); + if ready && let Some(s) = shot.take() { + PHASE.store(SAVING, Relaxed); + let to = folder.join(s.carry.folder_name()); + let spawned = std::thread::Builder::new().name("victory-shot".into()).spawn(move || { + crate::framelog::keep_on_slow_cores("frame shot"); + let next = save(s, &to); + *WAITING.lock().unwrap_or_else(|e| e.into_inner()) = next; + PHASE.store(IDLE, Relaxed); + }); + if let Err(e) = spawned { + tracing::warn!(error = %e, "frame shot: no thread to write it out; dropped"); + PHASE.store(IDLE, Relaxed); + } + } + } + _ => {} + } +} + +/// Starts a frame of a shot: frame `frame`, the shot's first or (`carry` +/// says) a later one. +fn arm(frame: u64, carry: Carry, folder: &std::path::Path) { + let mut room = room_mb(); + if room < LEAST_MB { + if carry.parts != 0 { + tracing::warn!( + free_mb = crate::framelog::free_mb(), + part = carry.parts, + "frame shot ends here: too little memory free for more of its pictures" + ); + finish(&carry, &folder.join(carry.folder_name()), "ended early: too little memory free for more pictures", 0); + return; + } + // The lines and times need none of it. + room = 0; + } + let lines = carry.parts == 0; + let clock = lines && CLOCK.get_or_init(make_clock).is_some(); + NEXT.store(0, Relaxed); + SUBMITTED.store(0, Relaxed); + let id = SHOT_ID.fetch_add(1, Relaxed) + 1; + tracing::info!( + frame, + part = carry.parts, + pictures_so_far = carry.done.len(), + why = carry.why, + room_mb = room, + free_mb = crate::framelog::free_mb(), + timestamps = clock, + "frame shot: recording the next frame" + ); + *SHOT.lock().unwrap_or_else(|e| e.into_inner()) = Some(Shot { + id, + frame, + carry, + presents: 0, + work: 0, + events: Vec::with_capacity(if lines { 32768 } else { 0 }), + snaps: Vec::new(), + bytes: 0, + budget: room << 20, + places: 0, + later: 0, + not_taken: 0, + per_texture: Default::default(), + titles: Default::default(), + resolved: Vec::new(), + stopped: None, + }); + LINES.store(lines, Relaxed); + PHASE.store(RECORDING, Relaxed); +} + +/// How much of a picture's texture holds anything, from its bytes as the +/// card wrote them: the share of texels with any bit set and, for R32_UINT +/// (the title's packed light, read back as R9G9B9E5), the highest channel +/// value of that reading. The picture says neither: it is scaled to its +/// largest value, so one bright texel leaves every other one black +/// (shot-2705: the screen probes' atlas, "0.0 % not black", one white pixel). +fn holds(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> (f64, f32) { + let n = match format { + 1..=2 => 16, + 9..=16 | 19..=22 => 8, + 23..=47 | 87..=93 => 4, + 48..=59 => 2, + 60..=65 => 1, + _ => return (f64::NAN, 0.0), + }; + let (mut set, mut high) = (0u64, 0f32); + for y in 0..h { + let Some(row) = rows.get(y * pitch..y * pitch + w * n) else { + break; + }; + for texel in row.chunks_exact(n) { + set += u64::from(texel.iter().any(|&b| b != 0)); + if format == 42 { + let v = u32::from_le_bytes([texel[0], texel[1], texel[2], texel[3]]); + let scale = 2f32.powi((v >> 27) as i32 - 24); + for k in 0..3 { + high = high.max((v >> (9 * k) & 0x1ff) as f32 * scale); + } + } + } + } + (set as f64 * 100.0 / (w * h).max(1) as f64, high) +} + +/// Writes one frame of a shot out and lets its buffers go. What the shot +/// carries on, if pictures are left for a later frame. +fn save(shot: Shot, to: &std::path::Path) -> Option<Carry> { + use std::fmt::Write; + use std::io::Write as _; + let started = std::time::Instant::now(); + if let Err(e) = std::fs::create_dir_all(to) { + tracing::warn!(error = %e, folder = %to.display(), "frame shot not saved: no folder"); + return None; + } + let mut carry = shot.carry.clone(); + let part = carry.parts; + if part == 0 { + // Lines: place, list, thread, timestamp's place (-1: none), text. + let mut events = String::with_capacity(shot.events.iter().map(|e| e.text.len() + 40).sum()); + for (seq, e) in shot.events.iter().enumerate() { + let stamp = if e.stamp == u32::MAX { -1 } else { i64::from(e.stamp) }; + let _ = writeln!(events, "{seq}\t{:#x}\t{}\t{stamp}\t{}", e.list, e.thread, e.text.replace(['\n', '\r', '\t'], " ")); + } + if let Err(e) = std::fs::write(to.join("events.txt"), events) { + tracing::warn!(error = %e, folder = %to.display(), "frame shot: its lines could not be written"); + } + // Timestamps: the places lists resolved, as the card wrote them. + let mut stamps = String::new(); + if let Some(Some(clock)) = CLOCK.get() { + let _ = writeln!(stamps, "frequency\t{}", clock.frequency); + for &(base, count) in &shot.resolved { + for slot in base..(base + count).min(SLOTS) { + // SAFETY: a place inside the mapped read-back buffer, + // which the card wrote long ago (or never: then what + // it held). + let ticks = unsafe { std::ptr::read_volatile((clock.mapped as *const u64).add(slot as usize)) }; + let _ = writeln!(stamps, "{slot}\t{ticks}"); + } + } + } + let _ = std::fs::write(to.join("stamps.txt"), stamps); + let _ = std::fs::write( + to.join("snaps.txt"), + "texture\tn\tslice\tfile\tpart\tframe\twidth\theight\tformat\tbefore\tafter\tnot_black_percent\tmean_rgb\ttexels_with_bits_percent\tpacked_high\n", + ); + carry.lines = shot.events.len(); + carry.work = shot.work; + carry.presents = shot.presents; + carry.places = shot.places; + carry.not_taken = shot.not_taken; + } + // Pictures. + let full = std::env::var_os("VICTORY_SHOT_FULL").is_some_and(|v| v == "1"); + let mut list = String::new(); + let (mut saved, mut failed) = (0u32, 0u32); + for snap in shot.snaps { + let f = snap.footprint; + let mut data = std::ptr::null_mut(); + let mut held = (f64::NAN, 0f32); + // SAFETY: the copy finished long ago; the mapping spans the bytes + // the footprint was sized for. + let rgba = unsafe { + if snap.buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() { + None + } else { + let rows = std::slice::from_raw_parts(data.cast::<u8>(), snap.bytes as usize); + let rgba = crate::capture::to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, f.RowPitch as usize, rows); + held = holds(f.Format.0 as u32, f.Width as usize, f.Height as usize, f.RowPitch as usize, rows); + snap.buffer.Unmap(0, None); + rgba + } + }; + let Some(rgba) = rgba else { + failed += 1; + continue; + }; + // Every `step`th pixel each way: 1280 across at most, unless asked. + let step = if full { 1 } else { (f.Width.max(f.Height) as usize).div_ceil(1280).max(1) }; + let (w, h) = ((f.Width as usize).div_ceil(step), (f.Height as usize).div_ceil(step)); + let mut raw = Vec::with_capacity((w * 3 + 1) * h); + let (mut lit, mut sum) = (0u64, [0u64; 3]); + for y in 0..h { + raw.push(0); + for x in 0..w { + let p = &rgba[((y * step) * f.Width as usize + x * step) * 4..][..3]; + raw.extend_from_slice(p); + lit += u64::from(p.iter().any(|&c| c > 8)); + for (s, &c) in sum.iter_mut().zip(p) { + *s += u64::from(c); + } + } + } + let n = (w * h).max(1) as u64; + match std::fs::write(to.join(format!("{}.png", snap.name)), crate::capture::png_rgb(w as u32, h as u32, &raw)) { + Ok(()) => saved += 1, + Err(_) => { + failed += 1; + continue; + } + } + let _ = writeln!( + list, + "{:#x}\t{}\t{}\t{}.png\t{part}\t{}\t{}\t{}\t{}\t{:#x}\t{:#x}\t{:.1}\t{},{},{}\t{:.3}\t{}", + snap.texture, + snap.occurrence, + snap.slice, + snap.name, + shot.frame, + snap.width, + snap.height, + snap.format, + snap.before, + snap.after, + lit as f64 * 100.0 / n as f64, + sum[0] / n, + sum[1] / n, + sum[2] / n, + held.0, + held.1 + ); + } + if let Ok(mut file) = std::fs::OpenOptions::new().append(true).create(true).open(to.join("snaps.txt")) { + let _ = file.write_all(list.as_bytes()); + } + carry.parts += 1; + carry.saved += saved; + carry.failed += failed; + carry.read_back_mb += shot.bytes >> 20; + tracing::info!( + folder = %to.display(), + part, + frame = shot.frame, + pictures = saved, + failed, + for_later = shot.later, + seconds = started.elapsed().as_secs_f64(), + "frame shot: a frame's part is saved" + ); + // More pictures in a later frame, while frames still get some. + if shot.later == 0 { + finish(&carry, to, "complete", 0); + None + } else if (saved == 0 && part != 0) || carry.parts >= MAX_PARTS { + finish(&carry, to, "ended early: a frame got no further picture", shot.later); + None + } else { + Some(carry) + } +} + +/// A shot's last files: `info.txt` and `done`. +fn finish(carry: &Carry, to: &std::path::Path, how: &str, missing: u32) { + let info = format!( + "frame\t{}\nwhy\t{}\nended\t{how}\npresents\t{}\ndraws_and_dispatches\t{}\nlines\t{}\nplaces_for_pictures\t{}\nplaces_never_taken\t{}\n\ + frames_taken_in\t{}\npictures_saved\t{}\npictures_failed\t{}\npictures_missing\t{missing}\nread_back_mb\t{}\n", + carry.first, + carry.why, + carry.presents, + carry.work, + carry.lines, + carry.places, + carry.not_taken, + carry.parts, + carry.saved, + carry.failed, + carry.read_back_mb + ); + let _ = std::fs::write(to.join("info.txt"), info); + let _ = std::fs::write(to.join("done"), ""); + tracing::info!( + folder = %to.display(), + how, + frames = carry.parts, + lines = carry.lines, + places = carry.places, + pictures = carry.saved, + failed = carry.failed, + missing, + "frame shot saved" + ); +} + +#[cfg(test)] +mod tests { + #[test] + fn the_formats_shown_are_the_ones_the_pictures_decode() { + // Every format `shows` names decodes, and one it does not name + // does not (a block-compressed one: never a target). + for format in (1..=2).chain(9..=16).chain(19..=65).chain(87..=93) { + assert!(super::shows(format)); + let pixel = [0u8; 16]; + assert!(crate::capture::to_rgba(format as u32, 1, 1, 16, &pixel).is_some(), "format {format}"); + } + assert!(!super::shows(71)); + assert!(crate::capture::to_rgba(71, 1, 1, 16, &[0u8; 16]).is_none()); + } +} diff --git a/crates/victory-gpu/src/spread.rs b/crates/victory-gpu/src/spread.rs new file mode 100644 index 0000000000..ef60966a9a --- /dev/null +++ b/crates/victory-gpu/src/spread.rs @@ -0,0 +1,260 @@ +//! The title's crowded thread groups get more processors to run on. +//! +//! The title pins its threads as on the console: sixteen logical +//! processors of eight like cores. Measured on a 14700KF (eight fast cores +//! as logical processors 0-15, twelve efficiency cores as 16-27): eleven +//! of its threads, the ones that record lists and run its jobs, share +//! logical processors 8-12, which are two and a half fast cores; a +//! two-second sample found those five 70 to 107 % busy while fast core 7 +//! and the efficiency cores carried no pinned thread at all. The profile +//! of run 236 shows what that costs: code of the recording threads that +//! cannot wait for anything (a load of an atomic, a step in a tree) was +//! on a processor in only 58 to 72 of 100 looks, where the same kind of +//! code on the layer's unpinned submit thread was in 90 to 97. The frame +//! waits about 50 ms for those threads before the submit thread's 80. +//! +//! With `VICTORY_SPREAD=1` a group with more threads than processors may +//! also run on the processors no pinned thread of the title uses: the +//! slow cores by default (`VICTORY_SPREAD_SPARE=<hex mask>`: those +//! instead). The title cannot tell which processor a thread is on (it +//! imports neither `GetCurrentProcessorNumber` nor uses `rdpid`), and a +//! wider set is a place to run, not an order: the scheduler still prefers +//! the fast cores. `VICTORY_SPREAD=alt`: twenty seconds with, twenty +//! without, in turn, each change said in the log, to measure it in one +//! scene. Off by default. + +use std::collections::HashMap; + +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next}; +use windows_sys::Win32::System::SystemInformation::GROUP_AFFINITY; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, GetCurrentProcessId, GetProcessAffinityMask, GetThreadGroupAffinity, OpenThread, SetThreadGroupAffinity, THREAD_QUERY_INFORMATION, + THREAD_SET_INFORMATION, +}; + +/// 0 off, 1 on, 2 in turn. +fn mode() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_SPREAD").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) +} + +/// A pinned thread of the title: the mask the title gave it and the one it +/// has from us. +struct Pinned { + original: usize, + wide: usize, +} + +/// The mask for a group of `threads` threads the title pinned to `mask`: +/// with `spare` added if they are more than its processors. +fn widened(mask: usize, threads: usize, spare: usize) -> usize { + if threads > mask.count_ones() as usize { mask | spare } else { mask } +} + +/// Whether `mask` is a pinning of the title's: some of the console's +/// sixteen logical processors, not all the processors there are. +fn console_pinning(mask: usize, all: usize) -> bool { + mask != 0 && mask != all && mask & !0xFFFF == 0 +} + +/// The ids of this process's threads. +fn threads() -> Vec<u32> { + let mut ids = Vec::new(); + // SAFETY: a snapshot handle, closed below; the entry says its own size. + unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snapshot == INVALID_HANDLE_VALUE { + return ids; + } + let process = GetCurrentProcessId(); + let mut entry: THREADENTRY32 = std::mem::zeroed(); + entry.dwSize = size_of::<THREADENTRY32>() as u32; + let mut more = Thread32First(snapshot, &mut entry) != 0; + while more { + if entry.th32OwnerProcessID == process { + ids.push(entry.th32ThreadID); + } + more = Thread32Next(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + } + ids +} + +/// A thread's mask in processor group 0, if it can be asked. +fn mask_of(thread: HANDLE) -> Option<usize> { + // SAFETY: plain data filled in by the query. + let mut affinity: GROUP_AFFINITY = unsafe { std::mem::zeroed() }; + // SAFETY: an open thread handle and a valid out pointer. + (unsafe { GetThreadGroupAffinity(thread, &mut affinity) } != 0 && affinity.Group == 0).then_some(affinity.Mask) +} + +/// One look at all threads: the title's pinned ones are noted, and each +/// gets its wide mask (`wide`) or the title's own back. +fn pass(pinned: &mut HashMap<u32, Pinned>, all: usize, spare: usize, wide: bool, said: &mut String) { + let ids = threads(); + pinned.retain(|id, _| ids.contains(id)); + let mut open: Vec<(u32, HANDLE, usize)> = Vec::new(); + for id in ids { + // SAFETY: a thread id of this process; the handle is closed below. + let handle = unsafe { OpenThread(THREAD_QUERY_INFORMATION | THREAD_SET_INFORMATION, 0, id) }; + if handle.is_null() { + continue; + } + match mask_of(handle) { + Some(mask) => { + let ours = pinned.get(&id).is_some_and(|p| mask == p.wide || mask == p.original); + if !ours { + if console_pinning(mask, all) { + // New, or the title pinned it again. + pinned.insert(id, Pinned { original: mask, wide: mask }); + } else { + // Not pinned (an id used again by another thread). + pinned.remove(&id); + } + } + open.push((id, handle, mask)); + } + // SAFETY: the handle opened above. + None => unsafe { + CloseHandle(handle); + }, + } + } + let mut groups: HashMap<usize, usize> = HashMap::new(); + for p in pinned.values() { + *groups.entry(p.original).or_default() += 1; + } + for p in pinned.values_mut() { + p.wide = widened(p.original, groups[&p.original], spare); + } + for (id, handle, mask) in open { + if let Some(p) = pinned.get(&id) { + let want = if wide { p.wide } else { p.original }; + if mask != want { + let affinity = GROUP_AFFINITY { Mask: want, Group: 0, Reserved: [0; 3] }; + // SAFETY: an open thread handle and a mask of this system's processors. + if unsafe { SetThreadGroupAffinity(handle, &affinity, std::ptr::null_mut()) } == 0 { + tracing::debug!(id, want, error = %std::io::Error::last_os_error(), "a thread's processors could not be set"); + } + } + } + // SAFETY: the handle opened above. + unsafe { CloseHandle(handle) }; + } + let mut table: Vec<(usize, usize)> = groups.into_iter().collect(); + table.sort(); + let text = table + .iter() + .map(|&(mask, threads)| { + let to = widened(mask, threads, spare); + if to == mask { + format!("{threads} on {mask:#x} ({} processors)", mask.count_ones()) + } else { + format!("{threads} on {mask:#x} ({} processors) -> {to:#x} ({})", mask.count_ones(), to.count_ones()) + } + }) + .collect::<Vec<_>>() + .join("; "); + if text != *said { + tracing::info!("spread: the title's pinned threads by its mask: {text}"); + *said = text; + } +} + +/// Starts the thread that widens the title's crowded groups, if asked for. +pub(crate) fn start() { + static ONCE: std::sync::Once = std::sync::Once::new(); + if mode() == 0 { + return; + } + ONCE.call_once(|| { + let made = std::thread::Builder::new().name("victory-spread".into()).spawn(|| { + let (mut all, mut system) = (0usize, 0usize); + // SAFETY: our own process and valid out pointers. + if unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut all, &mut system) } == 0 || all == 0 { + tracing::warn!("spread: the process's processors could not be asked; nothing is widened"); + return; + } + let spare = match std::env::var("VICTORY_SPREAD_SPARE").ok().and_then(|v| usize::from_str_radix(v.trim_start_matches("0x"), 16).ok()) { + Some(mask) => mask & all, + None => crate::framelog::slow_processors() & all, + }; + if spare == 0 { + tracing::info!("spread: no spare processors (all cores are alike and VICTORY_SPREAD_SPARE names none); nothing is widened"); + return; + } + tracing::info!( + "spread: the title's thread groups with more threads than processors may also run on processors {spare:#x} (VICTORY_SPREAD=1; alt: in turn)" + ); + let epoch = std::time::Instant::now(); + let mut pinned = HashMap::new(); + let mut said = String::new(); + let mut last = None; + loop { + let wide = mode() == 1 || (epoch.elapsed().as_secs() / 20) % 2 == 1; + if mode() == 2 && last != Some(wide) { + tracing::info!( + "the title's crowded thread groups run on more processors from now (VICTORY_SPREAD=alt): {}", + if wide { "ON" } else { "off, as usual" } + ); + } + last = Some(wide); + pass(&mut pinned, all, spare, wide, &mut said); + // Often enough to catch threads the title starts and to turn with the + // twenty-second phases; a pass is a snapshot and a query a thread. + std::thread::sleep(std::time::Duration::from_millis(500)); + } + }); + if let Err(error) = made { + tracing::warn!(%error, "the spread thread could not be started"); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_crowded_groups_are_widened() { + let spare = 0x0FFF_0000; + // eleven threads on five processors: crowded + assert_eq!(widened(0x1F00, 11, spare), 0x0FFF_1F00); + // eight on eight, three on six, one on one: left alone + assert_eq!(widened(0xFF, 8, spare), 0xFF); + assert_eq!(widened(0x3F00, 3, spare), 0x3F00); + assert_eq!(widened(0x2000, 1, spare), 0x2000); + assert_eq!(widened(0x3FFF, 11, spare), 0x3FFF); + assert_eq!(widened(0x3FFF, 15, spare), 0x0FFF_3FFF); + } + + #[test] + fn a_pinning_of_the_title_is_within_the_console_s_sixteen() { + let all = 0x0FFF_FFFF; + assert!(console_pinning(0x1F00, all)); + assert!(console_pinning(0xFFFF, all)); + assert!(!console_pinning(all, all), "not pinned"); + assert!(!console_pinning(0x0FFF_1F00, all), "already wide: not the title's"); + assert!(!console_pinning(0, all)); + // a PC with sixteen processors: all of them is not a pinning + assert!(!console_pinning(0xFFFF, 0xFFFF)); + } + + #[test] + fn this_process_has_threads_and_they_have_masks() { + let ids = threads(); + assert!(!ids.is_empty()); + // SAFETY: a thread id of this process. + let handle = unsafe { OpenThread(THREAD_QUERY_INFORMATION | THREAD_SET_INFORMATION, 0, ids[0]) }; + assert!(!handle.is_null()); + assert!(mask_of(handle).is_some_and(|m| m != 0)); + // SAFETY: the handle opened above. + unsafe { CloseHandle(handle) }; + } +} diff --git a/crates/victory-gpu/src/stats.rs b/crates/victory-gpu/src/stats.rs new file mode 100644 index 0000000000..ff8b042e29 --- /dev/null +++ b/crates/victory-gpu/src/stats.rs @@ -0,0 +1,376 @@ +//! The machine's load, looked at once a second on a thread of its own, for +//! the box in the corner of the picture (`crate::fpsbox`): how busy the +//! processors and the card are and how much memory is left, so that whoever +//! watches the picture sees which of them holds the frame. +//! +//! - Processors: the share of all logical processors that was busy, system +//! wide (`GetSystemTimes`); the processor time of this process, in +//! processors (`GetProcessTimes`: 5.2 means it kept 5.2 of them busy); +//! and its busiest thread, in per cent of one processor +//! (`GetThreadTimes`). A thread near 100 % with the card far from it is a +//! frame held by that thread. +//! - The card: Windows' own counters (`\GPU Engine(*)\Utilization +//! Percentage`, the ones the Task Manager shows), which name the process +//! and the engine of every figure. For the whole card and for this +//! process: the busiest engine's sum, as the Task Manager does it. They +//! work for every maker of cards and load no library of the maker's. +//! - Memory: this process's committed bytes and the PC's free physical +//! memory. (The card's memory is asked of the host by the box itself.) +//! +//! Nothing here touches the title or the card. `VICTORY_FPS_COUNTER=0` or +//! `=fps` never starts the thread. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +/// One look. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct Stats { + /// Per cent of all logical processors busy, system wide. + pub(crate) cpu_all: f32, + /// This process's processor time, in processors. + pub(crate) cores: f32, + /// This process's busiest thread, in per cent of one processor. + pub(crate) top_thread: f32, + /// The card's busiest engine, per cent, all processes; none if the + /// system's counters did not answer. + pub(crate) gpu_all: Option<f32>, + /// The same for this process alone. + pub(crate) gpu_ours: Option<f32>, + /// This process's committed memory, MB. + pub(crate) ram_ours_mb: u32, + /// The PC's free physical memory, MB. + pub(crate) ram_free_mb: u32, +} + +/// The last look, and its number (1 for the first). +static NOW: Mutex<(u64, Option<Stats>)> = Mutex::new((0, None)); + +/// The last look and its number; none before the first. +pub(crate) fn now() -> Option<(u64, Stats)> { + let now = NOW.lock().unwrap_or_else(|e| e.into_inner()); + now.1.map(|s| (now.0, s)) +} + +/// Starts the looks, once. +pub(crate) fn start() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let spawned = std::thread::Builder::new().name("victory-stats".into()).spawn(run); + if let Err(e) = spawned { + tracing::warn!(%e, "the load figures of the corner box have no thread: the box shows the frame rate only"); + } + }); +} + +/// A 100 ns count from the two halves Windows gives. +fn ticks(t: &windows_sys::Win32::Foundation::FILETIME) -> u64 { + u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime) +} + +/// System wide: (idle, busy and idle together), in 100 ns of processor time. +fn system_times() -> Option<(u64, u64)> { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::GetSystemTimes; + let (mut idle, mut kernel, mut user) = (FILETIME::default(), FILETIME::default(), FILETIME::default()); + // SAFETY: three structures the call fills. + if unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } == 0 { + return None; + } + // The kernel's time has the idle time in it. + Some((ticks(&idle), ticks(&kernel) + ticks(&user))) +} + +/// This process's processor time, in 100 ns. +fn process_time() -> u64 { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; + let mut t = [FILETIME::default(); 4]; + let [created, exited, kernel, user] = &mut t; + // SAFETY: our own process and four structures the call fills. + if unsafe { GetProcessTimes(GetCurrentProcess(), created, exited, kernel, user) } == 0 { + return 0; + } + ticks(&t[2]) + ticks(&t[3]) +} + +/// The processor time of each thread of this process, in 100 ns, by thread +/// id. (The snapshot lists every thread of the system: a few thousand +/// entries, about a millisecond.) +fn thread_times() -> HashMap<u32, u64> { + use windows_sys::Win32::Foundation::{CloseHandle, FILETIME, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, + }; + use windows_sys::Win32::System::Threading::{GetCurrentProcessId, GetThreadTimes, OpenThread, THREAD_QUERY_LIMITED_INFORMATION}; + let mut out = HashMap::new(); + // SAFETY: a snapshot handle of our own, closed below; sized structures + // the calls fill; thread handles opened and closed here. + unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snapshot == INVALID_HANDLE_VALUE || snapshot.is_null() { + return out; + } + let pid = GetCurrentProcessId(); + let mut entry = THREADENTRY32 { dwSize: size_of::<THREADENTRY32>() as u32, ..Default::default() }; + let mut more = Thread32First(snapshot, &mut entry) != 0; + while more { + if entry.th32OwnerProcessID == pid { + let thread = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, 0, entry.th32ThreadID); + if !thread.is_null() { + let mut t = [FILETIME::default(); 4]; + let [created, exited, kernel, user] = &mut t; + if GetThreadTimes(thread, created, exited, kernel, user) != 0 { + out.insert(entry.th32ThreadID, ticks(&t[2]) + ticks(&t[3])); + } + CloseHandle(thread); + } + } + more = Thread32Next(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + } + out +} + +/// This process's committed memory and the PC's free physical memory, MB. +fn memory() -> (u32, u32) { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, ..Default::default() }; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = size_of::<MEMORYSTATUSEX>() as u32; + // SAFETY: our own process and sized structures. + unsafe { + K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb); + GlobalMemoryStatusEx(&mut m); + } + ((c.PagefileUsage >> 20) as u32, (m.ullAvailPhys >> 20) as u32) +} + +/// Windows' counters of the card's engines: one figure for each process +/// and engine. +struct Engines { + query: windows_sys::Win32::System::Performance::PDH_HQUERY, + counter: windows_sys::Win32::System::Performance::PDH_HCOUNTER, + /// The answer's memory, kept from look to look (8-byte units: the + /// items hold pointers and doubles). + buffer: Vec<u64>, +} + +/// One figure of [`Engines`]: the process, the engine's kind ("3D", "Copy", +/// "Compute_0", ...) and its per cent. +#[derive(Debug, PartialEq)] +struct Engine { + pid: u32, + kind: String, + percent: f64, +} + +/// What an instance name of the counters says: the process and the kind of +/// engine ("pid_1234_luid_0x0_0x1_phys_0_eng_3_engtype_3D"). +fn parse_instance(name: &str) -> Option<(u32, &str)> { + let rest = name.strip_prefix("pid_")?; + let pid = rest.split('_').next()?.parse().ok()?; + let kind = name.split("engtype_").nth(1)?; + Some((pid, kind)) +} + +/// The busiest kind of engine: every kind's figures summed, the highest +/// sum, 100 at most. For the whole card (`pid` none) or one process. +fn busiest(engines: &[Engine], pid: Option<u32>) -> (f32, HashMap<&str, f64>) { + let mut by_kind: HashMap<&str, f64> = HashMap::new(); + for e in engines.iter().filter(|e| pid.is_none_or(|p| p == e.pid)) { + *by_kind.entry(e.kind.as_str()).or_default() += e.percent; + } + let top = by_kind.values().copied().fold(0.0, f64::max).min(100.0); + (top as f32, by_kind) +} + +impl Engines { + fn open() -> Option<Engines> { + use windows_sys::Win32::System::Performance::{PdhAddEnglishCounterW, PdhCollectQueryData, PdhOpenQueryW}; + let path: Vec<u16> = "\\GPU Engine(*)\\Utilization Percentage".encode_utf16().chain(std::iter::once(0)).collect(); + let (mut query, mut counter) = (std::ptr::null_mut(), std::ptr::null_mut()); + // SAFETY: plain calls with a terminated string and places for the + // two handles, kept for the life of the process. + unsafe { + if PdhOpenQueryW(std::ptr::null(), 0, &mut query) != 0 { + return None; + } + if PdhAddEnglishCounterW(query, path.as_ptr(), 0, &mut counter) != 0 { + return None; + } + // The first collection has nothing to compare with: a figure + // comes from the second on. + PdhCollectQueryData(query); + } + Some(Engines { query, counter, buffer: Vec::new() }) + } + + /// The figures since the last call. + fn look(&mut self) -> Option<Vec<Engine>> { + use windows_sys::Win32::System::Performance::{ + PDH_FMT_COUNTERVALUE_ITEM_W, PDH_FMT_DOUBLE, PDH_MORE_DATA, PdhCollectQueryData, PdhGetFormattedCounterArrayW, + }; + // SAFETY: our own handles; the buffer is as long as the size given, + // and the items and the names they point at lie inside it until the + // next call. + unsafe { + if PdhCollectQueryData(self.query) != 0 { + return None; + } + let (mut bytes, mut count) = (0u32, 0u32); + let status = PdhGetFormattedCounterArrayW(self.counter, PDH_FMT_DOUBLE, &mut bytes, &mut count, std::ptr::null_mut()); + if status != PDH_MORE_DATA || bytes == 0 { + return None; + } + // Instances come and go between the two calls: some room over. + bytes += 16 << 10; + self.buffer.resize((bytes as usize).div_ceil(8), 0); + let items = self.buffer.as_mut_ptr().cast::<PDH_FMT_COUNTERVALUE_ITEM_W>(); + if PdhGetFormattedCounterArrayW(self.counter, PDH_FMT_DOUBLE, &mut bytes, &mut count, items) != 0 { + return None; + } + let mut out = Vec::with_capacity(count as usize); + for item in std::slice::from_raw_parts(items, count as usize) { + if item.szName.is_null() || item.FmtValue.CStatus != 0 { + continue; + } + let len = (0..512).take_while(|&i| *item.szName.add(i) != 0).count(); + let name = String::from_utf16_lossy(std::slice::from_raw_parts(item.szName, len)); + if let Some((pid, kind)) = parse_instance(&name) { + out.push(Engine { pid, kind: kind.to_owned(), percent: item.FmtValue.Anonymous.doubleValue }); + } + } + Some(out) + } + } +} + +/// The thread: a look a second, for as long as the process runs. +fn run() { + let mut engines = Engines::open(); + if engines.is_none() { + tracing::info!("the system's counters of the card's engines did not open: the corner box shows no card load"); + } + let processors = std::thread::available_parallelism().map_or(1, |n| n.get()) as f64; + // SAFETY: a plain call. + let pid = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessId() }; + let mut last = (Instant::now(), system_times(), process_time(), thread_times()); + let mut looks = 0u64; + loop { + std::thread::sleep(Duration::from_secs(1)); + let now = (Instant::now(), system_times(), process_time(), thread_times()); + // 100 ns of wall time since the last look. + let wall = (now.0 - last.0).as_secs_f64() * 1e7; + if wall <= 0.0 { + continue; + } + let cpu_all = match (last.1, now.1) { + (Some((idle0, all0)), Some((idle1, all1))) if all1 > all0 => { + 100.0 * (1.0 - (idle1.saturating_sub(idle0)) as f64 / (all1 - all0) as f64) + } + _ => 0.0, + }; + let cores = now.2.saturating_sub(last.2) as f64 / wall; + let top_thread = now + .3 + .iter() + .map(|(id, &t)| t.saturating_sub(last.3.get(id).copied().unwrap_or(t))) + .max() + .unwrap_or(0) as f64 + / wall + * 100.0; + let looked = engines.as_mut().and_then(Engines::look); + let (gpu_all, gpu_ours) = match &looked { + Some(e) => (Some(busiest(e, None).0), Some(busiest(e, Some(pid)).0)), + None => (None, None), + }; + let (ram_ours_mb, ram_free_mb) = memory(); + let stats = Stats { + cpu_all: cpu_all.clamp(0.0, 100.0) as f32, + cores: cores.clamp(0.0, processors) as f32, + top_thread: top_thread.clamp(0.0, 100.0) as f32, + gpu_all, + gpu_ours, + ram_ours_mb, + ram_free_mb, + }; + looks += 1; + *NOW.lock().unwrap_or_else(|e| e.into_inner()) = (looks, Some(stats)); + // In the log every fifth look, with the card's engines by kind: the + // box has room for one figure only. + if looks.is_multiple_of(5) { + let kinds = |pid: Option<u32>| { + let Some(e) = &looked else { return "not known".to_owned() }; + let mut kinds: Vec<(&str, f64)> = busiest(e, pid).1.into_iter().filter(|(_, p)| *p >= 0.5).collect(); + kinds.sort_by(|a, b| b.1.total_cmp(&a.1)); + if kinds.is_empty() { + return "nothing at work".to_owned(); + } + kinds.iter().map(|(k, p)| format!("{k} {p:.0} %")).collect::<Vec<_>>().join(", ") + }; + tracing::info!( + "the machine's load over the last second (the corner box's figures): processors {:.0} % busy, all programs; this \ + process kept {:.1} of {processors:.0} processors busy, its busiest thread {:.0} % of one; the card's engines, all \ + programs: {}; this process's: {}; this process has {} MB committed, the PC {} MB of memory free", + stats.cpu_all, + stats.cores, + stats.top_thread, + kinds(None), + kinds(Some(pid)), + stats.ram_ours_mb, + stats.ram_free_mb, + ); + } + last = now; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_instance_name_says_the_process_and_the_engine() { + assert_eq!(parse_instance("pid_1234_luid_0x00000000_0x0000E3B5_phys_0_eng_0_engtype_3D"), Some((1234, "3D"))); + assert_eq!(parse_instance("pid_8_luid_0x0_0x1_phys_0_eng_5_engtype_Compute_0"), Some((8, "Compute_0"))); + assert_eq!(parse_instance("_Total"), None); + assert_eq!(parse_instance("pid_x_engtype_3D"), None); + } + + #[test] + fn the_cards_load_is_its_busiest_kind_of_engine() { + let e = |pid, kind: &str, percent| Engine { pid, kind: kind.to_owned(), percent }; + let engines = [e(1, "3D", 30.0), e(2, "3D", 25.0), e(1, "Copy", 40.0), e(2, "VideoEncode", 70.0), e(1, "3D", 5.0)]; + // All programs: 3D 60, Copy 40, VideoEncode 70. + assert_eq!(busiest(&engines, None).0, 70.0); + // Process 1: 3D 35, Copy 40. + assert_eq!(busiest(&engines, Some(1)).0, 40.0); + assert_eq!(busiest(&engines, Some(9)).0, 0.0); + // Sums over 100 (several engines of a kind) show as 100. + assert_eq!(busiest(&[e(1, "3D", 80.0), e(1, "3D", 60.0)], None).0, 100.0); + } + + /// The looks that need no card: they answer on any machine. + #[test] + fn the_processors_and_the_memory_answer() { + let (idle, all) = system_times().expect("system times"); + assert!(all >= idle && all > 0); + // Some work, so that this thread has time to show. + let mut x = 0u64; + for i in 0..20_000_000u64 { + x = x.wrapping_mul(31).wrapping_add(i); + } + std::hint::black_box(x); + assert!(process_time() > 0); + let threads = thread_times(); + assert!(!threads.is_empty(), "this process has threads"); + let (ours, free) = memory(); + assert!(ours > 0 && free > 0); + } +} diff --git a/crates/victory-gpu/src/texback.rs b/crates/victory-gpu/src/texback.rs new file mode 100644 index 0000000000..f4465553ef --- /dev/null +++ b/crates/victory-gpu/src/texback.rs @@ -0,0 +1,407 @@ +//! Textures shaders write that the title's own code then reads on the CPU. +//! On the console the CPU and the GPU share memory, so what a compute pass +//! stores into a texture is in title memory for the CPU to read. Here it stays +//! in the texture's host copy. The title's ocean is one: its wave passes write +//! a 256x256 height map (R32_FLOAT) and a displacement map (R32G32_FLOAT), and +//! its CPU code samples both, which is what boats float on; it read memory +//! nothing had written (run rw1, `VICTORY_READ_WATCH=1`: about 30 places in +//! the title read those two kinds), and boats sank. +//! +//! For textures of the kinds in `VICTORY_TEXTURE_BACK` (comma-separated +//! `<width>x<height>f<format>`; `1` for the four water formats found by +//! the upstream trace), a list in which shaders write one copies it +//! into a read-back buffer of ours when it closes, and once the list has run +//! the texels are tiled into the texture's title memory in the console's +//! layout, as the console's GPU would have left them. +//! +//! shortcut: by kind, not by texture: textures of those kinds the title never +//! reads are copied back too (about a megabyte per such list). The copy shows +//! what the list's last write left; a title read in between sees the frame +//! before, as it would before the console's GPU has run. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::object::This; + +/// The kinds copied back: (width, height, format). +fn kinds() -> &'static [(u64, u32, u32)] { + static KINDS: OnceLock<Vec<(u64, u32, u32)>> = OnceLock::new(); + KINDS.get_or_init(|| { + const DEFAULT: &str = "256x256f41,256x256f16,64x64f16,128x128f36"; + let list = match std::env::var("VICTORY_TEXTURE_BACK").as_deref() { + Ok("1") => DEFAULT.to_owned(), + Ok(spec) => spec.to_owned(), + Err(_) => String::new(), + }; + let kinds: Vec<(u64, u32, u32)> = list + .split(',') + .filter_map(|k| { + let (size, format) = k.trim().split_once('f')?; + let (w, h) = size.split_once('x')?; + Some((w.parse().ok()?, h.parse().ok()?, format.parse().ok()?)) + }) + .collect(); + if !kinds.is_empty() { + tracing::info!(?kinds, "textures of these kinds that shaders write are copied back into title memory (VICTORY_TEXTURE_BACK)"); + } + kinds + }) +} + +/// Whether title texture `resource` is of a kind copied back. +pub(crate) fn wanted(resource: This) -> bool { + let kinds = kinds(); + !kinds.is_empty() + && crate::resource::texture_kind(resource).is_some_and(|k| kinds.contains(&k)) +} + +/// An outstanding write to a specific allocation. Mapping and resource +/// changes invalidate only the writes that could touch the replaced memory. +struct Ticket { + owner: usize, + at: usize, + end: usize, + valid: AtomicBool, +} + +static TICKETS: Mutex<Vec<Weak<Ticket>>> = Mutex::new(Vec::new()); +static TRACKING: AtomicBool = AtomicBool::new(false); + +fn track(owner: usize, at: usize, end: usize) -> Arc<Ticket> { + let ticket = Arc::new(Ticket { owner, at, end, valid: AtomicBool::new(true) }); + let mut tickets = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); + tickets.retain(|weak| weak.strong_count() != 0); + tickets.push(Arc::downgrade(&ticket)); + TRACKING.store(true, Ordering::Relaxed); + ticket +} + +fn invalidate(matches: impl Fn(&Ticket) -> bool) { + if !TRACKING.load(Ordering::Relaxed) { + return; + } + TICKETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|weak| { + let Some(ticket) = weak.upgrade() else { return false }; + if matches(&ticket) { + ticket.valid.store(false, Ordering::Release); + } + true + }); +} + +pub(crate) fn released(owner: usize) { + invalidate(|ticket| ticket.owner == owner); +} + +pub(crate) fn replaced(at: usize) { + invalidate(|ticket| ticket.at == at); +} + +pub(crate) fn remapped(at: usize, len: usize) { + let end = at.saturating_add(len); + invalidate(|ticket| at < ticket.end && ticket.at < end); +} + +pub(crate) struct Target { + pub(crate) copy: Arc<crate::resource::HostTexture>, + layout: victory_formats::texture::Layout, + ticket: Arc<Ticket>, +} + +impl Target { + pub(crate) fn new(resource: This) -> Option<Self> { + // Keep the host copy independently of the title's resource lifetime. + let copy = crate::resource::host_copy(resource)?; + let _mapping = crate::watch::title_memory_reading(); + let (layout, at, size) = crate::resource::title_texture(resource)?; + let end = at.checked_add(size).filter(|&end| at != 0 && end > at)?; + let ticket = track(resource as usize, at, end); + Some(Self { copy, layout, ticket }) + } + + pub(crate) fn owner(&self) -> usize { self.ticket.owner } +} + +/// The readback resources and the allocation the pixels belong to. +pub(crate) struct Back { + buffer: ID3D12Resource, + footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>, + rows: Vec<u32>, + mips: u32, + layout: victory_formats::texture::Layout, + ticket: Arc<Ticket>, +} + +impl Back { + pub(crate) fn range(&self) -> (usize, usize) { + (self.ticket.at, self.ticket.end) + } +} + +/// Records a host copy from a texture already in COPY_SOURCE. +pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option<Back> { + if !target.ticket.valid.load(Ordering::Acquire) { + return None; + } + let host = crate::host::host()?; + let texture = &target.copy.texture; + // SAFETY: a live texture kept through the command list's state tracking. + let desc = unsafe { texture.GetDesc() }; + let mips = u32::from(desc.MipLevels.max(1)); + let subresources = mips * u32::from(desc.DepthOrArraySize.max(1)); + let n = subresources as usize; + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; + let mut rows = vec![0u32; n]; + let mut total = 0u64; + // SAFETY: out arrays of `n` entries. + unsafe { + host.device.GetCopyableFootprints( + &desc, + 0, + subresources, + 0, + Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), + None, + Some(&mut total), + ) + }; + // The last footprint's advertised extent can omit row-end padding. + // The tiler reads a pitched slice, so the mapped buffer must include it. + for (footprint, &rows) in footprints.iter().zip(&rows) { + let format = footprint.Footprint; + let pitched = u64::from(format.RowPitch) + .checked_mul(u64::from(rows))? + .checked_mul(u64::from(format.Depth))?; + total = total.max(footprint.Offset.checked_add(pitched)?); + } + let buffer = host.read_back_buffer(total)?; + // With device-removed data on: a page fault in it, alive or freed, is + // reported under this name (it was "unnamed"). + crate::host::name_frame(&buffer, || format!("texback read-back buffer of {total} bytes")); + for (i, footprint) in footprints.iter().enumerate() { + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 }, + }; + // SAFETY: an open list; the texture is in the copy-source state. + unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + Some(Back { buffer, footprints, rows, mips, layout: target.layout, ticket: target.ticket }) +} + +/// Whether texture read-backs are written into title memory by a thread of +/// their own (`VICTORY_TEXBACK_ASYNC`; on unless `0`). +/// +/// Try 6.13, ported from trustno1-coder/VIctory-NVIDIA 2d1dc382 (Indy2l; +/// GPL-3.0-or-later). Writing one takes the lock against mapping changes +/// ([`crate::watch::title_memory_reading`]), and while the title streams the +/// world it changes mappings all the time: on the thread that lands +/// submissions the wait for that lock stood 124-416 ms in some frames (a 16 GB +/// machine with an RTX 3060, two to ten 350 KB water maps a frame), and with +/// it the landing of everything else. Here the landing thread only copies the +/// texels out of the read-back buffer; the waiting, tiling and writing go to +/// [`writer`]. Of several copies of one texture waiting there only the newest +/// is written: the title reads the frame before at most, which it may on the +/// console too. +fn asynchronous() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXBACK_ASYNC").is_none_or(|v| v != "0")) +} + +/// A read-back's texels taken out of its buffer, to be tiled into title memory. +struct Landing { + footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>, + rows: Vec<u32>, + mips: u32, + layout: victory_formats::texture::Layout, + ticket: Arc<Ticket>, + /// The read-back buffer's bytes, from 0 to the end of its last subresource. + data: Vec<u8>, +} + +/// Once the list has run, tile its texels back into the same title allocation +/// (on [`writer`]'s thread when [`asynchronous`]). +pub(crate) fn land(back: &Back) { + if !back.ticket.valid.load(Ordering::Acquire) { + stale(); + return; + } + let len = back + .footprints + .iter() + .zip(&back.rows) + .map(|(f, &rows)| f.Offset as usize + f.Footprint.RowPitch as usize * rows as usize * f.Footprint.Depth as usize) + .max() + .unwrap_or(0); + let mut mapped = std::ptr::null_mut(); + // SAFETY: our read-back buffer, written by the list that has run; `len` + // ends with its last subresource, which it holds (`record` made it so). + let data = unsafe { + if back.buffer.Map(0, None, Some(&mut mapped)).is_err() || mapped.is_null() { + return; + } + let data = std::slice::from_raw_parts(mapped.cast::<u8>().cast_const(), len).to_vec(); + back.buffer.Unmap(0, None); + data + }; + let landing = Landing { + footprints: back.footprints.clone(), + rows: back.rows.clone(), + mips: back.mips, + layout: back.layout.clone(), + ticket: back.ticket.clone(), + data, + }; + match asynchronous().then(writer).flatten() { + Some(writer) => writer.send(landing), + None => write(&landing), + } +} + +fn stale() { + static STALE: AtomicU64 = AtomicU64::new(0); + let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1; + if skipped.is_power_of_two() { + tracing::info!(skipped, "skipping texture readbacks whose title allocation changed"); + } +} + +/// The writer's waits for the locks and its work, in microseconds, and the +/// landings it wrote and the ones a newer copy replaced (for the log). +static WRITER_STATS: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// Tiles a read-back's texels into its title allocation. +fn write(landing: &Landing) { + static COPIED: AtomicU64 = AtomicU64::new(0); + let asked = std::time::Instant::now(); + let _mapping = crate::watch::title_memory_reading(); + let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); + let working = std::time::Instant::now(); + WRITER_STATS[0].fetch_add((working - asked).as_micros() as u64, Ordering::Relaxed); + if !landing.ticket.valid.load(Ordering::Acquire) { + stale(); + return; + } + let (at, end) = (landing.ticket.at, landing.ticket.end); + let size = end - at; + let mut tiled = vec![0u8; size]; + // Keep title bytes the subresources do not cover. + if !crate::host::read_into(at as *const u8, &mut tiled) { + return; + } + for (i, (footprint, &rows)) in landing.footprints.iter().zip(&landing.rows).enumerate() { + let (mip, slice) = (i as u32 % landing.mips, i as u32 / landing.mips); + let f = footprint.Footprint; + let pitch = f.RowPitch as usize; + let from = footprint.Offset as usize; + let Some(linear) = landing.data.get(from..from + pitch * rows as usize * f.Depth as usize) else { + return; + }; + if let Err(e) = landing.layout.tile(&mut tiled, mip, slice, linear, pitch, pitch * rows as usize) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(?e, mip, slice, "a texture copied back could not be tiled")); + return; + } + } + crate::host::copy_mapped(at as *mut u8, tiled.as_ptr(), size, true); + WRITER_STATS[1].fetch_add(working.elapsed().as_micros() as u64, Ordering::Relaxed); + WRITER_STATS[2].fetch_add(1, Ordering::Relaxed); + let copied = COPIED.fetch_add(1, Ordering::Relaxed) + 1; + if copied == 1 || copied.is_multiple_of(128) { + tracing::info!( + copied, + bytes = size, + waited_ms = WRITER_STATS[0].load(Ordering::Relaxed) / 1000, + worked_ms = WRITER_STATS[1].load(Ordering::Relaxed) / 1000, + replaced = WRITER_STATS[3].load(Ordering::Relaxed), + on_own_thread = asynchronous(), + "texture readback landed (so far: waits for the mapping lock, work, older copies replaced by newer; VICTORY_TEXBACK_ASYNC=0 writes them where they land)" + ); + } +} + +/// The thread that writes read-backs into title memory, and what waits for it. +struct Writer { + /// By title address: the newest landing for that allocation. + waiting: Mutex<std::collections::HashMap<usize, Landing>>, + more: std::sync::Condvar, +} + +impl Writer { + fn send(&self, landing: Landing) { + let mut waiting = self.waiting.lock().unwrap_or_else(|e| e.into_inner()); + if waiting.insert(landing.ticket.at, landing).is_some() { + WRITER_STATS[3].fetch_add(1, Ordering::Relaxed); + } + drop(waiting); + self.more.notify_one(); + } +} + +/// The writer, if its thread could be started (if not, landings are written +/// where they are made, as before). +fn writer() -> Option<&'static Writer> { + static WRITER: OnceLock<Option<&'static Writer>> = OnceLock::new(); + *WRITER.get_or_init(|| { + let writer: &'static Writer = Box::leak(Box::new(Writer { + waiting: Mutex::new(std::collections::HashMap::new()), + more: std::sync::Condvar::new(), + })); + let started = std::thread::Builder::new().name("texture read-backs".into()).spawn(move || { + loop { + let batch: Vec<Landing> = { + let mut waiting = writer.waiting.lock().unwrap_or_else(|e| e.into_inner()); + while waiting.is_empty() { + waiting = writer.more.wait(waiting).unwrap_or_else(|e| e.into_inner()); + } + waiting.drain().map(|(_, landing)| landing).collect() + }; + for landing in &batch { + write(landing); + } + } + }); + match started { + Ok(_) => Some(writer), + Err(e) => { + tracing::warn!(error = %e, "no thread for texture read-backs: they are written where they land"); + None + } + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_readbacks_for_changed_allocations_are_invalidated() { + let first = track(91, 0x1000, 0x2000); + let next = track(92, 0x2000, 0x3000); + let far = track(93, 0x4000, 0x5000); + + remapped(0x0f00, 0x200); + assert!(!first.valid.load(Ordering::Acquire)); + assert!(next.valid.load(Ordering::Acquire)); + replaced(0x2000); + assert!(!next.valid.load(Ordering::Acquire)); + assert!(far.valid.load(Ordering::Acquire)); + + released(93); + assert!(!far.valid.load(Ordering::Acquire)); + assert!(track(94, 0x2000, 0x3000).valid.load(Ordering::Acquire)); + } +} diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index ea76b691a8..ba231edcda 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -15,7 +15,6 @@ //! (directly indexed views are not known per draw); plane 0 is uploaded //! (every mip and array slice), depth and stencil planes are not. -use std::cell::RefCell; use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -35,6 +34,9 @@ macro_rules! once { /// texture's subresources, and what was last detiled. pub(crate) struct Staging { buffer: ID3D12Resource, + /// The size class the buffer goes back to the pool as when the last + /// holder lets go (`crate::host::take_staging`; 0: not kept). + class: u64, /// Its bytes. #[cfg(feature = "diagnostics")] size: u64, @@ -44,8 +46,36 @@ pub(crate) struct Staging { layout: victory_formats::texture::Layout, /// Mips per array slice. mips: u32, + /// The staging buffer's bytes (counted in `STAGED` while it lives). + bytes: u64, memory: *const u8, last: Mutex<Last>, + /// Whether the staging buffer was detiled since a submitted list last + /// uploaded it, and whether one has uploaded it at all: a list records + /// the upload only then. (Every list that sampled a title texture + /// uploaded all of it again, changed or not: 5,411 subresource copies + /// of 1,120 textures in one frame of run 18.) + dirty: std::sync::atomic::AtomicBool, + uploaded: std::sync::atomic::AtomicBool, + /// When a list last recorded a use of it (`crate::host::moment`). + used: std::sync::atomic::AtomicU64, + /// Levels on demand (`crate::tiles`): the texture's host copy was made + /// without memory of its own when the staging buffer was made. + on_demand: bool, + /// For such a texture: the levels that were the title's at the last + /// detiling (a bit a level; the staging buffer holds zeros for the + /// others), and what that was judged by ([`Staging::judgement`]). + detiled: std::sync::atomic::AtomicU32, + judged: [std::sync::atomic::AtomicU64; 2], + /// For such a texture: when an upload last left a held level without + /// tiles (`crate::host::moment`, never 0; 0: none did). The upload is + /// recorded again about a second later if the card has room by then + /// ([`upload`]). + waiting: std::sync::atomic::AtomicU64, + /// For such a texture: the largest levels the last detile left out for + /// the texture rush (`crate::tiles::rush_levels`; a bit a level, 0: + /// none). Detiled again with every level once the rush is over. + rushed: std::sync::atomic::AtomicU32, } /// What a texture's staging buffer holds: the hash of the memory detiled @@ -54,6 +84,11 @@ pub(crate) struct Staging { struct Last { hash: Option<blake3::Hash>, asked: u64, + /// The frame a partly mapped texture was last read in. + partial: Option<u64>, + /// The frame it was read in ahead of its submission + /// ([`Staging::refresh_ahead`]). + ahead: Option<u64>, } // SAFETY: the staging mapping is written only at submission, under @@ -64,77 +99,477 @@ unsafe impl Sync for Staging {} static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None); +/// The buffer a texture the host writes is copied through into the texture +/// of a view the title placed in its memory in another format +/// ([`alias`]): every level of every layer as each of the two formats lays +/// it out for a copy (the same bytes: the texels are as wide), the written +/// texture's layout first. +struct Through { + buffer: ID3D12Resource, + parts: Vec<( + D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + )>, +} + +/// The most levels times layers [`alias`] copies (a cube of nine levels). +const ALIAS_PARTS: u32 = 54; + +// SAFETY: a device-local buffer only lists record copies with. +unsafe impl Send for Through {} +// SAFETY: as above. +unsafe impl Sync for Through {} + +/// The copy buffers of [`alias`], by the placed view's texture. +static THROUGH: Mutex<Option<HashMap<usize, Arc<Through>>>> = Mutex::new(None); + +/// Brings `placed`, the texture of a view the title placed in the memory +/// of `source` in another format (`crate::resource::alias_of`), up to date +/// with what the host wrote to `source`: the texels of every level and +/// layer are copied as they are, through a buffer (the host copies between +/// two formats of one texel width in no other way). Recorded the first time +/// the list reads the view +/// and again whenever the list used `source` in another way since (wrote +/// it, or read it itself). Leaves `placed` in the copy destination state, +/// as [`upload`] does. False if the copy cannot be made: the caller fills +/// the texture from title memory, as before. +pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { + const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8; + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let (Some(to), Some(from)) = ( + crate::resource::host_resource(placed), + crate::resource::host_resource(source), + ) else { + return false; + }; + let Some(host) = host() else { return false }; + let through = { + let mut map = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(HashMap::new); + match map.get(&(placed as usize)) { + Some(through) => through.clone(), + None => { + // SAFETY: live textures. + let (of_from, of_to) = unsafe { (from.GetDesc(), to.GetDesc()) }; + // Levels times layers (a volume's slices are one part). + let count = |d: &D3D12_RESOURCE_DESC| { + let layers = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + 1 + } else { + u32::from(d.DepthOrArraySize) + }; + u32::from(d.MipLevels) * layers + }; + let parts = count(&of_from); + if parts == 0 || parts > ALIAS_PARTS || parts != count(&of_to) { + return false; + } + let mut rows = [(); 2] + .map(|()| vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); parts as usize]); + let mut bytes = [0u64; 2]; + // SAFETY: plain queries; the out pointers are ours and + // hold `parts` layouts each. + unsafe { + host.device.GetCopyableFootprints( + &of_from, + 0, + parts, + 0, + Some(rows[0].as_mut_ptr()), + None, + None, + Some(&mut bytes[0]), + ); + host.device.GetCopyableFootprints( + &of_to, + 0, + parts, + 0, + Some(rows[1].as_mut_ptr()), + None, + None, + Some(&mut bytes[1]), + ); + } + let alike = rows[0].iter().zip(&rows[1]).all(|(a, b)| { + let (fa, fb) = (a.Footprint, b.Footprint); + a.Offset == b.Offset + && (fa.Width, fa.Height, fa.Depth, fa.RowPitch) + == (fb.Width, fb.Height, fb.Depth, fb.RowPitch) + }); + if bytes[0] == 0 || bytes[0] != bytes[1] || !alike { + return false; + } + let Some(buffer) = host.uav_buffer(bytes[0]) else { + return false; + }; + crate::host::name(&buffer, || { + format!( + "alias copy {}x{} f{} to f{}", + of_from.Width, of_from.Height, of_from.Format.0, of_to.Format.0 + ) + }); + tracing::info!( + view = ?placed, + texture = ?source, + width = of_from.Width, + height = of_from.Height, + parts, + written_as = of_from.Format.0, + read_as = of_to.Format.0, + "a view placed in the memory of a texture the host writes, in another format: read from that texture by a copy on the host" + ); + let [of_written, of_read] = rows; + let through = Arc::new(Through { + buffer, + parts: of_written.into_iter().zip(of_read).collect(), + }); + map.insert(placed as usize, through.clone()); + through + } + } + }; + // An upload from title memory can have already used this view. Only + // a copy from the same GPU source can satisfy this read. + list.first_use(placed as usize); + let new_source = list.alias_source_changed(to, from); + // The source's first use in the list records nothing (its prelude + // brings it to the state); a use in another way since the last copy + // shows as a change of state. + let before = list.transition(source, COPY_SOURCE).map(|(texture, before)| { + let state = crate::host::legal_state(texture, COPY_SOURCE); + let barrier = crate::host::transition( + texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(state as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + before + }); + if !new_source && before.is_none() { + return true; + } + card_writes(list, placed, to, None); + crate::list::ensure_state(list, placed, COPY_DEST); + let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index as u32, + }, + }; + let rows = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&through.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *row, + }, + }; + let (common, read, written) = ( + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("alias copy of {source:?} into {placed:?}")); + // SAFETY: an open list and live resources; the buffer is as big as + // the footprints and rests in the common state between copies. + unsafe { + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, common, written)]); + for (index, (of_written, _)) in through.parts.iter().enumerate() { + list.list + .CopyTextureRegion(&rows(of_written), 0, 0, 0, &part(from, index), None); + } + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, written, read)]); + for (index, (_, of_read)) in through.parts.iter().enumerate() { + list.list + .CopyTextureRegion(&part(to, index), 0, 0, 0, &rows(of_read), None); + } + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, read, common)]); + } + list.keep(&through.buffer); + // A draw that also writes the source (a view of it handled before + // this one) needs it in that state again; the next read of the alias + // then copies once more, as it must after a write. + if let Some(before) = before + && before & TARGET_OR_UNORDERED != 0 + { + crate::list::ensure_state(list, source, before); + } + true +} + +/// Whether a texture refresh that finds the runtime remapping title memory +/// goes on without waiting for it (on by default since the 2026-11-24 +/// report, where the same wait was 97-99% of every frame line's 1.2-2.2 s +/// of "textures" while the world streamed in; `VICTORY_TEXTURE_NO_WAIT=0` +/// waits, as before). +/// +/// A texture whose memory is all mapped is read in place, under a lock +/// the runtime takes alone while it changes a mapping +/// (`crate::watch::title_memory_reading`), so that no page goes away under +/// the read. While the world streams in the runtime remaps all the time, +/// and each of the frame's 150-360 refreshes waited for it: runs 99-101 +/// have 4, 15 and 16 frame lines with over 300 ms of "textures", up to +/// 3,708 ms, and on every one of them the wait for this lock is the whole +/// of it (1,345 of 1,381 ms; 3,630 of 3,708; the write-watch askings 3-12 +/// ms, the texture's own lock 0). +/// +/// With the switch the refresh asks for the lock without waiting. If the +/// runtime has it, the texture is read through the kernel instead, which +/// needs no lock: it fails if a page is not there, and then the texture is +/// left as it is and read at its next refresh, a frame later. A read +/// through the kernel costs about 0.6 ms a megabyte against 0.3 in place. +/// +/// What changes for the picture: a texture that arrives while the runtime +/// is remapping may show a frame later. It never shows partly read. +fn no_wait() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_NO_WAIT").is_none_or(|v| v != "0")) +} + +/// Since the last frame-rate line, with [`no_wait`]: refreshes that read +/// through the kernel because title memory was being remapped, and those +/// left for the next refresh because a page was not there. +pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Since the last frame-rate line, of texture refreshes on every thread, in +/// microseconds: waiting for the texture's own lock (another thread is +/// refreshing the same texture), asking the write watch and the guards, +/// waiting for title memory to hold still (the lock the runtime takes +/// alone while it remaps, `crate::watch::title_memory_reading`), and the +/// refreshes in all. +/// +/// While the world streams in, the frame line's "textures" is seconds a +/// frame in some runs and tenths in others for the same megabytes (2,566 +/// ms for 110 MB in run 93, 314 ms for 132 MB in run 91; before these +/// counters, runs 81, 83, 85 and 94 each had lines of 1.5-2.9 s), and the +/// submitting thread is not running while it lasts (run 93: 240-310 ms of +/// its own time a frame beside 1,100-1,800 ms of "textures"): it waits. +/// These say for what. +pub(crate) static REFRESH_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// `f`'s result, its time added to [`REFRESH_WAITS`]' place `slot`. +fn waited<T>(slot: usize, f: impl FnOnce() -> T) -> T { + let started = std::time::Instant::now(); + let out = f(); + let us = started.elapsed().as_micros() as u64; + REFRESH_WAITS[slot].fetch_add(us, std::sync::atomic::Ordering::Relaxed); + if slot == 2 { + crate::framelog::add(crate::framelog::T::RefreshStillUs, us); + } + out +} + thread_local! { - /// Texture memory read for hashing and detiling: one per submitting - /// thread, as large as the largest texture it read. - static SCRATCH: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) }; + /// Room to read a texture's memory into: one buffer per submitting + /// thread. Each texture kept its own, a second copy in memory of every + /// write-watched or partly mapped texture ever sampled, for the run. + static READ: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; } -/// Textures the host GPU wrote by a copy or resolve: their contents are on -/// the host, not in title memory, which stays as it was. Each with the -/// write-watch asking at the copy (0: its memory is not watched). -static HOST_WRITTEN: Mutex<Option<HashMap<usize, u64>>> = Mutex::new(None); +/// Calls `f` with `size` bytes of this thread's read buffer (their +/// contents are whatever the last texture left). +fn with_read<R>(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R { + READ.with(|read| { + let mut read = read.borrow_mut(); + if read.len() < size { + read.resize(size, 0); + } + f(&mut read[..size]) + }) +} -/// A texture's title memory, `[start, end)`. -fn memory_range(resource: This) -> Option<(usize, usize)> { - let (memory, desc) = crate::resource::texture_memory(resource)?; - let size = crate::resource::texture_layout(&desc)?.planes[0] - .layout - .size; - let start = memory as usize; - Some((start, start.checked_add(usize::try_from(size).ok()?)?)) +/// Whether a texture all of whose memory is mapped is read through the +/// kernel's copy instead of in place (`VICTORY_TEXTURE_COPY=1`; off by +/// default). Round 3 of the memory work read every such texture that way +/// to be safe from pages taken away under the read; it cost 0.6 ms per MB +/// against 0.3 in place (90-105 ms a frame while the world streams in, runs +/// 72 and 73, against 20-40), and both runs with it lost the graphics +/// device, for a reason not found. The read in place is safe now for +/// another reason (`crate::watch::title_memory_reading`); this switch is +/// left to tell whether the copy was what lost the device. +fn through_copy() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_COPY").is_some_and(|v| v == "1")) +} + +/// Calls `f` with the `size` bytes of title memory at `memory`, read +/// through the kernel into this thread's read buffer; pages that are not +/// there read as zeros. The bytes are those a read in place would see. +fn with_title<R>(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> R { + with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), memory, size, false); + f(read) + }) +} + +/// Staging buffers alive (also those only a list still holds) and their +/// bytes. +static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +impl Drop for Staging { + fn drop(&mut self) { + use std::sync::atomic::Ordering::Relaxed; + STAGED[0].fetch_sub(1, Relaxed); + STAGED[1].fetch_sub(self.bytes, Relaxed); + // The lists that copied from it have been reset (they held it + // until then): the buffer goes back for the next texture. + crate::host::give_staging(self.buffer.clone(), self.data, self.class); + } +} + +/// Staging buffers alive and their bytes (every build, for the line that +/// says where the card's memory goes). +pub(crate) fn staged_alive() -> [u64; 2] { + use std::sync::atomic::Ordering::Relaxed; + [STAGED[0].load(Relaxed), STAGED[1].load(Relaxed)] +} + +/// For the memory line: staging buffers alive, their bytes, and how many +/// of them their texture still has (the others wait for a list's reset). +#[cfg(feature = "diagnostics")] +pub(crate) fn memory() -> [u64; 3] { + use std::sync::atomic::Ordering::Relaxed; + let kept = STAGING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or(0, |map| map.len() as u64); + [STAGED[0].load(Relaxed), STAGED[1].load(Relaxed), kept] +} + +/// Staging buffers let go as idle since the start, and their bytes. +static LET_GO: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// For the memory line: staging buffers let go as idle, and their bytes. +#[cfg(feature = "diagnostics")] +pub(crate) fn let_go() -> [u64; 2] { + use std::sync::atomic::Ordering::Relaxed; + [LET_GO[0].load(Relaxed), LET_GO[1].load(Relaxed)] } +/// Lets go of the staging buffers no list recorded a use of for `IDLE_MS` +/// and `IDLE_FRAMES` frames and no list holds: a staging buffer is system memory the size of its +/// texture, kept so that an unchanged texture is not uploaded again, and +/// those of textures no longer sampled were kept for the run (2,246 of +/// them, 2.1 GB, at the end of run 24). The next list that samples such a +/// texture makes a staging buffer anew, detiles and uploads once more. +/// Called before a submission starts, by the thread that submits. +pub(crate) fn let_go_idle() { + use std::sync::atomic::Ordering::Relaxed; + const IDLE_FRAMES: u64 = 4; + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let Some(map) = map.as_mut() else { + return; + }; + if map.is_empty() { + return; + } + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()).min(crate::pressure::idle_cap_ms(false)); + // A list that recorded an upload or a check holds the staging until it + // is reset: one only the table holds is named by no list, recorded or + // running. + let (mut went, mut bytes) = (0u64, 0u64); + map.retain(|_, s| { + let keep = Arc::strong_count(s) > 1 + || !crate::host::long_ago(s.used.load(Relaxed), idle_ms, IDLE_FRAMES); + if !keep { + LET_GO[0].fetch_add(1, Relaxed); + LET_GO[1].fetch_add(s.bytes, Relaxed); + went += 1; + bytes += s.bytes; + } + keep + }); + if went > 0 { + crate::host::trail(|| format!("sweep: {went} staging buffers of textures let go ({} KiB), held by no list", bytes >> 10)); + } +} + +/// Textures the host GPU wrote by a copy or resolve: their contents are on +/// the host, not in title memory, which stays as it was. +static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None); + /// A host copy or resolve writes `resource`. pub(crate) fn host_written(resource: This) { - let asked = memory_range(resource) - .and_then(|(start, end)| crate::watch::writes(start, end, false)) - .map_or(0, |(now, _)| now); - let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - map.get_or_insert_with(Default::default) - .insert(resource as usize, asked); -} - -/// Whether the title wrote a texture's memory `[start, end)` again after -/// the host copied into it at write-watch asking `copied`, given the -/// watch's `(page, asking)` answer. Only watch pages wholly inside the -/// texture count: a neighbour written in a shared page must not send stale -/// memory over the copy. A texture never watched (`copied` 0) keeps the -/// copy. -fn rewritten_since(start: usize, end: usize, copied: u64, written: &[(usize, u64)]) -> bool { - use crate::watch::PAGE; - let (first, last) = (start.div_ceil(PAGE), end / PAGE); - copied != 0 - && written - .iter() - .any(|&(page, asking)| (first..last).contains(&page) && asking > copied) -} - -/// Whether `resource`'s host copy keeps what the host GPU wrote into it: -/// a copy or resolve did, and the title has not written its memory since -/// (upstream #758: a texture copied into once ignored later streaming). -fn keeps_host_contents(resource: This) -> bool { - let copied = { - let map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - match map.as_ref().and_then(|map| map.get(&(resource as usize))) { - Some(&copied) => copied, - None => return false, - } + let new = { + let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + set.get_or_insert_with(Default::default).insert(resource as usize) }; - if copied == 0 { - return true; + // Diagnostics (run 177): where its title memory is, for placed views + // the title reads that memory through ([`placed_in_host_written`]). + if new && let Some((at, desc)) = crate::resource::texture_memory(resource) { + // SAFETY: 56 bytes in the description's layout. + let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() }; + let bytes = crate::resource::placed_bytes(&words).unwrap_or(0); + if !at.is_null() && bytes > 0 { + HOST_WRITTEN_AT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(at as u64, (bytes, words[4], words[6], words[7], words[8], resource as usize)); + } } - let rewritten = memory_range(resource).is_some_and(|(start, end)| { - crate::watch::writes(start, end, false) - .is_some_and(|(_, written)| rewritten_since(start, end, copied, &written)) - }); - if rewritten { - let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(map) = map.as_mut() { - map.remove(&(resource as usize)); +} + +/// The title memory of textures the host copied into, by address: bytes +/// and description words 4, 6, 7 and 8 (width, height, layers and levels, +/// format). +static HOST_WRITTEN_AT: Mutex<std::collections::BTreeMap<u64, (u64, u32, u32, u32, u32, usize)>> = + Mutex::new(std::collections::BTreeMap::new()); + +/// A texture the title placed at `address` (description words `desc`) was +/// made: says so once if it lies in the memory of a texture the host +/// copied into ([`host_written`]). Its own host copy is filled from title +/// memory, which the copy never reached: the copied texels are on the +/// card in the other texture, where no shader that reads this view finds +/// them. +pub(crate) fn placed_in_host_written(address: u64, desc: &[u32; 14]) { + let hit = { + let map = HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()); + map.range(..=address) + .next_back() + .filter(|(at, d)| address < **at + d.0) + .map(|(at, d)| (*at, *d)) + }; + if let Some((at, (bytes, width, height, layers_levels, format, _))) = hit { + static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 200 { + tracing::warn!( + view_address = format_args!("{address:#x}"), + view_offset = address - at, + view_width = desc[4], + view_height = desc[6], + view_layers_levels = format_args!("{:#x}", desc[7]), + view_format = desc[8], + copied_address = format_args!("{at:#x}"), + copied_bytes = bytes, + copied_width = width, + copied_height = height, + copied_layers_levels = format_args!("{layers_levels:#x}"), + copied_format = format, + "HERO LEAD: a placed texture view lies in the memory of a texture the host copied into: it is filled from title memory, which the copy never reached" + ); } } - !rewritten +} + +/// Whether the host GPU wrote `resource` by a copy or resolve +/// ([`host_written`]): its host copy cannot be made again from title +/// memory. +pub(crate) fn host_wrote(resource: usize) -> bool { + HOST_WRITTEN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|set| set.contains(&resource)) } /// The title released a resource. @@ -143,9 +578,16 @@ pub(crate) fn forget(resource: usize) { if let Some(map) = map.as_mut() { map.remove(&resource); } - let mut map = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(map) = map.as_mut() { - map.remove(&resource); + let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(set) = set.as_mut() { + set.remove(&resource); + } + // Its memory may be given to other textures now (run 177: most of the + // "HERO LEAD" lines were views in memory a released texture had held). + HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, d| d.5 != resource); + let mut through = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(through) = through.as_mut() { + through.remove(&resource); } } @@ -162,14 +604,67 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { /// submission if the memory changed. Leaves the texture in the copy /// destination state. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { - // A texture the host copied into keeps the host's contents until the - // title writes its memory again (only noticed where it is watched). - if !list.first_use(resource as usize) || keeps_host_contents(resource) { + let host_written = HOST_WRITTEN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|set| set.contains(&(resource as usize))); + // shortcut: a texture the host copied into keeps the host's contents + // even if the title later writes its memory too. + if host_written || !list.first_use(resource as usize) { return; } let Some(staging) = staging(resource, texture) else { return; }; + use std::sync::atomic::Ordering::Relaxed; + staging.used.store(crate::host::moment(), Relaxed); + // Levels on demand: a view of the texture now starts at another + // level, or another texture now starts inside its span, with no byte + // of its memory changed. The levels are judged anew: detiled again at + // this list's submission, and uploaded by this list. + if staging.on_demand && staging.judgement() != staging.judged() { + staging.forget(); + staging.dirty.store(true, Relaxed); + } + // The texture rush is over: a texture detiled without its largest + // levels is detiled again whole and uploaded by this list. + if staging.on_demand && staging.rushed.load(Relaxed) != 0 && crate::tiles::rush_levels() == 0 { + staging.rushed.store(0, Relaxed); + staging.forget(); + staging.dirty.store(true, Relaxed); + } + // Levels on demand: the last upload left a held level without tiles + // (the card had no room, or no heap could be had), and nothing else + // would record an upload again until the title writes the texture: the + // level stayed empty, the texture blurred or black. Asked again about + // once a second, and only when the card has room; the staging buffer + // still holds the level's bytes. + if staging.on_demand { + let since = staging.waiting.load(Relaxed); + if since != 0 && crate::host::long_ago(since, 1000, 2) { + if crate::resource::room_lately() { + staging.waiting.store(0, Relaxed); + staging.dirty.store(true, Relaxed); + crate::tiles::STATS[10].fetch_add(1, Relaxed); + } else { + staging.waiting.store(crate::host::moment().max(1), Relaxed); + } + } + } + // The host texture has the staging buffer's contents: only the check + // at submission is left, and what it finds changed the next list that + // samples the texture uploads (a frame late where every list of the + // frame was recorded before that check). + if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexSkipped, 1); + list.defer_texture(staging); + return; + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexUploads, 1); + crate::framelog::add(crate::framelog::T::Uploads, 1); const COPY_DEST: u32 = 0x400; crate::list::ensure_state(list, resource, COPY_DEST); // The staging buffer lives as long as `staging`, which the deferred @@ -221,11 +716,228 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) // SAFETY: an open list; both locations name live resources. unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; } - // Once per submission however many of its lists sample the texture. - list.defer_texture(staging); + // When the list is submitted, its copy takes what the staging buffer + // holds by then: noted before the check below, which sets `dirty` + // again if it detiles (the next list then uploads once more). + { + let staging = staging.clone(); + list.defer_host(move || { + staging.uploaded.store(true, Relaxed); + staging.dirty.store(false, Relaxed); + }); + } + // Levels on demand (`crate::tiles`): after the check below, in the + // order of this list's steps, and before the list is executed, the + // levels the staging buffer holds as the title's are given the card's + // memory if they have none. The list copies every level, so each one + // given here is written whole by it (the rest are copies into no + // memory, which the card drops). + let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None }; + let Some(on_demand) = on_demand else { + // Once per submission however many of its lists sample the texture. + list.defer_texture(staging); + return; + }; + list.defer_texture(staging.clone()); + // After the check: it judges which levels are held (`detiled`). + list.defer_after_textures(move || { + let waiting = on_demand.uploaded(staging.detiled.load(Relaxed), staging.memory as u64); + staging.waiting.store(if waiting { crate::host::moment().max(1) } else { 0 }, Relaxed); + // Uploaded without its largest levels for the rush: made whole + // again when it is over, as a texture made blurred is. + if staging.rushed.load(Relaxed) != 0 { + crate::descriptor::host::rushed(staging.memory as u64); + } + // A texture picked by index has no staging buffer after this + // upload: its slots are made due again by the texture pass. + if waiting { + crate::descriptor::host::levels_waiting(staging.memory as u64); + } + }); +} + +/// Levels on demand: the levels a list claimed for its zeros +/// (`crate::tiles::Tiled::claim`), held by the list's submission-time +/// step. A list that is reset without having been submitted gives the +/// claim up, or the next list that writes those levels would send no zeros +/// and what its write does not cover would be what the tiles' last owner +/// left. +struct Claimed { + on_demand: crate::resource::OnDemand, + fresh: u32, + ran: std::sync::atomic::AtomicBool, +} + +impl Drop for Claimed { + fn drop(&mut self) { + if self.fresh != 0 + && !*self.ran.get_mut() + && let Some(tiled) = self.on_demand.tiled() + { + tiled.unclaim(self.fresh); + } + } +} + +/// Levels on demand (`crate::tiles`): the card itself is about to write +/// title texture `resource` in `list` (a copy or a resolve into level +/// `level`, or into every level). If its host copy `texture` was made +/// without memory, the levels written get theirs when the list is +/// submitted, ahead of it on the queue; the ones that have none yet are +/// first written with zeros, here in the same list, so that what the +/// card's write does not cover is not what the tiles' last owner left. +/// To be called before the list is brought to the state of that write. +/// shortcut: two lists that write the same new level, submitted in the +/// other order than recorded, lose the first one's write under the zeros +/// of the other; so does an upload recorded and not yet submitted. +pub(crate) fn card_writes(list: &HostList, resource: This, texture: &ID3D12Resource, level: Option<u32>) { + let Some(on_demand) = crate::resource::host_tiled(resource) else { + return; + }; + let Some(tiled) = on_demand.tiled() else { + return; + }; + let levels = match level { + Some(level) => tiled.with_level(level), + None => tiled.every_level(), + }; + if levels == 0 { + return; + } + let fresh = tiled.claim(levels); + // Of them, the ones whose zeros could not be recorded. + let mut unzeroed = if host().is_none() { fresh } else { 0 }; + if fresh != 0 + && let Some(host) = host() + { + const COPY_DEST: u32 = 0x400; + crate::list::ensure_state(list, resource, COPY_DEST); + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + for level in (0..u32::from(d.MipLevels).min(32)).filter(|&level| fresh & (1u32 << level) != 0) { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut bytes = 0u64; + // SAFETY: outputs for one subresource. + unsafe { + host.device + .GetCopyableFootprints(&d, level, 1, 0, Some(&mut footprint), None, None, Some(&mut bytes)); + } + let Some((buffer, data)) = list.upload(host, bytes) else { + // (With the levels that share its tiles, if it is one of + // the small ones.) + unzeroed |= tiled.with_level(level); + continue; + }; + // SAFETY: a mapped buffer of `bytes` bytes, just made. + unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: level }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above; the list holds the buffer until it is reset. + pResource: unsafe { std::mem::transmute_copy(&buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + } + // A new level without its zeros gets no tiles from this list: the + // card's write into it is lost (the level reads zeros, as before the + // write), which is less wrong than a part write over what the tiles' + // last owner left. The next list that writes it claims it again. + unzeroed &= fresh; + if unzeroed != 0 { + tiled.unclaim(unzeroed); + } + let levels = levels & !unzeroed; + if levels == 0 { + return; + } + let memory = crate::resource::texture_memory(resource).map_or(0, |(memory, _)| memory as u64); + let step = Claimed { + on_demand, + fresh: fresh & !unzeroed, + ran: std::sync::atomic::AtomicBool::new(false), + }; + list.defer_host(move || { + step.ran.store(true, std::sync::atomic::Ordering::Relaxed); + step.on_demand.card_wrote(levels, memory); + }); } impl Staging { + /// Levels on demand: what says, beside the mapping, which levels of + /// the texture are the title's now. First the lowest level a live view + /// of the texture shows (0 without a view that says): the title's own + /// word, a texture it holds from level 3 on is viewed from level 3. + /// Then where the next texture placed in this one's span starts, in + /// bytes from this one's start (`u64::MAX`: none does): for a texture + /// viewed from level 0 although a neighbour sits where its large + /// levels would be. + fn judgement(&self) -> [u64; 2] { + let start = self.memory as u64; + let first = crate::descriptor::host::first_viewed(start).map_or(0, u64::from); + let limit = crate::descriptor::host::next_start(start, start.saturating_add(self.layout.size)) + .map_or(u64::MAX, |at| at - start); + [first, limit] + } + + /// What [`Staging::judgement`] said at the last detiling. + fn judged(&self) -> [u64; 2] { + use std::sync::atomic::Ordering::Relaxed; + [self.judged[0].load(Relaxed), self.judged[1].load(Relaxed)] + } + + /// Levels on demand: the levels that are the title's now, a bit a + /// level. A level is held if no view starts above it, its bytes end + /// before the next texture starts, and all of them are mapped. The + /// smallest levels share the texture's first block and are held + /// together. (The console layout: that block first, then the other + /// levels from the smallest up, level 0 last: + /// `victory_formats::texture::Layout`.) A texture this cannot tell + /// the levels of holds them all. + fn held_levels(&self, [first, limit]: [u64; 2]) -> u32 { + let mips = &self.layout.mips; + if self.layout.slices != 1 || mips.is_empty() || mips.len() > 32 { + return u32::MAX; + } + let tail = (self.layout.first_tail_mip as usize).min(mips.len()); + let there = |from: u64, to: u64| { + to > from && to <= limit && committed(self.memory.wrapping_add(from as usize), (to - from) as usize) + }; + let mut held = 0u32; + for (level, m) in mips.iter().enumerate().take(tail) { + let end = if level == 0 { self.layout.slice_size } else { mips[level - 1].offset }; + if level as u64 >= first && there(m.offset, end) { + held |= 1 << level; + } + } + if tail < mips.len() && there(0, self.layout.alignment.min(self.layout.slice_size)) { + for level in tail..mips.len() { + if level as u64 >= first { + held |= 1 << level; + } + } + } + held + } + + /// Forgets what the staging buffer was last filled from: the next + /// refresh detiles anew, whether the memory changed or not. + fn forget(&self) { + *self.last.lock().unwrap_or_else(|e| e.into_inner()) = Last::default(); + } + + /// The title memory the texture is read from: address and bytes. + pub(crate) fn memory(&self) -> (usize, usize) { + (self.memory as usize, self.layout.size as usize) + } + /// Detiles the texture memory into the staging buffer if it changed /// since the last time (and is mapped at all). pub(crate) fn refresh(&self) { @@ -237,58 +949,137 @@ impl Staging { preparing[3].fetch_add(read as u64, Relaxed); } + /// [`Staging::refresh`] without adding to the frame line's texture + /// time (a caller that runs several at once counts its own): the bytes + /// of title memory read. + pub(crate) fn refresh_uncounted(&self) -> usize { + self.refresh_now() + } + /// Returns the bytes of title memory read. fn refresh_now(&self) -> usize { + let whole = std::time::Instant::now(); + let read = self.refresh_timed(); + let us = whole.elapsed().as_micros() as u64; + REFRESH_WAITS[3].fetch_add(us, std::sync::atomic::Ordering::Relaxed); + crate::framelog::add(crate::framelog::T::RefreshUs, us); + read + } + + fn refresh_timed(&self) -> usize { let size = self.layout.size as usize; let start = self.memory as usize; - let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let last = &mut *last; - if let Some((now, written)) = crate::watch::writes(start, start + size, false) { + if let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { return 0; } last.asked = now; // Read through the copy, which stands unmapped pages: memory of // big pools is too slow to ask page by page. - with_tiled_copy(self.memory, size, |tiled| self.detile(tiled)); + with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + self.detile(read); + }); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexWatched, size as u64); return size; } - // A streamed texture can be partly resident: its pool maps the mips - // it has loaded and leaves the others unmapped, as tiled resources - // on the console (reads of an unmapped tile give zero, and titles - // clamp their level of detail to what is resident). Uploading only a - // fully committed texture left such textures as they were made, - // black, until every mip was in. A texture with nothing committed - // keeps what it had. - if !any_committed(self.memory, size) { - #[cfg(feature = "diagnostics")] - tracing::debug!( - memory = ?self.memory, - size, - desc = ?self.layout.desc, - "a sampled texture's memory is not committed" - ); - return 0; + // View memory has no write-watch, and a texture there was hashed + // whole at every check: 229 MB and 51 ms a frame in a gameplay view + // where two textures change (run 58). It is guarded now, as buffers + // in view memory are: a write of the title's to it faults once and + // is noted, a mapping is announced by the runtime. While neither + // happened the texture is as it was. What the guard cannot see (a + // write to the same pages through another view) is still found by + // the hash, which is taken every eighth frame only, by the + // texture's address, so the textures take turns. + // `VICTORY_TEXTURE_GUARD=0` hashes at every check, as before. + static GUARD: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0")) + && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) + { + const HASH_EVERY: u64 = 8; + let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked); + last.asked = now; + let frame = crate::frame::current(); + let turn = frame.wrapping_add((start >> 16) as u64).is_multiple_of(HASH_EVERY) + && last.ahead.is_none_or(|at| frame > at + 1); + if unwritten && !turn { + return 0; + } } - // Read through the kernel, as above: the title may unmap the pages - // (evicting a texture a big table lists) while we read them, and a - // direct read would fault; unmapped pages read as zeros. The copy is - // reused, not kept per texture. - SCRATCH.with_borrow_mut(|tiled| { - tiled.resize(size, 0); - if !crate::host::read_into(self.memory, &mut tiled[..size]) { - read_resident(self.memory, &mut tiled[..size]); + // From here on the texture's memory may be read in place. Held until + // that read is done: the runtime changes what title memory shows + // only with this taken alone, so what `committed` finds mapped + // stays mapped (see `crate::watch::title_memory_reading`; without + // it a page went between the asking and the read in runs 71 and + // 74). + let _mapped = if no_wait() { + // Not waited for: while the runtime remaps title memory the + // texture is read through the kernel instead, whole or not at + // all (`no_wait`). + let Some(mapped) = crate::watch::title_memory_reading_now() else { + return self.refresh_unlocked(last, size); + }; + mapped + } else { + waited(2, crate::watch::title_memory_reading) + }; + if !committed(self.memory, size) { + // Partly mapped: a streamed texture with only some mips' pages + // there, the usual state while it streams in. Read through the + // copy, which stands unmapped pages (zeros), and upload what + // is there; nothing at all mapped changes nothing. + // shortcut: read again at most every 30 frames (reading around + // unmapped pages is slow, and nothing tells us when pages + // arrive): a mip that streams in shows up to 30 frames late. + let frame = crate::frame::current(); + if last.partial.is_some_and(|at| frame < at + 30) { + return 0; } - self.changed(last, tiled) - }) - } - - /// After reading the texture's memory into `tiled`: detiles it unless - /// its hash is the last one's. Returns the bytes read. - fn changed(&self, last: &mut Last, tiled: &[u8]) -> usize { - let size = tiled.len(); + last.partial = Some(frame); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexHashed, size as u64); + let changed = with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + let hash = blake3::hash(read); + if last.hash == Some(hash) { + return false; + } + last.hash = Some(hash); + if read.iter().all(|&b| b == 0) { + return false; + } + self.detile(read); + true + }); + #[cfg(feature = "diagnostics")] + if changed { + crate::copystat::add(crate::copystat::C::TexChanged, size as u64); + } + let _ = changed; + return size; + } + if through_copy() { + return with_title(self.memory, size, |tiled| { + let hash = blake3::hash(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexHashed, size as u64); + if last.hash == Some(hash) { + return size; + } + last.hash = Some(hash); + self.detile(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexChanged, size as u64); + size + }); + } + // SAFETY: committed memory of the texture's layout size, and it + // stays committed while `_mapped` is held. + let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; let hash = blake3::hash(tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexHashed, size as u64); @@ -302,8 +1093,89 @@ impl Staging { size } + /// Detiles the texture memory into the staging buffer ahead of the + /// submission, on the thread of `crate::heap_worker`: read through the + /// kernel, so that the runtime's remapping never waits for it, whole or + /// not at all (the submission then does it, as ever). False if it was + /// not read. What the title writes after this is found at submission. + pub(crate) fn refresh_ahead(&self) -> bool { + let size = self.layout.size as usize; + let start = self.memory as usize; + let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + let last = &mut *last; + if last.hash.is_some() || last.asked != 0 { + // Detiled before: the submission's check is cheap. + return true; + } + let asked = crate::watch::writes(start, start + size, false).or_else(|| crate::watch::writes(start, start + size, true)); + let Some((now, _)) = asked else { + return false; + }; + with_read(size, |read| { + if !crate::host::read_into(self.memory, read) { + return false; + } + last.hash = Some(blake3::hash(read)); + self.detile(read); + last.asked = now; + last.ahead = Some(crate::frame::current()); + true + }) + } + + /// A refresh while the runtime is remapping title memory ([`no_wait`]): + /// the texture is read through the kernel, which fails if a page of it + /// is not there at this moment. Then nothing is taken and the texture + /// is looked at again at its next refresh (what was learnt about writes + /// to it is forgotten, so that it is not passed over as unwritten). + /// Returns the bytes read. + fn refresh_unlocked(&self, last: &mut Last, size: usize) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let read = with_read(size, |read| { + if !crate::host::read_into(self.memory, read) { + return false; + } + let hash = blake3::hash(read); + if last.hash != Some(hash) { + last.hash = Some(hash); + self.detile(read); + } + true + }); + if read { + UNLOCKED[0].fetch_add(1, Relaxed); + size + } else { + UNLOCKED[1].fetch_add(1, Relaxed); + last.asked = 0; + 0 + } + } + /// Detiles `tiled` (the texture's memory) into the staging buffer. fn detile(&self, tiled: &[u8]) { + self.dirty.store(true, std::sync::atomic::Ordering::Relaxed); + // Levels on demand: which levels are the title's is judged here, + // once, for what the staging buffer holds from now on. The step + // that gives levels their memory goes by this answer. + let held = if self.on_demand { + use std::sync::atomic::Ordering::Relaxed; + let judged = self.judgement(); + self.judged[0].store(judged[0], Relaxed); + self.judged[1].store(judged[1], Relaxed); + // The texture rush leaves the largest levels out: not held, so + // they get no memory and views start below them. + let rush = self.rush_mask(); + if rush != 0 { + RUSHED.fetch_add(1, Relaxed); + } + self.rushed.store(rush, Relaxed); + let held = self.held_levels(judged) & !rush; + self.detiled.store(held, Relaxed); + held + } else { + u32::MAX + }; #[cfg(feature = "diagnostics")] if tiled.iter().all(|&b| b == 0) { tracing::debug!( @@ -312,6 +1184,9 @@ impl Staging { "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" ); } + if self.detile_spread(tiled, held) { + return; + } for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); let f = footprint.Footprint; @@ -321,6 +1196,11 @@ impl Staging { let linear = unsafe { std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) }; + if mip < 32 && held & (1 << mip) == 0 { + // Not the title's: zeros, not what lies in that memory. + linear.fill(0); + continue; + } if let Err(e) = self.layout .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) @@ -332,23 +1212,265 @@ impl Staging { } } -/// Reads a texture for the duration of its detile. Keep the initialized -/// length so alternating large and small textures do not re-zero the tail. -fn with_tiled_copy(memory: *const u8, size: usize, detile: impl FnOnce(&[u8])) { - SCRATCH.with_borrow_mut(|read| { - if size > read.len() { - read.reserve_exact(size - read.len()); - read.resize(size, 0); +/// Textures detiled without their largest levels for the texture rush +/// (`crate::tiles::rush_levels`), since the start. +pub(crate) static RUSHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +impl Staging { + /// The largest levels the texture rush leaves out of this texture now + /// (`crate::tiles::rush_levels`): from level 0, those of 512 KiB or + /// more on the host, never past the fourth level from the smallest. + fn rush_mask(&self) -> u32 { + // Try 6.16: one being made whole again after a rush stays whole + // (asked first: the detile takes it off that list either way). + if crate::descriptor::host::unrushing(self.memory as u64) { + return 0; + } + let n = crate::tiles::rush_levels(); + if n == 0 || self.mips < 5 { + return 0; + } + let mut mask = 0; + for level in 0..n.min(self.mips - 4) { + let i = level as usize; + let (Some(f), Some(&rows)) = (self.footprints.get(i), self.rows.get(i)) else { + break; + }; + let f = f.Footprint; + let bytes = u64::from(f.RowPitch) * u64::from(rows) * u64::from(f.Depth); + if bytes < 512 << 10 { + break; + } + mask |= 1 << level; + } + mask + } +} + +/// Threads a big texture's subresources are detiled on at once +/// (`VICTORY_DETILE_THREADS`; 1: on the refreshing thread alone, as before +/// Try 4.2). Try 4.2, idea 5: reading, hashing and detiling were 20-40 ms +/// a frame of the submitting thread's time while the world streamed in, +/// most of it the detile of big array and cube textures, whose slices and +/// levels are each their own job. Try 6.0: by default half the CPU's +/// threads (at least 4, at most 16), not 4 whatever the CPU: a 12- or +/// 16-thread CPU had most of its cores idle while the submitting thread +/// detiled. +fn detile_threads() -> usize { + static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("VICTORY_DETILE_THREADS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| (n.get() / 2).max(4))) + .clamp(1, 16) + }) +} + +/// A texture of at least this many bytes is detiled on [`detile_threads`]. +const SPREAD_BYTES: usize = 2 << 20; + +impl Staging { + /// [`Staging::detile`] of every subresource the title holds (`held`, + /// by level), on [`detile_threads`] threads at once. False, with + /// nothing done, for a small texture or one subresource. + fn detile_spread(&self, tiled: &[u8], held: u32) -> bool { + let threads = detile_threads(); + if threads < 2 || tiled.len() < SPREAD_BYTES || self.footprints.len() < 2 { + return false; + } + // Per subresource: level, slice, where in the staging buffer + // (as an address: threads take it apart) and its pitches. + let mut jobs: Vec<(u32, u32, usize, usize, usize, usize)> = Vec::new(); + for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { + let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); + let f = footprint.Footprint; + let pitch = f.RowPitch as usize; + let len = pitch * rows as usize * f.Depth as usize; + // SAFETY: the subresource's part of the mapped staging buffer. + let at = unsafe { self.data.add(footprint.Offset as usize) } as usize; + if mip < 32 && held & (1 << mip) == 0 { + // SAFETY: as above; no thread runs yet. + unsafe { std::slice::from_raw_parts_mut(at as *mut u8, len) }.fill(0); + continue; + } + jobs.push((mip, slice, at, len, pitch, pitch * rows as usize)); + } + // Biggest first, dealt out in turn. + jobs.sort_unstable_by_key(|j| std::cmp::Reverse(j.3)); + let layout = &self.layout; + std::thread::scope(|scope| { + for t in 0..threads.min(jobs.len()) { + let mine: Vec<_> = jobs.iter().skip(t).step_by(threads).copied().collect(); + scope.spawn(move || { + for (mip, slice, at, len, pitch, depth_pitch) in mine { + // SAFETY: subresources' parts of the staging + // buffer do not overlap; each is one thread's. + let linear = unsafe { std::slice::from_raw_parts_mut(at as *mut u8, len) }; + if let Err(e) = layout.detile(tiled, mip, slice, linear, pitch, depth_pitch) { + tracing::warn!(?e, mip, slice, "texture not detiled"); + } + } + }); + } + }); + true + } +} + +/// Lets go of a title texture's staging buffer (lists that recorded an +/// upload from it hold it until they have run); the next upload makes one +/// anew. +pub(crate) fn unstage(resource: This) { + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&(resource as usize)); + } +} + +/// Where a staged title texture's memory is: address and bytes. +pub(crate) fn staged_memory(resource: This) -> Option<(u64, u64)> { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let (at, len) = map.as_ref()?.get(&(resource as usize))?.memory(); + Some((at as u64, len as u64)) +} + +/// A fingerprint of the title memory `[at, at + len)`, never 0: of all of +/// it up to 48 KiB, else of 16 KiB at its start, its middle and its end +/// (a texture streams in whole mips; the small ones lie first). Read +/// through the kernel, so pages not there count as zeros. +pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { + const WINDOW: usize = 16 << 10; + thread_local! { + static READ: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; + } + let len = len as usize; + let mut hasher = blake3::Hasher::new(); + READ.with(|read| { + let mut read = read.borrow_mut(); + read.resize(3 * WINDOW, 0); + let mut take = |from: usize, bytes: usize| { + read[..bytes].fill(0); + crate::host::copy_mapped(read.as_mut_ptr(), (at as usize + from) as *const u8, bytes, false); + hasher.update(&read[..bytes]); + }; + if len <= 3 * WINDOW { + take(0, len); + } else { + take(0, WINDOW); + take((len / 2) & !0xfff, WINDOW); + take(len - WINDOW, WINDOW); } - let tiled = &mut read[..size]; - crate::host::copy_mapped(tiled.as_mut_ptr(), memory, size, false); - detile(tiled); }); + let hash = hasher.finalize(); + let mut first = [0u8; 8]; + first.copy_from_slice(&hash.as_bytes()[..8]); + u64::from_le_bytes(first) | 1 +} + +/// Whether a title texture has a staging buffer: a list recorded its +/// upload, and the lists that sample it check it at submission. +/// For the frame listing: whether a list has uploaded `resource`'s staging +/// buffer, and whether it was detiled since. None: it has none. +#[cfg(feature = "diagnostics")] +pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> { + use std::sync::atomic::Ordering::Relaxed; + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let staging = map.as_ref()?.get(&(resource as usize))?; + Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed))) +} + +pub(crate) fn is_staged(resource: This) -> bool { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize))) +} + +/// The bytes of a title texture's memory, and whether all of it is mapped, +/// if the texture has been staged for upload. +pub(crate) fn staged(resource: This) -> Option<(u64, bool)> { + let s = { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref()?.get(&(resource as usize))?.clone() + }; + let size = s.layout.size as usize; + Some((size as u64, committed(s.memory, size))) } /// Whether `[at, at + len)` is committed memory (streamed textures may be /// unmapped until their pages arrive). pub(crate) fn committed(at: *const u8, len: usize) -> bool { + if by_query() { + return committed_by_query(at, len); + } + if len == 0 { + return true; + } + let (there, of) = readable(at as usize, len, true); + there == of +} + +/// Whether the two questions above and below are put to `VirtualQuery`, as +/// they were (`VICTORY_COMMITTED_QUERY=1`). `VirtualQuery` answers with the +/// length of the run of pages in the same state, which it finds by walking +/// the page tables to the run's end: 8.8 ms for one question in the title's +/// 1.1 GB block (round 6). The pass over the heap's views asks three or +/// more of them for every texture slot that is due, 3,000 slots a frame +/// when the card has no room (run 75): that pass then ran 208-264 ms, and +/// while it ran the submitting thread's write-watch askings waited behind +/// the walks (run 76: 8-22 askings a frame of 6-21 ms each, 46-172 ms). +fn by_query() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_COMMITTED_QUERY").is_some_and(|v| v == "1")) +} + +/// Of the kernel's pages that hold `[at, at + len)` (`len > 0`): how many +/// can be read, and how many there are; with `all`, it stops at the first +/// that cannot. One question to the kernel for up to 256 pages at once +/// (`QueryWorkingSetEx`: the state of each page asked about, no walk); a +/// page not in the working set may still be there (never touched, or +/// trimmed), and a one-byte read through the kernel says. +/// A page that is committed and may not be read counts as not there, which +/// is what the callers ask for: they read or write the memory next. +fn readable(at: usize, len: usize, all: bool) -> (usize, usize) { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const KERNEL_PAGE: usize = 4096; + let (first, last) = (at / KERNEL_PAGE, at.saturating_add(len - 1) / KERNEL_PAGE); + let of = last - first + 1; + let mut there = 0; + // SAFETY: plain data. + let mut info: [PSAPI_WORKING_SET_EX_INFORMATION; 256] = unsafe { std::mem::zeroed() }; + let mut page = first; + while page <= last { + let n = (last - page + 1).min(info.len()); + for (i, entry) in info[..n].iter_mut().enumerate() { + entry.VirtualAddress = ((page + i) * KERNEL_PAGE) as *mut _; + } + // SAFETY: `n` entries of the size given; our own process. + let asked = unsafe { + K32QueryWorkingSetEx( + GetCurrentProcess(), + info.as_mut_ptr().cast(), + (n * size_of::<PSAPI_WORKING_SET_EX_INFORMATION>()) as u32, + ) + } != 0; + for (i, entry) in info[..n].iter().enumerate() { + // Bit 0 of the answer: the page is in the working set. + // SAFETY: plain data the query filled in. + let valid = asked && unsafe { entry.VirtualAttributes.Flags } & 1 != 0; + let mut byte = [0u8]; + if valid || crate::host::read_into(((page + i) * KERNEL_PAGE) as *const u8, &mut byte) { + there += 1; + } else if all { + return (there, of); + } + } + page += n; + } + (there, of) +} + +fn committed_by_query(at: *const u8, len: usize) -> bool { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; let mut p = at as usize; let end = p + len; @@ -365,61 +1487,72 @@ pub(crate) fn committed(at: *const u8, len: usize) -> bool { true } -/// Reads the committed regions of `[src, src + dst.len())` into `dst`, -/// zeros elsewhere: one query per region, not a failed read per page, for -/// a streamed texture most of which is not resident. -fn read_resident(src: *const u8, dst: &mut [u8]) { +/// How many bytes of `[at, at + len)` are committed memory: all of a +/// texture that is there, some of one streaming in (its smaller mips lie +/// at the start of its memory, and their pages are mapped first), none of +/// one not there. With neither the first nor the last page committed the +/// answer is none without a look at the pages between (two queries for the +/// slots whose texture is away, which are asked again and again). +pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; - let base = src as usize; - let end = base.saturating_add(dst.len()); - let mut p = base; - while p < end { - // SAFETY: plain data filled in by the query. - let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: a valid out pointer of the right size. - let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; - let stop = if n == 0 { - end - } else { - (info.BaseAddress as usize) - .saturating_add(info.RegionSize) - .clamp(p + 1, end) - }; - let piece = &mut dst[p - base..stop - base]; - if n != 0 && info.State == MEM_COMMIT { - // Through the kernel: a page unmapped since the query reads as - // zeros instead of faulting. - crate::host::copy_mapped(piece.as_mut_ptr(), p as *const u8, piece.len(), false); - } else { - piece.fill(0); + if len == 0 { + return 0; + } + let start = at as usize; + let end = start.saturating_add(len); + if !committed(at, 1) && !committed((end - 1) as *const u8, 1) { + return 0; + } + if !by_query() { + static BY_PAGE: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if *BY_PAGE.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_PAGE").is_some_and(|v| v == "1")) { + // By page, without the walk: whole pages, cut to the range. + let (there, _) = readable(start, len, false); + return (there as u64 * 4096).min(len as u64); + } + // By 64 KiB block, one page asked of each: the title's memory is + // mapped in blocks of that size (the console's page), and the + // answer is a measure of how much of a texture has arrived, not a + // promise that every byte can be read (the upload reads through the + // kernel). By page, a texture half there cost a failed kernel read + // for each of its missing pages, every frame it stayed due: 1,663 + // textures "uploaded in part" kept the pass over the heap's views at + // 90-160 ms a frame (run 81). `VICTORY_MAPPED_BY_PAGE=1`: by page. + const BLOCK: usize = 64 << 10; + let mut there = 0u64; + let mut block = start & !(BLOCK - 1); + while block < end { + let (lo, hi) = (block.max(start), block.saturating_add(BLOCK).min(end)); + if readable(lo, 1, true).0 == 1 { + there += (hi - lo) as u64; + } + block = block.saturating_add(BLOCK); } - p = stop; + return there; } -} - -/// Whether any page of `[at, at + len)` is committed. -fn any_committed(at: *const u8, len: usize) -> bool { - use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; - let mut p = at as usize; - let end = p.saturating_add(len); + let (mut p, mut there) = (start, 0u64); while p < end { // SAFETY: plain data filled in by the query. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; // SAFETY: a valid out pointer of the right size. let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; - if n == 0 { - return false; + let next = (info.BaseAddress as usize).saturating_add(info.RegionSize).min(end); + if n == 0 || next <= p { + break; } if info.State == MEM_COMMIT { - return true; + there += (next - p) as u64; } - p = info.BaseAddress as usize + info.RegionSize; + p = next; } - false + there } /// The staging state of a title texture, made on first use. fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> { + // Asked before the table is locked: the sweep lets go of a staging + // buffer with its texture's host side locked, in that order. + let on_demand = crate::resource::host_tiled(resource).is_some(); let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let map = map.get_or_insert_with(HashMap::new); if let Some(s) = map.get(&(resource as usize)) { @@ -462,16 +1595,25 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> { Some(&mut total), ); } - let (buffer, data) = host.upload_buffer(total)?; - crate::host::name(&buffer, || { + // Half a second after the driver refused an upload buffer, none is + // asked for a new staging buffer (`crate::pressure`): the next list + // that samples the texture asks again. + if crate::pressure::backing_off() { + return None; + } + let (buffer, data, class) = crate::host::take_staging(host, total)?; + crate::host::name_frame(&buffer, || { format!( "staging of {resource:?} {}x{}x{} f{}", d.Width, d.Height, d.DepthOrArraySize, d.Format.0 ) }); tracing::debug!(?desc, total, "texture contents uploaded from title memory"); + STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed); let s = Arc::new(Staging { buffer, + class, #[cfg(feature = "diagnostics")] size: total, data, @@ -479,116 +1621,129 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> { rows, layout, mips: u32::from(d.MipLevels), + bytes: total, memory, last: Mutex::default(), + dirty: std::sync::atomic::AtomicBool::new(true), + uploaded: std::sync::atomic::AtomicBool::new(false), + used: std::sync::atomic::AtomicU64::new(crate::host::moment()), + on_demand, + detiled: std::sync::atomic::AtomicU32::new(0), + judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], + waiting: std::sync::atomic::AtomicU64::new(0), + rushed: std::sync::atomic::AtomicU32::new(0), }); map.insert(resource as usize, s.clone()); Some(s) } #[cfg(test)] -mod tests { - - /// A texture half of whose pages are committed reads those pages and - /// zeros for the rest; one with none committed is not read at all. - #[cfg(windows)] - #[test] - fn partly_resident_textures_read_what_is_mapped() { - use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, - }; - const PAGE: usize = 64 << 10; - // SAFETY: a fresh reservation, released below. - let base = unsafe { VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE, PAGE_READWRITE) }; - assert!(!base.is_null()); - let base = base.cast::<u8>(); - assert!(!any_committed(base, 4 * PAGE)); - // SAFETY: inside the reservation. - let second = unsafe { base.add(PAGE) }; - // SAFETY: inside the reservation. - assert!(!unsafe { VirtualAlloc(second.cast(), PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); - // SAFETY: committed above. - unsafe { second.write_bytes(0xAB, PAGE) }; - assert!(any_committed(base, 4 * PAGE)); - assert!(!committed(base, 4 * PAGE)); - let mut out = vec![0x55; 4 * PAGE]; - read_resident(base, &mut out); - assert!(out[..PAGE].iter().all(|&b| b == 0)); - assert!(out[PAGE..2 * PAGE].iter().all(|&b| b == 0xAB)); - assert!(out[2 * PAGE..].iter().all(|&b| b == 0)); - // SAFETY: the reservation made above. - unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }; - } - use super::*; - - /// A copied texture uploads again only once the title writes a watch - /// page wholly its own after the copy (upstream #758). - #[test] - fn copied_texture_uploads_again_after_the_title_rewrites_it() { - use crate::watch::PAGE; - let (start, end) = (4 * PAGE, 8 * PAGE); - assert!(!rewritten_since(start, end, 7, &[(4, 6), (5, 7)])); - assert!(rewritten_since(start, end, 7, &[(4, 6), (6, 8)])); - // Never watched: the copy is kept. - assert!(!rewritten_since(start, end, 0, &[(5, 9)])); - // Pages shared with neighbours do not count. - let (start, end) = (4 * PAGE + 256, 6 * PAGE + 256); - assert!(!rewritten_since(start, end, 7, &[(4, 9), (6, 9)])); - assert!(rewritten_since(start, end, 7, &[(5, 9)])); - assert!(!rewritten_since(PAGE + 16, PAGE + 4096, 1, &[(1, 9)])); - } +mod title_memory_tests { + use super::with_title; + /// Title memory whose tail is reserved and not committed reads through + /// the copy as its bytes and then zeros, without a fault; so does + /// memory a page of which is taken away between two reads, and the + /// zeros are zeros whatever the read buffer held before. #[test] - fn watched_texture_reads_reuse_space_and_expose_only_current_bytes() { - #[cfg(feature = "diagnostics")] - if crate::copystat::mode() == 2 { - return; // this mode skips all copies - } - let large = [0x67; 8192]; - let small = [0x21; 128]; - let next = [0x43; 8192]; - let mut allocation = None; - for source in [&large[..], &small[..], &next[..]] { - with_tiled_copy(source.as_ptr(), source.len(), |tiled| { - assert_eq!(tiled, source); - if let Some(first) = allocation { - assert_eq!(tiled.as_ptr(), first); - } else { - allocation = Some(tiled.as_ptr()); - } + fn an_uncommitted_tail_reads_as_zeros() { + use windows_sys::Win32::System::Memory::*; + const HEAD: usize = 0xb_0000; + const SIZE: usize = 0x20_0000; + // SAFETY: a private reservation of our own; only committed pages + // are written in place, and nothing else reads them in place. + unsafe { + // The read buffer holds something else first. + let other = vec![0x77u8; SIZE]; + with_title(other.as_ptr(), SIZE, |bytes| assert!(bytes.iter().all(|&b| b == 0x77))); + let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>(); + assert!(!base.is_null()); + assert_eq!(VirtualAlloc(base.cast(), HEAD, MEM_COMMIT, PAGE_READWRITE), base.cast()); + base.write_bytes(0x5a, HEAD); + with_title(base, SIZE, |bytes| { + assert!(bytes[..HEAD].iter().all(|&b| b == 0x5a), "what is mapped"); + assert!(bytes[HEAD..].iter().all(|&b| b == 0), "what is not: zeros"); }); + // The title takes a page in the middle away: zeros from then + // on, the rest as before. + assert_ne!(VirtualFree(base.add(0x4_0000).cast(), 0x1_0000, MEM_DECOMMIT), 0); + with_title(base, SIZE, |bytes| { + assert!(bytes[..0x4_0000].iter().all(|&b| b == 0x5a)); + assert!(bytes[0x4_0000..0x5_0000].iter().all(|&b| b == 0)); + assert!(bytes[0x5_0000..HEAD].iter().all(|&b| b == 0x5a)); + assert!(bytes[HEAD..].iter().all(|&b| b == 0)); + }); + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); } } + /// The texture both device-loss runs named last (16 texels wide, 4 or 8 + /// high, format 10, layout 0x100, console flags 0x300000; its memory + /// began 0x300 into a page in run 73 and 0x700 in run 72, and here also + /// 0xf00, so that a page line runs through it): what the detiling is + /// given and what it writes are the same read in place and read through + /// the copy, and the rows it writes end where the staging buffer the + /// host sizes for it ends (896 bytes for 4 rows of 128 bytes 256 apart, + /// 1,920 for 8). #[test] - fn unmapped_texture_pages_do_not_keep_previous_pixels() { - use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, - VirtualFree, - }; - - #[cfg(feature = "diagnostics")] - if crate::copystat::mode() != 0 { - return; // diagnostic copy overrides do not handle unmapped pages + fn the_small_texture_of_runs_72_and_73_detiles_the_same_both_ways() { + use windows_sys::Win32::System::Memory::*; + for (height, within) in [(4u32, 0x300usize), (8, 0x700), (4, 0xf00), (8, 0xf00)] { + // The description as the log printed it, word for word. + let words: [u32; 14] = [3, 0, 0, 0, 16, 0, height, 65537, 10, 1, 0, 256, 3_145_728, 0]; + // SAFETY: fourteen words are a resource description (56 bytes, + // plain numbers). + let desc: crate::resource::ResourceDesc = unsafe { std::mem::transmute(words) }; + let layout = crate::resource::texture_layout(&desc) + .expect("a console layout") + .planes[0] + .layout + .clone(); + let size = layout.size as usize; + let (row, pitch) = (16 * 8, 256usize); + assert!(size >= row * height as usize, "the layout holds every texel"); + // Committed pages and a reserved one after them; the texture + // begins `within` bytes into the first, as the title placed it. + // SAFETY: our own reservation; the committed part is written + // and read in place, by this thread alone. + unsafe { + let pages = size.div_ceil(4096) + 1; + let base = VirtualAlloc(std::ptr::null(), (pages + 1) * 4096, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>(); + assert!(!base.is_null()); + assert_eq!(VirtualAlloc(base.cast(), pages * 4096, MEM_COMMIT, PAGE_READWRITE), base.cast()); + for i in 0..pages * 4096 { + base.add(i).write((i * 7 + i / 251) as u8); + } + let memory = base.add(within); + let in_place = std::slice::from_raw_parts(memory, size); + // The bytes: the same in place and through the copy. + with_title(memory, size, |copied| assert_eq!(copied, in_place)); + // What the detiling writes: the same, and inside the bytes + // the host's staging buffer for this texture has. + let staged = (height as usize - 1) * pitch + row; + assert_eq!(staged, if height == 4 { 896 } else { 1920 }); + let detile = |tiled: &[u8]| { + // The slice `Staging::detile` hands over: whole rows. + let mut linear = vec![0xeeu8; pitch * height as usize]; + layout + .detile(tiled, 0, 0, &mut linear, pitch, pitch * height as usize) + .expect("detiled"); + linear + }; + let direct = detile(in_place); + let through = with_title(memory, size, |copied| detile(copied)); + assert_eq!(direct, through); + for y in 0..height as usize { + assert!(direct[y * pitch..][..row].iter().any(|&b| b != 0xee), "row {y} written"); + assert!(direct[y * pitch + row..(y + 1) * pitch].iter().all(|&b| b == 0xee), "nothing past row {y}"); + } + // A buffer of exactly the staged bytes is enough. + let mut exact = vec![0u8; staged]; + layout + .detile(in_place, 0, 0, &mut exact, pitch, pitch * height as usize) + .expect("the staging buffer's bytes are enough"); + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); + } } - const PAGE: usize = 4096; - let previous = [0x65; 2 * PAGE]; - with_tiled_copy(previous.as_ptr(), previous.len(), |tiled| { - assert_eq!(tiled, previous); - }); - // SAFETY: reserve two pages at an address chosen by Windows. - let base = unsafe { VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_NOACCESS) }; - assert!(!base.is_null()); - // SAFETY: commit the first page of that reservation. - let mapped = unsafe { VirtualAlloc(base, PAGE, MEM_COMMIT, PAGE_READWRITE) }; - assert_eq!(mapped, base); - // SAFETY: the first page is writable. - unsafe { base.cast::<u8>().write_bytes(0x32, PAGE) }; - with_tiled_copy(base.cast(), 2 * PAGE, |tiled| { - assert!(tiled[..PAGE].iter().all(|&b| b == 0x32)); - assert!(tiled[PAGE..].iter().all(|&b| b == 0)); - }); - // SAFETY: this reservation is no longer used. - assert_ne!(unsafe { VirtualFree(base, 0, MEM_RELEASE) }, 0); } } diff --git a/crates/victory-gpu/src/tiles.rs b/crates/victory-gpu/src/tiles.rs new file mode 100644 index 0000000000..92fdb8f5e0 --- /dev/null +++ b/crates/victory-gpu/src/tiles.rs @@ -0,0 +1,1936 @@ +//! Levels on demand: host copies of title textures that take the card's +//! memory level by level, as the title holds the levels. +//! +//! The title places a texture's whole chain of levels in its address space +//! and holds only some of them: the smallest first, at the start of the +//! texture's memory. The memory of the larger ones is either not mapped, +//! or belongs to the next texture, which the title packs where they would +//! be (run 188). A host copy was a committed texture: every level of it +//! took the card's memory from the first upload on. Run 189's accounting +//! line counted 2.2 to 3.0 GB of 4.3 to 5.5 GB of host copies in levels +//! whose title memory was not mapped, on some 1,600 copies; with about +//! 2.2 to 3.1 GB of render targets that filled the card, and textures +//! that needed a new host copy waited for room (the main character's face +//! among them, runs 188 and 189). +//! +//! Here such a texture is a reserved one (`CreateReservedResource`): it has +//! every level, so level numbers and sizes are what they were, but no +//! memory. The rules: +//! - A level is given tiles of a heap of ours (`UpdateTileMappings`, on the +//! queue) only in a submission-time step of a list that also writes all +//! of that level: the upload of the texture (`texture.rs` `upload`, which +//! copies every level from the staging buffer every time), or, before +//! the card itself writes the texture (a copy, a resolve), an upload of +//! every level with every level given (`texture.rs` `make_whole`). The +//! step runs when the list is submitted, before the list is executed, so +//! the mapping is ahead of the copy on the queue. Tiles hold what their +//! last owner left; no level is shown before it is written whole. +//! - Which levels are held is said by one function, at the moment the +//! staging buffer is filled (`Staging::held_levels`): the levels whose +//! title memory is mapped and lies before the start of the next texture +//! placed in this one's span. The staging buffer holds zeros for the +//! others, and the step gives tiles by that same answer. +//! - The small levels the card packs into shared tiles are given together +//! when any of them is held; the upload writes all of them (zeros for +//! the ones not held). +//! - A shader must not reach a level without memory (it reads zeros: a +//! black texture). The host view of a slot is made from the first level +//! that is held and has tiles ([`show_from`], `descriptor/host.rs` +//! `make`), and the slots of a texture are made again when that level +//! changes (`HostHeap::texture_views_remade`). +//! - shortcut: tiles are not taken back while the host copy lives. A level +//! the title lets go of, or that turns out to be the next texture's, +//! keeps its tiles; it is hidden by the views and written with zeros at +//! the next upload. Its tiles go back when the host copy does. +//! +//! Only for a texture the title places in memory and fills, two-dimensional, +//! one layer, more than one level, of [`floor`] bytes or more, whose memory +//! is not all its own when the host copy is made (`resource.rs` `hosted`); +//! every other texture is made as before. Off unless +//! `VICTORY_LEVELS_ON_DEMAND=1`. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::host::host; + +/// The card's tile: 64 KiB. +const TILE: u64 = 64 << 10; + +/// Tiles in one heap of the pool (64 MiB). The largest level given is a +/// 4096x4096 one of one byte a texel: 256 tiles. +const HEAP_TILES: u32 = 1024; + +/// Since the start, or now: such textures alive; the bytes all their +/// levels would take; the bytes of the tiles given to them; the bytes of +/// the pool's heaps; such textures made in all; levels given; calls of +/// `UpdateTileMappings`; their microseconds; heaps given back to the card; +/// uploads that left a held level without tiles (the card had no room, or +/// no heap could be had); uploads recorded again for such a level. +pub(crate) static STATS: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11]; + +/// Whether textures are made this way: the switch +/// (`VICTORY_LEVELS_ON_DEMAND=1`; off by default), and a card that reads +/// zeros from, and drops writes to, levels without memory (tiled resources +/// tier 2). +pub(crate) fn wanted() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var_os("VICTORY_LEVELS_ON_DEMAND").is_some_and(|v| v == "1") { + return false; + } + let Some(host) = host() else { + return false; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: a plain query into a struct of its own size. + let asked = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + let tier = options.TiledResourcesTier.0; + let on = asked.is_ok() && tier >= 2; + tracing::info!( + tier, + on, + floor_kb = floor() >> 10, + "host copies of title textures take the card's memory level by level (VICTORY_LEVELS_ON_DEMAND=1)" + ); + on + }) +} + +fn parse_floor(value: Option<&str>) -> u64 { + value + .and_then(|v| v.trim().parse::<u64>().ok()) + .map_or(1 << 20, |kb| kb.max(64).saturating_mul(1024)) +} + +/// The bytes from which a texture is made this way: a megabyte, or +/// `VICTORY_LEVELS_MIN_KB`. (The accounting of run 189: the levels not +/// held are 1.9 MB a copy on some 1,600 copies; a 512x512 texture has six +/// tiles at most, and most of the calls for nothing.) +/// 5.7: 256 KiB where texture quality drops the largest levels +/// ([`top_dropped`]): the 2026-11-26 report's textures picked by index +/// were 411 KB on average (14,659 of them, 6,034 MB), so nearly all of +/// them were under a megabyte and kept every level's memory. +pub(crate) fn floor() -> u64 { + static BYTES: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new(); + let set = *BYTES.get_or_init(|| { + std::env::var("VICTORY_LEVELS_MIN_KB").ok().map(|v| parse_floor(Some(&v))) + }); + match set { + Some(bytes) => bytes, + None if by_quality() => 256 << 10, + None => parse_floor(None), + } +} + +/// Tiles (of 64 KiB) a level may have to get them on a card without room +/// for whole textures (`VICTORY_SQUEEZE_TILES`, 4: 256 KiB, a 512x512 +/// block-compressed level; 0: none, the textures wait as before). In the +/// 2026-11-25 report an 8 GB card stood at its line for the whole run with +/// 17,000 slots of textures waiting for room, drawn black or grey; texture +/// streaming in PC games drops the largest levels under a memory budget +/// the same way. +pub(crate) fn small_tiles() -> u32 { + static N: std::sync::OnceLock<u32> = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("VICTORY_SQUEEZE_TILES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4)) +} + +/// Texture quality on cards with little memory: how many of the largest +/// levels of a texture made level by level get no memory. The largest +/// level is three quarters of a texture's bytes: PC games' "texture +/// quality" and other emulators' texture-size caps drop it the same way. +/// Only levels of 4 tiles (256 KiB) or more are dropped, and never down past +/// the fourth level from the smallest, so small textures keep all their +/// detail. +/// `VICTORY_TEXTURE_TOP_DROP` (0 to 3) fixes the count. Unset (5.8: +/// adaptive, as engines stream to a memory budget): on a card whose budget +/// is under 7,000 MB, none while the card is under 70 % of it (full +/// detail), one past that, and one more while the card has no room for +/// whole textures; textures that were made blurred get their largest levels +/// back once it is under 70 % again (`crate::descriptor::host::sharpen`). +/// 5.6 and 5.7 dropped one level on such cards always: blurred even with +/// memory to spare. +pub(crate) fn top_dropped() -> u32 { + let quality = match quality_base() { + None | Some(Quality::Full) => 0, + Some(Quality::Fixed(n)) => n, + Some(Quality::Adaptive) => adaptive_drop(), + }; + // (While the rush is on, textures made blurred wait for it to end + // before `sharpen` makes them whole: the rush's own levels are left + // out at the detile, `texture.rs`.) + quality.max(rush_levels()) +} + +/// Try 6.2, the picture first and the detail after (as streaming engines +/// do): while the queue of textures picked by index has a backlog (1,500 +/// or more due; it ends under 300), a texture made level by level is +/// detiled and uploaded without its largest levels of 512 KiB or more (at +/// most `VICTORY_TEXTURE_RUSH` of them, 2 unless set, 0: off; never past +/// the fourth level from the smallest). Two levels left out are about a +/// sixteenth of the bytes and the CPU time, so the whole scene is there, +/// soft, in a fraction of the time; when the backlog has drained, the +/// textures made that way get their full detail back +/// (`crate::descriptor::host::sharpen`) while the game plays. In the world +/// up to 27,668 slots were due (report 141631) and textures came in one by +/// one over a minute. +/// +/// Try 6.16: at most once in [`rush_gap_ms`]. In the 6.15 report the rush +/// went on and off 209 times in six minutes, about once a second: when it +/// ended, the textures it had made soft were made due again to get their +/// detail back (`crate::descriptor::host::unrush`, 1,024 a pass), which put +/// the queue over 1,500 again, so the rush came back on and made them soft +/// again, and so on. Thousands of textures were uploaded again and again +/// (111,497 uploads, 51,988 MB, in six minutes; 35 to 51 ms a frame of +/// texture refreshes, 88 to 94 ms of the heap worker), alternately with and +/// without their largest levels, and each change of a texture's first level +/// is a change of its views: faces went from their skin to blank (the +/// placeholder's white) to see-through (the levels without memory) and +/// back. Now a texture `unrush` made due is uploaded whole whatever the +/// rush says ([`crate::descriptor::host::unrushing`]), and the rush stays +/// off for a while after it ends. +pub(crate) fn rush_levels() -> u32 { + static N: std::sync::OnceLock<u32> = std::sync::OnceLock::new(); + static ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + // When the rush last ended (`now_ms` plus one; 0: never). + static ENDED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = *N.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_RUSH").ok().and_then(|v| v.trim().parse::<u32>().ok()).unwrap_or(2).min(3) + }); + if n == 0 { + return 0; + } + // Try 6.3: not behind a loading screen; there is time there, and what + // is made there keeps its detail. + if crate::draw::loading_now() { + return 0; + } + let due = crate::draw::HEAP_TEXTURES_QUEUE[1].load(Ordering::Relaxed); + let was = ON.load(Ordering::Relaxed); + let ended = ENDED.load(Ordering::Relaxed); + let rested = ended == 0 || crate::host::now_ms().saturating_sub(ended - 1) >= rush_gap_ms(); + let now = rush_next(was, due, rested); + if now != was && ON.compare_exchange(was, now, Ordering::Relaxed, Ordering::Relaxed).is_ok() { + if !now { + ENDED.store(crate::host::now_ms() + 1, Ordering::Relaxed); + } + tracing::info!( + due, + on = now, + levels = n, + gap_s = rush_gap_ms() / 1000, + "texture rush (VICTORY_TEXTURE_RUSH): the scene first without the largest levels, the detail after (at most once in gap_s, VICTORY_TEXTURE_RUSH_GAP_S)" + ); + } + if now { n } else { 0 } +} + +/// Whether the rush is on after this look: it was (`was`), `due` slots +/// are due, and the gap since it last ended has passed (`rested`). Pure, +/// for testing. +fn rush_next(was: bool, due: u64, rested: bool) -> bool { + if was { due >= 300 } else { due >= 1500 && rested } +} + +/// How long the rush stays off after it ends (`VICTORY_TEXTURE_RUSH_GAP_S`, +/// 30 unless set; 0: no gap, as before Try 6.16), in milliseconds. +fn rush_gap_ms() -> u64 { + static MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *MS.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_RUSH_GAP_S").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(30).min(3600) * 1000 + }) +} + +/// Whether textures are made level by level whatever they hold, for +/// texture quality to work on ([`top_dropped`]): a card it may drop levels +/// on. +pub(crate) fn by_quality() -> bool { + matches!(quality_base(), Some(Quality::Adaptive | Quality::Fixed(1..))) +} + +#[derive(Clone, Copy)] +enum Quality { + Full, + Fixed(u32), + Adaptive, +} + +/// What [`top_dropped`] goes by, once the card says its budget. +fn quality_base() -> Option<Quality> { + // 0: not known yet; 1: full; 2: adaptive; 3 + n: fixed at n. + static BASE: AtomicU32 = AtomicU32::new(0); + let known = match BASE.load(Ordering::Relaxed) { + 0 => { + let set = std::env::var("VICTORY_TEXTURE_TOP_DROP").ok().and_then(|v| v.trim().parse::<u32>().ok()); + let code = match set { + Some(n) => 3 + n.min(3), + None => { + let [budget, ..] = host().and_then(|h| h.video_memory())?; + if budget < 7000 << 20 { 2 } else { 1 } + } + }; + if BASE.swap(code, Ordering::Relaxed) == 0 { + tracing::info!( + quality = code, + "texture quality (1: full detail; 2: adaptive, the largest levels left out only while the card is short; 3 + n: n levels left out always; VICTORY_TEXTURE_TOP_DROP)" + ); + } + code + } + code => code, + }; + Some(match known { + 1 => Quality::Full, + 2 => Quality::Adaptive, + code => Quality::Fixed(code - 3), + }) +} + +/// [`top_dropped`] when adaptive, asked of the card at most every tenth of +/// a second. +fn adaptive_drop() -> u32 { + // The tenth of the last asking, counted from 1, and its answer in the + // lowest two bits. + static LAST: AtomicU64 = AtomicU64::new(0); + let tenth = crate::host::now_ms() / 100 + 1; + let last = LAST.load(Ordering::Relaxed); + if last >> 2 == tenth { + return (last & 3) as u32; + } + // Try 6.5: with a band, as engines switch quality levels (hysteresis): + // short from the sharp line up, sharp again only 5 points under it. A + // card that sat on the line went short and sharp every tenth of a + // second, and each turn made textures blurred and then whole again. + static SHORT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let was = SHORT.load(Ordering::Relaxed); + let line = if was { sharp_percent().saturating_sub(5) } else { sharp_percent() }; + let short = host() + .and_then(|h| h.video_memory()) + .is_some_and(|[budget, used, ..]| used >= budget / 100 * line); + SHORT.store(short, Ordering::Relaxed); + let n = if short { 1 + u32::from(!crate::resource::room_lately()) } else { 0 }; + LAST.store((tenth << 2) | u64::from(n), Ordering::Relaxed); + n +} + +/// The share of the card's budget, in percent, under which textures keep +/// every level (`VICTORY_TEXTURE_SHARP_PERCENT`, 50 to 89; Try 6.0: 85, it +/// was 70). A 6 GB card sat at 73 % of its budget in the world, just past +/// the old line, so every texture made then lost its largest level and +/// people and buildings came in blurred first; the card's own line for new +/// textures (`resource::room`) is at 90 %. +fn sharp_percent() -> u64 { + static P: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *P.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_SHARP_PERCENT") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(85) + .clamp(50, 89) + }) +} + +/// The bytes of the tiles given to textures now: the card's memory they +/// hold (`resource.rs` `room` counts it with the other host copies). +pub(crate) fn given_total() -> u64 { + STATS[2].load(Ordering::Relaxed) +} + +/// One heap of the pool and its free runs of tiles (first tile, tiles), in +/// order, no two touching. +struct Heap { + heap: ID3D12Heap, + free: Vec<(u32, u32)>, +} + +// SAFETY: a heap of the device, named only in queue and device calls, which +// any thread may make; its free runs are plain numbers behind `POOL`'s lock. +unsafe impl Send for Heap {} + +impl Heap { + fn free_tiles(&self) -> u32 { + self.free.iter().map(|run| run.1).sum() + } +} + +/// The pool's heaps by place; a place is empty after its heap went back to +/// the card (a texture names its heaps by place). +static POOL: Mutex<Vec<Option<Heap>>> = Mutex::new(Vec::new()); + +/// `count` tiles of one heap, in as many runs as it takes, the lowest free +/// tiles first (single free tiles are used up before a long run is cut): +/// the heap, its place in the pool and the runs (first tile, tiles). A new +/// heap is made when no heap has that many free. +fn take(device: &ID3D12Device, count: u32) -> Option<(ID3D12Heap, usize, Vec<(u32, u32)>)> { + if count == 0 || count > HEAP_TILES { + return None; + } + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let found = pool.iter().position(|h| h.as_ref().is_some_and(|h| h.free_tiles() >= count)); + let index = match found { + Some(index) => index, + None => { + let desc = D3D12_HEAP_DESC { + SizeInBytes: u64::from(HEAP_TILES) * TILE, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut made: Option<ID3D12Heap> = None; + // SAFETY: plain creation; the out pointer is ours. + if let Err(e) = unsafe { device.CreateHeap::<ID3D12Heap>(&raw const desc, &raw mut made) } { + tracing::warn!(error = %e, "no heap for texture levels given on demand: those levels stay empty"); + return None; + } + let fresh = Heap { + heap: made?, + free: vec![(0, HEAP_TILES)], + }; + STATS[3].fetch_add(u64::from(HEAP_TILES) * TILE, Ordering::Relaxed); + match pool.iter().position(Option::is_none) { + Some(index) => { + pool[index] = Some(fresh); + index + } + None => { + pool.push(Some(fresh)); + pool.len() - 1 + } + } + } + }; + let h = pool[index].as_mut()?; + let mut runs = Vec::new(); + let mut left = count; + while left > 0 { + let &(start, tiles) = h.free.first()?; + let part = tiles.min(left); + runs.push((start, part)); + if part == tiles { + h.free.remove(0); + } else { + h.free[0] = (start + part, tiles - part); + } + left -= part; + } + Some((h.heap.clone(), index, runs)) +} + +/// Gives the runs `runs` of the pool's heap at `index` back; runs that +/// touch become one. A heap with every tile free goes back to the card, +/// unless it is the pool's only one. (Called when the texture that held +/// the tiles is dropped: nothing on the card reads through its mappings +/// any more, as for any host texture that is dropped.) +fn give_back(index: usize, runs: &[(u32, u32)]) { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(h)) = pool.get_mut(index) else { + return; + }; + h.free.extend_from_slice(runs); + h.free.sort_unstable(); + let mut joined: Vec<(u32, u32)> = Vec::with_capacity(h.free.len()); + for &(from, tiles) in &h.free { + match joined.last_mut() { + Some(last) if last.0 + last.1 == from => last.1 += tiles, + _ => joined.push((from, tiles)), + } + } + h.free = joined; + let all_free = h.free_tiles() == HEAP_TILES; + if all_free && pool.iter().flatten().count() > 1 { + pool[index] = None; + STATS[3].fetch_sub(u64::from(HEAP_TILES) * TILE, Ordering::Relaxed); + STATS[8].fetch_add(1, Ordering::Relaxed); + } +} + +/// Tiles taken for one level (or the packed ones) of a texture, not yet +/// mapped: the heap and its place in the pool, the runs, the subresource, +/// its tiles, and the level if it has tiles of its own. +struct Taken { + heap: ID3D12Heap, + index: usize, + runs: Vec<(u32, u32)>, + subresource: u32, + tiles: u32, + level: Option<usize>, +} + +/// What is given so far to one texture. +struct Given { + /// Per level with tiles of its own: whether it has them. + levels: Vec<bool>, + /// Whether the small levels the card packs together have theirs. + packed: bool, + /// The runs taken: the heap's place, first tile, tiles. + runs: Vec<(usize, u32, u32)>, +} + +/// A host texture made without memory, and the tiles its levels have been +/// given. +pub(crate) struct Tiled { + /// Tiles of each level that has tiles of its own (level 0 first). + standard: Vec<u32>, + /// The tiles of the levels the card packs together (0: there are none); + /// they are the levels from `standard.len()` on. + packed: u32, + /// Levels in all. + levels: u32, + /// The bytes all its tiles would take. + pub(crate) full: u64, + given: Mutex<Given>, + /// The first level a view of the texture may show: the first one that + /// is held or was written by the card and has tiles (`u32::MAX`: none + /// yet). + shown: AtomicU32, + /// The levels held at the last upload (a bit a level). + held: AtomicU32, + /// The levels the card itself wrote, in lists submitted so far. + card: AtomicU32, + /// The last upload left levels the title holds without memory because + /// texture quality dropped them ([`top_dropped`]): the texture is drawn + /// blurred, and is uploaded again when the card has memory to spare. + blurred: std::sync::atomic::AtomicBool, + /// The levels a recorded list of the card's own writes has already + /// written with zeros first ([`Tiled::claim`]). + claimed: AtomicU32, +} + +impl Tiled { + /// For `texture`, just made reserved with `levels` levels and one + /// layer: how the card cuts it into tiles. `None` if the card will not + /// say, or cuts it in a way this does not handle; the caller then makes + /// the texture the old way. + pub(crate) fn make(device: &ID3D12Device, texture: &ID3D12Resource, levels: u32) -> Option<Tiled> { + if levels == 0 || levels > 16 { + return None; + } + let mut total = 0u32; + let mut packed = D3D12_PACKED_MIP_INFO::default(); + let mut shape = D3D12_TILE_SHAPE::default(); + let mut count = levels; + let mut tilings = vec![D3D12_SUBRESOURCE_TILING::default(); levels as usize]; + // SAFETY: outputs of our own, `count` tilings of them. + unsafe { + device.GetResourceTiling( + texture, + Some(&raw mut total), + Some(&raw mut packed), + Some(&raw mut shape), + Some(&raw mut count), + 0, + tilings.as_mut_ptr(), + ); + } + let standard_levels = u32::from(packed.NumStandardMips); + if total == 0 || standard_levels + u32::from(packed.NumPackedMips) != levels || standard_levels > count { + return None; + } + let mut standard = Vec::with_capacity(standard_levels as usize); + for tiling in &tilings[..standard_levels as usize] { + let tiles = tiling + .WidthInTiles + .checked_mul(u32::from(tiling.HeightInTiles)) + .and_then(|n| n.checked_mul(u32::from(tiling.DepthInTiles))) + .unwrap_or(0); + if tiles == 0 || tiles > HEAP_TILES || tiling.StartTileIndexInOverallResource == D3D12_PACKED_TILE { + return None; + } + standard.push(tiles); + } + let packed_tiles = if packed.NumPackedMips > 0 { packed.NumTilesForPackedMips } else { 0 }; + if (packed.NumPackedMips > 0 && packed_tiles == 0) || packed_tiles > HEAP_TILES { + return None; + } + let full = u64::from(total) * TILE; + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(full, Ordering::Relaxed); + STATS[4].fetch_add(1, Ordering::Relaxed); + Some(Tiled { + given: Mutex::new(Given { + levels: vec![false; standard.len()], + packed: false, + runs: Vec::new(), + }), + standard, + packed: packed_tiles, + levels, + full, + shown: AtomicU32::new(u32::MAX), + held: AtomicU32::new(0), + card: AtomicU32::new(0), + blurred: std::sync::atomic::AtomicBool::new(false), + claimed: AtomicU32::new(0), + }) + } + + /// At the submission of a list that uploads every level of `texture` + /// from its staging buffer, of which `held` are the title's now (the + /// others are zeros there): tiles for the held ones that have none. + /// `room`: whether the card has room for more host copies + /// (`resource.rs` `room`). Without room no held level gets tiles: the + /// list still brings the levels that have theirs up to date (which + /// takes none of the card's memory), and its copies into the others go + /// nowhere. (An upload of a host copy that exists passes the full + /// card's gate in `draw.rs` on the ground that it takes no memory; + /// with tiles given here regardless, the line would not bound these + /// textures.) + /// Returns whether the first level a view may show changed, and + /// whether a level named is still without tiles (no room, or no heap + /// could be had): the caller has the upload recorded again later, or + /// the level would stay empty until the title writes the texture. + pub(crate) fn uploaded(&self, texture: &ID3D12Resource, held: u32, room: bool) -> (bool, bool) { + match host() { + Some(host) => self.uploaded_on(host.queue(), &host.device, texture, held, room), + None => (false, false), + } + } + + /// [`Tiled::uploaded`] on a queue and a device. + pub(crate) fn uploaded_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + held: u32, + room: bool, + ) -> (bool, bool) { + self.uploaded_may(queue, device, texture, held, if room { u32::MAX } else { 0 }) + } + + /// [`Tiled::uploaded`] on a card without room, when it still has some + /// below its hard line (`resource.rs` `squeeze_room`): the small held + /// levels get tiles ([`Tiled::small_levels`]), so the texture shows + /// blurred instead of black or grey; the large ones wait for room as + /// before (the second answer says so). + pub(crate) fn uploaded_small(&self, texture: &ID3D12Resource, held: u32) -> (bool, bool) { + match host() { + Some(host) => self.uploaded_may(host.queue(), &host.device, texture, held, self.small_levels()), + None => (false, false), + } + } + + /// [`Tiled::uploaded_on`] where the held levels in `may` may get tiles. + fn uploaded_may( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + held: u32, + may: u32, + ) -> (bool, bool) { + let mut held = held & self.every_level(); + let all_held = held; + // Texture quality ([`top_dropped`]): the largest levels count as + // not held, so they get no memory, wait for none, and views start + // below them. (Not if nothing else would be held.) + let dropped = self.dropped_levels(); + if held & !dropped != 0 { + held &= !dropped; + } + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + self.held.store(held, Ordering::Relaxed); + let card = self.card.load(Ordering::Relaxed); + let named = held | card; + // The levels the card itself writes are few and are not kept + // waiting: a write of the card's into no memory is lost. + let changed = self.give_locked(&mut given, queue, device, texture, named, (named & may) | card); + let missing = self.without_locked(&given, named) != 0; + let blurred = self.without_locked(&given, all_held & !held) != 0; + self.blurred.store(blurred, Ordering::Relaxed); + (changed, missing) + } + + /// Whether the last upload left held levels out for texture quality. + pub(crate) fn blurred(&self) -> bool { + self.blurred.load(Ordering::Relaxed) + } + + /// The largest levels left without memory ([`top_dropped`]), a bit a + /// level. + fn dropped_levels(&self) -> u32 { + let n = top_dropped(); + if n == 0 || self.levels < 5 { + return 0; + } + let mut mask = 0; + for level in 0..n.min(self.levels - 4) { + match self.standard.get(level as usize) { + Some(&tiles) if tiles >= 4 => mask |= 1 << level, + _ => break, + } + } + mask + } + + /// The levels of [`small_tiles`] tiles or fewer, and the ones the card + /// packs together (a bit a level). + pub(crate) fn small_levels(&self) -> u32 { + let most = small_tiles(); + if most == 0 { + return 0; + } + let first = self.standard.iter().position(|&tiles| tiles <= most).unwrap_or(self.standard.len()); + self.every_level() & !((1u32 << first.min(31)) - 1) + } + + /// At the submission of a list in which the card itself writes the + /// levels `levels` of `texture` (after zeros, if they were new: + /// [`Tiled::claim`]): tiles for those that have none. Returns whether + /// the first level a view may show changed. + /// Only the levels this list writes get tiles here: a held level that + /// is waiting for room is written by no copy of this list, and tiles + /// hold what their last owner left. + pub(crate) fn card_wrote(&self, texture: &ID3D12Resource, levels: u32) -> bool { + match host() { + Some(host) => self.card_wrote_on(host.queue(), &host.device, texture, levels), + None => false, + } + } + + /// [`Tiled::card_wrote`] on a queue and a device. + pub(crate) fn card_wrote_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + levels: u32, + ) -> bool { + let levels = levels & self.every_level(); + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + let prev = self.card.load(Ordering::Relaxed); + let changed = self.give_locked( + &mut given, + queue, + device, + texture, + prev | levels | self.held.load(Ordering::Relaxed), + levels, + ); + // Only levels that actually received tiles (or already had them) saw + // the card's write; a level that got no tiles saw its zeros and write + // dropped, so neither `card` nor `claimed` should keep it. + let without = self.without_locked(&given, levels); + let backed = levels & !without; + if backed != 0 { + self.card.fetch_or(backed, Ordering::Relaxed); + } + if without != 0 { + self.unclaim(without); + } + changed + } + + /// The bits of the levels that get their tiles with level `level`: + /// itself, or every level the card packs together if it is one of them. + pub(crate) fn with_level(&self, level: u32) -> u32 { + let first_packed = self.standard.len() as u32; + if level < first_packed { + 1 << level + } else if level < self.levels { + self.every_level() & !((1u32 << first_packed) - 1) + } else { + 0 + } + } + + /// Of `levels`, the ones that have no tiles now and that no list + /// recorded before has claimed: the caller's list writes them with + /// zeros before the card's own write, so that what the write does not + /// cover is not what the tiles' last owner left. + pub(crate) fn claim(&self, levels: u32) -> u32 { + let fresh = self.without(levels); + fresh & !self.claimed.fetch_or(fresh, Ordering::Relaxed) + } + + /// Gives up the claim on `levels` ([`Tiled::claim`]): the zeros of the + /// list that claimed them never reached tiles of theirs (the list was + /// reset without being submitted, the zeros could not be recorded, or + /// no tiles could be had), so the next list that writes them sends its + /// own. + /// shortcut: a second list recorded between the claim and this sends + /// no zeros; if it is the first whose write gets tiles, what that + /// write does not cover is what the tiles' last owner left. + pub(crate) fn unclaim(&self, levels: u32) { + self.claimed.fetch_and(!levels, Ordering::Relaxed); + } + + /// Of `levels` (a bit a level), the ones that have no tiles now. + pub(crate) fn without(&self, levels: u32) -> u32 { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + self.without_locked(&given, levels) + } + + fn without_locked(&self, given: &Given, levels: u32) -> u32 { + let first_packed = self.standard.len() as u32; + let mut without = 0; + for level in 0..self.levels.min(32) { + let has = if level < first_packed { given.levels[level as usize] } else { given.packed }; + if !has { + without |= 1 << level; + } + } + levels & without + } + + /// Gives tiles to the levels of `texture` that both `named` and `may` + /// name (a bit a level, level 0 the lowest) and that have none yet; + /// the levels the card packs together get theirs when any of them is + /// so named. `named`: the levels that are the title's or the card's + /// own, by which the first level a view may show is told; `may`: the + /// ones of them that may get tiles in this call. To be called only + /// from a submission-time step of a list that writes every level of + /// `may`, whole: the call is ahead of that list on `queue`, and tiles + /// hold what their last owner left. + /// Returns whether the first level a view may show changed + /// ([`Tiled::first_shown`]): the caller has the texture's slots made + /// again. + #[cfg(test)] + pub(crate) fn give_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + named: u32, + may: u32, + ) -> bool { + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + self.give_locked(&mut given, queue, device, texture, named, may) + } + + fn give_locked( + &self, + given: &mut Given, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + named: u32, + may: u32, + ) -> bool { + let has = |level: u32| level < 32 && named & (1 << level) != 0; + let now = |level: u32| level < 32 && named & may & (1 << level) != 0; + let first_packed = self.standard.len() as u32; + // (subresource, tiles, the level if it has tiles of its own) to map now. + let mut wanted: Vec<(u32, u32, Option<usize>)> = Vec::new(); + for level in 0..first_packed { + if !given.levels[level as usize] && now(level) { + wanted.push((level, self.standard[level as usize], Some(level as usize))); + } + } + if self.packed > 0 && !given.packed && (first_packed..self.levels).any(now) { + wanted.push((first_packed, self.packed, None)); + } + // Tiles for each, then one mapping call per heap for all the + // levels that got theirs there: one region per level, the ranges + // of all of them in order (the card gives a call's ranges to its + // regions' tiles in turn). It was a call per level, and a call + // costs as much as hundreds of microseconds. + let mut taken: Vec<Taken> = Vec::new(); + for (subresource, tiles, level) in wanted { + if let Some((heap, index, runs)) = take(device, tiles) { + taken.push(Taken { + heap, + index, + runs, + subresource, + tiles, + level, + }); + } + } + let mut from = 0; + while from < taken.len() { + let index = taken[from].index; + let to = taken[from..].iter().position(|t| t.index != index).map_or(taken.len(), |n| from + n); + let group = &taken[from..to]; + let coords: Vec<D3D12_TILED_RESOURCE_COORDINATE> = group + .iter() + .map(|t| D3D12_TILED_RESOURCE_COORDINATE { + X: 0, + Y: 0, + Z: 0, + Subresource: t.subresource, + }) + .collect(); + let sizes: Vec<D3D12_TILE_REGION_SIZE> = group + .iter() + .map(|t| D3D12_TILE_REGION_SIZE { + NumTiles: t.tiles, + ..Default::default() + }) + .collect(); + let starts: Vec<u32> = group.iter().flat_map(|t| t.runs.iter().map(|run| run.0)).collect(); + let counts: Vec<u32> = group.iter().flat_map(|t| t.runs.iter().map(|run| run.1)).collect(); + let flags = vec![D3D12_TILE_RANGE_FLAG_NONE; starts.len()]; + let began = std::time::Instant::now(); + // SAFETY: a live reserved texture and a live heap of ours; + // `coords.len()` regions, each the whole of a subresource's + // tiles from its first one; `starts.len()` ranges whose counts + // add up to the regions' tiles, in arrays that live through + // the call. + unsafe { + queue.UpdateTileMappings( + texture, + coords.len() as u32, + Some(coords.as_ptr()), + Some(sizes.as_ptr()), + &group[0].heap, + starts.len() as u32, + Some(flags.as_ptr()), + Some(starts.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + STATS[6].fetch_add(1, Ordering::Relaxed); + STATS[7].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + for t in group { + match t.level { + Some(level) => given.levels[level] = true, + None => given.packed = true, + } + for &(start, count) in &t.runs { + given.runs.push((t.index, start, count)); + } + STATS[2].fetch_add(u64::from(t.tiles) * TILE, Ordering::Relaxed); + STATS[5].fetch_add(1, Ordering::Relaxed); + } + from = to; + } + let with_tiles = |level: u32| { + if level < first_packed { + given.levels[level as usize] + } else { + given.packed + } + }; + let shown = (0..self.levels).find(|&level| has(level) && with_tiles(level)).unwrap_or(u32::MAX); + self.shown.swap(shown, Ordering::Relaxed) != shown + } + + /// The levels held at the last upload, a bit a level (0 before the + /// first): for the slot census (`HostHeap::placed_slot_census`). + #[cfg(feature = "diagnostics")] + pub(crate) fn held_now(&self) -> u32 { + self.held.load(Ordering::Relaxed) + } + + /// The first level a view of the texture may show; `None` while no + /// level is both held and given (the views are then as the title made + /// them, and read zeros). + pub(crate) fn first_shown(&self) -> Option<u32> { + let shown = self.shown.load(Ordering::Relaxed); + (shown != u32::MAX).then_some(shown) + } + + /// Whether level `level` has tiles. + #[cfg(test)] + fn has_tiles(&self, level: u32) -> bool { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + match given.levels.get(level as usize) { + Some(&has) => has, + None => level < self.levels && given.packed, + } + } + + /// Whether every level has tiles. + #[cfg(test)] + fn whole(&self) -> bool { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + given.levels.iter().all(|&has| has) && (self.packed == 0 || given.packed) + } + + /// A bit for every level of the texture. + pub(crate) fn every_level(&self) -> u32 { + if self.levels >= 32 { u32::MAX } else { (1 << self.levels) - 1 } + } + + /// The bytes of the tiles it has now. + pub(crate) fn given_bytes(&self) -> u64 { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + given.runs.iter().map(|run| u64::from(run.2) * TILE).sum() + } +} + +impl Drop for Tiled { + fn drop(&mut self) { + let given = self.given.get_mut().unwrap_or_else(|e| e.into_inner()); + let mut bytes = 0; + let mut by_heap: std::collections::BTreeMap<usize, Vec<(u32, u32)>> = std::collections::BTreeMap::new(); + for &(index, start, tiles) in &given.runs { + by_heap.entry(index).or_default().push((start, tiles)); + bytes += u64::from(tiles) * TILE; + } + for (index, runs) in by_heap { + give_back(index, &runs); + } + STATS[0].fetch_sub(1, Ordering::Relaxed); + STATS[1].fetch_sub(self.full, Ordering::Relaxed); + STATS[2].fetch_sub(bytes, Ordering::Relaxed); + } +} + +/// Keeps a two-dimensional shader view (2D or 2D array) from the levels +/// before `first` of a texture of `levels` levels: it starts at `first` if +/// it started before it, shows as many levels fewer (clamped to the +/// remaining levels), and reduces `ResourceMinLODClamp` by the same shift so +/// the effective minimum LOD stays at the same resource level. +pub(crate) fn show_from(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, first: u32, levels: u32) { + if first >= levels { + return; + } + // The title's minimum level stays as it is: `ResourceMinLODClamp` + // counts from the resource's first level, not the view's (fork pull + // request #1210; it was lowered by the levels moved past, which let a + // view sample levels finer than the title allowed). + let clamp = |most: &mut u32, mips: &mut u32| { + if first <= *most { + return; + } + let fewer = first - *most; + *most = first; + if *mips != u32::MAX { + *mips = mips.saturating_sub(fewer).clamp(1, levels - first); + } + }; + match desc.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE2D => { + // SAFETY: `ViewDimension` selects `Texture2D`. + let view = unsafe { &mut desc.Anonymous.Texture2D }; + clamp(&mut view.MostDetailedMip, &mut view.MipLevels); + } + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + // SAFETY: `ViewDimension` selects `Texture2DArray`. + let view = unsafe { &mut desc.Anonymous.Texture2DArray }; + clamp(&mut view.MostDetailedMip, &mut view.MipLevels); + } + _ => {} + } +} + +/// For the log, with the texture queue's line: what this saves, and what +/// the mapping calls cost since the line before. +pub(crate) fn status() { + static BEFORE: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + let s: Vec<u64> = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + if s[4] == 0 { + return; + } + let calls = s[6] - BEFORE[0].swap(s[6], Ordering::Relaxed); + let micros = s[7] - BEFORE[1].swap(s[7], Ordering::Relaxed); + tracing::info!( + "textures with levels on demand: {} alive ({} made so far), {} MB of the card given to {} levels in all, \ + {} MB of the card not allocated for levels the title does not hold ({} MB if every level had memory); \ + the pool's heaps {} MB ({} given back to the card so far); since the line before: {} calls of \ + UpdateTileMappings in {} microseconds; in all {} calls, {} microseconds; {} uploads left a held \ + level without memory (no room on the card, or no heap), {} uploads were recorded again for one", + s[0], + s[4], + s[2] >> 20, + s[5], + s[1].saturating_sub(s[2]) >> 20, + s[1] >> 20, + s[3] >> 20, + s[8], + calls, + micros, + s[6], + s[7], + s[9], + s[10], + ); +} + +/// On the card, without the title: what levels on demand relies on, with +/// the pool and the mapping call of this module on a device of the test's +/// own. One test, one device: the pool is one for the process, and its +/// heaps belong to the device that made them. +/// +/// Run by name, alone, no game needed: +/// `cargo test -p victory-gpu --release -- --ignored levels_on_demand --nocapture` +/// +/// It runs on the SOFTWARE adapter unless `VICTORY_TILES_TEST_CARD=1`: on +/// that adapter nothing reaches the card or its driver, so nothing it does +/// can reset the driver or touch the screen. Wherever it runs, the debug +/// layer is switched on if Windows has it (the optional feature "Graphics +/// Tools"), its messages are printed after every step, and the test stops +/// at the first error or lost device with the step's name, before +/// anything else is sent. On the card it does not run without the layer, +/// and no wait is longer than 1.5 s. +#[cfg(test)] +mod tests { + use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + use windows::core::{Interface, s}; + + use super::*; + use crate::host::{compile, transition, warp_adapter}; + + /// Try 6.16: the rush keeps its two lines, and after it ends it does not + /// come back before the gap has passed however long the queue is. + #[test] + fn the_rush_rests_between_turns() { + assert!(!rush_next(false, 1499, true)); + assert!(rush_next(false, 1500, true)); + assert!(!rush_next(false, 3000, false), "not again within the gap"); + assert!(rush_next(true, 300, false), "an ongoing rush runs on"); + assert!(!rush_next(true, 299, true)); + } + + const SIDE: u32 = 1024; + const LEVELS: u16 = 11; + + /// Two views of one texture read at the same place and level: the + /// first as the layer makes it for a texture whose level 0 has no + /// memory, the second as the title asked. + const LOOK: &str = r#" +#define RS "DescriptorTable(SRV(t0, numDescriptors = 2)), UAV(u0), StaticSampler(s0, filter = FILTER_MIN_MAG_MIP_POINT)" +Texture2D<float4> clamped : register(t0); +Texture2D<float4> whole : register(t1); +SamplerState nearest : register(s0); +RWByteAddressBuffer words : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void look() { + float4 a = clamped.SampleLevel(nearest, float2(0.3, 0.3), 0); + float4 b = whole.SampleLevel(nearest, float2(0.3, 0.3), 0); + words.Store(0, (uint)(a.x * 255.0 + 0.5)); + words.Store(4, (uint)(b.x * 255.0 + 0.5)); +} +"#; + + /// Where each level of a texture lies in a buffer of all of them: its + /// place, its rows, the bytes of a row that are the level's own, and + /// the buffer's bytes. + struct Laid { + footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>, + rows: Vec<u32>, + wide: Vec<u64>, + total: u64, + } + + struct Rig { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + event: HANDLE, + submitted: u64, + /// The debug layer's messages, if Windows has the layer. + messages: Option<ID3D12InfoQueue>, + /// What the test is doing, for the message when it stops. + step: &'static str, + /// On the card, not on the software adapter. + card: bool, + } + + impl Rig { + /// The software adapter, or the default one with + /// `VICTORY_TILES_TEST_CARD=1`; `None` without one, without tiled + /// resources of tier 2, or on the card without the debug layer. + fn new() -> Option<Rig> { + // SAFETY: plain object creation on a device of our own. + unsafe { + let card = std::env::var_os("VICTORY_TILES_TEST_CARD").is_some_and(|v| v == "1"); + // The debug layer, before the device is made: a call that + // is not well formed is then refused and named by the + // runtime, not handed to the driver. + let mut layer: Option<ID3D12Debug> = None; + let layered = D3D12GetDebugInterface(&mut layer).is_ok() && layer.is_some(); + layer.iter().for_each(|l| l.EnableDebugLayer()); + if card && !layered { + eprintln!("no D3D12 debug layer (Windows optional feature \"Graphics Tools\"): not run on the card without it"); + return None; + } + let mut device: Option<ID3D12Device> = None; + if card { + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + } else { + let adapter = warp_adapter().ok()?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + } + let device = device?; + let messages = device.cast::<ID3D12InfoQueue>().ok(); + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .ok()?; + eprintln!( + "levels on demand, {}: tiled resources tier {}, debug layer {}", + if card { "ON THE CARD" } else { "on the software adapter" }, + options.TiledResourcesTier.0, + if messages.is_some() { "on" } else { "not installed" } + ); + if options.TiledResourcesTier.0 < 2 { + return None; + } + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + Some(Rig { + device, + queue, + allocator, + list, + fence, + event, + submitted: 0, + messages, + step: "making the device", + card, + }) + } + } + + /// Prints what the debug layer said since the last call; the first + /// error among it (as `host.rs` `log_messages` reads them). + fn said(&self) -> Option<String> { + let queue = self.messages.as_ref()?; + let mut first_error = None; + // SAFETY: each message is read into a buffer of the size the + // queue reports, then the queue is emptied. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() { + let m = &*message; + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = String::from_utf8_lossy(text); + let text = text.trim_end_matches('\0'); + eprintln!("D3D12 says (severity {}, id {}): {text}", m.Severity.0, m.ID.0); + if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() { + first_error = Some(text.to_owned()); + } + } + } + queue.ClearStoredMessages(); + } + first_error + } + + /// Stops the test, naming the step, if the device is lost or the + /// debug layer reported an error: nothing more is sent after it. + fn check(&self, what: &str) { + let error = self.said(); + // SAFETY: a plain query. + let removed = unsafe { self.device.GetDeviceRemovedReason() }; + assert!(removed.is_ok(), "{}, {what}: the device is lost: {removed:?}", self.step); + assert!(error.is_none(), "{}, {what}: the debug layer reports an error: {}", self.step, error.unwrap_or_default()); + } + + /// Gives tiles as a submission would, and stops if the mapping + /// call was refused. + fn give(&self, tiled: &Tiled, texture: &ID3D12Resource, levels: u32) { + tiled.give_on(&self.queue, &self.device, texture, levels, levels); + self.check("tiles given"); + } + + /// Records with `record`, runs the list behind what is already on + /// the queue (tile mappings among it), waits for the card and + /// opens the list again. + fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) { + record(&self.list); + self.submitted += 1; + // SAFETY: our list, queue and fence; the allocator is reset + // only after the card finished everything recorded from it. + unsafe { + self.list.Close().unwrap(); + let run: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + // Never without end: a step is a few copies of a few + // megabytes. On the card the limit stays under Windows' own + // two seconds; the software adapter, which compiles its + // shader on first use and resets nothing, gets longer. + let limit = if self.card { 1500 } else { 20_000 }; + let waited = WaitForSingleObject(self.event, limit); + self.check("a submission"); + assert!( + waited == WAIT_OBJECT_0, + "{}: a submission did not finish within {limit} ms; stopped before another is sent", + self.step + ); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + + fn buffer(&self, kind: D3D12_HEAP_TYPE, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES, bytes: u64) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut out: Option<ID3D12Resource> = None; + // SAFETY: plain buffer creation. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + /// A square texture description of `side` texels and `levels` + /// levels; `reserved`: in the layout a texture without memory of + /// its own must have. + fn desc(format: DXGI_FORMAT, side: u32, levels: u16, reserved: bool) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(side), + Height: side, + DepthOrArraySize: 1, + MipLevels: levels, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: if reserved { D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE } else { D3D12_TEXTURE_LAYOUT_UNKNOWN }, + ..Default::default() + } + } + + /// A texture without memory, in the state copies into it need, and + /// how the card cuts it. + fn reserved(&self, desc: &D3D12_RESOURCE_DESC) -> (ID3D12Resource, Tiled) { + let mut made: Option<ID3D12Resource> = None; + // SAFETY: plain creation; a texture that is no target has no clear value. + let asked = unsafe { + self.device + .CreateReservedResource(desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + }; + // The layer's reason first, if it refused. + self.check("a texture without memory made"); + asked.expect("a reserved texture"); + let texture = made.expect("a reserved texture"); + let tiled = Tiled::make(&self.device, &texture, u32::from(desc.MipLevels)).expect("the card says how it cuts the texture"); + (texture, tiled) + } + + fn footprints(&self, desc: &D3D12_RESOURCE_DESC) -> Laid { + let levels = usize::from(desc.MipLevels); + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); levels]; + let mut rows = vec![0u32; levels]; + let mut wide = vec![0u64; levels]; + let mut total = 0u64; + // SAFETY: outputs for `levels` subresources. + unsafe { + self.device.GetCopyableFootprints( + desc, + 0, + levels as u32, + 0, + Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), + Some(wide.as_mut_ptr()), + Some(&mut total), + ); + } + Laid { + footprints, + rows, + wide, + total, + } + } + + /// An upload buffer of `total` bytes in which the bytes of each + /// level are `byte(level)`. + fn filled(&self, layout: &Laid, byte: impl Fn(usize) -> u8) -> ID3D12Resource { + let (footprints, rows) = (&layout.footprints, &layout.rows); + let upload = self.buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ, layout.total); + // SAFETY: the buffer is `total` bytes; each level's rows lie inside it. + unsafe { + let mut data = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut data)).unwrap(); + for (level, f) in footprints.iter().enumerate() { + let len = rows[level] as usize * f.Footprint.RowPitch as usize; + std::slice::from_raw_parts_mut(data.cast::<u8>().add(f.Offset as usize), len).fill(byte(level)); + } + upload.Unmap(0, None); + } + upload + } + + /// Copies every level of `texture` from `upload`, then every level + /// back, and gives for each level the first sixteen bytes read of + /// its first row and of the row and column half way (another tile + /// of a level of several). + fn round_trip( + &mut self, + texture: &ID3D12Resource, + layout: &Laid, + upload: Option<&ID3D12Resource>, + ) -> Vec<[Vec<u8>; 2]> { + let (footprints, rows) = (&layout.footprints, &layout.rows); + let back = self.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, layout.total); + self.run(|list| { + // SAFETY: an open list; the texture and buffers outlive the run. + unsafe { + if let Some(upload) = upload { + for (level, f) in footprints.iter().enumerate() { + list.CopyTextureRegion(&sub(texture, level as u32), 0, 0, 0, &placed(upload, *f), None); + } + } + list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + for (level, f) in footprints.iter().enumerate() { + list.CopyTextureRegion(&placed(&back, *f), 0, 0, 0, &sub(texture, level as u32), None); + } + list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]); + } + }); + let mut read = Vec::new(); + // SAFETY: a read-back buffer of `total` bytes the finished list copied into. + unsafe { + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + for (level, f) in footprints.iter().enumerate() { + let pitch = f.Footprint.RowPitch as usize; + let len = rows[level] as usize * pitch; + let bytes = std::slice::from_raw_parts(data.cast::<u8>().cast_const().add(f.Offset as usize), len); + // The bytes of a row that are the level's own (its + // blocks or texels; the rest of the pitch is padding). + let own = layout.wide[level] as usize; + let wide = own.min(len).min(16); + let first = bytes[..wide].to_vec(); + let middle = (rows[level] as usize / 2) * pitch + ((own / 2) & !15); + let far = if rows[level] >= 2 && own >= 32 && middle + wide <= len { + bytes[middle..middle + wide].to_vec() + } else { + first.clone() + }; + read.push([first, far]); + } + back.Unmap(0, None); + } + read + } + } + + fn sub(texture: &ID3D12Resource, index: u32) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: index }, + } + } + + fn placed(buffer: &ID3D12Resource, footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + } + } + + fn all(bytes: &[Vec<u8>; 2], want: u8) -> bool { + bytes.iter().all(|part| part.iter().all(|&b| b == want)) + } + + /// The levels from `first` on, a bit a level. + fn from_level(first: u32) -> u32 { + (u32::MAX << first) & ((1 << u32::from(LEVELS)) - 1) + } + + /// (i) Levels arrive one by one: after each step every level with + /// tiles reads back its own bytes and every level without reads zeros. + fn levels_arrive(rig: &mut Rig, format: DXGI_FORMAT) { + rig.step = if format == DXGI_FORMAT_BC7_UNORM { "step 1, levels arrive (BC7)" } else { "step 1, levels arrive (BC3)" }; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + // (The card packs the levels smaller than a tile into shared + // tiles; the software adapter may give each its own.) + eprintln!( + "format {}: {} levels with tiles of their own ({:?} tiles), {} tiles for the packed ones", + format.0, + tiled.standard.len(), + tiled.standard, + tiled.packed + ); + assert!(!rig.card || tiled.packed > 0, "on the card a 1024 texture has levels smaller than a tile"); + let layout = rig.footprints(&desc); + let upload = rig.filled(&layout, |level| level as u8 + 1); + for first in [3u32, 1, 0] { + // Ahead of the list on the queue, as at a submission. + rig.give(&tiled, &texture, from_level(first)); + let read = rig.round_trip(&texture, &layout, Some(&upload)); + for (level, bytes) in read.iter().enumerate() { + let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 }; + assert!(all(bytes, want), "format {} from level {first}: level {level} reads {bytes:?}, wanted {want}", format.0); + } + } + assert!(tiled.whole()); + assert_eq!(tiled.first_shown(), Some(0)); + } + + /// (ii) A copy on the card into a level without tiles is dropped; the + /// same copy in a list that runs after the level was given lands. + fn a_card_copy_lands_after_the_give(rig: &mut Rig) { + rig.step = "step 2, a copy on the card into a level without tiles"; + let format = DXGI_FORMAT_BC7_UNORM; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + let layout = rig.footprints(&desc); + // The last level with tiles of its own, and a texture of its size + // with every byte 0x5a to copy from. + let level = tiled.standard.len() as u32 - 1; + let source_desc = Rig::desc(format, SIDE >> level, 1, false); + let source_layout = rig.footprints(&source_desc); + let source_bytes = rig.filled(&source_layout, |_| 0x5a); + let mut made: Option<ID3D12Resource> = None; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + // SAFETY: plain texture creation. + unsafe { + rig.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &source_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + .unwrap(); + } + let source = made.unwrap(); + rig.run(|list| { + // SAFETY: an open list and live resources. + unsafe { + list.CopyTextureRegion(&sub(&source, 0), 0, 0, 0, &placed(&source_bytes, source_layout.footprints[0]), None); + list.ResourceBarrier(&[transition(&source, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + // No tiles yet: this copy goes nowhere. + list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None); + } + }); + let before = rig.round_trip(&texture, &layout, None); + assert!(all(&before[level as usize], 0), "a copy into a level without tiles left {:?}", before[level as usize]); + // As `texture.rs` `card_writes` has it: the give at the list's + // submission, the copy in the list. + assert_ne!(tiled.claim(tiled.with_level(level)), 0, "the level is new"); + rig.give(&tiled, &texture, tiled.with_level(level)); + rig.run(|list| { + // SAFETY: as above. + unsafe { list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None) }; + }); + let after = rig.round_trip(&texture, &layout, None); + assert!(all(&after[level as usize], 0x5a), "the copy after the give left {:?}", after[level as usize]); + assert_eq!(tiled.claim(tiled.with_level(level)), 0, "claimed once"); + } + + /// (iii) Tiles a texture gave back go to the next one, which reads + /// what was written into it and zeros where it has no tiles; what a + /// level given and not written reads is printed (the reason no level + /// is given outside a list that writes it). + fn a_reused_tile_reads_as_written(rig: &mut Rig) { + rig.step = "step 3, a reused tile"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (first, first_tiles) = rig.reserved(&desc); + let level = first_tiles.standard.len() as u32 - 1; + rig.give(&first_tiles, &first, 1 << level); + let upload = rig.filled(&layout, |_| 0xa5); + let read = rig.round_trip(&first, &layout, Some(&upload)); + assert!(all(&read[level as usize], 0xa5)); + let runs = first_tiles.given.lock().unwrap().runs.clone(); + drop(first_tiles); + drop(first); + let (second, second_tiles) = rig.reserved(&desc); + rig.give(&second_tiles, &second, 1 << level); + let reused = second_tiles.given.lock().unwrap().runs == runs; + let unwritten = rig.round_trip(&second, &layout, None); + eprintln!( + "a level given tiles and not written reads {:?} (its tiles are the first texture's: {reused})", + &unwritten[level as usize][0][..4] + ); + let upload = rig.filled(&layout, |_| 0x3c); + let read = rig.round_trip(&second, &layout, Some(&upload)); + assert!(all(&read[level as usize], 0x3c), "the reused level reads {:?}", read[level as usize]); + assert!(all(&read[0], 0), "level 0 has no tiles and reads {:?}", read[0]); + } + + /// (iv) A level whose tiles come from several runs of the heap (single + /// free tiles between taken ones) reads as written in every tile. + fn a_level_on_several_ranges(rig: &mut Rig) { + rig.step = "step 4, a level on several ranges of the heap"; + // Three single tiles; the first and the last go back, the middle + // one stays taken. + let singles: Vec<_> = (0..3).map(|_| take(&rig.device, 1).expect("a tile")).collect(); + give_back(singles[0].1, &singles[0].2); + give_back(singles[2].1, &singles[2].2); + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (texture, tiled) = rig.reserved(&desc); + // Level 1 of a 1024 texture: four tiles. + assert!(tiled.standard.len() > 1 && tiled.standard[1] >= 2); + rig.give(&tiled, &texture, 1 << 1); + let runs = tiled.given.lock().unwrap().runs.len(); + eprintln!("level 1 ({} tiles) was mapped on {runs} ranges", tiled.standard[1]); + assert!(runs >= 2, "the single free tiles were not used first"); + let upload = rig.filled(&layout, |_| 0x77); + let read = rig.round_trip(&texture, &layout, Some(&upload)); + assert!(all(&read[1], 0x77), "level 1 reads {:?}", read[1]); + give_back(singles[1].1, &singles[1].2); + } + + /// (v) A view made by [`show_from`] of a texture whose level 0 has no + /// tiles returns level 1's colour for a sample at level 0; the view as + /// the title asked returns zero. + fn the_view_starts_at_the_first_level_with_tiles(rig: &mut Rig) -> Option<()> { + rig.step = "step 5, the view from the first level with tiles"; + let cs = compile(LOOK, s!("look"), s!("cs_5_1")).ok()?; + let format = DXGI_FORMAT_R8G8B8A8_UNORM; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (texture, tiled) = rig.reserved(&desc); + // Every level but the largest; each level's bytes are sixteen + // times its number plus one. + rig.give(&tiled, &texture, from_level(1)); + assert_eq!(tiled.first_shown(), Some(1)); + let upload = rig.filled(&layout, |level| (level as u8 + 1) * 16); + rig.round_trip(&texture, &layout, Some(&upload)); + // SAFETY: plain object creation; the views are made in a heap + // that lives to the end of the function, of a live texture. + let (root, pipeline, views, words, back) = unsafe { + let root: ID3D12RootSignature = rig.device.CreateRootSignature(0, &cs[..]).ok()?; + let pipeline: ID3D12PipelineState = rig + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }) + .ok()?; + let views: ID3D12DescriptorHeap = rig + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + let as_asked = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: u32::MAX, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }; + let mut shown = as_asked; + show_from(&mut shown, tiled.first_shown()?, u32::from(LEVELS)); + assert_eq!(shown.Anonymous.Texture2D.MostDetailedMip, 1); + let step = rig.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let mut at = views.GetCPUDescriptorHandleForHeapStart(); + rig.device.CreateShaderResourceView(&texture, Some(&raw const shown), at); + at.ptr += step; + rig.device.CreateShaderResourceView(&texture, Some(&raw const as_asked), at); + let words = rig.buffer( + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + 256, + ); + let back = rig.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, 256); + (root, pipeline, views, words, back) + }; + // Before the one dispatch: the pipeline and both views are sound. + rig.check("the pipeline and the views made"); + rig.run(|list| { + // SAFETY: an open list and live objects. + unsafe { + list.ResourceBarrier(&[transition(&texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + list.SetDescriptorHeaps(&[Some(views.clone())]); + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pipeline); + list.SetComputeRootDescriptorTable(0, views.GetGPUDescriptorHandleForHeapStart()); + list.SetComputeRootUnorderedAccessView(1, words.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&words, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&back, 0, &words, 0, 16); + } + }); + // SAFETY: a read-back buffer the finished list copied sixteen bytes into. + let read = unsafe { + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: 16 }; + back.Map(0, Some(&range), Some(&mut data)).unwrap(); + let read = std::slice::from_raw_parts(data.cast::<u32>(), 2).to_vec(); + back.Unmap(0, None); + read + }; + eprintln!("a sample at level 0: {} through the view from level 1, {} through the view as asked", read[0], read[1]); + assert_eq!(read[0], 32, "the view from the first level with tiles reads level 1"); + assert_eq!(read[1], 0, "the view from level 0 reads a level without tiles"); + Some(()) + } + + fn a_full_card_keeps_new_levels_waiting(rig: &mut Rig) { + rig.step = "step 6, no room on the card: held levels wait, and get their tiles when asked again"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + let layout = rig.footprints(&desc); + let upload = rig.filled(&layout, |level| level as u8 + 1); + let read_as_given = |rig: &mut Rig, what: &str| { + let read = rig.round_trip(&texture, &layout, Some(&upload)); + for (level, bytes) in read.iter().enumerate() { + let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 }; + assert!(all(bytes, want), "{what}: level {level} reads {bytes:?}, wanted {want}"); + } + }; + // No room: nothing is given, the held levels are said to wait, + // nothing is shown, every level reads zeros. + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), false); + rig.check("an upload without room"); + assert!(!changed && waiting, "without room: changed {changed}, waiting {waiting}"); + assert_eq!(tiled.given_bytes(), 0, "without room no tile is given"); + assert_eq!(tiled.first_shown(), None); + read_as_given(rig, "without room"); + // Asked again with room: the same levels get theirs. + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), true); + rig.check("the upload again, with room"); + assert!(changed && !waiting, "with room: changed {changed}, waiting {waiting}"); + assert!(tiled.has_tiles(3) && !tiled.has_tiles(2)); + assert_eq!(tiled.first_shown(), Some(3)); + read_as_given(rig, "with room"); + // More levels held and no room again: the ones that have tiles + // are brought up to date, the new ones wait, the view stays. + let before = tiled.given_bytes(); + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), false); + rig.check("more levels held, without room"); + assert!(!changed && waiting, "more levels without room: changed {changed}, waiting {waiting}"); + assert_eq!(tiled.given_bytes(), before); + assert_eq!(tiled.first_shown(), Some(3)); + read_as_given(rig, "more levels without room"); + // The card's own write is not kept waiting, and brings only its + // own level: level 1 still waits although it is held. + assert_eq!(tiled.claim(1 << 0), 1 << 0); + let changed = tiled.card_wrote_on(&rig.queue, &rig.device, &texture, 1 << 0); + rig.check("the card's own write, without room"); + assert!(changed && tiled.has_tiles(0) && !tiled.has_tiles(1) && !tiled.has_tiles(2)); + assert_eq!(tiled.first_shown(), Some(0)); + assert_eq!(tiled.claim(1 << 0), 0, "a level with tiles is not claimed again"); + // With room everything held gets its tiles. + let (_, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), true); + rig.check("the last upload, with room"); + assert!(!waiting && tiled.whole()); + read_as_given(rig, "everything given"); + } + + fn a_claim_given_up_is_made_again(rig: &mut Rig) { + rig.step = "step 7, a claim whose zeros never landed is given up"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let (_texture, tiled) = rig.reserved(&desc); + let level = tiled.with_level(2); + assert_eq!(tiled.claim(level), level, "the level is new"); + assert_eq!(tiled.claim(level), 0, "claimed once"); + // The list that claimed it was reset without being submitted. + tiled.unclaim(level); + assert_eq!(tiled.claim(level), level, "claimed again after it was given up"); + // The small levels the card packs together are claimed together. + let small = tiled.with_level(u32::from(LEVELS) - 1); + assert!(!rig.card || small.count_ones() > 1, "on the card a 1024 texture has several levels in one tile"); + assert_eq!(tiled.claim(1 << (u32::from(LEVELS) - 1)), 1 << (u32::from(LEVELS) - 1)); + tiled.unclaim(small); + assert_eq!(tiled.claim(small), small); + } + + /// On the software adapter unless `VICTORY_TILES_TEST_CARD=1`. + #[test] + #[ignore = "on the card: run it by name with --ignored --nocapture"] + fn levels_on_demand_on_the_card() { + let Some(mut rig) = Rig::new() else { + eprintln!("no adapter with tiled resources of tier 2, or no debug layer for a run on the card; skipped"); + return; + }; + rig.check("the device made"); + levels_arrive(&mut rig, DXGI_FORMAT_BC7_UNORM); + levels_arrive(&mut rig, DXGI_FORMAT_BC3_UNORM); + a_card_copy_lands_after_the_give(&mut rig); + a_reused_tile_reads_as_written(&mut rig); + a_level_on_several_ranges(&mut rig); + a_full_card_keeps_new_levels_waiting(&mut rig); + a_claim_given_up_is_made_again(&mut rig); + if the_view_starts_at_the_first_level_with_tiles(&mut rig).is_none() { + eprintln!("the view test's shader or objects could not be made; that part was skipped"); + } + rig.step = "the end"; + rig.check("every step done"); + eprintln!( + "all steps passed {}", + if rig.card { "ON THE CARD" } else { "on the software adapter; VICTORY_TILES_TEST_CARD=1 is the run on the card" } + ); + let s: Vec<u64> = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + eprintln!( + "{} calls of UpdateTileMappings took {} microseconds in all ({} a call); the pool's heaps {} MB, {} given back", + s[6], + s[7], + s[7] / s[6].max(1), + s[3] >> 20, + s[8] + ); + } + + #[test] + fn floor_saturates_instead_of_wrapping() { + assert_eq!(parse_floor(None), 1 << 20); + assert_eq!(parse_floor(Some("0")), 64 << 10); + assert_eq!(parse_floor(Some("2048")), 2048 << 10); + assert_eq!(parse_floor(Some(&(1u64 << 54).to_string())), u64::MAX); + assert_eq!(parse_floor(Some(&u64::MAX.to_string())), u64::MAX); + } + + #[test] + fn show_from_clamps_2d_and_2d_array_and_keeps_min_lod() { + let mut srv2d = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 12, + PlaneSlice: 0, + ResourceMinLODClamp: 3.5, + }, + }, + }; + show_from(&mut srv2d, 3, 11); + // SAFETY: `ViewDimension` is `TEXTURE2D`. + let v2d = unsafe { srv2d.Anonymous.Texture2D }; + assert_eq!(v2d.MostDetailedMip, 3); + // Clamped to remaining levels (11 - 3 = 8), not 12 - 3 = 9. + assert_eq!(v2d.MipLevels, 8); + assert_eq!(v2d.ResourceMinLODClamp, 3.5); + + let mut srv_arr = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: 0, + MipLevels: 6, + FirstArraySlice: 0, + ArraySize: 1, + PlaneSlice: 0, + ResourceMinLODClamp: 1.5, + }, + }, + }; + show_from(&mut srv_arr, 2, 11); + // SAFETY: `ViewDimension` is `TEXTURE2DARRAY`. + let varr = unsafe { srv_arr.Anonymous.Texture2DArray }; + assert_eq!(varr.MostDetailedMip, 2); + assert_eq!(varr.MipLevels, 4); + assert_eq!(varr.ResourceMinLODClamp, 1.5); + } + + #[test] + fn card_wrote_failure_does_not_poison_card_mask() { + let Some(host) = host() else { + return; + }; + // A dummy live resource (never mapped because `take()` rejects `HEAP_TILES + 1`). + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = Rig::desc(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 2, false); + let mut tex: Option<ID3D12Resource> = None; + // SAFETY: plain texture creation on the host device. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut tex, + ) + .unwrap(); + } + let tex = tex.unwrap(); + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(TILE, Ordering::Relaxed); + let mut tiled = Tiled { + // Level 0 demands > HEAP_TILES so `take()` fails deterministically. + standard: vec![HEAP_TILES + 1, 1], + packed: 0, + levels: 2, + full: TILE, + given: Mutex::new(Given { + levels: vec![false, false], + packed: false, + runs: Vec::new(), + }), + shown: AtomicU32::new(u32::MAX), + held: AtomicU32::new(0), + card: AtomicU32::new(0), + blurred: std::sync::atomic::AtomicBool::new(false), + claimed: AtomicU32::new(0), + }; + assert_eq!(tiled.claim(1 << 0), 1 << 0); + let changed = tiled.card_wrote_on(host.queue(), &host.device, &tex, 1 << 0); + assert!(!changed); + assert_eq!(tiled.card.load(Ordering::Relaxed), 0, "failed tile allocation must not poison `card`"); + assert_eq!(tiled.first_shown(), None); + assert_eq!(tiled.claim(1 << 0), 1 << 0, "failed level must be unclaimed"); + // Even if level 0 later becomes allocatable, an upload with `room == false` + // that does not hold level 0 must not treat level 0 as card-owned. + tiled.standard[0] = 1; + let (changed, waiting) = tiled.uploaded_on(host.queue(), &host.device, &tex, 1 << 1, false); + assert!(!changed && waiting); + assert!(!tiled.has_tiles(0)); + assert_eq!(tiled.given_bytes(), 0); + } +} diff --git a/crates/victory-gpu/src/timeline.rs b/crates/victory-gpu/src/timeline.rs deleted file mode 100644 index 6650f5d98c..0000000000 --- a/crates/victory-gpu/src/timeline.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! A queue's timeline: its work in submission order, held back behind a -//! GPU-side wait (`ID3D12CommandQueue::Wait`) until the fence reaches the -//! value. -//! -//! Work runs on the thread that submits it, as before, unless the queue is -//! held back: then the submission returns at once and the work runs later, -//! on the thread that moves the fence (a signal or a bottom-of-pipe write -//! from another queue, or the title's CPU signal). Nothing blocks a -//! submitting thread behind a wait, so a thread may submit a queue's wait -//! before the signal it waits for. -//! -//! Locks: a timeline's state is taken before a fence's waiters, never -//! after; work runs with no lock held. - -use std::collections::VecDeque; -use std::sync::{Arc, Condvar, Mutex, MutexGuard}; - -use crate::fence::Held; - -/// One step of a queue's work. -pub(crate) enum Op { - /// Hold back what follows until the fence reaches the value. - Wait(Held, u64), - /// Command lists to run, a fence to signal. - Run(Box<dyn FnOnce() + Send>), -} - -#[derive(Default)] -pub(crate) struct Timeline { - state: Mutex<State>, - /// Signalled whenever work is done or the queue stops running it. - moved: Condvar, -} - -#[derive(Default)] -struct State { - ops: VecDeque<Op>, - /// Ops submitted and ops done (a submission's ticket is its count). - pushed: u64, - done: u64, - /// A thread is running the queue's work. - busy: bool, - /// The first op is a wait not reached yet, registered with its fence. - held: bool, -} - -impl Timeline { - fn lock(&self) -> MutexGuard<'_, State> { - self.state.lock().unwrap_or_else(|e| e.into_inner()) - } - - /// Adds work to the queue and runs it unless the queue is held back. - /// Work another thread is running for the queue is waited for, as a - /// submission's own work is. - pub(crate) fn submit(self: &Arc<Self>, op: Op) { - let mut s = self.lock(); - s.ops.push_back(op); - s.pushed += 1; - let ticket = s.pushed; - while s.busy && s.done < ticket { - s = self.moved.wait(s).unwrap_or_else(|e| e.into_inner()); - } - if s.done >= ticket { - return; - } - // Still held back unless the value was reached by a path that does - // not wake us (a CPU write to the fence's memory). - if s.held - && let Some(Op::Wait(fence, value)) = s.ops.front() - && !fence.reached(*value) - { - return; - } - self.run(s); - } - - /// The fence this queue waits for moved: runs what it held back. - pub(crate) fn wake(self: &Arc<Self>) { - let s = self.lock(); - if !s.busy { - self.run(s); - } - } - - fn run<'a>(self: &'a Arc<Self>, mut s: MutexGuard<'a, State>) { - s.busy = true; - s.held = false; - while let Some(op) = s.ops.pop_front() { - match op { - Op::Wait(fence, value) => { - // Checked and registered under the fence's lock, so a - // signal after this check wakes us. - if !fence.wait_on_gpu(value, self) { - s.ops.push_front(Op::Wait(fence, value)); - s.held = true; - break; - } - } - Op::Run(work) => { - drop(s); - work(); - s = self.lock(); - } - } - s.done += 1; - self.moved.notify_all(); - } - s.busy = false; - self.moved.notify_all(); - } -} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index f85b88b84e..0e65952918 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -10,13 +10,24 @@ //! copy leaves each 64 KiB block it took read-only, and our vectored handler //! takes the first write to it: it notes the block as written and gives the //! write access back. The runtime tells us when it maps or unmaps views -//! ([`title_memory_remapped`]), which resets their protection. +//! ([`title_memory_remapped`]), which resets their protection. Blocks found +//! wholly uncommitted are skipped while they remain so; one query can +//! confirm a whole region, including ordinary reservations between views. //! -//! shortcut: writes into physical pages through another view (xmem's -//! `write_physical`, DirectStorage's page destinations) are not seen at -//! the guarded addresses; they go to the texture pool, whose textures are -//! hashed, not guarded. A system call writing into a guarded block fails -//! (none is known to). +//! Writes into physical pages through another view are seen too: the +//! runtime tells us the views of the pages it wrote itself ([`writing`], +//! xmem's `write_physical` and DirectStorage's page destinations), and a +//! write by the title through any view of a guarded page faults like one +//! at the guarded address (the guard makes every view of the page +//! read-only, [`open`] gives them all back; not a page of more than +//! [`MANY_VIEWS`] views). A +//! system call writing into a guarded block fails (none is known to). +//! +//! With `VICTORY_LIGHT_REFRESH` a block that is read-only by our hand, +//! unwritten since, and whose earlier writes are all in the journal has a +//! bit ([`PUBLISHED`]): a range whose blocks all have theirs is answered +//! from the journal alone, with no lock of the guards and no kernel call +//! ([`light`]). use std::collections::{BTreeMap, BTreeSet}; use std::sync::Mutex; @@ -28,69 +39,331 @@ pub(crate) const PAGE: usize = 64 << 10; /// The kernel's page, the unit of its answers. const KERNEL_PAGE: usize = 4096; +/// A title-memory range whose changed pages another subsystem needs to read. +pub(crate) struct Tracked { + start: usize, + end: usize, + seen: Mutex<BTreeMap<usize, u64>>, +} + +/// Tracks a runtime GPU-memory range, including physical-page views when +/// `views` is true. Other process memory is not tracked. +pub(crate) fn track(start: usize, len: usize, views: bool) -> Option<Tracked> { + let end = start.checked_add(len)?; + if len == 0 || writes(start, end, views).is_none() { + return None; + } + Some(Tracked { + start, + end, + seen: Mutex::default(), + }) +} + struct Journal { /// Numbers the askings; 0 is "never". asked: u64, /// Page number → the asking that last found it written. written: BTreeMap<usize, u64>, + /// With `VICTORY_DIRTY_4K` ([`dirty4k`]): page number → the asking of `written` for it, the asking before that + /// which had found it written (0: never), and the 4 KiB kernel pages of it that asking found written (bit k: bytes + /// `k * 4096..(k + 1) * 4096` of the page). Only where the kernel's write watch answered: a page noted written + /// any other way (the guards, our own writes) has no entry, and counts as written whole. + sub: BTreeMap<usize, (u64, u64, u16)>, /// Room for the kernel's answer. found: Vec<usize>, - /// Page ranges the kernel was asked about since the submission began - /// (see [`new_submission`]); under Wine only. - asked_now: Vec<(usize, usize)>, + /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`]) + /// and the asking that did: `writes` answers for a range inside one + /// from the journal, without another kernel call. + ahead: Vec<(usize, usize)>, + ahead_asked: u64, + /// Askings of [`writes`] in the kernel now, with the journal let go: + /// their pages and tickets (Try 6.6). + asking: Vec<(usize, usize, u64)>, + ticket: u64, + /// The ahead asking stands for a whole submission ([`ask_once`]): no + /// other ahead asking is made, and `ahead` stays, until + /// [`ask_once_end`]. + kept: bool, } static JOURNAL: Mutex<Journal> = Mutex::new(Journal { asked: 0, written: BTreeMap::new(), + sub: BTreeMap::new(), found: Vec::new(), - asked_now: Vec::new(), + ahead: Vec::new(), + ahead_asked: 0, + asking: Vec::new(), + ticket: 0, + kept: false, }); -/// Whether we run under Wine (its ntdll exports `wine_get_version`). -fn on_wine() -> bool { - static WINE: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| { - use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; - // SAFETY: plain lookups in ntdll, always loaded. - unsafe { - let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); - !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() +/// Ranges of one submission closer than this are asked about together: +/// walking the pages between them costs less than another kernel call (a +/// call that resets written pages costs 30-70 microseconds whatever the +/// range). +const AHEAD_GAP: usize = (8 << 20) / PAGE; +/// The most one asking covers (its answer needs 8 bytes per 4 KiB page). +const AHEAD_MAX: usize = (1 << 30) / PAGE; + +/// Asks the kernel about many ranges `(start, end)` at once, before the +/// [`writes`] of each: ranges close together are one asking, and `writes` +/// then answers from the journal until [`ask_ahead_done`]. The world's +/// submissions refresh thousands of host copies (6,664 askings a frame, +/// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are +/// left to `writes`. +pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { + let mut pieces: Vec<(usize, usize)> = ranges + .iter() + .filter(|r| r.0 < r.1) + .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) + .collect(); + if pieces.len() < 2 { + return; + } + pieces.sort_unstable(); + let mut j = quiet(JOURNAL.lock().unwrap_or_else(|e| e.into_inner())); + let j = &mut *j; + // The submission's one asking stands ([`ask_once`]): what it does not + // hold is left to `writes`. + if j.kept { + return; + } + // View memory the guards hold is left to `writes`, which answers it + // from the guards ([`known_view`]): the kernel's write watch can only + // fail there. Asked here with the others, a run holding such a range + // failed, was asked again by halves down to single ranges, failing + // each time, and the range then went to `writes` all the same (after + // triippywhale d0581a55). `VICTORY_VIEW_ASK=1` asks as before. + #[cfg(feature = "diagnostics")] + let all = pieces.len(); + pieces.retain(|&(first, _)| !known_view(first * PAGE)); + #[cfg(feature = "diagnostics")] + AHEAD_VIEWS.fetch_add((all - pieces.len()) as u64, std::sync::atomic::Ordering::Relaxed); + j.asked += 1; + j.ahead_asked = j.asked; + j.ahead.clear(); + let mut i = 0; + while i < pieces.len() { + let first = pieces[i].0; + let mut last = pieces[i].1; + let mut k = i + 1; + while k < pieces.len() + && pieces[k].0 <= last + AHEAD_GAP + && last.max(pieces[k].1) - first <= AHEAD_MAX + { + last = last.max(pieces[k].1); + k += 1; } - }); - *WINE + ask_run(j, &pieces[i..k]); + i = k; + } } -/// A submission begins: memory asked about from now on is asked of the -/// kernel again. Within one submission, a range the kernel already -/// answered for is answered from the journal: Wine emulates write watching -/// page by page under one lock (about 1 ms an asking), and the world's -/// copies ask about the same big buffers dozens of times per submission -/// (17 GB checked per frame, 3 s of a frame). A write between two askings -/// in one submission keeps its dirty bit, so the next submission sees it. -pub(crate) fn new_submission() { - if on_wine() { - JOURNAL.lock().unwrap_or_else(|e| e.into_inner()).asked_now.clear(); +/// Since the last frame line: the kernel askings that took a millisecond +/// or more, their microseconds, and the longest asking's. An asking walks +/// page tables, some ten microseconds for most ranges; in run 75 the 2,644 +/// askings of a frame took 219 ms in the lines where the pass over the +/// heap's views ran long, 25-50 ms in the others. These numbers say +/// whether a few askings wait for something or all of them are slow. +#[cfg(feature = "diagnostics")] +static SLOW: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +#[cfg(feature = "diagnostics")] +fn slow(us: u64) { + use std::sync::atomic::Ordering::Relaxed; + if us >= 1000 { + SLOW[0].fetch_add(1, Relaxed); + SLOW[1].fetch_add(us, Relaxed); } + SLOW[2].fetch_max(us, Relaxed); } -/// The pages of `[start, end)` (whole pages) as last written, for pages -/// written since tracking began: `(page number, asking)` in page order, and -/// this asking's number, which is higher than any in the list but those the -/// kernel just reported. `None` if the memory is not write-watched (nor, -/// with `guarded`, view memory, which is then guarded). -pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> { - use windows_sys::Win32::System::Memory::GetWriteWatch; - const WRITE_WATCH_FLAG_RESET: u32 = 1; - let (first, last) = (start / PAGE, end.div_ceil(PAGE)); +/// Since the last frame line: ranges of view memory the guards hold that a +/// submission's askings ahead ([`ask_ahead`], [`ask_once`]) left out. Each +/// was a kernel asking that failed, or several, before. +#[cfg(feature = "diagnostics")] +pub(crate) static AHEAD_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// [`SLOW`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn slow_asks() -> [u64; 3] { + [0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// The submission's refreshes are done: `writes` asks the kernel again. +pub(crate) fn ask_ahead_done() { let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if !j.kept { + j.ahead.clear(); + } +} + +/// Whether a submission asks the kernel once, before its first refresh, +/// about every range its lists refresh (`VICTORY_ASK_ONCE=1`; off by +/// default). +/// +/// A submission's refreshes are done in groups, between the title's own +/// buffer copies (each copy flushes the refreshes recorded before it), and +/// every group asked the kernel again: 2,644 askings a frame, 70 a +/// submission. With the switch the journal answers all of them from one +/// asking made when the submission starts. +/// +/// What changes: memory the title's other threads write while the +/// submission is being prepared is seen by the next submission's asking, +/// not by this one's later groups. What this submission's lists read was +/// written before they were submitted, so before the asking. Our own +/// writes into title memory while preparing are told to the journal +/// ([`wrote`]) or end the asking ([`ask_once_end`]). +pub(crate) fn once() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + // On by default since run 81 (with card buffers: 375-450 ms a frame + // against 573-647, the picture unchanged over four minutes); + // `VICTORY_ASK_ONCE=0` asks per range, as before. + *ON.get_or_init(|| std::env::var_os("VICTORY_ASK_ONCE").is_none_or(|v| v != "0")) +} + +/// With [`once`]: asks about `ranges` (everything a submission's lists +/// refresh) as [`ask_ahead`] does, and lets that asking stand until +/// [`ask_once_end`]. +pub(crate) fn ask_once(ranges: &[(usize, usize)]) { + if !once() { + return; + } + // The light refresh: a few of the holes known by their bits are asked + // of Windows again, a submission at a time ([`look_at_holes`]). + if light_kept() { + look_at_holes(HOLES_A_LOOK); + } + ask_once_end(); + ask_ahead(ranges); + let mut j = quiet(JOURNAL.lock().unwrap_or_else(|e| e.into_inner())); let j = &mut *j; - if on_wine() && j.asked_now.iter().any(|&(f, l)| f <= first && last <= l) { + if j.ahead.is_empty() { + // `ask_ahead` asked nothing (fewer than two ranges). j.asked += 1; - return Some(( - j.asked, - j.written.range(first..last).map(|(&p, &w)| (p, w)).collect(), - )); + j.ahead_asked = j.asked; + } + // `ask_ahead` leaves a range that lies alone to `writes`, which asks + // once per flush: with one asking for the submission that was every + // such range asked again at each of its 70 flushes (run 76: 2,300 + // askings a frame with the switch on, as without it). They are asked + // here, once; what is not write-watched stays with `writes`. + for &(start, end) in ranges { + if start >= end { + continue; + } + // View memory the guards hold is not asked about: the asking can + // only fail there, one failed kernel call for each such copy at + // every submission, and `writes` answers it from the guards + // (after triippywhale cc368c7c). + if known_view(start) { + #[cfg(feature = "diagnostics")] + AHEAD_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + continue; + } + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + if !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) && ask_kernel(j, first, last) { + j.ahead.push((first, last)); + } + } + j.kept = !j.ahead.is_empty(); +} + +/// The submission's one asking stands no longer: its refreshes are done, +/// or title memory was written in a way the journal was not told. +pub(crate) fn ask_once_end() { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if j.kept { + j.kept = false; + j.ahead.clear(); + } +} + +/// We wrote title memory `[at, at + len)` while a submission's one asking +/// stands (the title's buffer copies, done at submission): its pages count +/// as written after that asking, so the refreshes that follow copy them. +pub(crate) fn wrote(at: usize, len: usize) { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if !j.kept || len == 0 { + return; + } + j.asked += 1; + let now = j.asked; + // The asking that stands moves with it: `asked` and `writes` give it as + // "now", and a page noted written after "now" stays stale for every + // copy that takes it (copied at `now`, written at `now + 1`): copied + // again at every refresh, and a reason to settle flights + // (fxceless/victory-fork#410). + j.ahead_asked = now; + for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { + j.written.insert(page, now); + j.sub.remove(&page); + } +} + +/// We wrote the 64 KiB page numbered `page` of title memory through a +/// view of our own (`crate::inplace::write_own`): no guard was opened and +/// no kernel write-watch bit set, so the journal is told here. The page, +/// and the same physical page at its other title addresses (`others`, +/// page numbers), count as written at a new asking, which every host copy +/// that holds them takes at its next refresh. Returns the asking that had +/// last found `page` written (0: never) and the new one, for the copy +/// that wrote to note itself current. +pub(crate) fn wrote_own(page: usize, others: &[usize]) -> (u64, u64) { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + j.asked += 1; + let now = j.asked; + // As in [`wrote`]: an asking that stands for a submission, or for a + // flush, moves with it, or a copy taking the page at the standing + // asking would find it written "later" at every refresh. + if j.kept || !j.ahead.is_empty() { + j.ahead_asked = now; + } + let before = j.written.insert(page, now).unwrap_or(0); + j.sub.remove(&page); + for &other in others { + if other != page { + j.written.insert(other, now); + j.sub.remove(&other); + } + } + (before, now) +} + +/// The asking that last found the 64 KiB page numbered `page` written (0: +/// never). Read only, for `crate::backreads`. +#[cfg(feature = "diagnostics")] +pub(crate) fn stamp(page: usize) -> u64 { + JOURNAL.lock().unwrap_or_else(|e| e.into_inner()).written.get(&page).copied().unwrap_or(0) +} + +/// One kernel asking for `pieces` (page ranges in order); by halves if it +/// fails, as a run across two reservations or into memory that is not +/// write-watched does. A piece alone is left to [`writes`]. +fn ask_run(j: &mut Journal, pieces: &[(usize, usize)]) { + if pieces.len() < 2 { + return; + } + let first = pieces[0].0; + let last = pieces.iter().map(|p| p.1).max().unwrap_or(first); + if ask_kernel(j, first, last) { + j.ahead.push((first, last)); + return; } + let (a, b) = pieces.split_at(pieces.len() / 2); + ask_run(j, a); + ask_run(j, b); +} + +/// Asks the kernel for the written pages of pages `[first, last)` and notes +/// them in the journal under the ahead asking; false (and nothing changed) +/// if the range is not write-watched memory of one reservation. +fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool { + use windows_sys::Win32::System::Memory::GetWriteWatch; + const WRITE_WATCH_FLAG_RESET: u32 = 1; let mut count = (last - first) * PAGE / KERNEL_PAGE; j.found.resize(count.max(j.found.len()), 0); let mut granularity = 0; @@ -107,31 +380,294 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve &mut granularity, ) } != 0; - let guarded = if failed { - count = 0; - match by_allocation(first * PAGE, last * PAGE, &mut j.found) { - Some(pages) => pages, - None if !guarded => return None, - None => guard(first * PAGE, last * PAGE)?, + if failed { + return false; + } + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Watches, 1); + add(C::WatchUs, started.elapsed().as_micros() as u64); + slow(started.elapsed().as_micros() as u64); + } + let now = j.ahead_asked; + for k in 0..count { + let at = j.found[k]; + note_kernel(j, at, now); + } + true +} + +/// Notes in the journal that the kernel's asking `now` found the 4 KiB page at `at` written: its 64 KiB page as +/// written at `now`, and with [`dirty4k_kept`] which of its 4 KiB pages the asking found ([`Journal::sub`]). +fn note_kernel(j: &mut Journal, at: usize, now: u64) { + let page = at / PAGE; + let before = j.written.insert(page, now).unwrap_or(0); + if !dirty4k_kept() { + return; + } + let bit = 1u16 << ((at % PAGE) / KERNEL_PAGE); + if before == now { + // Found again in the same asking: one more 4 KiB page of it. A page this asking already noted whole (our + // own writes under a standing asking) stays whole: it has no entry. + if let Some(entry) = j.sub.get_mut(&page) + && entry.0 == now + { + entry.2 |= bit; } } else { - if on_wine() && j.asked_now.len() < 4096 { - j.asked_now.push((first, last)); + j.sub.insert(page, (now, before, bit)); + } +} + +/// Whether refreshes of write-watched memory copy only the 4 KiB pages written (`VICTORY_DIRTY_4K=1`; off by +/// default; `alt`: twenty seconds with, twenty without, in turn, each change said in the log). +/// +/// The journal and the copies keep 64 KiB pages ([`PAGE`]): a page the kernel found written was copied whole, though +/// the kernel names the 4 KiB pages written. With the switch the journal also keeps, for a page the kernel's write +/// watch answered, which 4 KiB pages its last asking found and the asking before that which found the page written +/// ([`subpages`]). A copy that took the page at or after that earlier asking holds every other 4 KiB page as it is now: +/// a write to one of them after that asking would have been found by an asking between (the kernel's bits are reset +/// only by an asking, and every asking's finds go in the journal), and that asking would be the earlier one. So it +/// copies only the pieces found. Pages noted written another way (the guards of view memory, our own writes, the +/// title's copies at submission) have no entry and are copied whole, as before; so does a copy that took the page +/// before the earlier asking, or never. +pub(crate) fn dirty4k() -> bool { + match dirty4k_mode() { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "refreshes of write-watched memory copy only the 4 KiB pages written from now (VICTORY_DIRTY_4K=alt): {}", + if on { "ON" } else { "off, whole 64 KiB pages as usual" } + ); + } + on } - Vec::new() + } +} + +/// `VICTORY_DIRTY_4K`: 0 off, 1 on, 2 in turn. +fn dirty4k_mode() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_DIRTY_4K").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) +} + +/// Whether the journal keeps the 4 KiB pages found ([`Journal::sub`]): with the switch on, and in both phases of +/// `alt` (the phase without counts what it would have saved). +pub(crate) fn dirty4k_kept() -> bool { + dirty4k_mode() != 0 +} + +/// With [`dirty4k_kept`]: the entries of [`Journal::sub`] for the pages of `[start, end)`, in page order, as `(page, +/// asking, the asking before, 4 KiB pages found)`. Empty without the switch. Read once the refresh's asking is done; +/// an entry whose asking is not the one the refresh was given for its page (a later asking came between) is not used. +pub(crate) fn subpages(start: usize, end: usize) -> Vec<(usize, u64, u64, u16)> { + if !dirty4k_kept() || start >= end { + return Vec::new(); + } + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + j.sub.range(first..last).map(|(&p, &(asked, before, bits))| (p, asked, before, bits)).collect() +} + +/// Since the start, with `VICTORY_DIRTY_4K`: stale pages a refresh could narrow to their 4 KiB pages, the 4 KiB pages +/// of them, those narrowed in fact (the switch on), and stale pages copied whole (no entry, or taken too long ago). +pub(crate) static DIRTY4K: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Counts a stale page of a refresh ([`DIRTY4K`]): `found`, its 4 KiB pages if it could be narrowed; `narrowed`, +/// whether it was. Says the counts at each power of two of the pages that could be. +pub(crate) fn dirty4k_count(found: Option<u16>, narrowed: bool) { + use std::sync::atomic::Ordering::Relaxed; + let Some(bits) = found else { + DIRTY4K[3].fetch_add(1, Relaxed); + return; + }; + DIRTY4K[1].fetch_add(u64::from(bits.count_ones()), Relaxed); + DIRTY4K[2].fetch_add(u64::from(narrowed), Relaxed); + let n = DIRTY4K[0].fetch_add(1, Relaxed) + 1; + if n.is_power_of_two() { + let pieces = DIRTY4K[1].load(Relaxed); + tracing::info!( + "stale 64 KiB pages of write-watched memory (VICTORY_DIRTY_4K), since the start: {n} could be copied as their {pieces} written 4 KiB pages ({:.1} MB instead of {:.1} MB), {} were; {} copied whole (written another way, or taken too long ago)", + pieces as f64 * 4096.0 / 1e6, + n as f64 * 65536.0 / 1e6, + DIRTY4K[2].load(Relaxed), + DIRTY4K[3].load(Relaxed) + ); + } +} + +/// What [`writes`] would say of `[start, end)` from the journal alone, if +/// the range lies in one asked ahead ([`ask_ahead`], [`ask_once`]): the +/// pages written since tracking began and the asking that last found each +/// written, with the number of the asking that stands (as [`writes`] gives +/// it). `None` if the kernel would have to be asked. +pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> { + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + j.ahead + .iter() + .any(|&(a, b)| a <= first && last <= b) + .then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect())) +} + +/// The pages of `[start, end)` (whole pages) as last written, for pages +/// written since tracking began: `(page number, asking)` in page order, and +/// this asking's number, which is higher than any in the list but those the +/// kernel just reported. `None` if the memory is not write-watched (nor, +/// with `guarded`, view memory, which is then guarded). +pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> { + // The light refresh: its bits kept, and asked or not, as the switch + // says now. + let light = if light_kept() { 1 + u8::from(light()) } else { 0 }; + // Always on: the counts every 65,536 askings that allow for view + // memory (in turn they are said at each change). + if guarded && light_mode() == 1 { + static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if (CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1).is_multiple_of(65_536) { + let [bits, locked, filled] = light_asks(); + tracing::info!( + "refreshes of host copies go the light way (VICTORY_LIGHT_REFRESH=1): of the last 65536 askings that allowed for view memory {bits} were answered by the bits of their blocks and {locked} took the guards' lock (the others were of memory the kernel watches); {filled} holes found filled with nobody telling" + ); + } + } + writes_as(start, end, guarded, light) +} + +/// [`writes`] with the light refresh as `light` says ([`light`]): 0, as +/// without the switch, no bit is set or asked; 1, the blocks the asking +/// leaves clean get their bits and none is asked (the phase of `alt` +/// without); 2, a range whose blocks all have their bit is answered from +/// the journal. +fn writes_as(start: usize, end: usize, guarded: bool, light: u8) -> Option<(u64, Vec<(usize, u64)>)> { + use windows_sys::Win32::System::Memory::GetWriteWatch; + const WRITE_WATCH_FLAG_RESET: u32 = 1; + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let ticket = { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + // Asked ahead with the submission's other ranges: the journal has it. + if j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + return Some(( + j.ahead_asked, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )); + } + // (The light refresh and 4 KiB notes, both off by default, keep the + // journal held across the asking, as before.) + if !unlocked_asks() || light != 0 || dirty4k_kept() { + return writes_locked(j, start, end, guarded, light); + } + j.ticket += 1; + let ticket = j.ticket; + j.asking.push((first, last, ticket)); + ticket + }; + // Try 6.6, the job system's first rule (no thread waits on a lock while + // another is in the kernel): the kernel is asked with the journal let + // go. Texture refreshes on every thread spent 72-88 ms a frame "asking + // the write watch and the guards" in the 6.5 report, queued behind one + // lock held across each call. `VICTORY_WATCH_UNLOCKED=0`: as before. + let mut found = FOUND.with(|f| std::mem::take(&mut *f.borrow_mut())); + let mut count = (last - first) * PAGE / KERNEL_PAGE; + found.resize(count.max(found.len()), 0); + let mut granularity = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + // View memory the guards already hold cannot be write-watched: the + // kernel asking would only fail. Copies of it are flushed many times a + // frame, each time paying that failed call before the guards answer. + let known_view = guarded && known_view(first * PAGE); + // SAFETY: the answer buffer holds `count` entries. + let failed = known_view + || unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (first * PAGE) as *const _, + (last - first) * PAGE, + found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; + #[cfg(feature = "diagnostics")] + crate::copystat::add( + if known_view { + crate::copystat::C::WatchKnownView + } else { + crate::copystat::C::WatchFailed + }, + failed as u64, + ); + #[cfg(feature = "diagnostics")] + if failed && !known_view && guarded { + failed_asking(first * PAGE, last * PAGE); + } + let guarded_pages = if failed { + count = 0; + if guarded { + #[cfg(feature = "diagnostics")] + let guarding = std::time::Instant::now(); + let written = guard(first * PAGE, last * PAGE); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64); + written + } else { + None + } + } else { + Some(Vec::new()) }; #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; add(C::Watches, 1); add(C::WatchUs, started.elapsed().as_micros() as u64); + slow(started.elapsed().as_micros() as u64); + // What one failed asking costs, against one the guards answer + // without the kernel (fps41 round 7: the cost of `VICTORY_VIEW_KNOWN`'s + // case was known only from runs 222/225). + if failed { + add( + if known_view { C::WatchKnownUs } else { C::WatchFailedUs }, + started.elapsed().as_micros() as u64, + ); + } } + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + j.asking.retain(|&(.., t)| t != ticket); + ASKED.notify_all(); + let Some(guarded_pages) = guarded_pages else { + FOUND.with(|f| *f.borrow_mut() = found); + return None; + }; j.asked += 1; let now = j.asked; - let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded); - for page in pages.collect::<Vec<_>>() { + for page in found[..count].iter().map(|&at| at / PAGE).chain(guarded_pages) { j.written.insert(page, now); } + FOUND.with(|f| *f.borrow_mut() = found); + // Another thread asking about some of these pages right now holds + // writes the journal does not have yet (its call reset them): wait for + // it to note them, so nothing is missed. Only askings that share pages + // wait for each other; before, every asking waited for every other. + while j.asking.iter().any(|&(a, b, _)| a < last && first < b) { + j = ASKED.wait(j).unwrap_or_else(|e| e.into_inner()); + } + // What the list holds is noted by now, the others' askings with it. + let now = now.max(j.asked); + let j = &mut *j; Some(( now, j.written @@ -141,90 +677,893 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve )) } -/// The pages of `[start, end)` written, asked allocation by allocation: -/// the kernel refuses a range over several (a title buffer spans as many -/// allocations as the runtime made for it). Parts never committed cannot -/// have been written, so a range none of which is committed (a reserved -/// allocation the title has not committed yet) has no writes. `None` if a -/// committed part is not write-watched (or the range is one committed -/// allocation, already refused). -fn by_allocation(start: usize, end: usize, found: &mut Vec<usize>) -> Option<Vec<usize>> { - use windows_sys::Win32::System::Memory::{ - GetWriteWatch, MEM_COMMIT, MEM_FREE, MEMORY_BASIC_INFORMATION, VirtualQuery, - }; +/// Told when a [`writes`] asking in the kernel is back (Try 6.6). +static ASKED: std::sync::Condvar = std::sync::Condvar::new(); + +/// `j` once no [`writes`] asking is in the kernel: an ahead asking resets +/// pages too and notes them all at once, so it waits for those first. +fn quiet(mut j: std::sync::MutexGuard<'static, Journal>) -> std::sync::MutexGuard<'static, Journal> { + while !j.asking.is_empty() { + j = ASKED.wait(j).unwrap_or_else(|e| e.into_inner()); + } + j +} + +/// See [`writes`]: whether the kernel is asked with the journal let go +/// (`VICTORY_WATCH_UNLOCKED=0`: held, as before Try 6.6). +fn unlocked_asks() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WATCH_UNLOCKED").is_none_or(|v| v != "0")) +} + +thread_local! { + /// Room for the kernel's answer, per thread ([`writes`]). + static FOUND: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// [`writes`] with the journal held across the kernel call (before Try 6.6). +fn writes_locked( + mut j: std::sync::MutexGuard<'_, Journal>, + start: usize, + end: usize, + guarded: bool, + light: u8, +) -> Option<(u64, Vec<(usize, u64)>)> { + use windows_sys::Win32::System::Memory::GetWriteWatch; const WRITE_WATCH_FLAG_RESET: u32 = 1; - let query = |at: usize| { - let mut info = MEMORY_BASIC_INFORMATION::default(); - // SAFETY: a query about an address; nothing is dereferenced. - let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; - (n != 0).then_some(info) + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let j = &mut *j; + // The light refresh: every block of the range is read-only by our hand + // and unwritten since an asking noted it, or a hole noted for good + // ([`PUBLISHED`]). The guards would find nothing written and this + // asking would note nothing: its number and the journal as it is are + // the answer, with the guards' lock not taken and no kernel call. + if guarded && light == 2 && published(j, first * PAGE, last * PAGE) { + LIGHT_ASKS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + j.asked += 1; + return Some(( + j.asked, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )); + } + let mut count = (last - first) * PAGE / KERNEL_PAGE; + j.found.resize(count.max(j.found.len()), 0); + let mut granularity = 0; + let known_view = guarded && known_view(first * PAGE); + // SAFETY: the answer buffer holds `count` entries. + let failed = known_view + || unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (first * PAGE) as *const _, + (last - first) * PAGE, + j.found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; + let guarded = if failed { + count = 0; + if !guarded { + return None; + } + guard(first * PAGE, last * PAGE)? + } else { + Vec::new() }; - let (mut pages, mut at, mut allocations, mut any) = (Vec::new(), start, 0, false); - while at < end { - let info = query(at)?; - let base = info.AllocationBase as usize; - let mut committed = info.State == MEM_COMMIT; - let mut to = (info.BaseAddress as usize + info.RegionSize).min(end); - // The rest of the allocation's regions in the range. - while info.State != MEM_FREE && to < end { - let next = query(to)?; - if next.State == MEM_FREE || next.AllocationBase as usize != base { - break; + j.asked += 1; + let now = j.asked; + let pages: Vec<usize> = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded).collect(); + // The kernel's finds with their 4 KiB pages; the guards' as whole pages. + for k in 0..count { + let at = j.found[k]; + note_kernel(j, at, now); + } + for &page in &pages[count..] { + j.written.insert(page, now); + j.sub.remove(&page); + } + // The light refresh: the guards were asked, and what they found is + // noted. The blocks they made clean are known by their bits from now + // on (the journal's lock is still held: no other asking came between). + if failed && light != 0 { + LIGHT_ASKS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + publish(j, &pages, first * PAGE, last * PAGE, told()); + } + Some(( + now, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )) +} + +/// Diagnostics: one in 2,048 of the askings the kernel's write watch +/// refused for memory the guards did not know (some 200 a frame in the +/// first rooms, each followed by a question to Windows about the memory): +/// what the memory is and what the guards hold of its first block. +#[cfg(feature = "diagnostics")] +fn failed_asking(start: usize, end: usize) { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if !N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(2048) { + return; + } + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) }; + let (protected, clean, absent, viewed, aliased) = { + let g = guards(); + let b = start / BLOCK; + (g.protected.contains(&b), g.clean.contains(&b), g.absent.contains(&b), g.viewed.contains(&b), g.aliased.contains(&b)) + }; + tracing::info!( + "a failed write-watch asking (one in 2048): {start:#x}+{:#x}; Windows says (answered {n}): base {:#x} region {:#x} state {:#x} type {:#x} protect {:#x} allocation protect {:#x}; \ + the guards of its first block: protected {protected} clean {clean} absent {absent} viewed {viewed} aliased {aliased}; is a view: {}", + end - start, + info.BaseAddress as usize, + info.RegionSize, + info.State, + info.Type, + info.Protect, + info.AllocationProtect, + is_view(start, end) + ); +} + +impl Tracked { + /// Takes changed pages of `[from, to)`, cut to the tracked range. A + /// partial page stays changed so a later take can read its other bytes. + pub(crate) fn take(&self, from: usize, to: usize) -> Vec<(usize, usize)> { + let (from, to) = (from.max(self.start), to.min(self.end)); + if from >= to { + return Vec::new(); + } + let Some((_, pages)) = writes(from, to, true) else { + return Vec::new(); + }; + let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); + let mut ranges: Vec<(usize, usize)> = Vec::new(); + for (page, write) in pages { + if seen.get(&page).is_some_and(|&last| last >= write) { + continue; } - committed |= next.State == MEM_COMMIT; - to = (next.BaseAddress as usize + next.RegionSize).min(end); - } - allocations += 1; - any |= committed; - if committed { - let mut count = (to - at) / KERNEL_PAGE; - found.resize(count.max(found.len()), 0); - let mut granularity = 0; - // SAFETY: the answer buffer holds `count` entries. - let failed = unsafe { - GetWriteWatch( - WRITE_WATCH_FLAG_RESET, - at as *const _, - to - at, - found.as_mut_ptr().cast(), - &mut count, - &mut granularity, - ) - } != 0; - if failed { - return None; + let (start, end) = ((page * PAGE).max(from), ((page + 1) * PAGE).min(to)); + if start >= end { + continue; + } + // Keep partial pages dirty: the caller has not taken the rest. + if (page * PAGE).max(self.start) >= from + && ((page + 1) * PAGE).min(self.end) <= to + { + seen.insert(page, write); + } + match ranges.last_mut() { + Some((_, last)) if *last == start => *last = end, + _ => ranges.push((start, end)), } - pages.extend(found[..count].iter().map(|&a| a / PAGE)); } - at = to; + ranges } - (allocations > 1 || !any).then_some(pages) } /// Guarded blocks of view memory. const BLOCK: usize = PAGE; +/// Whether the block holding `start` is view memory the guards already +/// hold (read-only by our hand, or noted absent): asking the kernel's write +/// watch about it can only fail. `VICTORY_VIEW_ASK=1` (or +/// `VICTORY_GUARD_ASK=1`) asks the kernel anyway, as before. +fn known_view(start: usize) -> bool { + static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let ask = *ASK.get_or_init(|| { + ["VICTORY_VIEW_ASK", "VICTORY_GUARD_ASK"] + .iter() + .any(|n| std::env::var_os(n).is_some_and(|v| v == "1")) + }); + if ask { + return false; + } + let first = start / BLOCK; + // The light refresh: a block known by its bit is read-only by our hand + // or a hole the guards noted, which is what they are asked below. + if light() && PUBLISHED.all(first, first + 1) { + return true; + } + let g = guards(); + g.protected.contains(&first) || g.absent.contains(&first) || (view_known() && g.viewed.contains(&first)) +} + struct Guards { /// Blocks we made read-only. protected: BTreeSet<usize>, /// Of those, the ones not written since a copy took them. clean: BTreeSet<usize>, + /// Blocks already copied as zeros. While they remain wholly uncommitted, + /// the copy can skip hundreds of MB of failing kernel reads per world frame. + absent: BTreeSet<usize>, + /// Blocks whose physical page was guarded together with its other views + /// (those views' blocks are in it too): a write to one opens them all. + /// A write range can be huge (`fread`), so only these are looked up. + aliased: BTreeSet<usize>, + /// With [`view_known`]: blocks made read-only at least once since the + /// runtime last mapped or unmapped them. They are view memory whether + /// their guard stands now or a write has opened it. + viewed: BTreeSet<usize>, + /// With [`absent_once`]: for blocks of `absent`, when ([`guard_ms`]) + /// Windows last said they are uncommitted. + verified: BTreeMap<usize, u64>, + /// With the light refresh and notes kept for good ([`told`]): the + /// blocks of `verified` that [`publish`] has looked at. Those of them + /// that lie in a placeholder reservation ([`placeholder`]) are known by + /// their bits ([`PUBLISHED`]) until the runtime tells of them; the + /// others are answered from their notes, which then grow old + /// ([`note_life`]). + holes: BTreeSet<usize>, +} + +/// Whether a block once guarded stays known as view memory while its +/// guard is open (`VICTORY_VIEW_KNOWN=1`; off by default). +/// +/// A range whose first block the title wrote since the last check has +/// that block neither read-only nor noted absent, so nothing says it is a +/// view: the kernel's write watch is asked and fails, and then Windows is +/// asked what the memory is (`is_view`), a walk of the page tables to the +/// end of the pages that share the first one's state. In runs 222 and 225 +/// that was 338-450 failed askings a frame and 6.5-7.8 ms a frame of the +/// submitting thread in `VirtualQuery`. With the switch the block is +/// remembered from the time it was first made read-only until the runtime +/// maps or unmaps it ([`title_memory_remapped`]). +/// +/// `VICTORY_VIEW_KNOWN=alt`: twenty seconds with, twenty without, in turn, +/// each change said in the log, for measuring it in one scene. (Blocks +/// noted in one phase are forgotten at a remapping in either.) +fn view_known() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_VIEW_KNOWN").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "view memory stays known while its guard is open from now (VICTORY_VIEW_KNOWN=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } } static GUARDS: Mutex<Guards> = Mutex::new(Guards { protected: BTreeSet::new(), clean: BTreeSet::new(), + absent: BTreeSet::new(), + aliased: BTreeSet::new(), + viewed: BTreeSet::new(), + verified: BTreeMap::new(), + holes: BTreeSet::new(), }); fn guards() -> std::sync::MutexGuard<'static, Guards> { GUARDS.lock().unwrap_or_else(|e| e.into_inner()) } +/// Whether the block `page` is read-only by our hand and unwritten since a +/// copy took it (diagnostics of `VICTORY_BACK_OWN_CHECK`). +pub(crate) fn clean(page: usize) -> bool { + guards().clean.contains(&page) +} + +/// `VICTORY_LIGHT_REFRESH`: 0 off, 1 on, 2 in turn ([`light`]). +fn light_mode() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_LIGHT_REFRESH").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) +} + +/// Whether the bits of the light refresh are kept ([`PUBLISHED`]): with +/// the switch on, and in both phases of `alt`, so that the phase that asks +/// them finds them true whatever was written in the phase before. +fn light_kept() -> bool { + light_mode() != 0 +} + +/// Whether an asking about view memory is answered from the bits of its +/// blocks where they can answer (`VICTORY_LIGHT_REFRESH=1`; off by +/// default). +/// +/// A frame asks the guards about view memory 2,000 to 3,700 times, 4.5 to +/// 9.4 GB of it, to hear for 98-99 % that nothing was written; every such +/// asking takes the guards' lock, which the title's threads wait for in +/// their write faults, and reads the range's clean blocks off the set: +/// 22.8 ms a frame of the submitting thread in the rooms, 44.5 ms outdoors +/// (run 275). With the switch a range whose blocks all have their bit +/// ([`PUBLISHED`]) is answered from the journal alone ([`writes`], +/// [`nothing_new`]), and its first block is known for view memory without +/// the lock ([`known_view`]). +/// +/// What changes in the answers: nothing. A range is known by its bits +/// exactly while the guards would find it all clean, or clean but for +/// holes noted for good ([`told`]); only who is asked changes. +/// +/// `VICTORY_LIGHT_REFRESH=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log with the counts of the phase before. +/// The bits are kept in both phases ([`light_kept`]) and asked in one. +/// (After avatarmanz/VIctory-7900XTX 2aa8134b and 74045e46, by hand.) +pub(crate) fn light() -> bool { + match light_mode() { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + let [bits, locked, filled] = light_asks(); + tracing::info!( + "refreshes of host copies go the light way from now (VICTORY_LIGHT_REFRESH=alt): {}; since the change before: {bits} askings of view memory answered by the bits of their blocks, {locked} that took the guards' lock, {filled} holes found filled with nobody telling", + if on { "ON" } else { "off, as usual (the bits are kept)" } + ); + } + on + } + } +} + +/// Since they were last taken ([`light_asks`]), with the light refresh +/// kept: askings of view memory answered by the bits of their blocks, +/// askings that went to the guards, and holes known by their bits that +/// Windows said were filled with nobody telling ([`look_at_holes`]). +static LIGHT_ASKS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// [`LIGHT_ASKS`], taken. +fn light_asks() -> [u64; 3] { + [0, 1, 2].map(|i| LIGHT_ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// The words of a piece of [`Bits`]: the bits of 4 GiB. +const BITS_WORDS: usize = 1 << 10; +/// The pieces of [`Bits`]: 128 TiB, what a process has. +const BITS_PIECES: usize = 1 << 15; + +/// A bit per 64 KiB block of the address space, read and cleared with no +/// lock; in pieces made when first needed and never let go. +struct Bits([std::sync::atomic::AtomicPtr<BitsPiece>; BITS_PIECES]); + +/// The bits of 4 GiB. +type BitsPiece = [std::sync::atomic::AtomicU64; BITS_WORDS]; + +impl Bits { + const fn new() -> Bits { + Bits([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; BITS_PIECES]) + } + + /// The piece that holds word `word`, if it was ever made. + fn piece(&self, word: usize) -> Option<&BitsPiece> { + let piece = self.0.get(word / BITS_WORDS)?.load(std::sync::atomic::Ordering::Acquire); + // SAFETY: null, or a piece made by `set`, which is never freed. + unsafe { piece.as_ref() } + } + + /// Sets `block`'s bit (nothing past the address space). + fn set(&self, block: usize) { + use std::sync::atomic::Ordering::{AcqRel, Acquire, SeqCst}; + let word = block / 64; + let Some(place) = self.0.get(word / BITS_WORDS) else { + return; + }; + if place.load(Acquire).is_null() { + let made: *mut BitsPiece = Box::into_raw(Box::new([const { std::sync::atomic::AtomicU64::new(0) }; BITS_WORDS])); + if place.compare_exchange(std::ptr::null_mut(), made, AcqRel, Acquire).is_err() { + // SAFETY: made above and shown to nobody: another thread's + // piece is in the place. + drop(unsafe { Box::from_raw(made) }); + } + } + if let Some(piece) = self.piece(word) { + piece[word % BITS_WORDS].fetch_or(1u64 << (block % 64), SeqCst); + } + } + + /// Clears `block`'s bit: ahead of what makes the block writable, and + /// seen by whoever looks after it. + fn clear(&self, block: usize) { + let word = block / 64; + if let Some(piece) = self.piece(word) { + piece[word % BITS_WORDS].fetch_and(!(1u64 << (block % 64)), std::sync::atomic::Ordering::SeqCst); + } + } + + /// Whether the bits of all of `[first, last)` are set (not so of none). + fn all(&self, first: usize, last: usize) -> bool { + let mut block = first; + while block < last { + let word = block / 64; + let until = ((word + 1) * 64).min(last); + let mask = (u64::MAX >> (64 - (until - block))) << (block % 64); + let Some(piece) = self.piece(word) else { + return false; + }; + if piece[word % BITS_WORDS].load(std::sync::atomic::Ordering::SeqCst) & mask != mask { + return false; + } + block = until; + } + first < last + } +} + +/// The blocks an asking can answer for from the journal alone. A block has +/// its bit only while both of these hold: it is read-only by our hand and +/// noted clean (`Guards::clean`), or it is a hole noted for good that lies +/// in a placeholder reservation (`Guards::holes`); and the journal holds +/// every write to it that an asking found. +/// +/// Why that is so. A bit is set in one place, [`publish`]: by the asking +/// that found the block written and had it made clean, after it noted that +/// in the journal and with the journal's lock still held, under the +/// guards' lock, and only if the block is clean at that moment. It is +/// cleared under the guards' lock before the block's write access is given +/// back (`open_here`, which the write fault's handler, [`writing`], +/// [`title_memory_written`] and [`views_mapped`] all go through), and when +/// the runtime tells that what the block shows is new +/// ([`title_memory_remapped`], [`title_memory_committed`]). Clearing does +/// nothing where no bit was ever set, so it is not behind the switch. +/// +/// Who asks the bits holds the journal's lock from before the look until +/// it has read the journal ([`published`]), and nobody sets a bit without +/// that lock: a block opened and guarded again between the look and the +/// reading cannot have its bit back in time to be taken for unwritten. A +/// write that comes while the bits are looked at is no different from one +/// that comes just after an asking: its block's bit is gone, and the next +/// asking goes to the guards and finds the block open. +/// +/// Our own stores through a view of our own (`crate::inplace::write_own`) +/// open no guard and take no bit: they are noted in the journal +/// ([`wrote_own`]), which is where an asking answered by the bits looks. +static PUBLISHED: Bits = Bits::new(); + +/// An asking of view memory `[start, end)` found the pages `written` (page +/// numbers) written, had the guards make their blocks read-only and clean +/// ([`guard`]) and has noted them in the journal, whose lock it holds +/// still (`_noted`): the blocks of them that are clean now are known by +/// their bits from here on ([`PUBLISHED`]). With `holes` ([`told`]), so +/// are the blocks of the range noted uncommitted for good that lie in a +/// placeholder reservation; Windows is asked that once for each +/// ([`placeholder`]). +/// +/// The blocks an asking leaves clean that have no bit yet are the ones it +/// reports written: every other clean block was left clean by an asking +/// before it, which did this. +fn publish(_noted: &Journal, written: &[usize], start: usize, end: usize, holes: bool) { + let mut g = guards(); + let g = &mut *g; + for &page in written { + let block = page * PAGE / BLOCK; + // (Not one that a write has opened since the guards were asked, + // nor one that could not be made read-only.) + if g.clean.contains(&block) { + PUBLISHED.set(block); + } + } + if !holes { + return; + } + let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + // The notes of the range not looked at yet. Both sets are read in + // block order, and every block of `holes` has a note. + let fresh: Vec<usize> = { + let mut looked = g.holes.range(first..last).copied().peekable(); + g.verified + .range(first..last) + .map(|(&block, _)| block) + .filter(|&block| { + while looked.next_if(|&hole| hole < block).is_some() {} + looked.next_if_eq(&block).is_none() + }) + .collect() + }; + for block in fresh { + g.holes.insert(block); + // (Asked now, not when the note was made: a view the runtime is + // mapping there, and has not told of yet, is no placeholder.) + if g.absent.contains(&block) && placeholder(block) { + PUBLISHED.set(block); + } + } +} + +/// Whether every block of `[start, end)` has its bit ([`PUBLISHED`]): what +/// [`writes`] would answer of the range is in the journal. `_held`: the +/// journal's lock, which the caller holds from before this look until it +/// has read the journal (no bit is set meanwhile: [`publish`]). +fn published(_held: &Journal, start: usize, end: usize) -> bool { + PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK)) +} + +/// Whether a block noted uncommitted stays noted until the runtime tells +/// of it (`VICTORY_ABSENT_ONCE=1` with `VICTORY_ABSENT_MS=told`): then, and +/// only then, can such a block be known by its bit ([`publish`]). With +/// notes that grow old, or none, every asking of a range that holds a hole +/// goes to the guards, which put the question to Windows as they do. +fn told() -> bool { + absent_mode() == 1 && absent_keep_ms() == u64::MAX +} + +#[link(name = "ntdll", kind = "raw-dylib")] +unsafe extern "system" { + /// The kernel's question about a process's memory, `(process, address, + /// class of the answer, answer out, its room, bytes answered out)`: an + /// NTSTATUS, negative when it cannot answer. It changes nothing. + fn NtQueryVirtualMemory( + process: *mut std::ffi::c_void, + at: *const std::ffi::c_void, + class: u32, + out: *mut std::ffi::c_void, + len: usize, + returned: *mut usize, + ) -> i32; +} + +/// Whether `block` lies in a placeholder reservation: memory in which pages +/// come to be only by mapping a view, or making an allocation, in its +/// place, which the runtime does and tells of ([`title_memory_remapped`], +/// [`title_memory_committed`]). An ordinary reservation can be committed +/// by anybody, and free memory taken by anybody, with no word to us: +/// `VirtualQuery` does not tell the three apart, this question does. +fn placeholder(block: usize) -> bool { + /// `MEMORY_REGION_INFORMATION` (ntddk); only the kinds are read. + #[repr(C)] + #[derive(Default)] + #[allow(dead_code)] + struct Region { + allocation_base: usize, + allocation_protect: u32, + region_type: u32, + region_size: usize, + commit_size: usize, + partition_id: usize, + node_preference: usize, + } + // (`MemoryRegionInformationEx`; class 3 answers with the kind of memory + // in that word, not the flags.) + const MEMORY_REGION_INFORMATION_EX: u32 = 7; + const PLACEHOLDER_RESERVATION: u32 = 1 << 8; + let mut region = Region::default(); + // SAFETY: the answer's room and its size; the kernel checks the address. + let status = unsafe { + NtQueryVirtualMemory( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + (block * BLOCK) as *const _, + MEMORY_REGION_INFORMATION_EX, + (&raw mut region).cast(), + size_of::<Region>(), + std::ptr::null_mut(), + ) + }; + status >= 0 && region.region_type & PLACEHOLDER_RESERVATION != 0 +} + +/// The note that `block` is uncommitted is gone, or is true no longer: the +/// block is not known by its bit any more ([`publish`]). +fn forget_hole(g: &mut Guards, block: usize) { + if g.holes.remove(&block) { + PUBLISHED.clear(block); + } +} + +/// How long a note kept for good lives for a hole that lies in no +/// placeholder reservation ([`note_life`]), in milliseconds. +const UNSURE_MS: u64 = 100; + +/// How long the note that `block` is uncommitted lives, of `keep` +/// ([`absent_once`]). With the light refresh a note kept for good is kept +/// so only where pages cannot come to be without the runtime's word: in a +/// placeholder reservation, whose holes are known by their bits. A hole +/// that [`publish`] looked at and found in an ordinary reservation or in +/// free memory, which anybody can commit or take with no word to us, is +/// asked of Windows again when its note is [`UNSURE_MS`] old. (Without the +/// light refresh no hole is looked at, and `keep` stands.) +fn note_life(g: &Guards, block: usize, keep: u64) -> u64 { + if keep == u64::MAX && g.holes.contains(&block) && !PUBLISHED.all(block, block + 1) { + UNSURE_MS + } else { + keep + } +} + +/// Holes asked of Windows again at each submission ([`look_at_holes`]): a +/// question is a microsecond or so, and the submitting thread is the +/// frame's limit. +const HOLES_A_LOOK: usize = 16; + +/// With the light refresh: `most` of the holes known by their bits are +/// asked of Windows again, the next ones each time and round again, in +/// case one was filled with nobody telling ([`title_memory_remapped`], +/// [`title_memory_committed`]), which this title is not known to do. One +/// that was loses its bit and its note, so that the next asking of it goes +/// to the guards, which find it; counted, and said once. One whose +/// reservation is a placeholder no longer (let go, or made anew) loses its +/// bit and keeps its note. +/// +/// Not while the runtime changes a mapping: a view it has mapped and not +/// told of yet is no hole filled behind our back, and forgotten here it +/// could be made read-only before the runtime's word, which forgets the +/// guard and leaves the protection. +fn look_at_holes(most: usize) { + static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let Some(_still) = title_memory_reading_now() else { + return; + }; + let part: Vec<usize> = { + let g = guards(); + if g.holes.is_empty() { + return; + } + let from = FROM.load(std::sync::atomic::Ordering::Relaxed); + let part: Vec<usize> = g.holes.range(from..).take(most).copied().collect(); + FROM.store(part.last().map_or(0, |last| last + 1), std::sync::atomic::Ordering::Relaxed); + part + }; + for block in part { + // (Not the ones looked at that lie in no placeholder: they have no + // bit, and their notes are the guards' to keep.) + if !PUBLISHED.all(block, block + 1) { + continue; + } + let filled = block >= uncommitted_end(block); + if !filled && placeholder(block) { + continue; + } + let mut g = guards(); + // (Told of since the part was taken: forgotten already.) + if !g.holes.contains(&block) { + continue; + } + PUBLISHED.clear(block); + if filled { + g.holes.remove(&block); + g.verified.remove(&block); + LIGHT_ASKS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| { + tracing::warn!( + address = format_args!("{:#x}", block * BLOCK), + "a hole of view memory was filled with nobody telling: host copies of it held old bytes until now (VICTORY_LIGHT_REFRESH; said once, counted with the light refresh's askings)" + ); + }); + } + } +} + +/// Whether nothing of `[start, end)` was written that a copy does not +/// hold, known with nothing asked of the guards or the kernel: `copied` is +/// the copy's note, for each page from page `base` on, of the asking after +/// which it last took the page (0: never), as `crate::shadow` keeps it. +/// True only if [`writes`] would answer from the journal (the range was +/// asked ahead, or its blocks are known by their bits) and the answer would +/// have the copy take no page. `false` if something would have to be +/// asked, and always without the light refresh ([`light`]). +pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64]) -> bool { + light() && nothing_noted(start, end, base, copied) +} + +/// [`nothing_new`], whatever the switch says. +fn nothing_noted(start: usize, end: usize, base: usize, copied: &[u64]) -> bool { + if start >= end { + return false; + } + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { + return false; + }; + // A page never taken is taken at the next refresh (so is, at every + // refresh, a page the copy's refreshes only ever hold in part). + if taken.contains(&0) { + return false; + } + let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + // The bits first, then the journal, both under its lock ([`published`]). + let by_bits = !j.ahead.iter().any(|&(a, b)| a <= first && last <= b); + if by_bits && !published(&j, first * PAGE, last * PAGE) { + return false; + } + let same = j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first]); + if same && by_bits { + LIGHT_ASKS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + same +} + +/// Whether a refresh of `[start, end)` by a copy whose note of taken pages +/// is `copied` (from page `base` on, as for [`nothing_new`]) would copy +/// nothing, known before asking and whatever the light refresh says: +/// every page of the range was taken, the journal notes no write of a page +/// after the copy took it, and either the range lies in a standing asking +/// ahead (the journal is then the whole answer, as [`writes`] gives it) or +/// every 64 KiB block of it is read-only by our hand and clean (no write +/// opened its guard since a copy took it: the guard fault handler, our own +/// writes through the kernel ([`writing`]), DirectStorage's writes through +/// the runtime's views ([`title_memory_written`]) and a remapping +/// ([`title_memory_remapped`]) all open or forget the block first). +/// +/// What it cannot see is what the guards cannot see either: a write +/// through another view of the same physical page where the two were not +/// guarded together, and a write into private memory that no asking has +/// reported yet (such a range is answered here only inside a standing +/// asking, where [`writes`] would answer from the journal too). So where +/// this says yes, [`writes`] would say the same (fps41 round 8). +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] +pub(crate) fn unchanged_known(start: usize, end: usize, base: usize, copied: &[u64]) -> bool { + if start >= end { + return false; + } + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { + return false; + }; + if taken.contains(&0) { + return false; + } + let ahead = { + let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if !j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first]) { + return false; + } + j.ahead.iter().any(|&(a, b)| a <= first && last <= b) + }; + if ahead { + return true; + } + // (The journal's lock is let go first: `writes_as` takes it, then the + // guards'.) + let g = guards(); + let blocks = last - first; + g.protected.range(first..last).count() == blocks && g.clean.range(first..last).count() == blocks +} + +/// `VICTORY_ABSENT_ONCE`: 0 off, 1 on, 2 in turn ([`absent_once`]). +fn absent_mode() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_ABSENT_ONCE").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) +} + +/// Whether a block of view memory that Windows said is uncommitted is not +/// asked about again for [`absent_keep_ms`] (`VICTORY_ABSENT_ONCE=1`; off +/// by default). +/// +/// A block noted absent is never "clean", so a range that holds one is +/// walked block by block at every asking, and every such block is a +/// question to Windows (`uncommitted_end`): the title's unmapped pages are +/// placeholders of 64 KiB each, so one question answers for one block. The +/// profile of run 249 has 5.7 ms a frame of the submitting thread in +/// `VirtualQuery` under [`guard`], with the guards' lock held, which the +/// title's threads wait for in their write faults. +/// +/// What the runtime maps there it tells ([`title_memory_remapped`]), and +/// that forgets the block and its note at once, with or without the +/// switch. What changes: memory that appears at such an address without +/// the runtime's word (a commit that is not a page mapping) is seen up to +/// [`absent_keep_ms`] later than before; until then its copy holds zeros, +/// as it did while nothing was there. +/// +/// `VICTORY_ABSENT_ONCE=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log with the counts of the phase before. +fn absent_once() -> bool { + match absent_mode() { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + let [asked, kept] = absent_looks(); + tracing::info!( + "blocks of view memory found uncommitted are asked of Windows again only after {} ms from now (VICTORY_ABSENT_ONCE=alt): {}; since the change before: {asked} questions to Windows about such blocks, {kept} blocks answered from their note", + absent_keep_ms(), + if on { "ON" } else { "off, at every asking as usual" } + ); + } + on + } + } +} + +/// How long a block found uncommitted is not asked about again +/// ([`absent_once`]): `VICTORY_ABSENT_MS`, 100 by default (about a frame), +/// 1 to 1000. +fn absent_keep_ms() -> u64 { + static MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *MS.get_or_init(|| match std::env::var("VICTORY_ABSENT_MS").as_deref().map(str::trim) { + // Until the runtime tells of the block ([`title_memory_remapped`], + // [`title_memory_committed`]): no question to Windows at all for a + // block noted uncommitted. Run 279 with 100 ms: 600,000 to 690,000 + // questions in twenty seconds without the notes, and still 357,000 + // to 604,000 with them, because a frame is as long as a note lives. + Ok("told") => u64::MAX, + Ok(v) => v.parse::<u64>().map_or(100, |n| n.clamp(1, 1000)), + Err(_) => 100, + }) +} + +/// Since they were last taken ([`absent_looks`]): questions to Windows +/// about blocks noted absent, and such blocks answered from their note +/// ([`absent_once`]). Counted with the switch off too. +static ABSENT_LOOKS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// [`ABSENT_LOOKS`], taken. +fn absent_looks() -> [u64; 2] { + [0, 1].map(|i| ABSENT_LOOKS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// Milliseconds since the guards' first asking: the clock of +/// [`absent_once`]'s notes. +fn guard_ms() -> u64 { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + /// For view memory: the pages of `[start, end)`'s blocks written since /// they were last guarded (all of a block's pages), guarding them again /// before the caller copies them. `None` if the memory is not a view. fn guard(start: usize, end: usize) -> Option<Vec<usize>> { - if !mapped(start) { + let keep = if absent_once() { absent_keep_ms() } else { 0 }; + let written = guard_at(start, end, if keep != 0 { guard_ms() } else { 0 }, keep); + // Always on: the counts every 65,536 askings (in turn they are said + // at each change). + if absent_mode() == 1 { + static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if (CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1).is_multiple_of(65_536) { + let [asked, kept] = absent_looks(); + tracing::info!( + "blocks of view memory found uncommitted are asked of Windows again only after {} ms (VICTORY_ABSENT_ONCE=1): in the last 65536 askings of the guards {asked} questions to Windows about such blocks, {kept} blocks answered from their note", + absent_keep_ms() + ); + } + } + written +} + +/// [`guard`] at the moment `now` ([`guard_ms`]). `keep`: for how many +/// milliseconds a block Windows said is uncommitted is not asked about +/// again ([`absent_once`]); 0: it is asked about at every asking. +fn guard_at(start: usize, end: usize, now: u64, keep: u64) -> Option<Vec<usize>> { + // A range whose first block the guards hold already (read-only by our + // hand, or noted absent) is a view: no question to Windows. The + // question walks the page tables to the end of the pages that share the + // first one's state, and a guarded view is one long run of read-only + // pages: 0.6 ms for the title's 174 MB heap, 16 times a frame, and most + // of the 68 ms a frame of "guards" (run 58). + // `VICTORY_GUARD_ASK=1` asks every time, as before. + static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { + let g = guards(); + let first = start / BLOCK; + g.protected.contains(&first) || g.absent.contains(&first) || (view_known() && g.viewed.contains(&first)) + }; + if !known && !is_view(start, end) { return None; } install(); @@ -232,8 +1571,52 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> { let mut written = Vec::new(); let mut run: Option<usize> = None; let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + // The range's clean blocks, in order: read off the set in one pass, + // not looked up one block at a time. A frame asks about some 10 GB of + // view memory, 150,000 blocks, nearly all clean: the lookups were most + // of the 60-90 ms a frame of "guards" (run 54). What the loop adds to + // the set meanwhile is the block it stands at or ones before it. + let clean: Vec<usize> = g.clean.range(first..last).copied().collect(); + if clean.len() == last - first { + // Nothing written, mapped or new since the range was last taken. + return Some(written); + } + let mut next_clean = 0; + let mut uncommitted_until = first; for block in first..=last { - let open = block < last && !g.clean.contains(&block); + while next_clean < clean.len() && clean[next_clean] < block { + next_clean += 1; + } + let is_clean = next_clean < clean.len() && clean[next_clean] == block; + let mut open = block < last && !is_clean; + if open && g.absent.contains(&block) { + // Found uncommitted a moment ago ([`absent_once`]): Windows is + // not asked again yet. What the runtime maps there it tells, + // and that takes the block out of `absent` and its note away. + // (With the light refresh, kept for good only in a placeholder + // reservation: [`note_life`].) + let life = note_life(&g, block, keep); + let noted = life != 0 && g.verified.get(&block).is_some_and(|&at| now < at.saturating_add(life)); + if noted { + ABSENT_LOOKS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + open = false; + } else { + // Ordinary commits need no runtime mapping notification. Reuse + // this asking's query for the following blocks in the same region. + if block >= uncommitted_until { + ABSENT_LOOKS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + uncommitted_until = uncommitted_end(block); + } + open = block >= uncommitted_until; + if open { + g.absent.remove(&block); + g.verified.remove(&block); + forget_hole(&mut g, block); + } else if keep != 0 { + g.verified.insert(block, now); + } + } + } if open { written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE); if g.protected.contains(&block) { @@ -251,55 +1634,126 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> { Some(written) } -/// Whether the current allocation at `at` is a mapped view. Asking only for -/// the allocation type avoids enumerating pages with identical protection, -/// which can span an entire large view after its blocks were guarded. -fn mapped(at: usize) -> bool { +/// Whether `[start, end)` is view memory. The title's views lie in +/// placeholders, mapped and unmapped block by block as it streams, so a +/// range can begin in a block that is not mapped right now: the first +/// pages of the range that are there decide. A range with nothing there +/// counts as a view (its blocks are noted absent, and looked at again when +/// the runtime maps them). +/// +/// Looking at the first address only took such a range for "not a view": +/// its copy was marked not watched for good and copied whole at every +/// refresh, around its unmapped pages (run 54: 300 such ranges, 570 MB +/// copied a frame for them, 255 copies a frame reading around holes). +/// `VICTORY_GUARD_HOLES=0` looks at the first address only, as before. +fn is_view(start: usize, end: usize) -> bool { use windows_sys::Win32::System::Memory::{ - MEM_MAPPED, MEMORY_BASIC_INFORMATION, MemoryRegionInfo, QueryVirtualMemoryInformation, - VirtualQuery, WIN32_MEMORY_REGION_INFORMATION, - }; - use windows_sys::Win32::System::Threading::GetCurrentProcess; - - let mut region = WIN32_MEMORY_REGION_INFORMATION::default(); - // SAFETY: both queries describe an address without dereferencing it. The - // output buffers match their information classes. - let queried = unsafe { - QueryVirtualMemoryInformation( - GetCurrentProcess(), - at as *const _, - MemoryRegionInfo, - (&raw mut region).cast(), - size_of_val(®ion), - std::ptr::null_mut(), - ) + MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery, }; - if queried != 0 { - // These are the Windows SDK's named bitfields in declaration order. - // windows-sys exposes only the union's raw bits. - const PRIVATE: u32 = 1 << 0; - const MAPPED_DATA_FILE: u32 = 1 << 1; - const MAPPED_IMAGE: u32 = 1 << 2; - const MAPPED_PAGE_FILE: u32 = 1 << 3; - const MAPPED_PHYSICAL: u32 = 1 << 4; - // SAFETY: this union was filled by the successful query above. - match unsafe { region.Anonymous.Flags } { - MAPPED_DATA_FILE | MAPPED_PAGE_FILE | MAPPED_PHYSICAL => return true, - PRIVATE | MAPPED_IMAGE => return false, - _ => {} - } - } - // Unknown flag combinations and failed allocation queries keep the - // VirtualQuery type check, including for a free address. - let mut info = MEMORY_BASIC_INFORMATION::default(); - // SAFETY: the output buffer has the required layout and size. - let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; - n != 0 && info.Type == MEM_MAPPED + static HOLES: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let holes = *HOLES.get_or_init(|| std::env::var_os("VICTORY_GUARD_HOLES").is_none_or(|v| v != "0")); + let mut at = start; + loop { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + if n == 0 { + return false; + } + if info.Type == MEM_MAPPED { + return true; + } + // Committed memory that is no view (the title's heaps, ours), or + // the answer as it was before. + if info.State == MEM_COMMIT || !holes { + return false; + } + // A hole (a placeholder, or free): on to what follows it. + let next = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if next <= at || next >= end { + return true; + } + at = next; + } } /// Makes blocks `[from, to)` read-only and notes them guarded and clean; -/// block by block if they span views, leaving out any that fail (unmapped). +/// block by block if they span views, leaving out any that fail, and +/// noting those not committed (unmapped) absent. The same physical pages +/// at every other view of them are made read-only too: a write through +/// one of those is this memory written, and only a fault can say so. +/// `VICTORY_VIEW_GUARD=0` leaves the other views as they are, as before. fn protect(g: &mut Guards, from: usize, to: usize) { + protect_here(g, from, to); + if !view_guard() { + return; + } + for (base, bytes) in crate::inplace::views_between(from.saturating_mul(BLOCK), to.saturating_mul(BLOCK)) { + let first = (base / BLOCK).max(from); + let last = (base.saturating_add(bytes).div_ceil(BLOCK)).min(to); + for block in first..last { + let shown = crate::inplace::pages_of(block * BLOCK); + // One view (nothing else to guard), or the page the title shows + // wherever it has nothing (thousands of views): each view of + // that one is guarded by itself. + if shown.len() < 2 || shown.len() > MANY_VIEWS { + continue; + } + #[cfg(feature = "diagnostics")] + ALIASES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + for alias in shown { + let alias = alias / BLOCK; + g.aliased.insert(alias); + if alias != block { + protect_alias(g, alias); + } + } + } + } +} + +/// Views of one page past which its views are not guarded together. +pub(crate) const MANY_VIEWS: usize = 64; + +/// Whether all the views of a guarded page are guarded together +/// (`VICTORY_VIEW_GUARD`). +fn view_guard() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_GUARD").is_none_or(|v| v != "0")) +} + +/// Diagnostics: blocks guarded together with their other views, blocks +/// opened because another view of theirs was written, and blocks opened +/// because a view of theirs was mapped; since the start. +#[cfg(feature = "diagnostics")] +pub(crate) static ALIASES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Makes `block` read-only: another view of pages a copy has just taken +/// through its own view, so that a write through this one faults too. It is +/// not noted clean. The copies of title memory at this view have not taken +/// the pages: noted clean, the block would not be reported written at their +/// next check and they would keep the bytes from before the write (`guard` +/// reports a block that is read-only and not clean as written, then notes it +/// clean). A block that is clean stays so: had the pages been written since +/// its copies took them, `open` would have opened it. +fn protect_alias(g: &mut Guards, block: usize) { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + if g.protected.contains(&block) { + return; + } + let mut old = 0; + // SAFETY: title view memory; only its protection changes. + if unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READONLY, &mut old) } != 0 { + g.protected.insert(block); + if view_known() { + g.viewed.insert(block); + } + } +} + +/// [`protect`] for one range, without the other views of its pages. +fn protect_here(g: &mut Guards, from: usize, to: usize) { use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; let set = |from: usize, to: usize| { let mut old = 0; @@ -316,6 +1770,9 @@ fn protect(g: &mut Guards, from: usize, to: usize) { let note = |g: &mut Guards, from: usize, to: usize| { g.protected.extend(from..to); g.clean.extend(from..to); + if view_known() { + g.viewed.extend(from..to); + } }; if set(from, to) { note(g, from, to); @@ -324,14 +1781,83 @@ fn protect(g: &mut Guards, from: usize, to: usize) { for block in from..to { if set(block, block + 1) { note(g, block, block + 1); + } else { + #[cfg(feature = "diagnostics")] + let error = std::io::Error::last_os_error(); + if block < uncommitted_end(block) { + g.absent.insert(block); + } else { + // Diagnostics: a committed block that will not be made + // read-only is reported written at every asking and never + // known to the guards (one in 1,024 said). + #[cfg(feature = "diagnostics")] + { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(1024) { + tracing::info!("a block of title memory could not be made read-only (one in 1024): {:#x}: {error}", block * BLOCK); + } + } + } } } } +/// The end (exclusive) of the whole uncommitted blocks starting at `block`. +fn uncommitted_end(block: usize) -> usize { + use windows_sys::Win32::System::Memory::{ + MEM_FREE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, VirtualQuery, + }; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery((block * BLOCK) as *const _, &mut info, size_of_val(&info)) }; + if n != 0 && matches!(info.State, MEM_RESERVE | MEM_FREE) { + (info.BaseAddress as usize).saturating_add(info.RegionSize) / BLOCK + } else { + block + } +} + /// Gives write access back to the guarded blocks of `[start, end)` and -/// notes them written; true if any was guarded. +/// notes them written; true if any was guarded. The same physical pages at +/// every other view of them are opened too: the write that faulted (or is +/// ours, `crate::host::copy_mapped`) goes through one view, and every +/// guard over the pages must copy them again. fn open(g: &mut Guards, start: usize, end: usize) -> bool { + // The light refresh: no view of these pages is known by its bit once + // one of them can be written (who asks the bits takes no lock of ours; + // after avatarmanz/VIctory-7900XTX 689df313). + if light_kept() && start < end && !g.aliased.is_empty() { + for &block in g.aliased.range(start / BLOCK..end.div_ceil(BLOCK)) { + for alias in crate::inplace::pages_of(block * BLOCK) { + PUBLISHED.clear(alias / BLOCK); + } + } + } + let any = open_here(g, start, end); + if start >= end || g.aliased.is_empty() { + return any; + } + let aliased: Vec<usize> = g.aliased.range(start / BLOCK..end.div_ceil(BLOCK)).copied().collect(); + for block in aliased { + g.aliased.remove(&block); + for alias in crate::inplace::pages_of(block * BLOCK) { + if alias / BLOCK != block && open_here(g, alias, alias.saturating_add(BLOCK)) { + #[cfg(feature = "diagnostics")] + ALIASES[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + g.aliased.remove(&(alias / BLOCK)); + } + } + any +} + +/// [`open`] for one range, without the other views of its pages. +fn open_here(g: &mut Guards, start: usize, end: usize) -> bool { use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + // Held for a copy-back (`crate::lazy`): its own protection back first, + // which the guard's own below then replaces. + crate::lazy::release(start, end.saturating_sub(start)); let blocks: Vec<usize> = g .protected .range(start / BLOCK..end.div_ceil(BLOCK)) @@ -340,34 +1866,295 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { for &block in &blocks { g.protected.remove(&block); g.clean.remove(&block); + // Before the block can be written ([`PUBLISHED`]; nothing to do + // where no bit was ever set). + PUBLISHED.clear(block); let mut old = 0; // SAFETY: a block we made read-only. unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; } - !blocks.is_empty() -} - -/// Before our own write into title memory `[at, at + len)` through the -/// kernel (which does not fault into our handler): opens its guarded blocks. -/// The runtime calls it (as `kernel_will_write`) before the title's kernel -/// reads into its own memory. -pub fn writing(at: usize, len: usize) { - // The length is the title's (`fread`'s size times count, saturated). - open(&mut guards(), at, at.saturating_add(len)); + !blocks.is_empty() +} + +/// Before our own write into title memory `[at, at + len)` through the +/// kernel (which does not fault into our handler): opens its guarded blocks. +/// The runtime calls it (as `kernel_will_write`) before the title's kernel +/// reads into its own memory. +pub fn writing(at: usize, len: usize) { + // The length is the title's (`fread`'s size times count, saturated). + open(&mut guards(), at, at.saturating_add(len)); + // A placed texture there changes with no descriptor written. + crate::descriptor::host::remapped(at, len); +} + +/// What `VICTORY_PAGE_WRITES` asks to be done with a write the guards do +/// not see once its bytes are there ([`title_memory_written`]), as bits: +/// 1, the guarded blocks under it are opened and count as written (host +/// copies of buffers and textures read through tables take them again); +/// 2, the placed textures picked by index that lie under it are due again; +/// 4, both also for reads to plain addresses when they have finished; +/// 8, for reads to plain addresses the textures alone (bit 2's look). +/// Unset: bits 1, 2 and 8. `guards`: bit 1 alone (the default until +/// 2026-11-26). `0`: nothing, counted only (the default until run 199). +/// `1`: bits 1 and 2. `slots`: bit 2 alone. `all`: everything. +/// +/// Bits 2 and 8 by default (gfx41, the black faces of the opening +/// cutscene): a read makes the placed textures under it due before it +/// begins ([`writing`]), and the texture pass of its own thread +/// (`VICTORY_HEAP_WORKER=1`) uploads them while the read is under way, +/// from memory that does not hold the bytes yet; nothing asked again once +/// they were there. Run 345 at the cutscene: 282 slots of placed textures +/// uploaded before a DirectStorage write into their pages, "left as they +/// were", and 55,836 reads to plain addresses finished, "counted only". +/// Only slots uploaded before the bytes landed are made due again +/// (`HostHeap::texture_slots_page_written`): a slot still waiting for its +/// first upload takes the bytes that are there by then. +/// (Bit 1 by default: in every run 10,000 to 50,000 guarded blocks of host +/// copies lay under such writes and kept the bytes from before; runs 197 +/// and 198 opened them, 9,766 and 10,796 blocks, with nothing worse for +/// it. Bit 2 makes texture slots due and is the one that flooded the +/// queue in an earlier form: still asked for by name.) +pub(crate) fn page_writes() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_PAGE_WRITES").as_deref().map(str::trim) { + Ok("0") => 0, + Ok("1") => 3, + Ok("slots") => 2, + Ok("guards") => 1, + Ok("all") => 15, + _ => 1 | 2 | 8, + }) +} + +/// Since the start: writes into physical pages through the runtime's own +/// views that landed at addresses the title has mapped (one for each run +/// of addresses); their bytes; guarded blocks that lay under them (host +/// copies that would otherwise keep the bytes from before); reads to +/// plain addresses that finished; of those, the ones passed to the texture +/// pass (bit 8 or 4 of [`page_writes`]). +pub(crate) static WRITTEN: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// The bytes of a write the guards do not see are there: title memory +/// `[at, at + len)`. `pages`: DirectStorage wrote them into physical pages +/// through a view of the runtime's own, and this is an address where the +/// title has those pages mapped (no title address faulted, nothing was +/// mapped or unmapped; the shortcut this file's header names). Otherwise a +/// read to a plain address has finished, of which [`writing`] was told +/// before it began. +/// +/// Upstream's c75fdba does the same for its trackers (its `Writing` marks +/// the pages once more when dropped; page destinations are reported at +/// each address showing them). Here it is counted always and acted on as +/// [`page_writes`] says. Called without the runtime's page-table lock; +/// takes the guards' lock, then, alone, the lock of the ranges kept for +/// the texture pass. +pub fn title_memory_written(at: usize, len: usize, pages: bool) { + use std::sync::atomic::Ordering::Relaxed; + if len == 0 { + return; + } + let mode = page_writes(); + let end = at.saturating_add(len); + if pages { + WRITTEN[0].fetch_add(1, Relaxed); + WRITTEN[1].fetch_add(len as u64, Relaxed); + } else { + WRITTEN[3].fetch_add(1, Relaxed); + if mode & (4 | 8) == 0 { + return; + } + WRITTEN[4].fetch_add(1, Relaxed); + if mode & 4 == 0 { + // (Bit 8 alone: the placed textures under it, not the guards.) + crate::descriptor::host::page_written(at, len); + return; + } + } + { + let mut g = guards(); + let guarded = g.protected.range(at / BLOCK..end.div_ceil(BLOCK)).count() as u64; + if pages { + WRITTEN[2].fetch_add(guarded, Relaxed); + } + if mode & 1 != 0 && guarded != 0 { + open(&mut g, at, end); + } + } + // A placed texture there changed with no descriptor written. + crate::descriptor::host::page_written(at, len); +} + +/// The runtime mapped a view of the physical bytes `[offset, offset + len)` +/// of `section` (`crate::inplace::title_memory_view`): the view is +/// writable, so the same bytes guarded at another view must be checked +/// again — and are, the pages noted written, which also has the next check +/// guard the new view (`protect`). +pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) { + if !view_guard() { + return; + } + let ranges = crate::inplace::views_of_section(section, offset, len); + if ranges.is_empty() { + return; + } + let mut g = guards(); + // The light refresh: all of them told as written before the first can + // be written (as in [`open`]). + if light_kept() { + for &(at, n) in &ranges { + for &block in g.protected.range(at / BLOCK..at.saturating_add(n).div_ceil(BLOCK)) { + PUBLISHED.clear(block); + } + } + } + for &(at, n) in &ranges { + if open_here(&mut g, at, at.saturating_add(n)) { + #[cfg(feature = "diagnostics")] + ALIASES[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } +} + +/// Held shared by a read of title memory in place, and alone by the runtime +/// while it changes what title memory shows. +/// +/// The runtime does not change a mapping in one step. To unmap one page of +/// a view it unmaps the whole view and maps what stays again +/// (`xmem.rs` `unmap`), and a view it maps is a reservation until the next +/// call commits it (`map`, then `commit`). For that moment pages the title +/// never gave up are "reserved, never committed", and a thread reading +/// them in place takes an access violation: run 71 in `Layout::detile`, +/// run 74 in the hash before it, both under `Staging::refresh_now`, which +/// had asked whether the texture was all mapped and been told yes. Asking +/// cannot help; not changing the mapping while such a read is under way +/// does. +static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +/// What the runtime holds while it changes what title memory shows +/// ([`title_memory_remapping`]). +pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>, std::time::Instant); + +impl Drop for Remapping { + fn drop(&mut self) { + // From asking for the lock until it is let go (the frame log). + crate::framelog::add(crate::framelog::T::RemapUs, self.1.elapsed().as_micros() as u64); + } +} + +/// The runtime is about to map, unmap or move physical pages of title +/// memory: until what it returns is dropped, no read of title memory in +/// place is under way and none begins ([`title_memory_reading`]). Taken +/// around the whole change, the unmapping and the mapping again. +pub fn title_memory_remapping() -> Remapping { + let asked = std::time::Instant::now(); + let held = MAPPING.write().unwrap_or_else(|e| e.into_inner()); + crate::framelog::add(crate::framelog::T::Remaps, 1); + crate::framelog::add(crate::framelog::T::RemapWaitUs, asked.elapsed().as_micros() as u64); + Remapping(held, asked) +} + +/// What a read of title memory in place holds ([`title_memory_reading`]). +pub struct Reading(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>); + +/// For reading title memory in place: until what it returns is dropped, +/// the runtime changes no mapping, so memory found mapped stays mapped. +/// Not to be taken twice by one thread, nor held across anything that +/// maps title memory. +pub fn title_memory_reading() -> Reading { + Reading(MAPPING.read().unwrap_or_else(|e| e.into_inner())) +} + +/// [`title_memory_reading`] if it can be had at once: `None` while the +/// runtime changes a mapping (or waits to), for a caller that has another +/// way to read and would rather not wait. +pub fn title_memory_reading_now() -> Option<Reading> { + match MAPPING.try_read() { + Ok(guard) => Some(Reading(guard)), + Err(std::sync::TryLockError::Poisoned(e)) => Some(Reading(e.into_inner())), + Err(std::sync::TryLockError::WouldBlock) => None, + } +} + +/// The runtime committed title memory `[at, at + len)` for the title +/// (`XMemVirtualAlloc` with a commit): what [`absent_once`] noted about its +/// blocks is forgotten, so the next asking puts the question to Windows +/// again, as every asking did before the notes. With `VICTORY_ABSENT_MS=told` +/// this and [`title_memory_remapped`] are the only ways a block noted +/// uncommitted is asked about again. +pub fn title_memory_committed(at: usize, len: usize) { + if len == 0 || absent_mode() == 0 { + return; + } + let mut g = guards(); + if g.verified.is_empty() { + return; + } + let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); + let noted: Vec<usize> = g.verified.range(first..last).map(|(&block, _)| block).collect(); + for block in noted { + g.verified.remove(&block); + forget_hole(&mut g, block); + } } /// The runtime mapped or unmapped title memory `[at, at + len)`: what it -/// shows is new and read-write, so it is no longer guarded. +/// shows is new and read-write, so it is no longer guarded (nor known +/// unmapped). pub fn title_memory_remapped(at: usize, len: usize) { + // Stored pages followed there end (`VICTORY_BACK_READS`): counted only. + #[cfg(feature = "diagnostics")] + crate::backreads::remapped(at, len); + crate::texback::remapped(at, len); + // A placed texture there arrives, goes or changes with no descriptor + // written. + crate::descriptor::host::remapped(at, len); + // The views the runtime told us of there are no longer what it shows. + crate::inplace::views_gone(at, len); + // And nothing stays in place over it. + crate::inplace::title_memory_freeing(at, len); + // Nor held for a copy-back. + crate::lazy::forget(at, len); let mut g = guards(); - let blocks: Vec<usize> = g - .protected - .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) - .copied() - .collect(); + let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); + let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect(); + for block in absent { + g.absent.remove(&block); + g.verified.remove(&block); + forget_hole(&mut g, block); + } + let blocks: Vec<usize> = g.protected.range(range).copied().collect(); for block in blocks { g.protected.remove(&block); g.clean.remove(&block); + // What it shows is new ([`PUBLISHED`]). + PUBLISHED.clear(block); + } + let aliased: Vec<usize> = g.aliased.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + for block in aliased { + g.aliased.remove(&block); + } + if view_known() { + // The runtime calls this for two things only (`xmem`: `map` and + // `unmap`): a range it has just mapped a section's pages into, + // and a view it is about to make a placeholder again. Either way + // what stands there is view memory or a hole in it, which is what + // `is_view` would answer for a range that begins there; and the + // write watch's asking can only fail there. The title remaps some + // 83 times a frame, and each time the blocks were forgotten, so + // that the next asking about each range went to the kernel twice + // (run 235: 266 to 565 failed askings a frame with the blocks + // remembered from their guards alone, no fewer than without). + g.viewed.extend(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)); + return; + } + // What the range shows is new: no longer known to be a view. + let viewed: Vec<usize> = g.viewed.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + for block in viewed { + g.viewed.remove(&block); + } + let aliased: Vec<usize> = g.aliased.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + for block in aliased { + g.aliased.remove(&block); } } @@ -390,6 +2177,11 @@ fn install() { return EXCEPTION_CONTINUE_SEARCH; } let at = r.ExceptionInformation[1]; + // Memory held for a copy-back (`crate::lazy`): the write waits for + // it, and faults here again if the block is still guarded. + if crate::lazy::fault(at) { + return EXCEPTION_CONTINUE_EXECUTION; + } // Held across both checks: another thread may have opened the block // since this one faulted, and a copy may have guarded it again since // (then it is ours again, not read-only for some other reason). @@ -397,6 +2189,7 @@ fn install() { if open(&mut g, at, at + 1) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::GuardFaults, 1); + crate::framelog::add(crate::framelog::T::GuardFaults, 1); return EXCEPTION_CONTINUE_EXECUTION; } if writable(at) { @@ -406,6 +2199,9 @@ fn install() { } } static ONCE: std::sync::Once = std::sync::Once::new(); + // The switch is read here, not first in the handler ([`open`] asks + // it): reading the environment allocates. + light_kept(); // SAFETY: the handler only touches our guard state and protections. ONCE.call_once(|| unsafe { AddVectoredExceptionHandler(1, Some(on_write)); @@ -432,41 +2228,6 @@ mod tests { }; const MEM_WRITE_WATCH: u32 = 0x20_0000; - #[test] - fn allocation_query_recognizes_file_views_and_rejects_nonviews() { - use std::os::windows::io::AsRawHandle; - use windows_sys::Win32::Foundation::CloseHandle; - use windows_sys::Win32::System::Memory::{ - CreateFileMappingW, FILE_MAP_READ, MapViewOfFile, PAGE_READONLY, UnmapViewOfFile, - }; - let file = tempfile::tempfile().unwrap(); - file.set_len(PAGE as u64).unwrap(); - // SAFETY: a valid, open file and a read-only mapping of its contents. - let section = unsafe { - CreateFileMappingW( - file.as_raw_handle(), - std::ptr::null(), - PAGE_READONLY, - 0, - 0, - std::ptr::null(), - ) - }; - assert!(!section.is_null()); - // SAFETY: an open section containing at least one page. - let view = unsafe { MapViewOfFile(section, FILE_MAP_READ, 0, 0, PAGE) }; - assert!(!view.Value.is_null()); - assert!(mapped(view.Value as usize + 13)); - // SAFETY: our successful mapping and its section handle. - unsafe { - UnmapViewOfFile(view); - CloseHandle(section); - } - assert!(!mapped((&raw const file) as usize)); // private stack allocation - assert!(!mapped(mapped as *const () as usize)); // executable image - assert!(!mapped(0)); // no allocation to query - } - #[test] fn written_pages_are_reported_to_every_asker() { // SAFETY: a fresh write-watched allocation, freed at the end. @@ -480,20 +2241,17 @@ mod tests { } as usize; assert_ne!(p, 0); let (start, end) = (p, p + 4 * PAGE); - // A previous test may have used these virtual addresses. - let mut journal = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); - for page in start / PAGE..end / PAGE { - journal.written.remove(&page); - } - drop(journal); - let (_, before) = writes(start, end, false).expect("watched"); - assert!(before.is_empty()); + // (Not empty by rule: the journal is the process's and keeps what + // was written at an address for good, and a fresh allocation can + // land where another test's freed one stood; that failed this test + // now and then. Nothing written since the allocation is new.) + let (asked, before) = writes(start, end, false).expect("watched"); + assert!(before.iter().all(|&(_, at)| at < asked), "a fresh allocation has no page written at this asking"); // SAFETY: committed pages of ours. unsafe { ((p + PAGE + 8) as *mut u8).write(1) }; - // Under Wine a range is asked of the kernel once per submission. - new_submission(); let (now, after) = writes(start, end, false).expect("watched"); - assert_eq!(after, [(p / PAGE + 1, now)]); + let new: Vec<(usize, u64)> = after.iter().copied().filter(|entry| !before.contains(entry)).collect(); + assert_eq!(new, [(p / PAGE + 1, now)], "the written page, and no other, is new at this asking"); // Another asker after the kernel's bit was cleared still sees it. let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched"); assert!(later > now); @@ -511,106 +2269,6 @@ mod tests { unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; } - /// Two write-watched allocations side by side (the runtime reserves - /// title memory allocation by allocation), asked about as one range, as - /// a buffer spanning them is: the pages written in each are reported. - #[test] - fn a_range_over_several_watched_allocations_is_watched() { - let (a, b) = loop { - // SAFETY: a probe reservation, released at once to find room for two. - let span = - unsafe { VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE, PAGE_READWRITE) }; - assert!(!span.is_null()); - // SAFETY: the probe above. - unsafe { VirtualFree(span, 0, MEM_RELEASE) }; - let at = |p: usize| { - // SAFETY: a fixed address in the room just released. - let got = unsafe { - VirtualAlloc( - p as *const _, - 2 * PAGE, - MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, - PAGE_READWRITE, - ) - }; - got as usize - }; - let a = at(span as usize); - let b = at(span as usize + 2 * PAGE); - if a != 0 && b != 0 { - break (a, b); - } - for p in [a, b].into_iter().filter(|&p| p != 0) { - // SAFETY: ours. - unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; - } - }; - let _ = writes(a, b + 2 * PAGE, false); - // SAFETY: committed pages of ours. - unsafe { - ((a + 8) as *mut u8).write(1); - ((b + PAGE + 8) as *mut u8).write(1); - } - let (now, found) = writes(a, b + 2 * PAGE, false).expect("watched"); - assert_eq!(found, [(a / PAGE, now), (b / PAGE + 1, now)]); - // Not freed: the journal keeps these pages, and a later test given - // the same addresses would find them written. - } - - /// A range in an allocation reserved but not committed yet (as the - /// title's are before it uses them) has no writes, and is asked again - /// once committed. - #[test] - fn a_range_never_committed_has_no_writes() { - // SAFETY: a fresh write-watched reservation, freed at the end. - let p = unsafe { - VirtualAlloc( - std::ptr::null(), - 2 * PAGE, - MEM_RESERVE | MEM_WRITE_WATCH, - PAGE_READWRITE, - ) - } as usize; - assert_ne!(p, 0); - let (_, none) = writes(p, p + 2 * PAGE, false).expect("nothing can be written there"); - assert!(none.is_empty()); - // SAFETY: committing and writing a page of our reservation. - unsafe { - assert!(!VirtualAlloc(p as *const _, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); - ((p + 8) as *mut u8).write(1); - } - let (now, found) = writes(p, p + 2 * PAGE, false).expect("watched"); - assert_eq!(found, [(p / PAGE, now)]); - // Not freed: the journal keeps these pages, and a later test given - // the same addresses would find them written. - } - - /// Under Wine, a write after a range was asked about in a submission - /// is reported in the next one, not lost. - #[test] - fn writes_within_a_submission_show_in_the_next() { - if !on_wine() { - return; - } - // SAFETY: a fresh write-watched allocation, freed at the end. - let p = unsafe { - VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) - } as usize; - assert_ne!(p, 0); - // Kept, not freed: another test given this address would see the - // journal's entries for it. The journal may already hold some (a - // freed allocation of another test here), so compare with them. - new_submission(); - let (_, before) = writes(p, p + 2 * PAGE, false).expect("watched"); - // SAFETY: committed pages of ours. - unsafe { ((p + 8) as *mut u8).write(1) }; - let (_, same) = writes(p, p + 2 * PAGE, false).expect("watched"); - assert_eq!(same, before, "answered from the journal within the submission"); - new_submission(); - let (now, next) = writes(p, p + 2 * PAGE, false).expect("watched"); - assert!(next.contains(&(p / PAGE, now)), "the write shows in the next submission"); - } - /// A kernel read into a guarded view block fails; opened first, it /// lands and the block counts as written. #[test] @@ -649,11 +2307,9 @@ mod tests { ); writing(view + 100, 13); assert!(read(&mut file)); - assert_eq!( - // SAFETY: the bytes just read. - unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, - b"from the disk" - ); + // SAFETY: the bytes just read. + let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }; + assert_eq!(landed, b"from the disk"); assert_eq!( guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()) @@ -669,6 +2325,483 @@ mod tests { title_memory_remapped(view, 2 * BLOCK); } + #[test] + fn writes_in_partly_committed_view_blocks_are_reported() { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, + SEC_RESERVE, UnmapViewOfFile, + }; + + const SIZE: usize = 3 * BLOCK; + struct View(MEMORY_MAPPED_VIEW_ADDRESS); + impl Drop for View { + fn drop(&mut self) { + title_memory_remapped(self.0.Value as usize, SIZE); + // SAFETY: our view is still mapped. + unsafe { UnmapViewOfFile(self.0) }; + } + } + // SAFETY: a new reserved pagefile section. The view holds its own + // reference after we close the handle, including on assertion failure. + let view = unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE | SEC_RESERVE, + 0, + SIZE as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, SIZE); + CloseHandle(section); + assert!(!view.Value.is_null()); + View(view) + }; + let start = view.0.Value as usize; + let commit = |at: usize, len| { + // SAFETY: these pages belong to our reserved view. + let committed = unsafe { VirtualAlloc(at as _, len, MEM_COMMIT, PAGE_READWRITE) }; + assert_eq!(committed as usize, at); + }; + let early = start + BLOCK + 3 * KERNEL_PAGE; + let late = start + 2 * BLOCK + 3 * KERNEL_PAGE; + commit(start, BLOCK); + commit(early, KERNEL_PAGE); + let refresh = || guard(start, start + SIZE).unwrap(); + assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]); + // The last block is still entirely reserved. + assert!(!refresh().contains(&(late / PAGE))); + + commit(late, KERNEL_PAGE); // Ordinary commit, without a runtime mapping notification. + for at in [early, late] { + assert!(writable(at)); + // SAFETY: each address is inside its committed read-write page. + unsafe { (at as *mut u8).write_volatile(1) }; + } + assert_eq!(refresh(), [early / PAGE, late / PAGE]); + } + + /// A range of view memory whose first block is not mapped is a view + /// all the same: its blocks are reported once, then the ones written + /// or mapped since. + #[test] + fn a_range_that_begins_in_an_unmapped_block_is_guarded() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder of three blocks and a pagefile + // section of three; the middle block is mapped first. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 3 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (3 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + (p, section) + }; + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let all: Vec<usize> = (0..3).flat_map(pages).collect(); + // Nothing mapped at all: a view with every block absent. + assert!(is_view(p, p + 3 * BLOCK)); + let middle = map(1); + title_memory_remapped(p + BLOCK, BLOCK); + // The range begins in the placeholder, its middle block is a view. + assert!(is_view(p, p + 3 * BLOCK)); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since"); + // SAFETY: inside the mapped middle block. + unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) }; + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + let first = map(0); + title_memory_remapped(p, BLOCK); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + // Memory of ours that is no view stays none. + let mut local = [0u8; 16]; + let at = local.as_mut_ptr() as usize; + assert!(!is_view(at, at + local.len())); + // SAFETY: our views and placeholder. + unsafe { + UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); + UnmapViewOfFile2(GetCurrentProcess(), middle, MEM_PRESERVE_PLACEHOLDER); + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + windows_sys::Win32::Foundation::CloseHandle(section); + } + title_memory_remapped(p, 3 * BLOCK); + } + + /// Blocks of a placeholder between views are reported once, then not + /// again (they cannot be guarded) until the runtime maps them. + #[test] + fn unmapped_blocks_are_reported_once_until_mapped() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder of three blocks and a pagefile + // section of two; block 0 shows the section's first block, as the + // runtime maps physical pages. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 3 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + (p, section) + }; + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let first = map(0); + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let all: Vec<usize> = (0..3).flat_map(pages).collect(); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!( + guard(p, p + 3 * BLOCK), + Some(Vec::new()), + "nothing written since" + ); + let second = map(1); + title_memory_remapped(p + BLOCK, BLOCK); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + // SAFETY: our views and placeholder. + unsafe { + UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); + UnmapViewOfFile2(GetCurrentProcess(), second, MEM_PRESERVE_PLACEHOLDER); + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + windows_sys::Win32::Foundation::CloseHandle(section); + } + title_memory_remapped(p, 3 * BLOCK); + } + + /// With a note kept ([`absent_once`]): a block Windows said is + /// uncommitted is not asked about again until the note is old, so what + /// appears there without a word is seen that much later; what the + /// runtime tells of is seen at once; and with no note kept (`keep` 0) + /// everything is seen at the next asking, as before. + #[test] + fn a_block_noted_uncommitted_is_asked_about_again_only_when_its_note_is_old() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder of four blocks and a pagefile + // section of four, as the runtime maps physical pages. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 4 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (4 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + (p, section) + }; + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let (from, to) = (p, p + 4 * BLOCK); + const KEEP: u64 = 100; + let first = map(0); + let all: Vec<usize> = (0..4).flat_map(pages).collect(); + assert_eq!(guard_at(from, to, 1_000, KEEP), Some(all), "the first asking takes every block"); + assert_eq!(guard_at(from, to, 1_000, KEEP), Some(Vec::new()), "blocks 1 to 3 are noted uncommitted"); + // Mapped without a word to the guards. + let second = map(1); + assert_eq!(guard_at(from, to, 1_050, KEEP), Some(Vec::new()), "the note is 50 ms old: Windows is not asked"); + assert_eq!(guard_at(from, to, 1_100, KEEP), Some(pages(1).collect()), "the note is old: the block is found"); + assert_eq!(guard_at(from, to, 1_100, KEEP), Some(Vec::new())); + // Mapped and told, as the runtime does: seen at once, note or not. + let third = map(2); + title_memory_remapped(p + 2 * BLOCK, BLOCK); + assert_eq!(guard_at(from, to, 1_101, KEEP), Some(pages(2).collect())); + // No note kept: a block mapped without a word is found at the next + // asking, though its note is one millisecond old. + let fourth = map(3); + assert_eq!(guard_at(from, to, 1_101, 0), Some(pages(3).collect())); + assert_eq!(guard_at(from, to, 1_101, KEEP), Some(Vec::new())); + // SAFETY: our views and placeholder. + unsafe { + for view in [first, second, third, fourth] { + UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER); + } + for block in 0..4 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + windows_sys::Win32::Foundation::CloseHandle(section); + } + title_memory_remapped(p, 4 * BLOCK); + } + + /// A pagefile section mapped twice: two views of the same physical + /// pages, the second left for the test; the section handle, the two + /// addresses. + fn two_views(bytes: usize) -> (usize, usize, usize) { + use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, + }; + // SAFETY: a fresh pagefile section, mapped twice; the views keep + // the section alive and the handle is closed by the caller. + unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE, + 0, + bytes as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let one = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize; + let two = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize; + assert_ne!(one, 0); + assert_ne!(two, 0); + crate::inplace::title_memory_view(one, bytes, section as usize, 0); + crate::inplace::title_memory_view(two, bytes, section as usize, 0); + (section as usize, one, two) + } + } + + /// The section of [`two_views`] is closed and its views unmapped; the + /// guard is told they are gone first. + fn drop_views(section: usize, views: &[usize], bytes: usize) { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Memory::{MEMORY_MAPPED_VIEW_ADDRESS, UnmapViewOfFile}; + for &view in views { + title_memory_remapped(view, bytes); + // SAFETY: a view of the section mapped by `two_views`. + unsafe { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { + Value: view as *mut _, + }) + }; + } + // SAFETY: the section's last reference. + unsafe { CloseHandle(section as *mut std::ffi::c_void) }; + } + + /// The title wrote the pages of a guarded texture through another view + /// of them: the fault at that view is the guard's to see, and the + /// guarded view's next check reports the pages written. + #[test] + fn a_write_through_another_view_is_reported_at_the_guarded_one() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + // The first check takes it in (and every view of its pages). + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + // Writing through the other view faults into the handler, which + // opens that view and the guarded one: the next check sees it. + // SAFETY: the second view, read-write once the handler has opened it. + unsafe { ((other + BLOCK + 8) as *mut u8).write(1) }; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + drop_views(section, &[guarded, other], SIZE); + } + + /// A view of guarded pages is mapped anew: it is writable, so the + /// guarded view checks its pages again (and guards the new view). + #[test] + fn a_view_mapped_beside_a_guarded_one_makes_it_check_again() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + title_memory_remapped(other, SIZE); + crate::inplace::title_memory_view(other, SIZE, section, 0); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + drop_views(section, &[guarded, other], SIZE); + } + + /// A write of the runtime's own, told at one view of the pages + /// (`writing`): the other views' next checks report the pages written. + #[test] + fn a_write_told_at_one_view_is_reported_at_the_others() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + writing(other + BLOCK, BLOCK); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + // Half a page and the next: both blocks, not just the first's. + writing(other + BLOCK / 2, BLOCK); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + drop_views(section, &[guarded, other], SIZE); + } + + /// Both views of the pages are checked, each for a copy of its own + /// (the title shows one physical page at several addresses, and each + /// address has its host copy): a write through either is reported at + /// both, whichever is checked first. Guarding the pages for the first + /// view's check must not note the second view clean, or its copy would + /// keep the bytes from before the write. + #[test] + fn a_write_is_reported_at_every_checked_view() { + const SIZE: usize = 2 * BLOCK; + let (section, one, two) = two_views(SIZE); + let pages = |view: usize, block: usize| (view + block * BLOCK) / PAGE; + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0), pages(one, 1)])); + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0), pages(two, 1)]), "the second view's first check"); + assert_eq!(guard(one, one + SIZE), Some(Vec::new()), "nothing written yet"); + assert_eq!(guard(two, two + SIZE), Some(Vec::new()), "nothing written yet"); + // SAFETY: the second view, read-write once the handler has opened it. + unsafe { ((two + BLOCK + 8) as *mut u8).write(1) }; + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 1)])); + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 1)]), "written through this view, checked second"); + // SAFETY: the first view, as above. + unsafe { ((one + 8) as *mut u8).write(1) }; + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0)])); + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0)]), "written through this view, checked second"); + assert_eq!(guard(one, one + SIZE), Some(Vec::new())); + assert_eq!(guard(two, two + SIZE), Some(Vec::new())); + drop_views(section, &[one, two], SIZE); + } + + /// A page shown in more than `MANY_VIEWS` views is guarded at each by + /// itself: the others stay writable, and nothing looks through them all. + #[test] + fn a_page_of_many_views_is_guarded_one_view_at_a_time() { + let (section, one, two) = two_views(BLOCK); + let filler = one + (1 << 45); + for n in 0..MANY_VIEWS { + crate::inplace::title_memory_view(filler + n * BLOCK, BLOCK, section, 0); + } + assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE])); + assert!(writable(two), "another view of it is left alone"); + // SAFETY: the guarded view, opened by the handler. + unsafe { ((one + 8) as *mut u8).write(1) }; + assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE])); + title_memory_remapped(filler, MANY_VIEWS * BLOCK); + drop_views(section, &[one, two], BLOCK); + } + /// A write or mapping that runs past the end of the address space (a /// title's `fread` with a huge count) covers up to the end; the sum used /// to overflow. Up there no test has guarded blocks. @@ -678,4 +2811,375 @@ mod tests { writing(top, PAGE); title_memory_remapped(top, usize::MAX); } + + /// The tests of the light refresh take turns: they read its counts, + /// which no other test moves (the switch is not set in tests, so + /// [`writes`] itself keeps no bits and asks none). + fn light_turn() -> std::sync::MutexGuard<'static, ()> { + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Askings answered by the bits, and askings that went to the guards. + fn light_counts() -> [u64; 2] { + [0, 1].map(|i| LIGHT_ASKS[i].load(std::sync::atomic::Ordering::Relaxed)) + } + + /// Whether `[start, end)` is known by its bits. + fn known(start: usize, end: usize) -> bool { + published(&JOURNAL.lock().unwrap_or_else(|e| e.into_inner()), start, end) + } + + /// The pages of an answer of [`writes`] written after the asking `since`. + fn since(since: u64, written: Vec<(usize, u64)>) -> Vec<usize> { + written.into_iter().filter(|w| w.1 > since).map(|w| w.0).collect() + } + + /// The asking that makes blocks clean gives them their bits; the next + /// one is answered by them, and the guards are not asked. A write takes + /// the written block's bit, through the guarded view or through another + /// view of the same pages, and the next asking reports it. + #[test] + fn a_range_is_known_by_its_bits_until_a_write() { + let _turn = light_turn(); + const SIZE: usize = 3 * BLOCK; + let (section, one, two) = two_views(SIZE); + let pages = |block: usize| (one + block * BLOCK) / PAGE; + assert!(!known(one, one + SIZE), "nothing asked yet"); + // The first asking takes every block in, read-only and clean. + let (first, all) = writes_as(one, one + SIZE, true, 2).expect("a view"); + assert_eq!(all, [(pages(0), first), (pages(1), first), (pages(2), first)]); + assert!(known(one, one + SIZE), "made clean and noted"); + // The second is answered by the bits. + let before = light_counts(); + let (second, written) = writes_as(one, one + SIZE, true, 2).expect("a view"); + assert!(second > first); + assert!(since(first, written).is_empty(), "nothing written"); + assert_eq!(light_counts(), [before[0] + 1, before[1]], "the guards were not asked"); + // A write to the guarded view faults: the handler takes the bit. + // SAFETY: the first view, read-write once the handler has opened it. + unsafe { ((one + BLOCK + 8) as *mut u8).write_volatile(1) }; + assert!(!known(one, one + SIZE)); + assert!(known(one, one + BLOCK) && known(one + 2 * BLOCK, one + SIZE), "the blocks beside it keep theirs"); + let before = light_counts(); + let (third, written) = writes_as(one, one + SIZE, true, 2).expect("a view"); + assert_eq!(since(second, written), [pages(1)]); + assert_eq!(light_counts(), [before[0], before[1] + 1], "the guards were asked"); + assert!(known(one, one + SIZE), "guarded again and noted"); + // A write through the other view of the same pages takes it too. + // SAFETY: the second view, as above. + unsafe { ((two + 2 * BLOCK + 8) as *mut u8).write_volatile(1) }; + assert!(!known(one + 2 * BLOCK, one + SIZE), "written through another view"); + assert!(known(one, one + 2 * BLOCK)); + let (fourth, written) = writes_as(one, one + SIZE, true, 2).expect("a view"); + assert_eq!(since(third, written), [pages(2)]); + // A write of ours that is told of (`writing`) does as well. + writing(one + 8, 8); + assert!(!known(one, one + BLOCK)); + let (_, written) = writes_as(one, one + SIZE, true, 2).expect("a view"); + assert_eq!(since(fourth, written), [pages(0)]); + assert!(known(one, one + SIZE)); + // What the runtime maps anew is not known. + title_memory_remapped(one + BLOCK, BLOCK); + assert!(!known(one + BLOCK, one + 2 * BLOCK)); + drop_views(section, &[one, two], SIZE); + } + + /// `VICTORY_LIGHT_REFRESH=alt`: in the phase without, the bits are not + /// asked, and they are kept: what is written in that phase, asked about + /// in it or not, is reported by the first asking of the phase with. + /// With the switch off no bit is ever set. + #[test] + fn bits_kept_through_a_phase_that_does_not_ask_them_are_true_in_the_next() { + let _turn = light_turn(); + const SIZE: usize = 2 * BLOCK; + let (section, one, two) = two_views(SIZE); + let pages = |block: usize| (one + block * BLOCK) / PAGE; + // With: taken in, then known by its bits. + let (first, _) = writes_as(one, one + SIZE, true, 2).expect("a view"); + assert!(known(one, one + SIZE)); + // Without: the bits are there and are not asked. + let before = light_counts(); + let (second, written) = writes_as(one, one + SIZE, true, 1).expect("a view"); + assert!(since(first, written).is_empty()); + assert_eq!(light_counts(), [before[0], before[1] + 1], "without: the guards answer"); + // Written in the phase without: the fault takes the bit all the + // same, and that phase's asking gives it back. + // SAFETY: the first view, read-write once the handler has opened it. + unsafe { ((one + 8) as *mut u8).write_volatile(1) }; + assert!(!known(one, one + BLOCK)); + let (third, written) = writes_as(one, one + SIZE, true, 1).expect("a view"); + assert_eq!(since(second, written), [pages(0)]); + assert!(known(one, one + SIZE)); + // Written again in the phase without, through the other view, and + // not asked about until the phase with: its first asking goes to + // the guards and reports it. + // SAFETY: the second view, as above. + unsafe { ((two + BLOCK + 8) as *mut u8).write_volatile(1) }; + let before = light_counts(); + let (fourth, written) = writes_as(one, one + SIZE, true, 2).expect("a view"); + assert_eq!(since(third, written), [pages(1)], "a bit from before the phase without was trusted"); + assert_eq!(light_counts(), [before[0], before[1] + 1]); + let before = light_counts(); + let (fifth, written) = writes_as(one, one + SIZE, true, 2).expect("a view"); + assert!(since(fourth, written).is_empty()); + assert_eq!(light_counts(), [before[0] + 1, before[1]]); + // The switch off: a write still takes the bit, the asking sets none + // and counts nothing. + // SAFETY: the first view, as above. + unsafe { ((one + 8) as *mut u8).write_volatile(2) }; + let before = light_counts(); + let (_, written) = writes_as(one, one + SIZE, true, 0).expect("a view"); + assert_eq!(since(fifth, written), [pages(0)]); + assert_eq!(light_counts(), before); + assert!(!known(one, one + BLOCK), "off: no bit is set"); + drop_views(section, &[one, two], SIZE); + } + + /// A range with unmapped blocks is not known by its bits while its + /// holes are asked about at every asking. Noted for good, a hole that + /// lies in a placeholder is; then nothing is asked until the runtime + /// tells of the block, or the look at the holes finds it filled. A + /// hole in an ordinary reservation is never known by a bit, and its + /// note grows old. + #[test] + fn holes_are_known_by_their_bits_only_when_noted_for_good() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let _turn = light_turn(); + // SAFETY: a fresh placeholder of four blocks and a pagefile + // section of four, as the runtime maps physical pages. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 4 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (4 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + (p, section) + }; + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let pages = |block: usize| (p + block * BLOCK) / PAGE; + let (from, to) = (p, p + 4 * BLOCK); + let first = map(0); + assert!(placeholder(p / BLOCK + 1) && placeholder(p / BLOCK + 3), "what is left of the placeholder"); + assert!(!placeholder(p / BLOCK), "a view is none"); + // The first asking takes every block; blocks 1 to 3 are unmapped. + let (one, all) = writes_as(from, to, true, 2).expect("a view"); + assert_eq!(since(one - 1, all), [pages(0), pages(1), pages(2), pages(3)]); + assert!(known(p, p + BLOCK) && !known(from, to)); + // Their notes are not for good (no switch says so here): each + // asking goes to the guards, which ask Windows. + let before = light_counts(); + let (two, written) = writes_as(from, to, true, 2).expect("a view"); + assert!(since(one, written).is_empty()); + assert_eq!(light_counts(), [before[0], before[1] + 1]); + assert!(!known(from, to), "a hole not noted for good has no bit"); + // Noted for good, as with `VICTORY_ABSENT_MS=told`, and looked at + // as the asking after the notes does. + assert_eq!(guard_at(from, to, 1, u64::MAX), Some(Vec::new())); + publish(&JOURNAL.lock().unwrap_or_else(|e| e.into_inner()), &[], from, to, true); + assert!(known(from, to), "holes in a placeholder, noted for good"); + let before = light_counts(); + let (three, written) = writes_as(from, to, true, 2).expect("a view"); + assert!(since(two, written).is_empty()); + assert_eq!(light_counts(), [before[0] + 1, before[1]], "answered by the bits, holes and all"); + // Mapped without a word: not seen, as with the notes alone ... + let second = map(1); + let (four, written) = writes_as(from, to, true, 2).expect("a view"); + assert!(since(three, written).is_empty(), "nothing is asked about a hole known by its bit"); + // ... until the look at the holes comes by (it goes round, and + // waits its turn while another test changes a mapping). + for _ in 0..2000 { + if !known(p + BLOCK, p + 2 * BLOCK) { + break; + } + look_at_holes(usize::MAX); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(!known(p + BLOCK, p + 2 * BLOCK), "found filled"); + assert!(known(p + 2 * BLOCK, to), "the holes beside it are holes still"); + let (five, written) = writes_as(from, to, true, 2).expect("a view"); + assert_eq!(since(four, written), [pages(1)]); + assert!(known(from, to)); + // Mapped and told, as the runtime does: the bit goes at once. + let third = map(2); + title_memory_remapped(p + 2 * BLOCK, BLOCK); + assert!(!known(p + 2 * BLOCK, p + 3 * BLOCK)); + let (_, written) = writes_as(from, to, true, 2).expect("a view"); + assert_eq!(since(five, written), [pages(2)]); + // A hole in an ordinary reservation, noted for good all the same: + // anybody can commit it with no word to us, so it gets no bit. + // SAFETY: a fresh reservation of one block, released below. + let plain = unsafe { VirtualAlloc(std::ptr::null(), BLOCK, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(plain, 0); + assert!(!placeholder(plain / BLOCK)); + assert_eq!(guard_at(plain, plain + BLOCK, 1, u64::MAX), Some(vec![plain / PAGE])); + assert_eq!(guard_at(plain, plain + BLOCK, 2, u64::MAX), Some(Vec::new()), "noted"); + publish(&JOURNAL.lock().unwrap_or_else(|e| e.into_inner()), &[], plain, plain + BLOCK, true); + assert!(!known(plain, plain + BLOCK)); + // Nor does its note live for good: committed with no word, it is + // found when the note is old. + // SAFETY: the reservation made above. + let committed = unsafe { VirtualAlloc(plain as *const _, BLOCK, MEM_COMMIT, PAGE_READWRITE) }; + assert_eq!(committed as usize, plain); + assert_eq!(guard_at(plain, plain + BLOCK, 50, u64::MAX), Some(Vec::new()), "the note is 48 ms old"); + assert_eq!(guard_at(plain, plain + BLOCK, 2 + UNSURE_MS, u64::MAX), Some(vec![plain / PAGE]), "the note is old"); + title_memory_remapped(plain, BLOCK); + // SAFETY: our views, placeholder and reservation. + unsafe { + VirtualFree(plain as *mut _, 0, MEM_RELEASE); + for view in [first, second, third] { + UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER); + } + for block in 0..4 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + windows_sys::Win32::Foundation::CloseHandle(section); + } + title_memory_remapped(p, 4 * BLOCK); + } + + /// A copy has nothing new to take of a range known by its bits when it + /// took every page of it after the page's last noted write, and that is + /// known with nothing asked. + #[test] + fn a_copy_that_holds_every_noted_write_has_nothing_new() { + let _turn = light_turn(); + const SIZE: usize = 2 * BLOCK; + let (section, one, two) = two_views(SIZE); + let base = one / PAGE; + assert!(!nothing_noted(one, one + SIZE, base, &[1, 1]), "never asked about: something would have to be asked"); + let (first, _) = writes_as(one, one + SIZE, true, 2).expect("a view"); + let before = light_counts(); + assert!(nothing_noted(one, one + SIZE, base, &[first, first]), "both pages taken at the asking that found them"); + assert_eq!(light_counts(), [before[0] + 1, before[1]]); + assert!(!nothing_noted(one, one + SIZE, base, &[first, first - 1]), "a page taken before its write was found"); + assert!(!nothing_noted(one, one + SIZE, base, &[first, 0]), "a page never taken"); + assert!(!nothing_noted(one, one + SIZE, base + 1, &[first, first]), "a range the copy's notes do not hold"); + assert!(!nothing_noted(one, one + SIZE, base, &[first])); + assert!(!nothing_noted(one, one, base, &[first, first]), "no range"); + // Written: the block's bit is gone, and something must be asked. + // SAFETY: the first view, read-write once the handler has opened it. + unsafe { ((one + BLOCK + 8) as *mut u8).write_volatile(1) }; + assert!(!nothing_noted(one, one + SIZE, base, &[first, first])); + assert!(nothing_noted(one, one + BLOCK, base, &[first, first]), "the block beside it is as it was"); + let (second, _) = writes_as(one, one + SIZE, true, 2).expect("a view"); + assert!(!nothing_noted(one, one + SIZE, base, &[first, first]), "the journal has the write"); + assert!(nothing_noted(one, one + SIZE, base, &[first, second])); + drop_views(section, &[one, two], SIZE); + } + + /// A range's bits are all of its blocks', whatever lies beside them. + #[test] + fn bits_of_ranges() { + static BITS: Bits = Bits::new(); + let blocks = [0usize, 1, 63, 64, 65, 127, 128, 200, 65535, 65536, 65537, 1 << 20, (1 << 31) - 1]; + for &b in &blocks { + assert!(!BITS.all(b, b + 1)); + BITS.set(b); + assert!(BITS.all(b, b + 1)); + } + assert!(BITS.all(0, 2) && BITS.all(63, 66) && BITS.all(127, 129) && BITS.all(65535, 65538)); + assert!(!BITS.all(0, 3) && !BITS.all(62, 64) && !BITS.all(65534, 65536) && !BITS.all(5, 5)); + for b in 300..700 { + BITS.set(b); + } + assert!(BITS.all(300, 700) && !BITS.all(299, 700) && !BITS.all(300, 701)); + BITS.clear(511); + assert!(!BITS.all(300, 700) && BITS.all(300, 511) && BITS.all(512, 700)); + BITS.set(1 << 40); + BITS.clear(1 << 40); + assert!(!BITS.all(1 << 40, (1 << 40) + 1), "outside the address space"); + } +} + +#[cfg(test)] +mod mapping_tests { + use super::{title_memory_reading, title_memory_remapping}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, mpsc}; + use std::time::Duration; + + /// A change of mapping waits for a read in place that is under way, and + /// a read in place waits for a change of mapping. + #[test] + fn reads_in_place_and_remappings_wait_for_each_other() { + // A reader holds; the change does not begin until it lets go. + let changed = Arc::new(AtomicBool::new(false)); + let reading = title_memory_reading(); + let (began, wait) = mpsc::channel(); + let change = { + let changed = changed.clone(); + std::thread::spawn(move || { + began.send(()).unwrap(); + let _changing = title_memory_remapping(); + changed.store(true, Ordering::SeqCst); + }) + }; + wait.recv().unwrap(); + std::thread::sleep(Duration::from_millis(100)); + assert!(!changed.load(Ordering::SeqCst), "the mapping changed under a read in place"); + drop(reading); + change.join().unwrap(); + assert!(changed.load(Ordering::SeqCst)); + // A change holds; the read does not begin until it is done. + let read = Arc::new(AtomicBool::new(false)); + let changing = title_memory_remapping(); + let (began, wait) = mpsc::channel(); + let reader = { + let read = read.clone(); + std::thread::spawn(move || { + began.send(()).unwrap(); + let _reading = title_memory_reading(); + read.store(true, Ordering::SeqCst); + }) + }; + wait.recv().unwrap(); + std::thread::sleep(Duration::from_millis(100)); + assert!(!read.load(Ordering::SeqCst), "a read in place began during a change of mapping"); + drop(changing); + reader.join().unwrap(); + assert!(read.load(Ordering::SeqCst)); + } } diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index 045d2f0ed9..49b5a423b7 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -13,40 +13,32 @@ victory-loader.workspace = true victory-pe.workspace = true victory-formats.workspace = true opus-pure.workspace = true -miniz_oxide.workspace = true +zlib-rs.workspace = true tracing.workspace = true [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = [ - "Win32_Devices_DeviceAndDriverInstallation", - "Win32_Devices_HumanInterfaceDevice", "Win32_Foundation", "Win32_Globalization", "Win32_Media", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", - "Win32_System_IO", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Power", "Win32_System_ProcessStatus", + "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_XboxController", "Win32_UI_WindowsAndMessaging", ] } -# Diagnostics only: recording our own audio (`modules::audio::capture`). +# The host device for the PC FidelityFX upscaler (`modules::fidelityfx`); +# with diagnostics also recording our own audio (`modules::audio::capture`). windows = { workspace = true, features = [ - "Foundation", - "Media_Core", - "Media_SpeechSynthesis", - "Storage_Streams", - "Win32_Media_Audio", - "Win32_System_Com", - "Win32_System_Com_StructuredStorage", - "Win32_System_Threading", - "Win32_System_Variant", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi_Common", ] } # `#[implement]` names it. windows-core = { workspace = true, optional = true } @@ -56,7 +48,11 @@ tempfile.workspace = true [features] # Debugging switches (scripted keys and the like). -diagnostics = ["victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows-core"] +diagnostics = [ + "victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows-core", + "windows/Win32_Media_Audio", "windows/Win32_System_Com", + "windows/Win32_System_Com_StructuredStorage", "windows/Win32_System_Threading", "windows/Win32_System_Variant", +] [lints] workspace = true diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 6ef0966f76..8a2a8750c9 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -44,7 +44,6 @@ impl Default for HostPolicy { "ole32.dll", "advapi32.dll", "iphlpapi.dll", - "rpcrt4.dll", // The title's crash handler writes minidumps with it (loaded by name). "dbghelp.dll", // Same APIs as the console's (XAudio2 ordinal 1 is XAudio2Create @@ -123,15 +122,11 @@ mod imp { fn module(dll: &str) -> Option<usize> { let key = dll.to_ascii_lowercase(); - let cache = || MODULES.lock().unwrap_or_else(|e| e.into_inner()); - let cached = cache().get(&key).copied(); - if cached.is_some() { - return cached; + let mut cache = MODULES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(&m) = cache.get(&key) { + return Some(m); } let name = CString::new(key.as_str()).ok()?; - // Not under the cache's lock: loading takes the OS loader lock, and - // title code that runs under that one (a DLL's thread attach, a TLS - // callback) may look a function up here. // System32 only: never pick up a same-named DLL from the current folder or PATH. // SAFETY: NUL-terminated DLL name; only allow-listed system DLLs get here. let handle = unsafe { @@ -141,95 +136,7 @@ mod imp { LOAD_LIBRARY_SEARCH_SYSTEM32, ) } as usize; - // A thread that loaded it meanwhile got the same module, which stays loaded. - (handle != 0).then(|| *cache().entry(key).or_insert(handle)) - } - - #[cfg(test)] - mod tests { - use std::ffi::c_void; - use std::ptr::{null, null_mut}; - use std::sync::atomic::{AtomicBool, Ordering}; - use std::time::{Duration, Instant}; - - use windows_sys::Win32::System::Threading::{ - CreateThread, INFINITE, Sleep, WaitForSingleObject, - }; - - const CHILD: &str = "VICTORY_HOST_LOCK_CHILD"; - static ARMED: AtomicBool = AtomicBool::new(false); - static IN_ATTACH: AtomicBool = AtomicBool::new(false); - static STARTED: AtomicBool = AtomicBool::new(false); - - /// Runs as title TLS callbacks do: under the loader lock, as a new - /// thread starts. - #[used] - #[unsafe(link_section = ".CRT$XLY")] - static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = attach; - - unsafe extern "system" fn attach(_: *mut c_void, reason: u32, _: *mut c_void) { - const DLL_THREAD_ATTACH: u32 = 2; - if reason == DLL_THREAD_ATTACH && ARMED.swap(false, Ordering::SeqCst) { - IN_ATTACH.store(true, Ordering::SeqCst); - // SAFETY: a plain sleep, for the other thread to start a load. - unsafe { Sleep(500) }; - let found = super::super::function("kernel32.dll", "GetTickCount"); - assert!(found.is_some()); - } - } - - unsafe extern "system" fn idle(_: *mut c_void) -> u32 { - 0 - } - - /// One thread loads a DLL nothing has loaded yet, which needs the - /// loader lock, while another thread's attach holds that lock and - /// looks a function up. Run in a child process: a deadlock inside the - /// loader keeps a process from exiting, so the parent kills it. - #[test] - fn loading_a_host_dll_does_not_block_thread_attach() { - if std::env::var_os(CHILD).is_none() { - let name = "host::imp::tests::loading_a_host_dll_does_not_block_thread_attach"; - let mut child = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", name]) - .env(CHILD, "1") - .spawn() - .unwrap(); - let start = Instant::now(); - loop { - if let Some(status) = child.try_wait().unwrap() { - assert!(status.success()); - return; - } - if start.elapsed() > Duration::from_secs(30) { - child.kill().unwrap(); - panic!("deadlock: a host DLL loads under the module cache's lock"); - } - std::thread::sleep(Duration::from_millis(50)); - } - } - // The attach below only needs the cache, no load of its own. - assert!(super::super::function("kernel32.dll", "GetTickCount").is_some()); - let loader = std::thread::spawn(|| { - STARTED.store(true, Ordering::SeqCst); - while !IN_ATTACH.load(Ordering::SeqCst) { - std::hint::spin_loop(); - } - super::super::function("cabinet.dll", "FDICreate") - }); - // Its own attach is over: the next is the thread below. - while !STARTED.load(Ordering::SeqCst) { - std::hint::spin_loop(); - } - ARMED.store(true, Ordering::SeqCst); - let (security, start) = (std::ptr::null(), Some(idle as _)); - // SAFETY: a thread that returns at once. - let thread = unsafe { CreateThread(security, 0, start, null(), 0, null_mut()) }; - assert!(!thread.is_null()); - assert!(loader.join().unwrap().is_some()); - // SAFETY: our own thread's handle. - unsafe { WaitForSingleObject(thread, INFINITE) }; - } + (handle != 0).then(|| *cache.entry(key).or_insert(handle)) } } @@ -239,15 +146,3 @@ mod imp { None } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn host_policy_allows_rpcrt4() { - let policy = HostPolicy::default(); - assert!(policy.allows("rpcrt4.dll")); - assert!(policy.allows("RPCRT4.DLL")); - } -} diff --git a/crates/victory-hle/src/modules/apu.rs b/crates/victory-hle/src/modules/apu.rs index 51c3daa387..0668f0dead 100644 --- a/crates/victory-hle/src/modules/apu.rs +++ b/crates/victory-hle/src/modules/apu.rs @@ -1,13 +1,10 @@ -//! The console's audio unit (`xapu.dll`): Opus packets or float PCM in, -//! float PCM out, optionally resampled with a pitch change. +//! The console's audio decoder (`xapu.dll`): Opus packets in, float PCM out. //! -//! A title connects once for one kind of processing — decode Opus, decode -//! and convert, or convert PCM — gets a block of memory for its packets and -//! output, and then queues per-stream commands (activate, process, reset, -//! deactivate) and dequeues one result per command. We do each command when -//! it is queued, so its result is ready at once; the order of results is the -//! order of commands. The rate conversion itself lives in -//! [`super::apu_resample`], which is testable on every platform. +//! A title connects once for one kind of processing, gets a block of memory +//! for its packets and output, and then queues per-stream commands +//! (activate, process, reset, deactivate) and dequeues one result per +//! command. We decode each command when it is queued, so its result is ready +//! at once; the order of results is the order of commands. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] @@ -20,7 +17,6 @@ use opus_pure::OpusDecoder; use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent}; -use super::apu_resample::Resampler; use super::xasync::E_INVALIDARG; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleModule, hle_export}; @@ -35,12 +31,8 @@ const INVALID_STREAM: HRESULT = 0x8AC8_1003_u32 as i32; const ALREADY_ACTIVE: HRESULT = 0x8AC8_1005_u32 as i32; const BAD_PACKET: HRESULT = 0x8AC8_1008_u32 as i32; -/// XApuProcessType: decode, decode and resample, resample float PCM. +/// Processing kinds; only plain decoding is implemented. const DECODE_OPUS: u32 = 1; -const DECODE_CONVERT_OPUS: u32 = 2; -const CONVERT_PCM: u32 = 3; -/// The output lengths the hardware accepts when converting. -const OUTPUT_FRAMES: [u32; 5] = [256, 480, 512, 960, 1024]; const ACTIVATE: u32 = 1; const DEACTIVATE: u32 = 2; @@ -48,11 +40,9 @@ const PROCESS: u32 = 3; const NOTIFY: u32 = 4; const RESET: u32 = 5; -/// Command options: signal the connection's event, write out a partial frame. +/// Command option: signal the connection's event when the result is ready. const SIGNAL: u32 = 1; -const FLUSH: u32 = 2; -/// Connect options (XApuConnectOptions). -const DEINTERLEAVED_INPUT: u32 = 2; +/// Connect options. const DEINTERLEAVED_OUTPUT: u32 = 4; const RESULT_EVENT: u32 = 8; @@ -135,24 +125,13 @@ pub struct Connection { memory: *mut u8, layout: Layout, event: HANDLE, - process: u32, - /// The deinterleave midpoint of a converter's output buffer. - frames_per_output: u32, options: u32, per_stream: u32, state: Mutex<State>, } -/// The decoders and converters a stream owns: a decode connection needs a -/// decoder, a convert connection a resampler, decode-convert both. -struct Stream { - decoder: Option<OpusDecoder>, - resampler: Option<Resampler>, - start_pitch: f32, -} - struct State { - streams: Vec<Option<Stream>>, + streams: Vec<Option<OpusDecoder>>, /// Results not yet dequeued, per stream. queued: Vec<u32>, results: VecDeque<ApuResult>, @@ -180,31 +159,21 @@ pub extern "system" fn XApuConnect( { return E_INVALIDARG; } - if !matches!( - input.process, - DECODE_OPUS | DECODE_CONVERT_OPUS | CONVERT_PCM - ) { + if input.process != DECODE_OPUS { + // shortcut: rate conversion (decode-convert, PCM convert) is not + // implemented; add a resampler if a title connects for it. tracing::warn!( process = input.process, - "audio decoder: unknown processing kind" + "audio decoder: processing kind not implemented" ); return E_NOTIMPL; } - // Plain decoding writes what the packet holds; a converter fills a - // buffer of one of the durations the hardware lists. - if input.process == DECODE_OPUS { - if input.frames_per_output != 0 { - return E_INVALIDARG; - } - } else if !OUTPUT_FRAMES.contains(&input.frames_per_output) { + if input.frames_per_output != 0 { return E_INVALIDARG; } let Ok(layout) = Layout::from_size_align(input.memory as usize, 16) else { return E_INVALIDARG; }; - // shortcut: a converter's per-stream processing buffer is a host Vec in - // `Resampler`, not a slice carved out of this title-visible block; the - // block still holds the commands' inputs and outputs as on the console. // SAFETY: non-zero size. let memory = unsafe { std::alloc::alloc_zeroed(layout) }; if memory.is_null() { @@ -212,13 +181,7 @@ pub extern "system" fn XApuConnect( } let event = if input.options & RESULT_EVENT != 0 { // SAFETY: plain auto-reset event, no name. - let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; - if event.is_null() { - // SAFETY: allocated above with `layout`. - unsafe { std::alloc::dealloc(memory, layout) }; - return E_OUTOFMEMORY; - } - event + unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) } } else { std::ptr::null_mut() }; @@ -233,8 +196,6 @@ pub extern "system" fn XApuConnect( memory, layout, event, - process: input.process, - frames_per_output: input.frames_per_output, options: input.options, per_stream: input.commands_per_stream, state: Mutex::new(State { @@ -302,94 +263,36 @@ pub extern "system" fn XApuEnqueueCommand( input_length: 0, input: std::ptr::null(), }; - let stream_state = &mut state.streams[stream]; + let decoder = &mut state.streams[stream]; match id.kind { ACTIVATE => { // SAFETY: an activate command is this struct. - let activate = unsafe { command.cast::<Activate>().read_unaligned() }; - let channels = activate.channels as usize; - tracing::debug!( - stream, - channels, - process = connection.process, - "APU stream activated" - ); - if stream_state.is_some() { - result.error = ALREADY_ACTIVE; - } else if !(1..=2).contains(&channels) { - result.error = E_INVALIDARG; + let channels = unsafe { command.cast::<Activate>().read_unaligned() }.channels; + tracing::debug!(stream, channels, "Opus stream activated"); + result.error = if decoder.is_some() { + ALREADY_ACTIVE } else { - let decoder = match connection.process { - CONVERT_PCM => None, - _ => match OpusDecoder::new(48_000, channels) { - Ok(d) => Some(d), - Err(_) => { - result.error = E_INVALIDARG; - None - } - }, - }; - let resampler = match connection.process { - DECODE_OPUS => None, - _ => Some(Resampler::new(channels, activate.start_pitch)), - }; - if result.error == S_OK { - *stream_state = Some(Stream { - decoder, - resampler, - start_pitch: activate.start_pitch, - }); + match OpusDecoder::new(48_000, channels as usize) { + Ok(d) if (1..=2).contains(&channels) => { + *decoder = Some(d); + S_OK + } + _ => E_INVALIDARG, } - } + }; } - DEACTIVATE => *stream_state = None, + DEACTIVATE => *decoder = None, RESET => { - if let Some(stream) = stream_state { - let pitch = stream.start_pitch; - if let Some(d) = &mut stream.decoder { - let _ = d.reset_state(); - } - if let Some(r) = &mut stream.resampler { - r.reset(pitch); - } + if let Some(d) = decoder { + let _ = d.reset_state(); } } NOTIFY => {} PROCESS => { // SAFETY: a process command is this struct. let command = unsafe { command.cast::<Process>().read_unaligned() }; - match stream_state { - Some(stream) => { - match ( - connection.process, - &mut stream.decoder, - &mut stream.resampler, - ) { - (DECODE_OPUS, Some(d), _) => { - process(d, connection.options, &command, &mut result) - } - (DECODE_CONVERT_OPUS, Some(d), Some(r)) => process_convert( - Some(d), - r, - connection.frames_per_output, - connection.options, - &command, - &mut result, - ), - (CONVERT_PCM, _, Some(r)) => process_convert( - None, - r, - connection.frames_per_output, - connection.options, - &command, - &mut result, - ), - _ => result.error = INVALID_STREAM, - } - if let Some(r) = &stream.resampler { - result.pitch = r.pitch(); - } - } + match decoder { + Some(d) => process(d, connection.options, &command, &mut result), None => result.error = INVALID_STREAM, } } @@ -437,133 +340,17 @@ fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: & .min(command.frame_count as usize) .min(output_length as usize / (4 * channels)); let kept = &pcm[first * channels..(first + frames) * channels]; - // SAFETY: the title's output buffer holds `output_length` bytes, at - // least `frames * channels` samples. - let out = unsafe { std::slice::from_raw_parts_mut(output, frames * channels * 4) }; + // SAFETY: the title's output buffer holds `output_length` bytes. + let out = unsafe { std::slice::from_raw_parts_mut(output.cast::<f32>(), frames * channels) }; if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 { - let (left, right) = out.split_at_mut(frames * 4); - let pairs = kept.as_chunks::<2>().0; - put_samples(left, pairs.iter().map(|f| f[0])); - put_samples(right, pairs.iter().map(|f| f[1])); - } else { - put_samples(out, kept.iter().copied()); - } - result.frames = frames as u32; - result.output_length = (frames * channels * 4) as u32; -} - -/// Writes float samples to the title's output bytes. The title's buffer is a -/// `*mut u8` with no alignment promise, so it is never viewed as `[f32]`. -fn put_samples(out: &mut [u8], samples: impl Iterator<Item = f32>) { - for (dst, sample) in out.as_chunks_mut::<4>().0.iter_mut().zip(samples) { - *dst = sample.to_le_bytes(); - } -} - -/// Decodes (when the connection decodes) and resamples one command's input -/// into float PCM at the pitch the title asked for. -fn process_convert( - decoder: Option<&mut OpusDecoder>, - resampler: &mut Resampler, - max_frames: u32, - options: u32, - command: &Process, - result: &mut ApuResult, -) { - let channels = resampler.channels(); - let (input, input_length) = (command.input, command.input_length); - let (output, output_length) = (command.output, command.output_length); - result.input = input; - result.input_length = input_length; - result.output = output; - if input.is_null() || output.is_null() || input_length == 0 { - result.error = E_INVALIDARG; - return; - } - // SAFETY: the title's buffer in its connection memory. - let bytes = unsafe { std::slice::from_raw_parts(input, input_length as usize) }; - let pcm; - if let Some(decoder) = decoder { - let mut decoded = vec![0f32; MAX_FRAMES * channels]; - let n = match decoder.decode(bytes, MAX_FRAMES, &mut decoded) { - Ok(n) => n, - Err(_) => { - result.error = BAD_PACKET; - return; - } - }; - let first = (command.first_frame as usize).min(n); - let frames = (n - first).min(command.frame_count as usize); - pcm = decoded[first * channels..(first + frames) * channels].to_vec(); - } else { - // ConvertPCM's frameCount is required and fixes the input length. - let frames = command.frame_count as usize; - let minimum = if channels == 2 { 8 } else { 4 }; - let multiple = if channels == 2 { 8 } else { 4 }; - if frames < minimum - || frames > 960 - || !frames.is_multiple_of(multiple) - || input_length as usize != frames * channels * 4 - { - result.error = E_INVALIDARG; - return; + for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() { + (out[i], out[frames + i]) = (frame[0], frame[1]); } - let samples: Vec<f32> = bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - pcm = if options & DEINTERLEAVED_INPUT != 0 && channels == 2 { - let frames = samples.len() / 2; - let mut interleaved = vec![0f32; samples.len()]; - for (i, frame) in interleaved.as_chunks_mut::<2>().0.iter_mut().enumerate() { - *frame = [samples[i], samples[frames + i]]; - } - interleaved - } else { - samples - }; - } - let deinterleaved_output = options & DEINTERLEAVED_OUTPUT != 0 && channels == 2; - let mut room = output_length as usize / (4 * channels); - if deinterleaved_output { - // The right channel starts at the midpoint; more frames than that - // would write the left channel over it. - room = room.min(max_frames as usize); - } - let mut converted = vec![0f32; room * channels]; - let frames = resampler.convert( - &pcm, - &mut converted, - command.target_pitch, - command.pitch_ramp, - // FLUSH is a command option; `options` are the connection's. - { command.id.options } & FLUSH != 0, - ); - if deinterleaved_output { - // The converter's midpoint is `maxFrameCountPerOutput`, even when - // fewer frames were written (the docs spell this out). - let midpoint = max_frames as usize; - let len = midpoint + frames; - if len * 4 > output_length as usize { - result.error = E_INVALIDARG; - return; - } - // SAFETY: the title's output buffer holds `output_length` bytes. - let out = unsafe { std::slice::from_raw_parts_mut(output, len * 4) }; - let (left, right) = out.split_at_mut(midpoint * 4); - let pairs = converted[..frames * 2].as_chunks::<2>().0; - put_samples(left, pairs.iter().map(|f| f[0])); - put_samples(right, pairs.iter().map(|f| f[1])); } else { - // SAFETY: the title's output buffer holds `output_length` bytes. - let out = unsafe { std::slice::from_raw_parts_mut(output, frames * channels * 4) }; - put_samples(out, converted[..frames * channels].iter().copied()); + out.copy_from_slice(kept); } result.frames = frames as u32; result.output_length = (frames * channels * 4) as u32; - result.pitch = resampler.pitch(); } pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT { @@ -734,251 +521,4 @@ mod tests { assert_eq!(error, INVALID_STREAM); assert_eq!(XApuDisconnect(handle), S_OK); } - - fn connect(process: u32, frames: u32) -> (*mut Connection, *mut u8) { - connect_with(process, frames, 0) - } - - fn connect_with(process: u32, frames: u32, options: u32) -> (*mut Connection, *mut u8) { - let input = ConnectInput { - process, - streams: 1, - commands_per_stream: 2, - memory: 0x10_0000, - frames_per_output: frames, - options, - }; - let mut output = ConnectOutput { - memory: std::ptr::null_mut(), - result_event: std::ptr::null_mut(), - }; - let mut handle = std::ptr::null_mut(); - assert_eq!(XApuConnect(&input, &mut output, &mut handle), S_OK); - (handle, output.memory.cast::<u8>()) - } - - fn activate(handle: *mut Connection, channels: u32, pitch: f32) { - let command = Activate { - id: id(ACTIVATE, 0), - channels, - init_length: 0, - init: std::ptr::null(), - start_pitch: pitch, - processing_length: 0, - processing: std::ptr::null_mut(), - }; - assert_eq!( - XApuEnqueueCommand(handle, (&raw const command).cast(), std::ptr::null_mut()), - S_OK - ); - } - - #[test] - fn connects_for_both_conversion_kinds() { - let mut output = ConnectOutput { - memory: std::ptr::null_mut(), - result_event: std::ptr::null_mut(), - }; - let mut handle = std::ptr::null_mut(); - fn connect_as( - input: &ConnectInput, - output: &mut ConnectOutput, - handle: &mut *mut Connection, - ) -> HRESULT { - XApuConnect(input, output, handle) - } - let input = |process, frames| ConnectInput { - process, - streams: 1, - commands_per_stream: 1, - memory: 0x1_0000, - frames_per_output: frames, - options: 0, - }; - assert_eq!( - connect_as(&input(DECODE_OPUS, 0), &mut output, &mut handle), - S_OK - ); - assert_eq!(XApuDisconnect(handle), S_OK); - for frames in OUTPUT_FRAMES { - for process in [DECODE_CONVERT_OPUS, CONVERT_PCM] { - assert_eq!( - connect_as(&input(process, frames), &mut output, &mut handle), - S_OK - ); - assert_eq!(XApuDisconnect(handle), S_OK); - } - } - assert_eq!( - connect_as(&input(DECODE_OPUS, 256), &mut output, &mut handle), - E_INVALIDARG - ); - assert_eq!( - connect_as(&input(DECODE_CONVERT_OPUS, 0), &mut output, &mut handle), - E_INVALIDARG - ); - assert_eq!( - connect_as(&input(CONVERT_PCM, 7), &mut output, &mut handle), - E_INVALIDARG - ); - assert_eq!( - connect_as(&input(9, 256), &mut output, &mut handle), - E_NOTIMPL - ); - } - - #[test] - fn deinterleaved_output_stops_at_the_channel_midpoint() { - // A 256-frame midpoint, half pitch, and room for 1024 frames: the - // left channel must not run on over the right one. - let (handle, base) = connect_with(CONVERT_PCM, 256, DEINTERLEAVED_OUTPUT); - activate(handle, 2, 0.5); - let samples: Vec<f32> = (0..256) - .flat_map(|i| [i as f32, 1000.0 + i as f32]) - .collect(); - let bytes: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); - // SAFETY: inside the connection memory. - unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), base, bytes.len()) }; - let command = Process { - id: id(PROCESS, 0), - pitch_ramp: 0.0, - target_pitch: 0.5, - first_frame: 0, - frame_count: 256, - input_length: bytes.len() as u32, - input: base, - output_length: 1024 * 2 * 4, - output: base.wrapping_add(0x1000), - }; - assert_eq!( - XApuEnqueueCommand(handle, (&raw const command).cast(), std::ptr::null_mut()), - S_OK - ); - let mut result = std::mem::MaybeUninit::<ApuResult>::zeroed(); - assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); - assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); - // SAFETY: written above. - let result = unsafe { result.assume_init() }; - let (error, frames) = (result.error, result.frames); - assert_eq!((error, frames), (S_OK, 256)); - // SAFETY: the converter wrote both 256-float halves there. - let pcm = - unsafe { std::slice::from_raw_parts(base.wrapping_add(0x1000).cast::<f32>(), 512) }; - assert_eq!(pcm[..4], [0.0, 0.5, 1.0, 1.5]); - assert_eq!(pcm[255], 127.5); - assert_eq!(pcm[256..260], [1000.0, 1000.5, 1001.0, 1001.5]); - assert_eq!(pcm[511], 1127.5); - assert_eq!(XApuDisconnect(handle), S_OK); - } - - #[test] - fn converts_float_pcm_at_the_target_pitch() { - let (handle, base) = connect(CONVERT_PCM, 256); - activate(handle, 1, 1.0); - let samples: Vec<f32> = (0..16).map(|i| i as f32).collect(); - let bytes: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); - // SAFETY: inside the connection memory. - unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), base, bytes.len()) }; - let command = Process { - id: id(PROCESS, 0), - pitch_ramp: 0.0, - target_pitch: 2.0, - first_frame: 0, - frame_count: 16, - input_length: bytes.len() as u32, - input: base, - output_length: 256 * 4, - output: base.wrapping_add(0x1000), - }; - assert_eq!( - XApuEnqueueCommand(handle, (&raw const command).cast(), std::ptr::null_mut()), - S_OK - ); - let mut result = std::mem::MaybeUninit::<ApuResult>::zeroed(); - assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); - // SAFETY: written above. - let first = unsafe { result.assume_init() }; - let first_kind = first.id.kind; - assert_eq!(first_kind, ACTIVATE); - assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); - // SAFETY: written above. - let result = unsafe { result.assume_init() }; - let (error, frames, pitch, output_length) = ( - result.error, - result.frames, - result.pitch, - result.output_length, - ); - assert_eq!((error, frames, pitch, output_length), (S_OK, 8, 2.0, 8 * 4)); - // SAFETY: the converter wrote eight mono frames there. - let pcm = unsafe { std::slice::from_raw_parts(base.wrapping_add(0x1000).cast::<f32>(), 8) }; - assert_eq!(pcm, [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0]); - assert_eq!(XApuDisconnect(handle), S_OK); - } - - #[test] - fn decodes_and_converts_an_opus_stream() { - let (handle, base) = connect(DECODE_CONVERT_OPUS, 960); - activate(handle, 2, 1.0); - let tone: Vec<f32> = (0..960 * 2) - .map(|i| ((i / 2) as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5) - .collect(); - let mut encoder = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); - let mut packet = [0u8; 1500]; - let n = encoder.encode(&tone, 960, &mut packet).unwrap(); - // SAFETY: inside the connection memory. - unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) }; - let command = Process { - id: id(PROCESS, 0), - pitch_ramp: 0.0, - target_pitch: 0.5, - first_frame: 0, - frame_count: 960, - input_length: n as u32, - input: base, - output_length: 2048 * 2 * 4, - output: base.wrapping_add(0x1000), - }; - assert_eq!( - XApuEnqueueCommand(handle, (&raw const command).cast(), std::ptr::null_mut()), - S_OK - ); - let mut result = std::mem::MaybeUninit::<ApuResult>::zeroed(); - assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); - // SAFETY: written above. - let first = unsafe { result.assume_init() }; - let first_kind = first.id.kind; - assert_eq!(first_kind, ACTIVATE); - assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); - // SAFETY: written above. - let result = unsafe { result.assume_init() }; - let (error, frames, pitch, output_length) = ( - result.error, - result.frames, - result.pitch, - result.output_length, - ); - assert_eq!(error, S_OK); - assert!(frames > 960, "a half pitch writes more frames"); - assert_eq!(pitch, 0.5); - assert_eq!(output_length, frames * 2 * 4); - // SAFETY: the converter wrote `frames` stereo frames there. - let pcm = unsafe { - std::slice::from_raw_parts(base.wrapping_add(0x1000).cast::<f32>(), frames as usize * 2) - }; - let energy: f32 = pcm.iter().map(|s| s * s).sum::<f32>() / pcm.len() as f32; - assert!(energy > 0.01, "converted a tone, energy {energy}"); - assert_eq!(XApuDisconnect(handle), S_OK); - } - - #[test] - fn samples_go_to_an_unaligned_output_as_bytes() { - // One byte past a 4-byte boundary: a `[f32]` view there is UB. - let mut buf = [0u8; 13]; - put_samples(&mut buf[1..], [1.0f32, -2.0, 0.5].into_iter()); - assert_eq!(buf[0], 0); - assert_eq!(buf[1..5], 1.0f32.to_le_bytes()); - assert_eq!(buf[5..9], (-2.0f32).to_le_bytes()); - assert_eq!(buf[9..13], 0.5f32.to_le_bytes()); - } } diff --git a/crates/victory-hle/src/modules/apu_resample.rs b/crates/victory-hle/src/modules/apu_resample.rs deleted file mode 100644 index 2c30715f3e..0000000000 --- a/crates/victory-hle/src/modules/apu_resample.rs +++ /dev/null @@ -1,261 +0,0 @@ -//! The sample-rate converter of the console's audio unit (XAPU HSRC), kept -//! host-independent so its arithmetic is covered on every platform. -//! -//! The unit consumes Opus or float PCM at 48 kHz and writes float PCM. A -//! pitch of 1 leaves the rate unchanged; a pitch of 2 plays twice as fast -//! (half as many output frames), 0.5 twice as slowly. Frames left over at -//! the end of one command carry into the next, as they do on the hardware. - -// Linear interpolation between neighbouring samples. It is cheap and -// keeps the tone tests exact at whole-number pitches; a windowed-sinc -// filter would be quieter at large ratios but is not needed to fill the -// title's buffers with plausible audio. -pub(crate) struct Resampler { - channels: usize, - /// Interleaved input frames not yet consumed. - pending: Vec<f32>, - /// Position of the next output frame in `pending`, in frames. - position: f64, - pitch: f32, -} - -impl Resampler { - pub(crate) fn new(channels: usize, pitch: f32) -> Self { - Self { - channels, - pending: Vec::new(), - position: 0.0, - pitch: clamp(pitch), - } - } - - pub(crate) fn reset(&mut self, pitch: f32) { - self.pending.clear(); - self.position = 0.0; - self.pitch = clamp(pitch); - } - - pub(crate) fn pitch(&self) -> f32 { - self.pitch - } - - pub(crate) fn channels(&self) -> usize { - self.channels - } - - /// Converts `input` (interleaved frames) into `output`, returning the - /// number of frames written. `ramp` moves `pitch` towards `target` by - /// that much per frame. With `flush`, the last sample stands in for the - /// one after it so the remaining input can be written out. - pub(crate) fn convert( - &mut self, - input: &[f32], - output: &mut [f32], - target: f32, - ramp: f32, - flush: bool, - ) -> usize { - let channels = self.channels; - if channels == 0 || output.len() < channels { - return 0; - } - let target = clamp(target); - // Without a ramp the target pitch applies at once. - if ramp == 0.0 { - self.pitch = target; - } - self.pending.extend_from_slice(input); - let frames = output.len() / channels; - let mut written = 0; - while written < frames { - let available = self.pending.len() / channels; - let index = self.position as usize; - // One more sample is needed to interpolate; without it, stop - // unless the caller asked for the last partial frame. - if index >= available || (index + 1 >= available && !flush) { - break; - } - let fraction = (self.position - index as f64) as f32; - let (out, rest) = output[written * channels..].split_at_mut(channels); - for (channel, sample) in out.iter_mut().enumerate() { - let a = self.pending[index * channels + channel]; - let b = if index + 1 < available { - self.pending[(index + 1) * channels + channel] - } else { - a - }; - *sample = a + (b - a) * fraction; - } - let _ = rest; - written += 1; - self.position += f64::from(self.pitch); - self.pitch = step(self.pitch, target, ramp); - } - // Keep the unconsumed tail, including the sample the next call - // interpolates towards. - // The position can run past the buffered frames at high pitch; drain - // only what is buffered and carry the rest of the offset forward. - let consumed = (self.position as usize).min(self.pending.len() / channels); - if consumed > 0 { - self.pending.drain(..consumed * channels); - self.position -= consumed as f64; - } - written - } -} - -fn clamp(pitch: f32) -> f32 { - if pitch.is_finite() { - pitch.clamp(1.0 / 8.0, 8.0) - } else { - 1.0 - } -} - -/// Moves `from` towards `to` by at most `step`, without overshooting. -fn step(from: f32, to: f32, step: f32) -> f32 { - let difference = to - from; - if !step.is_finite() || step <= 0.0 { - return from; - } - if step >= difference.abs() { - to - } else { - from + step * difference.signum() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn run( - input: &[f32], - channels: usize, - pitch: f32, - room: usize, - ) -> (Vec<f32>, usize, Resampler) { - let mut resampler = Resampler::new(channels, pitch); - let mut output = vec![0.0; room * channels]; - let frames = resampler.convert(input, &mut output, pitch, 0.0, false); - output.truncate(frames * channels); - (output, frames, resampler) - } - - #[test] - fn unit_pitch_passes_samples_through() { - let input: Vec<f32> = (0..16).map(|i| i as f32).collect(); - let (output, frames, _) = run(&input, 1, 1.0, 64); - // The last sample needs a successor, so it waits for the next call. - assert_eq!(frames, 15); - assert_eq!(output, input[..15]); - } - - #[test] - fn half_pitch_doubles_the_frames_and_interpolates() { - let input = [0.0, 1.0]; - let (output, frames, _) = run(&input, 1, 0.5, 8); - assert_eq!(frames, 2); - assert!((output[0] - 0.0).abs() < 1e-6); - assert!((output[1] - 0.5).abs() < 1e-6); - } - - #[test] - fn double_pitch_halves_the_frames() { - let input: Vec<f32> = (0..9).map(|i| i as f32).collect(); - let (output, frames, _) = run(&input, 1, 2.0, 64); - assert_eq!(frames, 4); - assert_eq!(output, vec![0.0, 2.0, 4.0, 6.0]); - } - - #[test] - fn stereo_channels_stay_paired() { - let input = [0.0, 10.0, 1.0, 11.0, 2.0, 12.0]; - let (output, frames, _) = run(&input, 2, 1.0, 8); - assert_eq!(frames, 2); - assert_eq!(output, [0.0, 10.0, 1.0, 11.0]); - } - - #[test] - fn input_carries_across_commands() { - let mut resampler = Resampler::new(1, 1.0); - let mut output = [0.0; 8]; - assert_eq!( - resampler.convert(&[0.0, 1.0], &mut output, 1.0, 0.0, false), - 1 - ); - assert_eq!(output[0], 0.0); - // The 1 still waits for a successor; the next command supplies it. - assert_eq!(resampler.convert(&[2.0], &mut output, 1.0, 0.0, false), 1); - assert_eq!(output[0], 1.0); - assert_eq!(resampler.convert(&[3.0], &mut output, 1.0, 0.0, false), 1); - assert_eq!(output[0], 2.0); - } - - #[test] - fn flush_writes_the_last_partial_frame() { - let mut resampler = Resampler::new(1, 1.0); - let mut output = [0.0; 8]; - assert_eq!( - resampler.convert(&[0.0, 1.0], &mut output, 1.0, 0.0, true), - 2 - ); - assert_eq!(output[..2], [0.0, 1.0]); - } - - #[test] - fn a_pitch_past_the_buffered_input_does_not_panic() { - let mut resampler = Resampler::new(1, 3.0); - let input: Vec<f32> = (0..8).map(|i| i as f32).collect(); - let mut output = vec![0.0; 8]; - let frames = resampler.convert(&input, &mut output, 3.0, 0.0, false); - assert_eq!(output[..frames], [0.0, 3.0, 6.0]); - // The next frame is at position 9: one past the eight buffered. - let more: Vec<f32> = (8..12).map(|i| i as f32).collect(); - let frames = resampler.convert(&more, &mut output, 3.0, 0.0, false); - assert_eq!(output[..frames], [9.0]); - } - - #[test] - fn no_ramp_applies_the_target_pitch_at_once() { - let mut resampler = Resampler::new(1, 1.0); - let input: Vec<f32> = (0..16).map(|i| i as f32).collect(); - let mut output = vec![0.0; 32]; - let frames = resampler.convert(&input, &mut output, 2.0, 0.0, true); - assert_eq!( - output[..frames], - [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0] - ); - assert_eq!(resampler.pitch(), 2.0); - } - - #[test] - fn pitch_ramps_towards_the_target() { - let mut resampler = Resampler::new(1, 1.0); - assert_eq!(resampler.pitch(), 1.0); - let input: Vec<f32> = (0..16).map(|i| i as f32).collect(); - let mut output = vec![0.0; 32]; - resampler.convert(&input, &mut output, 2.0, 0.25, false); - assert_eq!(resampler.pitch(), 2.0, "eight frames of a quarter ramp"); - resampler.reset(8.0); - assert_eq!( - resampler.pitch(), - 8.0, - "pitch is bounded as the hardware is" - ); - resampler.reset(f32::NAN); - assert_eq!(resampler.pitch(), 1.0); - } - - #[test] - fn rejects_invalid_shapes() { - let mut resampler = Resampler::new(0, 1.0); - let mut output = [0.0; 8]; - assert_eq!(resampler.convert(&[1.0], &mut output, 1.0, 0.0, false), 0); - let mut resampler = Resampler::new(2, 1.0); - assert_eq!( - resampler.convert(&[1.0], &mut output[..1], 1.0, 0.0, false), - 0 - ); - } -} diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 46577adf41..5ce75518da 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -12,7 +12,7 @@ //! Mixed audio leaves through the host's WASAPI, which titles and //! middleware reach through COM like on PC. fmod's console build sets up //! the coprocessor inside `System_Create` and waits there for its first -//! command to be acknowledged; Grand Theft Auto VI uses only XMA contexts. +//! command to be acknowledged; the title uses only XMA contexts. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] @@ -114,6 +114,11 @@ fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> { heap.blocks .insert(ptr as usize, Block { size, apu, layout }); heap.by_apu.insert(apu, ptr as usize); + // The big ones are named in the log: they are the title's audio memory + // given out of our allocator, which the memory line counts as ours. + if size >= 32 << 20 { + tracing::info!(mb = size >> 20, at = ?ptr, "audio memory for the title from our allocator"); + } Some((ptr, apu)) } @@ -192,12 +197,7 @@ pub extern "system" fn ApuAlloc( align: u32, _flags: u32, ) -> HRESULT { - if out.is_null() - || size == 0 - || align < 4 - || !align.is_power_of_two() - || size.checked_add(align).is_none() - { + if out.is_null() || size == 0 || align < 4 || !align.is_power_of_two() { return E_INVALIDARG; } let Some((ptr, address)) = heap_alloc(size as usize, align as usize) else { @@ -218,16 +218,10 @@ pub extern "system" fn ApuFree(ptr: *mut c_void) { } pub extern "system" fn ApuMapVirtualAddress(ptr: *const c_void) -> u32 { - if ptr.is_null() { - return 0; - } heap_map(ptr as usize) } pub extern "system" fn ApuIsVirtualAddressValid(ptr: *const c_void, align: u32) -> bool { - if ptr.is_null() { - return false; - } let apu = heap_map(ptr as usize); apu != 0 && (align == 0 || apu.is_multiple_of(align)) } @@ -503,10 +497,9 @@ impl Xma { let start = Instant::now(); let mut active = 0; for index in 0..self.voices.len() as u32 { - if let (Some(context), Some(voice)) = ( - self.context(index), - &mut *lock(&self.voices[index as usize]), - ) { + if let (Some(context), Some(voice)) = + (self.context(index), &mut *lock(&self.voices[index as usize])) + { pump(context, voice); active += 1; } @@ -540,11 +533,7 @@ fn pump(context: Context, voice: &mut Voice) { voice.trace.produced += SAMPLES_PER_BLOCK / context.channels(); let write = (write + 1) % size; context.set_field(0, 27, 5, write); - // The read block is the title's: taken modulo the ring like the - // write block and `advance_read`'s. Compared as it is, one at or - // past the end would never be met, and a stream that loops would - // keep this voice (and its lock) filling forever. - if write == context.field(9, 0, 5) % size { + if write == context.field(9, 0, 5) { // Full: nothing more until the title advances its read block. context.set_field(1, 31, 1, 0); } @@ -619,25 +608,18 @@ fn decode(context: Context, voice: &mut Voice) -> bool { let ends_loop = loop_end != 0 && (frame.start == loop_end || (frame.start < loop_end && frame.next.is_none_or(|n| loop_end < n))); - let looping = loops > 0 && ends_loop; - if looping { + if loops > 0 && ends_loop { let keep = (context.field(1, 12, 2) as usize + 1) * xma::SUBFRAME_SAMPLES * channels; pcm.truncate(keep); next = context.field(3, 0, 26) as usize; + voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES; if loops != 255 { context.set_field(0, 12, 8, loops - 1); } } - // What is still to skip is this frame's (the stream's first, or a - // loop's first when it is its last too). let skip = (voice.skip * channels).min(pcm.len()); voice.skip -= skip / channels; voice.pcm.extend(&pcm[skip..]); - if looping { - // The loop's own skip is of its first frame, decoded next: not of - // this one, its last. - voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES; - } if next == 0 { context.set_field(0, 20 + current, 1, 0); } @@ -666,10 +648,7 @@ fn dump_input(index: u32, context: Context) { ); let _ = std::fs::create_dir_all(&dir); let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words); - let _ = std::fs::write( - dir.join(format!("{n:02}-{index}.xma")), - input.unwrap_or_default(), - ); + let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default()); } /// Starts the decoding thread on the first enabled voice, and has it fill @@ -955,9 +934,6 @@ mod tests { assert_eq!(heap_unmap(apu + 4), Some(ptr.cast::<u8>().wrapping_add(4))); ApuFree(ptr); assert_eq!(ApuMapVirtualAddress(ptr), 0); - assert!(!ApuIsVirtualAddressValid(std::ptr::null(), 0)); - assert_eq!(ApuMapVirtualAddress(std::ptr::null()), 0); - assert_eq!(ApuAlloc(&mut ptr, &mut apu, u32::MAX, 128, 1), E_INVALIDARG); assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 6, 1), E_INVALIDARG); } @@ -1024,86 +1000,6 @@ mod tests { data } - /// A read block past the end of the ring (6 on a ring of four) is block - /// 2 of it: a stream that loops forever fills blocks 0 and 1 and the - /// pass ends. It used to fill the ring for good, holding the voice. - #[test] - fn xma_read_blocks_past_the_ring_end_wrap() { - let _serial = lock(&CONTEXT_TESTS); - let mut request = ShapeContexts { - counts: [0, 0, 0, 0, 4, 0], - arrays: [std::ptr::null_mut(); 6], - apu: [0; 6], - }; - assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK); - let context = Context(request.arrays[4].cast::<u32>().wrapping_add(16)); - let (mut input, mut input_apu) = (std::ptr::null_mut(), 0); - assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK); - let stream = silent_stream(); - // SAFETY: two packets were allocated. - unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) }; - let (mut output, mut output_apu) = (std::ptr::null_mut(), 0); - assert_eq!( - ApuAlloc(&mut output, &mut output_apu, 0x400, 0x100, 2), - S_OK - ); - // SAFETY: the ring was just allocated. - unsafe { output.cast::<u8>().write_bytes(0x55, 0x400) }; - - // As in `xma_contexts_decode_into_their_output_rings`, but looping - // forever from the first frame to the last, and read block 6. - context.set(0, 2 | 255 << 12 | 1 << 20 | 4 << 22); - context.set(1, 1 << 31 | 3 << 27); - context.set(2, 32); - context.set(3, 32); - context.set(4, (xma::PACKET_BYTES * 8 + 32 + 2 * 31) as u32); - context.set(5, input_apu); - context.set(7, output_apu); - context.set(9, 6); - - let mut acp = std::ptr::null_mut(); - assert_eq!(AcpHalCreate(&mut acp), S_OK); - // SAFETY: just created. - let m = unsafe { (*acp).vtable }; - assert_eq!((m.connect)(acp, 0x1000, 0x1000), S_OK); - let submit = |command: u32, words: &[u32]| { - assert_eq!( - (m.submit)(acp, command, 0xf1, u32::MAX, words.as_ptr().cast(), 0), - S_OK - ); - }; - submit(ENABLE_XMA, &[1]); - // A pass on a thread of its own (the decoding thread runs them too), - // so that one that never ends fails this test instead of hanging it. - let (done, passed) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - xma().pump(); - let _ = done.send(()); - }); - let five = std::time::Duration::from_secs(5); - let wait = || passed.recv_timeout(five).is_ok(); - let ended = wait(); - if !ended { - // End it as a full ring would, to release the contexts below. - context.set_field(1, 31, 1, 0); - assert!(wait(), "the XMA pass did not end on a full ring either"); - } - let (write, writable) = (context.field(0, 27, 5), context.field(1, 31, 1)); - // SAFETY: the ring. - let ring = unsafe { std::slice::from_raw_parts(output.cast::<u8>(), 0x400) }.to_vec(); - - submit(DISABLE_XMA, &[1]); - (m.release)(acp); - ApuFree(input); - ApuFree(output); - assert_eq!(AcpHalReleaseShapeContexts(), S_OK); - assert!(ended, "the XMA pass never ended"); - // Blocks 0 and 1 written (silence), 2 and 3 left for the title. - assert_eq!((write, writable), (2, 0)); - assert!(ring[..0x200].iter().all(|&b| b == 0)); - assert!(ring[0x200..].iter().all(|&b| b == 0x55)); - } - #[test] fn xma_contexts_decode_into_their_output_rings() { let _serial = lock(&CONTEXT_TESTS); @@ -1187,69 +1083,6 @@ mod tests { assert_eq!(AcpHalReleaseShapeContexts(), S_OK); } - /// A loop over the first two frames, which ends after the second - /// frame's second subframe and starts two subframes into the first. - /// Each end of the loop is cut in its own frame. - #[test] - fn a_loop_skips_subframes_of_its_first_frame() { - let _serial = lock(&CONTEXT_TESTS); - let (mut input, mut input_apu) = (std::ptr::null_mut(), 0); - assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK); - let stream = silent_stream(); - // SAFETY: two packets were allocated. - unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) }; - - // Frames start at bits 32, 63 and 94 of each packet. - let (first, second, third) = (32, 63, 94); - let (end_subframe, skip_subframes) = (1, 2); - let mut words = [0u32; 16]; - let context = Context(words.as_mut_ptr()); - // Two packets, one loop, input 0 valid; 48 kHz mono. - context.set(0, 2 | 1 << 12 | 1 << 20 | 4 << 22); - context.set( - 1, - 1 << 31 | 3 << 27 | end_subframe << 12 | skip_subframes << 17, - ); - context.set(2, first); - context.set(3, first); - context.set(4, second); - context.set(5, input_apu); - let mut voice = Voice { - decoder: None, - pcm: VecDeque::new(), - skip: 0, - ended: false, - trace: Trace { - since: Instant::now(), - produced: 0, - taken: 0, - takes: 0, - partial_takes: 0, - frames: 0, - bad_frames: 0, - peak: 0, - ended_ms: None, - }, - }; - let mut step = |expect_next: u32| { - let before = voice.pcm.len(); - assert!(decode(context, &mut voice)); - assert_eq!(context.field(2, 0, 26), expect_next); - voice.pcm.len() - before - }; - let subframe = xma::SUBFRAME_SAMPLES; - // Before the loop: the first frame whole. - assert_eq!(step(second), 4 * subframe); - // The loop's last frame: its first two subframes, then back. - assert_eq!(step(first), 2 * subframe, "the loop's last frame"); - assert_eq!(context.field(0, 12, 8), 0, "one loop, taken"); - // The loop's first frame again: without its first two subframes. - assert_eq!(step(second), 2 * subframe, "the loop's first frame"); - // No loops left: both frames whole, and on to the third. - assert_eq!(step(third), 4 * subframe); - ApuFree(input); - } - #[test] fn full_message_queues_count_drops() { let mut acp = std::ptr::null_mut(); diff --git a/crates/victory-hle/src/modules/audio/capture.rs b/crates/victory-hle/src/modules/audio/capture.rs index b1de613877..f39bb3daec 100644 --- a/crates/victory-hle/src/modules/audio/capture.rs +++ b/crates/victory-hle/src/modules/audio/capture.rs @@ -12,7 +12,6 @@ use std::io::{Seek, SeekFrom, Write}; use std::path::Path; use std::time::{Duration, Instant}; -use windows::Win32::Foundation::WAIT_OBJECT_0; use windows::Win32::Media::Audio::{ AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK, @@ -24,6 +23,7 @@ use windows::Win32::Media::Audio::{ VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVE_FORMAT_PCM, WAVEFORMATEX, }; use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx}; +use windows::Win32::Foundation::WAIT_OBJECT_0; use windows::Win32::System::Threading::{ OpenProcess, PROCESS_SYNCHRONIZE, Sleep, WaitForSingleObject, }; @@ -93,10 +93,7 @@ pub fn child() -> bool { } fn header(frames: u64) -> [u8; 44] { - const MAX_DATA_BYTES: u32 = (u32::MAX - 36) & !(FRAME_BYTES as u32 - 1); - let data = frames - .saturating_mul(FRAME_BYTES as u64) - .min(u64::from(MAX_DATA_BYTES)) as u32; + let data = u32::try_from(frames * FRAME_BYTES as u64).unwrap_or(u32::MAX - 36); let mut h = [0u8; 44]; let fields: [(&[u8], usize); 11] = [ (b"RIFF", 0), @@ -118,36 +115,6 @@ fn header(frames: u64) -> [u8; 44] { h } -fn silence_frames(written: u64, first: &mut Option<u64>, qpc: u64, flags: u32) -> u64 { - if flags & windows::Win32::Media::Audio::AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR.0 as u32 != 0 { - return 0; - } - let start = *first.get_or_insert_with(|| { - let offset = - u64::try_from(u128::from(written) * 10_000_000 / u128::from(RATE)).unwrap_or(u64::MAX); - qpc.saturating_sub(offset) - }); - let Some(elapsed) = qpc.checked_sub(start) else { - return 0; - }; - let at = (u128::from(elapsed) * u128::from(RATE) / 10_000_000) as u64; - if at > written.saturating_add(u64::from(RATE / 500)) { - at - written - } else { - 0 - } -} - -fn write_zeros(writer: &mut impl std::io::Write, mut bytes: u64) -> std::io::Result<()> { - static ZEROS: [u8; 16 * 1024] = [0; 16 * 1024]; - while bytes > 0 { - let chunk = bytes.min(ZEROS.len() as u64) as usize; - writer.write_all(&ZEROS[..chunk])?; - bytes -= chunk as u64; - } - Ok(()) -} - fn record(pid: u32, path: &Path) -> Result<(), Box<dyn std::error::Error>> { // SAFETY: COM calls with parameters built here; buffers are used only // between `GetBuffer` and `ReleaseBuffer`. @@ -225,30 +192,26 @@ fn record(pid: u32, path: &Path) -> Result<(), Box<dyn std::error::Error>> { let (mut data, mut frames, mut flags, mut qpc) = (std::ptr::null_mut(), 0, 0, 0); capture.GetBuffer(&mut data, &mut frames, &mut flags, None, Some(&mut qpc))?; // Where this packet belongs, from its time stamp (100 ns). - let silence = silence_frames(written, &mut first, qpc, flags); - if silence > 0 { + let at = (qpc - *first.get_or_insert(qpc)) * u64::from(RATE) / 10_000_000; + if at > written + u64::from(RATE / 500) { tracing::debug!( - ms = (u128::from(silence) * 1000 / u128::from(RATE)) as u64, + ms = (at - written) * 1000 / u64::from(RATE), "audio capture: nothing played" ); - write_zeros(&mut file, silence.saturating_mul(FRAME_BYTES as u64))?; - written = written.saturating_add(silence); + let silence = vec![0u8; (at - written) as usize * FRAME_BYTES]; + file.write_all(&silence)?; + written = at; } - let bytes = u64::from(frames) * FRAME_BYTES as u64; - let packet_frames = if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 { - write_zeros(&mut file, bytes)?; - u64::from(frames) - } else if bytes > 0 && !data.is_null() { - let len = usize::try_from(bytes)?; - file.write_all(std::slice::from_raw_parts(data, len))?; - u64::from(frames) + let bytes = frames as usize * FRAME_BYTES; + if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 { + file.write_all(&vec![0u8; bytes])?; } else { - 0 - }; + file.write_all(std::slice::from_raw_parts(data, bytes))?; + } if flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY.0 as u32 != 0 && written > 0 { tracing::debug!("audio capture: discontinuity"); } - written = written.saturating_add(packet_frames); + written += u64::from(frames); capture.ReleaseBuffer(frames)?; } if ended || patched.elapsed() >= Duration::from_secs(1) { @@ -264,64 +227,3 @@ fn record(pid: u32, path: &Path) -> Result<(), Box<dyn std::error::Error>> { } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn header_caps_riff_size_without_overflow_and_stays_frame_aligned() { - for frames in [1_073_741_820, u64::MAX] { - let h = header(frames); - let riff_size = u32::from_le_bytes(h[4..8].try_into().unwrap()); - let data_size = u32::from_le_bytes(h[40..44].try_into().unwrap()); - assert_eq!(data_size, 4_294_967_256); - assert_eq!(data_size % 4, 0); - assert_eq!(riff_size, 36 + data_size); - } - - let normal = header(480); - let riff_size = u32::from_le_bytes(normal[4..8].try_into().unwrap()); - let data_size = u32::from_le_bytes(normal[40..44].try_into().unwrap()); - assert_eq!(data_size, 1_920); - assert_eq!(riff_size, 1_956); - } - - #[test] - fn timestamp_errors_and_backwards_qpc_do_not_underflow_or_anchor_zero() { - let ts_err = windows::Win32::Media::Audio::AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR.0 as u32; - let mut first = None; - - assert_eq!(silence_frames(0, &mut first, 0, ts_err), 0); - assert_eq!(first, None); - - assert_eq!(silence_frames(480, &mut first, 50_000_000, 0), 0); - assert_eq!(first, Some(49_900_000)); - - assert_eq!(silence_frames(480, &mut first, 10_000_000, 0), 0); - assert_eq!(silence_frames(480, &mut first, 90_000_000, ts_err), 0); - assert_eq!(first, Some(49_900_000)); - - assert_eq!(silence_frames(960, &mut first, 49_900_000 + 220_000, 0), 0); - assert_eq!( - silence_frames(960, &mut first, 49_900_000 + 10_000_000, 0), - 48_000 - 960 - ); - - let mut max_first = Some(0); - let expected = ((u128::from(u64::MAX) * u128::from(RATE)) / 10_000_000) as u64; - assert_eq!(silence_frames(0, &mut max_first, u64::MAX, 0), expected); - } - - #[test] - fn write_zeros_streams_exact_byte_count() { - let mut buf = Vec::new(); - write_zeros(&mut buf, 40_000).unwrap(); - assert_eq!(buf.len(), 40_000); - assert!(buf.iter().all(|&b| b == 0)); - - let mut empty = Vec::new(); - write_zeros(&mut empty, 0).unwrap(); - assert!(empty.is_empty()); - } -} diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 23bbccf5c7..e0198e3d74 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -36,6 +36,19 @@ fn host_gpu_failed(what: &str) -> ! { unreachable!("the process has ended") } +/// The offline warm-up: see `victory_gpu::shader_cache::warm`. +pub fn warm_shader(container: &[u8]) -> Result<bool, String> { + #[cfg(windows)] + { + victory_gpu::shader_cache::warm(container) + } + #[cfg(not(windows))] + { + let _ = container; + Err("no shader cache on this host".into()) + } +} + /// Keeps the host's translations of the title's shaders in `dir` (a /// folder of the cache) across runs, and its compiled pipelines beside it /// (`pipelines`). @@ -49,6 +62,58 @@ pub fn use_shader_cache(dir: std::path::PathBuf) { let _ = dir; } +/// `victory prepare`: the container's translation put in the shader cache +/// [`use_shader_cache`] opened, as a run on this PC makes it. Whether it +/// translates. +#[cfg(windows)] +pub fn prepare_shader(container: &[u8]) -> bool { + victory_gpu::shader_cache::prepare(container) +} + +/// Off Windows nothing runs: no translation is kept. +#[cfg(not(windows))] +pub fn prepare_shader(_container: &[u8]) -> bool { + false +} + +/// `victory prepare`: makes the host pipeline of every recipe earlier runs +/// kept (each pipeline a draw or dispatch asked for) into the pipeline +/// library [`use_shader_cache`] opened, on `threads` workers; `say` gets a +/// progress line every 15 s and a last one. Whether there were recipes. +#[cfg(windows)] +pub fn prepare_pipelines(threads: usize, say: &(dyn Fn(String) + Sync)) -> bool { + let line = |p: &victory_gpu::pipeline::Prepared, last: bool| { + say(format!( + "{} {} of {} pipelines ready ({} already in the library, {} compiled now), {} cannot be made", + if last { "prepared " } else { "preparing " }, + p.loaded + p.made, + p.usable, + p.loaded, + p.made, + p.failed + )); + }; + victory_gpu::pipeline::prepare_recipes(threads, &line).recipes > 0 +} + +/// Off Windows nothing runs: there are no recipes. +#[cfg(not(windows))] +pub fn prepare_pipelines(_threads: usize, _say: &(dyn Fn(String) + Sync)) -> bool { + false +} + +/// Translations found in the shader cache and made, since the start. +#[cfg(windows)] +pub fn prepared_shader_counts() -> (u64, u64) { + victory_gpu::shader_cache::prepared_counts() +} + +/// Off Windows nothing runs. +#[cfg(not(windows))] +pub fn prepared_shader_counts() -> (u64, u64) { + (0, 0) +} + pub(crate) fn module() -> HleModule { HleModule { name: "d3d12x", diff --git a/crates/victory-hle/src/modules/display.rs b/crates/victory-hle/src/modules/display.rs index 510c3e52c7..fd13187a92 100644 --- a/crates/victory-hle/src/modules/display.rs +++ b/crates/victory-hle/src/modules/display.rs @@ -36,7 +36,7 @@ pub const CAPTURE_PROVIDER: Guid = Guid::new( 0x4485, [0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27], ); -/// As Grand Theft Auto VI (2026) asks for it; it calls 0x28 (take a +/// As the title (2026) asks for it; it calls 0x28 (take a /// screenshot) with the public API's arguments. pub const CAPTURE_IID_2026: Guid = Guid::new( 0x22e6_72d7, @@ -57,39 +57,11 @@ pub const INTERFACES: &[Interface] = &[ type This = *const Object; -/// `XDisplayHdrModeInfo` (nits). -#[repr(C)] -#[derive(Debug, Clone, Copy, Default)] -struct HdrModeInfo { - min_tone_map_luminance: f32, - max_tone_map_luminance: f32, - max_full_frame_tone_map_luminance: f32, -} - -/// `XDisplayTryEnableHdrMode`: enables HDR (`1`) and fills the host display's -/// luminance bounds when Windows HDR is active; otherwise returns disabled (`2`). -extern "system" fn try_enable_hdr(_: This, preference: u32, info: *mut c_void) -> u32 { - #[cfg(windows)] - if let Some(hdr) = victory_gpu::display_hdr_info() { - if !info.is_null() { - // SAFETY: caller passed a writable `XDisplayHdrModeInfo` pointer. - unsafe { - info.cast::<HdrModeInfo>().write_unaligned(HdrModeInfo { - min_tone_map_luminance: hdr.min_luminance, - max_tone_map_luminance: hdr.max_luminance, - max_full_frame_tone_map_luminance: hdr.max_full_frame_luminance, - }); - } - } - tracing::info!( - preference, - min = hdr.min_luminance, - max = hdr.max_luminance, - max_ff = hdr.max_full_frame_luminance, - "HDR mode: enabled" - ); - return 1; - } +/// 2: disabled. We present in SDR, so the title must render SDR. +// shortcut: HDR output is not done (see the presentation items in +// `TODO.md`); report enabled, with the host display's luminance, once the +// swap chain can present HDR. +extern "system" fn try_enable_hdr(_: This, preference: u32, _info: *mut c_void) -> u32 { tracing::info!(preference, "HDR mode: disabled (SDR presentation)"); 2 } @@ -122,40 +94,24 @@ extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT { context.Reason.SimpleReasonString = reason.as_mut_ptr(); // SAFETY: a valid context; the string is copied by the call. let request = unsafe { PowerCreateRequest(&context) }; - if request.is_null() || request as isize == -1 { + if request as isize == -1 { return last_error(); } // SAFETY: the request we just created. if unsafe { PowerSetRequest(request, PowerRequestDisplayRequired) } == 0 { - // SAFETY: no preconditions. - let code = unsafe { windows_sys::Win32::Foundation::GetLastError() }; - if let Some(hr) = refused_request(code) { - // SAFETY: as above; not handed out. - unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; - return hr; - } - tracing::info!("display deferral: the system holds no display power here (no-op)"); + let hr = last_error(); + // SAFETY: as above; not handed out. + unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; + return hr; } put(out, request) } -/// What a refused display-required request means for the title: `None` -/// where the deferral still stands, else its error. A system with no -/// display power to hold (headless, Remote Desktop, some laptops without an -/// active display route) answers `ERROR_NOT_SUPPORTED`; the deferral is a -/// power hint, so it succeeds there (upstream #727: the title's acquire -/// failed with 0x80070032). Closing the request is unchanged. -#[cfg(windows)] -fn refused_request(code: u32) -> Option<HRESULT> { - const ERROR_NOT_SUPPORTED: u32 = 50; - (code != ERROR_NOT_SUPPORTED).then(|| hresult_from_win32(code)) -} - #[cfg(windows)] extern "system" fn close_deferral(_: This, handle: *mut c_void) { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Power::{PowerClearRequest, PowerRequestDisplayRequired}; - if !handle.is_null() && handle as isize != -1 { + if !handle.is_null() { // SAFETY: a request from `acquire_deferral`. unsafe { PowerClearRequest(handle, PowerRequestDisplayRequired); @@ -167,11 +123,7 @@ extern "system" fn close_deferral(_: This, handle: *mut c_void) { #[cfg(windows)] fn last_error() -> HRESULT { // SAFETY: no preconditions. - hresult_from_win32(unsafe { windows_sys::Win32::Foundation::GetLastError() }) -} - -#[cfg(windows)] -fn hresult_from_win32(code: u32) -> HRESULT { + let code = unsafe { windows_sys::Win32::Foundation::GetLastError() }; (0x8007_0000 | (code & 0xffff)) as i32 } @@ -224,22 +176,12 @@ mod tests { use crate::modules::xgameruntime::{S_OK, method}; #[test] - fn hdr_and_display_deferrals() { + fn sdr_and_display_deferrals() { type Hdr = extern "system" fn(This, u32, *mut c_void) -> u32; - let mut info = HdrModeInfo::default(); - let res = method::<Hdr>(&HDR_OBJECT, 0x20)(&HDR_OBJECT, 0, (&raw mut info).cast()); - if let Some(hdr) = victory_gpu::display_hdr_info() { - assert_eq!(res, 1); - assert_eq!(info.min_tone_map_luminance, hdr.min_luminance); - assert_eq!(info.max_tone_map_luminance, hdr.max_luminance); - assert_eq!( - info.max_full_frame_tone_map_luminance, - hdr.max_full_frame_luminance - ); - assert!(info.max_tone_map_luminance > 0.0); - } else { - assert_eq!(res, 2); - } + assert_eq!( + method::<Hdr>(&HDR_OBJECT, 0x20)(&HDR_OBJECT, 0, std::ptr::null_mut()), + 2 + ); type Acquire = extern "system" fn(This, *mut *mut c_void) -> HRESULT; type Close = extern "system" fn(This, *mut c_void); let mut handle = std::ptr::null_mut(); @@ -250,27 +192,4 @@ mod tests { assert!(!handle.is_null()); method::<Close>(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, handle); } - - #[test] - fn a_system_without_display_power_keeps_the_deferral() { - assert_eq!(refused_request(50), None); - assert_eq!(refused_request(5), Some(0x8007_0005_u32 as HRESULT)); - assert_eq!(refused_request(87), Some(0x8007_0057_u32 as HRESULT)); - } - - #[test] - fn acquire_deferral_rejects_null_out() { - type Acquire = extern "system" fn(This, *mut *mut c_void) -> HRESULT; - assert_eq!( - method::<Acquire>(&SHELL_OBJECT, 0x20)(&SHELL_OBJECT, std::ptr::null_mut()), - super::super::xasync::E_INVALIDARG - ); - } - - #[test] - fn close_deferral_handles_null_and_invalid() { - type Close = extern "system" fn(This, *mut c_void); - method::<Close>(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, std::ptr::null_mut()); - method::<Close>(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, (-1isize) as *mut c_void); - } } diff --git a/crates/victory-hle/src/modules/dsp.rs b/crates/victory-hle/src/modules/dsp.rs index 2e6737f5cb..87c456aed3 100644 --- a/crates/victory-hle/src/modules/dsp.rs +++ b/crates/victory-hle/src/modules/dsp.rs @@ -9,33 +9,27 @@ //! the title checks it one block later and treats a late command as an //! overrun. Commands complete when submitted here. //! -//! Convolution runs on the host with the console's partitioned -//! frequency-domain impulse responses (see [`super::dsp_convolve`]), so -//! reverb returns are wet. The FFT and IFFT stream transforms remain silent: -//! their inputs and outputs are spectra, not audio a title can play. +//! The transforms themselves are not computed: the hardware takes impulse +//! responses already in its own partitioned frequency-domain layout, which +//! is not known. Outputs are silence, so reverb returns are dry. +// shortcut: no convolution or block transform; outputs are zeros. Needs the +// coprocessor's impulse response and spectrum layouts to do better. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::c_void; use std::sync::Mutex; -use super::dsp_convolve::Convolver; use super::xasync::E_INVALIDARG; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleModule, hle_export}; const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; -/// XDSP_E_NO_DEVICE_RESOURCES: the connection's stream limit is used up. -const NO_DEVICE_RESOURCES: HRESULT = 0x8AC8_10A2_u32 as i32; -/// XDSP_E_NOT_ALL_HANDLES_DEACTIVATED: disconnect with streams still active. -const NOT_ALL_HANDLES_DEACTIVATED: HRESULT = 0x8AC8_10A4_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; const CONVOLUTION: u32 = 1; -/// XDspActivationOptions: a per-channel IR and deinterleaved blocks both -/// need a stereo stream; polar format is for FFT/IFFT only. -const DEINTERLEAVED: u32 = 2; -const STEREO_IR: u32 = 8; -const STEREO_OPTIONS: u32 = STEREO_IR | DEINTERLEAVED; +/// Option bits that need a stereo stream, and one convolution refuses. +const STEREO_OPTIONS: u32 = 2 | 8; const NOT_FOR_CONVOLUTION: u32 = 4; pub struct Dsp { @@ -68,9 +62,6 @@ pub struct Stream { frames: u32, channels: u32, status: Box<Status>, - /// `None` for the FFT/IFFT transforms, which we do not compute. - convolver: Option<Convolver>, - deinterleaved: bool, } /// One block of work. @@ -117,21 +108,12 @@ pub extern "system" fn XDspConnectWithMaximumStreamLimit( S_OK } -/// Refuses while streams are active, as the GDK documents, since each one -/// points at the connection. The client is kept, so the title can -/// deactivate them and disconnect again. pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT { if dsp.is_null() { return E_INVALIDARG; } - // SAFETY: made by `XDspConnectWithMaximumStreamLimit`, not disconnected. - let connection = unsafe { &*dsp }; - if *connection.active.lock().unwrap_or_else(|e| e.into_inner()) != 0 { - return NOT_ALL_HANDLES_DEACTIVATED; - } - // Checked under the lock but freed after it: the title finishes its - // XDspActivate and XDspDeactivate calls on this connection before this. - // SAFETY: as above, and no stream points at it any more; disconnected once. + // SAFETY: made by `XDspConnectWithMaximumStreamLimit`; disconnected + // once, after its streams. drop(unsafe { Box::from_raw(dsp) }); S_OK } @@ -142,9 +124,6 @@ fn valid(desc: &StreamDesc) -> bool { (1..=2).contains(&channels) && matches!(frames, 0x200 | 0x400) && options & NOT_FOR_CONVOLUTION == 0 - // The console's IR is complex pairs, one filter block at least. - && !desc.ir.is_null() - && desc.ir_floats >= 2 * frames } else { channels == 1 && matches!(frames, 0x200 | 0x400 | 0x800) }; @@ -176,35 +155,12 @@ pub extern "system" fn XDspActivate( channels, "audio DSP stream activated" ); - let convolver = if kind == CONVOLUTION { - // `ir_floats` is one channel's length; a stereo IR holds one per channel. - let stereo_ir = options & STEREO_IR != 0; - let len = desc.ir_floats as usize * if stereo_ir { channels as usize } else { 1 }; - // SAFETY: `valid` checked the pointer; the title's IR holds `ir_floats` - // floats per IR channel and stays alive in title memory for the - // stream's lifetime (the console copies it here). - let ir = unsafe { std::slice::from_raw_parts(desc.ir, len) }; - match Convolver::new( - ir, - desc.ir_floats as usize, - frames as usize, - channels as usize, - stereo_ir, - ) { - Some(convolver) => Some(convolver), - None => return E_INVALIDARG, - } - } else { - None - }; - // Reserve the stream only once it can be made, so a refused activation - // does not hold a slot. { // SAFETY: a connection from `XDspConnectWithMaximumStreamLimit`. let dsp = unsafe { &*dsp }; let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner()); if *active >= dsp.max_streams { - return NO_DEVICE_RESOURCES; + return E_OUTOFMEMORY; } *active += 1; } @@ -218,8 +174,6 @@ pub extern "system" fn XDspActivate( reserved: 0, result: S_OK, }), - convolver, - deinterleaved: options & DEINTERLEAVED != 0, }); // SAFETY: checked non-null. unsafe { @@ -235,14 +189,13 @@ pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT { } // SAFETY: made by `XDspActivate`; deactivated once. let stream = unsafe { Box::from_raw(stream) }; - // SAFETY: `XDspDisconnect` keeps the connection while this is active. + // SAFETY: the connection outlives its streams. let dsp = unsafe { &*stream.dsp }; *dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1; S_OK } -/// Completes the command at once. Convolution writes wet output; the FFT -/// and IFFT transforms still return silence. +/// Completes the command at once: its output block is silence. pub extern "system" fn XDspSubmitCommand( stream: *mut Stream, command: *const Command, @@ -255,29 +208,8 @@ pub extern "system" fn XDspSubmitCommand( let (stream, command) = unsafe { (&mut *stream, &*command) }; if !command.output.is_null() { let samples = (stream.frames * stream.channels) as usize; - let mut written = false; - if let Some(convolver) = &mut stream.convolver - && !command.input.is_null() - { - // SAFETY: the title's input and output buffers hold one block. - let (input, output) = unsafe { - ( - std::slice::from_raw_parts(command.input, samples), - std::slice::from_raw_parts_mut(command.output, samples), - ) - }; - written = convolver.process( - input, - output, - command.gains, - stream.deinterleaved, - stream.deinterleaved, - ); - } - if !written { - // SAFETY: the title's output buffer holds one block. - unsafe { std::ptr::write_bytes(command.output, 0, samples) }; - } + // SAFETY: the title's output buffer holds one block of the stream. + unsafe { std::ptr::write_bytes(command.output, 0, samples) }; } let status = &mut *stream.status; let next = status.submitted.wrapping_add(1); @@ -379,187 +311,4 @@ mod tests { assert_eq!(XDspDeactivate(stream), S_OK); assert_eq!(XDspDisconnect(dsp), S_OK); } - - #[test] - fn a_stereo_ir_activates_and_frees_its_slot() { - const BLOCK: usize = 0x200; - let mut base = vec![0u8; 0x10_0000]; - let mut dsp = std::ptr::null_mut(); - assert_eq!( - XDspConnectWithMaximumStreamLimit( - base.as_mut_ptr().cast(), - 0x10_0000, - 24, - 1, - 2, - &mut dsp - ), - S_OK - ); - // One unity impulse per channel; `ir_floats` is one channel's length. - let mut time = vec![0f32; BLOCK]; - time[0] = 1.0; - let left = crate::modules::dsp_convolve::encode_ir(&time, BLOCK); - let mut ir = left.clone(); - ir.extend_from_slice(&left); - let desc = StreamDesc { - kind: CONVOLUTION, - options: STEREO_IR, - frames: BLOCK as u32, - channels: 2, - ir_floats: left.len() as u32, - ir: ir.as_ptr(), - }; - let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut()); - assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK); - let input = vec![0.75f32; BLOCK * 2]; - let mut output = vec![0f32; BLOCK * 2]; - let command = Command { - gains: [1.0, 1.0], - input: input.as_ptr(), - output: output.as_mut_ptr(), - reserved: 0, - }; - let mut ticket = 0; - assert_eq!(XDspSubmitCommand(stream, &command, &mut ticket), S_OK); - for channel in 0..2 { - let energy: f32 = output - .iter() - .skip(channel) - .step_by(2) - .map(|s| s * s) - .sum::<f32>() - / BLOCK as f32; - assert!(energy > 0.5, "channel {channel} wet, energy {energy}"); - } - assert_eq!(XDspDeactivate(stream), S_OK); - // The only slot is free again. - assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK); - assert_eq!(XDspDeactivate(stream), S_OK); - assert_eq!(XDspDisconnect(dsp), S_OK); - } - - #[test] - fn convolution_through_the_api_returns_wet_audio() { - const BLOCK: usize = 0x200; - let mut base = vec![0u8; 0x10_0000]; - let mut dsp = std::ptr::null_mut(); - assert_eq!( - XDspConnectWithMaximumStreamLimit( - base.as_mut_ptr().cast(), - 0x10_0000, - 24, - 4, - 2, - &mut dsp - ), - S_OK - ); - // A unity impulse in the console's frequency-domain layout. - let mut time = vec![0f32; BLOCK]; - time[0] = 1.0; - let ir = crate::modules::dsp_convolve::encode_ir(&time, BLOCK); - let desc = StreamDesc { - kind: CONVOLUTION, - options: 0, - frames: BLOCK as u32, - channels: 1, - ir_floats: ir.len() as u32, - ir: ir.as_ptr(), - }; - let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut()); - assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK); - let input = vec![0.75f32; BLOCK]; - let mut output = vec![0f32; BLOCK]; - let command = Command { - gains: [1.0, 1.0], - input: input.as_ptr(), - output: output.as_mut_ptr(), - reserved: 0, - }; - let mut ticket = 0; - assert_eq!(XDspSubmitCommand(stream, &command, &mut ticket), S_OK); - assert_eq!(ticket, 1); - // SAFETY: the stream's status block. - let (completed, result) = unsafe { ((*status).completed, (*status).result) }; - assert_eq!((completed, result), (ticket, S_OK)); - let energy: f32 = output.iter().map(|s| s * s).sum::<f32>() / BLOCK as f32; - assert!(energy > 0.5, "wet return, energy {energy}"); - assert_eq!(XDspDeactivate(stream), S_OK); - assert_eq!(XDspDisconnect(dsp), S_OK); - } - - /// XDspConnectWithMaximumStreamLimit: "XDspActivate returns - /// XDSP_E_NO_DEVICE_RESOURCES if this count is exceeded." - #[test] - fn activations_past_the_stream_limit_have_no_device_resources() { - let mut base = vec![0u8; 0x1_0000]; - let mut dsp = std::ptr::null_mut(); - assert_eq!( - XDspConnectWithMaximumStreamLimit( - base.as_mut_ptr().cast(), - 0x1_0000, - 0, - 1, - 1, - &mut dsp - ), - S_OK - ); - let transform = StreamDesc { - kind: 2, - options: 0, - frames: 0x400, - channels: 1, - ir_floats: 0, - ir: std::ptr::null(), - }; - let (mut status, mut first, mut second) = - (std::ptr::null(), std::ptr::null_mut(), std::ptr::null_mut()); - assert_eq!(XDspActivate(dsp, &transform, &mut status, &mut first), S_OK); - assert_eq!( - XDspActivate(dsp, &transform, &mut status, &mut second), - NO_DEVICE_RESOURCES - ); - assert_eq!(XDspDeactivate(first), S_OK); - assert_eq!(XDspDisconnect(dsp), S_OK); - } - - /// XDspDisconnect: "All XDSP streams must be deactivated successfully - /// before calling this function"; otherwise it fails with - /// XDSP_E_NOT_ALL_HANDLES_DEACTIVATED. We take the error to leave the - /// client usable. - #[test] - fn disconnect_with_an_active_stream_is_refused() { - let mut base = vec![0u8; 0x1_0000]; - let mut dsp = std::ptr::null_mut(); - assert_eq!( - XDspConnectWithMaximumStreamLimit( - base.as_mut_ptr().cast(), - 0x1_0000, - 0, - 1, - 1, - &mut dsp - ), - S_OK - ); - let transform = StreamDesc { - kind: 2, - options: 0, - frames: 0x400, - channels: 1, - ir_floats: 0, - ir: std::ptr::null(), - }; - let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut()); - assert_eq!( - XDspActivate(dsp, &transform, &mut status, &mut stream), - S_OK - ); - assert_eq!(XDspDisconnect(dsp), NOT_ALL_HANDLES_DEACTIVATED); - // The client is still there for its stream. - assert_eq!(XDspDeactivate(stream), S_OK); - assert_eq!(XDspDisconnect(dsp), S_OK); - } } diff --git a/crates/victory-hle/src/modules/dsp_convolve.rs b/crates/victory-hle/src/modules/dsp_convolve.rs deleted file mode 100644 index 7112177505..0000000000 --- a/crates/victory-hle/src/modules/dsp_convolve.rs +++ /dev/null @@ -1,403 +0,0 @@ -//! Partitioned frequency-domain convolution for the console's audio DSP, -//! kept host-independent so its arithmetic is covered on every platform. -//! -//! The console hands the impulse response to `XDspActivate` already in its -//! frequency-domain layout: a run of complex (real, imaginary) float pairs, -//! split into filter blocks of `blockFrameCount` pairs each. A stereo IR -//! holds one such run per channel. Each block is the spectrum of one -//! time-domain slice of the filter; a real slice of `block` samples has -//! `block + 1` unique bins of a `2 * block` point FFT, of which the console -//! stores the first `block` (the Nyquist bin is dropped). The missing half -//! is reconstructed by conjugate symmetry before an inverse transform. - -const TAU: f32 = std::f32::consts::TAU; - -#[derive(Clone, Copy, Debug, Default, PartialEq)] -struct Complex { - re: f32, - im: f32, -} - -impl Complex { - fn new(re: f32, im: f32) -> Self { - Self { re, im } - } - - fn conj(self) -> Self { - Self { - re: self.re, - im: -self.im, - } - } - - fn add(self, other: Self) -> Self { - Self { - re: self.re + other.re, - im: self.im + other.im, - } - } - - fn sub(self, other: Self) -> Self { - Self { - re: self.re - other.re, - im: self.im - other.im, - } - } - - fn mul(self, other: Self) -> Self { - Self { - re: self.re * other.re - self.im * other.im, - im: self.re * other.im + self.im * other.re, - } - } - - fn scale(self, by: f32) -> Self { - Self { - re: self.re * by, - im: self.im * by, - } - } -} - -/// In-place radix-2 FFT. `inverse` uses the opposite sign and divides by N. -fn fft(data: &mut [Complex], inverse: bool) { - let n = data.len(); - debug_assert!(n.is_power_of_two() && n > 1); - let mut j = 0; - for i in 1..n { - let mut bit = n >> 1; - while j & bit != 0 { - j ^= bit; - bit >>= 1; - } - j ^= bit; - if i < j { - data.swap(i, j); - } - } - let mut len = 2; - while len <= n { - let angle = if inverse { - TAU / len as f32 - } else { - -TAU / len as f32 - }; - let step = Complex::new(angle.cos(), angle.sin()); - for start in (0..n).step_by(len) { - let mut twiddle = Complex::new(1.0, 0.0); - for k in 0..len / 2 { - let even = data[start + k]; - let odd = data[start + k + len / 2].mul(twiddle); - data[start + k] = even.add(odd); - data[start + k + len / 2] = even.sub(odd); - twiddle = twiddle.mul(step); - } - } - len *= 2; - } - if inverse { - let by = 1.0 / n as f32; - for value in data.iter_mut() { - *value = value.scale(by); - } - } -} - -/// One stream's convolution state. -pub(crate) struct Convolver { - block: usize, - fft_len: usize, - channels: usize, - /// [channel][filter block][spectrum] - filters: Vec<Vec<Vec<Complex>>>, - /// Past input spectra, newest first: [channel][history][spectrum]. - history: Vec<Vec<Vec<Complex>>>, - /// Samples carried from one output block to the next. - tail: Vec<Vec<f32>>, -} - -impl Convolver { - /// `ir` holds `ir_floats` floats per channel. With `stereo_ir` each - /// channel has its own filter; otherwise one filter feeds both. - pub(crate) fn new( - ir: &[f32], - ir_floats: usize, - block: usize, - channels: usize, - stereo_ir: bool, - ) -> Option<Self> { - if !block.is_power_of_two() || block == 0 || !(1..=2).contains(&channels) { - return None; - } - let fft_len = block * 2; - let pairs = ir_floats / 2; - let blocks = pairs / block; - if blocks == 0 || ir.len() < ir_floats * if stereo_ir { channels } else { 1 } { - return None; - } - let mut filters = Vec::new(); - for channel in 0..channels { - let source = if stereo_ir { channel } else { 0 }; - let base = source * ir_floats; - let mut per_block = Vec::with_capacity(blocks); - for filter in 0..blocks { - let at = base + filter * block * 2; - let stored = &ir[at..at + block * 2]; - let mut spectrum = vec![Complex::default(); fft_len]; - for (bin, pair) in stored.as_chunks::<2>().0.iter().enumerate() { - spectrum[bin] = Complex::new(pair[0], pair[1]); - } - // Bin `block` (Nyquist) was not stored; the upper half is - // the conjugate mirror of the lower half. - for bin in 1..block { - spectrum[fft_len - bin] = spectrum[bin].conj(); - } - per_block.push(spectrum); - } - filters.push(per_block); - } - let history = (0..channels) - .map(|_| vec![vec![Complex::default(); fft_len]; blocks]) - .collect(); - let tail = vec![vec![0.0; block]; channels]; - Some(Self { - block, - fft_len, - channels, - filters, - history, - tail, - }) - } - - #[cfg(test)] - pub(crate) fn reset(&mut self) { - for channel in &mut self.history { - for spectrum in channel { - spectrum.fill(Complex::default()); - } - } - for tail in &mut self.tail { - tail.fill(0.0); - } - } - - /// Convolves one block. `input` and `output` are interleaved unless the - /// matching deinterleaved flag is set; `gains` is `[begin, end]`, ramped - /// linearly over the block as the console command specifies. - // shortcut: the block's FFT scratch is allocated per call; reuse one - // buffer per stream once the title's block rate makes that worthwhile. - pub(crate) fn process( - &mut self, - input: &[f32], - output: &mut [f32], - gains: [f32; 2], - deinterleaved_input: bool, - deinterleaved_output: bool, - ) -> bool { - let needed = self.block * self.channels; - if input.len() < needed || output.len() < needed { - return false; - } - for channel in 0..self.channels { - let mut spectrum = vec![Complex::default(); self.fft_len]; - for (frame, slot) in spectrum.iter_mut().enumerate().take(self.block) { - let index = if deinterleaved_input { - channel * self.block + frame - } else { - frame * self.channels + channel - }; - *slot = Complex::new(input[index], 0.0); - } - fft(&mut spectrum, false); - let history = &mut self.history[channel]; - history.rotate_right(1); - history[0] = spectrum; - - let mut sum = vec![Complex::default(); self.fft_len]; - for (past, filter) in history.iter().zip(&self.filters[channel]) { - for (total, (x, h)) in sum.iter_mut().zip(past.iter().zip(filter)) { - *total = total.add(x.mul(*h)); - } - } - fft(&mut sum, true); - - let step = (gains[1] - gains[0]) / self.block as f32; - let (tail, filter) = (&mut self.tail[channel], &mut sum); - for frame in 0..self.block { - let wet = filter[frame].re + tail[frame]; - let gain = gains[0] + step * frame as f32; - let index = if deinterleaved_output { - channel * self.block + frame - } else { - frame * self.channels + channel - }; - output[index] = wet * gain; - } - for frame in 0..self.block { - tail[frame] = filter[self.block + frame].re; - } - } - true - } -} - -/// Builds the console's frequency-domain IR from a time-domain filter, for -/// tests and for tools. `block` complex pairs are stored per filter block. -#[cfg(test)] -pub(crate) fn encode_ir(time: &[f32], block: usize) -> Vec<f32> { - let blocks = time.len() / block; - let mut out = Vec::with_capacity(blocks * block * 2); - for block_index in 0..blocks { - let slice = &time[block_index * block..(block_index + 1) * block]; - let mut spectrum = vec![Complex::default(); block * 2]; - for (i, &sample) in slice.iter().enumerate() { - spectrum[i] = Complex::new(sample, 0.0); - } - fft(&mut spectrum, false); - for bin in &spectrum[..block] { - out.push(bin.re); - out.push(bin.im); - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Direct time-domain convolution, the reference for the FFT path. - fn direct(input: &[f32], ir: &[f32]) -> Vec<f32> { - let mut out = vec![0.0; input.len()]; - for (i, &x) in input.iter().enumerate() { - for (j, &h) in ir.iter().enumerate() { - if i + j < out.len() { - out[i + j] += x * h; - } - } - } - out - } - - fn stream(ir: &[f32], input: &[f32], block: usize, channels: usize) -> Vec<f32> { - let encoded = encode_ir(ir, block); - let mut convolver = - Convolver::new(&encoded, encoded.len(), block, channels, false).unwrap(); - let mut output = vec![0.0f32; input.len()]; - for (block_index, chunk) in input.as_chunks::<512>().0.iter().enumerate() { - assert!(convolver.process( - &chunk[..block], - &mut output[block_index * block..(block_index + 1) * block], - [1.0, 1.0], - false, - false, - )); - } - output - } - - #[test] - fn fft_round_trips_a_real_signal() { - let mut values: Vec<Complex> = (0..16) - .map(|i| Complex::new((i as f32 * 0.3).sin(), 0.0)) - .collect(); - let original = values.clone(); - fft(&mut values, false); - fft(&mut values, true); - for (a, b) in values.iter().zip(&original) { - assert!((a.re - b.re).abs() < 1e-4 && (a.im - b.im).abs() < 1e-4); - } - } - - #[test] - fn impulse_response_copies_the_input() { - let mut input = vec![0.0f32; 1024]; - input[3] = 1.0; - let mut ir = vec![0.0f32; 512]; - ir[0] = 1.0; - let got = stream(&ir, &input, 512, 1); - let expected = direct(&input, &ir); - for (a, b) in got.iter().zip(&expected) { - assert!((a - b).abs() < 1e-3, "{a} != {b}"); - } - } - - #[test] - fn matches_direct_convolution_over_several_blocks() { - const BLOCK: usize = 512; - let input: Vec<f32> = (0..BLOCK * 4) - .map(|i| (i as f32 * 0.07).sin() * 0.6) - .collect(); - let ir: Vec<f32> = (0..BLOCK * 2) - .map(|i| (-(i as f32) / 300.0).exp() * (i as f32 * 0.11).sin() * 0.2) - .collect(); - let got = stream(&ir, &input, BLOCK, 1); - let expected = direct(&input, &ir); - let error: f32 = got - .iter() - .zip(&expected) - .map(|(a, b)| (a - b).abs()) - .fold(0.0, f32::max); - assert!(error < 0.02, "largest error {error}"); - } - - #[test] - fn stereo_streams_keep_their_channels() { - const BLOCK: usize = 512; - let mut ir_left = vec![0.0f32; BLOCK]; - ir_left[0] = 1.0; - let mut ir_right = vec![0.0f32; BLOCK]; - ir_right[4] = 0.5; - let mut encoded = encode_ir(&ir_left, BLOCK); - encoded.extend(encode_ir(&ir_right, BLOCK)); - // `impulseResponseLengthInFloats` is per channel for a stereo IR. - let per_channel = encoded.len() / 2; - let mut convolver = Convolver::new(&encoded, per_channel, BLOCK, 2, true).unwrap(); - let mut input = vec![0.0f32; BLOCK * 2]; - input[0] = 1.0; // left frame 0 - input[1] = 1.0; // right frame 0 - let mut output = vec![0.0f32; BLOCK * 2]; - assert!(convolver.process(&input, &mut output, [1.0, 1.0], false, false)); - assert!((output[0] - 1.0).abs() < 1e-3, "left passed through"); - assert!(output[1].abs() < 1e-3, "right delayed by four frames"); - assert!((output[4 * 2 + 1] - 0.5).abs() < 1e-3, "right echo"); - } - - #[test] - fn ramped_gains_and_reset_change_the_output() { - const BLOCK: usize = 512; - let mut ir = vec![0.0f32; BLOCK]; - ir[0] = 1.0; - let encoded = encode_ir(&ir, BLOCK); - let mut convolver = Convolver::new(&encoded, encoded.len(), BLOCK, 1, false).unwrap(); - let input = vec![1.0f32; BLOCK]; - let mut output = vec![0.0f32; BLOCK]; - assert!(convolver.process(&input, &mut output, [0.0, 1.0], false, false)); - assert!(output[0].abs() < 1e-3); - // The console does not store the Nyquist bin, so a reconstructed - // impulse is off by a fraction of a percent. - assert!( - (output[BLOCK - 1] - 1.0).abs() < 5e-3, - "gain ramps to one, got {}", - output[BLOCK - 1] - ); - convolver.reset(); - output.fill(0.0); - assert!(convolver.process(&input, &mut output, [1.0, 1.0], false, false)); - assert!((output[0] - 1.0).abs() < 1e-3, "reset clears the history"); - } - - #[test] - fn rejects_bad_layouts_and_buffers() { - const BLOCK: usize = 512; - let encoded = encode_ir(&vec![0.0f32; BLOCK], BLOCK); - assert!(Convolver::new(&encoded, encoded.len(), 0, 1, false).is_none()); - assert!(Convolver::new(&encoded, encoded.len(), BLOCK, 3, false).is_none()); - assert!(Convolver::new(&encoded, 4, BLOCK, 1, false).is_none()); - let mut convolver = Convolver::new(&encoded, encoded.len(), BLOCK, 1, false).unwrap(); - let short = Vec::new(); - let mut output = Vec::new(); - assert!(!convolver.process(&short, &mut output, [1.0, 1.0], false, false)); - } -} diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 7cb06bd0a1..7fa9f902a7 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -1,7 +1,7 @@ //! The console's DirectStorage (`XCRDAPI.dll`): a factory that opens files //! and creates request queues and status arrays the title polls. Its //! interfaces have grown since 2020 (new interface ids, new slots); the -//! slots here are the ones Grand Theft Auto VI calls, read from its call +//! slots here are the ones the title calls, read from its call //! sites. Slots nobody has needed yet log their offset. //! //! Submitted requests of every queue run on one pool of workers, as the @@ -27,12 +27,11 @@ use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; use victory_formats::bcpack::{self, Tables}; -use super::release_ref; use super::xasync::{E_INVALIDARG, E_NOTIMPL, E_PENDING}; use super::xgameruntime::{Guid, HRESULT, Methods, Object, S_OK, add_ref, missing, put}; use crate::{HleModule, hle_export}; -/// The factory interface Grand Theft Auto VI asks for. +/// The factory interface the title asks for. const FACTORY: Guid = Guid::new( 0x6295_9d11, 0xd45f, @@ -90,12 +89,12 @@ extern "system" fn add_ref_instance<T>(this: *const Instance<T>) -> u32 { extern "system" fn release<T>(this: *mut Instance<T>) -> u32 { // SAFETY: as above. - let left = release_ref(&unsafe { &*this }.refs, "dstorage object"); - if left == Some(0) { + let left = unsafe { &*this }.refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { // SAFETY: the last reference; created by `Instance::create`. drop(unsafe { Box::from_raw(this) }); } - left.unwrap_or(0) + left } fn iid_text(iid: *const Guid) -> String { @@ -142,10 +141,12 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out tracing::warn!(path = name, %error, "dstorage: opening a file failed"); return from_win32(&error); } + let kept = name.clone(); tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened"); // SAFETY: a handle we just opened and nobody else owns. let file = unsafe { std::fs::File::from_raw_handle(handle) }; let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); + WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); put(out, file) } @@ -172,7 +173,7 @@ extern "system" fn create_status_array( } /// The queue's description: as in 2020 (source type, capacity, priority, -/// name), plus a field Grand Theft Auto VI sets to 1. +/// name), plus a field the title sets to 1. #[repr(C)] struct QueueDesc { source_type: u64, @@ -217,15 +218,31 @@ extern "system" fn create_queue( ) } -/// Grand Theft Auto VI asks for 32 MiB and stops if this fails. +/// The title asks for 32 MiB and stops if this fails. extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT { tracing::info!(size, "dstorage: staging buffer size"); if let Some(scheduler) = scheduler() { - scheduler.lock().staging = u64::from(size); + scheduler.lock().staging = staging_limit(u64::from(size)); } S_OK } +/// The compressed bytes let in flight for a staging buffer of `title` +/// bytes: at least `VICTORY_DSTORAGE_STAGING_MB` (128 unless set; 0 keeps +/// the title's). On the console the staging buffer is memory the hardware +/// decompresses through; here it only bounds how much is read and unpacked +/// at once, and the title's 32 MiB held most of the twelve workers idle +/// while the world streamed in (one request of a few MB each). +fn staging_limit(title: u64) -> u64 { + static MB: OnceLock<u64> = OnceLock::new(); + let mb = *MB.get_or_init(|| { + let mb = std::env::var("VICTORY_DSTORAGE_STAGING_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(128); + tracing::info!(mb, "dstorage: compressed bytes in flight at least (VICTORY_DSTORAGE_STAGING_MB)"); + mb + }); + title.max(mb << 20) +} + fn text(name: *const c_char) -> String { if name.is_null() { return String::new(); @@ -290,7 +307,7 @@ extern "system" fn status_result(this: Array, index: u32) -> HRESULT { .map_or(E_INVALIDARG, |e| e.load(Ordering::Acquire)) } -/// Grand Theft Auto VI polls this (entry 0, a `Sleep(1)` loop) and never +/// The title polls this (entry 0, a `Sleep(1)` loop) and never /// reads the result itself. extern "system" fn is_complete(this: Array, index: u32) -> bool { status_result(this, index) != E_PENDING @@ -357,6 +374,20 @@ struct Lanes { /// BCPack bytes written and time spent on them. bcpack: (u64, std::time::Duration), since: Option<std::time::Instant>, + /// Reads held back for the title's Submit when a half-full queue + /// submitted itself, since the last line: Submits that released some, + /// entries released, and the wait (sum, most) from the first hold to + /// that Submit (µs); when the last line was written. (A lead for the + /// stand-in models and the haze: a batch of streamed data waits here + /// for one call of the title's; gfx41.) + held_waits: (u64, u64, u64, u64), + held_line: Option<std::time::Instant>, + /// Since the last 5 s line: the slowest request run (ms, destination + /// bytes, options), and requests over 250 ms and over 1 s, plain and + /// BCPack apart (gfx41: BCPack decodes at about 12 MB/s a worker in run + /// 327, and a status waits for every earlier request of its queue). + slowest: (u64, u32, u64), + slow: [u64; 4], } /// A queue's requests in the scheduler. @@ -367,6 +398,11 @@ struct Lane { clock: u64, /// Enqueued, not yet submitted. unsubmitted: Vec<Command>, + /// Left out when the queue submitted itself, until the title's Submit: + /// reads into physical pages and the status entries behind them. + held: Vec<Command>, + /// When the first of `held` was left out (for the held-wait line). + held_since: Option<std::time::Instant>, /// Submitted, by sequence number: reads not started, status entries /// not written, reads running, and failures not yet reported. reads: VecDeque<(u64, Request)>, @@ -405,7 +441,7 @@ fn scheduler() -> Option<&'static Scheduler> { next_id: 0, next_seq: 0, staged: 0, - staging: STAGING, + staging: staging_limit(STAGING), starved: false, clock: [0; 3], now: 0, @@ -414,6 +450,10 @@ fn scheduler() -> Option<&'static Scheduler> { refused: 0, bcpack: Default::default(), since: None, + held_waits: Default::default(), + held_line: None, + slowest: (0, 0, 0), + slow: [0; 4], }), work: Condvar::new(), finished: Condvar::new(), @@ -426,7 +466,22 @@ fn scheduler() -> Option<&'static Scheduler> { .filter(|i| { std::thread::Builder::new() .name(format!("dstorage {i}")) - .spawn(|| work(scheduler)) + .spawn(|| { + // Try 6.0: above normal priority, as the console's + // decompression hardware runs beside its CPU: the + // title's streamer waits for these reads (people + // and buildings came in at a low level of detail + // first, the full one late). `VICTORY_WIDE_PRIORITY=0`: + // normal. + if std::env::var_os("VICTORY_WIDE_PRIORITY").is_none_or(|v| v != "0") { + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL, + }; + // SAFETY: a plain call on our own thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) }; + } + work(scheduler) + }) .is_ok() }) .count(); @@ -441,20 +496,74 @@ impl Scheduler { } } +/// The walls trace (`VICTORY_WALLS_TRACE`): 0 or unset: off; 1: a line for +/// every read request that fails, with its file; 2: for every request (the +/// list of a launch's reads, by file and offset, is what a launch with the +/// first room's walls and one without are compared by). +fn walls_trace() -> u8 { + static ON: OnceLock<u8> = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("VICTORY_WALLS_TRACE").ok().and_then(|v| v.trim().parse::<u8>().ok()).unwrap_or(0) + }) +} + +/// The files opened, by the address of our file object, with their paths +/// (for the walls trace: a request names its file by that address). +static WALLS_FILES: Mutex<Vec<(usize, String)>> = Mutex::new(Vec::new()); + +/// The walls trace's line for a request that is done. +fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std::time::Instant) { + let level = walls_trace(); + if level == 0 || (level == 1 && result.is_ok()) { + return; + } + let file = if request.options & MEMORY_SOURCE != 0 { + "memory".to_string() + } else { + let files = WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()); + let source = request.source as usize; + files.iter().find(|f| f.0 == source).map_or_else(|| "?".to_string(), |f| f.1.clone()) + }; + let hr = match result { + Ok(()) => 0, + Err(hr) => *hr as u32, + }; + tracing::info!( + file, + offset = request.offset, + source_size = request.source_size, + destination_size = request.destination_size, + to_pages = request.options & PAGE_DESTINATION != 0, + options = format_args!("{:#x}", request.options), + ms = started.elapsed().as_millis() as u64, + ok = result.is_ok(), + hr = format_args!("{hr:#010x}"), + "walls trace: a read request is done" + ); +} + /// A worker: runs the next read of the most deserving queue. fn work(scheduler: &'static Scheduler) { + // `VICTORY_DISK_CORES=slow`: the workers leave the fast cores to the + // title's threads (`victory_gpu::framelog::keep_on_slow_cores`; off by + // default until it is measured). + #[cfg(windows)] + { + static SLOW: OnceLock<bool> = OnceLock::new(); + if *SLOW.get_or_init(|| std::env::var_os("VICTORY_DISK_CORES").is_some_and(|v| v == "slow")) { + victory_gpu::framelog::keep_on_slow_cores("dstorage worker"); + } + } let mut lanes = scheduler.lock(); loop { let Some(job) = lanes.start() else { - lanes = scheduler - .work - .wait(lanes) - .unwrap_or_else(|e| e.into_inner()); + lanes = scheduler.work.wait(lanes).unwrap_or_else(|e| e.into_inner()); continue; }; drop(lanes); let started = std::time::Instant::now(); let result = execute(&job.request); + walls_request(&job.request, &result, started); lanes = scheduler.lock(); lanes.finish(&job, result); lanes.count(&job, started); @@ -472,10 +581,28 @@ impl Lanes { *requests += 1; *bytes += u64::from(job.request.destination_size); *busy += started.elapsed(); + #[cfg(windows)] + { + use victory_gpu::framelog::{T, add}; + add(T::DiskReads, 1); + add(T::DiskBytes, u64::from(job.request.destination_size)); + add(T::DiskUs, started.elapsed().as_micros() as u64); + } if job.request.options & BCPACK != 0 { self.bcpack.0 += u64::from(job.request.destination_size); self.bcpack.1 += started.elapsed(); } + let ms = started.elapsed().as_millis() as u64; + let bc = job.request.options & BCPACK != 0; + if ms > self.slowest.0 { + self.slowest = (ms, job.request.destination_size, job.request.options); + } + if ms >= 250 { + self.slow[usize::from(bc) * 2] += 1; + } + if ms >= 1000 { + self.slow[usize::from(bc) * 2 + 1] += 1; + } let since = *self.since.get_or_insert(started); let elapsed = since.elapsed(); if elapsed.as_secs() >= 5 { @@ -488,12 +615,23 @@ impl Lanes { reading_workers = format_args!("{:.2}", reading / elapsed.as_secs_f64()), staging_waits = std::mem::take(&mut self.refused), bcpack_mb = self.bcpack.0 / 1_000_000, - bcpack_workers = - format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), + bcpack_workers = format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), waiting, "dstorage: last {:.1} s", elapsed.as_secs_f64() ); + let (ms, bytes, options) = std::mem::take(&mut self.slowest); + let slow = std::mem::take(&mut self.slow); + tracing::info!( + "dstorage, slowest request in the last {:.1} s: {ms} ms for {:.1} MB (options {options:#x}{}); requests over 250 ms: {} plain, {} BCPack; over 1 s: {} plain, {} BCPack (a status behind such a request on its queue waits that long)", + elapsed.as_secs_f64(), + f64::from(bytes) / 1e6, + if options & BCPACK != 0 { ", BCPack" } else { "" }, + slow[0], + slow[2], + slow[1], + slow[3], + ); self.done = Default::default(); self.bcpack = Default::default(); self.since = None; @@ -545,8 +683,20 @@ impl Lanes { } } - /// Moves a queue's enqueued commands to the workers. + /// Moves a queue's enqueued commands to the workers (the title's + /// Submit). fn submit(&mut self, id: u64) { + self.submit_as(id, true); + } + + /// As [`Lanes::submit`]; `explicit` false when a half-full queue submits + /// itself, which leaves reads into physical pages for the title's + /// Submit: their page lists point into the title's page table, which + /// The title fills for the batch in its own submit path, right + /// before Submit (`sub_1400e88f0`), so until then they name no page or a + /// page that now holds something else. A status entry behind a held + /// read waits with it. + fn submit_as(&mut self, id: u64, explicit: bool) { let Some(class) = self.lanes.get(&id).map(|l| l.class) else { return; }; @@ -565,7 +715,27 @@ impl Lanes { if lane.reads.is_empty() { lane.clock = lane.clock.max(self.lane_now[class]); } - for command in std::mem::take(&mut lane.unsubmitted) { + let now = std::time::Instant::now(); + // The title's Submit releases what a self-submit held: how long it waited. + let released = if explicit && !lane.held.is_empty() { + lane.held_since + .take() + .map(|since| (lane.held.len() as u64, now.saturating_duration_since(since).as_micros() as u64)) + } else { + None + }; + let mut commands = if explicit { std::mem::take(&mut lane.held) } else { Vec::new() }; + commands.append(&mut lane.unsubmitted); + for command in commands { + let hold = !explicit + && match &command { + Command::Read(r) => r.options & PAGE_DESTINATION != 0, + Command::Status(_) => !lane.held.is_empty(), + }; + if hold { + lane.held.push(command); + continue; + } let seq = self.next_seq; self.next_seq += 1; match command { @@ -573,7 +743,38 @@ impl Lanes { Command::Status(status) => lane.statuses.push_back((seq, status)), } } + if !lane.held.is_empty() && lane.held_since.is_none() { + lane.held_since = Some(now); + } lane.flush(); + if let Some((entries, us)) = released { + let w = &mut self.held_waits; + w.0 += 1; + w.1 += entries; + w.2 += us; + w.3 = w.3.max(us); + } + self.held_line(now); + } + + /// Every 5 s while it has something: [`Lanes::held_waits`] as one line. + fn held_line(&mut self, now: std::time::Instant) { + let since = *self.held_line.get_or_insert(now); + let secs = now.saturating_duration_since(since).as_secs_f64(); + if secs < 5.0 { + return; + } + self.held_line = Some(now); + let (releases, entries, sum, most) = std::mem::take(&mut self.held_waits); + let held_now: usize = self.lanes.values().map(|l| l.held.len()).sum(); + if releases == 0 && held_now == 0 { + return; + } + tracing::info!( + "dstorage reads held for the title's Submit after a queue submitted itself, last {secs:.1} s: {releases} Submits released {entries} entries, waited {:.1} ms on average, {:.1} ms at most; held now {held_now}", + sum as f64 / releases.max(1) as f64 / 1e3, + most as f64 / 1e3, + ); } } @@ -584,6 +785,8 @@ impl Lane { capacity: usize::from(capacity), clock: 0, unsubmitted: Vec::new(), + held: Vec::new(), + held_since: None, reads: VecDeque::new(), statuses: VecDeque::new(), running: BTreeSet::new(), @@ -594,18 +797,18 @@ impl Lane { /// Requests and status entries held, submitted or not. fn entries(&self) -> usize { - self.unsubmitted.len() + self.reads.len() + self.statuses.len() + self.running.len() + self.unsubmitted.len() + + self.held.len() + + self.reads.len() + + self.statuses.len() + + self.running.len() } /// Writes the status entries whose earlier reads have all finished. fn flush(&mut self) { while let Some(&(seq, _)) = self.statuses.front() { let waiting = self.reads.front().map(|r| r.0); - if waiting - .into_iter() - .chain(self.running.first().copied()) - .any(|s| s < seq) - { + if waiting.into_iter().chain(self.running.first().copied()).any(|s| s < seq) { return; } let Some((_, status)) = self.statuses.pop_front() else { @@ -634,9 +837,8 @@ fn staging_bytes(request: &Request) -> u64 { } } -/// Ends a queue: what was enqueued but not submitted is dropped, and this -/// waits until what was submitted has completed or failed, its status -/// entries written, as the console's `Close` does. +/// Ends a queue: what was not started is dropped, and this waits for the +/// reads already running (they write title memory). fn close_lane(id: u64) { let Some(scheduler) = scheduler() else { return; @@ -647,8 +849,10 @@ fn close_lane(id: u64) { }; lane.closed = true; lane.unsubmitted.clear(); - let pending = |l: &Lane| !(l.reads.is_empty() && l.running.is_empty() && l.statuses.is_empty()); - while lanes.lanes.get(&id).is_some_and(pending) { + lane.held.clear(); + lane.reads.clear(); + lane.statuses.clear(); // releases their arrays + while lanes.lanes.get(&id).is_some_and(|l| !l.running.is_empty()) { lanes = scheduler .finished .wait(lanes) @@ -676,7 +880,7 @@ struct Request { source_size: u32, /// Compressed size between two decompression stages; unused here. intermediate_size: u32, - /// Matched by cancellation; Grand Theft Auto VI leaves it 0. + /// Matched by cancellation; the title leaves it 0. tag: u64, name: *const c_char, } @@ -689,7 +893,7 @@ const BCPACK: u64 = 0xf << 1; const PAGE_DESTINATION: u64 = 1 << 21; const MEMORY_SOURCE: u64 = 1 << 22; // Bits 5-20 select a further transform, bit 23 a source in physical pages; -// Grand Theft Auto VI's packages need neither, so requests with them fail. +// The title's packages need neither, so requests with them fail. const PAGE: usize = 64 * 1024; @@ -698,6 +902,7 @@ enum Command { Status(Status), } + /// A status entry to write, holding a reference on its array. struct Status { array: Array, @@ -756,6 +961,16 @@ fn queue(this: QueueRef, command: Command) { if lane.entries() + 1 < lane.capacity.max(2) { break; } + // Full with reads held for a Submit the title cannot make while it + // waits here: they go now, page lists as they are. + if !lane.held.is_empty() { + static WARNED: AtomicBool = AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + tracing::warn!("dstorage: a full queue's reads into physical pages start before the title's Submit"); + } + lanes.submit(id); + scheduler.work.notify_all(); + } lanes = scheduler .finished .wait(lanes) @@ -766,8 +981,19 @@ fn queue(this: QueueRef, command: Command) { }; lane.unsubmitted.push(command); if lane.unsubmitted.len() >= (lane.capacity / 2).max(1) { - lanes.submit(id); + let capacity = lane.capacity; + lanes.submit_as(id, false); scheduler.work.notify_all(); + let held = lanes.lanes.get(&id).map_or(0, |l| l.held.len()); + let n = AUTO_SUBMITS.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::info!( + n, + capacity, + held, + "dstorage: a queue half full submitted itself; reads into physical pages wait for the title's Submit" + ); + } } } @@ -778,16 +1004,15 @@ extern "system" fn submit(this: QueueRef) { return; }; let mut lanes = scheduler.lock(); - let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len()); + let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len() + l.held.len()); tracing::debug!(commands = pending, "dstorage: submit"); lanes.submit(id); scheduler.work.notify_all(); } -/// Ends the queue whatever its reference count: what was not submitted -/// never completes, and this returns once everything submitted has -/// completed or failed (a title may still be polling its status entries). -/// Grand Theft Auto VI calls this, not `Release`. +/// Ends the queue whatever its reference count: what was not started never +/// completes, and this returns once the reads already running have +/// finished. The title calls this, not `Release`. extern "system" fn close(this: QueueRef) { // SAFETY: as above. close_lane(unsafe { &*this }.state.id); @@ -823,14 +1048,27 @@ fn execute(request: &Request) -> Result<(), HRESULT> { return Err(fail(E_INVALIDARG, "source larger than destination")); } let size = request.source_size as usize; - return into_destination(request, size, |out| read_into(request, out).map(|()| size)) - .map_err(|hr| fail(hr, "copying")); + // A file read into a title address is the kernel's write, and the + // kernel does not fault into the GPU side's guard: a block guarded + // again between `kernel_will_write` and the read (the guard over all + // the views of a page protects other views from other threads) made + // the read fail with ERROR_INVALID_USER_BUFFER, and the title stops + // at the failed request (runs amd-C and amd-C2, seconds after the + // world's first frame). It is read beside and copied in: our copy + // faults into the guard like the title's own writes. + let bounce = options & (PAGE_DESTINATION | MEMORY_SOURCE) == 0; + return into_destination(request, size, |out| { + if !bounce { + return read_into(request, out).map(|()| size); + } + let mut data = vec![0; size]; + read_into(request, &mut data)?; + out.copy_from_slice(&data); + Ok(size) + }) + .map_err(|hr| fail(hr, "copying")); } - let tables = if bc != 0 { - Some(bcpack_tables()?) - } else { - None - }; + let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; // The console's order: zlib first, then BCPack. let source = if bc != 0 && options & ZLIB != 0 { @@ -860,11 +1098,47 @@ fn execute(request: &Request) -> Result<(), HRESULT> { /// that ends short of `out` passes: the title's chunks fill it exactly, and /// nothing says that is required. fn inflate(source: &[u8], out: &mut [u8]) -> Result<usize, HRESULT> { - miniz_oxide::inflate::decompress_slice_iter_to_slice(out, std::iter::once(source), true, false) - .map_err(|status| { - tracing::debug!(?status, "dstorage: zlib stream"); - INVALID_DATA - }) + thread_local! { + static INFLATE: std::cell::RefCell<zlib_rs::Inflate> = + std::cell::RefCell::new(zlib_rs::Inflate::new(true, 15)); + } + INFLATE.with_borrow_mut(|state| { + state.reset(true); + // `Inflate::decompress` cannot distinguish a valid empty stream from + // an insufficient buffer when `avail_out == 0`, so use a 1-byte scratch + // destination and verify `written <= out_len` afterward. + let out_len = out.len(); + let mut scratch = [0u8; 1]; + let dest = if out_len == 0 { &mut scratch[..] } else { out }; + let (mut in_pos, mut out_pos) = (0usize, 0usize); + let status = loop { + match state.decompress( + &source[in_pos..], + &mut dest[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) { + Ok(zlib_rs::Status::StreamEnd) => break Ok(zlib_rs::Status::StreamEnd), + Ok(zlib_rs::Status::Ok) => { + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + if next_in == in_pos && next_out == out_pos { + break Ok(zlib_rs::Status::BufError); + } + in_pos = next_in; + out_pos = next_out; + } + other => break other, + } + }; + let written = state.total_out() as usize; + match status { + Ok(zlib_rs::Status::StreamEnd) if written <= out_len => Ok(written), + other => { + tracing::debug!(?other, "dstorage: zlib stream"); + Err(INVALID_DATA) + } + } + }) } /// The BCPack format's constant tables, parsed once for the process. If @@ -902,9 +1176,7 @@ fn use_bcpack_tables(dir: std::path::PathBuf) { #[cfg(test)] fn load_bcpack_tables() -> Result<Tables, String> { - let dir = BCPACK_DIR - .get() - .ok_or("no folder set for the test tables")?; + let dir = BCPACK_DIR.get().ok_or("no folder set for the test tables")?; let bytes = std::fs::read(dir.join("tables.bin")).map_err(|e| e.to_string())?; Tables::parse(&bytes).map_err(|e| e.to_string()) } @@ -930,9 +1202,7 @@ static READING: AtomicU64 = AtomicU64::new(0); fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { if request.options & MEMORY_SOURCE != 0 { // SAFETY: the title's source holds `out.len()` bytes until completion. - out.copy_from_slice(unsafe { - std::slice::from_raw_parts(request.source.cast(), out.len()) - }); + out.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), out.len()) }); return Ok(()); } // SAFETY: a file object we created; the title keeps it open. @@ -966,13 +1236,22 @@ fn into_destination( fill: impl FnOnce(&mut [u8]) -> Result<usize, HRESULT>, ) -> Result<(), HRESULT> { if request.options & PAGE_DESTINATION == 0 { - // Raw reads land through the kernel, which does not fault into the - // GPU side's guard on title buffers; open them first. + // Opens the guarded blocks and tells the GPU side a placed texture + // there changes. `fill` writes from user mode (a file read is read + // beside first, see `execute`), so a block guarded again meanwhile + // faults into the guard instead of failing the write. victory_gpu::kernel_will_write(request.destination as usize, len); // SAFETY: the title's destination holds `destination_size` bytes, at // least `len`, and nothing else writes it until completion. let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::<u8>(), len) }; - return fill(out).map(drop); + let filled = fill(out).map(drop); + // Said again now that the bytes are there (upstream's c75fdba holds + // the blocks open over the read and marks them once more at its + // end): a copy or a texture pass that took the memory while the + // read was under way took what was there before. Counted; acted on + // only with `VICTORY_PAGE_WRITES=all`. + victory_gpu::title_memory_written(request.destination as usize, len, false); + return filled; } let offset = (request.page_offset & 0xffff) as usize; // SAFETY: the title passes a page number per 64 KiB of destination, @@ -986,19 +1265,81 @@ fn into_destination( // Consecutive pages of one allocation (the usual case): written in // place through one view. if let Some(mut window) = super::xmem::page_window(pages, offset, len) { - return fill(window.bytes()).map(drop); + let filled = fill(window.bytes()).map(drop); + drop(window); + // The title maps pages where the card reads them and has them + // filled afterwards: the GPU side's copies of those addresses + // learn of the bytes only from this (upstream c75fdba, fork PR + // #571). After a decode that failed part way too: what it wrote + // is there. + super::xmem::pages_written(pages, offset, len); + return filled; } let mut data = vec![0; len]; let n = fill(&mut data)?; - if super::xmem::write_physical(pages, offset, &data[..n]) { + // A page the title has just made, or a view the host refuses for a + // moment, comes right a little later: the write is tried again before + // the request fails (`VICTORY_DSTORAGE_RETRIES`, 12 tries, about 0.9 s + // in all; 0: not tried again, as before). Runs 175-178 lost 12 to 446 + // reads a launch here, all in one second of the loading; the one build + // that tried again (run 165) lost none of 13. + static RETRIES: std::sync::OnceLock<u32> = std::sync::OnceLock::new(); + let retries = *RETRIES.get_or_init(|| { + std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(12) + }); + // Since the start: writes that succeeded on a later try, and writes + // given up. + static RETRIED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + let mut written = super::xmem::write_physical(pages, offset, &data[..n]); + let mut tries = 0u32; + while !written && tries < retries { + std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128))); + tries += 1; + written = super::xmem::write_physical(pages, offset, &data[..n]); + } + if written { + if tries > 0 { + let on_a_retry = RETRIED[0].fetch_add(1, Ordering::Relaxed) + 1; + tracing::info!( + offset, + len, + tries, + on_a_retry, + given_up = RETRIED[1].load(Ordering::Relaxed), + "dstorage: a destination's physical pages written after a retry" + ); + } + // As above, after the write that succeeded. + super::xmem::pages_written(pages, offset, n); Ok(()) } else { + let given_up = RETRIED[1].fetch_add(1, Ordering::Relaxed) + 1; + tracing::warn!( + known = super::xmem::pages_known(pages, offset, len), + tries, + given_up, + on_a_retry = RETRIED[0].load(Ordering::Relaxed), + "dstorage: retries used up (VICTORY_DSTORAGE_RETRIES)" + ); + // Said aloud: the title never reads a request's result + // (it only polls for completion), so a destination left unwritten + // is a model or texture that silently holds whatever its pages + // held before. + tracing::warn!( + offset, + len, + pages = pages.len(), + "dstorage: a destination's physical pages could not be written (unknown page or a host failure); its request fails" + ); Err(E_INVALIDARG) } } -/// Slots by the 2020 order, which the argument shapes at Grand Theft Auto -/// VI's call sites match (0x18, 0x20, 0x30 and 0x40 are called). +/// Queues that submitted themselves, half full (diagnostics). +static AUTO_SUBMITS: AtomicU32 = AtomicU32::new(0); + +/// Slots by the 2020 order, which the argument shapes at +/// the title's call sites match (0x18, 0x20, 0x30 and 0x40 are called). static QUEUE_VTABLE: Methods<12> = Methods([ missing::<0> as *const (), add_ref_instance::<Queue> as *const (), @@ -1160,10 +1501,18 @@ mod tests { assert_eq!(std::mem::offset_of!(QueueDesc, unknown), 0x18); } + fn compress_zlib(plain: &[u8]) -> Vec<u8> { + let mut buf = vec![0u8; zlib_rs::compress_bound(plain.len())]; + let (packed, rc) = + zlib_rs::compress_slice(&mut buf, plain, zlib_rs::DeflateConfig::new(6)); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); + packed.to_vec() + } + #[test] fn raw_and_zlib_reads_from_a_file() { let plain = pattern(300_000); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let packed = compress_zlib(&plain); let mut contents = plain.clone(); contents.extend_from_slice(&packed); let (_dir, file) = file_with(&contents); @@ -1195,7 +1544,7 @@ mod tests { #[test] fn memory_sources_inflate_too() { let plain = pattern(70_000); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let packed = compress_zlib(&plain); let (queue, array) = (new_queue(1), status_array(1)); let mut out = vec![0u8; plain.len()]; let options = ZLIB | MEMORY_SOURCE; @@ -1222,8 +1571,7 @@ mod tests { // Requests in flight together run in any order, so none of them // shares a destination (failed ones leave theirs undefined). let mut buffers = [[0u8; 16]; 5]; - let [failed, failed_too, out, other, bcpack] = - buffers.each_mut().map(|b| b.as_mut_ptr().cast()); + let [failed, failed_too, out, other, bcpack] = buffers.each_mut().map(|b| b.as_mut_ptr().cast()); // Segment 0: a read past the end, then a bad stream; the first wins. enqueue(queue, &request(0, failed, 16, file, 4090, 16)); @@ -1285,6 +1633,10 @@ mod tests { refused: 0, bcpack: Default::default(), since: None, + held_waits: Default::default(), + held_line: None, + slowest: (0, 0, 0), + slow: [0; 4], } } @@ -1373,7 +1725,7 @@ mod tests { #[test] fn zlib_then_bcpack() { with_test_tables(); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&BC4_STREAM, 6); + let packed = compress_zlib(&BC4_STREAM); let (_dir, file) = file_with(&packed); let (queue, array) = (new_queue(0), status_array(1)); let mut out = [0u8; 16]; @@ -1439,10 +1791,7 @@ mod tests { let (_dir, file) = file_with(&contents); let (queue, array) = (new_queue(0), status_array(1)); let mut out = [0u8; 16]; - enqueue( - queue, - &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88), - ); + enqueue(queue, &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88)); enqueue_status(queue, array, 0); void(queue, 0x30); assert_eq!(wait(array, 0), S_OK); @@ -1463,29 +1812,6 @@ mod tests { assert_eq!(out, [0; 16]); } - /// Close blocks until every submitted request has completed or failed, - /// and writes their status entries. - #[test] - fn closing_a_queue_completes_what_was_submitted() { - let data = pattern(8 << 20); - let (_dir, file) = file_with(&data); - let (queue, array) = (new_queue(0), status_array(1)); - let chunk = 256 << 10; - let mut out = vec![0u8; data.len()]; - for k in 0..32 { - let dst = out[k * chunk..].as_mut_ptr().cast(); - enqueue( - queue, - &request(0, dst, chunk, file, (k * chunk) as u64, chunk), - ); - } - enqueue_status(queue, array, 0); - void(queue, 0x30); - void(queue, 0x40); - assert_eq!(result(array, 0), S_OK); - assert!(out == data); - } - #[test] fn physical_page_destinations() { use crate::modules::xmem; @@ -1528,6 +1854,95 @@ mod tests { let seen = unsafe { std::slice::from_raw_parts(mapped.cast::<u8>().add(PAGE - 40), 100) }; assert_eq!(seen, plain); } + #[test] + fn a_queue_that_submits_itself_holds_reads_into_pages() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 64)); + let array = status_array(1).cast::<Instance<StatusArray>>(); + read(&mut l, 0, PAGE_DESTINATION, 16); + read(&mut l, 0, 0, 16); + add_ref_instance(array); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(Command::Status(Status { array, index: 0 })); + l.submit_as(0, false); + // Only the plain read starts; the status waits behind the held one. + let plain = l.start().unwrap(); + assert_eq!(plain.request.options, 0); + assert!(l.start().is_none()); + l.finish(&plain, Ok(())); + assert_eq!(l.lanes[&0].held.len(), 2); + l.submit(0); + let paged = l.start().unwrap(); + assert_eq!(paged.request.options, PAGE_DESTINATION); + assert!(l.lanes[&0].held.is_empty()); + assert!(!l.lanes[&0].statuses.is_empty()); + l.finish(&paged, Ok(())); + assert!(l.lanes[&0].statuses.is_empty()); + } + + #[test] + fn a_page_list_the_title_changes_before_its_submit() { + use crate::modules::xmem; + let (mut given, mut pages) = (2usize, [0usize; 2]); + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!(xmem::XMemMapPhysicalPages(mapped, 2, pages.as_ptr()), mapped); + // The title's page table: still the page's previous owner when the + // request is enqueued, the right page by its Submit. + let mut list = [pages[0]]; + let plain = pattern(4096); + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type: 0, + capacity: 4, + priority: 1, + name: c"pages".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + let array = status_array(1); + let r = request( + PAGE_DESTINATION | MEMORY_SOURCE, + list.as_mut_ptr().cast(), + plain.len(), + plain.as_ptr().cast(), + 0, + plain.len(), + ); + enqueue(queue, &r); + let mut out = [0u8; 16]; + enqueue(queue, &request(MEMORY_SOURCE, out.as_mut_ptr().cast(), 16, plain.as_ptr().cast(), 0, 16)); + // Half of four: the queue submitted itself. Time for a read started + // then to land in the old page. + std::thread::sleep(std::time::Duration::from_millis(50)); + // SAFETY: the list outlives the request, which reads it when it runs. + unsafe { std::ptr::write_volatile(list.as_mut_ptr(), pages[1]) }; + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, plain[..16]); + // SAFETY: both pages are mapped read-write. + let (first, second) = unsafe { + ( + std::slice::from_raw_parts(mapped.cast::<u8>(), plain.len()), + std::slice::from_raw_parts(mapped.cast::<u8>().add(PAGE), plain.len()), + ) + }; + assert_eq!(second, plain); + assert!(first.iter().all(|&b| b == 0), "the old page was written"); + } + #[test] fn zlib_into_pages_in_place_and_across_allocations() { use crate::modules::xmem; @@ -1541,7 +1956,7 @@ mod tests { }; let (a, b) = (allocate(3), allocate(1)); let plain = pattern(2 * PAGE + 100); - let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let packed = compress_zlib(&plain); // One allocation's pages in order (one window), then pages of two // (through a buffer), both from 50 bytes into the first. let mut destinations = [a.clone(), vec![a[0], a[1], b[0]]]; @@ -1587,20 +2002,60 @@ mod tests { assert_eq!(xmem::XMemFreePhysicalPages(1, b.as_ptr()), 1); } - /// A title releasing once too often: the count stays 0 and nothing is - /// freed again (the old `fetch_sub(1) - 1` overflowed). #[test] - fn release_past_zero_leaves_the_count_at_zero() { - let object = Instance::create(Object::new("dstorage queue", &QUEUE_VTABLE), ()) - .cast::<Instance<()>>(); - assert_eq!(add_ref_instance(object), 2); - assert_eq!(release(object), 1); - // SAFETY: still allocated; the test holds the object. - let refs = &unsafe { &*object }.refs; - refs.store(0, Ordering::Relaxed); - assert_eq!(release(object), 0); - assert_eq!(refs.load(Ordering::Relaxed), 0); - // SAFETY: made by `Instance::create` and not freed by `release`. - drop(unsafe { Box::from_raw(object) }); + fn zlib_inflate_handles_short_exact_empty_and_bad_streams() { + let plain = pattern(65_537); + let packed = compress_zlib(&plain); + + // Exact fit. + let mut exact = vec![0u8; plain.len()]; + assert_eq!(inflate(&packed, &mut exact), Ok(plain.len())); + assert_eq!(exact, plain); + + // Short stream into a larger buffer passes and returns bytes written; + // guard bytes outside the slice passed to `inflate` stay untouched. + let mut larger = vec![0xAA; plain.len() + 64]; + assert_eq!( + inflate(&packed, &mut larger[..plain.len() + 32]), + Ok(plain.len()) + ); + assert_eq!(&larger[..plain.len()], &plain[..]); + assert!(larger[plain.len() + 32..].iter().all(|&b| b == 0xAA)); + + // Empty valid stream passes for empty or non-empty destinations. + let empty = compress_zlib(&[]); + assert_eq!(inflate(&empty, &mut []), Ok(0)); + let mut scratch = [0x55u8; 4]; + assert_eq!(inflate(&empty, &mut scratch), Ok(0)); + + // Oversized stream (destination too small, including empty) fails. + let mut small = vec![0u8; plain.len() - 1]; + assert_eq!(inflate(&packed, &mut small), Err(INVALID_DATA)); + assert_eq!(inflate(&packed, &mut []), Err(INVALID_DATA)); + + // Truncated stream (missing trailer or payload bytes) fails. + let mut out = vec![0u8; plain.len()]; + assert_eq!( + inflate(&packed[..packed.len() - 1], &mut out), + Err(INVALID_DATA) + ); + assert_eq!( + inflate(&packed[..packed.len() / 2], &mut out), + Err(INVALID_DATA) + ); + assert_eq!(inflate(&[], &mut out), Err(INVALID_DATA)); + + // Corrupt Adler-32 trailer fails. + let mut bad_adler = packed.clone(); + *bad_adler.last_mut().unwrap() ^= 1; + assert_eq!(inflate(&bad_adler, &mut out), Err(INVALID_DATA)); + + // Corrupt header/payload fails, and subsequent valid inflate on the + // same thread still succeeds (verifies thread-local state reset). + let mut bad_body = packed.clone(); + bad_body[2] ^= 0xFF; + assert_eq!(inflate(&bad_body, &mut out), Err(INVALID_DATA)); + assert_eq!(inflate(&packed, &mut out), Ok(plain.len())); + assert_eq!(out, plain); } } diff --git a/crates/victory-hle/src/modules/dualsense.rs b/crates/victory-hle/src/modules/dualsense.rs deleted file mode 100644 index 1326f705e5..0000000000 --- a/crates/victory-hle/src/modules/dualsense.rs +++ /dev/null @@ -1,512 +0,0 @@ -//! DualSense and DualShock 4 (PlayStation) pads over HID. -//! -//! The console reports gamepads through GameInput; on a PC these are not -//! XInput devices, so the title never sees them. This reads the pad's HID -//! reports and exposes the same state shape the XInput source does. -//! -//! The reports differ between USB (64 bytes) and Bluetooth (78 bytes, and a -//! different offset for the buttons and triggers), so fields are read through -//! Windows' HID parser (`HidP_*`) by their declared usages rather than by -//! fixed offsets. Both transports and the Edge's report then read the same. -//! -//! shortcut: touchpad, gyro and the lightbar are not reported (the title's -//! pad surface has no axes for them); rumble is not sent back yet. - -#![allow(non_snake_case)] - -use std::sync::{Mutex, Once}; -use std::time::Duration; - -use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{ - DIGCF_DEVICEINTERFACE, DIGCF_PRESENT, HDEVINFO, SP_DEVICE_INTERFACE_DATA, - SP_DEVICE_INTERFACE_DETAIL_DATA_W, SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInterfaces, - SetupDiGetClassDevsW, SetupDiGetDeviceInterfaceDetailW, -}; -use windows_sys::Win32::Devices::HumanInterfaceDevice::{ - GUID_DEVINTERFACE_HID, HID_USAGE_GENERIC_HATSWITCH, HID_USAGE_GENERIC_RX, HID_USAGE_GENERIC_RY, - HID_USAGE_GENERIC_RZ, HID_USAGE_GENERIC_X, HID_USAGE_GENERIC_Y, HID_USAGE_GENERIC_Z, - HID_USAGE_PAGE_BUTTON, HID_USAGE_PAGE_GENERIC, HIDD_ATTRIBUTES, HIDP_CAPS, HIDP_STATUS_SUCCESS, - HidD_FreePreparsedData, HidD_GetAttributes, HidD_GetPreparsedData, HidP_GetCaps, - HidP_GetUsageValue, HidP_GetUsages, HidP_Input, -}; -use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; -use windows_sys::Win32::Storage::FileSystem::{ - CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, ReadFile, -}; - -/// Gamepad buttons, the bits the title maps (same values as `gameinput`). -const MENU: u32 = 0x1; -const VIEW: u32 = 0x2; -const A: u32 = 0x4; -const B: u32 = 0x8; -const X: u32 = 0x10; -const Y: u32 = 0x20; -const UP: u32 = 0x40; -const DOWN: u32 = 0x80; -const LEFT: u32 = 0x100; -const RIGHT: u32 = 0x200; -const LEFT_SHOULDER: u32 = 0x400; -const RIGHT_SHOULDER: u32 = 0x800; -const LEFT_STICK: u32 = 0x1000; -const RIGHT_STICK: u32 = 0x2000; - -/// Sony's vendor id and the DualSense, DualSense Edge, and DualShock 4 -/// product ids (the last is the DualShock 4 USB wireless adaptor). -const SONY: u16 = 0x054c; -const DUALSENSE: u16 = 0x0ce6; -const DUALSENSE_EDGE: u16 = 0x0df2; -const DUALSHOCK4: [u16; 3] = [0x05c4, 0x09cc, 0x0ba0]; - -/// Whether a HID device is a PlayStation pad this module reads. The DualShock -/// 4's descriptor declares the same usages as the DualSense's (X/Y/Z/Rz sticks, -/// Rx/Ry triggers, hat, buttons 1-14 in the same order), so it reads the same. -fn is_playstation_pad(vendor: u16, product: u16) -> bool { - vendor == SONY - && (product == DUALSENSE || product == DUALSENSE_EDGE || DUALSHOCK4.contains(&product)) -} - -const GENERIC_READ: u32 = 0x8000_0000; - -/// A pad reading: triggers 0 to 1, sticks -1 to 1 (up positive). -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct Reading { - pub buttons: u32, - pub left_trigger: f32, - pub right_trigger: f32, - pub left_x: f32, - pub left_y: f32, - pub right_x: f32, - pub right_y: f32, -} - -static READING: Mutex<Option<Reading>> = Mutex::new(None); -static START: Once = Once::new(); - -/// The pad's newest state, starting the reader on first use. -pub fn latest() -> Option<Reading> { - START.call_once(|| { - let _ = std::thread::Builder::new() - .name("playstation-pad".into()) - .spawn(reader); - }); - *READING.lock().unwrap_or_else(|e| e.into_inner()) -} - -/// An open pad: its input handle, the HID parser's description of it (freed -/// on drop) and the input report length. -struct Pad { - handle: HANDLE, - preparsed: isize, - input_len: usize, -} - -impl Drop for Pad { - fn drop(&mut self) { - // SAFETY: both came from the HID API for this handle. - unsafe { - HidD_FreePreparsedData(self.preparsed); - CloseHandle(self.handle); - } - } -} - -fn reader() { - loop { - if let Some(pad) = open_pad() { - read_reports(&pad); - } - *READING.lock().unwrap_or_else(|e| e.into_inner()) = None; - // A pad that is off or out of range is looked for again. - std::thread::sleep(Duration::from_secs(2)); - } -} - -/// Reads until the pad goes away. A report that does not parse is ignored. -fn read_reports(pad: &Pad) { - let mut buf = vec![0u8; pad.input_len.max(78)]; - let log = std::env::var_os("VICTORY_PAD_LOG").is_some(); - let mut last: Option<Reading> = None; - loop { - let mut read = 0u32; - // SAFETY: a live handle and a buffer of its report length. - let ok = unsafe { - ReadFile( - pad.handle, - buf.as_mut_ptr().cast(), - buf.len() as u32, - &mut read, - std::ptr::null_mut(), - ) - }; - if ok == 0 || read == 0 { - return; - } - let Some(reading) = parse(pad.preparsed, &buf[..read as usize]) else { - continue; - }; - if last == Some(reading) { - continue; - } - if log && last.is_none_or(|before| before.buttons != reading.buttons) { - tracing::info!( - buttons = format_args!("{:#x}", reading.buttons), - left = format_args!("{:.2},{:.2}", reading.left_x, reading.left_y), - right = format_args!("{:.2},{:.2}", reading.right_x, reading.right_y), - triggers = format_args!("{:.2},{:.2}", reading.left_trigger, reading.right_trigger), - "PlayStation pad report" - ); - } - last = Some(reading); - *READING.lock().unwrap_or_else(|e| e.into_inner()) = Some(reading); - } -} - -/// Opens the first PlayStation pad and keeps its HID description. -fn open_pad() -> Option<Pad> { - for path in device_paths() { - // SAFETY: a path from SetupAPI, opened for reading only. - let handle = unsafe { - CreateFileW( - path.as_ptr(), - GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE, - std::ptr::null(), - OPEN_EXISTING, - 0, - std::ptr::null_mut(), - ) - }; - if handle == INVALID_HANDLE_VALUE { - continue; - } - // SAFETY: a plain Windows struct for which all zeroes is valid. - let mut attributes: HIDD_ATTRIBUTES = unsafe { std::mem::zeroed() }; - attributes.Size = std::mem::size_of::<HIDD_ATTRIBUTES>() as u32; - // SAFETY: a live HID handle and room for the attributes. - let known = unsafe { HidD_GetAttributes(handle, &mut attributes) }; - if known && is_playstation_pad(attributes.VendorID, attributes.ProductID) { - let mut preparsed: isize = 0; - // SAFETY: a live HID handle and room for the pointer. - if !unsafe { HidD_GetPreparsedData(handle, &mut preparsed) } { - // SAFETY: the handle came from CreateFileW above. - unsafe { CloseHandle(handle) }; - continue; - } - // SAFETY: a plain Windows struct for which all zeroes is valid. - let mut caps: HIDP_CAPS = unsafe { std::mem::zeroed() }; - // SAFETY: the preparations are ours until freed. - let status = unsafe { HidP_GetCaps(preparsed, &mut caps) }; - let input_len = if status == HIDP_STATUS_SUCCESS { - usize::from(caps.InputReportByteLength).max(1) - } else { - 78 - }; - tracing::info!( - product = format_args!("{:#06x}", attributes.ProductID), - report = input_len, - "PlayStation pad connected over HID" - ); - return Some(Pad { - handle, - preparsed, - input_len, - }); - } - // SAFETY: the handle came from CreateFileW above and was not kept. - unsafe { CloseHandle(handle) }; - } - None -} - -/// Every present HID interface's device path. -fn device_paths() -> Vec<Vec<u16>> { - let mut paths = Vec::new(); - // SAFETY: the HID interface class, no enumerator or parent window. - let set: HDEVINFO = unsafe { - SetupDiGetClassDevsW( - &GUID_DEVINTERFACE_HID, - std::ptr::null(), - std::ptr::null_mut(), - DIGCF_PRESENT | DIGCF_DEVICEINTERFACE, - ) - }; - if set == -1 { - return paths; - } - let mut index = 0u32; - loop { - // SAFETY: a plain Windows struct for which all zeroes is valid. - let mut interface: SP_DEVICE_INTERFACE_DATA = unsafe { std::mem::zeroed() }; - interface.cbSize = std::mem::size_of::<SP_DEVICE_INTERFACE_DATA>() as u32; - // SAFETY: the set from above, and room for one interface. - if unsafe { - SetupDiEnumDeviceInterfaces( - set, - std::ptr::null(), - &GUID_DEVINTERFACE_HID, - index, - &mut interface, - ) - } == 0 - { - break; - } - index += 1; - let mut required = 0u32; - // SAFETY: asks for the room the detail needs. - unsafe { - SetupDiGetDeviceInterfaceDetailW( - set, - &interface, - std::ptr::null_mut(), - 0, - &mut required, - std::ptr::null_mut(), - ) - }; - if required == 0 { - continue; - } - let mut buffer = vec![0u8; required as usize]; - let detail = buffer - .as_mut_ptr() - .cast::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>(); - // SAFETY: the buffer is the size the API asked for; cbSize is its header. - unsafe { - (*detail).cbSize = std::mem::size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>() as u32; - if SetupDiGetDeviceInterfaceDetailW( - set, - &interface, - detail, - required, - std::ptr::null_mut(), - std::ptr::null_mut(), - ) == 0 - { - continue; - } - } - // The path starts after the u32 cbSize, as UTF-16. - // SAFETY: the API wrote the path at this offset in our buffer. - let path = unsafe { buffer.as_ptr().add(4).cast::<u16>() }; - let mut len = 0usize; - // SAFETY: the API wrote a NUL-terminated path into the buffer. - while unsafe { *path.add(len) } != 0 { - len += 1; - } - // SAFETY: `path` is valid for `len` u16s in the live buffer. - paths.push(unsafe { std::slice::from_raw_parts(path, len) }.to_vec()); - } - // SAFETY: the set is ours. - unsafe { SetupDiDestroyDeviceInfoList(set) }; - paths -} - -/// A declared usage's value in `report`, if the descriptor has it. -fn usage_value(preparsed: isize, report: &[u8], usage: u16) -> Option<u32> { - let mut value = 0u32; - // SAFETY: the report and the parser's description are live. - let status = unsafe { - HidP_GetUsageValue( - HidP_Input, - HID_USAGE_PAGE_GENERIC, - 0, - usage, - &mut value, - preparsed, - report.as_ptr(), - report.len() as u32, - ) - }; - (status == HIDP_STATUS_SUCCESS).then_some(value) -} - -/// The buttons held in `report`, as HID usage numbers 1 to 14. -fn usage_buttons(preparsed: isize, report: &[u8]) -> Vec<u16> { - let mut usages = [0u16; 32]; - let mut len = usages.len() as u32; - // SAFETY: the report and the parser's description are live; the API only - // reads the report. - let status = unsafe { - HidP_GetUsages( - HidP_Input, - HID_USAGE_PAGE_BUTTON, - 0, - usages.as_mut_ptr(), - &mut len, - preparsed, - report.as_ptr() as *mut u8, - report.len() as u32, - ) - }; - if status == HIDP_STATUS_SUCCESS { - usages[..len as usize].to_vec() - } else { - Vec::new() - } -} - -/// Whether `report` is an input report this module parses: USB's 0x01 or -/// Bluetooth's 0x31 (the HID parser wants the report ID in the buffer). -fn input_report(report: &[u8]) -> bool { - matches!(report.first(), Some(0x01 | 0x31)) -} - -/// The pad state from the report's declared fields. -/// -/// Button usages, in Sony's order: 1 square, 2 cross, 3 circle, 4 triangle, -/// 5 L1, 6 R1, 7 L2, 8 R2, 9 create, 10 options, 11 L3, 12 R3, 13 PS, -/// 14 touchpad. Square, cross, circle and triangle become the title's X, A, -/// B and Y, so circle is back as on the console. -fn parse(preparsed: isize, report: &[u8]) -> Option<Reading> { - if report.len() < 2 || !input_report(report) { - return None; - } - let axis = |usage| usage_value(preparsed, report, usage).unwrap_or(128); - let trigger = |usage| usage_value(preparsed, report, usage).unwrap_or(0); - Some(state( - [ - axis(HID_USAGE_GENERIC_X), - axis(HID_USAGE_GENERIC_Y), - axis(HID_USAGE_GENERIC_Z), - axis(HID_USAGE_GENERIC_RZ), - ], - [trigger(HID_USAGE_GENERIC_RX), trigger(HID_USAGE_GENERIC_RY)], - usage_value(preparsed, report, HID_USAGE_GENERIC_HATSWITCH).unwrap_or(8), - &usage_buttons(preparsed, report), - )) -} - -/// Turns the declared fields into the title's pad state. -fn state(sticks: [u32; 4], triggers: [u32; 2], hat: u32, usages: &[u16]) -> Reading { - let centered = |v: u32| ((f32::from(v as u8) - 127.5) / 127.5).clamp(-1.0, 1.0); - let mut buttons = 0u32; - for usage in usages { - buttons |= match usage { - 1 => X, // square - 2 => A, // cross - 3 => B, // circle - 4 => Y, // triangle - 5 => LEFT_SHOULDER, // L1 - 6 => RIGHT_SHOULDER, // R1 - 9 => VIEW, // create - 10 => MENU, // options - 11 => LEFT_STICK, - 12 => RIGHT_STICK, - 13 => MENU, // PS - _ => 0, - }; - } - // 0 is up and the directions run clockwise; 8 is released. - buttons |= match hat { - 0 => UP, - 1 => UP | RIGHT, - 2 => RIGHT, - 3 => DOWN | RIGHT, - 4 => DOWN, - 5 => DOWN | LEFT, - 6 => LEFT, - 7 => UP | LEFT, - _ => 0, - }; - Reading { - buttons, - left_trigger: f32::from(triggers[0] as u8) / 255.0, - right_trigger: f32::from(triggers[1] as u8) / 255.0, - left_x: centered(sticks[0]), - // The pad's Y axes grow downwards; the title's sticks grow upwards. - left_y: -centered(sticks[1]), - right_x: centered(sticks[2]), - right_y: -centered(sticks[3]), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - const CENTER: [u32; 4] = [128, 128, 128, 128]; - const UP_NEUTRAL: u32 = 8; - - fn pad(usages: &[u16], hat: u32) -> Reading { - state(CENTER, [0, 0], hat, usages) - } - - #[test] - fn cross_circle_square_and_triangle_map() { - assert_eq!(pad(&[2], UP_NEUTRAL).buttons, A); - assert_eq!(pad(&[3], UP_NEUTRAL).buttons, B); - assert_eq!(pad(&[1], UP_NEUTRAL).buttons, X); - assert_eq!(pad(&[4], UP_NEUTRAL).buttons, Y); - } - - #[test] - fn shoulders_system_and_stick_clicks_map() { - assert_eq!( - pad(&[5, 6, 9, 10, 11, 12, 13], UP_NEUTRAL).buttons, - LEFT_SHOULDER | RIGHT_SHOULDER | VIEW | MENU | LEFT_STICK | RIGHT_STICK - ); - } - - #[test] - fn hat_directions_run_clockwise_from_up() { - assert_eq!(pad(&[], 0).buttons, UP); - assert_eq!(pad(&[], 1).buttons, UP | RIGHT); - assert_eq!(pad(&[], 2).buttons, RIGHT); - assert_eq!(pad(&[], 3).buttons, DOWN | RIGHT); - assert_eq!(pad(&[], 4).buttons, DOWN); - assert_eq!(pad(&[], 5).buttons, DOWN | LEFT); - assert_eq!(pad(&[], 6).buttons, LEFT); - assert_eq!(pad(&[], 7).buttons, UP | LEFT); - assert_eq!(pad(&[], 8).buttons, 0); - } - - #[test] - fn sticks_are_centered_and_signed() { - let r = state(CENTER, [0, 0], UP_NEUTRAL, &[]); - assert!(r.left_x.abs() < 0.01 && r.left_y.abs() < 0.01); - assert!(r.right_x.abs() < 0.01 && r.right_y.abs() < 0.01); - let r = state([255, 0, 0, 255], [0, 0], UP_NEUTRAL, &[]); - assert_eq!((r.left_x, r.left_y), (1.0, 1.0)); - assert_eq!((r.right_x, r.right_y), (-1.0, -1.0)); - } - - #[test] - fn triggers_run_zero_to_one() { - let r = state(CENTER, [255, 0], UP_NEUTRAL, &[]); - assert_eq!((r.left_trigger, r.right_trigger), (1.0, 0.0)); - } - - #[test] - fn usb_and_bluetooth_input_reports_are_accepted() { - assert!(input_report(&[0x01, 0])); - assert!(input_report(&[0x31, 0])); - assert!(!input_report(&[0x02, 0])); - assert!(!input_report(&[])); - } - - #[test] - fn playstation_pad_product_ids_are_recognised() { - for product in [DUALSENSE, DUALSENSE_EDGE, 0x05c4, 0x09cc, 0x0ba0] { - assert!(is_playstation_pad(SONY, product), "{product:#06x}"); - } - assert!(!is_playstation_pad(0x045e, 0x02ea)); // an Xbox pad - assert!(!is_playstation_pad(SONY, 0x0ce7)); // another Sony device - } - - /// Not part of the suite: prints what the HID scan sees on this machine. - /// `cargo test -p victory-hle --lib dualsense -- --ignored --nocapture` - #[test] - #[ignore] - fn lists_and_opens_hid_devices() { - let paths = device_paths(); - println!("hid interfaces: {}", paths.len()); - for path in &paths { - println!(" {}", String::from_utf16_lossy(path)); - } - match open_pad() { - Some(pad) => println!("opened a PlayStation pad: report length {}", pad.input_len), - None => println!("no PlayStation pad opened"), - } - } -} diff --git a/crates/victory-hle/src/modules/ffx.rs b/crates/victory-hle/src/modules/ffx.rs new file mode 100644 index 0000000000..47cbb4b3cb --- /dev/null +++ b/crates/victory-hle/src/modules/ffx.rs @@ -0,0 +1,230 @@ +//! `amd_fidelityfx_loader_xbox.dll`: the upscale dispatch. +//! +//! The title's Series S mode renders below its output size and calls the +//! console's FidelityFX upscaler to make the output. The loader and the +//! upscaler are the title's own DLLs and run as they are, but the +//! upscaler's passes are compute pipelines in a container we do not +//! translate: its output stayed black. `ffxDispatch` alone is taken here: +//! an upscale dispatch becomes a temporal resolve of the colour input +//! with the jitter, motion, exposure and reset the title passes (Try 6.7, +//! `victory_gpu::list::upscale_temporal`; a plain stretch before it and +//! with `VICTORY_UPSCALE_TEMPORAL=0`); anything else, and an upscale we +//! could not record, goes to the title's DLL. +//! +//! The structures are the public FidelityFX API's (`ffx_api.h`, +//! `ffx_upscale.h`): a header of a type and a next pointer, and resources of +//! a pointer, a 32-byte description and a state. + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; + +/// The DLL whose `ffxDispatch` is taken. +pub const LOADER: &str = "amd_fidelityfx_loader_xbox.dll"; + +static REAL: AtomicUsize = AtomicUsize::new(0); + +/// The title's own `ffxDispatch`, for what is not stretched here. +pub fn set_real_dispatch(address: usize) { + REAL.store(address, Ordering::Relaxed); +} + +#[repr(C)] +struct Header { + kind: u64, + next: *const Header, +} + +#[repr(C)] +struct Resource { + resource: *const c_void, + description: [u32; 8], + state: u32, +} + +#[repr(C)] +struct Upscale { + header: Header, + list: *const c_void, + colour: Resource, + depth: Resource, + motion: Resource, + exposure: Resource, + reactive: Resource, + composition: Resource, + output: Resource, + jitter: [f32; 2], + motion_scale: [f32; 2], + render: [u32; 2], + upscale: [u32; 2], + // C++ `bool`s, read as bytes. + enable_sharpening: u8, + sharpness: f32, + frame_time_delta: f32, + pre_exposure: f32, + reset: u8, + camera_near: f32, + camera_far: f32, + camera_fov: f32, + meters: f32, + flags: u32, +} + +const _: () = assert!(size_of::<Resource>() == 48); +const _: () = assert!(std::mem::offset_of!(Upscale, output) == 0x138); + +/// `FFX_API_RETURN_ERROR`: what a dispatch nothing could answer returns. +const ERROR: u32 = 1; + +/// `FFX_API_DISPATCH_DESC_TYPE_UPSCALE`. +const UPSCALE: u64 = 0x0001_0001; + +type Dispatch = extern "system" fn(*mut *mut c_void, *const Header) -> u32; + +extern "system" fn dispatch(context: *mut *mut c_void, desc: *const Header) -> u32 { + // SAFETY: the title passes a dispatch description, whose header says + // what follows it. + if let Some(header) = unsafe { desc.as_ref() } { + static SEEN: AtomicU32 = AtomicU32::new(0); + let first = SEEN.fetch_add(1, Ordering::Relaxed) < 4; + if header.kind == UPSCALE { + // SAFETY: an upscale description, by its type. + let d = unsafe { &*desc.cast::<Upscale>() }; + if first { + tracing::info!( + list = ?d.list, + colour = ?d.colour.resource, + colour_size = ?(d.colour.description[2], d.colour.description[3]), + output = ?d.output.resource, + output_size = ?(d.output.description[2], d.output.description[3]), + render = ?d.render, + upscale = ?d.upscale, + motion = ?d.motion.resource, + depth = ?d.depth.resource, + jitter = ?d.jitter, + motion_scale = ?d.motion_scale, + sharpening = d.enable_sharpening, + sharpness = d.sharpness, + frame_ms = d.frame_time_delta, + pre_exposure = d.pre_exposure, + reset = d.reset, + near = d.camera_near, + far = d.camera_far, + fov = d.camera_fov, + meters = d.meters, + flags = format_args!("{:#x}", d.flags), + "upscale dispatch" + ); + } + // Try 6.10: how many upscales carried a jitter, every 600 (a + // temporal upscale adds detail only from jittered frames; the + // first four of the 6.7 report had none). + static JITTERED: AtomicU32 = AtomicU32::new(0); + if d.jitter != [0.0, 0.0] { + JITTERED.fetch_add(1, Ordering::Relaxed); + } + let n = SEEN.load(Ordering::Relaxed); + if n.is_multiple_of(600) { + tracing::info!( + dispatches = n, + jittered = JITTERED.load(Ordering::Relaxed), + jitter = ?d.jitter, + render = ?d.render, + upscale = ?d.upscale, + sharpening = d.enable_sharpening, + reset = d.reset, + "upscale dispatches so far (our temporal resolve)" + ); + } + #[cfg(windows)] + if victory_gpu::list::upscale_temporal( + d.list, + d.colour.resource, + d.motion.resource, + d.output.resource, + victory_gpu::list::UpscaleFrame { + render: d.render, + jitter: d.jitter, + motion_scale: d.motion_scale, + reset: d.reset != 0, + sharpness: (d.enable_sharpening != 0).then_some(d.sharpness), + pre_exposure: d.pre_exposure, + }, + ) { + return 0; + } + if first { + tracing::warn!("upscale dispatch not stretched: left to the title's upscaler"); + } + } else if first { + tracing::info!( + kind = format_args!("{:#x}", header.kind), + "another FidelityFX dispatch" + ); + } + } + match REAL.load(Ordering::Relaxed) { + // Neither stretched nor passed on: the output was not written, and + // the title is told so instead of presenting it as it is. + 0 => { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::error!( + "a FidelityFX dispatch was not answered: no stretch was recorded and the title's own ffxDispatch was not found" + ); + }); + ERROR + } + // SAFETY: the title's own `ffxDispatch`, with its own arguments. + real => unsafe { std::mem::transmute::<usize, Dispatch>(real)(context, desc) }, + } +} + +/// What the title's import of `ffxDispatch` is bound to. The DLL is not an +/// HLE module: the title's own must load, for its other entry points and +/// for the dispatches passed on. +pub fn dispatch_address() -> usize { + dispatch as *const () as usize +} + +#[cfg(test)] +mod tests { + use super::*; + use std::mem::offset_of; + + /// The upscale description as the public API lays it out: what the + /// stretch reads sits where the title wrote it. + #[test] + fn the_upscale_description_is_laid_out_as_the_public_api() { + assert_eq!(size_of::<Header>(), 16); + assert_eq!(offset_of!(Upscale, list), 0x10); + assert_eq!(offset_of!(Upscale, colour), 0x18); + assert_eq!(offset_of!(Upscale, depth), 0x48); + assert_eq!(offset_of!(Upscale, motion), 0x78); + assert_eq!(offset_of!(Upscale, output), 0x138); + assert_eq!(offset_of!(Upscale, jitter), 0x168); + assert_eq!(offset_of!(Upscale, motion_scale), 0x170); + assert_eq!(offset_of!(Upscale, render), 0x178); + assert_eq!(offset_of!(Upscale, upscale), 0x180); + assert_eq!(offset_of!(Upscale, enable_sharpening), 0x188); + assert_eq!(offset_of!(Upscale, sharpness), 0x18C); + assert_eq!(offset_of!(Upscale, pre_exposure), 0x194); + assert_eq!(offset_of!(Upscale, reset), 0x198); + assert_eq!(offset_of!(Upscale, flags), 0x1AC); + assert_eq!(offset_of!(Resource, description), 8); + assert_eq!(offset_of!(Resource, state), 40); + } + + /// A dispatch that is not an upscale, with no DLL of the title's to + /// pass it to, is an error and not a silent success. + #[test] + fn a_dispatch_nothing_answers_is_an_error() { + let before = REAL.swap(0, Ordering::Relaxed); + let other = Header { + kind: 0x0002_0001, + next: std::ptr::null(), + }; + assert_eq!(dispatch(std::ptr::null_mut(), &other), ERROR); + assert_eq!(dispatch(std::ptr::null_mut(), std::ptr::null()), ERROR); + REAL.store(before, Ordering::Relaxed); + } +} diff --git a/crates/victory-hle/src/modules/fidelityfx.rs b/crates/victory-hle/src/modules/fidelityfx.rs new file mode 100644 index 0000000000..2f7e7e6c62 --- /dev/null +++ b/crates/victory-hle/src/modules/fidelityfx.rs @@ -0,0 +1,947 @@ +//! `amd_fidelityfx_loader_xbox.dll`: AMD FidelityFX's API, served by the +//! host's PC build of it on the host GPU when the user names a folder that +//! holds one (`VICTORY_FIDELITYFX_DIR`). Without it the title's own console +//! DLLs load and our temporal resolve answers the upscale (`super::ffx`). +//! +//! From Belobug/VIctory cd8dfc06, ported there from DexNom/VIctory +//! ab34a8b2 (GPL-3.0-or-later). Try 6.10: any profile (the Series S one +//! renders 1280x720 and upscales to 1920x1080), and on cards FSR 4 does +//! not run on (NVIDIA, Intel, older Radeons) the SDK's FSR 3.1 provider. +//! +//! Both builds have the same API (the FidelityFX SDK's, MIT): five functions +//! over chains of descriptions, each starting with a type id and the next +//! one's address; contexts are opaque pointers. The console-specific parts +//! are translated: the backend description names the console device (type +//! 0x0100_0002; on PC type 2 with the host device), and a dispatch names the +//! title's command list and resources (their host list and host copies, in +//! the states the title gives, see `victory_gpu::external`). The rest passes +//! through unchanged: sizes, flags, jitter, motion-vector scale, camera +//! values, the resource descriptions, the context. Only the upscaler: other +//! effects (frame generation) are refused. +#![allow(non_snake_case)] +// Title code calls these through its import table. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::BTreeMap; +use std::ffi::{CStr, c_char, c_void}; +use std::path::Path; +use std::ptr::{null, null_mut}; +use std::sync::{Arc, Mutex, OnceLock}; + +use victory_gpu::object::Object; +use windows::Win32::Graphics::Direct3D12::ID3D12Device; +use windows::core::Interface; + +use crate::{HleModule, hle_export}; + +/// The PC build's upscaler, which has the five functions itself. +const DLL: &str = "amd_fidelityfx_upscaler_dx12.dll"; + +// Return codes. +const OK: u32 = 0; +const UNKNOWN_TYPE: u32 = 2; +const NO_PROVIDER: u32 = 4; +const PARAMETER: u32 = 6; + +// Description types. +const CREATE_UPSCALE: u64 = 0x1_0000; +const DISPATCH_UPSCALE: u64 = 0x1_0001; +const CONSOLE_BACKEND: u64 = 0x100_0002; +const HOST_BACKEND: u64 = 2; +const GET_VERSIONS: u64 = 4; +const OVERRIDE_VERSION: u64 = 5; +const GET_PROVIDER_VERSION: u64 = 6; +const MEMORY_USAGE_WITH_DEVICE: u64 = 0x1_0009; +const GET_RENDER_RESOLUTION: u64 = 0x1_0003; +const DISPLAY_RESOLUTION_MOTION_VECTORS: u32 = 1 << 1; + +#[repr(C)] +#[derive(Clone, Copy)] +struct Header { + kind: u64, + next: *mut Header, +} + +/// An upscaler context: flags, largest render and output sizes, a message +/// callback. +#[repr(C)] +#[derive(Clone, Copy)] +struct CreateUpscale { + header: Header, + flags: u32, + max_render: [u32; 2], + max_output: [u32; 2], + message: usize, +} + +/// The backend description: a device. +#[repr(C)] +struct Backend { + header: Header, + device: *mut c_void, +} + +/// A resource, its description (type, format, sizes, mips, flags, usage) +/// and the state it is in. +#[repr(C)] +#[derive(Clone, Copy)] +struct Resource { + resource: *mut c_void, + description: [u32; 8], + state: u32, +} + +/// One upscaling: the command list, then colour, depth, motion vectors, +/// exposure, reactive mask, transparency mask and output; then jitter, +/// motion-vector scale, sizes, sharpening, frame time, pre-exposure, reset, +/// camera and flags, which pass through. +#[repr(C)] +#[derive(Clone, Copy)] +struct DispatchUpscale { + header: Header, + list: *mut c_void, + resources: [Resource; 7], + jitter: [f32; 2], + motion_scale: [f32; 2], + render_size: [u32; 2], + upscale_size: [u32; 2], + settings: [u32; 10], +} + +const _: () = assert!(size_of::<CreateUpscale>() == 0x30); +const _: () = assert!(size_of::<Resource>() == 0x30); +const _: () = assert!(size_of::<DispatchUpscale>() == 0x1b0); + +/// The versions a backend offers: count in and out, ids, names. +#[repr(C)] +#[derive(Clone, Copy)] +struct GetVersions { + header: Header, + create_kind: u64, + device: *mut c_void, + count: *mut u64, + ids: *mut u64, + names: *mut *const c_char, +} + +#[repr(C)] +#[derive(Clone, Copy)] +struct MemoryUsageWithDevice { + header: Header, + device: *mut c_void, + max_render: [u32; 2], + max_output: [u32; 2], + flags: u32, + usage: *mut c_void, +} + +#[repr(C)] +struct ProviderVersion { + header: Header, + id: u64, + name: *const c_char, +} + +#[repr(C)] +struct OverrideVersion { + header: Header, + id: u64, +} + +type Create = unsafe extern "C" fn(*mut *mut c_void, *mut Header, *const c_void) -> u32; +type Destroy = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> u32; +/// Configure, query and dispatch. +type Call = unsafe extern "C" fn(*mut *mut c_void, *mut Header) -> u32; + +struct Host { + _library: Library, + create: Create, + destroy: Destroy, + configure: Call, + query: Call, + dispatch: Call, + device: ID3D12Device, + /// The providers to ask for, in order: the chosen one, then the + /// others newest first (a provider the card turns down at creation). + providers: Vec<u64>, +} + +struct Library(windows_sys::Win32::Foundation::HMODULE); + +impl Drop for Library { + fn drop(&mut self) { + // SAFETY: this owns the reference acquired by LoadLibraryExW. + unsafe { + windows_sys::Win32::Foundation::FreeLibrary(self.0); + } + } +} + +// SAFETY: D3D12 devices are free-threaded; the rest is code. +unsafe impl Send for Host {} +// SAFETY: as above. +unsafe impl Sync for Host {} + +static HOST: OnceLock<Host> = OnceLock::new(); +struct Context { + // Serializes recording and destruction for this particular temporal history. + live: Mutex<bool>, + first_dispatch: std::sync::Once, + // The FFX API requires pointers in the creation descriptor to remain + // live through destroy, including our replacement backend. + creation: CreateChain, +} + +struct CreateChain { + description: Box<CreateUpscale>, + _backend: Box<Backend>, + _version: Box<OverrideVersion>, +} + +// SAFETY: after Create, the boxed descriptors are retained immutably. +// The device is held by Host; the remaining extension pointers belong +// to the title under the FFX context lifetime contract. +unsafe impl Send for CreateChain {} +// SAFETY: as above, no thread mutates the retained descriptors. +unsafe impl Sync for CreateChain {} + +static CONTEXTS: Mutex<BTreeMap<usize, Arc<Context>>> = Mutex::new(BTreeMap::new()); + +fn fits(extent: [u32; 2], maximum: [u32; 2]) -> bool { + extent[0] != 0 && extent[1] != 0 && extent[0] <= maximum[0] && extent[1] <= maximum[1] +} + +fn dispatch_output( + render: [u32; 2], + output: [u32; 2], + max_render: [u32; 2], + max_output: [u32; 2], +) -> Option<[u32; 2]> { + let output = if output == [0, 0] { max_output } else { output }; + (fits(render, max_render) && fits(output, max_output) && fits(render, output)).then_some(output) +} + +fn minimum_extent(index: usize, flags: u32, render: [u32; 2], output: [u32; 2]) -> [u32; 2] { + match index { + 6 => output, + 2 if flags & DISPLAY_RESOLUTION_MOTION_VECTORS != 0 => output, + 3 => [1, 1], // Optional exposure texture. + _ => render, + } +} + +macro_rules! once { + ($level:ident, $($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::$level!($($arg)*)); + }}; +} + +/// Select the PC provider before the title's import registry is initialized. +pub fn use_host_dir(dir: &Path) -> Result<(), String> { + let (host, version) = load(dir)?; + HOST.set(host) + .map_err(|_| String::from("FidelityFX provider already initialized"))?; + tracing::info!(folder = %dir.display(), version, "FidelityFX: selected PC upscaler"); + Ok(()) +} + +/// Whether the host's FidelityFX serves the title's. +pub fn serving() -> bool { + HOST.get().is_some() +} + +fn load(dir: &Path) -> Result<(Host, String), String> { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, + LoadLibraryExW, + }; + // The search flags below want a full path. + let path = std::path::absolute(dir.join(DLL)).map_err(|e| e.to_string())?; + if !path.is_file() { + return Err(format!("no {DLL} there")); + } + let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect(); + // Its own folder and System32 only, never the current folder. + let search = LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32; + // SAFETY: a NUL-terminated path to the user's FidelityFX build. + let module = unsafe { LoadLibraryExW(wide.as_ptr(), null_mut(), search) }; + if module.is_null() { + return Err(format!( + "{DLL} did not load ({})", + std::io::Error::last_os_error() + )); + } + let library = Library(module); + let find = |name: &CStr| { + // SAFETY: a loaded module and a NUL-terminated name. + unsafe { GetProcAddress(module, name.as_ptr().cast()) } + .map(|f| f as *const c_void) + .ok_or_else(|| format!("{DLL} has no {}", name.to_string_lossy())) + }; + let device = victory_gpu::external::host_device().ok_or("there is no host GPU")?; + // SAFETY: the SDK's ffxQuery export, with its declared signature. + let query = unsafe { std::mem::transmute::<*const c_void, Call>(find(c"ffxQuery")?) }; + let (providers, version) = select_version(query, &device)?; + // SAFETY: the API's exports, with its signatures. + let host = unsafe { + Host { + create: std::mem::transmute::<*const c_void, Create>(find(c"ffxCreateContext")?), + destroy: std::mem::transmute::<*const c_void, Destroy>(find(c"ffxDestroyContext")?), + configure: std::mem::transmute::<*const c_void, Call>(find(c"ffxConfigure")?), + query, + dispatch: std::mem::transmute::<*const c_void, Call>(find(c"ffxDispatch")?), + _library: library, + device, + providers, + } + }; + Ok((host, version)) +} + +fn is_fsr_4_1_2(name: &str) -> bool { + name.strip_prefix("4.1.2") + .is_some_and(|suffix| !suffix.starts_with(|c: char| c.is_ascii_digit())) +} + +/// The leading version number of a provider name ("4.1.2", "FSR 3.1.5"): +/// major and minor; `None` without one. +fn version_of(name: &str) -> Option<(u32, u32)> { + let start = name.find(|c: char| c.is_ascii_digit())?; + let mut parts = name[start..].split(|c: char| !c.is_ascii_digit()); + let major = parts.next()?.parse().ok()?; + let minor = parts.next().and_then(|m| m.parse().ok()).unwrap_or(0); + Some((major, minor)) +} + +/// Which of the offered providers runs: FSR 4.1.2 first, then the newest +/// other (the SDK offers FSR 4 only where it runs; FSR 3.1 everywhere). +/// `VICTORY_FIDELITYFX_PROVIDER` names one by the start of its name. +fn pick(names: &[String], asked: Option<&str>) -> Option<usize> { + if let Some(asked) = asked.map(str::trim).filter(|a| !a.is_empty()) + && let Some(i) = names.iter().position(|n| n.starts_with(asked)) + { + return Some(i); + } + if let Some(i) = names.iter().position(|n| is_fsr_4_1_2(n)) { + return Some(i); + } + names + .iter() + .enumerate() + .filter_map(|(i, n)| version_of(n).map(|v| (v, i))) + .max_by_key(|&(v, i)| (v, std::cmp::Reverse(i))) + .map(|(_, i)| i) + .or((!names.is_empty()).then_some(0)) +} + +/// The SDK supplies the version id to put in the context creation chain. +fn select_version(query_fn: Call, device: &ID3D12Device) -> Result<(Vec<u64>, String), String> { + let mut count = 0u64; + let mut query = GetVersions { + header: Header { + kind: GET_VERSIONS, + next: null_mut(), + }, + create_kind: CREATE_UPSCALE, + device: device.as_raw(), + count: &mut count, + ids: null_mut(), + names: null_mut(), + }; + // SAFETY: a version query naming the host device. + let code = unsafe { query_fn(null_mut(), &mut query.header) }; + if code != OK || count == 0 { + return Err(format!( + "it offers no upscaler for the host GPU (code {code})" + )); + } + let mut names = vec![null::<c_char>(); count as usize]; + let mut ids = vec![0u64; names.len()]; + query.names = names.as_mut_ptr(); + query.ids = ids.as_mut_ptr(); + // SAFETY: as above, with room for `count` names. + let code = unsafe { query_fn(null_mut(), &mut query.header) }; + if code != OK { + return Err(format!( + "upscaler version names could not be queried (code {code})" + )); + } + let mut available = Vec::new(); + let mut offered = Vec::new(); + for (id, name) in ids.into_iter().zip(names).take(count as usize) { + if !name.is_null() { + // SAFETY: NUL-terminated name owned by the SDK. + let name = unsafe { CStr::from_ptr(name) } + .to_string_lossy() + .into_owned(); + offered.push(id); + available.push(name); + } + } + let asked = std::env::var("VICTORY_FIDELITYFX_PROVIDER").ok(); + let Some(i) = pick(&available, asked.as_deref()) else { + return Err(String::from("it named no upscaler for the host GPU")); + }; + tracing::info!( + available = available.join(", "), + chosen = %available[i], + "FidelityFX: upscalers the PC build offers for this card" + ); + // The others after it, newest first. + let mut rest: Vec<usize> = (0..available.len()).filter(|&k| k != i).collect(); + rest.sort_by_key(|&k| std::cmp::Reverse(version_of(&available[k]))); + let order = std::iter::once(i).chain(rest).map(|k| offered[k]).collect(); + Ok((order, available[i].clone())) +} + +/// Puts the host backend after the title's upscaler description, in place +/// of the console's backend that follows it (where the title puts it); +/// anywhere else the console's is left for the host DLL to ignore, ours +/// coming first. +fn link(upscale: &mut CreateUpscale, backend: &mut Backend) { + let after = upscale.header.next; + // SAFETY: the title's chain. + backend.header.next = match unsafe { after.as_ref() } { + Some(h) if h.kind == CONSOLE_BACKEND => h.next, + _ => after, + }; + backend.header.kind = HOST_BACKEND; + upscale.header.next = &raw mut backend.header; +} + +/// A FidelityFX resource state as the host resource state it means (as the +/// PC backend reads it); `None` for generic read and indirect arguments, +/// which a host texture cannot be in. +fn host_state(state: u32) -> Option<u32> { + Some(match state { + 0x1 | 0x80 => 0, // common, present + 0x2 => 0x8, // unordered access + 0x4 => 0x40, // compute read + 0x8 => 0x80, // pixel read + 0xc => 0xc0, // both + 0x10 => 0x800, // copy source + 0x20 => 0x400, // copy destination + 0x100 => 0x4, // render target + 0x200 => 0x10, // depth write + _ => return None, // generic read, indirect arguments + }) +} + +extern "C" fn ffxCreateContext( + context: *mut *mut c_void, + desc: *mut Header, + memory: *const c_void, +) -> u32 { + let Some(host) = HOST.get() else { + return NO_PROVIDER; + }; + if context.is_null() || desc.is_null() { + return PARAMETER; + } + // SAFETY: the title passes a chain of descriptions. + let kind = unsafe { (*desc).kind }; + if kind != CREATE_UPSCALE { + once!( + warn, + kind = format_args!("{kind:#x}"), + "FidelityFX: only the upscaler runs on the host; another effect was refused" + ); + return NO_PROVIDER; + } + // SAFETY: an upscaler description, by its type. + let mut upscale = Box::new(unsafe { desc.cast::<CreateUpscale>().read() }); + let mut backend = Box::new(Backend { + header: Header { + kind: HOST_BACKEND, + next: null_mut(), + }, + device: host.device.as_raw(), + }); + link(&mut upscale, &mut backend); + let mut requested = Box::new(OverrideVersion { + header: Header { + kind: OVERRIDE_VERSION, + next: backend.header.next, + }, + id: 0, + }); + backend.header.next = &raw mut requested.header; + let mut code = NO_PROVIDER; + for &id in &host.providers { + requested.id = id; + // SAFETY: a PC chain; the title's later descriptions live for the call. + code = unsafe { (host.create)(context, &mut upscale.header, memory) }; + if code == OK { + break; + } + tracing::warn!(code, id = format_args!("{id:#x}"), render = ?upscale.max_render, output = ?upscale.max_output, flags = format_args!("{:#x}", upscale.flags), "FidelityFX: the host turned down this provider for the title's upscaler"); + } + if code != OK { + tracing::error!(code, "FidelityFX: the host refused the title's upscaler with every provider"); + return code; + } + let mut version = ProviderVersion { + header: Header { + kind: GET_PROVIDER_VERSION, + next: null_mut(), + }, + id: 0, + name: null(), + }; + // SAFETY: a provider query on the context just made. + let query_code = unsafe { (host.query)(context, &mut version.header) }; + // SAFETY: a NUL-terminated name the DLL keeps, if any. + let name = (!version.name.is_null()) + .then(|| unsafe { CStr::from_ptr(version.name) }.to_string_lossy()); + if query_code != OK || version.id != requested.id { + tracing::warn!( + query_code, + provider = name.as_deref().unwrap_or("?"), + asked = format_args!("{:#x}", requested.id), + "FidelityFX created another provider than the one asked for; it runs" + ); + } + // SAFETY: a successful SDK creation wrote an opaque context into this slot. + tracing::info!( + provider = name.as_deref().unwrap_or("?"), + id = format_args!("{:#x}", version.id), + render = ?upscale.max_render, + output = ?upscale.max_output, + flags = format_args!("{:#x}", upscale.flags), + "FidelityFX: upscaler context on the host" + ); + CONTEXTS.lock().unwrap_or_else(|e| e.into_inner()).insert( + unsafe { *context } as usize, + Arc::new(Context { + live: Mutex::new(true), + first_dispatch: std::sync::Once::new(), + creation: CreateChain { + description: upscale, + _backend: backend, + _version: requested, + }, + }), + ); + OK +} + +extern "C" fn ffxDestroyContext(context: *mut *mut c_void, memory: *const c_void) -> u32 { + let Some(host) = HOST.get() else { + return NO_PROVIDER; + }; + if context.is_null() { + return PARAMETER; + } + // SAFETY: the title passes its context. Capture its value before destroy clears it. + let handle = unsafe { *context } as usize; + let ctx = CONTEXTS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(&handle) + .cloned(); + let Some(ctx) = ctx else { return PARAMETER }; + let mut live = ctx.live.lock().unwrap_or_else(|e| e.into_inner()); + if !*live { + return PARAMETER; + } + // The guest releases a context after submitting its frames. The host + // may still be executing their lists, even after guest Execute returns. + victory_gpu::external::finish_submitted(); + let code = unsafe { (host.destroy)(context, memory) }; + if code == OK { + *live = false; + let mut contexts = CONTEXTS.lock().unwrap_or_else(|e| e.into_inner()); + // A concurrent Create may already have reused the released SDK address. + if contexts + .get(&handle) + .is_some_and(|current| Arc::ptr_eq(current, &ctx)) + { + contexts.remove(&handle); + } + } + code +} + +/// Settings (key-value pairs, debug messages) name nothing console-specific. +extern "C" fn ffxConfigure(context: *mut *mut c_void, desc: *mut Header) -> u32 { + // SAFETY: the title passes its context and descriptions. + HOST.get() + .map_or(NO_PROVIDER, |h| unsafe { (h.configure)(context, desc) }) +} + +extern "C" fn ffxQuery(context: *mut *mut c_void, desc: *mut Header) -> u32 { + let Some(host) = HOST.get() else { + return NO_PROVIDER; + }; + if desc.is_null() { + return PARAMETER; + } + // SAFETY: the title passes a description. + let kind = unsafe { (*desc).kind }; + // Substitute the native device; the SDK returns values through the + // title's original output pointers in both request structures. + if kind == GET_VERSIONS { + let mut query = unsafe { *desc.cast::<GetVersions>() }; + query.device = host.device.as_raw(); + return unsafe { (host.query)(context, &mut query.header) }; + } + if kind == MEMORY_USAGE_WITH_DEVICE { + let mut query = unsafe { *desc.cast::<MemoryUsageWithDevice>() }; + query.device = host.device.as_raw(); + return unsafe { (host.query)(context, &mut query.header) }; + } + // SAFETY: as above. + let code = unsafe { (host.query)(context, desc) }; + if kind == GET_RENDER_RESOLUTION && code != OK { + tracing::warn!( + code, + "FidelityFX provider refused the render-resolution query" + ); + } + code +} + +extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 { + let Some(host) = HOST.get() else { + return NO_PROVIDER; + }; + if desc.is_null() { + return PARAMETER; + } + // SAFETY: the title passes a description. + let kind = unsafe { (*desc).kind }; + if kind != DISPATCH_UPSCALE { + once!( + warn, + kind = format_args!("{kind:#x}"), + "FidelityFX: only upscaling runs on the host; a dispatch was refused" + ); + return UNKNOWN_TYPE; + } + // SAFETY: an upscaling, by its type. + let mut dispatch = unsafe { desc.cast::<DispatchUpscale>().read() }; + if context.is_null() { + once!(warn, "FidelityFX dispatch arrived without a context"); + return PARAMETER; + } + if let Some(index) = [0, 1, 2, 6] + .into_iter() + .find(|&i| dispatch.resources[i].resource.is_null()) + { + once!( + warn, + index, + "FidelityFX dispatch is missing a required texture" + ); + return PARAMETER; + } + // SAFETY: the title passes the same opaque context slot as for creation. + let handle = unsafe { *context } as usize; + let ctx = CONTEXTS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(&handle) + .cloned(); + let Some(ctx) = ctx else { + once!( + warn, + "FidelityFX dispatch referenced an unregistered context" + ); + return PARAMETER; + }; + let live = ctx.live.lock().unwrap_or_else(|e| e.into_inner()); + if !*live { + return PARAMETER; + } + let create = &ctx.creation.description; + let Some(output_size) = dispatch_output( + dispatch.render_size, + dispatch.upscale_size, + create.max_render, + create.max_output, + ) else { + once!(warn, render = ?dispatch.render_size, output = ?dispatch.upscale_size, + max_render = ?create.max_render, max_output = ?create.max_output, + "FidelityFX rejected dispatch dimensions outside the context's allocations"); + return if ours_instead(&dispatch) { OK } else { PARAMETER }; + }; + let original = dispatch; + let list = dispatch.list.cast::<Object>().cast_const(); + let code = victory_gpu::external::record(list, |list| { + record_dispatch(list, host, context, &ctx, &mut dispatch, output_size) + }) + .unwrap_or_else(|| { + once!( + warn, + "FidelityFX could not record to the title command list" + ); + PARAMETER + }); + drop(live); + if code != OK && ours_instead(&original) { + return OK; + } + code +} + +/// Our temporal resolve (`victory_gpu::list::upscale_temporal`, as +/// `super::ffx` does without the PC build) for a dispatch the PC upscaler +/// did not record: the output is made all the same, not left black. +fn ours_instead(d: &DispatchUpscale) -> bool { + let s = &d.settings; + let done = victory_gpu::list::upscale_temporal( + d.list.cast_const(), + d.resources[0].resource.cast_const(), + d.resources[2].resource.cast_const(), + d.resources[6].resource.cast_const(), + victory_gpu::list::UpscaleFrame { + render: d.render_size, + jitter: d.jitter, + motion_scale: d.motion_scale, + reset: s[4] & 0xff != 0, + sharpness: (s[0] & 0xff != 0).then_some(f32::from_bits(s[1])), + pre_exposure: f32::from_bits(s[3]), + }, + ); + if done { + once!(warn, "FidelityFX: a dispatch the PC upscaler did not record was made by our temporal resolve instead"); + } + done +} + +fn record_dispatch( + list: &victory_gpu::external::Recording<'_>, + host: &Host, + context: *mut *mut c_void, + ctx: &Context, + dispatch: &mut DispatchUpscale, + output_size: [u32; 2], +) -> u32 { + let output = dispatch.resources[6].resource.cast::<Object>(); + // Alive for the call (the list holds them too). + let mut textures = Vec::new(); + let mut backing_extents = [None; 7]; + for (index, r) in dispatch.resources.iter_mut().enumerate() { + if r.resource.is_null() { + continue; + } + if index < 6 && list.prepare_input(r.resource.cast::<Object>()).is_none() { + once!( + warn, + index, + "FidelityFX input could not be prepared on the title command list" + ); + return PARAMETER; + } + let wanted = host_state(r.state); + let texture = wanted.and_then(|w| { + list.texture(r.resource.cast::<Object>(), w) + .filter(|&(_, state)| state == w) + }); + let Some((texture, _)) = texture else { + once!( + warn, + index, + state = r.state, + "FidelityFX: a resource has no host texture in its state; the upscaling did not run" + ); + return PARAMETER; + }; + let desc = unsafe { texture.GetDesc() }; + backing_extents[index] = Some((desc.Width, desc.Height)); + let needed = minimum_extent( + index, + ctx.creation.description.flags, + dispatch.render_size, + output_size, + ); + if desc.Width < u64::from(needed[0]) || desc.Height < needed[1] { + once!( + warn, + index, + ?needed, + width = desc.Width, + height = desc.Height, + "FidelityFX resource cannot cover the active dispatch rectangle" + ); + return PARAMETER; + } + r.resource = texture.as_raw(); + textures.push(texture); + } + once!(info, formats = ?textures.iter().map(|t| { + // SAFETY: a live texture. + unsafe { t.GetDesc() }.Format.0 + }).collect::<Vec<_>>(), "FidelityFX: first upscaling, host formats of its textures"); + dispatch.list = list.commands().as_raw(); + // SAFETY: the PC dispatch on host objects. The context is live and locked. + let code = unsafe { (host.dispatch)(context, &raw mut dispatch.header) }; + if code == OK { + victory_gpu::external::output_written(output); + // Try 6.10: every 600 upscales, how many carried a jitter (FSR adds + // detail only from jittered frames). + static DONE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + static JITTERED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + use std::sync::atomic::Ordering::Relaxed; + if dispatch.jitter != [0.0, 0.0] { + JITTERED.fetch_add(1, Relaxed); + } + let n = DONE.fetch_add(1, Relaxed) + 1; + if n.is_multiple_of(600) { + tracing::info!(upscales = n, jittered = JITTERED.load(Relaxed), jitter = ?dispatch.jitter, + render = ?dispatch.render_size, output = ?output_size, "FidelityFX (PC): upscales so far"); + } + ctx.first_dispatch.call_once(|| { + tracing::info!(render = ?dispatch.render_size, output = ?output_size, ?backing_extents, + jitter = ?dispatch.jitter, motion_vector_scale = ?dispatch.motion_scale, + "FidelityFX (PC) recorded the title's temporal dispatch"); + }); + } else { + once!( + warn, + code, + "FidelityFX (PC) provider rejected the title dispatch" + ); + } + code +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "fidelityfx", + dlls: &["amd_fidelityfx_loader_xbox.dll"], + exports: vec![ + hle_export!(ffxConfigure), + hle_export!(ffxCreateContext), + hle_export!(ffxDestroyContext), + hle_export!(ffxDispatch), + hle_export!(ffxQuery), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validates_logical_rectangles_against_the_current_context() { + for display in [[1920, 1080], [2560, 1440], [3840, 2160]] { + for divisor in [1.0_f32, 1.5, 1.7, 2.0, 3.0] { + let render = display.map(|v| (v as f32 / divisor) as u32); + assert_eq!( + dispatch_output(render, display, render, display), + Some(display) + ); + assert_eq!( + dispatch_output(render, [0, 0], render, display), + Some(display) + ); + assert_eq!(minimum_extent(2, 0x29, render, display), render); + assert_eq!(minimum_extent(2, 0x2b, render, display), display); + assert_eq!(minimum_extent(6, 0x29, render, display), display); + assert_eq!(minimum_extent(3, 0x29, render, display), [1, 1]); + } + } + assert_eq!( + dispatch_output([0, 720], [0, 0], [1280, 720], [2560, 1440]), + None + ); + assert_eq!( + dispatch_output([1281, 720], [0, 0], [1280, 720], [2560, 1440]), + None + ); + assert_eq!( + dispatch_output([1280, 720], [0, 1440], [1280, 720], [2560, 1440]), + None + ); + assert_eq!( + dispatch_output([1280, 720], [3000, 1440], [1280, 720], [2560, 1440]), + None + ); + assert_eq!( + dispatch_output([1280, 720], [960, 540], [1280, 720], [2560, 1440]), + None + ); + } + + fn header(kind: u64, next: *mut Header) -> Header { + Header { kind, next } + } + + /// The title's chain: upscaler, console backend, version. + #[test] + fn the_console_backend_becomes_the_hosts() { + let mut version = header(0x1_000b, null_mut()); + let mut console = Backend { + header: header(CONSOLE_BACKEND, &raw mut version), + device: 0x1234 as *mut c_void, + }; + let mut upscale = CreateUpscale { + header: header(CREATE_UPSCALE, &raw mut console.header), + flags: 0x29, + max_render: [1280, 720], + max_output: [1920, 1080], + message: 0, + }; + let mut backend = Backend { + header: header(0, null_mut()), + device: 0x5678 as *mut c_void, + }; + link(&mut upscale, &mut backend); + assert_eq!(upscale.header.next, &raw mut backend.header); + assert_eq!(backend.header.kind, HOST_BACKEND); + assert_eq!(backend.header.next, &raw mut version); + assert_eq!(backend.device, 0x5678 as *mut c_void); + // Without a console backend right after it, ours goes in front. + let mut upscale = CreateUpscale { + header: header(CREATE_UPSCALE, &raw mut version), + ..upscale + }; + link(&mut upscale, &mut backend); + assert_eq!(backend.header.next, &raw mut version); + } + + /// Without the PC build the title's own DLL serves its imports. + #[test] + fn without_the_dll_the_titles_own_runs() { + let dir = tempfile::tempdir().unwrap(); + assert!(load(dir.path()).err().unwrap().contains(DLL)); + assert!(!serving()); + let symbol = victory_pe::ImportSymbol::Name { + hint: 0, + name: "ffxCreateContext".into(), + }; + let resolver = crate::HleResolver::new(crate::HostPolicy::none()); + assert_eq!( + resolver.classify("amd_fidelityfx_loader_xbox.dll", &symbol), + None + ); + } + + #[test] + fn the_newest_provider_runs_unless_one_is_named() { + let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>(); + // FSR 4.1.2 where the card runs it. + assert_eq!(pick(&names(&["3.1.5", "4.1.2"]), None), Some(1)); + // Elsewhere the newest the SDK offers. + assert_eq!(pick(&names(&["FSR 3.1.4", "FSR 3.1.5"]), None), Some(0)); + assert_eq!(pick(&names(&["3.0.4", "3.1.5"]), None), Some(1)); + assert_eq!(pick(&names(&["3.1.5", "4.0.3"]), None), Some(1)); + assert_eq!(pick(&names(&["3.1.5", "4.0.3"]), Some("3.1")), Some(0)); + assert_eq!(pick(&names(&["mystery"]), None), Some(0)); + assert_eq!(pick(&[], None), None); + assert_eq!(version_of("FSR 3.1.5"), Some((3, 1))); + assert_eq!(version_of("4"), Some((4, 0))); + } + + #[test] + fn resource_states_read_as_the_pc_backend_reads_them() { + assert_eq!(host_state(0xc), Some(0xc0)); + assert_eq!(host_state(0x2), Some(0x8)); + assert_eq!(host_state(0x200), Some(0x10)); + assert_eq!(host_state(0x14), None); + } +} diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index fea5c285c4..d13c3bc271 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -21,7 +21,6 @@ use std::sync::{Mutex, MutexGuard}; use windows_sys::Win32::Globalization::{CP_ACP, MultiByteToWideChar}; use windows_sys::Win32::Storage::FileSystem::GetLogicalDrives; -use crate::modules::paths; use crate::{HleExport, HleModule, hle_export}; /// The host's own function: what the import would have been bound to. @@ -84,28 +83,97 @@ pub fn mount_at(letter: char, root: &Path) { } /// `root` as UTF-16, absolute, without trailing separators (a drive root -/// keeps its own). An empty root is the current directory, as it is to a -/// path joined to it: it is the title's folder when the title is run by its -/// file name alone (`victory run GTA6.exe`). +/// keeps its own). fn root_wide(root: &Path) -> Vec<u16> { - let root = if root.as_os_str().is_empty() { - Path::new(".") - } else { - root - }; let root = std::path::absolute(root).unwrap_or_else(|_| root.to_owned()); let mut wide: Vec<u16> = root.as_os_str().encode_wide().collect(); - while wide.len() > 3 && wide.last().is_some_and(|c| paths::SEPARATORS.contains(c)) { + while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) { wide.pop(); } wide } +const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16]; +const VERBATIM: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]; + +/// Host paths from this length on take the `\\?\` form, which lifts the +/// host's MAX_PATH limit (248 characters for a directory, 260 for a file). +const LONG: usize = 248; + +/// `root` and the title's `tail` as a `\\?\` path. That form turns off the +/// host's own clean-up, so `/` becomes `\` and `.` and `..` are resolved +/// here (`..` stops at the root). +fn verbatim(root: &[u16], tail: &[u16]) -> Vec<u16> { + let backslash = u16::from(b'\\'); + let mut out = if root.starts_with(&VERBATIM) { + root.to_vec() + } else if let Some(unc) = root.strip_prefix(&[backslash; 2][..]) { + let mut out = VERBATIM.to_vec(); + out.extend("UNC\\".encode_utf16()); + out.extend_from_slice(unc); + out + } else { + [&VERBATIM[..], root].concat() + }; + while out.last() == Some(&backslash) { + out.pop(); + } + let dot = u16::from(b'.'); + let mut parts: Vec<&[u16]> = Vec::new(); + for part in tail.split(|c| SEPARATORS.contains(c)) { + match part { + [] => {} + [d] if *d == dot => {} + [d, e] if [*d, *e] == [dot; 2] => drop(parts.pop()), + _ => parts.push(part), + } + } + for part in parts { + out.push(backslash); + out.extend_from_slice(part); + } + out +} + /// The host path, NUL-terminated, for `path` (without its NUL) if it is on -/// a virtual drive. The lexical rules are host-independent so CI tests -/// them; only the mounted drives come from here. +/// a virtual drive. pub(crate) fn translate(path: &[u16]) -> Option<Vec<u16>> { - paths::translate(path, &drives()) + let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) { + Some(rest) => (&VERBATIM[..], rest), + None => (&[][..], path), + }; + let &[letter, colon, ..] = rest else { + return None; + }; + if colon != u16::from(b':') { + return None; + } + let letter = u8::try_from(letter).ok().filter(u8::is_ascii_alphabetic)?; + let letter = u16::from(letter.to_ascii_uppercase()); + let drives = drives(); + let (_, root) = drives.iter().find(|(l, _)| *l == letter)?; + let tail = &rest[2..]; + if prefix.is_empty() && root.len() + tail.len() >= LONG { + let mut out = verbatim(root, tail); + out.push(0); + return Some(out); + } + let mut out = prefix.to_vec(); + out.extend_from_slice(root); + // `X:` and `X:name` are relative to the root. + if !tail.first().is_some_and(|c| SEPARATORS.contains(c)) { + out.push(b'\\'.into()); + } + let verbatim = !prefix.is_empty(); + out.extend(tail.iter().map(|&c| { + if verbatim && c == u16::from(b'/') { + b'\\'.into() + } else { + c + } + })); + out.push(0); + Some(out) } /// A title's wide path: the host path when it is on a virtual drive, else @@ -150,9 +218,12 @@ fn narrow(path: *const c_char) -> Option<Vec<u16>> { // SAFETY: the title passes a NUL-terminated path. let bytes = unsafe { CStr::from_ptr(path) }.to_bytes(); // The drive part is ASCII in every code page; decode only candidates. - if !paths::has_drive(bytes) { - tracing::debug!(path = %String::from_utf8_lossy(bytes), "title path"); - return None; + match bytes.strip_prefix(br"\\?\").unwrap_or(bytes) { + [letter, b':', ..] if letter.is_ascii_alphabetic() => {} + _ => { + tracing::debug!(path = %String::from_utf8_lossy(bytes), "title path"); + return None; + } } let len = i32::try_from(bytes.len()).ok()?; // SAFETY: sizing call, then a call with room for `n` units. @@ -354,7 +425,7 @@ pub extern "system" fn GetDiskFreeSpaceW( if let Some(host) = &mut p.1 && let [letter, colon, sep, ..] = host[..] && colon == u16::from(b':') - && paths::SEPARATORS.contains(&sep) + && SEPARATORS.contains(&sep) { *host = vec![letter, colon, sep, 0]; } @@ -445,10 +516,13 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi // Kernel reads into title memory. The GPU side leaves blocks of title GPU // buffers read-only to see the title's next write, and the kernel's writes -// fail there instead of faulting into its handler; Grand Theft Auto VI's +// fail there instead of faulting into its handler; the title's // synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned // destinations and retry a failed `ReadFile` forever. So the destination -// is opened first. +// is opened first. A block guarded again before the kernel writes it (the +// guard over all the views of a page protects other views from other +// threads) fails that `ReadFile`, and the title's retry opens it again; +// `fread` has no such retry and reads beside instead (see there). pub extern "system" fn ReadFile( file: *mut c_void, @@ -463,12 +537,38 @@ pub extern "system" fn ReadFile( ) } -/// The host CRT reads large requests straight into the caller's buffer. +/// The host CRT reads large requests straight into the caller's buffer +/// through the kernel, whose write fails on a guarded block instead of +/// faulting into the guard. So the bytes are read beside, a chunk at a time +/// (a caller may ask for far more than the file holds), and copied in from +/// user mode, where a guarded block faults into the guard like the title's +/// own writes. Returns the items read, as the CRT does; the bytes of a +/// partial last item are copied too, as the CRT leaves them. pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize { - victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count)); - host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)( - buffer, size, count, stream, - ) + let read = host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize); + let total = size.saturating_mul(count); + if buffer.is_null() || total == 0 { + // The CRT's own checks and answer (EINVAL, or nothing to read). + return read(buffer, size, count, stream); + } + const CHUNK: usize = 1 << 20; + let mut beside = vec![0u8; total.min(CHUNK)]; + let mut done = 0; + while done < total { + let want = (total - done).min(CHUNK); + let n = read(beside.as_mut_ptr(), 1, want, stream); + if n > 0 { + victory_gpu::kernel_will_write(buffer as usize + done, n); + // SAFETY: the caller's buffer holds `size * count` bytes, and + // `done + n` is at most that. + unsafe { std::ptr::copy_nonoverlapping(beside.as_ptr(), buffer.add(done), n) }; + done += n; + } + if n < want { + break; + } + } + done / size } pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File { @@ -676,13 +776,44 @@ mod tests { let file = std::fs::File::open(&path).unwrap(); let (mut out, mut n) = ([0u8; 10], 0); let handle = file.as_raw_handle().cast(); - assert_ne!( - ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), - 0 - ); + assert_ne!(ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), 0); assert_eq!((&out, n), (b"0123456789", 10)); } + #[test] + fn fread_reads_beside_in_chunks() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + // Over two chunks, and not a whole number of 3-byte items. + let bytes: Vec<u8> = (0..(5 << 19) + 1).map(|i| (i * 7 + i / 251) as u8).collect(); + std::fs::write(&path, &bytes).unwrap(); + let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32); + let open = || { + let f = _wfopen(w(&path.to_string_lossy()).as_ptr(), w("rb").as_ptr()); + assert!(!f.is_null()); + f + }; + + // Asked for far more than the file holds: the whole file, in items. + let f = open(); + let mut out = vec![0xaau8; bytes.len() + 64]; + let items = fread(out.as_mut_ptr(), 3, out.len() / 3, f); + assert_eq!(items, bytes.len() / 3); + assert_eq!(&out[..bytes.len()], &bytes[..], "the partial last item's bytes too"); + assert!(out[bytes.len()..].iter().all(|&b| b == 0xaa), "nothing past what was read"); + fclose(f); + + // Exact reads continue where the last one stopped. + let f = open(); + let mut a = vec![0u8; 1000]; + let mut b = vec![0u8; (1 << 20) + 5]; + assert_eq!(fread(a.as_mut_ptr(), 1000, 1, f), 1); + assert_eq!(fread(b.as_mut_ptr(), 1, b.len(), f), b.len()); + assert_eq!(a, bytes[..1000]); + assert_eq!(b, bytes[1000..1000 + b.len()]); + fclose(f); + } + fn text(v: &[u16]) -> String { String::from_utf16_lossy(&v[..v.len() - 1]) } @@ -731,22 +862,11 @@ mod tests { Some(format!(r"\\?\{}\a\{long}\f", package.path().display())) ); assert_eq!( - paths::verbatim(&w(r"\\server\share\")[..15], &w("/x/../../y")[..10]), + verbatim(&w(r"\\server\share\")[..15], &w("/x/../../y")[..10]), w(r"\\?\UNC\server\share\y")[..22].to_vec() ); } - /// A title run by its file name alone has an empty folder: the drive - /// over it is the current directory, not the current drive's root. - #[test] - fn an_empty_root_is_the_current_directory() { - let letter = mount(Path::new("")).unwrap(); - let path = format!(r"{letter}:\a.rpf"); - let host = translate(&w(&path)[..path.len()]).map(|v| text(&v)); - let cwd = std::env::current_dir().unwrap(); - assert_eq!(host, Some(cwd.join("a.rpf").display().to_string())); - } - #[test] fn long_title_paths_work_on_the_host() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index b5d77b305a..838826e110 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -17,7 +17,6 @@ use std::sync::{Condvar, LazyLock, Mutex, MutexGuard, PoisonError}; use std::thread::ThreadId; use std::time::{Duration, Instant}; -use super::release_ref; use super::xasync::{E_INVALIDARG, E_NOTIMPL}; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleExport, HleModule}; @@ -59,17 +58,16 @@ const KEYBOARD: usize = PADS + 1; const DEVICES: usize = PADS + 2; /// Readings kept per device for next/previous lookups. -const HISTORY: usize = 32; +const HISTORY: usize = 256; const POLL: Duration = Duration::from_millis(8); /// The keyboard's stand-in gamepad (virtual key, button); README lists it. /// Sticks: W/A/S/D left, I/J/K/L right; triggers Z and C. -const FALLBACK_BUTTONS: [(u8, u32); 15] = [ +const FALLBACK_BUTTONS: [(u8, u32); 14] = [ (0x1B, MENU), // Esc (0x09, VIEW), // Tab (0x0D, A), // Enter (0x08, B), // Backspace - (b'O', B), // Circle, for PlayStation players (b'X', X), (b'Y', Y), (0x26, UP), // arrows @@ -95,18 +93,6 @@ struct PadState { right_y: f32, } -/// Motor speeds for one pad, each 0 (off) to `u16::MAX` (full), in the -/// order of the title's four rumble levels. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -struct Motors { - /// Low frequency, in the left grip. - low: u16, - /// High frequency, in the right grip. - high: u16, - left_trigger: u16, - right_trigger: u16, -} - /// One key held down: scan code (0xE0xx when extended), character, key. #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -125,9 +111,8 @@ trait Source: Send { fn pad(&mut self, slot: usize) -> Option<PadState>; /// Keys held down; none while the title's window lacks focus. fn keys(&mut self) -> Vec<KeyState>; - /// Motor speeds for the pad in host slot `slot`; a host without - /// trigger motors drops those two. - fn rumble(&mut self, slot: usize, motors: Motors); + /// Motor speeds: low frequency (left), high frequency (right). + fn rumble(&mut self, slot: usize, low: u16, high: u16); } fn fallback(keys: &[KeyState]) -> PadState { @@ -340,10 +325,6 @@ struct State { pending: Vec<Event>, /// Device callbacks running now: token and thread. running: Vec<(u64, ThreadId)>, - /// Host slots that have reported input at least once. A wireless receiver - /// answers for its pad while the pad is off, with an all-zero report; that - /// slot is not a pad until something is actually pressed. - seen_input: [bool; PADS], } pub struct Hub { @@ -388,7 +369,6 @@ impl Hub { callbacks: Vec::new(), pending: Vec::new(), running: Vec::new(), - seen_input: [false; PADS], }), returned: Condvar::new(), })); @@ -474,16 +454,6 @@ impl State { ) -> Vec<Event> { let now = now(); let mut events = std::mem::take(&mut self.pending); - // A slot that has never reported input is not a pad: a wireless receiver keeps - // answering for a pad that is switched off, and its all-zero report used to hide the - // keyboard's stand-in, leaving the keyboard dead with no pad in hand. - let pads: [Option<PadState>; PADS] = std::array::from_fn(|slot| { - let pad = pads[slot]?; - if pad != PadState::default() { - self.seen_input[slot] = true; - } - self.seen_input[slot].then_some(pad) - }); let any_pad = pads.iter().any(Option::is_some); for (slot, pad) in pads.into_iter().enumerate() { self.update(devices, slot, pad.map(Value::Pad), now, &mut events); @@ -555,7 +525,7 @@ fn host() -> Box<dyn Source> { fn keys(&mut self) -> Vec<KeyState> { Vec::new() } - fn rumble(&mut self, _: usize, _: Motors) {} + fn rumble(&mut self, _: usize, _: u16, _: u16) {} } Box::new(Nothing) } @@ -651,8 +621,7 @@ extern "system" fn current_reading( hand(out, found) } -/// The reading after (`forward`) or before `reference`: on `device`, or with -/// none given on any device, in time order (ties by device, then sequence). +/// The reading after (`forward`) or before `reference` on its device. fn relative( this: This, reference: *const Reading, @@ -667,6 +636,9 @@ fn relative( let hub = hub(this); // SAFETY: a reading we handed out and the title still holds. let reference = unsafe { &*reference }; + // shortcut: with no device given only the reference's device is walked, + // not every device's readings in time order; the title walks + // only keyboard readings (one device) and the current pad's previous one. let Some(index) = hub.index(reference.device) else { return fail(out, E_INVALIDARG); }; @@ -674,38 +646,27 @@ fn relative( return fail(out, E_INVALIDARG); } let state = hub.state(); - if state.slots[index] - .history + let history = &state.slots[index].history; + if history .front() .is_none_or(|oldest| reference.sequence < oldest.sequence) { return fail(out, REFERENCE_TOO_OLD); } - // On one device this order is its sequence order. - let at = (reference.timestamp, index, reference.sequence); - let devices = if device.is_null() { - 0..DEVICES - } else { - index..index + 1 - }; - let candidates = devices - .flat_map(|i| { - let history = &state.slots[i].history; - history - .iter() - .map(move |r| ((r.timestamp, i, r.sequence), r)) - }) - .filter(|(_, r)| r.kind() & kind != 0); + let wanted = |r: &&Ref| r.kind() & kind != 0; let found = if forward { - candidates - .filter(|(key, _)| *key > at) - .min_by_key(|(key, _)| *key) + history + .iter() + .filter(|r| r.sequence > reference.sequence) + .find(wanted) } else { - candidates - .filter(|(key, _)| *key < at) - .max_by_key(|(key, _)| *key) + history + .iter() + .rev() + .filter(|r| r.sequence < reference.sequence) + .find(wanted) }; - hand(out, found.map(|(_, r)| r)) + hand(out, found) } extern "system" fn next_reading( this: This, @@ -751,7 +712,7 @@ fn token(out: *mut u64) -> HRESULT { S_OK } -// shortcut: reading callbacks never run; Grand Theft Auto VI registers none +// shortcut: reading callbacks never run; the title registers none // (it polls). extern "system" fn register_reading( _: This, @@ -857,10 +818,7 @@ extern "system" fn unregister_callback(this: This, token: u64, timeout: u64) -> return true; } state = match deadline { - None => hub - .returned - .wait(state) - .unwrap_or_else(PoisonError::into_inner), + None => hub.returned.wait(state).unwrap_or_else(PoisonError::into_inner), Some(deadline) => { let Some(left) = deadline.checked_duration_since(Instant::now()) else { return false; @@ -950,28 +908,24 @@ extern "system" fn device_status(this: *const Device) -> u32 { 0 } } -// Grand Theft Auto VI sends trigger levels in slot 0x50; all four reach the -// host, which drops the trigger motors (see `host::Host::rumble`). +// shortcut: trigger motors are dropped (XInput has none). The host API that +// drives them without a redistributable is Windows.Gaming.Input (WinRT +// `Gamepad.Vibration`), which needs WinRT bindings this crate lacks outside +// diagnostics builds; the title sends trigger levels in slot 0x50. extern "system" fn set_rumble(this: *const Device, params: *const [f32; 4]) { // SAFETY: one of our devices. let device = unsafe { &*this }; if device.index >= PADS { return; } - let [low, high, left_trigger, right_trigger] = if params.is_null() { + let [low, high, ..] = if params.is_null() { [0.0; 4] } else { // SAFETY: checked non-null; four motor levels. unsafe { *params } }; let speed = |level: f32| (level.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; - let motors = Motors { - low: speed(low), - high: speed(high), - left_trigger: speed(left_trigger), - right_trigger: speed(right_trigger), - }; - lock(&device.hub().source).rumble(device.index, motors); + lock(&device.hub().source).rumble(device.index, speed(low), speed(high)); } extern "system" fn unsupported<const SLOT: usize>(_: *const c_void) -> HRESULT { tracing::warn!( @@ -1013,12 +967,12 @@ extern "system" fn reading_add_ref(this: *const Reading) -> u32 { reading(this).refs.fetch_add(1, Ordering::Relaxed) + 1 } extern "system" fn reading_release(this: *const Reading) -> u32 { - let left = release_ref(&reading(this).refs, "input reading"); - if left == Some(0) { + let left = reading(this).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { // SAFETY: the last reference is gone; `Ref::new` boxed it. drop(unsafe { Box::from_raw(this.cast_mut()) }); } - left.unwrap_or(0) + left } extern "system" fn input_kind(this: *const Reading) -> u32 { reading(this).kind() @@ -1120,8 +1074,7 @@ mod host { use windows_sys::Win32::System::Threading::GetCurrentProcessId; use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ - GetAsyncKeyState, GetKeyState, GetKeyboardLayout, HKL, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, - ToUnicodeEx, + GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, }; use windows_sys::Win32::UI::Input::XboxController::{ XINPUT_GAMEPAD, XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_BACK, @@ -1181,32 +1134,31 @@ mod host { impl Source for Host { fn pad(&mut self, slot: usize) -> Option<PadState> { - let empty = self.empty_until[slot].is_some_and(|until| Instant::now() < until); - if !empty { - let mut state = XINPUT_STATE::default(); - // SAFETY: room for the state. - if unsafe { XInputGetState(slot as u32, &mut state) } == 0 { - self.empty_until[slot] = None; - return Some(convert(&state.Gamepad)); - } + if self.empty_until[slot].is_some_and(|until| Instant::now() < until) { + return None; + } + let mut state = XINPUT_STATE::default(); + // SAFETY: room for the state. + if unsafe { XInputGetState(slot as u32, &mut state) } != 0 { self.empty_until[slot] = Some(Instant::now() + EMPTY_SLOT_RECHECK); + return None; } - // A DualSense is a HID device, not an XInput one; it plays slot 0 - // when no XInput pad answers there. - if slot == 0 - && let Some(pad) = super::super::dualsense::latest() - { - return Some(PadState { - buttons: pad.buttons, - left_trigger: pad.left_trigger, - right_trigger: pad.right_trigger, - left_x: pad.left_x, - left_y: pad.left_y, - right_x: pad.right_x, - right_y: pad.right_y, - }); + self.empty_until[slot] = None; + #[allow(unused_mut)] + let mut pad = convert(&state.Gamepad); + // The scripted keys (`VICTORY_KEYS`) also press the first + // pad's buttons, by the stand-in pad's table: with a real pad + // connected the stand-in is not there, and a title that listens + // to the pad (the title's start screen) saw nothing. + #[cfg(feature = "diagnostics")] + if slot == 0 { + for vk in scripted() { + if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) { + pad.buttons |= button; + } + } } - None + Some(pad) } fn keys(&mut self) -> Vec<KeyState> { @@ -1224,31 +1176,22 @@ mod host { .collect(); down.extend(held); } - let state = keyboard_state(&down, caps_lock()); - let layout = layout(); - down.iter() - .map(|&vk| { + down.into_iter() + .map(|vk| KeyState { // SAFETY: plain query. - let scan_code = unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) }; - let (code_point, dead_key) = character(vk, scan_code, &state, layout); - KeyState { - scan_code, - code_point, - virtual_key: vk, - dead_key, - } + scan_code: unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) }, + virtual_key: vk, + // shortcut: no characters (code point 0); + // the title reads scan codes and virtual keys only. + ..Default::default() }) .collect() } - // shortcut: trigger motors are dropped (XInput has none). The host - // API that drives them without a redistributable is - // Windows.Gaming.Input (WinRT `Gamepad.Vibration`), which needs WinRT - // bindings this crate lacks outside diagnostics builds. - fn rumble(&mut self, slot: usize, motors: Motors) { + fn rumble(&mut self, slot: usize, low: u16, high: u16) { let speeds = XINPUT_VIBRATION { - wLeftMotorSpeed: motors.low, - wRightMotorSpeed: motors.high, + wLeftMotorSpeed: low, + wRightMotorSpeed: high, }; // SAFETY: a valid vibration; an empty slot just fails. unsafe { XInputSetState(slot as u32, &speeds) }; @@ -1294,82 +1237,6 @@ mod host { .collect() } - /// The keyboard state `ToUnicodeEx` reads with the keys `held` down: - /// each held key, the generic Shift, Ctrl and Alt from either side's key - /// (devices report sides only), and Caps Lock's toggle. - fn keyboard_state(held: &[u8], caps_lock: bool) -> [u8; 256] { - const DOWN: u8 = 0x80; - const TOGGLED: u8 = 1; - let mut state = [0u8; 256]; - for &vk in held { - state[usize::from(vk)] = DOWN; - let generic = match vk { - 0xA0 | 0xA1 => Some(0x10), // shift - 0xA2 | 0xA3 => Some(0x11), // control - 0xA4 | 0xA5 => Some(0x12), // alt - _ => None, - }; - if let Some(g) = generic { - state[g] = DOWN; - } - } - if caps_lock { - state[0x14] |= TOGGLED; - } - state - } - - fn caps_lock() -> bool { - // SAFETY: plain query. - let state = unsafe { GetKeyState(0x14) }; - state & 1 != 0 - } - - /// The foreground window's keyboard layout (the title's while it has - /// focus; this thread's when there is no foreground window). - fn layout() -> HKL { - // SAFETY: plain queries; a null window gives thread 0, this thread. - unsafe { - GetKeyboardLayout(GetWindowThreadProcessId( - GetForegroundWindow(), - std::ptr::null_mut(), - )) - } - } - - /// The character key `vk` types in `layout` with `state`: its code point - /// (0 when it types none, or several at once), and whether it is a dead - /// key, whose code point is then the accent's spacing form. Pending dead - /// keys are not combined: the thread's keyboard state is left alone. - fn character(vk: u8, scan_code: u32, state: &[u8; 256], layout: HKL) -> (u32, bool) { - /// `ToUnicodeEx` flag: keep the keyboard state (Windows 10 1607 on). - const KEEP_STATE: u32 = 4; - let mut text = [0u16; 8]; - // SAFETY: the state is the 256 bytes the call reads; the buffer's - // length is passed with it. - let n = unsafe { - ToUnicodeEx( - u32::from(vk), - scan_code & 0xFF, - state.as_ptr(), - text.as_mut_ptr(), - text.len() as i32, - KEEP_STATE, - layout, - ) - }; - let units = match n { - 0 => return (0, false), - ..0 => &text[..1], - n => &text[..(n as usize).min(text.len())], - }; - let mut chars = char::decode_utf16(units.iter().copied()); - match (chars.next(), chars.next()) { - (Some(Ok(c)), None) => (u32::from(c), n < 0), - _ => (0, false), - } - } - /// The foreground window is one of ours (the title's or our fallback). fn focused() -> bool { let mut process = 0; @@ -1401,32 +1268,6 @@ mod host { (1.0, -1.0, 1.0, 0.0) ); } - - #[test] - fn either_sides_modifier_holds_the_generic_one() { - let state = keyboard_state(&[0xA1, 0xA2, 0x41], false); - for vk in [0xA1, 0x10, 0xA2, 0x11, 0x41] { - assert_eq!(state[vk], 0x80, "{vk:#x}"); - } - for vk in [0xA0, 0xA3, 0x12, 0x14] { - assert_eq!(state[vk], 0, "{vk:#x}"); - } - assert_eq!(keyboard_state(&[], true)[0x14], 1); - } - - #[test] - fn keys_type_their_characters() { - // Space and Enter type the same in every layout; F1 types nothing. - let layout = layout(); - let typed = |vk: u8, held: &[u8]| { - // SAFETY: plain query. - let scan = unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) }; - character(vk, scan, &keyboard_state(held, false), layout) - }; - assert_eq!(typed(0x20, &[0x20]), (0x20, false)); - assert_eq!(typed(0x0D, &[0x0D]), (0x0D, false)); - assert_eq!(typed(0x70, &[0x70]), (0, false)); - } } #[cfg(test)] @@ -1443,7 +1284,7 @@ mod tests { struct FakeHost { pads: [Option<PadState>; PADS], keys: Vec<KeyState>, - rumble: Vec<(usize, Motors)>, + rumble: Vec<(usize, u16, u16)>, } struct Fake(Arc<Mutex<FakeHost>>); @@ -1455,8 +1296,8 @@ mod tests { fn keys(&mut self) -> Vec<KeyState> { self.0.lock().unwrap().keys.clone() } - fn rumble(&mut self, slot: usize, motors: Motors) { - self.0.lock().unwrap().rumble.push((slot, motors)); + fn rumble(&mut self, slot: usize, low: u16, high: u16) { + self.0.lock().unwrap().rumble.push((slot, low, high)); } } @@ -1646,102 +1487,6 @@ mod tests { release(rest); } - #[test] - fn with_no_device_readings_are_walked_across_devices_in_time_order() { - type Walk = extern "system" fn(This, *const Reading, u32, *const Device, Out) -> HRESULT; - let any = |hub: &Hub, offset, from, kind| { - let mut out = std::ptr::null(); - let walk = slot::<Walk, _>(&hub.object, offset); - result( - walk(&hub.object, from, kind, std::ptr::null(), &mut out), - out, - ) - }; - let both = GAMEPAD_KIND | KEYBOARD_KIND; - let tick = || std::thread::sleep(Duration::from_millis(2)); - let (hub, host) = fake(); - // The first poll: the stand-in pad and the keyboard, at one time. - let stand_in = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); - let no_keys = current(hub, KEYBOARD_KIND, KEYBOARD).unwrap(); - tick(); - // A slot that has never reported input is not a pad: press A. - host.lock().unwrap().pads[1] = Some(PadState { - buttons: A, - ..Default::default() - }); - hub.poll(); - let pad_a = current(hub, GAMEPAD_KIND, 1).unwrap(); - tick(); - host.lock().unwrap().keys = vec![key(b'W')]; - hub.poll(); - let w = current(hub, KEYBOARD_KIND, KEYBOARD).unwrap(); - tick(); - host.lock().unwrap().pads[1].as_mut().unwrap().buttons = B; - hub.poll(); - let pad_b = current(hub, GAMEPAD_KIND, 1).unwrap(); - - let order = [stand_in, no_keys, pad_a, w, pad_b]; - for pair in order.windows(2) { - assert_eq!(any(hub, 0x28, pair[0], both), Ok(pair[1])); - assert_eq!(any(hub, 0x30, pair[1], both), Ok(pair[0])); - } - assert_eq!(any(hub, 0x30, stand_in, both), Err(READING_NOT_FOUND)); - assert_eq!(any(hub, 0x28, pad_b, both), Err(READING_NOT_FOUND)); - // Only gamepads: the keyboard's readings are skipped. - assert_eq!(any(hub, 0x28, stand_in, GAMEPAD_KIND), Ok(pad_a)); - assert_eq!(any(hub, 0x28, pad_a, GAMEPAD_KIND), Ok(pad_b)); - assert_eq!(any(hub, 0x30, pad_a, GAMEPAD_KIND), Ok(stand_in)); - // Naming the device keeps the walk on it. - assert_eq!(walk(hub, 0x30, pad_a), Err(READING_NOT_FOUND)); - for r in order { - release(r); - } - } - - #[test] - fn a_receiver_with_a_switched_off_pad_does_not_hide_the_keyboard_stand_in() { - let (hub, host) = fake(); - let log = Log::default(); - register(hub, GAMEPAD_KIND, 2, &log); - assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); - - // A wireless receiver answers for a pad that is switched off: the slot reads - // connected with an all-zero report. That is not a pad, and it must not take the - // stand-in away - the keyboard would be dead with nothing in the player's hands. - host.lock().unwrap().pads[0] = Some(PadState::default()); - hub.poll(); - assert_eq!( - *log.lock().unwrap(), - [(FALLBACK, STATUS_CONNECTED, 0)], - "an all-zero slot is not a pad" - ); - assert_eq!(current(hub, GAMEPAD_KIND, 0), Err(DEVICE_DISCONNECTED)); - - // The first real press turns the slot into a pad, and the stand-in steps aside. - host.lock().unwrap().pads[0] = Some(PadState { - buttons: A, - ..Default::default() - }); - hub.poll(); - assert_eq!( - log.lock().unwrap()[1..], - [(0, STATUS_CONNECTED, 0), (FALLBACK, 0, STATUS_CONNECTED)] - ); - let pressed = current(hub, GAMEPAD_KIND, 0).unwrap(); - assert_eq!(pad(pressed).buttons, A); - release(pressed); - - // Back at rest it stays a pad: a pad that has been used does not connect and - // disconnect on every button release. - host.lock().unwrap().pads[0] = Some(PadState::default()); - hub.poll(); - assert_eq!(log.lock().unwrap().len(), 3, "no churn while the pad rests"); - let rest = current(hub, GAMEPAD_KIND, 0).unwrap(); - assert_eq!(pad(rest), PadState::default()); - release(rest); - assert_eq!(current(hub, GAMEPAD_KIND, FALLBACK), Err(DEVICE_DISCONNECTED)); - } - #[test] fn keys_feed_the_keyboard_and_the_stand_in_pad() { let (hub, host) = fake(); @@ -1833,33 +1578,16 @@ mod tests { let mut token = 0; let context = (&raw const hub.object).cast_mut().cast(); assert_eq!( - register( - &hub.object, - std::ptr::null(), - GAMEPAD_KIND, - 1, - 0, - context, - Some(slow), - &mut token - ), + register(&hub.object, std::ptr::null(), GAMEPAD_KIND, 1, 0, context, Some(slow), &mut token), S_OK ); - // A slot that has never reported input is not a pad, so the callback test - // presses a button to make this one appear. - host.lock().unwrap().pads[1] = Some(PadState { - buttons: A, - ..Default::default() - }); + host.lock().unwrap().pads[1] = Some(PadState::default()); let poller = std::thread::spawn(|| hub.poll()); while !INSIDE.load(Ordering::SeqCst) { std::thread::sleep(Duration::from_millis(1)); } let unregister = slot::<extern "system" fn(This, u64, u64) -> bool, _>(&hub.object, 0x68); - assert!( - !unregister(&hub.object, token, 5000), - "times out while it runs" - ); + assert!(!unregister(&hub.object, token, 5000), "times out while it runs"); let leave = std::thread::spawn(|| { std::thread::sleep(Duration::from_millis(50)); LEAVE.store(true, Ordering::SeqCst); @@ -1875,11 +1603,7 @@ mod tests { #[test] fn devices_are_found_by_id_and_rumble_reaches_the_host() { let (hub, host) = fake(); - // A slot is a pad once it has reported input. - host.lock().unwrap().pads[2] = Some(PadState { - buttons: A, - ..Default::default() - }); + host.lock().unwrap().pads[2] = Some(PadState::default()); hub.poll(); let device = &hub.devices[2] as *const Device; let info = slot::<extern "system" fn(*const Device) -> *const u8, _>(device, 0x18); @@ -1900,63 +1624,6 @@ mod tests { rumble(device, &[0.5, 1.0, 1.0, 1.0]); rumble(&hub.devices[FALLBACK], &[1.0; 4]); rumble(device, std::ptr::null()); - let full = Motors { - low: 32767, - high: 65535, - left_trigger: 65535, - right_trigger: 65535, - }; - assert_eq!( - host.lock().unwrap().rumble, - [(2, full), (2, Motors::default())] - ); - } - - #[test] - fn trigger_rumble_reaches_the_host() { - let (hub, host) = fake(); - // A slot is a pad once it has reported input. - host.lock().unwrap().pads[1] = Some(PadState { - buttons: A, - ..Default::default() - }); - hub.poll(); - let device = &hub.devices[1] as *const Device; - type Rumble = extern "system" fn(*const Device, *const [f32; 4]); - let rumble = slot::<Rumble, _>(device, 0x50); - // Out-of-range and NaN levels clamp or fall to off, like the grips. - rumble(device, &[0.0, 0.0, 0.25, 2.0]); - rumble(device, &[0.0, 0.0, -1.0, f32::NAN]); - let expected = [ - ( - 1, - Motors { - left_trigger: 16383, - right_trigger: 65535, - ..Motors::default() - }, - ), - (1, Motors::default()), - ]; - assert_eq!(host.lock().unwrap().rumble, expected); - } - - /// A title releasing a reading once too often: the count stays 0 and - /// nothing is freed again (the old `fetch_sub(1) - 1` overflowed). - #[test] - fn reading_release_past_zero_leaves_the_count_at_zero() { - let reading = Box::into_raw(Box::new(Reading { - vtable: &READING, - refs: AtomicU32::new(0), - device: std::ptr::null(), - sequence: 0, - timestamp: 0, - value: Value::Keys(Vec::new()), - })); - assert_eq!(reading_release(reading), 0); - // SAFETY: still allocated: `reading_release` freed nothing. - assert_eq!(unsafe { &*reading }.refs.load(Ordering::Relaxed), 0); - // SAFETY: boxed above and not freed. - drop(unsafe { Box::from_raw(reading) }); + assert_eq!(host.lock().unwrap().rumble, [(2, 32767, 65535), (2, 0, 0)]); } } diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 428fdeaeda..28676f2278 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -52,7 +52,10 @@ pub extern "system" fn GetModuleFileNameW(module: *mut c_void, out: *mut u16, si return host::get_module_file_name_w(module, out, size); }; let wide: Vec<u16> = path.encode_utf16().collect(); - copy_truncated(&wide, title_buffer(out, size)) + // SAFETY: the title passes a buffer of `size` characters. + copy_truncated(&wide, unsafe { + std::slice::from_raw_parts_mut(out, size as usize) + }) } /// See [`GetModuleFileNameW`]. @@ -60,18 +63,10 @@ pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, siz let Some(path) = title_path(module) else { return host::get_module_file_name_a(module, out, size); }; - copy_truncated(path.as_bytes(), title_buffer(out, size)) -} - -/// The title's buffer of `size` elements; none for a null pointer (a slice -/// may not start at null, even an empty one, so `(NULL, 0)` would be -/// undefined behaviour). -fn title_buffer<'a, T>(out: *mut T, size: u32) -> &'a mut [T] { - if out.is_null() { - return &mut []; - } - // SAFETY: the title passes a buffer of `size` elements. - unsafe { std::slice::from_raw_parts_mut(out, size as usize) } + // SAFETY: the title passes a buffer of `size` bytes. + copy_truncated(path.as_bytes(), unsafe { + std::slice::from_raw_parts_mut(out, size as usize) + }) } fn title_path(module: *mut c_void) -> Option<String> { @@ -85,8 +80,7 @@ fn title_path(module: *mut c_void) -> Option<String> { /// `GetModuleFileName`'s contract: copy with a NUL; if it does not fit, /// truncate to the buffer, report `ERROR_INSUFFICIENT_BUFFER` and return -/// the buffer size. A name that fits clears the last error, as the host -/// does: titles tell a truncated name from a whole one by it. +/// the buffer size. fn copy_truncated<T: Copy + Default>(text: &[T], out: &mut [T]) -> u32 { let Some(room) = out.len().checked_sub(1) else { host::set_last_error(ERROR_INSUFFICIENT_BUFFER); @@ -99,12 +93,9 @@ fn copy_truncated<T: Copy + Default>(text: &[T], out: &mut [T]) -> u32 { host::set_last_error(ERROR_INSUFFICIENT_BUFFER); return out.len() as u32; } - host::set_last_error(ERROR_SUCCESS); n as u32 } -const ERROR_SUCCESS: u32 = 0; - const ERROR_INSUFFICIENT_BUFFER: u32 = 122; /// Console-only DLLs we implement load as a pseudo handle (titles load @@ -164,19 +155,14 @@ pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> * let Some(m) = registry().iter().find(|m| handle(m) == module) else { return host_override(module, name).unwrap_or_else(|| host::get_proc_address(module, name)); }; - // Values below 0x10000 are ordinals. Our export table names ordinal - // exports `#n`, the same form the import binder looks up. A miss fails - // as the host's does, with the last error set. + // Values below 0x10000 are ordinals; we export by name only. if (name as usize) < 0x1_0000 { - let ordinal = format!("#{}", name as usize); - return match m.exports.iter().find(|e| e.name == ordinal) { - Some(e) => e.address as *mut c_void, - None => { - tracing::warn!(module = m.name, %ordinal, "GetProcAddress: not implemented"); - host::set_last_error(ERROR_PROC_NOT_FOUND); - std::ptr::null_mut() - } - }; + tracing::warn!( + module = m.name, + ordinal = name as usize, + "GetProcAddress by ordinal" + ); + return std::ptr::null_mut(); } // SAFETY: not an ordinal, so the title passes a NUL-terminated name. let name = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy(); @@ -184,7 +170,6 @@ pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> * Some(e) => e.address as *mut c_void, None => { tracing::warn!(module = m.name, %name, "GetProcAddress: not implemented"); - host::set_last_error(ERROR_PROC_NOT_FOUND); std::ptr::null_mut() } } @@ -310,6 +295,7 @@ fn handle(m: &HleModule) -> *mut c_void { /// import binding); others fail. With `load`, a title DLL not mapped yet is /// mapped now. fn find_module(path: &str, load: bool) -> Option<*mut c_void> { + let path = path.trim_end_matches(['\0', ' ']); let file = path.rsplit(['\\', '/']).next().unwrap_or(path); // As the Windows loader does, a name without extension means a DLL. let file = if file.contains('.') { @@ -345,28 +331,39 @@ fn find_module(path: &str, load: bool) -> Option<*mut c_void> { if host_dll { return None; } + // A title DLL another thread is mapping right now has no name yet: + // wait for that load, as the Windows loader lock makes a + // `GetModuleHandle` wait, and ask again. + runtime::settle_title_dlls(); + if let Some(base) = runtime::image_named(&file) { + tracing::info!(dll = file, load, "a title DLL asked for while it was being mapped: found after the load"); + return Some(base as *mut c_void); + } // Any other host DLL (wininet, urlmon, ...) is beyond what we guard, and // the console does not have it. - refuse(&file); + refuse(&file, path, load); host::set_last_error(ERROR_MOD_NOT_FOUND); Some(std::ptr::null_mut()) } /// Logs a DLL name the title is refused, once. -fn refuse(file: &str) { +fn refuse(file: &str, path: &str, load: bool) { static REFUSED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new()); let file = file.to_ascii_lowercase(); let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner()); - if refused.contains(&file) { - return; + if !refused.contains(&file) { + tracing::warn!( + dll = file, + path, + load, + similar = ?runtime::images_like(&file), + "a host DLL outside the host policy: refused" + ); + refused.push(file); } - refused.push(file.clone()); - drop(refused); - tracing::warn!(dll = file, from = %host::callers(), "a host DLL outside the host policy: refused"); } const ERROR_MOD_NOT_FOUND: u32 = 126; -const ERROR_PROC_NOT_FOUND: u32 = 127; pub(crate) fn module() -> HleModule { HleModule { @@ -633,50 +630,6 @@ mod tests { assert_eq!(&small, &[b'C', b':', b'\\', 0]); } - /// The host clears the last error when the name fits (titles tell a - /// truncated name from a whole one by it, also after a call that - /// filled the buffer exactly); a title image's name does the same. - #[cfg(windows)] - #[test] - fn a_module_name_that_fits_clears_the_last_error() { - use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; - // SAFETY: reads this thread's last error. - let last_error = || unsafe { GetLastError() }; - // SAFETY: sets this thread's last error. - let stale = || unsafe { SetLastError(ERROR_INSUFFICIENT_BUFFER) }; - let (mut wide, mut narrow) = ([0u16; 512], [0u8; 512]); - - // What the host does, for one of its own modules. - let kernel32 = host::get_module_handle_w(w("kernel32.dll").as_ptr()); - stale(); - assert_ne!(GetModuleFileNameW(kernel32, wide.as_mut_ptr(), 512), 0); - assert_eq!(last_error(), 0, "the host, wide"); - stale(); - assert_ne!(GetModuleFileNameA(kernel32, narrow.as_mut_ptr(), 512), 0); - assert_eq!(last_error(), 0, "the host, narrow"); - - let base = 0x7200_0000_0000; - runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe")); - let module = base as *mut c_void; - // Too small: the error says so, as before. - // SAFETY: this thread's last error. - unsafe { SetLastError(0) }; - assert_eq!(GetModuleFileNameW(module, wide.as_mut_ptr(), 4), 4); - assert_eq!(last_error(), ERROR_INSUFFICIENT_BUFFER); - // Then with room, the way titles grow their buffer until it fits. - assert_eq!(GetModuleFileNameW(module, wide.as_mut_ptr(), 512), 17); - assert_eq!(last_error(), 0, "a title image, wide"); - stale(); - assert_eq!(GetModuleFileNameA(module, narrow.as_mut_ptr(), 512), 17); - assert_eq!(last_error(), 0, "a title image, narrow"); - // An exact fit is whole too (17 characters and the NUL). - stale(); - assert_eq!(GetModuleFileNameA(module, narrow.as_mut_ptr(), 18), 17); - assert_eq!(last_error(), 0); - assert_eq!(GetModuleFileNameA(module, narrow.as_mut_ptr(), 17), 17); - assert_eq!(last_error(), ERROR_INSUFFICIENT_BUFFER); - } - fn w(text: &str) -> Vec<u16> { text.encode_utf16().chain(Some(0)).collect() } @@ -716,30 +669,10 @@ mod tests { ); } - #[test] - fn pseudo_module_ordinals_resolve() { - let module = LoadLibraryA(c"gameinput.dll".as_ptr().cast()); - assert!(!module.is_null(), "gameinput is one of our pseudo modules"); - assert_eq!( - GetProcAddress(module, std::ptr::dangling::<u8>()) as usize, - crate::registry::lookup("gameinput.dll", "#1").unwrap(), - "GameInputCreate is imported by ordinal" - ); - assert!( - GetProcAddress(module, 2 as *const u8).is_null(), - "an ordinal we do not export stays null" - ); - } - #[test] fn title_dlls_and_pseudo_modules_are_found_by_name() { let base = 0x7100_0000_0000usize; - let path = if cfg!(windows) { - r"C:\title\Mapped.dll" - } else { - "/title/Mapped.dll" - }; - runtime::set_image_path(base, std::path::Path::new(path)); + runtime::set_image_path(base, std::path::Path::new(r"C:\title\Mapped.dll")); runtime::set_title_dll_loader(Box::new(|file| match file { "late.dll" => Ok(Some(0x7200_0000_0000)), "broken.dll" => Err("bad image".into()), @@ -766,42 +699,4 @@ mod tests { assert!(!runtime.is_null()); assert_eq!(GetModuleHandleW(w("XGameRuntime.dll").as_ptr()), runtime); } - - /// No buffer: nothing written, the error says it was too small. - #[test] - fn a_title_image_name_into_no_buffer() { - let base = 0x7300_0000_0000; - runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe")); - let module = base as *mut c_void; - assert_eq!(GetModuleFileNameW(module, std::ptr::null_mut(), 0), 0); - assert_eq!(GetModuleFileNameA(module, std::ptr::null_mut(), 0), 0); - #[cfg(windows)] - { - // SAFETY: reads this thread's last error. - let last = unsafe { windows_sys::Win32::Foundation::GetLastError() }; - assert_eq!(last, ERROR_INSUFFICIENT_BUFFER); - } - } - - #[cfg(windows)] - #[test] - fn a_missing_export_of_our_modules_sets_the_last_error() { - use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; - // SAFETY: sets and reads this thread's last error. - let clear = || unsafe { SetLastError(0) }; - // SAFETY: as above. - let last = || unsafe { GetLastError() }; - // The host's own modules, for comparison. - let kernel32 = GetModuleHandleW(w("kernel32.dll").as_ptr()); - clear(); - assert!(GetProcAddress(kernel32, c"NotAnExport".as_ptr().cast()).is_null()); - assert_eq!(last(), ERROR_PROC_NOT_FOUND); - // Ours, by name and by ordinal. - let runtime = LoadLibraryA(c"xgameruntime.dll".as_ptr().cast()); - for name in [c"NotAnExport".as_ptr().cast(), 9999 as *const u8] { - clear(); - assert!(GetProcAddress(runtime, name).is_null()); - assert_eq!(last(), ERROR_PROC_NOT_FOUND, "{name:?}"); - } - } } diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 01bc68ff18..f1b577719d 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -110,8 +110,8 @@ pub extern "system" fn CreateWindowExA( hwnd } -/// A console title sizes its window to its render target (Grand Theft -/// Auto VI: 3840x2160 on a Series X), which can exceed the host's screen. +/// A console title sizes its window to its render target ( +/// the title: 3840x2160 on a Series X), which can exceed the host's screen. /// A top-level window larger than the work area is shrunk to fit, keeping /// its proportions, and centred; what it shows is scaled to it (the swap /// chain stretches). @@ -142,11 +142,9 @@ fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) { f64::from(aw) / f64::from(width), f64::from(ah) / f64::from(height), ); - // A very small work area can scale a positive requested dimension below - // one pixel, which truncates to zero. A window still needs a pixel there. ( - ((f64::from(width) * scale) as i32).max(1), - ((f64::from(height) * scale) as i32).max(1), + (f64::from(width) * scale) as i32, + (f64::from(height) * scale) as i32, ) } @@ -179,8 +177,8 @@ extern "system" fn window_proc( // Alt or F10 puts a window into menu mode: the system runs a modal menu // loop on the thread that owns the window, which is the title's. The // title then stops (no frames, no input) until a key ends the loop, and - // nothing shows it, since the window has no menu bar; Grand Theft Auto - // VI aborts itself about half a minute later. A console has no window + // nothing shows it, since the window has no menu bar; + // the title aborts itself about half a minute later. A console has no window // menu. The mouse still opens it from the title bar. if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize { return 0; @@ -347,16 +345,6 @@ mod tests { fit_into(&area, wm::CW_USEDEFAULT, 0), (wm::CW_USEDEFAULT, 0) ); - - // A tiny work area must not round a positive size down to zero. - let tiny = RECT { - left: 0, - top: 0, - right: 1, - bottom: 100, - }; - assert_eq!(fit_into(&tiny, 1000, 100), (1, 1)); - assert_eq!(fit_into(&area, 0, -5), (0, -5)); } #[test] diff --git a/crates/victory-hle/src/modules/media.rs b/crates/victory-hle/src/modules/media.rs index d2a30d105e..aa6e91c5bb 100644 --- a/crates/victory-hle/src/modules/media.rs +++ b/crates/victory-hle/src/modules/media.rs @@ -12,7 +12,6 @@ use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Mutex, OnceLock}; use super::files; -use super::release_ref; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleModule, hle_export}; @@ -49,25 +48,13 @@ fn local(url: &[u16]) -> Result<Vec<u16>, (String, String)> { b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' }; let host_of = |rest: &str| rest.split(['/', '\\']).next().unwrap_or("").to_string(); - // Two leading separators, of either kind: to the host, a share. - let share = |s: &str| { - let b = s.as_bytes(); - b.len() >= 2 && b[..2].iter().all(|c| b"/\\".contains(c)) - }; let path = if let Some(rest) = text.strip_prefix(r"\\?\") { if !drive(rest) { return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\")))); } text.clone() - } else if let Some(rest) = text.strip_prefix(r"\??\") { - // The same prefix as the object manager spells it; the host's file - // calls take it too. - if !drive(rest) { - return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\")))); - } - return Ok(with_nul(url)); - } else if share(&text) { - return Err(("unc".into(), host_of(&text[2..]))); + } else if let Some(rest) = text.strip_prefix(r"\\").or_else(|| text.strip_prefix("//")) { + return Err(("unc".into(), host_of(rest))); } else if drive(&text) { text.clone() } else if let Some((scheme, rest)) = text.split_once(':').filter(|(s, _)| { @@ -80,24 +67,18 @@ fn local(url: &[u16]) -> Result<Vec<u16>, (String, String)> { if scheme != "file" { return Err((scheme, authority.map(host_of).unwrap_or_default())); } - let (path, this_machine) = match authority { + let path = match authority { Some(rest) => { let host = host_of(rest); if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") { return Err((scheme, host)); } - (&rest[host.len()..], !host.is_empty()) + &rest[host.len()..] } - None => (rest, false), + None => rest, }; - let whole = percent_decode(path); let path = percent_decode(path.trim_start_matches(['/', '\\'])).replace('/', "\\"); if !drive(&path) { - // With no host named, a path that starts with two separators - // names one: `file:////server/share` is `\\server\share`. - if !this_machine && share(&whole) { - return Err((scheme, host_of(whole.trim_start_matches(['/', '\\'])))); - } // A local file without a drive: the host resolves it as is. return Ok(with_nul(url)); } @@ -119,11 +100,8 @@ fn percent_decode(s: &str) -> String { let mut out = Vec::with_capacity(b.len()); let mut i = 0; while i < b.len() { - // `from_str_radix` accepts a leading sign, so `%+1` would decode as - // a control byte. A percent escape is exactly two hex digits. let hex = b .get(i + 1..i + 3) - .filter(|h| h.iter().all(|c| c.is_ascii_hexdigit())) .and_then(|h| std::str::from_utf8(h).ok()); match (b[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) { (b'%', Some(v)) => { @@ -295,8 +273,8 @@ extern "system" fn add_ref(this: *mut Resolver) -> u32 { extern "system" fn release(this: *mut Resolver) -> u32 { // SAFETY: as in `host`. - let left = release_ref(unsafe { &(*this).refs }, "source resolver"); - if left == Some(0) { + let left = unsafe { (*this).refs.fetch_sub(1, Ordering::AcqRel) } - 1; + if left == 0 { // SAFETY: made by `MFCreateSourceResolver`; this was the last // reference, to the proxy and to the host object it holds. let proxy = unsafe { Box::from_raw(this) }; @@ -304,7 +282,7 @@ extern "system" fn release(this: *mut Resolver) -> u32 { let release: extern "system" fn(*mut Host) -> u32 = unsafe { Host::method(proxy.host, 2) }; release(proxy.host); } - left.unwrap_or(0) + left } extern "system" fn create_from_url( @@ -497,15 +475,6 @@ mod tests { String::from_utf16_lossy(v.strip_suffix(&[0]).unwrap_or(v)) } - #[test] - fn percent_decode_requires_two_hex_digits() { - assert_eq!(percent_decode("%20"), " "); - assert_eq!(percent_decode("%+1"), "%+1"); - assert_eq!(percent_decode("%2"), "%2"); - assert_eq!(percent_decode("%%20"), "% "); - assert_eq!(percent_decode("a%2Gb"), "a%2Gb"); - } - #[test] fn only_local_files_reach_the_host() { // Network schemes and shares are refused, naming scheme and host. @@ -554,107 +523,9 @@ mod tests { assert_eq!(text(&local(&wide("clip.mp4")).unwrap()), "clip.mp4"); } - /// Other spellings of `\\server\share\a.mp4`, as paths and as `file:` - /// URLs without a host. - const SHARE_PATHS: [&str; 3] = [ - r"/\server\share\a.mp4", - r"\/server/share/a.mp4", - r"\??\UNC\server\share\a.mp4", - ]; - const SHARE_URLS: [&str; 5] = [ - "file:////server/share/a.mp4", - "file://///server/share/a.mp4", - r"file:\\server\share\a.mp4", - "file:/%5Cserver/share/a.mp4", - "file:///%5C%5Cserver/share/a.mp4", - ]; - - #[test] - fn shares_are_refused_however_they_are_spelled() { - let asked = |url: &str| local(&wide(url)).map(|v| text(&v)); - for path in SHARE_PATHS { - assert_eq!(asked(path), Err(("unc".into(), "server".into())), "{path}"); - } - for url in SHARE_URLS { - assert_eq!(asked(url), Err(("file".into(), "server".into())), "{url}"); - } - // Local files that look alike still pass: one leading separator, a - // drive after the slashes, a drive after the object prefix, and the - // path of a URL that names this machine. - for local_file in [ - r"\movies\a.mp4", - "file:///movies/a.mp4", - r"\??\C:\Windows\a.wav", - "file://localhost//server/share/a.mp4", - ] { - assert_eq!(asked(local_file), Ok(local_file.into()), "{local_file}"); - } - assert_eq!( - asked("file:////C:/Windows/a.wav"), - Ok(r"C:\Windows\a.wav".into()) - ); - } - - /// What the host makes of those spellings: the share, for each. - #[cfg(windows)] - #[test] - fn the_host_reads_those_spellings_as_shares() { - for path in &SHARE_PATHS[..2] { - assert_eq!( - std::path::absolute(path).unwrap().to_str(), - Some(r"\\server\share\a.mp4"), - "{path}" - ); - } - // The object prefix reaches the host's file calls as it is. - let windows = std::env::var("SystemRoot").unwrap(); - assert!(std::fs::metadata(format!(r"\??\{windows}")).is_ok()); - - let from_url = files::host!("shlwapi.dll", "PathCreateFromUrlW": - extern "system" fn(*const u16, *mut u16, *mut u32, u32) -> HRESULT); - let host_path = |url: &str| { - let url: Vec<u16> = url.encode_utf16().chain([0]).collect(); - let (mut path, mut n) = ([0u16; 260], 260); - assert_eq!(from_url(url.as_ptr(), path.as_mut_ptr(), &mut n, 0), S_OK); - String::from_utf16_lossy(&path[..n as usize]) - }; - for url in SHARE_URLS { - let path = host_path(url); - assert!( - path.starts_with(r"\\") && path.ends_with(r"server\share\a.mp4"), - "{url}: {path}" - ); - } - // And of the ones that pass: local paths. - assert_eq!( - host_path("file://localhost//server/share/a.mp4"), - r"\server\share\a.mp4" - ); - assert_eq!(host_path("file:////C:/Windows/a.wav"), r"C:\Windows\a.wav"); - assert_eq!(host_path("file:///movies/a.mp4"), r"\movies\a.mp4"); - } - #[test] fn interface_ids_are_the_resolvers() { assert_eq!(&IID_IUNKNOWN[8..], &[0xC0, 0, 0, 0, 0, 0, 0, 0x46]); assert_eq!(&IID_RESOLVER[..4], &[0x2D, 0xA3, 0xE5, 0xFB]); } - - /// A title releasing the resolver once too often: the count stays 0, - /// and neither the proxy nor the host object is released again (the - /// old `fetch_sub(1) - 1` overflowed). - #[test] - fn release_past_zero_leaves_the_count_at_zero() { - // No host object: `release` must not reach it at a count of 0. - let resolver = Box::into_raw(Box::new(Resolver { - vtable: &METHODS, - host: std::ptr::null_mut(), - refs: AtomicU32::new(0), - })); - assert_eq!(release(resolver), 0); - // SAFETY: still allocated: `release` freed nothing. - assert_eq!(unsafe { &*resolver }.refs.load(Ordering::Relaxed), 0); - // SAFETY: boxed above and not freed. - drop(unsafe { Box::from_raw(resolver) }); - } } diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index fd92e6be6d..3d60aa062a 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -10,18 +10,15 @@ #[cfg(windows)] pub mod apu; -/// Portable sample-rate conversion used by the Windows-gated APU. -pub(crate) mod apu_resample; pub mod audio; pub mod d3d12x; +pub mod ffx; pub mod display; pub mod dsp; -/// Portable partitioned convolution for the Windows/Xbox audio DSP. -pub(crate) mod dsp_convolve; #[cfg(windows)] pub mod dstorage; #[cfg(windows)] -pub mod dualsense; +pub mod fidelityfx; #[cfg(windows)] pub mod files; pub mod gameinput; @@ -32,8 +29,6 @@ pub mod lifecycle; pub mod media; #[cfg(windows)] pub mod net; -/// Lexical Windows path rules, host-independent so CI covers them. -pub(crate) mod paths; pub mod speech; pub mod storage; pub mod xasync; @@ -50,23 +45,8 @@ pub mod xstore; pub mod xsystem; pub mod xuser; -use std::sync::atomic::{AtomicU32, Ordering}; - use crate::HleModule; -/// Takes one reference off a COM count: the count left, or `None` when -/// none was left (the title released once too often). Then the count -/// stays 0 and the caller frees nothing a second time. -pub(crate) fn release_ref(refs: &AtomicU32, object: &'static str) -> Option<u32> { - match refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) { - Ok(n) => Some(n - 1), - Err(_) => { - tracing::warn!(object, "released with no references left"); - None - } - } -} - pub(crate) fn all() -> Vec<HleModule> { let mut all = vec![ kernel::module(), @@ -93,5 +73,9 @@ pub(crate) fn all() -> Vec<HleModule> { all.push(xmem::module()); #[cfg(windows)] all.push(xsystem::module()); + #[cfg(windows)] + if fidelityfx::serving() { + all.push(fidelityfx::module()); + } all } diff --git a/crates/victory-hle/src/modules/net.rs b/crates/victory-hle/src/modules/net.rs index deb80ccd8e..ee8c5a81f5 100644 --- a/crates/victory-hle/src/modules/net.rs +++ b/crates/victory-hle/src/modules/net.rs @@ -11,8 +11,9 @@ //! numeric, or fail if a name is required, as with no network. //! * `WinHttpConnect` to a host that is not loopback fails with //! `ERROR_WINHTTP_CANNOT_CONNECT`, so no request (or WebSocket) handle can -//! exist for one. Proxies are off and proxy auto-detection (WPAD, PAC -//! downloads) fails with `ERROR_WINHTTP_AUTODETECTION_FAILED`. +//! exist for one. Automatic redirects are disabled, including redirects +//! returned by a loopback server. Proxies are off and proxy auto-detection +//! (WPAD, PAC downloads) fails with `ERROR_WINHTTP_AUTODETECTION_FAILED`. //! * A bind to all interfaces is narrowed to loopback, so nothing on the //! network can connect in. #![allow(non_snake_case)] @@ -23,7 +24,7 @@ use std::ffi::{CStr, c_char, c_void}; use std::net::{IpAddr, SocketAddr}; use std::sync::Mutex; -use windows_sys::Win32::Foundation::SetLastError; +use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; use crate::modules::files::host; use crate::{HleExport, HleModule, hle_export}; @@ -45,6 +46,8 @@ const SIO_GET_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0006; const SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0024; const WINHTTP_ACCESS_TYPE_NO_PROXY: u32 = 1; const WINHTTP_OPTION_PROXY: u32 = 38; +const WINHTTP_OPTION_REDIRECT_POLICY: u32 = 88; +const WINHTTP_OPTION_REDIRECT_POLICY_NEVER: u32 = 0; #[repr(C)] #[derive(Clone, Copy, PartialEq, Eq)] @@ -753,8 +756,8 @@ pub extern "system" fn WinHttpConnect( ) } -/// Sessions never use a proxy: only loopback is reachable, and a proxy -/// (named, or found by auto-detection) would carry it off the machine. +/// Sessions never use a proxy or follow redirects: either could carry a +/// loopback request off the machine inside the host's own WinHTTP calls. pub extern "system" fn WinHttpOpen( agent: *const u16, access: u32, @@ -765,16 +768,44 @@ pub extern "system" fn WinHttpOpen( if access != WINHTTP_ACCESS_TYPE_NO_PROXY { once("HTTP proxy ignored", format!("access type {access}")); } - host!("winhttp.dll", "WinHttpOpen": extern "system" fn(*const u16, u32, *const u16, *const u16, u32) -> Handle)( + let session = host!("winhttp.dll", "WinHttpOpen": extern "system" fn(*const u16, u32, *const u16, *const u16, u32) -> Handle)( agent, WINHTTP_ACCESS_TYPE_NO_PROXY, std::ptr::null(), std::ptr::null(), flags, - ) + ); + if session.is_null() || no_http_redirects(session) == 0 { + return std::ptr::null_mut(); + } + session +} + +/// Applies the documented DWORD policy to a session or request. If the +/// host cannot enforce it, the handle is closed and the original error +/// is preserved; an unguarded handle must not remain usable. +fn no_http_redirects(handle: Handle) -> i32 { + let policy = WINHTTP_OPTION_REDIRECT_POLICY_NEVER; + let result = host!("winhttp.dll", "WinHttpSetOption": extern "system" fn(Handle, u32, *const c_void, u32) -> i32)( + handle, + WINHTTP_OPTION_REDIRECT_POLICY, + (&raw const policy).cast(), + std::mem::size_of_val(&policy) as u32, + ); + if result == 0 { + // SAFETY: reads only the calling thread's last error. + let error = unsafe { GetLastError() }; + if !handle.is_null() { + host!("winhttp.dll", "WinHttpCloseHandle": extern "system" fn(Handle) -> i32)(handle); + } + // SAFETY: restore the option failure after closing the unsafe handle. + unsafe { SetLastError(error) }; + } + result } -/// See [`WinHttpOpen`]: a proxy set later is accepted and not used. +/// See [`WinHttpOpen`]: later proxy settings are ignored and every redirect +/// policy change still enforces NEVER, on both sessions and requests. pub extern "system" fn WinHttpSetOption( handle: Handle, option: u32, @@ -785,6 +816,13 @@ pub extern "system" fn WinHttpSetOption( once("HTTP proxy ignored", "WINHTTP_OPTION_PROXY".into()); return 1; } + if option == WINHTTP_OPTION_REDIRECT_POLICY { + once( + "HTTP redirects disabled", + "WINHTTP_OPTION_REDIRECT_POLICY".into(), + ); + return no_http_redirects(handle); + } host!("winhttp.dll", "WinHttpSetOption": extern "system" fn(Handle, u32, *const c_void, u32) -> i32)( handle, option, buffer, len, ) @@ -894,6 +932,10 @@ pub(crate) fn module() -> HleModule { } } +#[cfg(test)] +#[path = "net_redirect_tests.rs"] +mod redirect_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/victory-hle/src/modules/net_redirect_tests.rs b/crates/victory-hle/src/modules/net_redirect_tests.rs new file mode 100644 index 0000000000..a95e9f8631 --- /dev/null +++ b/crates/victory-hle/src/modules/net_redirect_tests.rs @@ -0,0 +1,322 @@ +//! Real WinHTTP requests between two synthetic loopback listeners only. +//! No external destination, request body, title data, or credentials. + +use super::*; +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +struct LocalServer { + port: u16, + connections: Arc<AtomicUsize>, + stop: Arc<AtomicBool>, + thread: Option<std::thread::JoinHandle<()>>, +} + +impl LocalServer { + fn new(response: String) -> Self { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + listener.set_nonblocking(true).unwrap(); + let connections = Arc::new(AtomicUsize::new(0)); + let stop = Arc::new(AtomicBool::new(false)); + let (count, done) = (connections.clone(), stop.clone()); + let thread = std::thread::spawn(move || { + while !done.load(Ordering::Acquire) { + let (mut stream, peer) = match listener.accept() { + Ok(pair) => pair, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(2)); + continue; + } + Err(e) => panic!("local listener: {e}"), + }; + assert!(peer.ip().is_loopback()); + count.fetch_add(1, Ordering::Release); + stream.set_nonblocking(false).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(2))) + .unwrap(); + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n") { + let mut bytes = [0u8; 1024]; + let n = stream.read(&mut bytes).unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&bytes[..n]); + assert!(request.len() <= 4096); + } + assert!(request.starts_with(b"GET /")); + stream.write_all(response.as_bytes()).unwrap(); + } + }); + Self { + port, + connections, + stop, + thread: Some(thread), + } + } +} + +impl Drop for LocalServer { + fn drop(&mut self) { + self.stop.store(true, Ordering::Release); + let result = self.thread.take().unwrap().join(); + if !std::thread::panicking() { + result.unwrap(); + } + } +} + +struct HttpHandle(Handle); + +impl HttpHandle { + fn new(handle: Handle) -> Self { + assert!(!handle.is_null()); + Self(handle) + } +} + +impl Drop for HttpHandle { + fn drop(&mut self) { + host!("winhttp.dll", "WinHttpCloseHandle": extern "system" fn(Handle) -> i32)(self.0); + } +} + +fn wide(text: &str) -> Vec<u16> { + text.encode_utf16().chain(Some(0)).collect() +} + +fn query_policy(handle: Handle) -> u32 { + let (mut policy, mut len) = (u32::MAX, 4u32); + let query = host!("winhttp.dll", "WinHttpQueryOption": extern "system" fn(Handle, u32, *mut c_void, *mut u32) -> i32); + assert_ne!( + query( + handle, + WINHTTP_OPTION_REDIRECT_POLICY, + (&raw mut policy).cast(), + &mut len + ), + 0 + ); + assert_eq!(len, 4); + policy +} + +fn try_policy(handle: Handle, policy: u32) { + assert_ne!( + WinHttpSetOption( + handle, + WINHTTP_OPTION_REDIRECT_POLICY, + (&raw const policy).cast(), + 4 + ), + 0 + ); +} + +fn exchange( + port: u16, + session_policy: Option<u32>, + request_policy: Option<u32>, +) -> (u32, u32, u32) { + let session = HttpHandle::new(WinHttpOpen( + wide("VIctory loopback regression").as_ptr(), + WINHTTP_ACCESS_TYPE_NO_PROXY, + std::ptr::null(), + std::ptr::null(), + 0, + )); + let timeouts = host!("winhttp.dll", "WinHttpSetTimeouts": extern "system" fn(Handle, i32, i32, i32, i32) -> i32); + assert_ne!(timeouts(session.0, 2000, 2000, 2000, 2000), 0); + if let Some(policy) = session_policy { + try_policy(session.0, policy); + } + let connection = HttpHandle::new(WinHttpConnect( + session.0, + wide("127.0.0.1").as_ptr(), + port, + 0, + )); + let open = host!("winhttp.dll", "WinHttpOpenRequest": extern "system" fn(Handle, *const u16, *const u16, *const u16, *const u16, *const *const u16, u32) -> Handle); + let request = HttpHandle::new(open( + connection.0, + wide("GET").as_ptr(), + wide("/redirect").as_ptr(), + std::ptr::null(), + std::ptr::null(), + std::ptr::null(), + 0, + )); + if let Some(policy) = request_policy { + try_policy(request.0, policy); + } + let send = host!("winhttp.dll", "WinHttpSendRequest": extern "system" fn(Handle, *const u16, u32, *const c_void, u32, u32, usize) -> i32); + let receive = host!("winhttp.dll", "WinHttpReceiveResponse": extern "system" fn(Handle, *mut c_void) -> i32); + assert_ne!( + send(request.0, std::ptr::null(), 0, std::ptr::null(), 0, 0, 0), + 0 + ); + assert_ne!(receive(request.0, std::ptr::null_mut()), 0); + let query = host!("winhttp.dll", "WinHttpQueryHeaders": extern "system" fn(Handle, u32, *const u16, *mut c_void, *mut u32, *mut u32) -> i32); + let (mut status, mut len) = (0u32, 4u32); + // WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER from winhttp.h. + assert_ne!( + query( + request.0, + 19 | 0x2000_0000, + std::ptr::null(), + (&raw mut status).cast(), + &mut len, + std::ptr::null_mut() + ), + 0 + ); + (status, query_policy(session.0), query_policy(request.0)) +} + +#[test] +fn localhost_redirects_are_returned_without_following_or_policy_relaxation() { + let target = LocalServer::new( + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(), + ); + let origin = LocalServer::new(format!( + "HTTP/1.1 307 Temporary Redirect\r\nLocation: http://127.0.0.1:{}/target\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + target.port + )); + // 1 = DISALLOW_HTTPS_TO_HTTP (the host default), 2 = ALWAYS. Neither + // may relax our policy, whether applied to the session or the request. + let observed: Vec<_> = [ + (None, None), + (Some(2), None), + (None, Some(2)), + (Some(2), Some(1)), + ] + .into_iter() + .map(|(session, request)| exchange(origin.port, session, request)) + .collect(); + let origins = origin.connections.load(Ordering::Acquire); + let targets = target.connections.load(Ordering::Acquire); + eprintln!( + "Loopback origin connections={origins}, redirect target connections={targets}, responses/policies={observed:?}" + ); + assert_eq!(origins, 4); + assert_eq!( + targets, 0, + "the second loopback listener must never be contacted" + ); + assert_eq!( + observed, + vec![ + ( + 307, + WINHTTP_OPTION_REDIRECT_POLICY_NEVER, + WINHTTP_OPTION_REDIRECT_POLICY_NEVER + ); + 4 + ] + ); +} + +#[test] +fn dynamically_loaded_redirect_controls_use_the_guards() { + use crate::modules::kernel::{FreeLibrary, GetProcAddress, LoadLibraryA}; + let module = LoadLibraryA(c"winhttp.dll".as_ptr().cast()); + assert!(!module.is_null()); + for (name, guarded) in [ + (c"WinHttpOpen", WinHttpOpen as *const () as usize), + (c"WinHttpSetOption", WinHttpSetOption as *const () as usize), + ] { + assert_eq!( + GetProcAddress(module, name.as_ptr().cast()) as usize, + guarded + ); + } + assert_eq!(FreeLibrary(module), 1); +} + +#[test] +fn redirect_policy_failure_is_not_reported_as_success() { + // Other tests may open WinHTTP handles in parallel. Isolate this closed- + // handle check so its value cannot be reused between close and query. + const CHILD: &str = "VICTORY_TEST_WINHTTP_POLICY_FAILURE"; + if std::env::var(CHILD).as_deref() != Ok("1") { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "modules::net::redirect_tests::redirect_policy_failure_is_not_reported_as_success", + "--exact", + "--nocapture", + "--test-threads=1", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{stdout}\n{stderr}"); + assert!(stdout.contains("1 passed"), "child ran no test: {stdout}"); + return; + } + let policy = 2u32; + assert_eq!( + WinHttpSetOption( + std::ptr::null_mut(), + WINHTTP_OPTION_REDIRECT_POLICY, + (&raw const policy).cast(), + 4 + ), + 0 + ); + // SAFETY: reads only this thread's error. + assert_ne!(unsafe { windows_sys::Win32::Foundation::GetLastError() }, 0); + + // A connection is a real WinHTTP handle, but the redirect policy is only + // supported on sessions and requests. This exercises failure after a + // non-null handle exists, without issuing any HTTP request. + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + listener.set_nonblocking(true).unwrap(); + let session = HttpHandle::new(WinHttpOpen( + wide("VIctory option failure regression").as_ptr(), + WINHTTP_ACCESS_TYPE_NO_PROXY, + std::ptr::null(), + std::ptr::null(), + 0, + )); + let connection = WinHttpConnect( + session.0, + wide("127.0.0.1").as_ptr(), + listener.local_addr().unwrap().port(), + 0, + ); + assert!(!connection.is_null()); + let query = host!("winhttp.dll", "WinHttpQueryOption": extern "system" fn(Handle, u32, *mut c_void, *mut u32) -> i32); + let (mut kind, mut len) = (0u32, 4u32); + // WINHTTP_OPTION_HANDLE_TYPE = 9, WINHTTP_HANDLE_TYPE_CONNECT = 2. + assert_ne!(query(connection, 9, (&raw mut kind).cast(), &mut len), 0); + assert_eq!(kind, 2); + assert_eq!( + WinHttpSetOption( + connection, + WINHTTP_OPTION_REDIRECT_POLICY, + (&raw const policy).cast(), + 4 + ), + 0 + ); + // The option failure survives the close; querying the same handle then + // confirms that it no longer remains usable. Do not close it again. + // SAFETY: reads only this thread's error (INCORRECT_HANDLE_TYPE). + assert_eq!(unsafe { GetLastError() }, 12018); + assert_eq!(query(connection, 9, (&raw mut kind).cast(), &mut len), 0); + // SAFETY: reads only this thread's error (INVALID_HANDLE). + assert_eq!(unsafe { GetLastError() }, 6); + assert_eq!( + listener.accept().unwrap_err().kind(), + std::io::ErrorKind::WouldBlock + ); +} diff --git a/crates/victory-hle/src/modules/paths.rs b/crates/victory-hle/src/modules/paths.rs deleted file mode 100644 index 168d461c99..0000000000 --- a/crates/victory-hle/src/modules/paths.rs +++ /dev/null @@ -1,209 +0,0 @@ -//! The lexical part of Windows path rewriting for virtual drives. -//! -//! [`super::files`] hands the title's paths to the host, but the decisions -//! about drive letters, separators and `\\?\` paths are pure UTF-16 work. -//! They live here so tests cover them on every platform, not only Windows. -#![allow(clippy::not_unsafe_ptr_arg_deref)] - -pub(crate) const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16]; -pub(crate) const VERBATIM: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]; - -/// Host paths from this length on take the `\\?\` form, which lifts the -/// host's MAX_PATH limit (248 characters for a directory, 260 for a file). -const LONG: usize = 248; - -/// A mounted drive: upper-case letter and host root (UTF-16, no trailing -/// separator, no NUL). -pub(crate) type Mount = (u16, Vec<u16>); - -/// Whether `bytes`, a narrow path, names a drive (possibly through `\\?\`). -/// The drive part is ASCII in every code page, so this needs no decoding. -pub(crate) fn has_drive(bytes: &[u8]) -> bool { - matches!( - bytes.strip_prefix(br"\\?\").unwrap_or(bytes), - [letter, b':', ..] if letter.is_ascii_alphabetic() - ) -} - -/// `root` and the title's `tail` as a `\\?\` path. That form turns off the -/// host's own clean-up, so `/` becomes `\` and `.` and `..` are resolved -/// here (`..` stops at the root). -pub(crate) fn verbatim(root: &[u16], tail: &[u16]) -> Vec<u16> { - let backslash = u16::from(b'\\'); - let mut out = if root.starts_with(&VERBATIM) { - root.to_vec() - } else if let Some(unc) = root.strip_prefix(&[backslash; 2][..]) { - let mut out = VERBATIM.to_vec(); - out.extend("UNC\\".encode_utf16()); - out.extend_from_slice(unc); - out - } else { - [&VERBATIM[..], root].concat() - }; - while out.last() == Some(&backslash) { - out.pop(); - } - let dot = u16::from(b'.'); - let mut parts: Vec<&[u16]> = Vec::new(); - for part in tail.split(|c| SEPARATORS.contains(c)) { - match part { - [] => {} - [d] if *d == dot => {} - [d, e] if [*d, *e] == [dot; 2] => drop(parts.pop()), - _ => parts.push(part), - } - } - for part in parts { - out.push(backslash); - out.extend_from_slice(part); - } - out -} - -/// The host path, NUL-terminated, for `path` (without its NUL) if it is on -/// one of `mounts`. Every decision is lexical: no host calls, no filesystem. -pub(crate) fn translate(path: &[u16], mounts: &[Mount]) -> Option<Vec<u16>> { - let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) { - Some(rest) => (&VERBATIM[..], rest), - None => (&[][..], path), - }; - let &[letter, colon, ..] = rest else { - return None; - }; - if colon != u16::from(b':') { - return None; - } - let letter = u8::try_from(letter).ok().filter(u8::is_ascii_alphabetic)?; - let letter = u16::from(letter.to_ascii_uppercase()); - let (_, root) = mounts.iter().find(|(l, _)| *l == letter)?; - let tail = &rest[2..]; - if prefix.is_empty() && root.len() + tail.len() >= LONG { - let mut out = verbatim(root, tail); - out.push(0); - return Some(out); - } - let mut out = prefix.to_vec(); - out.extend_from_slice(root); - // `X:` and `X:name` are relative to the root. - if !tail.first().is_some_and(|c| SEPARATORS.contains(c)) { - out.push(b'\\'.into()); - } - let verbatim = !prefix.is_empty(); - out.extend(tail.iter().map(|&c| { - if verbatim && c == u16::from(b'/') { - b'\\'.into() - } else { - c - } - })); - out.push(0); - Some(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn wide(s: &str) -> Vec<u16> { - s.encode_utf16().collect() - } - fn text(s: &[u16]) -> String { - String::from_utf16_lossy(&s[..s.len() - usize::from(s.last() == Some(&0))]) - } - fn mounts() -> Vec<Mount> { - vec![ - (u16::from(b'X'), wide(r"C:\games\title")), - (u16::from(b'G'), wide(r"D:\package")), - // A root that is already verbatim and one that is a UNC share. - ( - u16::from(b'T'), - [&VERBATIM[..], &wide(r"E:\temp")[..]].concat(), - ), - (u16::from(b'U'), wide(r"\\server\share")), - ] - } - fn host(path: &str) -> String { - text(&translate(&wide(path), &mounts()).expect("mounted drive")) - } - - #[test] - fn rewrites_drive_paths_and_their_case() { - assert_eq!(host(r"X:\save\one.dat"), r"C:\games\title\save\one.dat"); - assert_eq!(host(r"x:\SAVE\one.dat"), r"C:\games\title\SAVE\one.dat"); - assert_eq!(host("X:/save/one.dat"), r"C:\games\title/save/one.dat"); - assert_eq!(host("G:\\"), r"D:\package\"); - } - - #[test] - fn drives_without_a_separator_stay_relative_to_the_root() { - assert_eq!(host("X:"), r"C:\games\title\"); - assert_eq!(host("X:save"), r"C:\games\title\save"); - assert_eq!(host("x:save/one.dat"), r"C:\games\title\save/one.dat"); - } - - #[test] - fn unmounted_and_malformed_paths_are_left_alone() { - assert!(translate(&wide(r"C:\Windows"), &mounts()).is_none()); - assert!(translate(&wide(r"1:\bad"), &mounts()).is_none()); - assert!(translate(&wide(r"X"), &mounts()).is_none()); - assert!(translate(&[], &mounts()).is_none()); - assert!(translate(&wide(r"Y:\unmounted"), &mounts()).is_none()); - assert!(translate(&wide(r"\\?\C:\Windows"), &mounts()).is_none()); - } - - #[test] - fn verbatim_paths_keep_their_prefix_and_use_backslashes() { - assert_eq!( - host(r"\\?\X:\save/one.dat"), - r"\\?\C:\games\title\save\one.dat" - ); - // A short verbatim path keeps its dots: the host's own `\\?\` - // handling passes them through, and only long paths are cleaned up. - assert_eq!( - host(r"\\?\x:\save/./two/../one.dat"), - r"\\?\C:\games\title\save\.\two\..\one.dat" - ); - // An already-verbatim root is not prefixed again. - assert_eq!(host(r"T:\file"), r"\\?\E:\temp\file"); - } - - #[test] - fn long_paths_take_the_verbatim_form_and_resolve_dots() { - let tail = format!("X:{}\\one.dat", "a".repeat(LONG)); - assert_eq!( - host(&tail), - format!(r"\\?\C:\games\title\{}\one.dat", "a".repeat(LONG)) - ); - let tail = format!("X:{}\\.\\up\\..\\one.dat", "a".repeat(LONG)); - assert_eq!( - host(&tail), - format!(r"\\?\C:\games\title\{}\one.dat", "a".repeat(LONG)) - ); - // `..` stops at the root instead of escaping it. - let tail = format!("X:{}\\..\\..\\one.dat", "a".repeat(LONG)); - assert_eq!(host(&tail), r"\\?\C:\games\title\one.dat".to_string()); - // Just under the limit stays in the ordinary form. - let tail = format!("X:{}", "a".repeat(LONG - r"C:\games\title".len() - 1)); - assert!(host(&tail).starts_with(r"C:\games\title")); - assert!(!host(&tail).starts_with(r"\\?\")); - } - - #[test] - fn unc_roots_become_verbatim_unc() { - let tail = format!("U:{}\\{}", "a".repeat(LONG), "file"); - assert_eq!( - host(&tail), - format!(r"\\?\UNC\server\share\{}\file", "a".repeat(LONG)) - ); - } - - #[test] - fn narrow_drive_detection_precedes_decoding() { - assert!(has_drive(br"X:\save")); - assert!(has_drive(br"x:save")); - assert!(has_drive(br"\\?\X:\save")); - assert!(!has_drive(br"\Windows")); - assert!(!has_drive(br"\\server\share")); - assert!(!has_drive(b"")); - } -} diff --git a/crates/victory-hle/src/modules/speech.rs b/crates/victory-hle/src/modules/speech.rs index 571a8d3a86..15e8eca869 100644 --- a/crates/victory-hle/src/modules/speech.rs +++ b/crates/victory-hle/src/modules/speech.rs @@ -1,15 +1,14 @@ -//! Accessibility: speech synthesis for the title's narration, spoken by -//! the host's WinRT speech synthesizer in its default voice. Streams are -//! WAVE files of 16 kHz mono 16-bit PCM, the console's format; with no -//! voice installed (or off Windows) a stream is valid WAVE audio of no -//! length and the narration is silent, as before. -// shortcut: no voices are listed and the title's voice choice is ignored; -// the host's default voice speaks everything. +//! Accessibility: speech synthesis for the title's narration. No voice is +//! installed here, and every stream is valid WAVE audio of no length, so +//! narration is silent. +// shortcut: silent speech. The host's engine (SAPI through COM, or WinRT +// speech synthesis) needs COM bindings this crate has only in diagnostics +// builds, plus voice enumeration and SSML the title sends (slot 0xa8); the +// title then plays the empty stream and goes on. #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::{c_char, c_void}; -use super::xasync::{E_INVALIDARG, E_NOT_SUFFICIENT_BUFFER}; use super::xgameruntime::{ Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, }; @@ -32,165 +31,20 @@ pub const IID: Guid = Guid::new( pub static OBJECT: Object = Object::new("accessibility", &VTABLE); pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)]; -/// The console's stream format: 16 kHz mono 16-bit PCM. -const RATE: u32 = 16_000; +/// A WAVE file of 16 kHz mono 16-bit PCM with no samples: RIFF size 36, +/// a 16-byte format chunk (PCM, 1 channel, 16,000 Hz, 32,000 bytes/s, +/// block 2, 16 bits), an empty data chunk. +const SILENCE: [u8; 44] = + *b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0"; -/// Synthesizers hold nothing, so their handle is a fixed address and -/// closing one is free. A stream's handle is its boxed WAVE file. +/// Synthesizers and streams hold nothing, so their handles are fixed +/// addresses and closing them is free. static SYNTHESIZER: u8 = 0; +static STREAM: u8 = 0; type This = *const Object; -/// A WAVE file of [`RATE`] mono 16-bit PCM holding `samples`: RIFF, a -/// 16-byte format chunk, the data chunk. -fn wave(samples: &[i16]) -> Vec<u8> { - let samples = &samples[..samples.len().min(u32::MAX as usize / 2 - 44)]; - let data = (samples.len() * 2) as u32; - let mut w = Vec::with_capacity(44 + data as usize); - w.extend_from_slice(b"RIFF"); - w.extend_from_slice(&(36 + data).to_le_bytes()); - w.extend_from_slice(b"WAVEfmt "); - w.extend_from_slice(&16u32.to_le_bytes()); - w.extend_from_slice(&1u16.to_le_bytes()); // PCM - w.extend_from_slice(&1u16.to_le_bytes()); // mono - w.extend_from_slice(&RATE.to_le_bytes()); - w.extend_from_slice(&(RATE * 2).to_le_bytes()); - w.extend_from_slice(&2u16.to_le_bytes()); // block - w.extend_from_slice(&16u16.to_le_bytes()); // bits - w.extend_from_slice(b"data"); - w.extend_from_slice(&data.to_le_bytes()); - for s in samples { - w.extend_from_slice(&s.to_le_bytes()); - } - w -} - -/// The samples of a 16-bit PCM WAVE file mixed to mono and resampled -/// (linearly) to [`RATE`]; `None` for anything else. -fn to_console(file: &[u8]) -> Option<Vec<i16>> { - if file.get(..4)? != b"RIFF" || file.get(8..12)? != b"WAVE" { - return None; - } - let (mut fmt, mut data) = (None, None); - let mut at = 12usize; - while at.checked_add(8)? <= file.len() { - let len = u32::from_le_bytes(file[at + 4..at + 8].try_into().ok()?) as usize; - let end = (at + 8).saturating_add(len).min(file.len()); - match &file[at..at + 4] { - b"fmt " => fmt = Some(&file[at + 8..end]), - b"data" => data = Some(&file[at + 8..end]), - _ => {} - } - at = at - .saturating_add(8) - .saturating_add(len) - .saturating_add(len & 1); - } - let fmt = fmt?; - let u16_at = |k: usize| fmt.get(k..k + 2).map(|b| u16::from_le_bytes([b[0], b[1]])); - let (tag, channels, bits) = (u16_at(0)?, usize::from(u16_at(2)?), u16_at(14)?); - let rate = u32::from_le_bytes(fmt.get(4..8)?.try_into().ok()?); - // PCM, or WAVE_FORMAT_EXTENSIBLE around it. - if !matches!(tag, 1 | 0xFFFE) || bits != 16 || channels == 0 || rate == 0 { - return None; - } - let mono: Vec<f32> = data? - .chunks_exact(2 * channels) - .map(|frame| { - let sum: f32 = frame - .as_chunks::<2>() - .0 - .iter() - .map(|s| f32::from(i16::from_le_bytes(*s))) - .sum(); - sum / channels as f32 - }) - .collect(); - let Some(last) = mono.len().checked_sub(1) else { - return Some(Vec::new()); - }; - let n = (mono.len() as u64 * u64::from(RATE) / u64::from(rate)) as usize; - let step = f64::from(rate) / f64::from(RATE); - Some( - (0..n) - .map(|i| { - let x = i as f64 * step; - let k = (x as usize).min(last); - let t = (x - k as f64) as f32; - let (a, b) = (mono[k], mono[(k + 1).min(last)]); - (a + (b - a) * t).round().clamp(-32768.0, 32767.0) as i16 - }) - .collect(), - ) -} - -/// SSML's text: the markup between `<` and `>` dropped. -fn plain(ssml: &str) -> String { - let mut out = String::with_capacity(ssml.len()); - let mut tag = false; - for c in ssml.chars() { - match c { - '<' => tag = true, - '>' if tag => { - tag = false; - out.push(' '); - } - c if !tag => out.push(c), - _ => {} - } - } - out -} - -/// The host's speech for `words` (SSML with `ssml`) as a WAVE file in the -/// host synthesizer's format; `None` without a voice or on failure. -#[cfg(windows)] -fn speak(words: &str, ssml: bool) -> Option<Vec<u8>> { - let words = windows::core::HSTRING::from(words); - // A thread of our own in the multithreaded apartment, whatever the - // title's thread initialised. - let spoken = std::thread::spawn(move || -> windows::core::Result<Vec<u8>> { - use windows::Media::SpeechSynthesis::SpeechSynthesizer; - use windows::Storage::Streams::DataReader; - use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx}; - // SAFETY: initialises COM on this thread, which ends after the call. - let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }; - let synth = SpeechSynthesizer::new()?; - let stream = if ssml { - synth.SynthesizeSsmlToStreamAsync(&words)?.join()? - } else { - synth.SynthesizeTextToStreamAsync(&words)?.join()? - }; - let size = u32::try_from(stream.Size()?).unwrap_or(u32::MAX); - let reader = DataReader::CreateDataReader(&stream.GetInputStreamAt(0)?)?; - reader.LoadAsync(size)?.join()?; - let mut bytes = vec![0; reader.UnconsumedBufferLength()? as usize]; - reader.ReadBytes(&mut bytes)?; - Ok(bytes) - }) - .join() - .ok()?; - spoken - .inspect_err(|e| tracing::debug!(error = %e, ssml, "speech synthesis failed")) - .ok() -} - -#[cfg(not(windows))] -fn speak(_: &str, _: bool) -> Option<Vec<u8>> { - None -} - -/// The narration of `words` at the console's format; SSML the host's -/// synthesizer refuses is spoken as its plain text. -fn narration(words: &str, ssml: bool) -> Vec<i16> { - if words.trim().is_empty() { - return Vec::new(); - } - let host = speak(words, ssml).or_else(|| ssml.then(|| speak(&plain(words), false)).flatten()); - host.and_then(|file| to_console(&file)).unwrap_or_default() -} - -/// No voice is listed, so the callback never runs. +/// No voice is installed, so the callback never runs. extern "system" fn enumerate_voices( _: This, _context: *mut c_void, @@ -210,71 +64,33 @@ extern "system" fn set_default_voice(_: This, _: *const u8) -> HRESULT { extern "system" fn set_custom_voice(_: This, _: *const u8, _voice: *const c_char) -> HRESULT { S_OK } - -fn create_stream(words: *const c_char, ssml: bool, out: *mut *const u8) -> HRESULT { - if out.is_null() { - return E_INVALIDARG; - } - let words = text(words).unwrap_or_default(); - let samples = narration(&words, ssml); - tracing::debug!(text = words, samples = samples.len(), "speech"); - let file = Box::into_raw(Box::new(wave(&samples))); - put(out, file.cast_const().cast()) -} -extern "system" fn stream_from_text( +extern "system" fn create_stream( _: This, _: *const u8, words: *const c_char, out: *mut *const u8, ) -> HRESULT { - create_stream(words, false, out) + tracing::debug!(text = text(words).unwrap_or_default(), "speech (silent)"); + put(out, &raw const STREAM) } -extern "system" fn stream_from_ssml( - _: This, - _: *const u8, - ssml: *const c_char, - out: *mut *const u8, -) -> HRESULT { - create_stream(ssml, true, out) -} - -/// The WAVE file behind a stream handle. -fn file<'a>(stream: *const u8) -> Option<&'a [u8]> { - // SAFETY: stream handles are the boxed files `create_stream` made, - // alive until `close_stream`. - (!stream.is_null()).then(|| unsafe { (*stream.cast::<Vec<u8>>()).as_slice() }) -} -extern "system" fn close_stream(_: This, stream: *const u8) -> HRESULT { - if !stream.is_null() { - // SAFETY: as in `file`; the title closes a stream once. - drop(unsafe { Box::from_raw(stream.cast::<Vec<u8>>().cast_mut()) }); - } - S_OK -} -extern "system" fn stream_size(_: This, stream: *const u8, out: *mut usize) -> HRESULT { - match file(stream) { - Some(f) => put(out, f.len()), - None => E_INVALIDARG, - } +extern "system" fn stream_size(_: This, _: *const u8, out: *mut usize) -> HRESULT { + put(out, SILENCE.len()) } extern "system" fn stream_data( _: This, - stream: *const u8, + _: *const u8, size: usize, buffer: *mut u8, used: *mut usize, ) -> HRESULT { - let Some(f) = file(stream) else { - return E_INVALIDARG; - }; - if buffer.is_null() || size < f.len() { - return E_NOT_SUFFICIENT_BUFFER; + if buffer.is_null() || size < SILENCE.len() { + return super::xasync::E_NOT_SUFFICIENT_BUFFER; } // SAFETY: the buffer holds `size` bytes, checked above. - unsafe { buffer.copy_from_nonoverlapping(f.as_ptr(), f.len()) }; + unsafe { buffer.copy_from_nonoverlapping(SILENCE.as_ptr(), SILENCE.len()) }; if !used.is_null() { // SAFETY: checked non-null. - unsafe { used.write(f.len()) }; + unsafe { used.write(SILENCE.len()) }; } S_OK } @@ -293,15 +109,15 @@ static VTABLE: Methods<22> = Methods([ close as *const (), // 0x50 set_default_voice as *const (), // 0x58 set_custom_voice as *const (), // 0x60 - stream_from_text as *const (), // 0x68 from text - close_stream as *const (), // 0x70 a stream + create_stream as *const (), // 0x68 from text + close as *const (), // 0x70 a stream stream_size as *const (), // 0x78 stream_data as *const (), // 0x80 missing::<17> as *const (), // 0x88 speech to text missing::<18> as *const (), // 0x90 missing::<19> as *const (), // 0x98 missing::<20> as *const (), // 0xa0 - stream_from_ssml as *const (), // 0xa8 from SSML + create_stream as *const (), // 0xa8 from SSML ]); #[cfg(test)] @@ -309,99 +125,27 @@ mod tests { use super::*; use crate::modules::xgameruntime::method; - type Create = extern "system" fn(This, *mut *const u8) -> HRESULT; - type Stream = extern "system" fn(This, *const u8, *const c_char, *mut *const u8) -> HRESULT; - type Close = extern "system" fn(This, *const u8) -> HRESULT; - type Size = extern "system" fn(This, *const u8, *mut usize) -> HRESULT; - type Data = extern "system" fn(This, *const u8, usize, *mut u8, *mut usize) -> HRESULT; - - /// The stream the title gets for `words` through `slot`, read as it - /// reads one, then closed. - fn spoken(slot: usize, words: &std::ffi::CStr) -> Vec<u8> { + #[test] + fn streams_are_empty_wave_files() { let this: This = &OBJECT; + type Create = extern "system" fn(This, *mut *const u8) -> HRESULT; + type Stream = extern "system" fn(This, *const u8, *const c_char, *mut *const u8) -> HRESULT; + type Size = extern "system" fn(This, *const u8, *mut usize) -> HRESULT; + type Data = extern "system" fn(This, *const u8, usize, *mut u8, *mut usize) -> HRESULT; let (mut synth, mut stream, mut size) = (std::ptr::null(), std::ptr::null(), 0); assert_eq!(method::<Create>(&OBJECT, 0x48)(this, &mut synth), S_OK); - let say = method::<Stream>(&OBJECT, slot); - assert_eq!(say(this, synth, words.as_ptr(), &mut stream), S_OK); + let say = method::<Stream>(&OBJECT, 0x68); + assert_eq!(say(this, synth, c"Hello".as_ptr(), &mut stream), S_OK); assert_eq!(method::<Size>(&OBJECT, 0x78)(this, stream, &mut size), S_OK); let mut wav = vec![0u8; size]; let mut used = 0; let data = method::<Data>(&OBJECT, 0x80); - let short = data(this, stream, size - 1, wav.as_mut_ptr(), &mut used); - assert_eq!(short, E_NOT_SUFFICIENT_BUFFER); assert_eq!(data(this, stream, size, wav.as_mut_ptr(), &mut used), S_OK); - assert_eq!(used, size); - assert_eq!(method::<Close>(&OBJECT, 0x70)(this, stream), S_OK); - assert_eq!(method::<Close>(&OBJECT, 0x50)(this, synth), S_OK); assert_eq!( (&wav[..4], &wav[8..16], &wav[36..40]), (&b"RIFF"[..], &b"WAVEfmt "[..], &b"data"[..]) ); - assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), RATE); - let data_len = u32::from_le_bytes(wav[40..44].try_into().unwrap()) as usize; - assert_eq!(data_len, size - 44); - wav - } - - #[test] - fn empty_text_is_an_empty_wave_file() { - assert_eq!(spoken(0x68, c"").len(), 44); - } - - #[test] - fn text_and_ssml_are_spoken_when_a_voice_is_installed() { - if speak("a", false).is_none() { - eprintln!("no voice; skipped"); - return; - } - let ssml = c"<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>Press <emphasis>A</emphasis> to continue</speak>"; - for (slot, words) in [(0x68, c"Press A to continue"), (0xa8, ssml)] { - let wav = spoken(slot, words); - let loud = wav[44..] - .as_chunks::<2>() - .0 - .iter() - .filter(|s| i16::from_le_bytes(**s).unsigned_abs() > 1000) - .count(); - // Half a second or more of audio, and not silence. - assert!( - wav.len() > 44 + RATE as usize, - "{slot:#x}: {} bytes", - wav.len() - ); - assert!(loud > 1000, "{slot:#x}: {loud} loud samples"); - } - } - - #[test] - fn host_audio_is_mixed_and_resampled() { - // 22,050 Hz stereo: left 1000, right 3000, for 2,205 frames, after - // an odd-sized chunk the reader skips with its pad byte. - let mut file = b"RIFF\0\0\0\0WAVEfmt ".to_vec(); - for v in [16u32, 1 | 2 << 16, 22_050, 22_050 * 4, 4 | 16 << 16] { - file.extend_from_slice(&v.to_le_bytes()); - } - file.extend_from_slice(b"LIST"); - file.extend_from_slice(&3u32.to_le_bytes()); - file.extend_from_slice(b"abc\0data"); - file.extend_from_slice(&(2_205u32 * 4).to_le_bytes()); - for _ in 0..2_205 { - file.extend_from_slice(&1000i16.to_le_bytes()); - file.extend_from_slice(&3000i16.to_le_bytes()); - } - let out = to_console(&file).unwrap(); - assert_eq!(out.len(), 1_600); - assert!(out.iter().all(|&s| s == 2000)); - // Not 16-bit PCM, or not WAVE. - let mut eight = file.clone(); - eight[34] = 8; - assert_eq!(to_console(&eight), None); - assert_eq!(to_console(b"RIFF\0\0\0\0AVI "), None); - } - - #[test] - fn ssml_text_without_markup() { - let words = plain("<speak>Press <emphasis>A</emphasis></speak>"); - assert_eq!(words.split_whitespace().collect::<Vec<_>>(), ["Press", "A"]); + assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 16_000); + assert_eq!(used, 44); } } diff --git a/crates/victory-hle/src/modules/storage.rs b/crates/victory-hle/src/modules/storage.rs index 585b641a1e..600cbad97c 100644 --- a/crates/victory-hle/src/modules/storage.rs +++ b/crates/victory-hle/src/modules/storage.rs @@ -26,7 +26,7 @@ pub const IID: Guid = Guid::new( [0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d], ); -/// As Grand Theft Auto VI (2026) asks for it; it calls 0x20 (path) and 0x28 +/// As the title (2026) asks for it; it calls 0x20 (path) and 0x28 /// (space) with the same arguments. pub const IID_2026: Guid = Guid::new( 0x41a4_e10c, diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 0b962691ad..068d75f2a8 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -472,10 +472,6 @@ struct Call { provider: Provider, context: usize, identity: usize, - /// Set by the first completion, which then runs without a lock: the - /// provider's cleanup may wait for a thread completing the same call. - claimed: AtomicBool, - /// The status is published. done: Mutex<bool>, finished: Condvar, } @@ -505,14 +501,6 @@ fn call(block: *mut AsyncBlock) -> Option<Arc<Call>> { lock(&CALLS).get(&(block as usize)).cloned() } -/// Whether `call` is still the call in flight on `block`: once it is over, -/// the title may begin another call on the same block. -fn is_current(call: &Arc<Call>, block: *mut AsyncBlock) -> bool { - lock(&CALLS) - .get(&(block as usize)) - .is_some_and(|current| Arc::ptr_eq(current, call)) -} - /// The block's status and result-size words. fn words(block: *mut AsyncBlock) -> (&'static AtomicUsize, &'static AtomicUsize) { // SAFETY: the title's block outlives the call; its system area is ours. @@ -526,12 +514,6 @@ fn status(block: *mut AsyncBlock) -> HRESULT { words(block).0.load(Ordering::Acquire) as u32 as i32 } -/// Whether the block's system area is all zero, as in a block not yet used. -fn zeroed(block: *mut AsyncBlock) -> bool { - // SAFETY: the title's block, whose system area is ours to read. - unsafe { std::ptr::addr_of!((*block).internal).read_volatile() == [0; 4] } -} - fn release(block: *mut AsyncBlock) { // Unlocked before the provider runs: it may call back into us. let removed = lock(&CALLS).remove(&(block as usize)); @@ -550,23 +532,9 @@ pub fn XAsyncBegin( let Some(provider) = provider else { return E_INVALIDARG; }; - if block.is_null() { + if block.is_null() || call(block).is_some() { return E_INVALIDARG; } - if let Some(left) = call(block) { - // Calls are filed by block address, and one that succeeded stays - // filed until its result is taken. A title that never takes it and - // frees the block may get the same address for its next one, which - // it zeroes as every new block must be; the block of a result left - // behind never reads zero (it holds the result's size). So this is - // a new block, and the call left behind ends here. A call in flight - // keeps its address, and a block still holding a result is in use. - let over = *lock(&left.done); - if !(over && zeroed(block)) { - return E_INVALIDARG; - } - release(block); - } let (status, size) = words(block); status.store(E_PENDING as u32 as usize, Ordering::Release); size.store(0, Ordering::Release); @@ -574,7 +542,6 @@ pub fn XAsyncBegin( provider, context: context as usize, identity: identity as usize, - claimed: AtomicBool::new(false), done: Mutex::new(false), finished: Condvar::new(), }); @@ -582,66 +549,39 @@ pub fn XAsyncBegin( // A failed begin fails the call, so the completion routine still runs. let hr = call.provider(OP_BEGIN, block, 0, std::ptr::null_mut()); if hr < 0 { - complete_call(&call, block, hr, 0); + XAsyncComplete(block, hr, 0); } S_OK } -/// Queues the provider's `DoWork` on the block's work port. The work -/// belongs to the call that scheduled it: when it runs, that call may be -/// over and the block may hold another. +/// Queues the provider's `DoWork` on the block's work port. pub fn XAsyncSchedule(block: *mut AsyncBlock, delay_ms: u32) -> HRESULT { - struct Work { - call: Arc<Call>, - block: *mut AsyncBlock, - } - extern "system" fn work(context: *mut c_void, canceled: bool) { - // SAFETY: boxed in `XAsyncSchedule`; a task runs once. - let Work { call, block } = *unsafe { Box::from_raw(context.cast::<Work>()) }; - if !is_current(&call, block) { - return; - } + extern "system" fn work(block: *mut c_void, canceled: bool) { + let block = block.cast::<AsyncBlock>(); + let Some(call) = call(block) else { return }; let hr = if canceled { E_ABORT } else { call.provider(OP_DO_WORK, block, 0, std::ptr::null_mut()) }; - complete_call(&call, block, hr, 0); + if hr != E_PENDING { + XAsyncComplete(block, hr, 0); + } } - if block.is_null() { + if block.is_null() || call(block).is_none() { return E_INVALIDARG; } - let Some(call) = call(block) else { - return E_INVALIDARG; - }; // SAFETY: a block in flight is valid. let handle = unsafe { (*block).queue }; - let Some(queue) = queue(handle) else { - return E_INVALIDARG; - }; - let context = Box::into_raw(Box::new(Work { call, block })); - let hr = queue.submit(WORK, delay_ms, Task::new(context.cast(), work)); - if hr < 0 { - // Refused, so the task never runs. - // SAFETY: still ours. - drop(unsafe { Box::from_raw(context) }); + match queue(handle) { + Some(queue) => queue.submit(WORK, delay_ms, Task::new(block.cast(), work)), + None => E_INVALIDARG, } - hr } /// Records the result (the first one wins), wakes waiters and queues the /// completion routine on the block's completion port. pub fn XAsyncComplete(block: *mut AsyncBlock, result: HRESULT, required_size: usize) { - if let Some(call) = call(block) { - complete_call(&call, block, result, required_size); - } -} - -/// [`XAsyncComplete`] for `call`, which is or was in flight on `block`. Our -/// own completions name the call they belong to, not the block: if the -/// provider already completed it, the title may have begun another call on -/// the block, which a second complete by block would end. -fn complete_call(call: &Call, block: *mut AsyncBlock, result: HRESULT, required_size: usize) { extern "system" fn complete(block: *mut c_void, _canceled: bool) { let block = block.cast::<AsyncBlock>(); // SAFETY: read before the status was published; see below. @@ -649,10 +589,12 @@ fn complete_call(call: &Call, block: *mut AsyncBlock, result: HRESULT, required_ routine(block); } } + let Some(call) = call(block) else { return }; if result == E_PENDING { return; } - if call.claimed.swap(true, Ordering::AcqRel) { + let mut done = lock(&call.done); + if *done { return; } // Read before publishing: once the status is set, the title may free @@ -665,8 +607,9 @@ fn complete_call(call: &Call, block: *mut AsyncBlock, result: HRESULT, required_ } size.store(required_size, Ordering::Release); status.store(result as u32 as usize, Ordering::Release); - *lock(&call.done) = true; + *done = true; call.finished.notify_all(); + drop(done); if routine.is_some() { let task = Task::new(block.cast(), complete); match queue(handle) { @@ -706,7 +649,7 @@ pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT { pub fn XAsyncCancel(block: *mut AsyncBlock) { if let Some(call) = call(block) { call.provider(OP_CANCEL, block, 0, std::ptr::null_mut()); - complete_call(&call, block, E_ABORT, 0); + XAsyncComplete(block, E_ABORT, 0); } } @@ -812,18 +755,12 @@ pub fn finished_with( /// Like [`finished_with`], but the result comes from `work`, run on a /// thread of ours; the call stays pending until it returns (a dialog, say). -/// -/// The thread may outlive the call: a canceled call ends at once, its state -/// is cleaned up and the title may begin its next call on the same block. -/// So the thread shares the state rather than borrowing it, and completes -/// only its own call, if that is still the block's. pub fn pending_with( block: *mut AsyncBlock, identity: *const c_void, work: impl FnOnce() -> Result<Vec<u8>, HRESULT> + Send + 'static, ) -> HRESULT { - type Work = Box<dyn FnOnce() -> Result<Vec<u8>, HRESULT> + Send>; - type Data = Arc<Mutex<(Option<Work>, Vec<u8>)>>; + type Data = Mutex<(Option<Box<dyn FnOnce() -> Result<Vec<u8>, HRESULT> + Send>>, Vec<u8>)>; extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { // SAFETY: the runtime passes valid provider data; the context is the // boxed state until cleanup frees it. @@ -833,11 +770,9 @@ pub fn pending_with( // SAFETY: boxed in `pending_with`; nothing runs after cleanup. OP_CLEANUP => drop(unsafe { Box::from_raw(state) }), OP_BEGIN => { - // SAFETY: as above; the call is beginning, so not cleaned up. - let state = unsafe { &*state }.clone(); - let work = lock(&state).0.take(); - // The call being begun, already the block's. - let (block, mine) = (data.block as usize, call(data.block)); + // SAFETY: as above; cleanup waits for completion. + let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take(); + let (block, state) = (data.block as usize, state as usize); std::thread::spawn(move || { let result = work.map_or(Err(E_ABORT), |work| work()); let (hr, len) = match &result { @@ -845,13 +780,11 @@ pub fn pending_with( Err(hr) => (*hr, 0), }; if let Ok(bytes) = result { - lock(&state).1 = bytes; - } - let block = block as *mut AsyncBlock; - let current = call(block); - if mine.is_some_and(|mine| current.is_some_and(|c| Arc::ptr_eq(&c, &mine))) { - XAsyncComplete(block, hr, len); + // SAFETY: the call is pending, so its state lives. + let state = unsafe { &*(state as *const Data) }; + state.lock().unwrap_or_else(|e| e.into_inner()).1 = bytes; } + XAsyncComplete(block as *mut AsyncBlock, hr, len); }); } // SAFETY: as above; the runtime checked the buffer's size. @@ -865,16 +798,9 @@ pub fn pending_with( } S_OK } - let work: Work = Box::new(work); - let state: Box<Data> = Box::new(Arc::new(Mutex::new((Some(work), Vec::new())))); + let state: Box<Data> = Box::new(Mutex::new((Some(Box::new(work)), Vec::new()))); let context = Box::into_raw(state); - let hr = XAsyncBegin( - block, - context.cast(), - identity, - std::ptr::null(), - Some(provider), - ); + let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider)); if hr < 0 { // SAFETY: refused before the call existed; still ours. drop(unsafe { Box::from_raw(context) }); @@ -1160,62 +1086,6 @@ mod tests { COMPLETED.fetch_add(1, Ordering::SeqCst); } - /// A title that never takes a call's result and frees its block: the - /// next block allocated at that address (zeroed, as a new block must - /// be) begins a call like any other. - #[test] - fn a_new_block_where_a_result_was_left_begins_a_call() { - static CLEANED: AtomicU32 = AtomicU32::new(0); - /// Completes at once with one byte to fetch; counts its cleanups. - extern "system" fn left(op: u32, data: *const ProviderData) -> HRESULT { - match op { - // SAFETY: the runtime passes valid provider data. - OP_BEGIN => XAsyncComplete(unsafe { (*data).block }, S_OK, 1), - OP_CLEANUP => drop(CLEANED.fetch_add(1, Ordering::SeqCst)), - _ => {} - } - S_OK - } - /// Never completes by itself. - extern "system" fn idle(_: u32, _: *const ProviderData) -> HRESULT { - S_OK - } - let fresh = || AsyncBlock { - queue: std::ptr::null(), - context: std::ptr::null_mut(), - callback: None, - internal: [0; 4], - }; - let (none, identity) = (std::ptr::null_mut(), 0x1e as *const c_void); - let begin = |block: &mut AsyncBlock, provider: Provider| { - XAsyncBegin(block, none, identity, std::ptr::null(), Some(provider)) - }; - - let mut block = fresh(); - assert_eq!(begin(&mut block, left), S_OK); - assert_eq!(XAsyncGetStatus(&mut block, false), S_OK); - // The block as the call left it is still that call's. - assert_eq!(begin(&mut block, left), E_INVALIDARG); - assert_eq!(CLEANED.load(Ordering::SeqCst), 0); - - // Freed with its result never taken, and a new block in its place. - block = fresh(); - assert_eq!(finished_with(&mut block, identity, Ok(vec![9])), S_OK); - assert_eq!(CLEANED.load(Ordering::SeqCst), 1, "the call left behind"); - let mut value = 0u8; - assert_eq!(result(&mut block, identity, &mut value), S_OK); - assert_eq!(value, 9); - assert!(call(&mut block).is_none()); - - // A call still in flight keeps its address, whatever the block holds. - let mut block = fresh(); - assert_eq!(begin(&mut block, idle), S_OK); - block = fresh(); - assert_eq!(begin(&mut block, left), E_INVALIDARG); - XAsyncComplete(&mut block, E_ABORT, 0); - assert!(call(&mut block).is_none()); - } - #[test] fn async_calls_complete_and_return_results() { let mut q = std::ptr::null(); @@ -1264,156 +1134,6 @@ mod tests { XTaskQueueCloseHandle(q); } - /// What a test sees of a block that a title reuses: its completion - /// routine begins the next call on the same block. - #[derive(Default)] - struct Reuse { - completions: AtomicU32, - next_begun: AtomicBool, - next_worked: AtomicBool, - } - - /// A block whose completion routine is [`begin_next`]. - fn reused_block(queue: *const Queue, reuse: &Reuse) -> AsyncBlock { - AsyncBlock { - queue, - context: std::ptr::from_ref(reuse).cast_mut().cast(), - callback: Some(begin_next), - internal: [0; 4], - } - } - - /// Begins a call without an identity. - fn begin(block: *mut AsyncBlock, context: *mut c_void, provider: Provider) -> HRESULT { - let none = std::ptr::null(); - XAsyncBegin(block, context, none, none.cast(), Some(provider)) - } - - /// Begins the next call on the block the first time a call completes, - /// as a title that keeps one block for repeated calls does. - extern "system" fn begin_next(block: *mut AsyncBlock) { - // SAFETY: the block is from `reused_block`, its `Reuse` still alive. - let context = unsafe { (*block).context }; - // SAFETY: as above. - let reuse = unsafe { &*context.cast::<Reuse>() }; - if reuse.completions.fetch_add(1, Ordering::SeqCst) == 0 { - let hr = begin(block, context, next_call); - reuse.next_begun.store(hr == S_OK, Ordering::SeqCst); - } - } - - /// The next call's provider: it never ends on its own, and notes being - /// asked to work. - extern "system" fn next_call(op: u32, data: *const ProviderData) -> HRESULT { - // SAFETY: the runtime passes valid provider data; its context is - // the test's `Reuse`. - let reuse = unsafe { &*(*data).context.cast::<Reuse>() }; - if op == OP_DO_WORK { - reuse.next_worked.store(true, Ordering::SeqCst); - return E_PENDING; - } - S_OK - } - - /// A provider that ends its call itself, in `DoWork` and on cancel, then - /// returns `S_OK`, as providers do. - extern "system" fn ends_itself(op: u32, data: *const ProviderData) -> HRESULT { - // SAFETY: the runtime passes valid provider data. - let block = unsafe { (*data).block }; - match op { - OP_DO_WORK => XAsyncComplete(block, S_OK, 0), - OP_CANCEL => XAsyncComplete(block, E_ABORT, 0), - _ => {} - } - S_OK - } - - #[test] - fn a_finished_calls_work_result_leaves_the_next_call_alone() { - let mut q = std::ptr::null(); - // Work dispatched by hand; completion routines run where the call - // completes, inside the provider's `DoWork`. - assert_eq!(XTaskQueueCreate(0, 3, &mut q), S_OK); - let reuse = Reuse::default(); - let mut block = reused_block(q, &reuse); - assert_eq!(begin(&mut block, std::ptr::null_mut(), ends_itself), S_OK); - assert_eq!(XAsyncSchedule(&mut block, 0), S_OK); - assert!(XTaskQueueDispatch(q, WORK, 0)); - assert!(reuse.next_begun.load(Ordering::SeqCst)); - assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING); - assert_eq!(reuse.completions.load(Ordering::SeqCst), 1); - - XAsyncCancel(&mut block); - assert_eq!(XAsyncGetStatus(&mut block, false), E_ABORT); - XTaskQueueCloseHandle(q); - } - - #[test] - fn a_canceled_call_leaves_the_next_call_alone() { - let mut q = std::ptr::null(); - assert_eq!(XTaskQueueCreate(0, 3, &mut q), S_OK); - let reuse = Reuse::default(); - let mut block = reused_block(q, &reuse); - assert_eq!(begin(&mut block, std::ptr::null_mut(), ends_itself), S_OK); - assert_eq!(XAsyncSchedule(&mut block, 0), S_OK); - // The provider ends the call on cancel, before its work has run. - XAsyncCancel(&mut block); - assert!(reuse.next_begun.load(Ordering::SeqCst)); - assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING); - // The canceled call's work is still queued; it runs nothing now. - assert!(XTaskQueueDispatch(q, WORK, 0)); - assert!(!reuse.next_worked.load(Ordering::SeqCst)); - assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING); - assert_eq!(reuse.completions.load(Ordering::SeqCst), 1); - - XAsyncCancel(&mut block); - assert_eq!(XAsyncGetStatus(&mut block, false), E_ABORT); - XTaskQueueCloseHandle(q); - } - - #[test] - fn a_canceled_pending_call_leaves_the_next_call_alone() { - static IDENTITY: u8 = 0; - let identity = (&raw const IDENTITY).cast(); - let mut block = AsyncBlock { - queue: std::ptr::null(), - context: std::ptr::null_mut(), - callback: None, - internal: [0; 4], - }; - // Work that runs until it is told to finish (a dialog, say). - let gated = |result: Vec<u8>| { - let (go, wait) = std::sync::mpsc::channel::<()>(); - let work = move || { - let _ = wait.recv(); - Ok(result) - }; - (go, work) - }; - let (finish_first, first) = gated(vec![1, 2, 3]); - assert_eq!(pending_with(&mut block, identity, first), S_OK); - XAsyncCancel(&mut block); - assert_eq!(XAsyncGetStatus(&mut block, true), E_ABORT); - - // The title begins its next call on the same block; then the - // canceled call's work ends. - let (finish_second, second) = gated(vec![9]); - assert_eq!(pending_with(&mut block, identity, second), S_OK); - finish_first.send(()).unwrap(); - std::thread::sleep(Duration::from_millis(200)); - assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING); - - finish_second.send(()).unwrap(); - assert_eq!(XAsyncGetStatus(&mut block, true), S_OK); - let (mut out, mut used) = ([0u8; 4], 0); - let buffer = out.as_mut_ptr().cast(); - assert_eq!( - XAsyncGetResult(&mut block, identity, 4, buffer, &mut used), - S_OK - ); - assert_eq!(&out[..used], [9]); - } - #[test] fn a_nonnegative_completion_still_returns_its_payload() { const S_FALSE: HRESULT = 1; @@ -1444,13 +1164,7 @@ mod tests { }; let identity = 0x77 as *const c_void; assert_eq!( - XAsyncBegin( - &mut block, - std::ptr::null_mut(), - identity, - std::ptr::null(), - Some(provider) - ), + XAsyncBegin(&mut block, std::ptr::null_mut(), identity, std::ptr::null(), Some(provider)), S_OK ); assert!(XTaskQueueDispatch(q, WORK, 0)); @@ -1461,20 +1175,11 @@ mod tests { let mut value = 0u64; let mut used = 0; assert_eq!( - XAsyncGetResult( - &mut block, - identity, - 8, - (&mut value as *mut u64).cast(), - &mut used - ), + XAsyncGetResult(&mut block, identity, 8, (&mut value as *mut u64).cast(), &mut used), S_OK ); assert_eq!((value, used), (0x1234, 8)); - assert!( - call(&raw mut block).is_none(), - "the call ends with its result" - ); + assert!(call(&raw mut block).is_none(), "the call ends with its result"); XTaskQueueCloseHandle(q); } @@ -1629,40 +1334,4 @@ mod tests { ); XTaskQueueCloseHandle(q); } - - /// The call a test provider looks at in its cleanup, and what it saw - /// (1: the completion lock was free, 2: held). - static CLEANED: Mutex<Option<Arc<Call>>> = Mutex::new(None); - static SEEN: AtomicU32 = AtomicU32::new(0); - - extern "system" fn cleanup_checks(op: u32, _: *const ProviderData) -> HRESULT { - if op == OP_CLEANUP { - let call = CLEANED.lock().unwrap().clone(); - let free = call.is_some_and(|c| c.done.try_lock().is_ok()); - SEEN.store(if free { 1 } else { 2 }, Ordering::SeqCst); - } - S_OK - } - - /// A failed call's cleanup runs without the completion lock: a cleanup - /// that waits for a thread completing the same call would otherwise - /// deadlock with it. The status is published after the cleanup. - #[test] - fn cleanup_runs_without_the_completion_lock() { - let mut block = AsyncBlock { - queue: std::ptr::null(), - context: std::ptr::null_mut(), - callback: None, - internal: [0; 4], - }; - let (context, none) = (std::ptr::null_mut(), std::ptr::null()); - let provider = Some(cleanup_checks as Provider); - let begun = XAsyncBegin(&mut block, context, none, none.cast(), provider); - assert_eq!(begun, S_OK); - *CLEANED.lock().unwrap() = call(&mut block); - XAsyncComplete(&mut block, E_ABORT, 0); - assert_eq!(SEEN.load(Ordering::SeqCst), 1, "cleanup ran under the lock"); - assert_eq!(XAsyncGetStatus(&mut block, true), E_ABORT); - *CLEANED.lock().unwrap() = None; - } } diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs index f5cbeebd66..56011ec5fe 100644 --- a/crates/victory-hle/src/modules/xg.rs +++ b/crates/victory-hle/src/modules/xg.rs @@ -3,7 +3,7 @@ //! slice lies, and to copy linear data into tiled memory and back. Served //! from `victory_formats::texture`. //! -//! Grand Theft Auto VI imports `XGCreateTextureComputer` and +//! The title imports `XGCreateTextureComputer` and //! `XGSuggestSwizzleMode` and calls these computer methods: Release (0x08), //! the layout (0x10), copies into (0x40) and out of (0x48) a subresource, //! and the 64 KiB tiling (0x50). The other slots log and fail. @@ -15,7 +15,6 @@ use std::sync::atomic::{AtomicU32, Ordering}; use victory_formats::texture::{Dimension, Error, Layout, Swizzle, Texture, TextureDesc}; -use super::release_ref; use super::xasync::{E_INVALIDARG, E_NOTIMPL}; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleModule, hle_export}; @@ -135,7 +134,7 @@ pub extern "system" fn XGCreateTextureComputer( S_OK } -fn texture_desc(desc: &ResourceDesc) -> Option<TextureDesc> { +fn texture(desc: &ResourceDesc) -> Option<Texture> { let dimension = match desc.dimension { TEXTURE_1D => Dimension::Tex1d, 3 => Dimension::Tex2d, @@ -148,7 +147,7 @@ fn texture_desc(desc: &ResourceDesc) -> Option<TextureDesc> { l if l & !0xff == SWIZZLED => Swizzle(l & 0xff), _ => return None, }; - Some(TextureDesc { + let texture = Texture::new(&TextureDesc { dimension, width: u32::try_from(desc.width).ok()?, height: desc.height, @@ -158,10 +157,7 @@ fn texture_desc(desc: &ResourceDesc) -> Option<TextureDesc> { samples: desc.samples.max(1), swizzle, }) -} - -fn texture(desc: &ResourceDesc) -> Option<Texture> { - let texture = Texture::new(&texture_desc(desc)?).ok()?; + .ok()?; // The layout struct has room for 15 mips. (texture.planes[0].layout.mips.len() <= MIPS).then_some(texture) } @@ -169,7 +165,7 @@ fn texture(desc: &ResourceDesc) -> Option<Texture> { const MIPS: usize = 15; /// One mip in the layout the title reads (offsets 0x00, 0x08, 0x10 and -/// 0x1c are read by Grand Theft Auto VI; the rest follow the library's +/// 0x1c are read by the title; the rest follow the library's /// older public shape). #[repr(C)] #[derive(Debug, Default, Clone, Copy)] @@ -284,13 +280,13 @@ extern "system" fn add_ref(this: This) -> u32 { } extern "system" fn release(this: This) -> u32 { - let left = release_ref(&computer(this).refs, "texture computer"); - if left == Some(0) { + let left = computer(this).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { // SAFETY: made by `Box::into_raw` in `XGCreateTextureComputer`; the // last reference is gone. drop(unsafe { Box::from_raw(this) }); } - left.unwrap_or(0) + left } extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { @@ -304,6 +300,8 @@ extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { out.write_bytes(0, 1); &mut *out }; + out.size = c.texture.size; + out.alignment = c.texture.alignment; out.mips = c.mips; out.planes = c.texture.planes.len() as u32; out.dimension = c.desc.dimension; @@ -311,28 +309,6 @@ extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { // without mips. let depth = c.desc.flags & ALLOW_DEPTH_STENCIL != 0 && (c.texture.planes.len() > 1 || c.mips == 1); - // A render target or depth buffer also needs memory for the console's - // compression metadata. Its plane shapes are not published, so report - // an upper-bound reservation after the data planes rather than making - // up plane types the title might try to copy from. - let render = c.desc.flags & (ALLOW_RENDER_TARGET | ALLOW_DEPTH_STENCIL) != 0; - let meta = texture_desc(&c.desc) - .map(|d| victory_formats::texture::metadata(&d, &c.texture, depth, render)) - .unwrap_or(0); - if meta > 0 { - let offset = c - .texture - .size - .next_multiple_of(victory_formats::texture::METADATA_ALIGNMENT); - out.size = offset + meta; - out.alignment = c - .texture - .alignment - .max(victory_formats::texture::METADATA_ALIGNMENT); - } else { - out.size = c.texture.size; - out.alignment = c.texture.alignment; - } for (plane, p) in out.plane.iter_mut().zip(&c.texture.planes) { let l = &p.layout; plane.usage = match (p.stencil, depth) { @@ -355,13 +331,12 @@ extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { } /// The plane, its mip and array slice for a subresource index, and the -/// tiled byte range and linear byte count the copy touches. +/// tiled bytes and the linear bytes the copy touches. struct CopyArgs<'a> { layout: &'a Layout, mip: u32, slice: u32, - tiled_offset: usize, - tiled_len: usize, + tiled: usize, linear: usize, } @@ -375,37 +350,15 @@ fn copy_args( let p = c.texture.planes.get(plane as usize)?; let l = &p.layout; let (mip, slice) = (subresource % c.mips, subresource / c.mips); - if slice >= l.slices { - return None; - } let m = l.mips.get(mip as usize)?; - let bytes = usize::try_from(m.width) - .ok()? - .checked_mul(usize::try_from(l.desc.element_bytes).ok()?)?; - let depths = usize::try_from(l.subresource_depth(mip)).ok()?; - let depth_span = depths - .checked_sub(1)? - .checked_mul(usize::try_from(depth).ok()?)?; - let row_span = usize::try_from(m.height) - .ok()? - .checked_sub(1)? - .checked_mul(usize::try_from(row).ok()?)?; - let linear = depth_span.checked_add(row_span)?.checked_add(bytes)?; - if linear > isize::MAX as usize { - return None; - } - let tiled_end = p.offset.checked_add(l.size)?; - if usize::try_from(tiled_end).ok()? > isize::MAX as usize { - return None; - } - let tiled_offset = usize::try_from(p.offset).ok()?; - let tiled_len = usize::try_from(l.size).ok()?; + let bytes = m.width as usize * l.desc.element_bytes as usize; + let depths = l.subresource_depth(mip) as usize; + let linear = (depths - 1) * depth as usize + (m.height as usize - 1) * row as usize + bytes; Some(CopyArgs { layout: l, mip, slice, - tiled_offset, - tiled_len, + tiled: (p.offset + l.size) as usize, linear, }) } @@ -435,10 +388,11 @@ extern "system" fn copy_into( if tiled.is_null() || linear.is_null() { return E_INVALIDARG; } + let offset = c.texture.planes[plane as usize].offset as usize; // SAFETY: the title's memory holds the whole texture and its rows. let (tiled, linear) = unsafe { ( - std::slice::from_raw_parts_mut(tiled.add(a.tiled_offset), a.tiled_len), + std::slice::from_raw_parts_mut(tiled.add(offset), a.tiled - offset), std::slice::from_raw_parts(linear, a.linear), ) }; @@ -471,10 +425,11 @@ extern "system" fn copy_from( if tiled.is_null() || linear.is_null() { return E_INVALIDARG; } + let offset = c.texture.planes[plane as usize].offset as usize; // SAFETY: the title's memory holds the whole texture and its rows. let (tiled, linear) = unsafe { ( - std::slice::from_raw_parts(tiled.add(a.tiled_offset), a.tiled_len), + std::slice::from_raw_parts(tiled.add(offset), a.tiled - offset), std::slice::from_raw_parts_mut(linear, a.linear), ) }; @@ -529,10 +484,6 @@ extern "system" fn tiling( if l.thick { return E_NOTIMPL; } - // SAFETY: `count` is null or a valid pointer to the caller's capacity. - if unsafe { count.as_ref().is_some_and(|&n| n > 0) } && out.is_null() { - return E_INVALIDARG; - } let standard = l.first_tail_mip; let tail = standard < c.mips; let tail_tiles = match standard { @@ -541,8 +492,8 @@ extern "system" fn tiling( _ => 0, }; let block = l.desc.block; - // SAFETY: each output is null or room for its value; `out` is non-null - // whenever `*count > 0` and has room for `*count` entries. + // SAFETY: each output is null or room for its value; `out` has room + // for `*count` entries. unsafe { if let Some(t) = tiles.as_mut() { *t = (l.size / TILE) as u32; @@ -560,7 +511,7 @@ extern "system" fn tiling( } if let Some(n) = count.as_mut() { let slices = if tail { l.slices.min(2) } else { l.slices }; - let wanted = standard.saturating_mul(slices).saturating_sub(first).min(*n); + let wanted = (standard * slices).saturating_sub(first).min(*n); for i in 0..wanted { let (slice, mip) = ((first + i) / standard, (first + i) % standard); let m = &l.mips[mip as usize]; @@ -588,7 +539,7 @@ extern "system" fn tiling( } /// Slot 0x30 `(plane, mip, x, y, z or slice, sample, bit position)`: an -/// element's byte offset from the texture's start. Grand Theft Auto VI reads +/// element's byte offset from the texture's start. The title reads /// texels of a 128x4 `4KB_S` texture on the CPU through it (title+0x5151c90); /// an error returned as an offset made it read wild memory. 0 if outside. extern "system" fn element_offset( @@ -631,19 +582,19 @@ struct Vtable([*const (); 13]); unsafe impl Sync for Vtable {} static VTABLE: Vtable = Vtable([ - add_ref as *const (), // 0x00 - release as *const (), // 0x08 - layout as *const (), // 0x10 - unused as *const (), // 0x18 size - unused as *const (), // 0x20 alignment - unused as *const (), // 0x28 mip offset + add_ref as *const (), // 0x00 + release as *const (), // 0x08 + layout as *const (), // 0x10 + unused as *const (), // 0x18 size + unused as *const (), // 0x20 alignment + unused as *const (), // 0x28 mip offset element_offset as *const (), // 0x30 - unused as *const (), // 0x38 element coordinate - copy_into as *const (), // 0x40 - copy_from as *const (), // 0x48 - tiling as *const (), // 0x50 - unused as *const (), // 0x58 view descriptor - unused as *const (), // 0x60 tiled resource? + unused as *const (), // 0x38 element coordinate + copy_into as *const (), // 0x40 + copy_from as *const (), // 0x48 + tiling as *const (), // 0x50 + unused as *const (), // 0x58 view descriptor + unused as *const (), // 0x60 tiled resource? ]); pub(crate) fn module() -> HleModule { @@ -714,37 +665,6 @@ mod tests { d.flags = ALLOW_DEPTH_STENCIL; XGSuggestSwizzleMode(&d, 0, &mut out); assert_eq!(out, 0x118); - // A 1D texture has no tiled layout, whatever its use. - d.dimension = TEXTURE_1D; - XGSuggestSwizzleMode(&d, 0, &mut out); - assert_eq!(out, 0x100); - } - - #[test] - fn render_targets_reserve_metadata_memory() { - let plain = desc(256, 256, 1, 28, 0); - let mut render = plain; - render.flags = ALLOW_RENDER_TARGET; - let mut depth = plain; - depth.flags = ALLOW_DEPTH_STENCIL; - let layout = |d: &ResourceDesc| { - let c = create(d); - // SAFETY: LayoutOut is plain data; all zeroes is a valid value. - let mut out: Box<LayoutOut> = Box::new(unsafe { std::mem::zeroed() }); - let get: extern "system" fn(This, *mut LayoutOut) -> HRESULT = slot(c, 2); - assert_eq!(get(c, &mut *out), S_OK); - let result = (out.size, out.alignment, out.planes); - slot::<extern "system" fn(This) -> u32>(c, 1)(c); - result - }; - let (base, base_align, base_planes) = layout(&plain); - let (color, color_align, color_planes) = layout(&render); - let (depth_size, _, _) = layout(&depth); - assert!(color > base, "color metadata is reserved"); - assert!(depth_size > base, "depth metadata is reserved"); - assert!(depth_size >= color, "HTILE is at least color metadata"); - assert!(color_align >= base_align && color_align.is_multiple_of(1 << 16)); - assert_eq!(color_planes, base_planes, "data planes are unchanged"); } /// The title's calls: layout, then a copy in and out of each mip. @@ -857,95 +777,4 @@ mod tests { assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG); assert!(module().exports.len() == 2); } - - /// A title releasing a computer once too often: the count stays 0 and - /// nothing is freed again (the old `fetch_sub(1) - 1` overflowed). - #[test] - fn release_past_zero_leaves_the_count_at_zero() { - let c = create(&desc(128, 4, 1, 11, 0x100)); - let release = slot::<extern "system" fn(This) -> u32>(c, 1); - assert_eq!(slot::<extern "system" fn(This) -> u32>(c, 0)(c), 2); - assert_eq!(release(c), 1); - computer(c).refs.store(0, Ordering::Relaxed); - assert_eq!(release(c), 0); - assert_eq!(computer(c).refs.load(Ordering::Relaxed), 0); - // SAFETY: made by `XGCreateTextureComputer` and not freed by - // `release`. - drop(unsafe { Box::from_raw(c) }); - } - - #[test] - fn tiling_rejects_null_out_when_count_nonzero() { - type Tiling = extern "system" fn( - This, - *mut u32, - *mut PackedMips, - *mut [u32; 3], - *mut u32, - u32, - *mut SubresourceTiling, - ) -> HRESULT; - let c = create(&desc(256, 256, 0, 98, 0x10a)); - let tiling: Tiling = slot(c, 10); - - let mut tiles = 99; - let mut count = 2; - assert_eq!( - tiling( - c, - &mut tiles, - std::ptr::null_mut(), - std::ptr::null_mut(), - &mut count, - 0, - std::ptr::null_mut(), - ), - E_INVALIDARG - ); - // Failed call leaves caller's outputs untouched. - assert_eq!((tiles, count), (99, 2)); - - // Zero capacity with null `out` is allowed and fills the summary fields. - count = 0; - assert_eq!( - tiling( - c, - &mut tiles, - std::ptr::null_mut(), - std::ptr::null_mut(), - &mut count, - 0, - std::ptr::null_mut(), - ), - S_OK - ); - assert_eq!((tiles, count), (2, 0)); - assert_eq!(release(c), 0); - } - - #[test] - fn copy_rejects_out_of_range_slice_and_plane() { - type Into = extern "system" fn(This, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT; - type From = - extern "system" fn(This, *mut u8, u32, u32, u32, *const u8, u32, u32) -> HRESULT; - let c = create(&desc(64, 64, 2, 98, 0x10a)); - let (into, from): (Into, From) = (slot(c, 8), slot(c, 9)); - - // 1 slice, 2 mips -> subresource 2 is slice 1 (out of range). - // Must fail in `copy_args` before touching `tiled` or `linear`. - let mut dummy = [0u8; 16]; - assert_eq!( - into(c, dummy.as_mut_ptr(), 0, 2, dummy.as_ptr(), 256, 0), - E_INVALIDARG - ); - assert_eq!( - from(c, dummy.as_mut_ptr(), 0, 2, 0, dummy.as_ptr(), 256, 0), - E_INVALIDARG - ); - assert_eq!( - into(c, dummy.as_mut_ptr(), 1, 0, dummy.as_ptr(), 256, 0), - E_INVALIDARG - ); - assert_eq!(release(c), 0); - } } diff --git a/crates/victory-hle/src/modules/xgame.rs b/crates/victory-hle/src/modules/xgame.rs index 54f8474dc8..edcf2eaafe 100644 --- a/crates/victory-hle/src/modules/xgame.rs +++ b/crates/victory-hle/src/modules/xgame.rs @@ -63,8 +63,8 @@ extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT { } /// As documented: the title ends (suspended first, as on any end) and the -/// game starts again in a new process; this never returns. Grand Theft -/// Auto VI relaunches itself (its own path from `GetModuleFileNameA`) with +/// game starts again in a new process; this never returns. +/// The title relaunches itself (its own path from `GetModuleFileNameA`) with /// arguments from its configuration. The new `victory run` gets the same /// options, the new executable, and the title's arguments after `--` /// (the title reads the whole command line). @@ -74,28 +74,20 @@ extern "system" fn launch_new_game( args: *const c_char, _user: *const c_void, ) { - let (exe, args) = ( - text(exe).unwrap_or_default(), - text(args).unwrap_or_default(), - ); + let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default()); tracing::info!(exe, args, "XLaunchNewGame"); let current = runtime::main_image() .and_then(runtime::image_path) .unwrap_or_default(); let ours: Vec<_> = std::env::args_os().skip(1).collect(); let command = relaunch_args(ours, current.as_os_str(), &exe, &args); - #[cfg(windows)] - { - super::lifecycle::end_title( - "XLaunchNewGame", - Box::new(move || super::lifecycle::relaunch(command)), - ); - loop { - std::thread::park(); - } + super::lifecycle::end_title( + "XLaunchNewGame", + Box::new(move || super::lifecycle::relaunch(command)), + ); + loop { + std::thread::park(); } - #[cfg(not(windows))] - let _ = command; } /// Our own arguments for the relaunch: the title's executable replaced by @@ -107,53 +99,14 @@ fn relaunch_args( args: &str, ) -> Vec<std::ffi::OsString> { let mut out: Vec<_> = ours.into_iter().take_while(|a| a != "--").collect(); - // `runtime` makes the image path absolute when it maps the title, so a - // relative launch argument is not textually equal to it. Normalise the - // same way before matching, or a relaunch would run the old executable. if !exe.is_empty() - && let Some(slot) = out.iter_mut().find(|a| { - a.as_os_str() == current - || std::path::absolute(a).is_ok_and(|p| p.as_os_str() == current) - }) + && let Some(slot) = out.iter_mut().find(|a| a.as_os_str() == current) { *slot = exe.into(); } if !args.trim().is_empty() { out.push("--".into()); - out.extend(split_args(args).into_iter().map(Into::into)); - } - out -} - -/// Splits the title's command-line tail into arguments, keeping quoted -/// strings together (including empty ones). `split_whitespace` would hand -/// the child a quoted path as several broken arguments. -fn split_args(args: &str) -> Vec<String> { - let mut out = Vec::new(); - let mut current = String::new(); - let mut quote = None; - let mut started = false; - for c in args.chars() { - match c { - '"' | '\'' if quote == Some(c) => quote = None, - '"' | '\'' if quote.is_none() => { - quote = Some(c); - started = true; - } - c if quote.is_none() && c.is_whitespace() => { - if started { - out.push(std::mem::take(&mut current)); - started = false; - } - } - c => { - current.push(c); - started = true; - } - } - } - if started { - out.push(current); + out.extend(args.split_whitespace().map(Into::into)); } out } @@ -242,74 +195,20 @@ mod tests { #[test] fn a_relaunch_keeps_our_options() { - let ours: Vec<std::ffi::OsString> = [ - "run", - "G:/game.exe", - "--execute", - "--console", - "series-s", - "--", - "-old", - ] - .map(Into::into) - .into(); + let ours: Vec<std::ffi::OsString> = + ["run", "G:/game.exe", "--execute", "--console", "series-s", "--", "-old"] + .map(Into::into) + .into(); let current = std::ffi::OsStr::new("G:/game.exe"); let again = relaunch_args(ours.clone(), current, "G:/game.exe", " -config=x -y "); - let expected = [ - "run", - "G:/game.exe", - "--execute", - "--console", - "series-s", - "--", - ]; + let expected = ["run", "G:/game.exe", "--execute", "--console", "series-s", "--"]; assert_eq!(again[..6], expected.map(std::ffi::OsString::from)); - assert_eq!( - again[6..], - ["-config=x", "-y"].map(std::ffi::OsString::from) - ); + assert_eq!(again[6..], ["-config=x", "-y"].map(std::ffi::OsString::from)); let other = relaunch_args(ours, current, "G:/other.exe", ""); assert_eq!(other.len(), 5); assert_eq!(other[1], "G:/other.exe"); } - #[test] - fn a_relaunch_replaces_a_relative_startup_executable() { - // `runtime::set_image_path` makes this absolute before the launch. - let current = std::path::absolute("game.exe").unwrap(); - let ours: Vec<std::ffi::OsString> = [ - "run", - "game.exe", - "--execute", - "--console", - "series-s", - "--", - "-old", - ] - .map(Into::into) - .into(); - let again = relaunch_args( - ours, - current.as_os_str(), - "other.exe", - r#"--config="C:\Program Files\game" "" -y"#, - ); - let expected: Vec<std::ffi::OsString> = [ - "run", - "other.exe", - "--execute", - "--console", - "series-s", - "--", - r"--config=C:\Program Files\game", - "", - "-y", - ] - .map(Into::into) - .into(); - assert_eq!(again, expected, "the requested exe and quoted args survive"); - } - #[test] fn served_areas_are_available_others_not() { type Check = extern "system" fn(This, u32) -> bool; diff --git a/crates/victory-hle/src/modules/xgameruntime.rs b/crates/victory-hle/src/modules/xgameruntime.rs index 0a141b04ac..b3f5963fce 100644 --- a/crates/victory-hle/src/modules/xgameruntime.rs +++ b/crates/victory-hle/src/modules/xgameruntime.rs @@ -145,13 +145,6 @@ pub fn put<T>(out: *mut T, value: T) -> HRESULT { pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { let len = text.len() + 1; if buffer.is_null() || size < len { - // String getters are called twice: once with no buffer to learn the - // required size, then with that many bytes. Report it even on the - // insufficient-buffer branch so the first call can be used. - if !used.is_null() { - // SAFETY: checked non-null. - unsafe { used.write(len) }; - } return xasync::E_NOT_SUFFICIENT_BUFFER; } // SAFETY: the buffer holds `size` bytes, checked above. @@ -209,7 +202,7 @@ pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) /// The stub prefers this one when present. It passes the same three values /// and a pointer to the title's initialisation options, null unless the -/// title initialises with options (Grand Theft Auto VI does not). +/// title initialises with options (the title does not). pub extern "system" fn InitializeApiImplEx2( version: u64, build: u64, @@ -348,46 +341,4 @@ mod tests { assert!(!GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()).is_null()); } } - - #[test] - fn string_getters_report_the_required_size() { - let none = std::ptr::null_mut(); - let mut used = usize::MAX; - assert_eq!( - put_string("gamertag", 0, none, &mut used), - xasync::E_NOT_SUFFICIENT_BUFFER - ); - assert_eq!(used, 9, "the NUL is part of the required size"); - - // The two-call pattern: query, then fetch exactly that many bytes. - let mut buffer = vec![0xffu8; used]; - assert_eq!( - put_string("gamertag", buffer.len(), buffer.as_mut_ptr(), &mut used), - S_OK - ); - assert_eq!(buffer, b"gamertag\0"); - assert_eq!(used, 9); - - // A short buffer reports the size too, and writes nothing. - let mut short = [0xffu8; 3]; - used = 0; - assert_eq!( - put_string("gamertag", short.len(), short.as_mut_ptr(), &mut used), - xasync::E_NOT_SUFFICIENT_BUFFER - ); - assert_eq!(used, 9); - assert_eq!(short, [0xff; 3]); - - // Callers that do not ask for the size are still supported. - assert_eq!( - put_string("gamertag", 0, none, std::ptr::null_mut()), - xasync::E_NOT_SUFFICIENT_BUFFER - ); - let mut empty = [0xffu8; 1]; - assert_eq!( - put_string("", empty.len(), empty.as_mut_ptr(), std::ptr::null_mut()), - S_OK - ); - assert_eq!(empty, [0]); - } } diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index 2dd57cf29a..1f0c1fdb5d 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -37,7 +37,7 @@ pub const PROVIDER: Guid = Guid::new( 0x4cc2, [0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2], ); -/// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes +/// As the title (2026) asks for it; every slot it calls takes /// the public API's arguments in the same order as under the provider's /// own id (older titles). pub const IID_2026: Guid = Guid::new( @@ -178,7 +178,8 @@ fn parse_manifest(bytes: &[u8]) -> Option<Vec<String>> { } /// The container's newest committed version, if any. Removes what a crash -/// left: unfinished versions and older ones. +/// left: unfinished versions and older ones (what cannot be removed now +/// is left for a later call). fn current(dir: &Path) -> std::io::Result<Option<Version>> { let mut committed = Vec::new(); for entry in std::fs::read_dir(dir)?.flatten() { @@ -198,14 +199,23 @@ fn current(dir: &Path) -> std::io::Result<Option<Version>> { let Some(&number) = committed.last() else { return Ok(None); }; + // Older versions are removed as far as that goes. The highest version + // is the container whatever is left below it, and a file another + // program holds without letting it be deleted (a virus scanner, a + // backup in progress) fails the removal: returning that error made the + // container unreadable and every save of it fail for as long as the + // file was held. + for old in &committed[..committed.len() - 1] { + let path = dir.join(format!("v{old}")); + if let Err(e) = std::fs::remove_dir_all(&path) { + tracing::info!(dir = %path.display(), %e, "an older save version stays for now; it goes at a later save"); + } + } let version = dir.join(format!("v{number}")); let bad = || std::io::Error::new(std::io::ErrorKind::InvalidData, "bad save manifest"); let mut names = parse_manifest(&std::fs::read(version.join(MANIFEST))?).ok_or_else(bad)?; let blobs = names.split_off(2); let [name, display] = <[String; 2]>::try_from(names).map_err(|_| bad())?; - for old in &committed[..committed.len() - 1] { - std::fs::remove_dir_all(dir.join(format!("v{old}")))?; - } Ok(Some(Version { dir: version, number, @@ -260,9 +270,8 @@ fn commit( match source { Source::Data(data) => write(path, data)?, // Files are never changed in place, so sharing one is safe. - Source::Kept(from) => { - std::fs::hard_link(from, &path).or_else(|_| std::fs::copy(from, &path).map(drop))? - } + Source::Kept(from) => std::fs::hard_link(from, &path) + .or_else(|_| std::fs::copy(from, &path).map(drop))?, } step(); } @@ -364,13 +373,6 @@ fn take<T>(handle: *mut T) { drop(unsafe { Box::from_raw(handle) }); } } -/// Nulls a handle the title asked for before anything can fail: the GDK -/// documents these as null on failure (`_Outptr_result_nullonfailure_`), -/// and titles close whatever handle they hold, without checking that the -/// call that should have given it worked. -fn clear<T>(out: *mut *mut T) { - let _ = put(out, std::ptr::null_mut()); -} impl Provider { /// The provider for the only user and `config` (the service @@ -472,9 +474,7 @@ impl Update { } let replaced: u64 = current.as_ref().map_or(0, |v| { let sizes = v.sizes(); - let changed = sizes - .iter() - .filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n)); + let changed = sizes.iter().filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n)); changed.map(|(_, size)| size).sum() }); let root = self.dir.parent().unwrap_or(&self.dir); @@ -527,11 +527,7 @@ fn read(c: &Container, names: Option<Vec<String>>) -> Result<Vec<(String, Vec<u8 names .into_iter() .map(|name| { - let i = version - .blobs - .iter() - .position(|b| *b == name) - .ok_or(BLOB_NOT_FOUND)?; + let i = version.blobs.iter().position(|b| *b == name).ok_or(BLOB_NOT_FOUND)?; let data = std::fs::read(version.blob(i)).map_err(|e| io_error(&c.dir, &e))?; Ok((name, data)) }) @@ -591,12 +587,7 @@ pub struct BlobInfo { /// Calls `callback` with the information of each container that passes /// `keep` until it returns false; never under our lock (it may call us). -fn report( - root: &Path, - keep: impl Fn(&str) -> bool, - context: *mut c_void, - callback: ContainerCallback, -) { +fn report(root: &Path, keep: impl Fn(&str) -> bool, context: *mut c_void, callback: ContainerCallback) { let infos: Vec<(CString, CString, u32, u64, i64)> = { let _saves = saves_lock(); containers(root) @@ -660,7 +651,6 @@ extern "system" fn initialize_result( block: *mut AsyncBlock, out: *mut *mut Provider, ) -> HRESULT { - clear(out); xasync::result(block, (&raw const INIT).cast(), out) } extern "system" fn close_provider(_: This, provider: *mut Provider) { @@ -738,7 +728,6 @@ extern "system" fn create_container( name: *const c_char, out: *mut *mut Container, ) -> HRESULT { - clear(out); let (Some(p), Some(name)) = (get(provider), text(name)) else { return E_INVALIDARG; }; @@ -863,7 +852,6 @@ extern "system" fn create_update( display: *const c_char, out: *mut *mut Update, ) -> HRESULT { - clear(out); let Some(c) = get(container) else { return E_INVALIDARG; }; @@ -1000,10 +988,7 @@ mod tests { fn a_full_disk_is_not_the_quota() { let mb = 1 << 20; assert_eq!(no_room(2 * mb, 0, 0, mb), Some(OUT_OF_LOCAL_STORAGE)); - assert_eq!( - no_room(2 * mb, 0, QUOTA - mb, 100 * mb), - Some(QUOTA_EXCEEDED) - ); + assert_eq!(no_room(2 * mb, 0, QUOTA - mb, 100 * mb), Some(QUOTA_EXCEEDED)); // Replacing a blob of the same size fits a full quota. assert_eq!(no_room(mb, mb, QUOTA, 100 * mb), None); assert_eq!(no_room(mb, 0, 0, mb), None); @@ -1031,51 +1016,50 @@ mod tests { Some((display, blobs.into_iter().map(text).collect())) } + /// A file of an older version held by another program (a virus scanner, + /// a backup copy in progress) keeps that version from being removed. + /// The saves after it must not fail for that: the newest version is the + /// container whatever is left below it, and what is left goes at a + /// later save. #[test] - fn unreadable_latest_manifest_preserves_previous_version() { - let dir = tempfile::tempdir().unwrap(); - let older = dir.path().join("v1"); - let latest = dir.path().join("v2"); - std::fs::create_dir(&older).unwrap(); - std::fs::create_dir(&latest).unwrap(); - std::fs::write(older.join(MANIFEST), manifest("Slot", "Previous", &[])).unwrap(); - - assert!(current(dir.path()).is_err()); - assert!(older.join(MANIFEST).is_file()); - - std::fs::write(latest.join(MANIFEST), []).unwrap(); - assert!(current(dir.path()).is_err()); - assert!(older.join(MANIFEST).is_file()); - - std::fs::write(latest.join(MANIFEST), manifest("Slot", "Latest", &[])).unwrap(); - let loaded = current(dir.path()).unwrap().unwrap(); - assert_eq!(loaded.number, 2); - assert!(!older.exists()); + fn an_older_version_that_cannot_be_removed_does_not_fail_the_saves_after_it() { + use std::os::windows::fs::OpenOptionsExt; + let root = tempfile::tempdir().unwrap(); + let dir = container_dir(root.path(), "Slot"); + let versions = || { + let entries = std::fs::read_dir(&dir).unwrap().flatten(); + entries.filter(|e| e.file_name().to_string_lossy().starts_with('v')).count() + }; + assert_eq!(update(root.path(), "one", &[("a", Some("first a"))]), S_OK); + let first = current(&dir).unwrap().unwrap(); + // Opened with no sharing: nobody else can delete it while it is held. + let held = std::fs::OpenOptions::new().read(true).share_mode(0).open(first.blob(0)).unwrap(); + // Blob `a` is written anew each time, so no version shares the held file. + assert_eq!(update(root.path(), "two", &[("a", Some("second a"))]), S_OK); + assert_eq!(state(root.path()), Some(("two".into(), vec![("a".into(), "second a".into())]))); + assert_eq!(update(root.path(), "three", &[("a", Some("third a"))]), S_OK); + assert_eq!(state(root.path()), Some(("three".into(), vec![("a".into(), "third a".into())]))); + assert!(first.blob(0).exists(), "the held file is still there"); + // Let go of: the next looks at the container remove what was left. + drop(held); + assert_eq!(update(root.path(), "four", &[("a", Some("fourth a"))]), S_OK); + assert_eq!(state(root.path()), Some(("four".into(), vec![("a".into(), "fourth a".into())]))); + assert_eq!(versions(), 1); } fn old_state() -> Option<(String, Vec<(String, String)>)> { - Some(( - "one".into(), - vec![("a".into(), "old a".into()), ("b".into(), "old b".into())], - )) + Some(("one".into(), vec![("a".into(), "old a".into()), ("b".into(), "old b".into())])) } /// Run by the crash test in a child process; does nothing otherwise. #[test] fn crash_child() { - let (Ok(root), Ok(op)) = ( - std::env::var("VICTORY_SAVE_CHILD"), - std::env::var("VICTORY_SAVE_OP"), - ) else { + let (Ok(root), Ok(op)) = (std::env::var("VICTORY_SAVE_CHILD"), std::env::var("VICTORY_SAVE_OP")) else { return; }; let root = PathBuf::from(root); let hr = if op == "update" { - update( - &root, - "two", - &[("a", Some("new a")), ("b", None), ("c", Some("new c"))], - ) + update(&root, "two", &[("a", Some("new a")), ("b", None), ("c", Some("new c"))]) } else { delete(&root, "Slot") }; @@ -1088,25 +1072,15 @@ mod tests { /// new one. #[test] fn a_kill_at_any_step_leaves_old_or_new() { - let new = Some(( - "two".into(), - vec![("a".into(), "new a".into()), ("c".into(), "new c".into())], - )); + let new = Some(("two".into(), vec![("a".into(), "new a".into()), ("c".into(), "new c".into())])); for (op, after) in [("update", new), ("delete", None)] { let mut seen = (0, 0); for stop in 1.. { let dir = tempfile::tempdir().unwrap(); let root = dir.path(); - assert_eq!( - update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), - S_OK - ); + assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK); let mut child = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "modules::xgamesave::tests::crash_child", - "--nocapture", - ]) + .args(["--exact", "modules::xgamesave::tests::crash_child", "--nocapture"]) .args(["--test-threads=1"]) .env("VICTORY_SAVE_CHILD", root) .env("VICTORY_SAVE_OP", op) @@ -1151,35 +1125,16 @@ mod tests { for good in ["Profile/Slot_1", "a/b/Save-2.sav", "x", &"a".repeat(256)] { assert!(valid_container(good), "{good}"); } - for bad in [ - "a b", - "", - "a/", - "a.", - "a..b", - "a.b/c", - "a-b/c", - &"a".repeat(257), - ] { + for bad in ["a b", "", "a/", "a.", "a..b", "a.b/c", "a-b/c", &"a".repeat(257)] { assert!(!valid_container(bad), "{bad}"); } // Containers and blobs differing only in case, reserved device // names, characters the host forbids, long names: all distinct. let dir = tempfile::tempdir().unwrap(); - let p = Provider { - root: dir.path().into(), - }; + let p = Provider { root: dir.path().into() }; let long = "n".repeat(300); - let blobs = [ - "A", - "a", - "CON", - "nul.txt", - "x/y:z*?\"<>|", - long.as_str(), - "end. ", - ]; + let blobs = ["A", "a", "CON", "nul.txt", "x/y:z*?\"<>|", long.as_str(), "end. "]; for container in ["Save", "save", "SAVE/CON.x"] { let c = p.container(container); let u = Update { @@ -1211,10 +1166,7 @@ mod tests { #[test] fn the_old_layout_moves_over() { let saves = tempfile::tempdir().unwrap(); - let root = saves - .path() - .join(format!("{:016X}", xuser::XUID)) - .join("scid"); + let root = saves.path().join(format!("{:016X}", xuser::XUID)).join("scid"); let old = root.join("Player"); std::fs::create_dir_all(&old).unwrap(); std::fs::write(old.join("Save%20Game%20Data"), b"data").unwrap(); @@ -1278,42 +1230,6 @@ mod tests { assert_eq!(state(&scid.root), kept); } - #[test] - fn a_failed_create_leaves_a_null_handle() { - let this: This = &OBJECT; - let saves = tempfile::tempdir().unwrap(); - let provider = give(Provider::open(saves.path(), Some("scid")).unwrap()); - // What an uninitialized handle variable may hold. - fn garbage<T>() -> *mut T { - std::ptr::without_provenance_mut(0x1234) - } - - let mut container = garbage(); - let bad = c"bad name".as_ptr(); - let hr = create_container(this, provider, bad, &mut container); - assert_eq!(hr, INVALID_CONTAINER_NAME); - assert!(container.is_null()); - - let mut update = garbage(); - let hr = create_update(this, std::ptr::null(), c"x".as_ptr(), &mut update); - assert_eq!(hr, E_INVALIDARG); - assert!(update.is_null()); - - // A provider that could not be opened (its folder could not be made). - let mut b = block(); - xasync::finished_with(&mut b, (&raw const INIT).cast(), Err(NO_ACCESS)); - let mut opened = garbage(); - let hr = initialize_result(this, &mut b, &mut opened); - assert_eq!(hr, NO_ACCESS); - assert!(opened.is_null()); - - // So closing what the title holds, as it does, is harmless. - close_container(this, container); - close_update(this, update); - close_provider(this, opened); - close_provider(this, provider); - } - #[test] fn saves_persist_across_providers() { let this: This = &OBJECT; @@ -1360,10 +1276,7 @@ mod tests { S_OK ); type Delete = extern "system" fn(This, *mut Update, *const c_char) -> HRESULT; - assert_eq!( - method::<Delete>(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), - S_OK - ); + assert_eq!(method::<Delete>(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), S_OK); type Submit = extern "system" fn(This, *const Update, *mut AsyncBlock) -> HRESULT; let mut b = block(); assert_eq!(method::<Submit>(&OBJECT, 0xe0)(this, update, &mut b), S_OK); diff --git a/crates/victory-hle/src/modules/xgameui.rs b/crates/victory-hle/src/modules/xgameui.rs index 84fe02f20e..9882b2eac4 100644 --- a/crates/victory-hle/src/modules/xgameui.rs +++ b/crates/victory-hle/src/modules/xgameui.rs @@ -1,6 +1,6 @@ //! System dialogs a title opens (XGameUi). A profile card has nothing to //! show and closes at once. Text entry opens a small host dialog (title, -//! description, default text, the console's length limit) on a thread of its own and +//! description, default text, the length limit) on a thread of its own and //! completes the call with what the user typed, or as cancelled (`E_ABORT`) //! when the dialog is dismissed or cannot open. #![allow(clippy::not_unsafe_ptr_arg_deref)] @@ -18,7 +18,7 @@ pub const PROVIDER: Guid = Guid::new( 0x4043, [0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0], ); -/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x38, +/// As the title (2026) asks for it; the slots it calls (0x38, /// 0x40, 0x88-0x98) take the public API's arguments in the 2020 order. pub const IID_2026: Guid = Guid::new( 0xeaf6_69df, @@ -49,7 +49,7 @@ extern "system" fn profile_card_result(_: This, block: *mut AsyncBlock) -> HRESU xasync::XAsyncGetResult(block, (&raw const PROFILE).cast(), 0, none, none.cast()) } -/// Grand Theft Auto VI treats `E_ABORT` as cancelled and goes on; any +/// The title treats `E_ABORT` as cancelled and goes on; any /// other failure as an error. extern "system" fn text_entry_async( _: This, @@ -57,12 +57,10 @@ extern "system" fn text_entry_async( title: *const c_char, description: *const c_char, default: *const c_char, - scope: u32, + _scope: u32, max_length: u32, ) -> HRESULT { - let [title, description, default] = - [title, description, default].map(|t| text(t).unwrap_or_default()); - let max_length = max_length_for(scope, max_length); + let [title, description, default] = [title, description, default].map(|t| text(t).unwrap_or_default()); tracing::info!(title, description, max_length, "text entry"); xasync::pending_with(block, (&raw const TEXT).cast(), move || { match ask(&title, &description, &default, max_length) { @@ -104,24 +102,12 @@ extern "system" fn text_entry_result( put(used, written as u32) } -/// The console's most characters for a text entry. -const MAX_LENGTH: u32 = 1024; -/// `XGameUiTextEntryInputScope::Password`. -const PASSWORD: u32 = 31; - -/// The limit the console applies, as documented: the title's, at most -/// 1024; 1024 for 0 and for a password, whatever the title asks. -fn max_length_for(scope: u32, max: u32) -> u32 { - if max == 0 || scope == PASSWORD { - MAX_LENGTH - } else { - max.min(MAX_LENGTH) - } -} - -/// At most `max` characters. +/// At most `max` characters (0: no limit). fn limit(typed: &str, max: u32) -> String { - typed.chars().take(max as usize).collect() + match max { + 0 => typed.to_owned(), + max => typed.chars().take(max as usize).collect(), + } } /// Asks the user in a modal host dialog; `None` if dismissed. @@ -192,13 +178,7 @@ mod dialog { let ok = wm::BS_DEFPUSHBUTTON as u32 | tab; item(ok, [129, 40, 50, 14], wm::IDOK as u16, button, "OK"); let cancel = wm::BS_PUSHBUTTON as u32 | tab; - item( - cancel, - [183, 40, 50, 14], - wm::IDCANCEL as u16, - button, - "Cancel", - ); + item(cancel, [183, 40, 50, 14], wm::IDCANCEL as u16, button, "Cancel"); // The template must start on a DWORD. let template: Vec<u32> = t .chunks(2) @@ -219,12 +199,7 @@ mod dialog { entry.typed } - extern "system" fn procedure( - dialog: HWND, - message: u32, - wparam: WPARAM, - lparam: LPARAM, - ) -> isize { + extern "system" fn procedure(dialog: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> isize { // SAFETY: our dialog; its user data is the `Entry` from `ask`, // stored at WM_INITDIALOG. unsafe { @@ -239,16 +214,12 @@ mod dialog { 0 // focus set here } wm::WM_COMMAND => { - let entry = - &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); + let entry = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); match (wparam & 0xffff) as i32 { wm::IDOK => { - let mut buffer = - vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; - let n = - wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32); - entry.typed = - Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize])); + let mut buffer = vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; + let n = wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32); + entry.typed = Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize])); wm::EndDialog(dialog, 1); } wm::IDCANCEL => { @@ -324,29 +295,19 @@ mod tests { u32, ) -> HRESULT; type Size = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; - type Result_ = - extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; + type Result_ = extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; let null = std::ptr::null(); let entry = method::<Entry>(&OBJECT, 0x88); // Dismissed: cancelled. let mut b = block(); - assert_eq!( - entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), - S_OK - ); + assert_eq!(entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), S_OK); assert_eq!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT); let mut size = 0; - assert_eq!( - method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), - E_ABORT - ); + assert_eq!(method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), E_ABORT); // Typed: the text, cut to the limit, with its NUL. let mut b = block(); let default = c"abc".as_ptr(); - assert_eq!( - entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), - S_OK - ); + assert_eq!(entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), S_OK); assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); assert_eq!(method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK); assert_eq!(size, 7); @@ -357,46 +318,4 @@ mod tests { assert_eq!((text(out.as_ptr()).as_deref(), used), (Some("abctyp"), 7)); assert_eq!(limit("\u{e9}t\u{e9}s", 3), "\u{e9}t\u{e9}"); } - - /// 0 and limits over 1024 mean 1024; a password ignores the title's. - #[test] - fn text_entry_limits_follow_the_console() { - assert_eq!(max_length_for(0, 0), 1024); - assert_eq!(max_length_for(0, 5000), 1024); - assert_eq!(max_length_for(0, 16), 16); - assert_eq!(max_length_for(PASSWORD, 8), 1024); - - type Entry = extern "system" fn( - This, - *mut AsyncBlock, - *const c_char, - *const c_char, - *const c_char, - u32, - u32, - ) -> HRESULT; - type Size = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; - type Result_ = - extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; - let this: This = &OBJECT; - let entry = method::<Entry>(&OBJECT, 0x88); - let null = std::ptr::null(); - let long = std::ffi::CString::new("a".repeat(2000)).unwrap(); - for (scope, max, default, expect) in [ - (0, 0, long.as_ptr(), 1025), - (PASSWORD, 8, c"abc".as_ptr(), 9), - ] { - let mut b = block(); - let title = c"Type".as_ptr(); - assert_eq!(entry(this, &mut b, title, null, default, scope, max), S_OK); - assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); - let mut size = 0; - assert_eq!(method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK); - assert_eq!(size, expect, "scope {scope}, max {max}"); - let mut out = vec![0 as c_char; size as usize]; - let result = method::<Result_>(&OBJECT, 0x98); - let used = std::ptr::null_mut(); - assert_eq!(result(this, &mut b, size, out.as_mut_ptr(), used), S_OK); - } - } } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 5e51fc7ccb..14b68de459 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -18,21 +18,24 @@ use windows_sys::Win32::Foundation::{ }; use windows_sys::Win32::System::Memory::{ CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, - MEM_PRESERVE_PLACEHOLDER, MEM_PRIVATE, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, + MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3, MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_COMMIT, - SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQuery, - VirtualQueryEx, + SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx, }; use windows_sys::Win32::System::ProcessStatus::{ K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION, PROCESS_MEMORY_COUNTERS, }; -use windows_sys::Win32::System::Threading::GetCurrentProcess; +use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentThread}; use windows_sys::core::BOOL; use crate::{HleModule, hle_export}; +/// `VirtualFree`'s flag that joins adjacent placeholders into one (not in +/// windows-sys' memory module). +const MEM_COALESCE_PLACEHOLDERS: u32 = 0x1; + const MIB: usize = 1 << 20; /// Whether we run under Wine (its ntdll exports `wine_get_version`). @@ -73,8 +76,8 @@ const MEM_WRITE_WATCH: u32 = 0x20_0000; /// 32-bit memory; else from 4 GiB (kept for 32-bit requests, which the /// title's big pools would otherwise crowd out) up to 46 down to 40 bits /// from the field at bit 12, or 40 bits without one: the console keeps -/// title memory there, and its ray-tracing structures must be (Grand Theft -/// Auto VI's BVH builder refuses one above; the title asks for its GPU heap +/// title memory there, and its ray-tracing structures must be ( +/// the title's BVH builder refuses one above; the title asks for its GPU heap /// with no field). Decision 0001. fn address_range(flags: u64) -> (usize, usize) { let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) { @@ -91,8 +94,32 @@ pub extern "system" fn XMemVirtualAlloc( kind: u32, flags: u64, protect: u32, +) -> *mut c_void { + virtual_alloc( + base, + size, + kind, + flags, + protect, + victory_gpu::title_memory_committed, + ) +} + +fn virtual_alloc( + base: *mut c_void, + size: usize, + kind: u32, + flags: u64, + protect: u32, + on_commit: impl FnOnce(usize, usize), ) -> *mut c_void { let (lowest, highest) = address_range(flags); + // Asked for as 2 MiB pages, committed, and for the CPU alone (no + // graphics access bits): large pages may serve it. + let large_ok = base.is_null() + && kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M + && kind & MEM_COMMIT != 0 + && protect & GRAPHICS_ACCESS == 0; let mut requirements = MEM_ADDRESS_REQUIREMENTS { LowestStartingAddress: lowest as *mut c_void, HighestEndingAddress: highest as *mut c_void, @@ -109,7 +136,7 @@ pub extern "system" fn XMemVirtualAlloc( // A reservation of 64 KiB pages takes physical pages later // (`XMemMapPhysicalPages`); on the host only a placeholder can. // shortcut: committing part of such a reservation later would fail - // (Grand Theft Auto VI's 23 calls never do); replace that part of the + // (the title's 23 calls never do); replace that part of the // placeholder then. let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0; if placeholder { @@ -137,6 +164,11 @@ pub extern "system" fn XMemVirtualAlloc( kind |= MEM_WRITE_WATCH; } } + if large_ok + && let Some(at) = large_alloc(size, kind, protect, &mut parameter) + { + return at; + } // SAFETY: the title's own arguments, cleaned of console bits; the // parameter points at `requirements`, which outlives the call. let at = unsafe { @@ -154,20 +186,6 @@ pub extern "system" fn XMemVirtualAlloc( constrained.into(), ) }; - if at.is_null() { - let error = std::io::Error::last_os_error(); - if kind & MEM_COMMIT != 0 { - commit_refused(size, "virtual memory", error); - } else { - tracing::warn!( - size, - kind = format_args!("{kind:#x}"), - flags = format_args!("{flags:#x}"), - %error, - "XMemVirtualAlloc refused" - ); - } - } if base.is_null() { tracing::debug!( size, @@ -177,9 +195,117 @@ pub extern "system" fn XMemVirtualAlloc( "XMemVirtualAlloc" ); } + // Memory committed for the title: the GPU side's notes that blocks there + // are uncommitted go (`VICTORY_ABSENT_ONCE`). + if !at.is_null() && kind & MEM_COMMIT != 0 { + // Windows rounds a fixed commit's address down to a page. The + // caller's last byte can be in the next 64 KiB watch block. + let start = if base.is_null() { at } else { base }; + on_commit(start as usize, size); + } at } +/// The console's graphics access protection bits (read-only to coherent): +/// memory with none of them is the CPU's alone. +const GRAPHICS_ACCESS: u32 = 0x3_f000; + +/// Large pages (`VICTORY_LARGE_PAGES=0`: never): CPU-only memory the title +/// asks for as 2 MiB pages is served from the host's 2 MiB pages, so the +/// CPU's address translation covers it with 512 times fewer entries +/// (fewer TLB misses in the title's big pools). The host gives them only +/// to an account with "Lock pages in memory" (SeLockMemoryPrivilege); they +/// are never paged out, so at most `VICTORY_LARGE_PAGES_MB` (2048 unless +/// set) are taken. The graphics side never watches such memory, so nothing +/// is lost by its lacking write watching. Where the host refuses (no +/// privilege, no free 2 MiB pages), the usual pages serve, as before. +fn large_minimum() -> Option<usize> { + static MIN: LazyLock<Option<usize>> = LazyLock::new(|| { + if std::env::var_os("VICTORY_LARGE_PAGES").is_some_and(|v| v == "0") { + return None; + } + // SAFETY: a plain query. + let min = unsafe { windows_sys::Win32::System::Memory::GetLargePageMinimum() }; + let allowed = min != 0 && lock_privilege(); + tracing::info!( + allowed, + min, + "large pages for CPU-only title memory (VICTORY_LARGE_PAGES=0: never; needs \"Lock pages in memory\" for this account)" + ); + allowed.then_some(min) + }); + *MIN +} + +/// Turns on SeLockMemoryPrivilege for the process; whether the account has +/// it. +fn lock_privilege() -> bool { + use windows_sys::Win32::Foundation::{GetLastError, LUID}; + use windows_sys::Win32::Security::{ + AdjustTokenPrivileges, LUID_AND_ATTRIBUTES, LookupPrivilegeValueW, TOKEN_PRIVILEGES, + }; + use windows_sys::Win32::System::Threading::OpenProcessToken; + const TOKEN_ADJUST_PRIVILEGES: u32 = 0x20; + const TOKEN_QUERY: u32 = 0x8; + const SE_PRIVILEGE_ENABLED: u32 = 2; + const ERROR_NOT_ALL_ASSIGNED: u32 = 1300; + let name: Vec<u16> = "SeLockMemoryPrivilege".encode_utf16().chain([0]).collect(); + let mut token: HANDLE = std::ptr::null_mut(); + // SAFETY: valid out pointers; the token is closed below. + unsafe { + if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &mut token) == 0 { + return false; + } + let mut luid = LUID { LowPart: 0, HighPart: 0 }; + let mut ok = LookupPrivilegeValueW(std::ptr::null(), name.as_ptr(), &mut luid) != 0; + if ok { + let privileges = TOKEN_PRIVILEGES { + PrivilegeCount: 1, + Privileges: [LUID_AND_ATTRIBUTES { + Luid: luid, + Attributes: SE_PRIVILEGE_ENABLED, + }], + }; + ok = AdjustTokenPrivileges(token, 0, &privileges, 0, std::ptr::null_mut(), std::ptr::null_mut()) != 0 + && GetLastError() != ERROR_NOT_ALL_ASSIGNED; + } + CloseHandle(token); + ok + } +} + +/// Bytes of large pages handed out (never given back to the count: a cap, +/// not a balance). +static LARGE_BYTES: AtomicUsize = AtomicUsize::new(0); + +/// [`large_minimum`]'s allocation of `size` bytes, if the host gives it. +fn large_alloc(size: usize, kind: u32, protect: u32, parameter: &mut MEM_EXTENDED_PARAMETER) -> Option<*mut c_void> { + const MEM_LARGE_PAGES: u32 = 0x2000_0000; + let min = large_minimum()?; + if size == 0 || !size.is_multiple_of(min) || protect != PAGE_READWRITE { + return None; + } + let cap = std::env::var("VICTORY_LARGE_PAGES_MB") + .ok() + .and_then(|v| v.trim().parse::<usize>().ok()) + .unwrap_or(2048) + * MIB; + if LARGE_BYTES.fetch_add(size, Ordering::Relaxed) + size > cap { + LARGE_BYTES.fetch_sub(size, Ordering::Relaxed); + return None; + } + let kind = (kind | MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES) & !MEM_WRITE_WATCH; + // SAFETY: as the usual allocation; the parameter outlives the call. + let at = unsafe { VirtualAlloc2(GetCurrentProcess(), std::ptr::null(), size, kind, protect, parameter, 1) }; + if at.is_null() { + LARGE_BYTES.fetch_sub(size, Ordering::Relaxed); + return None; + } + static FIRST: std::sync::Once = std::sync::Once::new(); + FIRST.call_once(|| tracing::info!(size, "title memory on large pages")); + Some(at) +} + /// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the /// same), then the XMem flags and tag. #[repr(C)] @@ -191,7 +317,7 @@ pub struct BasicInformation { } // shortcut: every committed page reports graphics memory and no tag, since -// all of it is GPU-reachable here (Grand Theft Auto VI's BVH builder, the +// all of it is GPU-reachable here (the title's BVH builder, the // only caller, wants graphics memory); remember the flags of // `XMemVirtualAlloc` regions if a title tells CPU-only memory apart. pub extern "system" fn XMemVirtualQuery( @@ -236,7 +362,7 @@ type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void; type FreeRoutine = extern "system" fn(*mut c_void, u64); /// The allocation and free routines the title's exe exports as -/// `__XMemAllocationHooks__` (Grand Theft Auto VI does): `XMemAlloc` and +/// `__XMemAllocationHooks__` (the title does): `XMemAlloc` and /// `XMemFree` call them, for the title's own calls and its middleware's; /// the `…Default` exports do not. fn hooks() -> [usize; 2] { @@ -306,12 +432,11 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_ }; // shortcut: the host heap's addresses lie above 2^40, unlike the // console's; nothing seen builds ray-tracing structures in this memory - // (Grand Theft Auto VI uses its GPU heap). Sub-allocate from a + // (the title uses its GPU heap). Sub-allocate from a // reservation below 2^40 if one does. // SAFETY: the layout has a non-zero size. let block = unsafe { alloc(layout) }; if block.is_null() { - tracing::warn!(size, "XMemAllocDefault: the host heap is out of memory"); return block.cast(); } // SAFETY: the block holds the alignment (at least the header) and then @@ -351,6 +476,136 @@ pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL { 0 } +#[link(name = "kernel32", kind = "raw-dylib")] +unsafe extern "system" { + /// The processor cycles a thread has used so far, in user and kernel + /// mode. + fn QueryThreadCycleTime(thread: HANDLE, cycles: *mut u64) -> i32; +} + +/// Whether the remapping meter also reads the calling thread's processor +/// cycles around each of the system's unmapping and mapping calls +/// (`VICTORY_REMAP_METER=0`: not; the counts and the lengths are kept +/// either way). It costs two short system calls a metered call. +fn meter_cycles() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_REMAP_METER").is_none_or(|v| v != "0")) +} + +/// One of the system's calls that change what an address range shows, +/// metered for the frame log (`victory_gpu::framelog`, "remapping, +/// metered"): how long it took, and how many processor cycles the calling +/// thread used meanwhile against the processor's clock over the same +/// span. A thread that stood blocked in the kernel used few: run 307's +/// profile found the title's thread on a processor 10 to 15 % of its time +/// in these calls, on the one thread it followed. +struct Meter { + started: std::time::Instant, + cycles: u64, + tsc: u64, +} + +impl Meter { + fn begin() -> Meter { + let mut cycles = 0; + if meter_cycles() { + // SAFETY: the calling thread's own pseudo-handle and a valid + // out pointer. + unsafe { QueryThreadCycleTime(GetCurrentThread(), &mut cycles) }; + } + Meter { + started: std::time::Instant::now(), + cycles, + // SAFETY: reads the processor's counter. + tsc: unsafe { std::arch::x86_64::_rdtsc() }, + } + } + + /// Ends the span and counts it: `mapping` false for an unmapping call, + /// true for a mapping call. + fn end(self, mapping: bool) { + use victory_gpu::framelog::{T, add}; + // SAFETY: reads the processor's counter. + let tsc = unsafe { std::arch::x86_64::_rdtsc() }.wrapping_sub(self.tsc); + let us = self.started.elapsed().as_micros() as u64; + let (calls, cycles_of, tsc_of, count, time) = if mapping { + ( + T::RemapMapCalls, + T::RemapMapCycles, + T::RemapMapTsc, + [T::RemapMapC0, T::RemapMapC1, T::RemapMapC2, T::RemapMapC3], + [T::RemapMapU0, T::RemapMapU1, T::RemapMapU2, T::RemapMapU3], + ) + } else { + ( + T::RemapUnmapCalls, + T::RemapUnmapCycles, + T::RemapUnmapTsc, + [T::RemapUnmapC0, T::RemapUnmapC1, T::RemapUnmapC2, T::RemapUnmapC3], + [T::RemapUnmapU0, T::RemapUnmapU1, T::RemapUnmapU2, T::RemapUnmapU3], + ) + }; + add(calls, 1); + let class = match us { + 0..50 => 0, + 50..200 => 1, + 200..1000 => 2, + _ => 3, + }; + add(count[class], 1); + add(time[class], us); + if meter_cycles() { + let mut cycles = 0; + // SAFETY: as in `begin`. + unsafe { QueryThreadCycleTime(GetCurrentThread(), &mut cycles) }; + add(cycles_of, cycles.saturating_sub(self.cycles)); + add(tsc_of, tsc); + } + } +} + +/// Whether a mapping is tried before the placeholder is split, and the +/// split made only if the mapping failed (`VICTORY_REMAP_SPLIT=late`; +/// `alt`: twenty seconds so, twenty as before, each change said in the +/// log; unset: the split is tried first every time, as before). +/// +/// The split fails harmlessly when the range is a whole placeholder, which +/// it is after a page's own view was unmapped: then it is one call into +/// the system for nothing, and the title's thread takes its turn in the +/// kernel for it (run 307's profile: 1.05 ms a frame beside 8.75 ms of +/// mapping on the title's frame thread, on a processor 16 % of that +/// time). Tried late, a mapping into a range that is part of a larger +/// placeholder fails first (the range must match the placeholder exactly), +/// is split and tried again: two mapping calls and a split where there +/// was one of each. The frame log counts both ("splits tried, needed", +/// "tried again after a split"). +/// A mapping that fails is taken to leave the placeholder as it was. +fn split_late() -> bool { + use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_REMAP_SPLIT").as_deref() { + Ok("late") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: AtomicU8 = AtomicU8::new(2); + if LAST.swap(u8::from(on), Relaxed) != u8::from(on) { + tracing::info!( + "a placeholder is split only after a mapping into it failed from now (VICTORY_REMAP_SPLIT=alt): {}", + if on { "ON" } else { "off, split first as usual" } + ); + } + on + } + } +} + // Physical pages: on the console, 64 KiB frames a title maps into its own // reservations, at more than one address if it likes. Here each allocation // is a pagefile-backed section, its pages are 64 KiB slices of it, and a @@ -380,12 +635,25 @@ struct Slice { index: usize, } +impl Slice { + /// The key in `Physical::shown` of the page `k` pages after this one. + fn key(&self, k: usize) -> (usize, usize) { + (Arc::as_ptr(&self.section) as usize, self.index + k) + } +} + #[derive(Default)] struct Physical { next_page: usize, pages: HashMap<usize, Slice>, /// Mapped views by address: their length and what they show. views: BTreeMap<usize, (usize, Slice)>, + /// Where each page shows: by its section and its index there, the + /// address of that page in every view that shows it now ([`shown_at`]; + /// as upstream's c75fdba keeps it). The title maps pages where the + /// card reads them and has them filled afterwards by DirectStorage, + /// which writes through views of our own. + shown: HashMap<(usize, usize), Vec<usize>>, } static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| { @@ -415,7 +683,7 @@ pub extern "system" fn XMemAllocatePhysicalPages( return 0; }; // A pagefile-backed section of `size` bytes, its pages committed when - // first mapped or written (`commit`): Grand Theft Auto VI asks for 6.1 + // first mapped or written (`commit`): the title asks for 6.1 // GiB at once, which a busy host often cannot commit (error 1450). // SAFETY: plain section creation. let handle = unsafe { @@ -444,6 +712,9 @@ pub extern "system" fn XMemAllocatePhysicalPages( flags = format_args!("{flags:#x}"), "XMemAllocatePhysicalPages" ); + // For the GPU side's in-place census: only a committed section can be + // opened as a host heap. + victory_gpu::title_memory_section(handle as usize, size as u64, on_wine()); let section = Arc::new(Section(handle)); let mut physical = physical(); let first = physical.next_page; @@ -462,7 +733,7 @@ pub extern "system" fn XMemAllocatePhysicalPages( } /// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of -/// 16: Grand Theft Auto VI keeps them as 21-bit `number >> 4` and rebuilds +/// 16: the title keeps them as 21-bit `number >> 4` and rebuilds /// them with `<< 4` (128 GiB of pages at most). const FRAMES: usize = PAGE >> 12; @@ -491,6 +762,9 @@ impl View { fn map(slice: &Slice, n: usize) -> Option<View> { use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile}; let (offset, len) = ((slice.index * PAGE) as u64, n * PAGE); + // For the frame log: these views take their turn in the kernel + // beside the title's own mapping calls. + let started = std::time::Instant::now(); // SAFETY: slices of a section we own; the view is ours until dropped. let at = unsafe { MapViewOfFile( @@ -505,7 +779,10 @@ impl View { return None; } let view = View { at, len }; - commit(at.Value as usize, len).then_some(view) + let committed = commit(at.Value as usize, len); + victory_gpu::framelog::add(victory_gpu::framelog::T::DiskViews, 1); + victory_gpu::framelog::add(victory_gpu::framelog::T::DiskViewUs, started.elapsed().as_micros() as u64); + committed.then_some(view) } fn bytes(&mut self) -> &mut [u8] { @@ -519,8 +796,10 @@ impl View { impl Drop for View { fn drop(&mut self) { use windows_sys::Win32::System::Memory::UnmapViewOfFile; + let started = std::time::Instant::now(); // SAFETY: our view. unsafe { UnmapViewOfFile(self.at) }; + victory_gpu::framelog::add(victory_gpu::framelog::T::DiskViewUs, started.elapsed().as_micros() as u64); } } @@ -549,6 +828,12 @@ fn runs(pages: &[usize], offset: usize, len: usize) -> Option<Vec<(Slice, usize) Some(runs) } +/// Whether every page under `[offset, offset + len)` is known (a write that +/// fails with them known is a host failure). +pub(crate) fn pages_known(pages: &[usize], offset: usize, len: usize) -> bool { + runs(pages, offset, len).is_some() +} + /// Copies `data` into physical pages, from `offset` bytes into the first, /// whether or not they are mapped anywhere (DirectStorage destinations). /// One view per run of consecutive pages, not one per page: each view @@ -603,6 +888,58 @@ pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option< }) } +/// The title addresses that show bytes `[offset, offset + len)` of `pages` +/// now, byte for byte, as runs (address, bytes) in address order: a write +/// to the pages through a view of our own ([`page_window`], +/// [`write_physical`]) lands there too, and nothing that watches those +/// addresses sees it (the GPU side's guards fault only on a write at the +/// guarded address itself). Empty if no view shows them. Byte for byte, +/// not by whole pages: the title packs several small textures into one +/// page and fills each with a request of its own. +pub(crate) fn shown_at(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> { + let Some(end) = offset.checked_add(len) else { + return Vec::new(); + }; + let first = offset / PAGE; + let Some(touched) = pages.get(first..end.div_ceil(PAGE)) else { + return Vec::new(); + }; + let mut pieces: Vec<(usize, usize)> = Vec::new(); + { + let physical = physical(); + for (i, page) in touched.iter().enumerate() { + let Some(addresses) = physical.pages.get(page).and_then(|slice| physical.shown.get(&slice.key(0))) else { + continue; + }; + // The bytes of this page that the write covers. + let lo = if i == 0 { offset % PAGE } else { 0 }; + let hi = (end - (first + i) * PAGE).min(PAGE); + pieces.extend(addresses.iter().map(|&at| (at + lo, hi - lo))); + } + } + pieces.sort_unstable(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (at, bytes) in pieces { + match runs.last_mut() { + Some((start, n)) if *start + *n == at => *n += bytes, + _ => runs.push((at, bytes)), + } + } + runs +} + +/// Bytes `[offset, offset + len)` of `pages` have been written through a +/// view of our own: the GPU side is told at every title address that +/// shows them (`victory_gpu::title_memory_written`; what it does with it +/// is `VICTORY_PAGE_WRITES`' to say, and it counts either way). Call when +/// the bytes are there, and without the page table's lock ([`shown_at`] +/// takes and leaves it). +pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) { + for (at, bytes) in shown_at(pages, offset, len) { + victory_gpu::title_memory_written(at, bytes, true); + } +} + /// Maps `n` pages at `address`, in place of what is mapped there; null /// `pages` unmaps. Returns `address`, or null if a page or the host fails. pub extern "system" fn XMemMapPhysicalPages( @@ -610,8 +947,24 @@ pub extern "system" fn XMemMapPhysicalPages( n: usize, pages: *const usize, ) -> *mut c_void { + use victory_gpu::framelog::{T, add}; + let entered = std::time::Instant::now(); + let mapped = map_pages(address, n, pages); + add(T::RemapDirectCalls, 1); + add(T::RemapDirectPages, n as u64); + add(T::RemapDirectUs, entered.elapsed().as_micros() as u64); + mapped +} + +/// [`XMemMapPhysicalPages`] itself; the caller counts it for the frame log. +fn map_pages(address: *mut c_void, n: usize, pages: *const usize) -> *mut c_void { let base = address as usize; let mut physical = physical(); + // Until the pages are mapped again: `unmap` takes whole views away and + // maps what stays of them again, and a mapped view is a reservation + // until it is committed. A read of title memory in place must not fall + // into that gap (`victory_gpu::title_memory_remapping`). + let _changing = victory_gpu::title_memory_remapping(); unmap(&mut physical, base, n * PAGE); if pages.is_null() { return address; @@ -624,7 +977,7 @@ pub extern "system" fn XMemMapPhysicalPages( tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page"); return std::ptr::null_mut(); }; - // One mapping per run of consecutive slices of one section. + // One view per run of consecutive slices of one section. let run = 1 + pages[i + 1..] .iter() .zip(1..) @@ -643,7 +996,7 @@ pub extern "system" fn XMemMapPhysicalPages( } /// One page at each address; null `pages`, or a page number 0, unmaps -/// (Grand Theft Auto VI passes 0 for addresses to clear). +/// (the title passes 0 for addresses to clear). pub extern "system" fn XMemMapPhysicalPagesScatter( addresses: *const *mut c_void, n: usize, @@ -673,19 +1026,32 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( /// Maps the physical pages shown at `[from, from + len)` at `to` as well, /// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping -/// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`): Grand Theft Auto -/// VI maps pages into a pool view, then has the GPU map them into its tiled +/// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`): +/// the title maps pages into a pool view, then has the GPU map them into its tiled /// heap. Page by page; false if a source page is not mapped physical memory. pub fn map_alias(to: u64, from: u64, len: u64) -> bool { - let (to, from, len) = (to as usize, from as usize, len as usize); + use victory_gpu::framelog::{T, add}; + // From entry to return, the wait for the page table's lock included. + let entered = std::time::Instant::now(); + let mapped = alias(to as usize, from as usize, len as usize); + add(T::RemapAliasCalls, 1); + add(T::RemapAliasUs, entered.elapsed().as_micros() as u64); + mapped +} + +/// [`map_alias`] itself; the caller counts it for the frame log. +fn alias(to: usize, from: usize, len: usize) -> bool { + use victory_gpu::framelog::{T, add}; let mut physical = physical(); + // As in `XMemMapPhysicalPages`: no read in place meets the gap. + let _changing = victory_gpu::title_memory_remapping(); unmap(&mut physical, to, len); - for k in (0..len).step_by(PAGE) { - if from == 0 { - break; - } - let at = from + k; - let Some(slice) = physical + if from == 0 { + return true; + } + // The slice `from + k` shows. + let slice_at = |physical: &Physical, at: usize| { + physical .views .range(..=at) .next_back() @@ -694,79 +1060,132 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool { index: s.index + (at - base) / PAGE, section: s.section.clone(), }) - else { + }; + // One view per run of consecutive slices of one section, as + // `XMemMapPhysicalPages` maps: page by page was three host calls a + // page under the remapping lock, which texture reads wait on while the + // world streams in (up to 2 s of a frame's texture refreshes on the + // RTX 5070 test machine, runs r03 and r04). + // Where the two ranges overlap, a page looked up may be one just mapped: + // page by page then, as before. + let overlap = from < to + len && to < from + len; + let pages = len.div_ceil(PAGE); + let mut i = 0; + while i < pages { + let Some(first) = slice_at(&physical, from + i * PAGE) else { return false; }; - if !map(&mut physical, to + k, PAGE, slice) { - return false; + let mut run = 1; + while !overlap + && i + run < pages + && slice_at(&physical, from + (i + run) * PAGE) + .is_some_and(|s| Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + run) + { + run += 1; } + // For the frame log: the pages, and those of a run after its first, + // which one view shows together. + add(T::RemapAliasPages, run as u64); + add(T::RemapAliasRunPages, run as u64 - 1); + let at = to + i * PAGE; + if run > 1 { + // `unmap` leaves a placeholder per view it took away (a page each + // here): made one, or the run is mapped page by page below. + // SAFETY: acts only on placeholders; fails harmlessly unless + // `[at, at + run pages)` is exactly whole adjacent placeholders. + unsafe { + VirtualFree(at as *mut c_void, run * PAGE, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS); + } + if map_quiet(&mut physical, at, run * PAGE, first.clone()) { + i += run; + continue; + } + } + for k in 0..run { + let slice = Slice { + index: first.index + k, + section: first.section.clone(), + }; + if !map(&mut physical, at + k * PAGE, PAGE, slice) { + return false; + } + } + i += run; } true } /// Maps `slice` and the slices after it over `[base, base + len)`, which -/// must be placeholders. A view replaces exactly one placeholder, and a -/// reservation is often several by now (each mapping splits it at its -/// ends, unmapping does not join the pieces, titles split their own), so -/// the range is split at its two ends and each placeholder in it gets a -/// view of its part. Placeholders are never joined: that would also join -/// separate reservations, or pieces the title split, for good. All or -/// nothing: if a view fails, those made before it are placeholders again. +/// must lie in one placeholder. fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { - let end = base + len; - split_at(base); - split_at(end); - let mut made: Vec<(usize, usize, Slice)> = Vec::new(); - let mut at = base; - while at < end { - // What is not a placeholder fails in `map_view`. - let next = placeholder(at).map_or(end, |(_, stop)| stop.min(end)); - let offset = at - base; - let part = Slice { - index: slice.index + offset / PAGE, - section: slice.section.clone(), - }; - // A view must start on a page of the run to show its slice. - if !offset.is_multiple_of(PAGE) || !map_view(at, next - at, &part) { - for &(view, _, _) in &made { - let view = MEMORY_MAPPED_VIEW_ADDRESS { - Value: view as *mut c_void, - }; - // SAFETY: a view made above, back to its placeholder. - unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; - } - return false; - } - made.push((at, next - at, part)); - at = next; - } - for (at, len, part) in made { - // New contents, read-write: the GPU side's copies no longer guard it. - victory_gpu::title_memory_remapped(at, len); - physical.views.insert(at, (len, part)); - } - true + map_logged(physical, base, len, slice, true) } -/// Replaces the placeholder `[base, base + len)` with a view of `slice` and -/// the slices after it, committed. -fn map_view(base: usize, len: usize, slice: &Slice) -> bool { - // SAFETY: replaces the placeholder `[base, base + len)` with a view of - // the section; the host refuses anything that is not that placeholder. - let view = unsafe { - MapViewOfFile3( - slice.section.0, - GetCurrentProcess(), - base as *const c_void, - (slice.index * PAGE) as u64, - len, - MEM_REPLACE_PLACEHOLDER, - PAGE_READWRITE, - std::ptr::null_mut(), - 0, - ) +/// [`map`] without the warning when the host refuses (a caller with +/// another way to map). +fn map_quiet(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { + map_logged(physical, base, len, slice, false) +} + +fn map_logged(physical: &mut Physical, base: usize, len: usize, slice: Slice, log: bool) -> bool { + use victory_gpu::framelog::{T, add}; + let started = std::time::Instant::now(); + // Splits the placeholder around the range (failing harmlessly when the + // range is the whole placeholder). + let split = || { + let began = std::time::Instant::now(); + // SAFETY: acts only on a placeholder. + let done = unsafe { + VirtualFree( + base as *mut c_void, + len, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ) + } != 0; + add(T::RemapSplits, 1); + add(T::RemapSplitsDone, u64::from(done)); + add(T::RemapSplitUs, began.elapsed().as_micros() as u64); + }; + // Maps the section over the range, which must be a whole placeholder. + let map_view = || { + let meter = Meter::begin(); + // SAFETY: acts only on a placeholder. + let view = unsafe { + MapViewOfFile3( + slice.section.0, + GetCurrentProcess(), + base as *const c_void, + (slice.index * PAGE) as u64, + len, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + meter.end(true); + view + }; + let view = if split_late() { + // The range is most often a whole placeholder already (a page + // whose own view was just unmapped): mapped at once; split and + // mapped again only if that failed ([`split_late`]). + let first = map_view(); + if first.Value as usize == base { + first + } else { + add(T::RemapMapRetries, 1); + split(); + map_view() + } + } else { + split(); + map_view() }; if view.Value as usize != base { + if !log { + return false; + } tracing::warn!( address = format_args!("{base:#x}"), len, @@ -775,51 +1194,25 @@ fn map_view(base: usize, len: usize, slice: &Slice) -> bool { ); return false; } + let mapped = std::time::Instant::now(); + add(T::RemapMapUs, (mapped - started).as_micros() as u64); if !commit(base, len) { // SAFETY: the view just mapped, back to a placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; return false; } - true -} - -/// The start and end of the placeholder holding `at`, if it may be one -/// (other reserved memory looks the same, but the host refuses to split it -/// or map over it). -fn placeholder(at: usize) -> Option<(usize, usize)> { - // SAFETY: plain data; zero is a valid value. - let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - let size = size_of::<MEMORY_BASIC_INFORMATION>(); - // SAFETY: a query of our own address space into `info`. - let found = unsafe { VirtualQuery(at as *const c_void, &mut info, size) } == size; - (found && info.State == MEM_RESERVE && info.Type == MEM_PRIVATE).then(|| { - ( - info.AllocationBase as usize, - info.BaseAddress as usize + info.RegionSize, - ) - }) -} - -/// Splits the placeholder holding `at` in two there, if it starts below. -/// The same call frees reserved memory that replaced a placeholder back to -/// one, committed pages and all, so everything below `at` in it must be -/// reserved: nothing committed is ever freed here. -fn split_at(at: usize) { - if let Some((start, _)) = placeholder(at) - && start < at - && placeholder(start).is_some_and(|(_, stop)| stop >= at) - { - // SAFETY: `[start, at)` is reserved and holds no data; the host - // fails the call on anything but a placeholder or memory that - // replaced one, and then changes nothing. - unsafe { - VirtualFree( - start as *mut c_void, - at - start, - MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, - ) - }; + let committed = std::time::Instant::now(); + add(T::RemapCommitUs, (committed - mapped).as_micros() as u64); + // New contents, read-write: the GPU side's copies no longer guard it. + victory_gpu::title_memory_remapped(base, len); + // What the range shows now, for the GPU side's in-place census. + victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64); + add(T::RemapNotesUs, committed.elapsed().as_micros() as u64); + for k in 0..len.div_ceil(PAGE) { + physical.shown.entry(slice.key(k)).or_default().push(base + k * PAGE); } + physical.views.insert(base, (len, slice)); + true } /// Commits the section pages a view shows (once per page, whichever view). @@ -831,14 +1224,7 @@ fn commit(base: usize, len: usize) -> bool { if !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null() { return true; } - commit_refused(len, "physical pages", std::io::Error::last_os_error()); - false -} - -/// Reports memory the host would not give: at the Windows commit limit to -/// `crashes.log`, since the title usually faults soon after on the null it -/// gets; otherwise as a warning. -fn commit_refused(len: usize, what: &str, error: std::io::Error) { + let error = std::io::Error::last_os_error(); if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) { let mut info = PERFORMANCE_INFORMATION { cb: size_of::<PERFORMANCE_INFORMATION>() as u32, @@ -846,25 +1232,20 @@ fn commit_refused(len: usize, what: &str, error: std::io::Error) { }; // SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION. let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0; - victory_loader::log_crash(&commit_limit_message( - len, - what, - &error, - queried.then_some(&info), - )); + victory_loader::log_crash(&commit_limit_message(len, &error, queried.then_some(&info))); } else { - tracing::warn!(len, %error, "committing {what} failed"); + tracing::warn!(len, %error, "committing physical pages failed"); } + false } fn commit_limit_message( len: usize, - what: &str, error: &std::io::Error, info: Option<&PERFORMANCE_INFORMATION>, ) -> String { let mut message = format!( - "VIctory: Windows commit limit reached while committing {len} bytes of {what}: {error}.\n" + "VIctory: Windows commit limit reached while committing {len} bytes of physical pages: {error}.\n" ); if let Some(info) = info { use std::fmt::Write; @@ -908,7 +1289,21 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { let Some((size, slice)) = physical.views.remove(&at) else { continue; }; + for k in 0..size.div_ceil(PAGE) { + let key = slice.key(k); + if let Some(addresses) = physical.shown.get_mut(&key) { + addresses.retain(|&a| a != at + k * PAGE); + if addresses.is_empty() { + physical.shown.remove(&key); + } + } + } + use victory_gpu::framelog::{T, add}; + let started = std::time::Instant::now(); victory_gpu::title_memory_remapped(at, size); + let noted = std::time::Instant::now(); + add(T::RemapNotesUs, (noted - started).as_micros() as u64); + let meter = Meter::begin(); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { UnmapViewOfFile2( @@ -919,6 +1314,15 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { MEM_PRESERVE_PLACEHOLDER, ) }; + meter.end(false); + add(T::RemapUnmapUs, noted.elapsed().as_micros() as u64); + // What of the view lies outside the range asked for is mapped + // again below: the whole view went for it. + let outside = base.saturating_sub(at) + (at + size).saturating_sub(end); + if outside != 0 { + add(T::RemapCuts, 1); + add(T::RemapCutBytes, outside as u64); + } if at < base { map(physical, at, base - at, slice.clone()); } @@ -970,6 +1374,25 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin gpu_optimal_limit: gpu_optimal, ..Default::default() }; + // What the title is told, logged at the first asking and at every + // 1,024th: "used" is all the process has committed, the layer's own + // memory and the card's included (27 GB in run 60's gameplay against a + // limit of 13.5 GB). A title that budgets its streaming from these two + // figures believes it is far over its limit. + // shortcut: the figure is not yet the title's own memory alone (its + // heaps and the pages it mapped); count those if this line shows the + // title asking. + static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let asked = ASKED.fetch_add(1, Ordering::Relaxed); + if asked.is_multiple_of(1024) { + tracing::info!( + asked = asked + 1, + which = _which, + limit_mb = stats.title_limit >> 20, + used_mb = stats.title_used >> 20, + "the title asks how much memory it uses" + ); + } // SAFETY: checked non-null; the title passes room for the structure. unsafe { out.write(stats) }; 1 @@ -1022,6 +1445,61 @@ pub(crate) fn module() -> HleModule { mod tests { use super::*; + #[test] + fn commit_notifications_cover_both_blocks_of_an_unaligned_request() { + let reservation = XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + MEM_RESERVE, + 0, + PAGE_NOACCESS, + ); + assert!(!reservation.is_null()); + let first = reservation as usize; + let boundary = first + PAGE; + let mut notified = None; + let at = virtual_alloc( + (boundary - 1) as _, + 2, + MEM_COMMIT, + 0, + PAGE_READWRITE, + |start, size| { + notified = Some(start..start + size); + }, + ); + assert!(!at.is_null()); + assert!((at as usize) < boundary - 1); + assert_eq!(query((boundary - 1) as _).host.State, MEM_COMMIT); + assert_eq!(query(boundary as _).host.State, MEM_COMMIT); + // SAFETY: this test owns the entire reservation. + assert_ne!(unsafe { VirtualFree(reservation, 0, MEM_RELEASE) }, 0); + let range = notified.expect("a successful commit notifies the GPU watch"); + assert_eq!( + range.start / PAGE..range.end.div_ceil(PAGE), + first / PAGE..first / PAGE + 2 + ); + } + + #[test] + fn commit_notification_uses_the_chosen_address_for_a_null_request() { + let mut notified = None; + let at = virtual_alloc( + std::ptr::null_mut(), + PAGE, + MEM_COMMIT, + 0, + PAGE_READWRITE, + |start, size| { + notified = Some((start, size)); + }, + ); + assert!(!at.is_null()); + // SAFETY: this test owns the entire reservation. + assert_ne!(unsafe { VirtualFree(at, 0, MEM_RELEASE) }, 0); + assert_eq!(notified, Some((at as usize, PAGE))); + } + fn query(address: *const c_void) -> BasicInformation { // SAFETY: plain data; zero is a valid value. let mut info: BasicInformation = unsafe { std::mem::zeroed() }; @@ -1126,11 +1604,10 @@ mod tests { PageSize: 4096, ..Default::default() }; - let report = commit_limit_message(4 * MIB, "physical pages", &error, Some(&info)); - assert!(report.contains("4194304 bytes of physical pages")); + let report = commit_limit_message(4 * MIB, &error, Some(&info)); + assert!(report.contains("4194304 bytes")); assert!(report.contains("2 MiB of 3 MiB in use")); - let fallback = commit_limit_message(4 * MIB, "virtual memory", &error, None); - assert!(fallback.contains("4194304 bytes of virtual memory")); + let fallback = commit_limit_message(4 * MIB, &error, None); for report in [&report, &fallback] { assert!(report.contains("os error 1455")); assert!(report.contains("Windows paging file size")); @@ -1215,6 +1692,100 @@ mod tests { assert_eq!(XMemIsToolsMemAvailable(), 0); } + /// The GPU's page-mapping copy over a range that holds a view per page + /// (how it leaves one): the pages are mapped as one view, and every + /// address shows the page it should. + #[test] + fn a_page_mapping_copy_maps_a_run_as_one_view() { + const N: usize = 4; + let mut pages = [0usize; N]; + let mut n = N; + assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + let reserve = || XMemVirtualAlloc(std::ptr::null_mut(), N * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + let (a, b) = (reserve(), reserve()); + assert!(!a.is_null() && !b.is_null()); + let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE); + assert_eq!(XMemMapPhysicalPages(a, N, pages.as_ptr()), a); + for k in 0..N { + // SAFETY: mapped read-write. + unsafe { at(a, k).cast::<u8>().add(3).write(10 + k as u8) }; + // A view per page at `b`, in reverse order of the pages. + assert!(map_alias(at(b, k) as u64, at(a, N - 1 - k) as u64, PAGE as u64)); + } + // SAFETY: mapped read-write. + assert_eq!(unsafe { b.cast::<u8>().add(3).read() }, 10 + (N - 1) as u8); + assert!(map_alias(b as u64, a as u64, (N * PAGE) as u64)); + { + let physical = physical(); + let (len, _) = physical.views.get(&(b as usize)).expect("a view at b"); + assert_eq!(*len, N * PAGE, "one view for the run"); + assert!(physical.views.range(b as usize + 1..b as usize + N * PAGE).next().is_none()); + } + for k in 0..N { + // SAFETY: mapped read-write. + assert_eq!(unsafe { at(b, k).cast::<u8>().add(3).read() }, 10 + k as u8); + } + // Unmapping one page in the middle of the run keeps the others. + assert!(map_alias(at(b, 1) as u64, 0, PAGE as u64)); + assert_eq!(query(at(b, 1)).host.State, MEM_RESERVE); + // SAFETY: still mapped. + assert_eq!(unsafe { at(b, 2).cast::<u8>().add(3).read() }, 12); + assert!(map_alias(b as u64, 0, (N * PAGE) as u64)); + assert!(map_alias(a as u64, 0, (N * PAGE) as u64)); + assert_eq!(XMemFreePhysicalPages(N, pages.as_ptr()), 1); + } + + /// A thread that reads a mapped page in place, as the GPU side reads a + /// texture, never meets the moment in which the runtime has taken the + /// page's view away to map it again: mapping the same pages at the same + /// address unmaps the view and maps a new one, and without the lock the + /// reader faults on a page "reserved, never committed" (the crashes of + /// runs 71 and 74). + #[test] + fn a_read_in_place_never_meets_the_gap_of_a_remapping() { + use std::sync::atomic::{AtomicBool, Ordering}; + let mut pages = [0usize; 3]; + let mut n = 3; + assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + let a = XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + // SAFETY: mapped read-write. + unsafe { a.cast::<u8>().write(1) }; + let first = a as usize; + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let reader = { + let stop = stop.clone(); + std::thread::spawn(move || { + let mut reads = 0u64; + while !stop.load(Ordering::Relaxed) { + let _reading = victory_gpu::title_memory_reading(); + // SAFETY: the page is mapped whenever no change of + // mapping is under way, and none is while `_reading` + // is held. + assert_eq!(unsafe { (first as *const u8).read_volatile() }, 1); + reads += 1; + } + reads + }) + }; + for _ in 0..2000 { + // The same pages at the same address: the view goes and comes + // back, with the same bytes. + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + } + stop.store(true, Ordering::Relaxed); + assert!(reader.join().expect("the reader never faulted") > 0); + assert_eq!(XMemMapPhysicalPages(a, 3, std::ptr::null()), a); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + } + #[test] fn mapping_no_pages_changes_nothing() { let pages = allocate(2); @@ -1321,6 +1892,54 @@ mod tests { assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); } + /// Pages say where the title has them mapped, byte for byte (after + /// fork PR #571's test; its runs are whole pages). + #[test] + fn pages_say_where_they_are_mapped() { + let pages = allocate(3); + let reserve = |n: usize| { + let at = XMemVirtualAlloc(std::ptr::null_mut(), n * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!at.is_null()); + at + }; + // `b` keeps a page unmapped at either end, so that no run at `b` + // ever touches one at `a`, wherever the host puts the two. + let (a, b) = (reserve(3), reserve(4)); + assert!(shown_at(&pages, 0, 3 * PAGE).is_empty(), "mapped nowhere"); + // All three at `a`; the last two at `b`, from its second page on. + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + let second = b.wrapping_byte_add(PAGE); + assert_eq!(XMemMapPhysicalPages(second, 2, pages[1..].as_ptr()), second); + let (a, second) = (a as usize, second as usize); + let sorted = |mut runs: Vec<(usize, usize)>| { + runs.sort_unstable(); + runs + }; + assert_eq!(shown_at(&pages, 0, PAGE), vec![(a, PAGE)]); + // A request for part of a page names those bytes alone. + assert_eq!(shown_at(&pages, 0x4000, 0x3000), vec![(a + 0x4000, 0x3000)]); + // Across two pages, shown at two addresses each: one run at each. + assert_eq!( + shown_at(&pages, PAGE + 1, PAGE), + sorted(vec![(a + PAGE + 1, PAGE), (second + 1, PAGE)]) + ); + // A page unmapped in the middle of a view: the rest still shows. + let middle = (a + PAGE) as *mut c_void; + assert_eq!(XMemMapPhysicalPages(middle, 1, std::ptr::null()), middle); + assert_eq!( + shown_at(&pages, 0, 3 * PAGE), + sorted(vec![(a, PAGE), (a + 2 * PAGE, PAGE), (second, 2 * PAGE)]) + ); + // Too few pages for the bytes: nothing (the write fails too). + assert!(shown_at(&pages, 0, 3 * PAGE + 1).is_empty()); + for (at, n) in [(a, 3), (second, 2)] { + let at = at as *mut c_void; + assert_eq!(XMemMapPhysicalPages(at, n, std::ptr::null()), at); + } + assert!(shown_at(&pages, 0, 3 * PAGE).is_empty()); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + } + #[test] fn page_windows_cover_one_run_in_place() { let (a, b) = (allocate(3), allocate(1)); @@ -1342,137 +1961,4 @@ mod tests { assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); } - - /// `n` physical pages (consecutive slices of one section) and a - /// reservation of `n` 64 KiB pages for them. - fn pages_and_reservation(n: usize) -> (Vec<usize>, *mut c_void) { - let mut pages = vec![0usize; n]; - let mut count = n; - assert_eq!( - XMemAllocatePhysicalPages(0, &mut count, pages.as_mut_ptr()), - 1 - ); - let reservation = XMemVirtualAlloc( - std::ptr::null_mut(), - n * PAGE, - MEM_RESERVE | PAGES_64K, - 0, - PAGE_READWRITE, - ); - assert!(!reservation.is_null()); - (pages, reservation) - } - - /// Unmapping part of a run leaves the range as several host - /// placeholders; mapping a run over all of them again works, and the - /// pages keep what was written through the first mapping. - #[test] - fn a_run_maps_again_after_a_partial_unmap() { - let (pages, a) = pages_and_reservation(3); - let at = |page: usize| a.wrapping_byte_add(page * PAGE); - assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); - // SAFETY: mapped read-write. - unsafe { - for page in 0..3 { - at(page).cast::<u8>().write(10 + page as u8); - } - } - assert_eq!(XMemMapPhysicalPages(at(1), 1, std::ptr::null()), at(1)); - assert_eq!(query(at(1)).host.State, MEM_RESERVE); - - assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); - for page in 0..3 { - assert_eq!(query(at(page)).host.State, MEM_COMMIT, "page {page}"); - // SAFETY: mapped read-write. - assert_eq!(unsafe { at(page).cast::<u8>().read() }, 10 + page as u8); - } - assert_eq!(XMemMapPhysicalPages(a, 3, std::ptr::null()), a); - assert_eq!(query(a).host.State, MEM_RESERVE); - assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); - } - - /// A run that starts inside one host placeholder and ends inside the - /// next (left by an earlier, shorter run) maps, and the pages around it - /// stay unmapped. - #[test] - fn a_run_maps_across_two_placeholders() { - let (pages, a) = pages_and_reservation(4); - let at = |page: usize| a.wrapping_byte_add(page * PAGE); - // Mapping and unmapping pages 0-1 splits the reservation in two. - assert_eq!(XMemMapPhysicalPages(a, 2, pages.as_ptr()), a); - assert_eq!(XMemMapPhysicalPages(a, 2, std::ptr::null()), a); - - assert_eq!(XMemMapPhysicalPages(at(1), 2, pages[1..].as_ptr()), at(1)); - assert_eq!(query(a).host.State, MEM_RESERVE); - assert_eq!(query(at(1)).host.State, MEM_COMMIT); - assert_eq!(query(at(2)).host.State, MEM_COMMIT); - assert_eq!(query(at(3)).host.State, MEM_RESERVE); - // Page 3, split off by the run, still takes a mapping: the run's - // last page shows there too. - // SAFETY: mapped read-write. - unsafe { - at(2).cast::<u8>().write(42); - assert_eq!(XMemMapPhysicalPages(at(3), 1, pages[2..].as_ptr()), at(3)); - assert_eq!(at(3).cast::<u8>().read(), 42); - } - assert_eq!(XMemMapPhysicalPages(a, 4, std::ptr::null()), a); - assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); - } - - /// Placeholders a run spans are never joined: a piece the title split - /// off itself is still its own after the run is unmapped, so the title - /// can release it. - #[test] - fn a_run_keeps_the_placeholders_it_spans() { - let (pages, a) = pages_and_reservation(4); - let at = |page: usize| a.wrapping_byte_add(page * PAGE); - // SAFETY: splits the reservation's placeholder, as a title does. - let split = unsafe { VirtualFree(a, 2 * PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) }; - assert_ne!(split, 0); - assert_eq!(XMemMapPhysicalPages(a, 4, pages.as_ptr()), a); - assert_eq!(XMemMapPhysicalPages(a, 4, std::ptr::null()), a); - let info = query(at(2)).host; - assert_eq!((info.AllocationBase, info.RegionSize), (at(2), 2 * PAGE)); - // SAFETY: the title's own piece, unmapped. - assert_ne!(unsafe { VirtualFree(at(2), 0, MEM_RELEASE) }, 0); - assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); - } - - /// A run whose second part is no placeholder (memory committed in place - /// of one) fails: its first part is unmapped again, and the committed - /// memory, which the run ends inside, keeps its data. - #[test] - fn a_failed_run_leaves_no_view() { - let (pages, a) = pages_and_reservation(3); - let at = |page: usize| a.wrapping_byte_add(page * PAGE); - // SAFETY: splits the placeholder, makes pages 1-2 an ordinary - // allocation in place and commits page 1 of it. - unsafe { - assert_ne!( - VirtualFree(a, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), - 0 - ); - let p = VirtualAlloc2( - GetCurrentProcess(), - at(1), - 2 * PAGE, - MEM_RESERVE | MEM_REPLACE_PLACEHOLDER, - PAGE_READWRITE, - std::ptr::null_mut(), - 0, - ); - assert_eq!(p, at(1)); - assert!(!VirtualAlloc(at(1), PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); - at(1).cast::<u8>().write(99); - } - assert!(XMemMapPhysicalPages(a, 2, pages.as_ptr()).is_null()); - assert_eq!(query(a).host.State, MEM_RESERVE); - assert_eq!(query(at(1)).host.State, MEM_COMMIT); - // SAFETY: still committed. - assert_eq!(unsafe { at(1).cast::<u8>().read() }, 99); - // Page 0 is a placeholder again: it takes a mapping. - assert_eq!(XMemMapPhysicalPages(a, 1, pages.as_ptr()), a); - assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a); - assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); - } } diff --git a/crates/victory-hle/src/modules/xnetworking.rs b/crates/victory-hle/src/modules/xnetworking.rs index 8670ff2922..c0b21a3f2a 100644 --- a/crates/victory-hle/src/modules/xnetworking.rs +++ b/crates/victory-hle/src/modules/xnetworking.rs @@ -18,7 +18,7 @@ pub const PROVIDER: Guid = Guid::new( [0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a], ); -/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x18-0x88) +/// As the title (2026) asks for it; the slots it calls (0x18-0x88) /// take the same arguments as under the provider's own id (older titles). pub const IID_2026: Guid = Guid::new( 0xbf23_46b2, diff --git a/crates/victory-hle/src/modules/xpackage.rs b/crates/victory-hle/src/modules/xpackage.rs index f3ac8d1272..315faac507 100644 --- a/crates/victory-hle/src/modules/xpackage.rs +++ b/crates/victory-hle/src/modules/xpackage.rs @@ -20,7 +20,7 @@ pub const PROVIDER: Guid = Guid::new( [0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e], ); -/// As Grand Theft Auto VI (2026) asks for it. Its slots up to 0xd0 take the +/// As the title (2026) asks for it. Its slots up to 0xd0 take the /// arguments the public API lists in the same order; 0x110 uninstalls a /// package, 0x128/0x130 mount one with UI, 0x138 enumerates packages. pub const IID_2026: Guid = Guid::new( @@ -46,63 +46,6 @@ fn is_ours(id: *const c_char) -> bool { text(id).is_some_and(|id| id == identifier()) } -/// Values of the public `XPackageChunkSelectorType` enum. -pub const SELECTOR_LANGUAGE: u32 = 0; -pub const SELECTOR_TAG: u32 = 1; -pub const SELECTOR_CHUNK: u32 = 2; -pub const SELECTOR_FEATURE: u32 = 3; - -/// The public `XPackageChunkSelector` ABI: a `u32` type tag and a union of a -/// NUL-terminated attribute or a chunk id. Read the tag as an integer: an -/// unknown value must be rejected, not turned into an invalid Rust enum. -#[repr(C)] -#[derive(Clone, Copy)] -pub struct ChunkSelector { - pub kind: u32, - pub value: SelectorValue, -} - -#[repr(C)] -#[derive(Clone, Copy)] -pub union SelectorValue { - pub language: *const c_char, - pub tag: *const c_char, - pub feature: *const c_char, - pub chunk_id: u32, -} - -/// Accepts zero selectors (meaning "the whole package") and rejects the -/// combinations the console rejects: a missing array, an unknown type, or a -/// string attribute that is null or empty. -fn validate_selectors(count: u32, selectors: *const ChunkSelector) -> Result<(), HRESULT> { - if count == 0 { - return Ok(()); - } - if selectors.is_null() - || count as usize > isize::MAX as usize / std::mem::size_of::<ChunkSelector>() - { - return Err(xasync::E_INVALIDARG); - } - // SAFETY: the title passes `count` contiguous selectors (checked above). - for selector in unsafe { std::slice::from_raw_parts(selectors, count as usize) } { - let attribute = match selector.kind { - // SAFETY: language, tag and feature all store a NUL-terminated - // pointer in the union, as the public XPackage header defines. - SELECTOR_LANGUAGE => unsafe { selector.value.language }, - // SAFETY: same union member type as `language`. - SELECTOR_TAG => unsafe { selector.value.tag }, - // SAFETY: same union member type as `language`. - SELECTOR_FEATURE => unsafe { selector.value.feature }, - SELECTOR_CHUNK => continue, - _ => return Err(xasync::E_INVALIDARG), - }; - if text(attribute).is_none_or(|s| s.is_empty()) { - return Err(xasync::E_INVALIDARG); - } - } - Ok(()) -} - /// Bytes in the package folder, counted once. fn package_bytes() -> u64 { fn size(dir: &Path) -> u64 { @@ -145,8 +88,8 @@ fn monitor() -> *const c_void { extern "system" fn create_monitor( _: This, id: *const c_char, - selector_count: u32, - selectors: *const c_void, + _selector_count: u32, + _selectors: *const c_void, _interval_ms: u32, _queue: *const c_void, out: *mut *const c_void, @@ -154,9 +97,6 @@ extern "system" fn create_monitor( if !is_ours(id) { return NO_PACKAGE; } - if let Err(hr) = validate_selectors(selector_count, selectors.cast()) { - return hr; - } put(out, monitor()) } extern "system" fn close_monitor(_: This, _: *const c_void) {} @@ -197,37 +137,30 @@ extern "system" fn register_progress( } /// 0: ready. -// shortcut: every well-formed selector counts as installed, including ones -// the package's layout does not have; Grand Theft Auto VI asks only about -// its own chunks, which a full install has. +// shortcut: every selector counts as installed, including ones the +// package's layout does not have (the console answers those with an +// invalid-selector error); the title asks only about its own +// chunks, which a full install has. extern "system" fn find_availability( _: This, id: *const c_char, - selector_count: u32, - selectors: *const c_void, + _selector_count: u32, + _selectors: *const c_void, out: *mut u32, ) -> HRESULT { if !is_ours(id) { return NO_PACKAGE; } - if let Err(hr) = validate_selectors(selector_count, selectors.cast()) { - return hr; - } put(out, 0) } extern "system" fn change_order( _: This, id: *const c_char, - count: u32, - selectors: *const c_void, + _count: u32, + _selectors: *const c_void, ) -> HRESULT { - if !is_ours(id) { - return NO_PACKAGE; - } - validate_selectors(count, selectors.cast()) - .err() - .unwrap_or(S_OK) + if is_ours(id) { S_OK } else { NO_PACKAGE } } static INSTALL: u8 = 0; @@ -236,23 +169,18 @@ static INSTALL: u8 = 0; extern "system" fn install_chunks_async( _: This, id: *const c_char, - count: u32, - selectors: *const c_void, + _count: u32, + _selectors: *const c_void, _interval_ms: u32, _suppress_confirmation: bool, block: *mut AsyncBlock, ) -> HRESULT { - if !is_ours(id) { - return NO_PACKAGE; - } - if let Err(hr) = validate_selectors(count, selectors.cast()) { - return hr; - } - xasync::finished_with( - block, - (&raw const INSTALL).cast(), - Ok(xasync::bytes(monitor())), - ) + let result = if is_ours(id) { + Ok(xasync::bytes(monitor())) + } else { + Err(NO_PACKAGE) + }; + xasync::finished_with(block, (&raw const INSTALL).cast(), result) } extern "system" fn install_chunks_result( _: This, @@ -266,17 +194,14 @@ extern "system" fn install_chunks_result( extern "system" fn estimate_download( _: This, id: *const c_char, - count: u32, - selectors: *const c_void, + _count: u32, + _selectors: *const c_void, bytes: *mut u64, confirm: *mut bool, ) -> HRESULT { if !is_ours(id) { return NO_PACKAGE; } - if let Err(hr) = validate_selectors(count, selectors.cast()) { - return hr; - } if !confirm.is_null() { // SAFETY: checked non-null. unsafe { confirm.write(false) }; @@ -285,20 +210,15 @@ extern "system" fn estimate_download( } // shortcut: accepted but nothing is removed (the package folder is the -// user's), so the chunks stay ready; Grand Theft Auto VI's one call site +// user's), so the chunks stay ready; the title's one call site // (title+0x293b4b0, its chunk manager) would then see them still installed. extern "system" fn uninstall_chunks( _: This, id: *const c_char, - count: u32, - selectors: *const c_void, + _count: u32, + _selectors: *const c_void, ) -> HRESULT { - if !is_ours(id) { - return NO_PACKAGE; - } - validate_selectors(count, selectors.cast()) - .err() - .unwrap_or(S_OK) + if is_ours(id) { S_OK } else { NO_PACKAGE } } /// Mount handles only come from mounting another package, and there is @@ -336,7 +256,7 @@ extern "system" fn mount_result( /// Titles enumerate content packages (kind 1); there are none. // shortcut: the game kind (0) also lists nothing, not this installation; -// Grand Theft Auto VI enumerates only content (kind 1, title+0x2937bf0). +// The title enumerates only content (kind 1, title+0x2937bf0). extern "system" fn enumerate( _: This, kind: u32, @@ -396,159 +316,6 @@ mod tests { use super::*; use crate::modules::xgameruntime::method; - #[test] - fn selectors_are_validated() { - let none = std::ptr::null(); - assert_eq!(validate_selectors(0, none), Ok(())); - assert_eq!(validate_selectors(1, none), Err(xasync::E_INVALIDARG)); - - let unknown = [ChunkSelector { - kind: 4, - value: SelectorValue { chunk_id: 0 }, - }]; - assert_eq!( - validate_selectors(1, unknown.as_ptr()), - Err(xasync::E_INVALIDARG) - ); - - let empty = [ChunkSelector { - kind: SELECTOR_LANGUAGE, - value: SelectorValue { - language: c"".as_ptr(), - }, - }]; - assert_eq!( - validate_selectors(1, empty.as_ptr()), - Err(xasync::E_INVALIDARG) - ); - - let null = [ChunkSelector { - kind: SELECTOR_TAG, - value: SelectorValue { - tag: std::ptr::null(), - }, - }]; - assert_eq!( - validate_selectors(1, null.as_ptr()), - Err(xasync::E_INVALIDARG) - ); - - let good = [ - ChunkSelector { - kind: SELECTOR_LANGUAGE, - value: SelectorValue { - language: c"en-US".as_ptr(), - }, - }, - ChunkSelector { - kind: SELECTOR_TAG, - value: SelectorValue { - tag: c"BigMap".as_ptr(), - }, - }, - ChunkSelector { - kind: SELECTOR_FEATURE, - value: SelectorValue { - feature: c"BigMaps".as_ptr(), - }, - }, - ChunkSelector { - kind: SELECTOR_CHUNK, - value: SelectorValue { chunk_id: 7 }, - }, - ]; - assert_eq!(validate_selectors(good.len() as u32, good.as_ptr()), Ok(())); - } - - #[test] - fn bad_selectors_are_refused_by_the_api() { - let this: This = &OBJECT; - let ours = format!("{}\0", identifier()); - let id = ours.as_ptr().cast(); - let none = std::ptr::null(); - - type Create = extern "system" fn( - This, - *const c_char, - u32, - *const c_void, - u32, - *const c_void, - *mut *const c_void, - ) -> HRESULT; - let mut handle = std::ptr::null(); - assert_eq!( - method::<Create>(&OBJECT, 0x28)(this, id, 1, none, 0, none, &mut handle), - xasync::E_INVALIDARG - ); - assert!(handle.is_null()); - - type Find = - extern "system" fn(This, *const c_char, u32, *const c_void, *mut u32) -> HRESULT; - let mut availability = 9; - let find = method::<Find>(&OBJECT, 0x60); - assert_eq!( - find(this, id, 1, none, &mut availability), - xasync::E_INVALIDARG - ); - assert_eq!(availability, 9, "no output on error"); - assert_eq!( - find(this, c"dlc".as_ptr(), 1, none, &mut availability), - NO_PACKAGE - ); - assert_eq!(find(this, id, 0, none, &mut availability), S_OK); - assert_eq!(availability, 0, "ready"); - - type Change = extern "system" fn(This, *const c_char, u32, *const c_void) -> HRESULT; - assert_eq!( - method::<Change>(&OBJECT, 0x70)(this, id, 1, none), - xasync::E_INVALIDARG - ); - - type Install = extern "system" fn( - This, - *const c_char, - u32, - *const c_void, - u32, - bool, - *mut AsyncBlock, - ) -> HRESULT; - let mut block = AsyncBlock { - queue: std::ptr::null(), - context: std::ptr::null_mut(), - callback: None, - internal: [0; 4], - }; - assert_eq!( - method::<Install>(&OBJECT, 0x80)(this, id, 1, none, 0, false, &mut block), - xasync::E_INVALIDARG - ); - - type Estimate = extern "system" fn( - This, - *const c_char, - u32, - *const c_void, - *mut u64, - *mut bool, - ) -> HRESULT; - let mut bytes = 7; - let mut confirm = true; - assert_eq!( - method::<Estimate>(&OBJECT, 0x90)(this, id, 1, none, &mut bytes, &mut confirm), - xasync::E_INVALIDARG - ); - assert_eq!(bytes, 7, "no output on error"); - assert!(confirm, "no output on error"); - - type Uninstall = extern "system" fn(This, *const c_char, u32, *const c_void) -> HRESULT; - assert_eq!( - method::<Uninstall>(&OBJECT, 0x98)(this, id, 1, none), - xasync::E_INVALIDARG - ); - } - #[test] fn the_installation_is_complete_and_alone() { let this: This = &OBJECT; diff --git a/crates/victory-hle/src/modules/xstore.rs b/crates/victory-hle/src/modules/xstore.rs index e54bbbecf1..9e2b74b21f 100644 --- a/crates/victory-hle/src/modules/xstore.rs +++ b/crates/victory-hle/src/modules/xstore.rs @@ -7,7 +7,7 @@ use std::ffi::{c_char, c_void}; -use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL, E_INVALIDARG}; +use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL}; use super::xgameruntime::{ Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, }; @@ -20,7 +20,7 @@ pub const PROVIDER: Guid = Guid::new( 0x448c, [0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c], ); -/// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes +/// As the title (2026) asks for it; every slot it calls takes /// the public API's arguments in the 2020 order. pub const IID_2026: Guid = Guid::new( 0xb09d_803c, @@ -301,8 +301,7 @@ extern "system" fn install_async( } /// The game's own store id maps to its installation; nothing else is -/// installed, and any other id gets the documented E_INVALIDARG (not -/// XPackage's "could not resolve" error). +/// installed. extern "system" fn package_identifier( _: This, store_id: *const c_char, @@ -314,7 +313,7 @@ extern "system" fn package_identifier( Some(id) if !title.store_id.is_empty() && id == title.store_id => { put_string(&xpackage::identifier(), size, buffer, std::ptr::null_mut()) } - _ => E_INVALIDARG, + _ => xpackage::NO_PACKAGE, } } @@ -333,7 +332,7 @@ extern "system" fn unregister(_: This, _: Handle, _token: u64, _wait: bool) -> b true } -static VTABLE: Methods<77> = Methods([ +static VTABLE: Methods<76> = Methods([ missing::<0> as *const (), add_ref as *const (), add_ref as *const (), @@ -368,9 +367,9 @@ static VTABLE: Methods<77> = Methods([ missing::<31> as *const (), // 0xf8 missing::<32> as *const (), // 0x100 consumable_balance_async as *const (), // 0x108 - count_status as *const (), // 0x110 + status as *const (), // 0x110 report_fulfillment_async as *const (), // 0x118 - count_status as *const (), // 0x120 + missing::<36> as *const (), // 0x120 user_id_async as *const (), // 0x128 collections id size_status as *const (), // 0x130 string_status as *const (), // 0x138 @@ -384,11 +383,11 @@ static VTABLE: Methods<77> = Methods([ missing::<47> as *const (), // 0x178 missing::<48> as *const (), // 0x180 purchase_ui_async as *const (), // 0x188 - status as *const (), // 0x190 + missing::<50> as *const (), // 0x190 missing::<51> as *const (), // 0x198 rate and review missing::<52> as *const (), // 0x1a0 redeem_ui_async as *const (), // 0x1a8 - status as *const (), // 0x1b0 + missing::<54> as *const (), // 0x1b0 updates_async as *const (), // 0x1b8 count_status as *const (), // 0x1c0 array_status as *const (), // 0x1c8 @@ -410,7 +409,6 @@ static VTABLE: Methods<77> = Methods([ missing::<73> as *const (), // 0x248 associated products page missing::<74> as *const (), // 0x250 product_page_ui_async as *const (), // 0x258 - status as *const (), // 0x260 ]); #[cfg(test)] @@ -427,133 +425,6 @@ mod tests { } } - #[test] - fn offline_async_calls_report_network_error_from_their_result_slots() { - assert!(VTABLE.0.len() > 0x260 / 8); - - let this: This = &OBJECT; - type StoreIdAsync = - extern "system" fn(This, Handle, *const c_char, *mut AsyncBlock) -> HRESULT; - type ReportFulfillmentAsync = extern "system" fn( - This, - Handle, - *const c_char, - u32, - *const c_void, - *mut AsyncBlock, - ) -> HRESULT; - type PurchaseUiAsync = extern "system" fn( - This, - Handle, - *const c_char, - *const c_char, - *const c_char, - *mut AsyncBlock, - ) -> HRESULT; - type RedeemUiAsync = extern "system" fn( - This, - Handle, - *const c_char, - *const *const c_char, - usize, - bool, - *mut AsyncBlock, - ) -> HRESULT; - type StatusResult = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; - type CountResult = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; - - let mut b = block(); - assert_eq!( - method::<StoreIdAsync>(&OBJECT, 0x258)( - this, - handle(&CONTEXT), - c"9DUMMY".as_ptr(), - &mut b, - ), - S_OK - ); - assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); - assert_eq!( - method::<StatusResult>(&OBJECT, 0x260)(this, &mut b), - NETWORK_ERROR - ); - - let mut b = block(); - let mut remaining = 7u32; - assert_eq!( - method::<ReportFulfillmentAsync>(&OBJECT, 0x118)( - this, - handle(&CONTEXT), - c"9DUMMY".as_ptr(), - 1, - std::ptr::null(), - &mut b, - ), - S_OK - ); - assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); - assert_eq!( - method::<CountResult>(&OBJECT, 0x120)(this, &mut b, &mut remaining), - NETWORK_ERROR - ); - assert_eq!(remaining, 7); - - let mut b = block(); - assert_eq!( - method::<PurchaseUiAsync>(&OBJECT, 0x188)( - this, - handle(&CONTEXT), - c"9DUMMY".as_ptr(), - std::ptr::null(), - std::ptr::null(), - &mut b, - ), - S_OK - ); - assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); - assert_eq!( - method::<StatusResult>(&OBJECT, 0x190)(this, &mut b), - NETWORK_ERROR - ); - - let mut b = block(); - assert_eq!( - method::<RedeemUiAsync>(&OBJECT, 0x1a8)( - this, - handle(&CONTEXT), - c"DUMMY-TOKEN".as_ptr(), - std::ptr::null(), - 0, - false, - &mut b, - ), - S_OK - ); - assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); - assert_eq!( - method::<StatusResult>(&OBJECT, 0x1b0)(this, &mut b), - NETWORK_ERROR - ); - - let mut b = block(); - let mut balance = 3u32; - assert_eq!( - method::<StoreIdAsync>(&OBJECT, 0x108)( - this, - handle(&CONTEXT), - c"9DUMMY".as_ptr(), - &mut b, - ), - S_OK - ); - assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); - assert_eq!( - method::<CountResult>(&OBJECT, 0x110)(this, &mut b, &mut balance), - NETWORK_ERROR - ); - assert_eq!(balance, 3); - } - #[test] fn the_game_is_licensed_and_the_store_is_offline() { let this: This = &OBJECT; @@ -605,15 +476,4 @@ mod tests { &OBJECT, 0xb0 )(this, l)); } - - #[test] - fn a_store_id_without_a_package_is_an_invalid_argument() { - type Query = extern "system" fn(This, *const c_char, usize, *mut u8) -> HRESULT; - let query = method::<Query>(&OBJECT, 0x208); - let mut id = [0u8; 33]; - assert_eq!( - query(&OBJECT, c"9NOTINSTALLED".as_ptr(), 33, id.as_mut_ptr()), - E_INVALIDARG - ); - } } diff --git a/crates/victory-hle/src/modules/xsystem.rs b/crates/victory-hle/src/modules/xsystem.rs index f94d546146..2adeb5a94b 100644 --- a/crates/victory-hle/src/modules/xsystem.rs +++ b/crates/victory-hle/src/modules/xsystem.rs @@ -45,7 +45,7 @@ const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE="; pub static OBJECT: Object = Object::new("system", &VTABLE); pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE); -/// The interface as Grand Theft Auto VI (2026) asks for it; it calls the +/// The interface as the title (2026) asks for it; it calls the /// same three slots (0x18, 0x20, 0x28) with the same arguments. pub const IID_2026: Guid = Guid::new( 0x1861_cf2e, @@ -110,9 +110,6 @@ fn text(s: &str) -> [u8; 64] { /// A struct this large comes back through the caller's buffer, whose /// address is also the return value. extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut AnalyticsInfo { - if out.is_null() { - return std::ptr::null_mut(); - } let info = AnalyticsInfo { os: OS, hosting_os: OS, @@ -190,20 +187,11 @@ mod device_type { text.eq_ignore_ascii_case(expected) } - /// Opens our key for its path; the key has no subkeys, and a null or - /// empty path below it opens the key itself, as the host's do. `None`: - /// not ours, ask the host. + /// Opens our key for its path; the key has no subkeys. `None`: not + /// ours, ask the host. fn open(root: Key, sub: *const u16, out: *mut Key) -> Option<u32> { if root == oem() { - if !(sub.is_null() || is(sub, "")) { - return Some(FILE_NOT_FOUND); - } - if out.is_null() { - return Some(INVALID_PARAMETER); - } - // SAFETY: checked non-null; the title passes room for a key. - unsafe { out.write(oem()) }; - return Some(SUCCESS); + return Some(FILE_NOT_FOUND); } if root == LOCAL_MACHINE && is(sub, KEY) && !out.is_null() { // SAFETY: checked non-null; the title passes room for a key. @@ -358,34 +346,6 @@ mod device_type { assert_eq!(again, oem()); } - #[test] - fn a_null_or_empty_path_opens_the_key_itself() { - const KEY_READ: u32 = 0x2_0019; - let empty = w(""); - let host_key = w(r"Software\Microsoft\Windows NT\CurrentVersion"); - for (root, path) in [(oem(), w(KEY)), (std::ptr::null_mut(), host_key)] { - // Ours, then the host's for comparison. - let mut key = std::ptr::null_mut(); - assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS); - assert!(root.is_null() || key == root); - for sub in [std::ptr::null(), empty.as_ptr()] { - // `RegOpenKeyW` gives back the key it was passed. - let mut same = std::ptr::null_mut(); - assert_eq!(RegOpenKeyW(key, sub, &mut same), SUCCESS, "{sub:?}"); - assert_eq!(same, key); - // `RegOpenKeyExW` a handle to the same key. - let mut again = std::ptr::null_mut(); - assert_eq!( - RegOpenKeyExW(key, sub, 0, KEY_READ, &mut again), - SUCCESS, - "{sub:?}" - ); - assert_eq!(RegCloseKey(again), SUCCESS); - } - assert_eq!(RegCloseKey(key), SUCCESS); - } - } - #[test] fn other_keys_reach_the_host() { let mut key = std::ptr::null_mut(); @@ -461,8 +421,5 @@ mod tests { assert_eq!(size_of::<AnalyticsInfo>(), 0x90); assert_eq!(info.os.build, 22000); assert_eq!(&info.form[..14], b"Xbox Series X\0"); - - // A null output is refused rather than written through. - assert!(get(&ANALYTICS_OBJECT, std::ptr::null_mut()).is_null()); } } diff --git a/crates/victory-hle/src/modules/xuser.rs b/crates/victory-hle/src/modules/xuser.rs index dafcfba771..226d4248c8 100644 --- a/crates/victory-hle/src/modules/xuser.rs +++ b/crates/victory-hle/src/modules/xuser.rs @@ -81,7 +81,7 @@ pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE); pub const INTERFACES: &[Interface] = &[ (PROVIDER, IID, &OBJECT), - // Grand Theft Auto VI (2026) asks with the provider's id; its thunks call + // The title (2026) asks with the provider's id; its thunks call // the same slots with the same arguments (0x108/0x110 change events). (PROVIDER, PROVIDER, &OBJECT), (PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT), diff --git a/crates/victory-hle/src/registry.rs b/crates/victory-hle/src/registry.rs index d229e7b1d8..e8744b48e7 100644 --- a/crates/victory-hle/src/registry.rs +++ b/crates/victory-hle/src/registry.rs @@ -1,7 +1,5 @@ //! The table of everything we implement. -use std::collections::HashMap; -use std::hash::{BuildHasherDefault, Hasher}; use std::sync::LazyLock; use crate::modules; @@ -55,101 +53,19 @@ pub fn registry() -> &'static [HleModule] { ®ISTRY } -/// FNV-1a: the keys are short export names built into the binary, so the -/// default hasher's resistance to chosen keys buys nothing here, and FNV -/// hashes them in a fraction of its time. -#[derive(Clone, Copy)] -struct Fnv(u64); - -impl Default for Fnv { - fn default() -> Self { - Fnv(0xCBF2_9CE4_8422_2325) - } -} - -impl Hasher for Fnv { - fn write(&mut self, bytes: &[u8]) { - for &b in bytes { - self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x100_0000_01B3); - } - } - - fn finish(&self) -> u64 { - self.0 - } -} - -type Map<V> = HashMap<&'static str, V, BuildHasherDefault<Fnv>>; - -/// Whether `pattern` (lower case, a trailing `*` matching a prefix) names -/// `dll` in any case, as [`HleModule::serves`] decides it. -fn matches(pattern: &str, dll: &str) -> bool { - match pattern.strip_suffix('*') { - Some(prefix) => dll - .as_bytes() - .get(..prefix.len()) - .is_some_and(|start| start.eq_ignore_ascii_case(prefix.as_bytes())), - None => dll.eq_ignore_ascii_case(pattern), - } -} - -/// The registry's exports by name, for [`lookup`]. -struct Index { - modules: &'static [HleModule], - /// Export name to (module, address) in registry order: the first export - /// of the name in each module that has one, as a scan finds it. - exports: Map<Vec<(usize, usize)>>, -} - -impl Index { - fn new(modules: &'static [HleModule]) -> Index { - let mut exports = Map::<Vec<(usize, usize)>>::default(); - for (i, m) in modules.iter().enumerate() { - for e in &m.exports { - let owners = exports.entry(e.name).or_default(); - if owners.last().is_none_or(|&(m, _)| m != i) { - owners.push((i, e.address)); - } - } - } - Index { modules, exports } - } - - /// The address of `name` in the first module, in registry order, that - /// serves `dll` and exports it. Only the modules exporting `name` (one, - /// nearly always) test their DLL patterns. - fn find(&self, dll: &str, name: &str) -> Option<usize> { - self.exports - .get(name)? - .iter() - .find(|&&(m, _)| self.modules[m].dlls.iter().any(|p| matches(p, dll))) - .map(|&(_, address)| address) - } -} - -static INDEX: LazyLock<Index> = LazyLock::new(|| Index::new(registry())); - -/// The address we bind `dll!name` to (`#n` for an ordinal), if a module -/// serving `dll` implements it. Called once per title import at load and on -/// every `GetProcAddress` of a host module. pub(crate) fn lookup(dll: &str, name: &str) -> Option<usize> { - INDEX.find(dll, name) + registry() + .iter() + .filter(|m| m.serves(dll)) + .flat_map(|m| m.exports.iter()) + .find(|e| e.name == name) + .map(|e| e.address) } #[cfg(test)] mod tests { use super::*; - /// [`lookup`] as it was: walking every module and export. - fn scan(modules: &[HleModule], dll: &str, name: &str) -> Option<usize> { - modules - .iter() - .filter(|m| m.serves(dll)) - .flat_map(|m| m.exports.iter()) - .find(|e| e.name == name) - .map(|e| e.address) - } - #[test] fn export_names_are_unique_per_dll_pattern() { for module in registry() { @@ -166,236 +82,6 @@ mod tests { } } - /// DLL names that reach every pattern of `modules`: exact names as - /// written and upper-cased, prefixes with a version suffix, and names no - /// module serves. - fn dll_names(modules: &[HleModule]) -> Vec<String> { - let mut names = vec![ - "nothing.dll".to_owned(), - "api-ms-win-core-unserved-l1-1-0.dll".to_owned(), - String::new(), - "x".repeat(200), - ]; - for m in modules { - for pattern in m.dlls { - let name = match pattern.strip_suffix('*') { - Some(prefix) => format!("{prefix}l1-2-0.dll"), - None => (*pattern).to_owned(), - }; - names.push(name.to_ascii_uppercase()); - names.push(name); - } - } - names - } - - fn export_names(modules: &[HleModule]) -> Vec<&'static str> { - let mut names: Vec<_> = modules - .iter() - .flat_map(|m| m.exports.iter().map(|e| e.name)) - .collect(); - names.extend(["NotExported", "#999", ""]); - names - } - - fn agrees_with_scan(modules: &'static [HleModule]) -> usize { - let index = Index::new(modules); - let mut checked = 0; - for dll in dll_names(modules) { - for name in export_names(modules) { - assert_eq!( - index.find(&dll, name), - scan(modules, &dll, name), - "{dll}!{name}" - ); - checked += 1; - } - } - checked - } - - #[test] - fn index_agrees_with_a_scan_on_the_registry() { - assert!(agrees_with_scan(registry()) > 1000); - let ours = lookup("XGameRuntime.dll", "XGameRuntimeInitialize"); - assert!(ours.is_some()); - assert_eq!( - ours, - scan(registry(), "XGameRuntime.dll", "XGameRuntimeInitialize") - ); - } - - fn export(name: &'static str, address: usize) -> HleExport { - HleExport { name, address } - } - - /// Overlapping exact and prefix patterns, a name two modules export and - /// a name one module exports twice. - fn overlapping() -> &'static [HleModule] { - Box::leak(Box::new([ - HleModule { - name: "files", - dlls: &["kernel32.dll", "api-ms-win-core-file-*"], - exports: vec![ - export("CreateFileW", 1), - export("ReadFile", 2), - export("ReadFile", 3), - ], - }, - HleModule { - name: "kernel", - dlls: &["kernel32.dll", "api-ms-win-core-*"], - exports: vec![export("CreateFileW", 4), export("Sleep", 5)], - }, - HleModule { - name: "empty", - dlls: &[], - exports: vec![export("Sleep", 6)], - }, - HleModule { - name: "late", - dlls: &["api-ms-win-core-file-l1-2-0.dll"], - exports: vec![export("GetFileType", 7), export("Sleep", 8)], - }, - ])) - } - - #[test] - fn the_first_serving_module_and_first_export_win() { - let modules = overlapping(); - assert!(agrees_with_scan(modules) > 0); - let index = Index::new(modules); - let find = |dll: &str, name| index.find(dll, name); - assert_eq!(find("KERNEL32.DLL", "CreateFileW"), Some(1)); - assert_eq!(find("kernel32.dll", "ReadFile"), Some(2)); - assert_eq!(find("kernel32.dll", "Sleep"), Some(5)); - assert_eq!(find("api-ms-win-core-file-l1-2-0.dll", "Sleep"), Some(5)); - assert_eq!( - find("api-ms-win-core-file-l1-2-0.dll", "GetFileType"), - Some(7) - ); - assert_eq!(find("api-ms-win-core-file-l1-1-0.dll", "GetFileType"), None); - assert_eq!( - find("api-ms-win-core-synch-l1-1-0.dll", "CreateFileW"), - Some(4) - ); - assert_eq!(find("api-ms-win-core-", "Sleep"), Some(5)); - assert_eq!(find("kernel32", "Sleep"), None); - } - - #[test] - fn patterns_match_in_any_case_as_serves_does() { - let patterns = ["kernel32.dll", "api-ms-win-core-file-*", "", "*"]; - let dlls = [ - "KERNEL32.DLL", - "kernel32.dll", - "kernel32", - "kernel32.dll2", - "Api-MS-Win-Core-File-L1-2-0.dll", - "api-ms-win-core-file-", - "api-ms-win-core-fil", - "KÉRNEL32.DLL", - "", - ]; - for pattern in patterns { - let m = HleModule { - name: "t", - dlls: Box::leak(Box::new([pattern])), - exports: vec![], - }; - for dll in dlls { - assert_eq!(matches(pattern, dll), m.serves(dll), "{pattern} {dll}"); - } - } - } - - #[test] - fn registry_patterns_are_lower_case() { - for m in registry() { - for pattern in m.dlls { - assert_eq!(*pattern, pattern.to_ascii_lowercase(), "module {}", m.name); - } - } - } - - #[test] - fn many_modules_exporting_one_name_keep_registry_order() { - let many: &'static [HleModule] = Box::leak( - (0..300) - .map(|i| HleModule { - name: "m", - dlls: if i % 2 == 0 { - &["even.dll"] - } else { - &["odd.dll", "many.dll"] - }, - exports: vec![export("F", i)], - }) - .collect::<Vec<_>>() - .into_boxed_slice(), - ); - let index = Index::new(many); - for (dll, first) in [ - ("EVEN.dll", Some(0)), - ("odd.DLL", Some(1)), - ("many.dll", Some(1)), - ("none.dll", None), - ] { - assert_eq!(index.find(dll, "F"), first); - assert_eq!(scan(many, dll, "F"), first); - } - } - - /// Import binding throughput: every registry export looked up under - /// each DLL name that serves it, as a title's import table does, plus - /// a miss per DLL that falls through to the host. Run with - /// `cargo test --release -p victory-hle registry_lookup_throughput -- --ignored --nocapture`. - #[test] - #[ignore = "benchmark"] - fn registry_lookup_throughput() { - let modules = registry(); - let mut imports = Vec::new(); - for m in modules { - for pattern in m.dlls { - let dll = match pattern.strip_suffix('*') { - Some(prefix) => format!("{}L1-1-0.dll", prefix.to_ascii_uppercase()), - None => pattern.to_ascii_uppercase(), - }; - for e in &m.exports { - imports.push((dll.clone(), e.name.to_owned())); - } - imports.push((dll.clone(), "HostOnlyFunction".to_owned())); - } - } - let _ = lookup("warm.dll", "up"); - let rounds = 200; - let time = |f: &dyn Fn(&str, &str) -> Option<usize>| { - let mut best = f64::MAX; - let mut sum = 0usize; - for _ in 0..5 { - let started = std::time::Instant::now(); - for _ in 0..rounds { - for (dll, name) in &imports { - let found = std::hint::black_box(f(dll, name)); - sum = sum.wrapping_add(found.unwrap_or(1)); - } - } - let ns = started.elapsed().as_nanos() as f64 / (rounds * imports.len()) as f64; - best = best.min(ns); - } - (best, sum) - }; - let (before, a) = time(&|dll, name| scan(modules, dll, name)); - let (after, b) = time(&|dll, name| lookup(dll, name)); - assert_eq!(a, b); - println!( - "{} modules, {} imports: scan {before:.0} ns, index {after:.0} ns per import ({:.1}x)", - modules.len(), - imports.len(), - before / after - ); - } - #[test] fn api_set_prefix_matching() { let m = HleModule { diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index 87055c4b23..a2813a68c4 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -71,6 +71,35 @@ pub fn load_title_dll(file: &str) -> Result<Option<usize>, String> { TITLE_DLL_LOADER.get().map_or(Ok(None), |load| load(file)) } +static TITLE_DLL_SETTLE: std::sync::OnceLock<Box<dyn Fn() + Send + Sync>> = std::sync::OnceLock::new(); + +/// Set once, by whoever maps the title's DLLs: waits until no thread is +/// mapping, binding or initialising one (the loader lock's shape). +pub fn set_title_dll_settle(settle: Box<dyn Fn() + Send + Sync>) { + let _ = TITLE_DLL_SETTLE.set(settle); +} + +/// Waits for a title DLL mapping in progress on another thread (Try 6.7: +/// a `GetModuleHandle` racing the title's load of its upscaler was refused +/// as a host DLL). +pub fn settle_title_dlls() { + if let Some(settle) = TITLE_DLL_SETTLE.get() { + settle(); + } +} + +/// The file names of the title images whose names start as `file`'s does, +/// for the log of a refused name. +pub fn images_like(file: &str) -> Vec<String> { + let stem: String = file.chars().take(8).collect::<String>().to_ascii_lowercase(); + let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths + .iter() + .filter_map(|(_, p)| p.file_name()?.to_str().map(str::to_owned)) + .filter(|n| n.to_ascii_lowercase().starts_with(&stem)) + .collect() +} + /// What the title's manifest (`MicrosoftGame.config` beside its executable) /// says about it, and where its persistent local storage lives. #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -96,13 +125,12 @@ impl Title { .map(|(_, text)| text.as_str()) }; let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok()); - let storage_mb = - get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse::<u64>().ok()); + let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok()); Title { id: id.unwrap_or(0), store_id: get("Game/StoreId").unwrap_or_default().to_owned(), storage: PathBuf::new(), - storage_bytes: storage_mb.unwrap_or(0).saturating_mul(1024 * 1024), + storage_bytes: storage_mb.unwrap_or(0) << 20, } } @@ -128,7 +156,7 @@ fn elements(text: &str) -> Vec<(String, String)> { } else if rest.starts_with("<![CDATA[") { rest.find("]]>").map(|e| e + 3) } else { - tag_end(rest) + rest.find('>').map(|e| e + 1) }; let Some(end) = end else { break }; let tag = &rest[1..end - 1]; @@ -150,15 +178,9 @@ fn elements(text: &str) -> Vec<(String, String)> { .unwrap_or(""); path.push(name); let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); - let body = [ - ("<", "<"), - (">", ">"), - (""", "\""), - ("'", "'"), - ("&", "&"), - ] - .iter() - .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); + let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] + .iter() + .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); out.push((path.join("/"), body)); if closed { path.pop(); @@ -167,21 +189,6 @@ fn elements(text: &str) -> Vec<(String, String)> { out } -/// Where the tag that starts `text` ends, past its `>`; a `>` in a quoted -/// attribute value is part of the value (XML allows it there unescaped). -fn tag_end(text: &str) -> Option<usize> { - let mut quote = None; - for (at, c) in text.char_indices() { - match (quote, c) { - (None, '"' | '\'') => quote = Some(c), - (Some(open), _) if c == open => quote = None, - (None, '>') => return Some(at + 1), - _ => {} - } - } - None -} - static TITLE: Mutex<Option<Title>> = Mutex::new(None); pub fn set_title(title: Title) { @@ -198,7 +205,7 @@ pub fn title() -> Title { } /// Gives the process the console's millisecond timers. Titles pace -/// themselves with short waits (Grand Theft Auto VI's audio mixer sleeps +/// themselves with short waits (the title's audio mixer sleeps /// about 4 ms per 5.3 ms block) and cannot tune the timer on the console; /// a desktop process waits in 15.6 ms ticks unless it asks for finer ones, /// and Windows 11 drops that request while the window is hidden unless the @@ -207,13 +214,23 @@ pub fn title() -> Title { pub fn use_console_timers() { use windows_sys::Win32::Media::timeBeginPeriod; use windows_sys::Win32::System::Threading::{ - GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, + GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, PROCESS_POWER_THROTTLING_EXECUTION_SPEED, PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, ProcessPowerThrottling, SetProcessInformation, }; + // Also: the system does not run this process at reduced speed (its + // "efficiency mode": lower clock, the slow cores of a hybrid processor) + // when its window is not the one in front, as while its owner works in + // another window or streams. The console has eight cores alike and no + // such mode. `VICTORY_EFFICIENCY_MODE=1` leaves the system its choice. + let execution = if std::env::var_os("VICTORY_EFFICIENCY_MODE").is_some_and(|v| v == "1") { + 0 + } else { + PROCESS_POWER_THROTTLING_EXECUTION_SPEED + }; let keep = PROCESS_POWER_THROTTLING_STATE { Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, - ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION | execution, StateMask: 0, }; // SAFETY: plain process settings; `keep` outlives the call. @@ -226,21 +243,90 @@ pub fn use_console_timers() { ); timeBeginPeriod(1); } + use_whole_machine(); +} + +#[cfg(windows)] +fn whole_machine() -> bool { + std::env::var_os("VICTORY_WHOLE_MACHINE").is_none_or(|v| v != "0") +} + +/// Try 6.0: asks Windows for the whole machine while the title runs. +/// `VICTORY_WHOLE_MACHINE=0`: none of it. +/// +/// - The process runs above normal priority: the title's threads and ours +/// come before the browser, the launcher and updaters on a busy CPU. +/// - Windows is told not to throttle its execution speed (no EcoQoS): on +/// CPUs with performance and efficiency cores (Intel 12th generation and +/// later) a thread Windows judges to be in the background is put on the +/// slow cores, and our helper threads that wait a lot looked like that. +/// - A soft minimum working set of a quarter of the PC's memory (at most +/// 4 GiB): on a PC whose memory is nearly all in use (under 1 GB free in +/// the 2026-11-26 report) Windows takes pages away from the biggest +/// process first, and the title's memory then came back from the page +/// file a page at a time. Soft: Windows still takes them if it must. +#[cfg(windows)] +fn use_whole_machine() { + use windows_sys::Win32::System::Memory::{ + QUOTA_LIMITS_HARDWS_MAX_DISABLE, QUOTA_LIMITS_HARDWS_MIN_DISABLE, SetProcessWorkingSetSizeEx, + }; + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + use windows_sys::Win32::System::Threading::{ + ABOVE_NORMAL_PRIORITY_CLASS, GetCurrentProcess, HIGH_PRIORITY_CLASS, SetPriorityClass, + }; + if !whole_machine() { + return; + } + // Try 6.12 (all-out mode): `VICTORY_PRIORITY=high` runs the process at + // high priority (never realtime: the mouse, the keyboard and the driver + // still come first), and `VICTORY_WORKING_SET_PERCENT` sets the soft + // minimum working set as a share of the PC's memory (1 to 95, no 4 GiB + // cap) instead of a quarter. + let high = std::env::var("VICTORY_PRIORITY").is_ok_and(|v| v.trim().eq_ignore_ascii_case("high")); + let percent = std::env::var("VICTORY_WORKING_SET_PERCENT") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .map(|p| p.clamp(1, 95)); + // SAFETY: plain process settings and a query that fills our structure. + unsafe { + let process = GetCurrentProcess(); + let class = if high { HIGH_PRIORITY_CLASS } else { ABOVE_NORMAL_PRIORITY_CLASS }; + let priority = SetPriorityClass(process, class) != 0; + let mut status: MEMORYSTATUSEX = std::mem::zeroed(); + status.dwLength = size_of_val(&status) as u32; + let mut kept_mb = 0; + if GlobalMemoryStatusEx(&mut status) != 0 { + let min = match percent { + Some(p) => (status.ullTotalPhys / 100 * p) as usize, + None => (status.ullTotalPhys / 4).min(4 << 30) as usize, + }; + // The maximum only has to be above the minimum: it is not enforced. + let max = min.saturating_mul(4); + if SetProcessWorkingSetSizeEx( + process, + min, + max, + QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_DISABLE, + ) != 0 + { + kept_mb = min >> 20; + } + } + tracing::info!( + above_normal = priority && !high, + high = priority && high, + soft_min_working_set_mb = kept_mb, + pc_memory_mb = status.ullTotalPhys >> 20, + pc_memory_free_mb = status.ullAvailPhys >> 20, + "the whole machine for the title (VICTORY_WHOLE_MACHINE=0: none of it)" + ); + } } #[cfg(test)] mod tests { use super::*; - #[test] - fn a_quoted_angle_bracket_does_not_end_its_tag() { - let text = "<Game><ShellVisuals DefaultDisplayName=\"A > B\" Description='x>y'/>\ - <TitleId>639AA8DD</TitleId>\ - <PersistentLocalStorage><SizeMB>64</SizeMB></PersistentLocalStorage></Game>"; - let t = Title::from_manifest(text); - assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 64 << 20)); - } - #[test] fn reads_title_id_store_id_and_storage_quota() { let text = "\u{feff}<?xml version=\"1.0\"?>\n<Game configVersion=\"1\">\ @@ -254,23 +340,4 @@ mod tests { assert_eq!(t.store_id, "9&C"); assert_eq!(Title::from_manifest("").storage_bytes, 0); } - - #[test] - fn storage_quota_saturates_when_megabytes_exceed_u64_bytes() { - let max_mb = u64::MAX / (1024 * 1024); - - let at_limit = format!( - "<Game><PersistentLocalStorage><SizeMB>{max_mb}</SizeMB></PersistentLocalStorage></Game>" - ); - assert_eq!( - Title::from_manifest(&at_limit).storage_bytes, - max_mb * 1024 * 1024 - ); - - let above_limit = format!( - "<Game><PersistentLocalStorage><SizeMB>{}</SizeMB></PersistentLocalStorage></Game>", - max_mb + 1 - ); - assert_eq!(Title::from_manifest(&above_limit).storage_bytes, u64::MAX); - } } diff --git a/crates/victory-loader/Cargo.toml b/crates/victory-loader/Cargo.toml index 6f2ade66cb..0f3497b00e 100644 --- a/crates/victory-loader/Cargo.toml +++ b/crates/victory-loader/Cargo.toml @@ -17,7 +17,6 @@ blake3.workspace = true [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = [ - "Wdk_System_SystemServices", "Wdk_System_Threading", "Win32_Foundation", "Win32_System_Diagnostics_Debug", @@ -25,7 +24,7 @@ windows-sys = { workspace = true, features = [ "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", - "Win32_System_SystemInformation", + "Win32_System_Performance", "Win32_System_Threading", ] } diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs new file mode 100644 index 0000000000..a110f45d03 --- /dev/null +++ b/crates/victory-loader/src/console_insn.rs @@ -0,0 +1,781 @@ +//! Instructions the console's CPU (Zen 2) has and an Intel PC's lacks, emulated: the title's +//! code raises STATUS_ILLEGAL_INSTRUCTION on them (the title zeroes memory with a `clzero` loop at +//! its first frames), and the vectored handler steps over them here. +//! +//! Ported from XCL (github.com/ivall/xcl, GPL-2.0-only): `insn.rs` (decoder, as +//! `console_insn_decode.rs`, unchanged) and `eh.rs` `emulate_console_only`. + +#[path = "console_insn_decode.rs"] +mod decode; + +use decode::ConsoleOnly; +use std::cell::Cell; +use std::sync::atomic::{AtomicU64, Ordering, Ordering::Relaxed}; +use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; + +const CONTINUE_EXECUTION: i32 = -1; + +/// Whether what Windows said about memory is remembered per thread (the regions it found +/// writable, the code bytes it found readable) and not asked again at every emulated +/// instruction. A query walks the pages of the region it answers for: asked from outside, it +/// took 2-9 ms in the title's heaps of 0.6-2.2 GB and 89 ms in its 6.2 GB page pool (run 30), +/// and the title zeroes blocks of them with `clzero` loops all through a frame: six of its +/// threads spent 25-78 % of their time inside that query (runs 29 and 30), about 27 s of +/// processor time in Windows per 9 s frame. On by default; `VICTORY_CLZERO_ASK=1` asks every +/// time, as before. +fn remembers() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CLZERO_ASK").is_none_or(|v| v != "1")) +} + +/// Answers a remembered region gives before Windows is asked about it again: one freed or +/// protected meanwhile is forgotten then. +const ANSWERS: u32 = 4096; + +thread_local! { + /// The regions Windows last said are committed and writable (start, end), newest first, + /// and the answers they gave since they were emptied. + static WRITABLE: Cell<([(usize, usize); 4], u32)> = const { Cell::new(([(0, 0); 4], 0)) }; + /// Faulting addresses and the code bytes found readable there, newest first. + static CODE: Cell<[(usize, usize); 8]> = const { Cell::new([(0, 0); 8]) }; +} + +/// Instructions emulated, the times Windows was asked about memory for them, and the bytes +/// `clzero` loops zeroed, since the start. +static EMULATED: AtomicU64 = AtomicU64::new(0); +static ASKED: AtomicU64 = AtomicU64::new(0); +static ZEROED: AtomicU64 = AtomicU64::new(0); + +/// Exceptions taken by kind since the last line: a lone `clzero`, the 12-byte loop, the +/// 15-byte loop taken whole, `monitorx`, `mwaitx`, everything else; and the 64-byte lines the +/// 15-byte loops zeroed (each was an exception of its own before they were taken whole). +static KINDS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; +const K_CLZERO: usize = 0; +const K_LOOP12: usize = 1; +const K_LOOP15: usize = 2; +const K_MONITORX: usize = 3; +const K_MWAITX: usize = 4; +const K_OTHER: usize = 5; +const K_LOOP15_LINES: usize = 6; + +/// Waits the title made with `monitorx` / `mwaitx` (it waits for a fence that way, reading +/// the fence's value in memory: its +0x4fb0ad0) that have ended since the last line: how +/// many, their microseconds, and both again for those of 1 ms and more, 5 ms and more, +/// 20 ms and more. +static WAITS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; +/// Waits said in the log one by one. +static WAITS_SAID: AtomicU64 = AtomicU64::new(0); +/// When the last line was written, in milliseconds of [`clock_us`]. +static LINE_AT: AtomicU64 = AtomicU64::new(0); + +thread_local! { + /// The address and the value this thread last armed a monitor for (`monitorx`: rax, and + /// the title's wanted value in rsi). + static MONITOR: Cell<(usize, u64)> = const { Cell::new((0, 0)) }; + /// This thread's wait under way: when it began and when its last `mwaitx` was, in + /// microseconds, what it waits for, and its `mwaitx` count. + static WAIT: Cell<(u64, u64, usize, u64, u32)> = const { Cell::new((0, 0, 0, 0, 0)) }; +} + +/// Microseconds on the performance counter. +fn clock_us() -> u64 { + static PER_SECOND: std::sync::OnceLock<i64> = std::sync::OnceLock::new(); + let per_second = *PER_SECOND.get_or_init(|| { + let mut f = 0i64; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceFrequency(&mut f) }; + f.max(1) + }); + let mut now = 0i64; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut now) }; + (now as u128 * 1_000_000 / per_second as u128) as u64 +} + +/// Whether events are said one by one now: four seconds of every two minutes of the wall +/// clock, the same seconds in which the fence meter of the graphics side says its own +/// (`victory_gpu::fence::pace`), so that the two can be laid side by side. +fn detail_now() -> bool { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).is_ok_and(|d| d.as_secs() % 120 < 4) +} + +/// Whether the 15-byte `clzero` loop is taken whole (`VICTORY_CLZERO_LOOP15=0`: line by +/// line, as before). +fn loop15() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CLZERO_LOOP15").is_none_or(|v| v != "0")) +} + +/// A wait of this thread has ended: counted, and said if it is one to say. +fn wait_ended(begin: u64, last: u64, address: usize, wanted: u64, spins: u32) { + let us = last.saturating_sub(begin); + for (i, least) in [0u64, 1_000, 5_000, 20_000].into_iter().enumerate() { + if us >= least { + WAITS[2 * i].fetch_add(1, Relaxed); + WAITS[2 * i + 1].fetch_add(us, Relaxed); + } + } + if us >= 500 && (detail_now() || WAITS_SAID.fetch_add(1, Relaxed) < 40) { + // SAFETY: no preconditions. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + tracing::info!( + "mwait: thread {thread} waited {:.1} ms for the value at {address:#x} to reach {wanted} ({spins} mwaitx)", + us as f64 / 1e3 + ); + } +} + +/// A `mwaitx` of this thread: part of the wait under way, or the first of a new one. +fn wait_step() { + let now = clock_us(); + let (address, wanted) = MONITOR.with(Cell::get); + let (begin, last, was_at, was_for, spins) = WAIT.with(Cell::get); + if begin != 0 && was_at == address && was_for == wanted && now.saturating_sub(last) < 2_000 { + WAIT.with(|w| w.set((begin, now, address, wanted, spins + 1))); + return; + } + if begin != 0 { + wait_ended(begin, last, was_at, was_for, spins); + } + WAIT.with(|w| w.set((now, now, address, wanted, 1))); +} + +/// A line every five seconds: exceptions a second by kind, and the waits that ended. +fn line() { + let now = clock_us() / 1000; + let last = LINE_AT.load(Relaxed); + if now < last + 5_000 || LINE_AT.compare_exchange(last, now, Relaxed, Relaxed).is_err() { + return; + } + if last == 0 { + return; + } + let seconds = (now - last) as f64 / 1e3; + let k: Vec<f64> = KINDS.iter().map(|k| k.swap(0, Relaxed) as f64 / seconds).collect(); + let w: Vec<f64> = WAITS.iter().map(|w| w.swap(0, Relaxed) as f64).collect(); + tracing::info!( + "console CPU instructions, exceptions a second: clzero alone {:.0}, its 12-byte loop {:.0}, its 15-byte loop taken whole {:.0} ({:.0} lines a second, each an exception \ + before; VICTORY_CLZERO_LOOP15=0: again), monitorx {:.0}, mwaitx {:.0}, others {:.0} | mwaitx waits ended a second: {:.0}, {:.1} ms of thread time a second; of 1 ms and \ + more {:.1} ({:.1} ms), of 5 ms and more {:.1} ({:.1} ms), of 20 ms and more {:.1} ({:.1} ms)", + k[K_CLZERO], + k[K_LOOP12], + k[K_LOOP15], + k[K_LOOP15_LINES], + k[K_MONITORX], + k[K_MWAITX], + k[K_OTHER], + w[0] / seconds, + w[1] / seconds / 1e3, + w[2] / seconds, + w[3] / seconds / 1e3, + w[4] / seconds, + w[5] / seconds / 1e3, + w[6] / seconds, + w[7] / seconds / 1e3, + ); +} + +fn readable(va: usize, bytes: usize) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery}; + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0; + ASKED.fetch_add(1, Relaxed); + found && m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.BaseAddress as usize + m.RegionSize >= va + bytes +} + +fn writable(va: usize, bytes: usize) -> bool { + writable_to(va, va + bytes) == Some(va + bytes) +} + +/// Where the committed, writable memory that `va` lies in ends, at most `end`; None if `va` +/// is not in such memory. A region found is remembered ([`remembers`]). +/// shortcut: a remembered region that was freed or protected since is written all the same +/// for up to [`ANSWERS`] answers: the write then faults inside the handler, which the guard +/// on view memory opens as it does any write, and which is a crash otherwise (as the +/// unchecked single-line emulation behind this one already is). +fn writable_to(va: usize, end: usize) -> Option<usize> { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualQuery}; + let remember = remembers(); + if remember { + let (regions, answers) = WRITABLE.with(Cell::get); + if let Some(&(_, to)) = regions.iter().find(|&&(from, to)| from <= va && va < to) { + let next = if answers >= ANSWERS { ([(0, 0); 4], 0) } else { (regions, answers + 1) }; + WRITABLE.with(|w| w.set(next)); + return Some(to.min(end)); + } + } + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0; + ASKED.fetch_add(1, Relaxed); + if !found || m.State != MEM_COMMIT || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 { + return None; + } + let (from, to) = (m.BaseAddress as usize, m.BaseAddress as usize + m.RegionSize); + if remember { + WRITABLE.with(|w| { + let (mut regions, answers) = w.get(); + regions.rotate_right(1); + regions[0] = (from, to); + w.set((regions, answers)); + }); + } + Some(to.min(end)) +} + +/// Whether `monitorx` and `mwaitx` are patched where the title has them, so that they take no +/// exception again: `monitorx` becomes NOPs, `mwaitx` a `pause` (and NOPs). The title waits for +/// a fence with them, reading the fence's value again after each `mwaitx` (which may end at any +/// time on the console too), so the wait is the same spin without a trip into Windows and back +/// at every turn: about 125,000 exceptions a second in the 6.7 report (67 million in nine +/// minutes, most of them these two). The waits are no longer measured then. +/// `VICTORY_MWAIT_PATCH=0`: emulated at every turn, as before. +fn patches_waits() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_MWAIT_PATCH").is_none_or(|v| v != "0")) +} + +/// Instructions patched in place ([`patch`]), and the ones that could not be. +static PATCHED: AtomicU64 = AtomicU64::new(0); +static UNPATCHED: AtomicU64 = AtomicU64::new(0); + +/// Try 6.17: where a patch could not be made, so that the next exception there does not try +/// again (with `VirtualProtect` refused, each try was two more trips into Windows on top of +/// the exception). A few places: the title has its waits in a handful. +static UNPATCHABLE: [std::sync::atomic::AtomicUsize; 16] = [const { std::sync::atomic::AtomicUsize::new(0) }; 16]; + +fn unpatchable(at: usize) -> bool { + UNPATCHABLE.iter().any(|a| a.load(Relaxed) == at) +} + +fn mark_unpatchable(at: usize, why: &str, code: &[u8]) { + UNPATCHED.fetch_add(1, Relaxed); + if let Some(free) = UNPATCHABLE.iter().find(|a| a.load(Relaxed) == 0) { + let _ = free.compare_exchange(0, at, Relaxed, Relaxed); + } + static SAID: AtomicU64 = AtomicU64::new(0); + if SAID.fetch_add(1, Relaxed) < 4 { + tracing::warn!( + at = format_args!("{at:#x}"), + in_word = at % 8, + code = format_args!("{code:02x?}"), + why, + "a console wait instruction could not be patched in place: it stays emulated (an exception at every turn)" + ); + } +} + +/// How [`patch`] writes `with` over the instruction `code` at `at`: where the write starts, +/// its bytes, and how many, all inside one aligned eight-byte word. In turn: +/// - the instruction whole, if it lies in one word; +/// - a short jump over it (`jmp $+len`) in its first two bytes, if those lie in one word; +/// - Try 6.17, for a NOP-like `with` (NOPs, or a `pause` and NOPs): an instruction +/// `[66/67 prefixes] 0F xx yy` keeps its `0F` and has `xx yy` made `1F C0`, which makes +/// it `nop eax` (the three-byte NOP), when `xx yy` lie in one word. The 6.15 report had +/// the title's hot `monitorx` (`0F 01 FA`) start on the last byte of a word: neither of +/// the first two fitted, and it was emulated 440,000 times a second (patched 1, +/// unpatched 65,974,989). A thread running it meanwhile meets `0F 01 FA` or `0F 1F C0`. +/// +/// None if no way fits. +fn plan(at: usize, code: &[u8], with: &[u8]) -> Option<(usize, [u8; 8], usize)> { + let len = with.len(); + if len == 0 || len > 8 || code.len() != len { + return None; + } + let word = |a: usize, n: usize| a / 8 == (a + n - 1) / 8; + let mut bytes = [0u8; 8]; + if word(at, len) { + bytes[..len].copy_from_slice(with); + return Some((at, bytes, len)); + } + if len >= 2 && word(at, 2) { + bytes[..2].copy_from_slice(&[0xEB, (len as u8).wrapping_sub(2)]); + return Some((at, bytes, 2)); + } + let nop_like = with.iter().enumerate().all(|(i, &b)| b == 0x90 || (i == 0 && b == 0xF3)); + let prefixes = code.iter().take_while(|&&b| b == 0x66 || b == 0x67).count(); + if nop_like && len == prefixes + 3 && code[prefixes] == 0x0F && word(at + prefixes + 1, 2) { + bytes[..2].copy_from_slice(&[0x1F, 0xC0]); + return Some((at + prefixes + 1, bytes, 2)); + } + None +} + +/// Writes `with` over the `with.len()` bytes of code at `at` in one store that no other thread +/// can see half done (a compare-and-swap of the aligned eight bytes holding them), so that a +/// thread running the same code meanwhile meets the old instruction or the new one, never a +/// mix ([`plan`] says how when the instruction lies across two words). Returns whether the +/// code was patched; it is left as it was otherwise (and emulated again next time, without +/// another try). +/// +/// # Safety +/// `at` is the start of an instruction of `with.len()` bytes in loaded code. +unsafe fn patch(at: usize, with: &[u8]) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; + use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let len = with.len(); + if len == 0 || len > 8 || unpatchable(at) { + return false; + } + // SAFETY: the instruction's bytes, just decoded from loaded code. + let code = unsafe { std::slice::from_raw_parts(at as *const u8, len) }; + let Some((from, bytes, n)) = plan(at, code, with) else { + mark_unpatchable(at, "its bytes lie across two eight-byte words in a way no single store covers", code); + return false; + }; + let word = from & !7; + let mut old = 0u32; + // SAFETY: the eight bytes around the instruction, in its own page or the next (both + // mapped: the instruction's bytes were read, and code pages are whole); made writable + // for the patch and given their protection back. + unsafe { + if VirtualProtect(word as *const _, 8, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + let error = windows_sys::Win32::Foundation::GetLastError(); + mark_unpatchable(at, &format!("VirtualProtect refused (error {error})"), code); + return false; + } + let w = AtomicU64::from_ptr(word as *mut u64); + let before = w.load(Relaxed); + let mut after = before.to_le_bytes(); + let off = from - word; + after[off..off + n].copy_from_slice(&bytes[..n]); + let done = w.compare_exchange(before, u64::from_le_bytes(after), Ordering::SeqCst, Relaxed).is_ok(); + VirtualProtect(word as *const _, 8, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), word as *const _, 8); + if done { + PATCHED.fetch_add(1, Relaxed); + } else { + // (Another thread changed the word meanwhile: tried again at the next exception.) + UNPATCHED.fetch_add(1, Relaxed); + } + done + } +} + +/// The register `r` of `ctx` (CONTEXT order: rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, r8..r15). +fn register(ctx: &mut CONTEXT, r: u8) -> &mut u64 { + match r & 15 { + 0 => &mut ctx.Rax, + 1 => &mut ctx.Rcx, + 2 => &mut ctx.Rdx, + 3 => &mut ctx.Rbx, + 4 => &mut ctx.Rsp, + 5 => &mut ctx.Rbp, + 6 => &mut ctx.Rsi, + 7 => &mut ctx.Rdi, + 8 => &mut ctx.R8, + 9 => &mut ctx.R9, + 10 => &mut ctx.R10, + 11 => &mut ctx.R11, + 12 => &mut ctx.R12, + 13 => &mut ctx.R13, + 14 => &mut ctx.R14, + _ => &mut ctx.R15, + } +} + +/// Where the lines of the loop `mov rax, ptr; add ptr, 0x40; clzero; cmp ptr, end; jb` end, +/// from the state the loop has at its `clzero`: the line at `rax` is zeroed now, and one +/// more at `ptr` for every pass the `cmp` sends back. None if this is not the plain case +/// the loop makes (the line at `rax` on a 64-byte boundary, `ptr` the next line, under +/// 2 GiB in all): then every line is taken alone, as the instruction itself does it. +fn loop15_end(rax: usize, ptr: usize, end: usize) -> Option<usize> { + if rax & 63 != 0 || ptr != rax.wrapping_add(64) || ptr < rax { + return None; + } + let more = if ptr < end { (end - ptr).div_ceil(64) } else { 0 }; + let last = ptr.checked_add(more.checked_mul(64)?)?; + (last - rax < 2 << 30).then_some(last) +} + +/// The `clzero` at `rip` in the loop `mov rax, ptr; add ptr, 0x40; clzero; cmp ptr, end; jb`, +/// with all the lines the loop would still zero: `Some(true)` when they are zeroed and the +/// registers stand as the loop leaves them at its last `clzero` (the caller steps over the +/// instruction; the title's own `cmp` and `jb` then leave the loop), `Some(false)` when the +/// first line is not writable (the real instruction faults there too), and when only a +/// first part was writable the registers stand at the line after it, where the instruction +/// runs again. None if it is not that loop: the lone instruction is emulated. +/// +/// # Safety +/// `rip` is the faulting instruction of `ctx`, whose bytes were read. +unsafe fn clzero_loop15(ctx: &mut CONTEXT, rip: usize, ptr_reg: u8, end_reg: u8) -> Option<bool> { + // The seven bytes in front of it: in the same page as the instruction, which ran. + if rip & 0xFFF < 7 && !readable(rip - 7, 7) { + return None; + } + // SAFETY: readable, as checked or as the instruction's own page. + let before = unsafe { std::slice::from_raw_parts((rip - 7) as *const u8, 7) }; + if !decode::loop15_head(before, ptr_reg) || end_reg == 0 || end_reg == ptr_reg { + return None; + } + let rax = ctx.Rax as usize; + let ptr = *register(ctx, ptr_reg) as usize; + let end = *register(ctx, end_reg) as usize; + let last = loop15_end(rax, ptr, end)?; + // Region by region, as the 12-byte loop: a block may lie across several views. + let mut at = rax; + while at < last { + let Some(to) = writable_to(at, last) else { break }; + // A region ends on a page boundary, so `to` is on a line boundary as `at` is. + // SAFETY: committed and writable from `at` to `to`. + unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) }; + at = to; + } + if at == rax { + return Some(false); + } + ZEROED.fetch_add((at - rax) as u64, Relaxed); + KINDS[K_LOOP15_LINES].fetch_add(((at - rax) / 64) as u64, Relaxed); + if at < last { + // What follows is not writable: the loop stands at that line's `clzero` now, where + // the real one faults too. The instruction runs again (the caller must not step). + ctx.Rax = at as u64; + *register(ctx, ptr_reg) = (at + 64) as u64; + ctx.Rip = (rip as u64).wrapping_sub(3); + return Some(true); + } + ctx.Rax = (last - 64) as u64; + *register(ctx, ptr_reg) = last as u64; + Some(true) +} + +/// An illegal instruction at `ctx.Rip`: a console-only one is emulated and stepped over +/// (`CONTINUE_EXECUTION`); anything else returns 0 (the crash report and the title's handlers +/// see it). +/// +/// # Safety +/// `ctx` is the faulting thread's context, from the exception being dispatched. +pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { + let rip = ctx.Rip as usize; + // The same few instructions fault again and again: their bytes are asked about once. + let known = if remembers() { CODE.with(Cell::get) } else { [(0, 0); 8] }; + let n = match known.iter().find(|&&(at, n)| at == rip && n > 0) { + Some(&(_, n)) => n, + None => { + if !readable(rip, 1) { + return 0; + } + let n = (1..=16).rev().find(|&n| readable(rip, n)).unwrap_or(0); + if remembers() { + let mut known = known; + known.rotate_right(1); + known[0] = (rip, n); + CODE.with(|c| c.set(known)); + } + n + } + }; + // SAFETY: `n` bytes at `rip` are readable. + let code = unsafe { std::slice::from_raw_parts(rip as *const u8, n) }; + let Some((what, len)) = decode::decode(code) else { return 0 }; + static SEEN: std::sync::Mutex<Vec<std::mem::Discriminant<ConsoleOnly>>> = std::sync::Mutex::new(Vec::new()); + if let Ok(mut seen) = SEEN.lock() + && !seen.contains(&std::mem::discriminant(&what)) + { + seen.push(std::mem::discriminant(&what)); + if what != ConsoleOnly::Ud2 { + tracing::warn!(instruction = ?what, at = format_args!("{rip:#x}"), "a console CPU instruction this CPU lacks: emulated (logged once)"); + } + } + match what { + ConsoleOnly::Ud2 => return 0, + ConsoleOnly::Clwb => { + // nothing to write back on the PC: patched to NOPs, no exception next time + use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; + let mut old = 0u32; + // SAFETY: the instruction's own bytes, made writable for the patch and restored. + unsafe { + if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 { + std::slice::from_raw_parts_mut(rip as *mut u8, len).fill(0x90); + VirtualProtect(rip as *const _, len, old, &mut old); + } + } + } + ConsoleOnly::Monitorx => { + KINDS[K_MONITORX].fetch_add(1, Relaxed); + MONITOR.with(|m| m.set((ctx.Rax as usize, ctx.Rsi))); + if patches_waits() && len <= 8 { + // SAFETY: the faulting instruction, `len` bytes, in the title's code. + unsafe { patch(rip, &[0x90; 8][..len]) }; + } + } + ConsoleOnly::Mwaitx => { + KINDS[K_MWAITX].fetch_add(1, Relaxed); + wait_step(); + std::hint::spin_loop(); + if patches_waits() && (2..=8).contains(&len) { + let mut with = [0x90u8; 8]; + with[0] = 0xF3; // pause + // SAFETY: as above. + unsafe { patch(rip, &with[..len]) }; + } + } + ConsoleOnly::Clzero | ConsoleOnly::ClzeroStep { .. } => { + // The loop `mov rax, ptr; add ptr, 0x40; clzero; cmp ptr, end; jb` (the title's + // +0x4e8ab4c and three more like it zero 896 to 7,040 bytes each, a line an + // exception) is taken whole from the line it stands at. + if let ConsoleOnly::ClzeroStep { ptr_reg, end_reg } = what + && loop15() + && let Some(done) = unsafe { clzero_loop15(ctx, rip, ptr_reg, end_reg) } + { + if !done { + return 0; + } + ctx.Rip += len as u64; + EMULATED.fetch_add(1, Relaxed); + KINDS[K_LOOP15].fetch_add(1, Relaxed); + line(); + return CONTINUE_EXECUTION; + } + KINDS[K_CLZERO].fetch_add(1, Relaxed); + // with an address-size prefix (0x67) the line is at EAX, zero-extended + let a32 = code[..len - 3].contains(&0x67); + let line = (if a32 { ctx.Rax & 0xFFFF_FFFF } else { ctx.Rax } as usize) & !63; + if !writable(line, 64) { + return 0; // the real instruction faults there too + } + // SAFETY: the 64-byte line is committed and writable. + unsafe { std::ptr::write_bytes(line as *mut u8, 0, 64) }; + } + ConsoleOnly::ClzeroLoop { end_reg } => { + KINDS[K_LOOP12].fetch_add(1, Relaxed); + // the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once + let regs: [u64; 16] = [ + ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15, + ]; + let end = regs[end_reg as usize & 15] as usize; + let start = ctx.Rax as usize; + if end > start && end - start < 2 << 30 { + // Region by region: a block may lie across several (the title's pages are + // mapped one view each), and one answer for all of it was a refusal, after + // which every 64-byte line took an exception of its own. + let mut at = start; + while at < end { + let Some(to) = writable_to(at, end) else { break }; + // SAFETY: committed and writable from `at` to `to`. + unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) }; + at = to; + } + if at == start { + return 0; + } + ZEROED.fetch_add((at - start) as u64, Relaxed); + if at < end { + // What follows is not writable: the loop goes on there (the same + // instruction again), where the real one faults too. + ctx.Rax = at as u64; + return CONTINUE_EXECUTION; + } + } + ctx.Rax = end as u64; + } + ConsoleOnly::Rdpru => { + let mut v = 0i64; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut v) }; + let v = if ctx.Rcx as u32 <= 1 { v as u64 } else { 0 }; + ctx.Rax = v & 0xFFFF_FFFF; + ctx.Rdx = v >> 32; + } + ConsoleOnly::Rdpid(r) => { + // SAFETY: no preconditions. + let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u64; + let regs: [&mut u64; 16] = [ + &mut ctx.Rax, &mut ctx.Rcx, &mut ctx.Rdx, &mut ctx.Rbx, &mut ctx.Rsp, &mut ctx.Rbp, &mut ctx.Rsi, &mut ctx.Rdi, &mut ctx.R8, &mut ctx.R9, &mut ctx.R10, &mut ctx.R11, &mut ctx.R12, &mut ctx.R13, + &mut ctx.R14, &mut ctx.R15, + ]; + *regs[r as usize & 15] = cpu; + } + // the low quadword changes; the high one is zeroed, as a Zen 5 does + ConsoleOnly::Extrq { dst, src, len, idx } => { + // SAFETY: the context's XMM registers (CONTEXT_FLOATING_POINT is captured for exceptions). + let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters }; + let (len, idx) = match src { + Some(s) => { + let c = x[s as usize & 15].Low; + (c as u8, (c >> 8) as u8) + } + None => (len, idx), + }; + let d = &mut x[dst as usize & 15]; + d.Low = decode::extrq(d.Low, len, idx); + d.High = 0; + } + ConsoleOnly::Insertq { dst, src, reg, len, idx } => { + // SAFETY: as above. + let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters }; + let s = x[src as usize & 15]; + let (len, idx) = if reg { (s.High as u8, (s.High >> 8) as u8) } else { (len, idx) }; + let d = &mut x[dst as usize & 15]; + d.Low = decode::insertq(d.Low, s.Low, len, idx); + d.High = 0; + } + } + if !matches!( + what, + ConsoleOnly::Monitorx | ConsoleOnly::Mwaitx | ConsoleOnly::Clzero | ConsoleOnly::ClzeroStep { .. } | ConsoleOnly::ClzeroLoop { .. } + ) { + KINDS[K_OTHER].fetch_add(1, Relaxed); + } + line(); + ctx.Rip += len as u64; + // How often this runs at all (each one is an exception: a trip into Windows and back). + let emulated = EMULATED.fetch_add(1, Relaxed) + 1; + if emulated >= 1 << 16 && emulated.is_power_of_two() { + tracing::info!( + emulated, + asked = ASKED.load(Relaxed), + zeroed_mb = ZEROED.load(Relaxed) >> 20, + patched = PATCHED.load(Relaxed), + unpatched = UNPATCHED.load(Relaxed), + "console CPU instructions emulated so far, the times Windows was asked about memory for them, what clzero loops zeroed, and the monitorx / mwaitx patched in place (VICTORY_MWAIT_PATCH=0: none)" + ); + } + CONTINUE_EXECUTION +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What the title's loop leaves, run line by line as the processor would: the lines it + /// zeroed and the registers (rax, ptr) at the end, from the state at its first `clzero`. + fn by_hand(mut rax: usize, mut ptr: usize, end: usize) -> (Vec<usize>, usize, usize) { + let mut lines = vec![rax & !63]; + while ptr < end { + rax = ptr; + ptr += 0x40; + lines.push(rax & !63); + } + (lines, rax, ptr) + } + + #[test] + fn the_15_byte_loop_ends_where_the_processor_would_end_it() { + for (rax, len) in [(0x1000usize, 7040usize), (0x1000, 3264), (0x1000, 3776), (0x1000, 896), (0x4000, 64), (0x4000, 65), (0x4000, 100), (0x4000, 1), (0x4000, 0), (0x8000, 128)] { + let (ptr, end) = (rax + 64, rax + len); + let (lines, last_rax, last_ptr) = by_hand(rax, ptr, end); + let last = loop15_end(rax, ptr, end).expect("the plain case"); + assert_eq!(last, last_ptr, "rax {rax:#x} len {len}"); + assert_eq!(last - 64, last_rax, "rax {rax:#x} len {len}"); + assert_eq!((last - rax) / 64, lines.len(), "rax {rax:#x} len {len}"); + assert_eq!(*lines.last().unwrap(), last - 64); + } + // an end before the pointer: the line at rax alone + assert_eq!(loop15_end(0x1000, 0x1040, 0x800), Some(0x1040)); + // not the plain case: a line not on a boundary, a pointer that is not the next line + assert_eq!(loop15_end(0x1008, 0x1048, 0x2000), None); + assert_eq!(loop15_end(0x1000, 0x1080, 0x2000), None); + assert_eq!(loop15_end(0x1000, 0x1040, 0x1000 + (3 << 30)), None, "over 2 GiB"); + } + + /// The loop as the title has it at +0x4e8ab4c, for the given registers. + fn code(ptr_reg: u8, end_reg: u8) -> Vec<u8> { + let (ph, pl, eh, el) = (ptr_reg >> 3, ptr_reg & 7, end_reg >> 3, end_reg & 7); + vec![ + 0x48 | ph << 2, 0x89, 0xC0 | pl << 3, // mov rax, ptr + 0x48 | ph, 0x83, 0xC0 | pl, 0x40, // add ptr, 0x40 + 0x0F, 0x01, 0xFC, // clzero + 0x48 | eh << 2 | ph, 0x39, 0xC0 | el << 3 | pl, // cmp ptr, end + 0x72, 0xF1, // jb -15 + 0x90, + ] + } + + #[test] + fn the_15_byte_loop_is_zeroed_whole_and_leaves_the_loop_s_registers() { + for (ptr_reg, end_reg, len) in [(10u8, 11u8, 7040usize), (9, 10, 3264), (8, 9, 3776), (2, 8, 896), (10, 11, 64), (10, 11, 100)] { + let code = code(ptr_reg, end_reg); + // a block of 0xAA with room on both sides, its start on a line boundary + let mut block = vec![0xAAu8; 16384]; + let base = (block.as_mut_ptr() as usize + 4096 + 63) & !63; + // SAFETY: plain data. + let mut ctx: CONTEXT = unsafe { std::mem::zeroed() }; + ctx.Rip = code.as_ptr() as u64 + 7; + ctx.Rax = base as u64; + *register(&mut ctx, ptr_reg) = base as u64 + 64; + *register(&mut ctx, end_reg) = (base + len) as u64; + // SAFETY: the context points at the code above. + assert_eq!(unsafe { emulate(&mut ctx) }, CONTINUE_EXECUTION); + let (lines, last_rax, last_ptr) = by_hand(base, base + 64, base + len); + assert_eq!(ctx.Rip, code.as_ptr() as u64 + 10, "at the loop's own cmp"); + assert_eq!(ctx.Rax as usize, last_rax); + assert_eq!(*register(&mut ctx, ptr_reg) as usize, last_ptr); + assert_eq!(*register(&mut ctx, end_reg) as usize, base + len, "the end is left alone"); + let zeroed = lines.len() * 64; + let at = base - block.as_ptr() as usize; + assert!(block[at..at + zeroed].iter().all(|&b| b == 0), "{zeroed} bytes zeroed"); + assert!(block[..at].iter().all(|&b| b == 0xAA), "nothing before the block"); + assert!(block[at + zeroed..].iter().all(|&b| b == 0xAA), "nothing after its last line"); + } + } + + #[test] + fn a_clzero_that_only_looks_like_the_loop_is_one_line() { + // the same bytes behind it, another head in front (add ptr, 0x80): one line, one step + let mut code = code(10, 11); + code[6] = 0x80; + let mut block = vec![0xAAu8; 8192]; + let base = (block.as_mut_ptr() as usize + 2048 + 63) & !63; + // SAFETY: plain data. + let mut ctx: CONTEXT = unsafe { std::mem::zeroed() }; + ctx.Rip = code.as_ptr() as u64 + 7; + ctx.Rax = base as u64; + ctx.R10 = base as u64 + 64; + ctx.R11 = base as u64 + 640; + // SAFETY: the context points at the code above. + assert_eq!(unsafe { emulate(&mut ctx) }, CONTINUE_EXECUTION); + assert_eq!(ctx.Rip, code.as_ptr() as u64 + 10); + assert_eq!((ctx.Rax, ctx.R10), (base as u64, base as u64 + 64), "registers untouched"); + let at = base - block.as_ptr() as usize; + assert!(block[at..at + 64].iter().all(|&b| b == 0)); + assert!(block[at + 64..].iter().all(|&b| b == 0xAA), "one line only"); + } + + #[test] + fn waits_are_patched_in_one_store_or_jumped_over() { + #[repr(align(64))] + struct Code([u8; 64]); + // monitorx inside one aligned word: NOPs + let mut code = Code([0xCC; 64]); + code.0[9..12].copy_from_slice(&[0x0F, 0x01, 0xFA]); + let at = code.0.as_mut_ptr() as usize + 9; + // SAFETY: the three bytes stand for an instruction in this writable buffer. + assert!(unsafe { patch(at, &[0x90; 3]) }); + assert_eq!(code.0[8..13], [0xCC, 0x90, 0x90, 0x90, 0xCC]); + // mwaitx across a word boundary: a jump over its third byte + code.0[22..25].copy_from_slice(&[0x0F, 0x01, 0xFB]); + let at = code.0.as_mut_ptr() as usize + 22; + // SAFETY: as above. + assert!(unsafe { patch(at, &[0xF3, 0x90, 0x90]) }); + assert_eq!(code.0[21..26], [0xCC, 0xEB, 0x01, 0xFB, 0xCC]); + // its first two bytes across one too (6.17): the 0F kept, the rest made `nop eax` + code.0[31..34].copy_from_slice(&[0x0F, 0x01, 0xFB]); + let at = code.0.as_mut_ptr() as usize + 31; + // SAFETY: as above. + assert!(unsafe { patch(at, &[0xF3, 0x90, 0x90]) }); + assert_eq!(code.0[30..35], [0xCC, 0x0F, 0x1F, 0xC0, 0xCC]); + } + + /// Try 6.17: the 6.15 report's `monitorx` on the last byte of a word. + #[test] + fn a_wait_across_words_is_made_a_three_byte_nop() { + let monitorx = [0x0F, 0x01, 0xFA]; + // in one word, its first two bytes in one word: as before + assert_eq!(plan(8, &monitorx, &[0x90; 3]).map(|p| (p.0, p.2)), Some((8, 3))); + assert_eq!(plan(14, &monitorx, &[0x90; 3]).map(|p| (p.0, p.1[..2].to_vec())), Some((14, vec![0xEB, 0x01]))); + // on the last byte of a word: the two after the 0F + let (from, bytes, n) = plan(15, &monitorx, &[0x90; 3]).unwrap(); + assert_eq!((from, &bytes[..n]), (16, &[0x1F, 0xC0][..])); + // with an address-size prefix + let prefixed = [0x67, 0x0F, 0x01, 0xFA]; + assert_eq!(plan(23, &prefixed, &[0x90; 4]).map(|p| p.0), Some(25)); + // not for a write that is no NOP, nor for an instruction of another shape + assert_eq!(plan(15, &monitorx, &[0xCC; 3]), None); + assert_eq!(plan(15, &[0x48, 0x01, 0xC0], &[0x90; 3]), None); + } +} diff --git a/crates/victory-loader/src/console_insn_decode.rs b/crates/victory-loader/src/console_insn_decode.rs new file mode 100644 index 0000000000..ccfeb4005f --- /dev/null +++ b/crates/victory-loader/src/console_insn_decode.rs @@ -0,0 +1,284 @@ +//! Instructions the console's CPU (Zen 2) has and a PC's may lack – a title raises +//! STATUS_ILLEGAL_INSTRUCTION on them on an Intel CPU before Ice Lake / Alder Lake (CLWB, +//! SHA) or on any Intel CPU (CLZERO, RDPRU, MONITORX / MWAITX and SSE4a's EXTRQ / INSERTQ, +//! which are AMD's). The exception handler (`eh`) emulates the ones decoded here and steps over +//! them. + +/// A console-only instruction at the faulting address. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConsoleOnly { + /// `clwb m8`: write a cache line back – nothing to do, the PC's memory is coherent + Clwb, + /// `clzero`: zero the 64-byte cache line at rAX + Clzero, + /// `clzero` loop: `clzero; add rax, 0x40; cmp rax, <reg>; jb -12` – zero `[rax..reg)` + ClzeroLoop { end_reg: u8 }, + /// `clzero` in the loop `mov rax, <ptr>; add <ptr>, 0x40; clzero; cmp <ptr>, <end>; jb -15` + /// (the seven bytes before it are the caller's to check, [`loop15_head`]): the length is + /// the `clzero`'s own + ClzeroStep { ptr_reg: u8, end_reg: u8 }, + /// `rdpru`: ecx = 0 MPERF / 1 APERF → edx:eax (a counter) + Rdpru, + /// `monitorx` / `mwaitx`: a wait the emulation skips + Monitorx, + Mwaitx, + /// `rdpid r64`: TSC_AUX (the processor number) into the register (CONTEXT order: rax, rcx, + /// rdx, rbx, rsp, rbp, rsi, rdi, r8..r15) + Rdpid(u8), + /// SSE4a `extrq xmm, imm8 (length), imm8 (index)` / `extrq xmm1, xmm2` (`src` Some: the + /// length and index in xmm2's bits 5:0 and 13:8): a bit field of the low quadword, moved + /// down and zero-extended (the high quadword zeroed). Registers are XMM numbers 0..15. + Extrq { dst: u8, src: Option<u8>, len: u8, idx: u8 }, + /// SSE4a `insertq xmm1, xmm2, imm8 (length), imm8 (index)` / `insertq xmm1, xmm2` (`reg`: + /// the length and index in xmm2's bits 69:64 and 77:72): the low bits of xmm2 put into a + /// bit field of xmm1's low quadword. + Insertq { dst: u8, src: u8, reg: bool, len: u8, idx: u8 }, + /// `ud2`: the title's own trap (not emulated) + Ud2, +} + +/// A field length of SSE4a's six bits: 0 is 64. +fn field_len(len: u8) -> u32 { + match len & 63 { + 0 => 64, + n => n as u32, + } +} + +/// EXTRQ on a low quadword: `len` bits from bit `idx`, zero-extended (a field past bit 63 is +/// undefined on the console; here it is what a shift gives). +pub fn extrq(v: u64, len: u8, idx: u8) -> u64 { + let (len, idx) = (field_len(len), (idx & 63) as u32); + let field = v.checked_shr(idx).unwrap_or(0); + if len >= 64 { + field + } else { + field & ((1u64 << len) - 1) + } +} + +/// INSERTQ on a low quadword: the low `len` bits of `src` put at bit `idx` of `dst`. +pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 { + let (len, idx) = (field_len(len), (idx & 63) as u32); + let ones = if len >= 64 { u64::MAX } else { (1u64 << len) - 1 }; + let mask = ones.checked_shl(idx).unwrap_or(0); + (dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask) +} + +/// The length of a ModRM-encoded operand (ModRM, SIB and displacement) at `b[0]`, None when the +/// bytes run out. +fn modrm_len(b: &[u8]) -> Option<usize> { + let modrm = *b.first()?; + let (md, rm) = (modrm >> 6, modrm & 7); + if md == 3 { + return Some(1); + } + let mut len = 1; + let mut base = rm; + if rm == 4 { + base = *b.get(1)? & 7; + len += 1; + } + len += match md { + 0 if base == 5 => 4, // disp32 (rip-relative, or a SIB without a base) + 0 => 0, + 1 => 1, + _ => 4, + }; + (b.len() >= len).then_some(len) +} + +/// Whether `before`, the seven bytes in front of a [`ConsoleOnly::ClzeroStep`], are +/// `mov rax, <ptr>; add <ptr>, 0x40` for that pointer register (neither rax nor rsp). +pub fn loop15_head(before: &[u8], ptr_reg: u8) -> bool { + let (hi, lo) = (ptr_reg >> 3 & 1, ptr_reg & 7); + ptr_reg != 0 + && ptr_reg != 4 + && before.len() == 7 + // mov rax, ptr: REX.W (+R for r8..r15) 89 /r with rm = rax + && before[0] == 0x48 | hi << 2 + && before[1] == 0x89 + && before[2] == 0xC0 | lo << 3 + // add ptr, 0x40: REX.W (+B) 83 /0 ib + && before[3] == 0x48 | hi + && before[4] == 0x83 + && before[5] == 0xC0 | lo + && before[6] == 0x40 +} + +/// The console-only instruction at the start of `code` and its length. +pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { + let mut i = 0; + // `rep`: the last of F2 / F3, which decides between them (and over 66) for SSE4a + let (mut p66, mut pf3, mut rep, mut rex) = (false, false, 0u8, 0u8); + while let Some(&b) = code.get(i) { + match b { + 0x66 => p66 = true, + 0xF2 => rep = 0xF2, + 0xF3 => { + pf3 = true; + rep = 0xF3; + } + 0x2E | 0x3E | 0x26 | 0x36 | 0x64 | 0x65 | 0x67 => {} + // REX counts only right before the opcode: one before a legacy prefix is ignored + 0x40..=0x4F => { + rex = b; + i += 1; + continue; + } + _ => break, + } + rex = 0; + i += 1; + } + if *code.get(i)? != 0x0F { + return None; + } + match (*code.get(i + 1)?, code.get(i + 2).copied()) { + (0x01, Some(0xFC)) => { + // clzero (0F 01 FC); add rax, 0x40 (48 83 C0 40); cmp rax, <reg> ([48|4C] 39 modrm); jb -12 (72 F4) + // (not after an 0x67: that CLZERO is at EAX, and the jb goes back to the 0F, past the + // prefix – it is stepped alone, the loop is taken from the next one) + if code.len() >= i + 12 + && !code[..i].contains(&0x67) + && code[i + 3..i + 7] == [0x48, 0x83, 0xC0, 0x40] + && (code[i + 7] == 0x48 || code[i + 7] == 0x4C) + && code[i + 8] == 0x39 + && code[i + 10..i + 12] == [0x72, 0xF4] + { + let rex_r = code[i + 7] == 0x4C; + let modrm = code[i + 9]; + let reg_idx = ((modrm >> 3) & 7) | if rex_r { 8 } else { 0 }; + Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12)) + } else if i == 0 + && code.len() >= 8 + && code[3] & 0xF8 == 0x48 + && code[3] & 0x02 == 0 + && code[4] == 0x39 + && code[5] >> 6 == 3 + && code[6..8] == [0x72, 0xF1] + { + // clzero; cmp <ptr>, <end> (REX.W 39 /r, register form); jb -15 + let (rex, modrm) = (code[3], code[5]); + let end_reg = ((modrm >> 3) & 7) | (rex & 4) << 1; + let ptr_reg = (modrm & 7) | (rex & 1) << 3; + Some((ConsoleOnly::ClzeroStep { ptr_reg, end_reg }, 3)) + } else { + Some((ConsoleOnly::Clzero, i + 3)) + } + } + (0x01, Some(0xFD)) => Some((ConsoleOnly::Rdpru, i + 3)), + (0x01, Some(0xFA)) => Some((ConsoleOnly::Monitorx, i + 3)), + (0x01, Some(0xFB)) => Some((ConsoleOnly::Mwaitx, i + 3)), + (0x0B, _) => Some((ConsoleOnly::Ud2, i + 2)), + // SSE4a: register operands only (ModRM mod 3); REX.R extends reg, REX.B rm + // (the last of F2 / F3 decides: F2 INSERTQ, F3 #UD; neither with 66: EXTRQ) + (0x78 | 0x79, Some(m)) if (rep == 0xF2 || (rep == 0 && p66)) && m >> 6 == 3 => { + let reg = ((m >> 3) & 7) | (rex & 4) << 1; + let rm = (m & 7) | (rex & 1) << 3; + let imm = |k: usize| code.get(i + 3 + k).copied(); + match (code[i + 1], rep == 0xF2) { + // extrq xmm(rm), imm8, imm8 – the ModRM reg field is /0 + (0x78, false) if (m >> 3) & 7 == 0 => Some((ConsoleOnly::Extrq { dst: rm, src: None, len: imm(0)?, idx: imm(1)? }, i + 5)), + (0x79, false) => Some((ConsoleOnly::Extrq { dst: reg, src: Some(rm), len: 0, idx: 0 }, i + 3)), + (0x78, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: false, len: imm(0)?, idx: imm(1)? }, i + 5)), + (0x79, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: true, len: 0, idx: 0 }, i + 3)), + _ => None, + } + } + // 66 0F AE /6 with a memory operand (without 66 it is xsaveopt) + (0xAE, Some(m)) if p66 && (m >> 3) & 7 == 6 && m >> 6 != 3 => Some((ConsoleOnly::Clwb, i + 2 + modrm_len(&code[i + 2..])?)), + // F3 0F C7 /7 with a register operand + (0xC7, Some(m)) if pf3 && (m >> 3) & 7 == 7 && m >> 6 == 3 => Some((ConsoleOnly::Rdpid((m & 7) | (rex & 1) << 3), i + 3)), + _ => None, + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + /// EXTRQ / INSERTQ as AMD's manual gives them: a length of 0 is 64. + #[test] + fn sse4a_bit_fields() { + assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 8, 16), 0xBC); + assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 0, 0), 0x1234_5678_9ABC_DEF0); + assert_eq!(extrq(0x8000_0000_0000_0000, 1, 63), 1); + assert_eq!(insertq(0xFFFF_FFFF_FFFF_FFFF, 0xAB, 8, 8), 0xFFFF_FFFF_FFFF_ABFF); + assert_eq!(insertq(0, 0x1FF, 4, 60), 0xF000_0000_0000_0000); + assert_eq!(insertq(0x1111, 0xDEAD_BEEF_0000_0000, 0, 0), 0xDEAD_BEEF_0000_0000); + for (v, len, idx) in [(0x0123_4567_89AB_CDEFu64, 12u8, 20u8), (u64::MAX, 63, 1), (0x55, 3, 0)] { + assert_eq!(extrq(insertq(0, v, len, idx), len, idx), extrq(v, len, 0)); + } + } + + #[test] + fn decodes_the_console_only_instructions() { + assert_eq!(decode(&[0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 3))); + // clzero loop against r10 (4C 39 D0 = cmp rax, r10) + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4]), + Some((ConsoleOnly::ClzeroLoop { end_reg: 10 }, 12)) + ); + // clzero loop against rdx (48 39 D0 = cmp rax, rdx) + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), + Some((ConsoleOnly::ClzeroLoop { end_reg: 2 }, 12)) + ); + // the same loop after an address-size prefix: that one CLZERO alone + assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 4))); + // the title's other loop, as at its +0x4e8ab4c: mov rax, r10; add r10, 0x40; clzero; + // cmp r10, r11; jb -15 (and against r9/r10, r8/r9, rdx/r8) + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xDA, 0x72, 0xF1]), Some((ConsoleOnly::ClzeroStep { ptr_reg: 10, end_reg: 11 }, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xD1, 0x72, 0xF1]), Some((ConsoleOnly::ClzeroStep { ptr_reg: 9, end_reg: 10 }, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xC8, 0x72, 0xF1]), Some((ConsoleOnly::ClzeroStep { ptr_reg: 8, end_reg: 9 }, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4C, 0x39, 0xC2, 0x72, 0xF1]), Some((ConsoleOnly::ClzeroStep { ptr_reg: 2, end_reg: 8 }, 3))); + assert!(loop15_head(&[0x4C, 0x89, 0xD0, 0x49, 0x83, 0xC2, 0x40], 10)); + assert!(loop15_head(&[0x4C, 0x89, 0xC8, 0x49, 0x83, 0xC1, 0x40], 9)); + assert!(loop15_head(&[0x4C, 0x89, 0xC0, 0x49, 0x83, 0xC0, 0x40], 8)); + assert!(loop15_head(&[0x48, 0x89, 0xD0, 0x48, 0x83, 0xC2, 0x40], 2)); + assert!(!loop15_head(&[0x4C, 0x89, 0xD0, 0x49, 0x83, 0xC2, 0x40], 9), "another register"); + assert!(!loop15_head(&[0x4C, 0x89, 0xD0, 0x49, 0x83, 0xC2, 0x80], 10), "another step"); + // not that loop: another jump back, a memory operand, a 32-bit compare + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xDA, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0x1A, 0x72, 0xF1]), Some((ConsoleOnly::Clzero, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x45, 0x39, 0xDA, 0x72, 0xF1]), 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))); + assert_eq!(decode(&[0x0F, 0x0B]), Some((ConsoleOnly::Ud2, 2))); + // clwb [rax]; clwb [rcx+0x40]; clwb [rsp+8]; clwb [rip+disp32]; clwb [r8] + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 4))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x71, 0x40]), Some((ConsoleOnly::Clwb, 5))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24, 0x08]), Some((ConsoleOnly::Clwb, 6))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x35, 1, 2, 3, 4]), Some((ConsoleOnly::Clwb, 8))); + assert_eq!(decode(&[0x66, 0x41, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 5))); + // rdpid rax; rdpid r9 + assert_eq!(decode(&[0xF3, 0x0F, 0xC7, 0xF8]), Some((ConsoleOnly::Rdpid(0), 4))); + assert_eq!(decode(&[0xF3, 0x41, 0x0F, 0xC7, 0xF9]), Some((ConsoleOnly::Rdpid(9), 5))); + // not console-only: clflushopt (/7), xsaveopt (no 66), a plain mov, truncated bytes + // SSE4a, as a retail game has it (#216: insertq xmm0, xmm1 with length / index bytes) + assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10]), Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 8, idx: 16 }, 6))); + assert_eq!(decode(&[0xF2, 0x45, 0x0F, 0x79, 0xC1]), Some((ConsoleOnly::Insertq { dst: 8, src: 9, reg: true, len: 0, idx: 0 }, 5))); + assert_eq!(decode(&[0x66, 0x0F, 0x78, 0xC2, 0x04, 0x08]), Some((ConsoleOnly::Extrq { dst: 2, src: None, len: 4, idx: 8 }, 6))); + assert_eq!(decode(&[0x66, 0x0F, 0x79, 0xCA]), Some((ConsoleOnly::Extrq { dst: 1, src: Some(2), len: 0, idx: 0 }, 4))); + assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08]), None, "an immediate missing"); + assert_eq!(decode(&[0x0F, 0x78, 0xC1, 0x08, 0x10]), None, "VMREAD without a prefix is not SSE4a"); + // prefixes as a Zen 5 runs them (Kalmarv on #209): the last of F2 / F3 decides, 66 next + // to them does not; 0x67 and a REX before a legacy prefix are ignored + let insertq = Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 16, idx: 16 }, 7)); + for code in [[0x66, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF2, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x67, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10]] { + assert_eq!(decode(&code), insertq, "{code:02x?}"); + } + for code in [[0xF2, 0xF3, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x66, 0xF3, 0x0F, 0x78, 0xC0, 0x10, 0x10]] { + assert_eq!(decode(&code), None, "#UD on the CPU: {code:02x?}"); + } + assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 4))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x38]), None); + assert_eq!(decode(&[0x0F, 0xAE, 0x30]), None); + assert_eq!(decode(&[0x48, 0x8B, 0x01]), None); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24]), None); + assert_eq!(decode(&[0x0F]), None); + } +} diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index c27235c914..e1a6483813 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -8,12 +8,9 @@ //! exception too), is reported from the unhandled-exception filter //! (`report_unhandled`, which the runtime calls ahead of the title's own) //! and appended to the crash log, with the title's last debug output, which -//! often states the reason. Diagnostics builds can also append first-chance -//! breakpoints with `VICTORY_CRASH_BREAKPOINTS=1`. Panics of ours go to the -//! crash log too. +//! often states the reason. Panics of ours go to the crash log too. use std::ptr::null_mut; -use std::sync::atomic::{AtomicBool, Ordering}; use windows_sys::Win32::Foundation::{ EXCEPTION_ACCESS_VIOLATION, EXCEPTION_BREAKPOINT, EXCEPTION_ILLEGAL_INSTRUCTION, EXCEPTION_INT_DIVIDE_BY_ZERO, EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE, @@ -48,21 +45,17 @@ pub fn save_on_crash(ranges: Vec<(usize, usize, std::path::PathBuf)>) { /// The file crash reports are appended to, besides being printed. static LOG: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new(); -/// Read before installing the exception handler. -static LOG_FIRST_CHANCE_BREAKPOINTS: AtomicBool = AtomicBool::new(false); - /// Also appends every unhandled-exception report and panic to `file`, so a /// crash can be read after the console is gone. pub fn log_crashes_to(file: std::path::PathBuf) { if LOG.set(file).is_ok() { - let _ = HOST.set(host()); let print = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { print(info); append_to_log(&format!( "VIctory: panic on thread {:?}: {info}\n{}", std::thread::current().name().unwrap_or("?"), - report_end() + title_output() )); })); } @@ -71,11 +64,8 @@ pub fn log_crashes_to(file: std::path::PathBuf) { /// Appends a failure that is not an exception (the host GPU's) to the crash /// log, with the title's last debug output, and prints it. pub fn log_crash(text: &str) { - let text = format!( - "{text} -{}", - report_end() - ); + let text = format!("{text} +{}", title_output()); eprint!("{text}"); append_to_log(&text); } @@ -86,16 +76,9 @@ fn append_to_log(text: &str) { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()); - let opened = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(file); + let opened = std::fs::OpenOptions::new().create(true).append(true).open(file); if let Ok(mut f) = opened { - let _ = write!( - f, - "unix time {now}, process {}\n{text}\n", - std::process::id() - ); + let _ = write!(f, "unix time {now}, process {}\n{text}\n", std::process::id()); } } @@ -122,60 +105,7 @@ fn title_output() -> String { let Ok(said) = SAID.try_lock() else { return String::new(); }; - said.iter() - .map(|l| format!(" title said: {l}\n")) - .collect() -} - -/// The host's line in a crash report. Its CPU and Windows build decide what -/// title code runs (Intel CPUs lack some of the console's AMD-only -/// instructions) and which D3D12 runtime there is, so a report needs both. -/// Set along with the crash log, so a crash queries nothing. -static HOST: std::sync::OnceLock<String> = std::sync::OnceLock::new(); - -/// What ends a crash report: the host, then the title's last debug output. -fn report_end() -> String { - let host = HOST.get().map_or("", String::as_str); - format!("{host}{}", title_output()) -} - -/// The line [`HOST`] holds. -fn host() -> String { - format!(" host: {}, Windows {}\n", cpu_name(), windows_version()) -} - -/// The CPU's brand string, e.g. `AMD Ryzen 7 5700X3D 8-Core Processor`. -fn cpu_name() -> String { - use std::arch::x86_64::__cpuid; - if __cpuid(0x8000_0000).eax < 0x8000_0004 { - return "an unnamed CPU".into(); - } - let bytes: Vec<u8> = (0x8000_0002..=0x8000_0004) - .flat_map(|leaf| { - let r = __cpuid(leaf); - [r.eax, r.ebx, r.ecx, r.edx] - }) - .flat_map(u32::to_le_bytes) - .collect(); - let padding = |c: char| c == '\0' || c.is_whitespace(); - let name = String::from_utf8_lossy(&bytes); - name.trim_matches(padding).to_owned() -} - -/// The running Windows as `major.minor.build`. `RtlGetVersion` gives the -/// real one; `GetVersionEx` gives what the executable's manifest declares. -fn windows_version() -> String { - use windows_sys::Wdk::System::SystemServices::RtlGetVersion; - use windows_sys::Win32::System::SystemInformation::OSVERSIONINFOW; - // SAFETY: a zeroed OSVERSIONINFOW is valid; its size field is set. - let mut info: OSVERSIONINFOW = unsafe { std::mem::zeroed() }; - info.dwOSVersionInfoSize = size_of::<OSVERSIONINFOW>() as u32; - // SAFETY: fills the structure passed, whose size it was told. - if unsafe { RtlGetVersion(&mut info) } != 0 { - return "of unknown version".into(); - } - let (major, minor, build) = (info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber); - format!("{major}.{minor}.{build}") + said.iter().map(|l| format!(" title said: {l}\n")).collect() } /// Installs the handlers; call once before running title code. @@ -185,11 +115,6 @@ pub fn report_crashes() { unsafe { report_unhandled(info) }; EXCEPTION_CONTINUE_SEARCH } - LOG_FIRST_CHANCE_BREAKPOINTS.store( - cfg!(feature = "diagnostics") - && std::env::var_os("VICTORY_CRASH_BREAKPOINTS").is_some_and(|value| value == "1"), - Ordering::Relaxed, - ); // SAFETY: registers handlers that only read the exception they are // given; the title's own filter, once it sets one, takes the place of // ours and calls `report_unhandled` first. @@ -211,12 +136,8 @@ const FATAL: [i32; 6] = [ /// Console CPUs are Zen 2: titles use AMD-only instructions Intel CPUs /// lack. Does their job instead: `clzero` (`0f 01 fc`) zeroes the 64-byte -/// line at `rax` (see [`clzero`] for the loops around it); -/// `monitorx`/`mwaitx` (`0f 01 fa`/`fb`) are wait hints, so a spin loop -/// around them works with mwaitx as a yield; `rdpru` (`0f 01 fd`) reads -/// MPERF (`ecx` 0) or APERF (1), cycles at the nominal and the actual -/// frequency, and gets the time-stamp counter for both: a core that never -/// changes frequency. +/// line at `rax`; `monitorx`/`mwaitx` (`0f 01 fa`/`fb`) are wait hints, so +/// a spin loop around them works with mwaitx as a yield. unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { // SAFETY: the system passes valid exception pointers; the faulting // instruction's bytes are readable, as the CPU just fetched them. @@ -228,21 +149,9 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { } let code = context.Rip as *const u8; match code.cast::<[u8; 3]>().read_unaligned() { - [0x0f, 0x01, 0xfc] => return clzero(context), + [0x0f, 0x01, 0xfc] => ((context.Rax & !63) as *mut u8).write_bytes(0, 64), [0x0f, 0x01, 0xfa] => {} [0x0f, 0x01, 0xfb] => std::thread::yield_now(), - [0x0f, 0x01, 0xfd] => { - // Flags are left as they are: a Zen 3 changes none, for - // known counters or not (measured in user mode). - let known = context.Rcx as u32 <= 1; - let cycles = if known { - std::arch::x86_64::_rdtsc() - } else { - 0 - }; - context.Rax = cycles & 0xffff_ffff; - context.Rdx = cycles >> 32; - } _ => { // Only bytes inside the faulting instruction's page are read: the next page may // not be mapped. @@ -264,7 +173,9 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { context.Rip += pass.len as u64; return true; } - if let Some(len) = clwb_len(&bytes[..n]) { + if n >= 15 + && let Some(len) = clwb_len(bytes[..15].try_into().unwrap_or([0; 15])) + { // A write-back hint: the PC's memory is coherent, so it has nothing to do. context.Rip += len as u64; return true; @@ -283,12 +194,12 @@ unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { /// `clwb m8` (`66 [rex] 0f ae /6`, a memory operand), which Intel CPUs before /// Ice Lake lack: its length, or `None` for any other instruction. -fn clwb_len(code: &[u8]) -> Option<usize> { - let at = if *code.get(1)? & 0xf0 == 0x40 { 2 } else { 1 }; - if *code.first()? != 0x66 || code.get(at..at + 2)? != [0x0f, 0xae] { +fn clwb_len(code: [u8; 15]) -> Option<usize> { + let at = if code[1] & 0xf0 == 0x40 { 2 } else { 1 }; + if code[0] != 0x66 || code[at] != 0x0f || code[at + 1] != 0xae { return None; } - let modrm = *code.get(at + 2)?; + let modrm = code[at + 2]; let (mode, rm) = (modrm >> 6, modrm & 7); if mode == 3 || (modrm >> 3) & 7 != 6 { return None; @@ -296,7 +207,7 @@ fn clwb_len(code: &[u8]) -> Option<usize> { let mut len = at + 3; let mut base = rm; if rm == 4 { - base = *code.get(len)? & 7; + base = code[len] & 7; len += 1; } len += match mode { @@ -305,7 +216,7 @@ fn clwb_len(code: &[u8]) -> Option<usize> { 2 => 4, _ => 0, }; - (len <= code.len()).then_some(len) + Some(len) } /// A `clwb` write-back loop as the title's compilers build it, one cache line a @@ -366,109 +277,6 @@ fn clwb_loop(code: &[u8]) -> Option<ClwbLoop> { (limit != base).then_some(ClwbLoop { base, limit, len }) } -/// `clzero` at `context.Rip`. An exception costs about a microsecond and -/// titles clear tens of kilobytes at a time, a line per pass, so the two -/// loops compilers build around the instruction are done whole in one -/// exception, leaving registers and flags as their last pass would (`a` -/// and `b` any registers but `rax`): -/// -/// ```text -/// top: clzero top: mov rax, a -/// add rax, 0x40 add a, 0x40 -/// cmp rax, b clzero -/// jb top cmp a, b -/// jb top -/// ``` -/// -/// Anything else around it is one line and the next instruction. -/// -/// # Safety -/// `context` is the state of a thread that faulted at a `clzero`; the -/// lines its registers name are the title's to zero. -unsafe fn clzero(context: &mut CONTEXT) -> bool { - // SAFETY: (every use) a line the title asked to zero. - let zero = |rax: u64| unsafe { ((rax & !63) as *mut u8).write_bytes(0, 64) }; - let at = context.Rip as usize; - // The loops' other instructions are read only where that stays inside - // the faulting instruction's page (the next one may not be mapped). - let page = at & 0xfff; - if page + 12 <= 0x1000 { - // SAFETY: inside the page the CPU fetched the instruction from. - let after = unsafe { &*((at + 3) as *const [u8; 9]) }; - if let [0x48, 0x83, 0xc0, 0x40, cmp @ .., 0x72, 0xf4] = after - && let Some((0, limit)) = compare_registers(cmp) - && limit != 0 - { - let limit = *gpr(context, limit); - loop { - zero(context.Rax); - context.Rax = context.Rax.wrapping_add(0x40); - if context.Rax >= limit { - break; - } - } - context.EFlags = context.EFlags & !CMP_FLAGS | cmp_flags(context.Rax, limit); - context.Rip += 12; - return true; - } - } - if (7..=0x1000 - 8).contains(&page) { - // SAFETY: inside the page the CPU fetched the instruction from. - let (before, after) = unsafe { - ( - &*((at - 7) as *const [u8; 7]), - &*((at + 3) as *const [u8; 5]), - ) - }; - if let [ - rex @ (0x48 | 0x4c), - 0x89, - load, - add_rex @ (0x48 | 0x49), - 0x83, - add, - 0x40, - ] = *before - && let [cmp @ .., 0x72, 0xf1] = after - && let Some((a, b)) = compare_registers(cmp) - && load & 0xc7 == 0xc0 - && a == (load >> 3) & 7 | (rex & 4) << 1 - && add & 0xf8 == 0xc0 - && a == add & 7 | (add_rex & 1) << 3 - && a != 0 - && b != 0 - { - let limit = *gpr(context, b); - loop { - zero(context.Rax); - let next = *gpr(context, a); - if next >= limit { - break; - } - context.Rax = next; - *gpr(context, a) = next.wrapping_add(0x40); - } - context.EFlags = context.EFlags & !CMP_FLAGS | cmp_flags(*gpr(context, a), limit); - context.Rip += 8; - return true; - } - } - zero(context.Rax); - context.Rip += 3; - true -} - -/// `cmp rm, reg` between 64-bit registers (`REX.W 39 /r`): (`rm`, `reg`). -fn compare_registers(code: &[u8]) -> Option<(u8, u8)> { - let &[rex @ 0x48..=0x4f, 0x39, modrm] = code else { - return None; - }; - (modrm >> 6 == 3).then_some(( - modrm & 7 | (rex & 1) << 3, - (modrm >> 3) & 7 | (rex & 4) << 1, - )) -} - /// The general register numbered `n` as instructions encode it. fn gpr(context: &mut CONTEXT, n: u8) -> &mut u64 { match n & 15 { @@ -528,20 +336,12 @@ unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option<usize> { ((b(at + 3), b(at + 4)), at + 5) } else { // extrq reads its fields from src's low half, insertq from its high. - let f = if prefix == 0x66 { - xmm[src].Low - } else { - xmm[src].High as u64 - }; + let f = if prefix == 0x66 { xmm[src].Low } else { xmm[src].High as u64 }; ((f as u8, (f >> 8) as u8), at + 3) }; let (n, at_bit) = (u32::from(fields.0 & 63), u32::from(fields.1 & 63)); let bits = if n == 0 { 64 } else { n }; - let mask = if bits == 64 { - u64::MAX - } else { - (1u64 << bits) - 1 - }; + let mask = if bits == 64 { u64::MAX } else { (1u64 << bits) - 1 }; if prefix == 0x66 { // extrq: register form takes its fields from src, works on dst. if immediate && (modrm >> 3) & 7 != 0 { @@ -557,17 +357,23 @@ unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option<usize> { } unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + // an instruction of the console's CPU this one lacks: emulated, the title goes on + // SAFETY: the system passes valid exception pointers. + if unsafe { (*(*info).ExceptionRecord).ExceptionCode } == EXCEPTION_ILLEGAL_INSTRUCTION { + // SAFETY: the faulting thread's context, for the exception being dispatched. + let r = unsafe { crate::console_insn::emulate(&mut *(*info).ContextRecord) }; + if r != 0 { + return r; + } + } // SAFETY: the system passes valid exception pointers. if unsafe { emulate_amd_only(info) } { return -1; // EXCEPTION_CONTINUE_EXECUTION } // SAFETY: as above. - let code = unsafe { (*(*info).ExceptionRecord).ExceptionCode }; - if FATAL.contains(&code) { - let to_file = - code == EXCEPTION_BREAKPOINT && LOG_FIRST_CHANCE_BREAKPOINTS.load(Ordering::Relaxed); + if FATAL.contains(&unsafe { (*(*info).ExceptionRecord).ExceptionCode }) { // SAFETY: as above. - unsafe { report("first-chance exception", info, to_file) }; + unsafe { report("first-chance exception", info, false) }; } EXCEPTION_CONTINUE_SEARCH } @@ -598,6 +404,43 @@ unsafe fn instruction_bytes(at: usize) -> String { hex.join(" ") } +/// `len` bytes at `address` as hex, if all of them are committed, readable +/// and not a guard page; `None` otherwise (nothing is read then). +fn readable_hex(address: usize, len: usize) -> Option<String> { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, + PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, + VirtualQuery, + }; + if address < 0x10000 || address.checked_add(len).is_none() { + return None; + } + let mut at = address; + while at < address + len { + // SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: reads the address space's bookkeeping only. + if unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) } == 0 { + return None; + } + let readable = PAGE_READONLY + | PAGE_READWRITE + | PAGE_WRITECOPY + | PAGE_EXECUTE_READ + | PAGE_EXECUTE_READWRITE + | PAGE_EXECUTE_WRITECOPY; + if info.State != MEM_COMMIT || info.Protect & readable == 0 || info.Protect & PAGE_GUARD != 0 + { + return None; + } + at = info.BaseAddress as usize + info.RegionSize; + } + // SAFETY: every page of the range is committed and readable. + let bytes = unsafe { std::slice::from_raw_parts(address as *const u8, len) }; + let hex: Vec<_> = bytes.iter().map(|b| format!("{b:02x}")).collect(); + Some(hex.join("")) +} + /// MSVC's code for a C++ `throw`, and its magic first parameter. const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32; const CPP_MAGIC: usize = 0x1993_0520; @@ -617,7 +460,8 @@ unsafe fn thrown(p: &[usize]) -> String { let types = p[3] + rva(p[2] + 12); let name = |i: usize| { let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4); - std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char).to_string_lossy() + std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char) + .to_string_lossy() }; let first = name(0); let value = match &*first { @@ -699,13 +543,59 @@ unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) { context.R14, context.R15 )); - for (i, pc) in unwind(*context).into_iter().enumerate() { - line(format!(" #{i:<2} {}", locate(pc as usize))); + let frames = unwind(*context); + for (i, pc) in frames.iter().enumerate() { + line(format!(" #{i:<2} {}", locate(*pc as usize))); + } + if code == EXCEPTION_ACCESS_VIOLATION { + // The code that faulted and its callers, and what the registers + // point at: enough to read the faulting function without the + // title's files. One print, so other threads' reports do not + // interleave with it. + // SAFETY: a plain query. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let mut dump = format!(" dump of thread {thread}:"); + let mut line = |l: String| { + dump.push('\n'); + dump.push_str(&l); + }; + if let Some(hex) = readable_hex(at.wrapping_sub(64), 64) { + line(format!(" code {hex} |")); + } + if let Some(hex) = readable_hex(at, 32) { + line(format!(" code| {hex}")); + } + for (i, pc) in frames.iter().enumerate().skip(1).take(4) { + if let Some(hex) = readable_hex((*pc as usize).wrapping_sub(48), 48) { + line(format!(" #{i} called by {hex} |")); + } + } + let registers = [ + ("rax", context.Rax), + ("rcx", context.Rcx), + ("rdx", context.Rdx), + ("rsi", context.Rsi), + ("rdi", context.Rdi), + ("r8", context.R8), + ("r12", context.R12), + ("r15", context.R15), + ]; + for (name, value) in registers { + if let Some(hex) = readable_hex(value as usize, 64) { + line(format!(" [{name}] {hex}")); + } + } + if let Some(hex) = readable_hex(context.Rsp as usize, 128) { + line(format!(" [rsp] {hex}")); + } + eprintln!("{dump}"); + text.push_str(&dump); + text.push('\n'); } if to_file { - let end = report_end(); - eprint!("{end}"); - text.push_str(&end); + let said = title_output(); + eprint!("{said}"); + text.push_str(&said); append_to_log(&text); } #[cfg(feature = "diagnostics")] @@ -963,83 +853,26 @@ mod tests { #[test] fn clwb_lengths() { - assert_eq!(clwb_len(&[0x66, 0x41, 0x0f, 0xae, 0x31]), Some(5)); // clwb [r9] - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x30]), Some(4)); // clwb [rax] - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x70, 0x40]), Some(5)); // clwb [rax+0x40] - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0]), Some(8)); // [rax+disp32] - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x34, 0x24]), Some(5)); // clwb [rsp] - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0]), Some(8)); // [rip+disp32] - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x38]), None); // clflushopt, /7 - assert_eq!(clwb_len(&[0x0f, 0xae, 0x30]), None); // xsaveopt, no 66 - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0xf0]), None); // register form - } - - #[test] - fn a_clwb_at_the_end_of_a_page_is_decoded() { - // Exact-length slices, as at the end of a page. - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x30]), Some(4)); - assert_eq!(clwb_len(&[0x66, 0x41, 0x0f, 0xae, 0x31]), Some(5)); - // Cut short by the slice: returns None without panicking. - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0xb0, 0, 1]), None); // disp32, 6 of 8 bytes - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x70]), None); // disp8, 4 of 5 bytes - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x34]), None); // SIB missing - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae, 0x34, 0x25, 0, 0]), None); // SIB disp32 cut short - assert_eq!(clwb_len(&[0x66, 0x0f, 0xae]), None); // ModRM missing - assert_eq!(clwb_len(&[0x66]), None); - assert_eq!(clwb_len(&[]), None); - - // Emulation at the last 4 and 5 bytes of a page with an unreadable page after it. - use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, - VirtualFree, VirtualProtect, + let pad = |b: &[u8]| { + let mut c = [0u8; 15]; + c[..b.len()].copy_from_slice(b); + c }; - // SAFETY: two pages of ours, the second unreadable so reading past the first faults. - unsafe { - let page = VirtualAlloc( - std::ptr::null(), - 0x2000, - MEM_RESERVE | MEM_COMMIT, - PAGE_READWRITE, - ) - .cast::<u8>(); - assert!(!page.is_null()); - let mut old = 0; - let guard = page.add(0x1000).cast(); - assert_ne!(VirtualProtect(guard, 0x1000, PAGE_NOACCESS, &mut old), 0); - for insn in [ - &[0x66, 0x0f, 0xae, 0x30][..], - &[0x66, 0x41, 0x0f, 0xae, 0x31][..], - ] { - let end = page.add(0x1000 - insn.len()); - end.copy_from_nonoverlapping(insn.as_ptr(), insn.len()); - let mut record: EXCEPTION_RECORD = std::mem::zeroed(); - record.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION; - let mut context: CONTEXT = std::mem::zeroed(); - context.Rip = end as u64; - let mut pointers = EXCEPTION_POINTERS { - ExceptionRecord: &mut record, - ContextRecord: &mut context, - }; - assert!(emulate_amd_only(&mut pointers)); - assert_eq!(context.Rip, end as u64 + insn.len() as u64); - } - VirtualFree(page.cast(), 0, MEM_RELEASE); - } - } - - #[test] - fn the_host_line_names_the_cpu_and_windows() { - // e.g. " host: AMD EPYC 7763 64-Core Processor, Windows 10.0.26100\n" - let line = host(); - let framed = line.starts_with(" host: ") && line.ends_with('\n'); - assert!(framed, "{line:?}"); - let inner = line.trim_start_matches(" host: ").trim_end(); - let (cpu, windows) = inner.rsplit_once(", Windows ").expect(&line); - let named = !cpu.is_empty() && cpu == cpu.trim() && !cpu.contains('\0'); - assert!(named, "{line:?}"); - let version: Vec<u32> = windows.split('.').filter_map(|n| n.parse().ok()).collect(); - assert!(version.len() == 3 && version[0] >= 10, "{line:?}"); - println!("{line}"); + assert_eq!(clwb_len(pad(&[0x66, 0x41, 0x0f, 0xae, 0x31])), Some(5)); // clwb [r9] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x30])), Some(4)); // clwb [rax] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x70, 0x40])), Some(5)); // clwb [rax+0x40] + assert_eq!( + clwb_len(pad(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0])), + Some(8) + ); // [rax+disp32] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x34, 0x24])), Some(5)); // clwb [rsp] + assert_eq!( + clwb_len(pad(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0])), + Some(8) + ); // [rip+disp32] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x38])), None); // clflushopt, /7 + assert_eq!(clwb_len(pad(&[0x0f, 0xae, 0x30])), None); // xsaveopt, no 66 + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xf0])), None); // register form } #[test] @@ -1072,85 +905,6 @@ mod tests { std::arch::asm!(".byte 0x0f, 0x01, 0xfa", ".byte 0x0f, 0x01, 0xfb", in("rax") at, in("ecx") 0, in("edx") 0) }; - // rdpru of MPERF: a count in edx:eax, their high halves clear. - let (low, high): (u64, u64); - // SAFETY: touches only the named registers. - unsafe { - std::arch::asm!(".byte 0x0f, 0x01, 0xfd", - out("rax") low, inout("rcx") 0u64 => _, out("rdx") high) - }; - assert_ne!(high << 32 | low, 0); - assert!(high >> 32 == 0 && low >> 32 == 0); - } - - /// The flags a native `cmp a, b` leaves. - fn native_compare(a: u64, b: u64) -> u32 { - let flags: u64; - // SAFETY: compares two registers and reads the flags. - unsafe { - std::arch::asm!("cmp {a}, {b}", "pushfq", "pop {f}", - a = in(reg) a, b = in(reg) b, f = out(reg) flags) - }; - flags as u32 & CMP_FLAGS - } - - #[test] - fn compare_sets_flags_like_the_cpu() { - let values = [ - 0, - 1, - 0x40, - 0x7f, - 0x80, - 0xff, - 1 << 63, - (1 << 63) - 1, - !0, - !0 - 0x40, - ]; - for a in values { - for b in values { - assert_eq!(cmp_flags(a, b), native_compare(a, b), "cmp {a:#x}, {b:#x}"); - } - } - } - - #[test] - fn clzero_loops_end_like_their_last_pass() { - report_crashes(); - #[repr(align(64))] - struct Lines([u8; 192]); - let zeroed = |l: &Lines| [l.0[0] == 0, l.0[64] == 0, l.0[128] == 0]; - // clzero; add rax, 0x40; cmp rax, r10; jb - let mut mem = Lines([0xff; 192]); - let start = mem.0.as_mut_ptr() as u64; - let (end, flags): (u64, u64); - // SAFETY: zeroes the first two lines of `mem`. - unsafe { - std::arch::asm!( - ".byte 0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40, 0x4c, 0x39, 0xd0, 0x72, 0xf4", - "pushfq", "pop {f}", - inout("rax") start => end, in("r10") start + 100, f = out(reg) flags) - }; - assert_eq!(end, start + 128); - assert_eq!(flags as u32 & CMP_FLAGS, native_compare(end, start + 100)); - assert_eq!(zeroed(&mem), [true, true, false]); - // mov rax, rdx; add rdx, 0x40; clzero; cmp rdx, r8; jb - let mut mem = Lines([0xff; 192]); - let start = mem.0.as_mut_ptr() as u64; - let (last, next, flags): (u64, u64, u64); - // SAFETY: zeroes the last two lines of `mem`. - unsafe { - std::arch::asm!( - ".byte 0x48, 0x89, 0xd0, 0x48, 0x83, 0xc2, 0x40, 0x0f, 0x01, 0xfc", - ".byte 0x4c, 0x39, 0xc2, 0x72, 0xf1", - "pushfq", "pop {f}", - out("rax") last, inout("rdx") start + 64 => next, in("r8") start + 192, - f = out(reg) flags) - }; - assert_eq!((last, next), (start + 128, start + 192)); - assert_eq!(flags as u32 & CMP_FLAGS, native_compare(next, start + 192)); - assert_eq!(zeroed(&mem), [false, true, true]); } fn reg(low: u64, high: u64) -> M128A { @@ -1211,123 +965,6 @@ mod tests { assert!(line.0[64..].iter().all(|&b| b == 0xff)); } - /// Gives `code` to the emulation as if it faulted at `code[at]` with - /// `context` as the saved state, on any CPU; returns whether it - /// emulated and leaves the state after in `context`. - fn emulate_in(code: &[u8], at: usize, context: &mut CONTEXT) -> bool { - // At a fixed place in a page, so the loops' neighbours are always - // read (they are not near a page's edges). - #[repr(align(4096))] - struct Page([u8; 4096]); - let mut page = Box::new(Page([0xcc; 4096])); - let bytes = &mut page.0[0x800..]; - bytes[..code.len()].copy_from_slice(code); - context.Rip = bytes.as_ptr() as u64 + at as u64; - // SAFETY: a zeroed record is valid; the emulation reads only - // `bytes` and writes `context` and the lines the caller owns. - unsafe { - let mut record: EXCEPTION_RECORD = std::mem::zeroed(); - record.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION; - let mut pointers = EXCEPTION_POINTERS { - ExceptionRecord: &mut record, - ContextRecord: context, - }; - let emulated = emulate_amd_only(&mut pointers); - context.Rip -= bytes.as_ptr() as u64; - emulated - } - } - - #[test] - fn emulated_clzero_loops_end_like_their_last_pass() { - #[repr(align(64))] - struct Lines([u8; 192]); - let zeroed = |l: &Lines| [l.0[0] == 0, l.0[64] == 0, l.0[128] == 0]; - // clzero; add rax, 0x40; cmp rax, r10; jb - let mut mem = Lines([0xff; 192]); - let start = mem.0.as_mut_ptr() as u64; - // SAFETY: an all-zero context is valid. - let mut context: CONTEXT = unsafe { std::mem::zeroed() }; - context.Rax = start; - context.R10 = start + 100; - context.EFlags = 0x202 | CMP_FLAGS; - let code = [ - 0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40, 0x4c, 0x39, 0xd0, 0x72, 0xf4, - ]; - assert!(emulate_in(&code, 0, &mut context)); - assert_eq!((context.Rip, context.Rax), (12, start + 128)); - assert_eq!( - context.EFlags, - 0x202 | native_compare(start + 128, start + 100) - ); - assert_eq!(zeroed(&mem), [true, true, false]); - // mov rax, rdx; add rdx, 0x40; clzero; cmp rdx, r8; jb (faults at clzero, - // after the first pass's mov and add) - let mut mem = Lines([0xff; 192]); - let start = mem.0.as_mut_ptr() as u64; - // SAFETY: an all-zero context is valid. - let mut context: CONTEXT = unsafe { std::mem::zeroed() }; - context.Rax = start + 64; - context.Rdx = start + 128; - context.R8 = start + 192; - let code = [ - 0x48, 0x89, 0xd0, 0x48, 0x83, 0xc2, 0x40, 0x0f, 0x01, 0xfc, 0x4c, 0x39, 0xc2, 0x72, - 0xf1, - ]; - assert!(emulate_in(&code, 7, &mut context)); - assert_eq!( - (context.Rip, context.Rax, context.Rdx), - (15, start + 128, start + 192) - ); - assert_eq!(context.EFlags, native_compare(start + 192, start + 192)); - assert_eq!(zeroed(&mem), [false, true, true]); - // cmp rax, rax is not the loop (the limit would move with rax): one - // line, flags untouched. - let mut mem = Lines([0xff; 192]); - // SAFETY: an all-zero context is valid. - let mut context: CONTEXT = unsafe { std::mem::zeroed() }; - context.Rax = mem.0.as_mut_ptr() as u64; - context.EFlags = 0x202; - let code = [ - 0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40, 0x48, 0x39, 0xc0, 0x72, 0xf4, - ]; - assert!(emulate_in(&code, 0, &mut context)); - assert_eq!((context.Rip, context.EFlags), (3, 0x202)); - assert_eq!(zeroed(&mem), [true, false, false]); - // Any other neighbours: one line, then the next instruction. - let mut mem = Lines([0xff; 192]); - // SAFETY: an all-zero context is valid. - let mut context: CONTEXT = unsafe { std::mem::zeroed() }; - context.Rax = mem.0.as_mut_ptr() as u64 + 70; - context.R10 = !0; - let code = [ - 0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x20, 0x4c, 0x39, 0xd0, 0x72, 0xf4, - ]; - assert!(emulate_in(&code, 0, &mut context)); - assert_eq!(context.Rip, 3); - assert_eq!(zeroed(&mem), [false, true, false]); - } - - #[test] - fn emulated_rdpru_reads_known_counters_and_keeps_flags() { - let cases = [(0, true), (1, true), (2, false), (0x1_0000_0000, true)]; - let starts = [0x202, 0x202 | CMP_FLAGS]; - for ((ecx, known), flags) in cases.into_iter().flat_map(|c| starts.map(|f| (c, f))) { - // SAFETY: an all-zero context is valid. - let mut context: CONTEXT = unsafe { std::mem::zeroed() }; - context.Rcx = ecx; - context.Rax = !0; - context.Rdx = !0; - context.EFlags = flags; - assert!(emulate_in(&[0x0f, 0x01, 0xfd], 0, &mut context)); - assert_eq!(context.Rip, 3); - assert_eq!(context.EFlags, flags, "ecx {ecx:#x}"); - let count = context.Rdx << 32 | context.Rax; - assert!(context.Rax >> 32 == 0 && context.Rdx >> 32 == 0); - assert_eq!(count != 0, known, "ecx {ecx:#x}"); - } - } - #[test] fn emulated_monitorx_and_mwaitx_are_skipped() { let mut xmm = [reg(1, 2); 16]; diff --git a/crates/victory-loader/src/hooks.rs b/crates/victory-loader/src/hooks.rs deleted file mode 100644 index 024810d730..0000000000 --- a/crates/victory-loader/src/hooks.rs +++ /dev/null @@ -1,91 +0,0 @@ -//! Opt-in compatibility hooks for known title builds. -//! -//! Only per-build offsets and short byte signatures live here (asset policy: -//! nothing of the title itself). Every hook checks the build's hash and the -//! exact bytes it replaces, and does nothing otherwise. - -use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; -use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; -use windows_sys::Win32::System::Threading::GetCurrentProcess; - -/// First 16 hex digits of the BLAKE3 of the Series X 1.0.2.1 executable. -const BUILD_1_0_2_1: &str = "b99f876b74d4a77f"; - -/// Environment variable that turns the watchdog hook on. -pub(crate) const NO_WATCHDOG_ENV: &str = "VICTORY_NO_WATCHDOG"; - -/// One code patch: `rva` must hold exactly `expect` before `new` is written. -struct Patch { - what: &'static str, - rva: usize, - expect: &'static [u8], - new: &'static [u8], -} - -/// The title's watchdog thread ends the process on purpose when its main -/// thread has not advanced for about 30 one-second ticks. Two places do it: -/// the handler it calls (`mov dword ptr [0], imm32`) and, when the handler -/// returns or is unset, a fallback right after the call (`mov dword ptr [0], -/// 0; int3`). Jumping over the whole block returns the loop to its normal -/// path; the first patch makes the handler harmless if something else calls it. -const WATCHDOG: &[Patch] = &[ - Patch { - what: "watchdog: skip the call and the fallback fault", - rva: 0x2215c27, - // mov rax, [rip + disp32] (the handler pointer) - expect: &[0x48, 0x8B, 0x05, 0x1A, 0x07, 0xFA, 0x04], - // jmp +0x18 (to the loop's normal continuation), then NOPs - new: &[0xEB, 0x18, 0x90, 0x90, 0x90, 0x90, 0x90], - }, - Patch { - what: "watchdog: handler's deliberate fault", - rva: 0x23cf683, - expect: &[0xC7, 0x04, 0x25, 0, 0, 0, 0, 0x21, 0xD4, 0x8B, 0x4D], - // an eleven-byte NOP - new: &[0x66, 0x66, 0x2E, 0x0F, 0x1F, 0x84, 0, 0, 0, 0, 0], - }, -]; - -/// Applies the watchdog patches whose bytes match. Returns how many applied. -/// -/// # Safety -/// `base` is the mapped image whose original BLAKE3 is `hash`, and no title -/// code is running yet. -pub(crate) unsafe fn disarm_watchdog(base: usize, hash: &blake3::Hash) -> usize { - if !hash.to_hex().starts_with(BUILD_1_0_2_1) { - return 0; - } - WATCHDOG - .iter() - // SAFETY: forwarded from this function's contract. - .filter(|p| unsafe { apply(base, p) }) - .count() -} - -/// # Safety -/// See `disarm_watchdog`. -unsafe fn apply(base: usize, p: &Patch) -> bool { - let at = (base + p.rva) as *mut u8; - // SAFETY: the offset is inside the mapped .text of this exact build. - let now = unsafe { std::slice::from_raw_parts(at, p.expect.len()) }; - if now != p.expect || p.new.len() != p.expect.len() { - tracing::warn!( - what = p.what, - "hook skipped: the bytes are not the expected ones" - ); - return false; - } - let mut old = 0; - // SAFETY: changing the protection of those bytes only, restored below. - if unsafe { VirtualProtect(at as _, p.new.len(), PAGE_EXECUTE_READWRITE, &mut old) } == 0 { - return false; - } - // SAFETY: writable now; the bytes are the ones checked above. - unsafe { - std::ptr::copy_nonoverlapping(p.new.as_ptr(), at, p.new.len()); - VirtualProtect(at as _, p.new.len(), old, &mut old); - FlushInstructionCache(GetCurrentProcess(), at as _, p.new.len()); - } - tracing::info!(what = p.what, "hook applied"); - true -} diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index cb51af552a..220208cb53 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -22,11 +22,13 @@ //! on, pass every thread start and end on to the attached images. #[cfg(windows)] +mod console_insn; mod crash; #[cfg(windows)] -mod hooks; +mod pool_asserts; pub mod prepare; pub mod resolve; +pub mod resolution; #[cfg(all(windows, feature = "diagnostics"))] mod stacks; #[cfg(windows)] @@ -38,12 +40,12 @@ mod tls; #[cfg(windows)] mod windows; -#[cfg(all(windows, feature = "diagnostics"))] -pub use crash::save_on_crash; #[cfg(windows)] pub use crash::{ locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled, }; +#[cfg(all(windows, feature = "diagnostics"))] +pub use crash::save_on_crash; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-loader/src/pool_asserts.rs b/crates/victory-loader/src/pool_asserts.rs new file mode 100644 index 0000000000..ed6802879f --- /dev/null +++ b/crates/victory-loader/src/pool_asserts.rs @@ -0,0 +1,131 @@ +//! `VICTORY_POOL_NO_ASSERT=1`: the title's fixed-size pool allocators stop the +//! game with an `int3` when a pool has no free slot. In the opening cinematic +//! the `INSTANCE_LIST` pool fills (45000/45000) at a fixed point about 6-8 +//! minutes in, and every worker thread stops at once (VIctory issue #698). +//! The code right after each of those `int3`s is `xor reg, reg` on the way to +//! the allocator's own null return, so writing a NOP over the `int3` makes the +//! allocation fail with null instead. +//! +//! Approach by WalliceCariasPerussio (VIctory #698, gist 3f344d52): 17+ +//! minutes in the world on an RTX 5060 with every such site disarmed. This +//! version finds the sites itself in the mapped image (no list derived from +//! the title is shipped): every allocator copy pops its free list with a +//! 17-bit index (`and r32, 0x1ffff`) next to a `lock cmpxchg`; every jump +//! near it that lands on `int3` + `xor r, r` (same register) is a site. +//! +//! A diagnostic workaround, off by default: a caller that does not expect +//! null may fault later. + +use victory_pe::ImageInfo; +use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; +use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +pub(crate) const ENV: &str = "VICTORY_POOL_NO_ASSERT"; + +/// The build the scan was checked on (1.0.2.1; BLAKE3 prefix). +const BUILD: &str = "b99f876b74d4a77f"; + +/// `int3` followed by `xor r32, r32` / `xor r64, r64` of one register. +fn null_return_int3(code: &[u8], at: usize) -> bool { + let Some(&[cc, mut op, mut modrm, next]) = code.get(at..at + 4) else { + return false; + }; + if cc != 0xCC { + return false; + } + if (0x40..=0x4F).contains(&op) { + op = modrm; + modrm = next; + } + (op == 0x31 || op == 0x33) && modrm >> 6 == 3 && (modrm >> 3) & 7 == modrm & 7 +} + +/// Offsets (in `code`) of the pool-empty `int3`s. +pub(crate) fn sites(code: &[u8]) -> Vec<usize> { + const IMM: [u8; 4] = [0xFF, 0xFF, 0x01, 0x00]; + let mut out = std::collections::BTreeSet::new(); + for i in 2..code.len().saturating_sub(24) { + if code[i..i + 4] != IMM || code[i - 2] != 0x81 || (code[i - 1] >> 3) & 7 != 4 || code[i - 1] >> 6 != 3 { + continue; + } + let w = &code[i..i + 24]; + if !w.contains(&0xF0) || !w.windows(2).any(|p| p == [0x0F, 0xB1]) { + continue; + } + let (lo, hi) = (i.saturating_sub(0xA0), (i + 0x1C0).min(code.len().saturating_sub(8))); + for p in lo..hi { + let b = code[p]; + let target = match b { + 0x70..=0x7F | 0xEB => (p + 2).checked_add_signed(code[p + 1] as i8 as isize), + 0x0F if (0x80..=0x8F).contains(&code[p + 1]) => { + (p + 6).checked_add_signed(i32::from_le_bytes(code[p + 2..p + 6].try_into().unwrap()) as isize) + } + 0xE9 => (p + 5).checked_add_signed(i32::from_le_bytes(code[p + 1..p + 5].try_into().unwrap()) as isize), + _ => None, + }; + if let Some(t) = target + && null_return_int3(code, t) + { + out.insert(t); + } + } + } + out.into_iter().collect() +} + +/// Writes a NOP over each pool-empty `int3` of the mapped image's `.text`. +/// Returns how many were disarmed (0 for another build). +/// +/// # Safety +/// `base` is the just-mapped image described by `info`, and no title code +/// has run yet. +pub(crate) unsafe fn disarm(base: usize, info: &ImageInfo, hash: &blake3::Hash) -> usize { + if !hash.to_hex().starts_with(BUILD) { + tracing::warn!("{ENV}: not the build this was checked on; nothing changed"); + return 0; + } + let Some(text) = info.sections.iter().find(|s| s.name == ".text") else { return 0 }; + let start = base + text.rva as usize; + // SAFETY: the section is mapped and readable for its virtual size. + let code = unsafe { std::slice::from_raw_parts(start as *const u8, text.virtual_size as usize) }; + let found = sites(code); + let mut done = 0; + for off in found.iter().copied() { + let at = (start + off) as *mut u8; + let mut old = 0; + // SAFETY: one byte inside the mapped `.text`; protection restored below. + if unsafe { VirtualProtect(at.cast(), 1, PAGE_EXECUTE_READWRITE, &mut old) } == 0 { + continue; + } + // SAFETY: writable now, and the byte is the int3 checked by `sites`. + unsafe { + *at = 0x90; + VirtualProtect(at.cast(), 1, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), at.cast(), 1); + } + done += 1; + } + tracing::info!(found = found.len(), disarmed = done, "{ENV}: pool-empty int3s now return null"); + done +} + +#[cfg(test)] +mod tests { + #[test] + fn finds_the_jump_target_after_a_17_bit_pop() { + // and eax, 0x1ffff; lock cmpxchg [rcx], edx; jz +2; ret; ret; int3; xor edi, edi + let mut code = vec![0x90; 0xC0]; + code.extend([0x81, 0xE0, 0xFF, 0xFF, 0x01, 0x00, 0xF0, 0x0F, 0xB1, 0x11, 0x74, 0x02, 0xC3, 0xC3, 0xCC, 0x31, 0xFF, 0xC3]); + code.extend(vec![0x90; 0x40]); + assert_eq!(super::sites(&code), vec![0xC0 + 14]); + } + + #[test] + fn ignores_int3_without_a_null_return() { + let mut code = vec![0x90; 0xC0]; + code.extend([0x81, 0xE0, 0xFF, 0xFF, 0x01, 0x00, 0xF0, 0x0F, 0xB1, 0x11, 0x74, 0x02, 0xC3, 0xC3, 0xCC, 0x31, 0xC7, 0xC3]); + code.extend(vec![0x90; 0x40]); + assert!(super::sites(&code).is_empty()); + } +} diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs index daefdbc26e..c8935081bf 100644 --- a/crates/victory-loader/src/prepare.rs +++ b/crates/victory-loader/src/prepare.rs @@ -39,8 +39,7 @@ impl PreparedImage { /// directory is cleared: we bind the original slots using `info.imports`; /// * TLS callback pointer cleared: the OS still allocates static TLS for /// the image, but callbacks only run when we call them (after binding); -/// every base relocation that writes into it is made a no-op so the 0 -/// survives a rebase; +/// its base relocation is made a no-op so the 0 survives a rebase; /// * `FORCE_INTEGRITY` cleared, checksum zeroed: the copy is unsigned. pub fn prepare(original: &[u8]) -> Result<PreparedImage, PrepareError> { let info = ImageInfo::parse(original)?; @@ -95,37 +94,16 @@ pub fn prepare(original: &[u8]) -> Result<PreparedImage, PrepareError> { at as usize + layout::TLS64_ADDRESS_OF_CALLBACKS, 0, )?; - // A base relocation that writes into the field would turn the 0 - // into (part of) `delta` whenever the loader maps the copy away from - // its preferred base (Wine always does for DYNAMIC_BASE images), and - // the loader then reads callbacks from there. That is not only the - // field's own DIR64 entry: a HIGHLOW, HIGH, LOW or HIGHADJ entry, or - // a DIR64 entry a few bytes before it, patches some of its bytes - // too. Make every such entry a no-op. - let field_rva = tls - .directory_rva - .checked_add(layout::TLS64_ADDRESS_OF_CALLBACKS as u32) - .ok_or(PrepareError::Patch("TLS callback field RVA overflow"))?; - for reloc in relocations(&bytes, &info) { - if reloc.overlaps(field_rva, 8) { - for slot in 0..reloc.slots { - write_u16(&mut bytes, reloc.entry + 2 * slot, 0)?; // ABSOLUTE - } + // The field's base relocation would turn the 0 into `delta` whenever + // the loader maps the copy away from its preferred base (Wine always + // does for DYNAMIC_BASE images), and the loader then reads callbacks + // from there. Make that entry a no-op. + let field_rva = tls.directory_rva + layout::TLS64_ADDRESS_OF_CALLBACKS as u32; + for (entry, target) in dir64_relocations(&bytes, &info) { + if target == field_rva { + write_u16(&mut bytes, entry, 0)?; // IMAGE_REL_BASED_ABSOLUTE } } - // The parser reads the directory through `object`, which skips a - // section with no virtual size; `rva_to_file_offset` maps that - // section by its raw size. A damaged section table can make the two - // disagree, and then the write above lands somewhere else while the - // callbacks stay armed. The copy must never run them on its own. - if ImageInfo::parse(&bytes)? - .tls - .is_some_and(|tls| tls.callbacks_va != 0) - { - return Err(PrepareError::Patch( - "TLS callback pointer is not where the image was parsed from", - )); - } } Ok(PreparedImage { @@ -138,87 +116,22 @@ pub fn prepare(original: &[u8]) -> Result<PreparedImage, PrepareError> { /// Size of an IMAGE_IMPORT_DESCRIPTOR in the PE file. const IMPORT_DESCRIPTOR_SIZE: u32 = 20; -/// One base relocation entry that patches something. -#[derive(Debug, PartialEq, Eq)] -struct Relocation { - /// File offset of the entry. - entry: usize, - /// 16-bit slots it occupies: two for HIGHADJ, whose second slot holds - /// the low half of the adjusted value rather than an entry of its own. - slots: usize, - /// RVA it patches. - target: u32, - /// Bytes it writes at `target`. A type this table does not know is - /// taken to write a whole pointer. - width: u32, -} - -impl Relocation { - fn overlaps(&self, rva: u32, len: u32) -> bool { - let (start, end) = ( - u64::from(self.target), - u64::from(self.target) + u64::from(self.width), - ); - start < u64::from(rva) + u64::from(len) && u64::from(rva) < end - } -} - -/// Every base relocation that patches something (all but ABSOLUTE -/// padding). Empty if the image has no readable relocation table. -fn relocations(bytes: &[u8], info: &ImageInfo) -> Vec<Relocation> { +/// Every `IMAGE_REL_BASED_DIR64` base relocation: (file offset of its entry, +/// RVA it patches). Empty if the image has no readable relocation table. +fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> { + const DIR64: u16 = 10; + let mut out = Vec::new(); let Some(d) = layout::data_directory_offset(bytes, dir::BASERELOC) else { - return Vec::new(); + return out; }; let (Some(rva), Some(size)) = (layout::read_u32(bytes, d), layout::read_u32(bytes, d + 4)) else { - return Vec::new(); + return out; }; - if size == 0 { - return Vec::new(); - } - if let Some(start) = info.rva_to_file_offset(rva) { - let start = start as usize; - return relocation_entries(bytes, start, start.saturating_add(size as usize)); - } - // The loaders read the table wherever the directory points in the - // mapped image, and that includes the headers, which are mapped at the - // RVA equal to their file offset. A table there that went unread would - // leave the callback field's relocation armed. - match header_bytes(bytes) { - Some(headers) if (rva as usize) < headers => { - let start = rva as usize; - relocation_entries( - bytes, - start, - start.saturating_add(size as usize).min(headers), - ) - } - _ => Vec::new(), - } -} - -/// How many bytes at the start of the file are mapped as the headers: -/// `SizeOfHeaders`, but never more than the file holds. -fn header_bytes(bytes: &[u8]) -> Option<usize> { - let opt = layout::optional_header_offset(bytes)?; - let size = layout::read_u32(bytes, opt.checked_add(layout::OPT_SIZE_OF_HEADERS)?)?; - Some((size as usize).min(bytes.len())) -} - -/// The entries of the relocation blocks in `bytes[start..end]`, ABSOLUTE -/// padding left out. An entry whose target does not fit in an RVA (a -/// damaged block near the top of the address space) patches nothing the -/// image could hold, so it is left out rather than wrapped around to the -/// RVA of some other field. -fn relocation_entries(bytes: &[u8], start: usize, end: usize) -> Vec<Relocation> { - const ABSOLUTE: u16 = 0; - const HIGH: u16 = 1; - const LOW: u16 = 2; - const HIGHLOW: u16 = 3; - const HIGHADJ: u16 = 4; - const DIR64: u16 = 10; - let mut out = Vec::new(); - let mut at = start; + let Some(start) = info.rva_to_file_offset(rva).filter(|_| size != 0) else { + return out; + }; + let (mut at, end) = (start as usize, start as usize + size as usize); while at + 8 <= end { let (Some(page), Some(block)) = (layout::read_u32(bytes, at), layout::read_u32(bytes, at + 4)) @@ -229,35 +142,14 @@ fn relocation_entries(bytes: &[u8], start: usize, end: usize) -> Vec<Relocation> if block < 8 || at + block > end { break; } - let mut entry = at + 8; - while entry + 2 <= at + block { + for entry in (at + 8..at + block).step_by(2) { let Some(e) = bytes.get(entry..entry + 2) else { break; }; let e = u16::from_le_bytes([e[0], e[1]]); - let (kind, offset) = (e >> 12, u32::from(e & 0xFFF)); - let (width, slots) = match kind { - ABSOLUTE => (0, 1), - HIGH | LOW => (2, 1), - HIGHADJ => (2, 2), - HIGHLOW => (4, 1), - DIR64 => (8, 1), - _ => (8, 1), - }; - if kind != ABSOLUTE - && let Some(target) = page.checked_add(offset) - { - // A HIGHADJ whose parameter slot is past the block still - // has its own slot cleared, and only that one. - let slots = slots.min((at + block - entry) / 2); - out.push(Relocation { - entry, - slots, - target, - width, - }); + if e >> 12 == DIR64 { + out.push((entry, page + u32::from(e & 0xFFF))); } - entry += 2 * slots; } at += block; } @@ -301,9 +193,9 @@ mod tests { assert_eq!(tls.callbacks_va, 0); let field = tls.directory_rva + layout::TLS64_ADDRESS_OF_CALLBACKS as u32; assert!( - relocations(&prepared.bytes, &patched) + dir64_relocations(&prepared.bytes, &patched) .iter() - .all(|r| !r.overlaps(field, 8)), + .all(|&(_, target)| target != field), "the cleared callback pointer must not be relocated" ); } @@ -381,102 +273,6 @@ mod tests { ); } - /// One relocation block: page RVA, then its 16-bit entries. - fn block(page: u32, entries: &[u16]) -> Vec<u8> { - let mut b = page.to_le_bytes().to_vec(); - b.extend_from_slice(&(8 + 2 * entries.len() as u32).to_le_bytes()); - for e in entries { - b.extend_from_slice(&e.to_le_bytes()); - } - b - } - - /// (entry, slots, target, width) of each relocation, for comparing. - fn entries(bytes: &[u8], end: usize) -> Vec<(usize, usize, u32, u32)> { - relocation_entries(bytes, 0, end) - .into_iter() - .map(|r| (r.entry, r.slots, r.target, r.width)) - .collect() - } - - #[test] - fn relocation_entries_walk_blocks_and_skip_padding() { - // DIR64 at +0x10, an ABSOLUTE pad, a HIGHLOW at +0x20, a DIR64. - let mut bytes = block(0x1000, &[0xA010, 0x0000, 0x3020, 0xA018]); - bytes.extend(block(0x2000, &[0xA000, 0x0000])); - assert_eq!( - entries(&bytes, bytes.len()), - [ - (8, 1, 0x1010, 8), - (12, 1, 0x1020, 4), - (14, 1, 0x1018, 8), - (24, 1, 0x2000, 8) - ] - ); - // A block that claims more than the directory holds ends the walk. - let mut bytes = block(0x1000, &[0xA010, 0x0000]); - bytes[4] = 0x40; - assert!(relocation_entries(&bytes, 0, bytes.len()).is_empty()); - } - - #[test] - fn relocation_entries_know_each_width_and_the_highadj_parameter() { - // HIGH, LOW, HIGHADJ (its next slot is a parameter, here 0xA040, - // which must not be read as a DIR64 entry), then a type x64 loaders - // do not define, taken as pointer-wide. - let bytes = block(0x1000, &[0x1002, 0x2004, 0x4006, 0xA040, 0x5008, 0x0000]); - assert_eq!( - entries(&bytes, bytes.len()), - [ - (8, 1, 0x1002, 2), - (10, 1, 0x1004, 2), - (12, 2, 0x1006, 2), - (16, 1, 0x1008, 8) - ] - ); - // A HIGHADJ in the last slot of its block owns only that slot. - let bytes = block(0x1000, &[0xA010, 0x4006]); - assert_eq!( - entries(&bytes, bytes.len()), - [(8, 1, 0x1010, 8), (10, 1, 0x1006, 2)] - ); - } - - #[test] - fn a_relocation_overlaps_the_bytes_it_writes() { - let at = |target, width| Relocation { - entry: 0, - slots: 1, - target, - width, - }; - // An 8-byte field at 0x1118. - assert!(at(0x1118, 8).overlaps(0x1118, 8)); - assert!(at(0x1118, 4).overlaps(0x1118, 8)); - assert!(at(0x111C, 4).overlaps(0x1118, 8), "upper half"); - assert!(at(0x1110, 9).overlaps(0x1118, 8)); - assert!(at(0x111F, 2).overlaps(0x1118, 8)); - assert!(!at(0x1110, 8).overlaps(0x1118, 8), "ends where it starts"); - assert!(!at(0x1120, 8).overlaps(0x1118, 8), "starts where it ends"); - assert!(at(0xFFFF_FFFC, 8).overlaps(0xFFFF_FFF8, 8), "no wrap"); - } - - #[test] - fn relocation_entries_drop_targets_past_the_top_of_the_address_space() { - // A damaged page RVA near u32::MAX: page + offset does not fit, and - // wrapping it would name a low RVA (0x0 for 0xFFFF_FFF0 + 0x10) that - // belongs to some other field. Entries whose target fits are kept. - let bytes = block(0xFFFF_F000, &[0xA000, 0xAFFF, 0x0000]); - assert_eq!( - entries(&bytes, bytes.len()), - [(8, 1, 0xFFFF_F000, 8), (10, 1, 0xFFFF_FFFF, 8)] - ); - let bytes = block(0xFFFF_FFF0, &[0xA00F, 0xA010, 0xAFFF]); - assert_eq!(entries(&bytes, bytes.len()), [(8, 1, 0xFFFF_FFFF, 8)]); - // An end past the buffer stops at the bytes there are. - assert_eq!(relocation_entries(&bytes, 0, usize::MAX).len(), 1); - } - #[test] fn file_name_is_stable_per_build() { let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); diff --git a/crates/victory-loader/src/resolution.rs b/crates/victory-loader/src/resolution.rs new file mode 100644 index 0000000000..8e0dc137c8 --- /dev/null +++ b/crates/victory-loader/src/resolution.rs @@ -0,0 +1,445 @@ +//! The title's output size and render scale (`VICTORY_OUTPUT`, +//! `VICTORY_TITLE_SCALE`, `VICTORY_FFX_SCALE`, `VICTORY_UPSCALER`; each off +//! without it): places +//! in the title's code changed at load, each compared byte for byte first +//! and left alone, said so, if it differs (another build of the title). +//! +//! What the title does (game_scarlett_master.exe 1.0.2.1, image offsets): +//! +//! - **Output size.** Its settings (`settings.xml` in its storage, +//! `video/resolutionFullscreen`, 3840x2160 as a Series X wrote it; read +//! into the live settings at +0x204/+0x208, the defaults' 1920x1080 at +//! +0x5b37a20 overwritten) are applied by +0x22434a0: from +0x224352b it +//! hands them to +0x2478130, the one writer of the screen size +//! (+0xa9438cc/+0xa9438d0), and when the height changes calls +0xd8c3a0. +//! The back buffers (+0x247ad10, by +0x501f4a0 and +0xcc2780) take that +//! size through the copy +0x5eb24f0 makes (+0x75e6fe0). The display mode +//! list it matches against is its own (+0x5a38910: 1280x720, 1664x936, +//! 1920x1080, 2560x1440, 3840x2160 at 60 Hz, table +0x615c0c0), not the +//! DXGI output's, which is why `VICTORY_DISPLAY_MODE` changes nothing. +//! Here that block becomes: write the size asked for into the settings +//! (+0x204/+0x208), then the title's own else-path (screen size set, +//! +0xd8c3a0 if the height changed). Everything that reads the settings +//! after it (the device parameters +0x1e0fb30, the render size +0x7b4e10) +//! sees the same size. The back buffers' pool (64 MB on Series X) is +//! checked to be used up but for 2 MB (+0x247af25, an `int3`); for another +//! size that check is jumped over. +//! - **Render scale.** The upscaler the title picks (+0x7e93f0: 6, its own, +//! except on Series S with a flag, 7, AMD FidelityFX) gives the render +//! size from the output size (+0x7e92f0 → the upscaler's +0x50 method): +//! its own (+0x7e9440) multiplies by a scale at +0x90 of it, set to 2/3 at +//! +0x28f1e78 (so 2560x1440 for 4K, 1280x720 for 1080p); +//! `VICTORY_TITLE_SCALE` replaces that constant (Series X; run res-4 at +//! 1.0). FidelityFX's (+0x28ef680, Series S) multiplies by 1.0 on Series X, +//! 2/3 on Series S; `VICTORY_FFX_SCALE` points its two loads at a constant +//! in its padding (as pull request #53 did). That one is not safe: at 0.5 +//! on Series S (run res-6) FidelityFX's jitter phase count came back 0 and +//! the title divided by it (+0x28f03e8) 49 s in. +//! - **Upscaler.** `VICTORY_UPSCALER=<kind>` makes the picker return +//! `kind` (pull request #53): 6 the title's own, 7 FidelityFX. +//! +//! Taken from avatarmanz/VIctory-7900XTX (merge f63b4b1, commits e151e71 and +//! 45cad4c, "port/res"; GPL-3.0-or-later) for VIctory Try 6.9. Their render +//! scale switch is `VICTORY_TITLE_SCALE` here: this fork's own render scale +//! switch (50-100) is the host's. In this fork `VICTORY_DISPLAY_MODE` (the +//! DXGI output's modes) is what Try 6.8's low preset set, and as the notes +//! above say the title does not follow it: `VICTORY_OUTPUT` is what changes +//! its size. + +/// What became of a site. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Patched { + Done, + /// Its bytes are not the ones expected: left alone. + Differs, + Failed(&'static str), +} + +/// Sizes the title has a display mode for (its own list, +0x615c0c0). +pub const MODES: [(u32, u32); 5] = [(1280, 720), (1664, 936), (1920, 1080), (2560, 1440), (3840, 2160)]; + +/// `VICTORY_OUTPUT=<w>x<h>`: one of [`MODES`]. `None` if unset or not one +/// (said why). +pub fn asked_output() -> Option<(u32, u32)> { + let spec = std::env::var("VICTORY_OUTPUT").ok()?; + let size = parse_output(&spec); + if size.is_none() { + eprintln!("VIctory: VICTORY_OUTPUT={spec}: expected one of the title's modes: 1920x1080, 2560x1440, 1280x720, 1664x936, 3840x2160"); + } + size +} + +pub fn parse_output(spec: &str) -> Option<(u32, u32)> { + let (w, h) = spec.trim().split_once(['x', 'X'])?; + let size = (w.trim().parse().ok()?, h.trim().parse().ok()?); + MODES.contains(&size).then_some(size) +} + +/// `VICTORY_TITLE_SCALE=<s>`, 0.5 to 1.0 (0.5: half the output's width and +/// height): the title's own upscaler's scale (Series X; 2/3 without it). +/// Tested at 1.0 (run res-4); below 2/3 the title's largest render size +/// (+0x94, max(2/3, scale)) stays at 2/3. `None` if unset or out of range +/// (said why). +pub fn asked_render_scale() -> Option<f32> { + let spec = std::env::var("VICTORY_TITLE_SCALE").ok()?; + let scale = parse_render_scale(&spec); + if scale.is_none() { + eprintln!("VIctory: VICTORY_TITLE_SCALE={spec}: expected 0.5 to 1.0"); + } + scale +} + +pub fn parse_render_scale(spec: &str) -> Option<f32> { + spec.trim().parse::<f32>().ok().filter(|s| (0.5..=1.0).contains(s)) +} + +/// `VICTORY_FFX_SCALE=<s>`, 0.5 to 1.0: FidelityFX's render scale (Series +/// S). Crashed at 0.5 (run res-6); see the module's notes. +pub fn asked_ffx_scale() -> Option<f32> { + let spec = std::env::var("VICTORY_FFX_SCALE").ok()?; + let scale = parse_render_scale(&spec); + if scale.is_none() { + eprintln!("VIctory: VICTORY_FFX_SCALE={spec}: expected 0.5 to 1.0"); + } + scale +} + +/// `VICTORY_UPSCALER=<kind>`: 6 (the title's own) or 7 (FidelityFX). +pub fn asked_upscaler() -> Option<u32> { + let spec = std::env::var("VICTORY_UPSCALER").ok()?; + let kind = spec.trim().parse::<u32>().ok().filter(|k| matches!(k, 6 | 7)); + if kind.is_none() { + eprintln!("VIctory: VICTORY_UPSCALER={spec}: expected 6 (the title's own) or 7 (FidelityFX)"); + } + kind +} + +/// A place to change: its offset in the image and the bytes there +/// (compared first; the replacement is at most as long). +pub struct Site { + pub at: usize, + pub what: &'static str, + pub bytes: &'static [u8], +} + +/// The screen size setter, its screen height, and what +0x22434a0 calls when +/// the height changed. +pub const SET_SCREEN_SIZE: usize = 0x2478130; +pub const SCREEN_HEIGHT: usize = 0xa9438d0; +pub const HEIGHT_CHANGED: usize = 0xd8c3a0; + +/// +0x22434a0 from +0x224352b to +0x2243568: the settings' size handed to +/// the screen size. +pub const OUTPUT: Site = Site { + at: 0x224352b, + what: "settings' output size applied", + bytes: &[ + 0x8b, 0x0d, 0x9b, 0x03, 0x70, 0x08, // mov ecx, [+0xa9438cc] + 0x8b, 0x86, 0x04, 0x02, 0x00, 0x00, // mov eax, [rsi+204h] + 0x39, 0xc1, 0x75, 0x0d, // cmp ecx, eax ; jne + 0x8b, 0x96, 0x08, 0x02, 0x00, 0x00, // mov edx, [rsi+208h] + 0xe8, 0xea, 0x4b, 0x23, 0x00, 0xeb, 0x20, // call +0x2478130 ; jmp +0x2243568 + 0x8b, 0xbe, 0x08, 0x02, 0x00, 0x00, // mov edi, [rsi+208h] + 0x8b, 0x2d, 0x7c, 0x03, 0x70, 0x08, // mov ebp, [+0xa9438d0] + 0x89, 0xc1, 0x89, 0xfa, // mov ecx, eax ; mov edx, edi + 0xe8, 0xd3, 0x4b, 0x23, 0x00, // call +0x2478130 + 0x39, 0xfd, 0x74, 0x07, 0xb1, 0x01, // cmp ebp, edi ; je ; mov cl, 1 + 0xe8, 0x38, 0x8e, 0xb4, 0xfe, // call +0xd8c3a0 + ], +}; + +/// +0x247ad10, after the back buffers are made in their pool (64 MB on +/// Series X, 82 MB on Series S, from +0x247ad45): `int3` unless less than +/// 2 MB of the pool is left over. Sized for 3840x2160; at 1920x1080 49 MB +/// are left (run res-1 stopped here). With another output size the check +/// becomes a jump over the `int3`; the pool stays as large. +pub const POOL_CHECK: Site = Site { + at: 0x247af25, + what: "back buffer pool's left-over check", + bytes: &[0x48, 0x3d, 0xff, 0xff, 0x1f, 0x00, 0x76, 0x01, 0xcc], // cmp rax, 1FFFFFh ; jbe +1 ; int3 +}; + +/// What goes at [`POOL_CHECK`]: `jmp +1` in place of `jbe +1`. +pub fn pool_check_code() -> Vec<u8> { + let mut c = POOL_CHECK.bytes[..8].to_vec(); + c[6] = 0xeb; + c +} + +/// The title's own upscaler, its method +0x28f1e70: `mov dword [rcx+90h], +/// 2/3` (the scale +0x7e9440 renders at). +pub const OWN_SCALE: Site = Site { + at: 0x28f1e78, + what: "the title's own upscaler's render scale", + bytes: &[0xc7, 0x81, 0x90, 0x00, 0x00, 0x00, 0xab, 0xaa, 0x2a, 0x3f], +}; + +/// FidelityFX's render size method, +0x28ef680, and its padding: the scale +/// is 1.0 (+0x5fc6ed8) or, on Series S, 2/3 (+0x615d95c), loaded at +0x28 +/// and +0x32. +pub const FFX_SCALE: Site = Site { + at: 0x28ef680, + what: "FidelityFX's render scale", + bytes: &[ + 0x41, 0x56, 0x56, 0x57, 0x53, 0x48, 0x83, 0xec, 0x28, 0x44, 0x89, 0xcb, 0x4c, 0x89, 0xc6, 0x48, 0x89, 0xd7, 0x49, 0x89, + 0xce, 0xe8, 0xa6, 0x5a, 0x78, 0xfd, 0x0f, 0xb6, 0xc0, 0x41, 0x89, 0x86, 0x90, 0x00, 0x00, 0x00, 0x84, 0xc0, 0x75, 0x0a, + 0xc5, 0xfa, 0x10, 0x05, 0x28, 0x78, 0x6d, 0x03, 0xeb, 0x08, 0xc5, 0xfa, 0x10, 0x05, 0xa2, 0xe2, 0x86, 0x03, 0xc5, 0xf2, + 0x2a, 0x54, 0x24, 0x70, 0xc5, 0xf2, 0x2a, 0xcb, 0xc5, 0xfa, 0x59, 0xc9, 0xc5, 0xfa, 0x2c, 0xc1, 0x89, 0x07, 0xc5, 0xfa, + 0x59, 0xc2, 0xc5, 0xfa, 0x2c, 0xc0, 0x89, 0x06, 0x48, 0x83, 0xc4, 0x28, 0x5b, 0x5f, 0x5e, 0x41, 0x5e, 0xc3, 0xcc, 0xcc, + 0xcc, 0xcc, 0xcc, 0xcc, + ], +}; + +/// The upscaler picker, +0x7e93f0, to its first `ret`. +pub const PICKER: Site = Site { + at: 0x7e93f0, + what: "upscaler picker", + bytes: &[ + 0x48, 0x83, 0xec, 0x28, 0x80, 0x3d, 0x6d, 0xf0, 0x3a, 0x07, 0x00, 0x75, 0x09, 0x83, 0x3d, 0x68, 0xf0, 0x3a, 0x07, 0x00, + 0x74, 0x28, 0xe8, 0x35, 0xbd, 0x88, 0xff, 0x8a, 0x0d, 0x5b, 0xf0, 0x3a, 0x07, 0x80, 0xe1, 0x40, 0x80, 0xf9, 0x01, 0xb9, + 0x07, 0x00, 0x00, 0x00, 0x83, 0xd9, 0x00, 0x84, 0xc0, 0xb8, 0x06, 0x00, 0x00, 0x00, 0x0f, 0x45, 0xc1, 0x48, 0x83, 0xc4, + 0x28, 0xc3, + ], +}; + +/// `rel32` from the end of an instruction at image offset `next` to `to`. +fn rel(to: usize, next: usize) -> [u8; 4] { + ((to as i64 - next as i64) as i32).to_le_bytes() +} + +/// What goes at [`OUTPUT`] for `width` x `height` (the same length). +pub fn output_code(width: u32, height: u32) -> Vec<u8> { + let at = OUTPUT.at; + let mut c = Vec::with_capacity(OUTPUT.bytes.len()); + c.push(0xb8); // mov eax, width + c.extend(width.to_le_bytes()); + c.extend([0x89, 0x86, 0x04, 0x02, 0x00, 0x00]); // mov [rsi+204h], eax + c.push(0xbf); // mov edi, height + c.extend(height.to_le_bytes()); + c.extend([0x89, 0xbe, 0x08, 0x02, 0x00, 0x00]); // mov [rsi+208h], edi + c.extend([0x8b, 0x2d]); // mov ebp, [screen height] + c.extend(rel(SCREEN_HEIGHT, at + c.len() + 4)); + c.extend([0x89, 0xc1, 0x89, 0xfa]); // mov ecx, eax ; mov edx, edi + c.push(0xe8); // call the setter + c.extend(rel(SET_SCREEN_SIZE, at + c.len() + 4)); + let end = OUTPUT.bytes.len(); + c.extend([0x39, 0xfd, 0x74, (end - (c.len() + 4)) as u8]); // cmp ebp, edi ; je end + c.extend([0xb1, 0x01, 0xe8]); // mov cl, 1 ; call + c.extend(rel(HEIGHT_CHANGED, at + c.len() + 4)); + c.extend([0xeb, (end - (c.len() + 2)) as u8]); // jmp end + c.resize(end, 0xcc); + c +} + +/// What goes at [`OWN_SCALE`] for `scale`. +pub fn own_scale_code(scale: f32) -> Vec<u8> { + let mut c = OWN_SCALE.bytes[..6].to_vec(); + c.extend(scale.to_le_bytes()); + c +} + +/// What goes at [`FFX_SCALE`] for `scale`: both loads read `scale`, written +/// into the padding at +0x64. +pub fn ffx_scale_code(scale: f32) -> Vec<u8> { + const LOADS: [usize; 2] = [0x28, 0x32]; + const SLOT: usize = 0x64; + let mut c = FFX_SCALE.bytes.to_vec(); + c[SLOT..SLOT + 4].copy_from_slice(&scale.to_le_bytes()); + for l in LOADS { + c[l + 4..l + 8].copy_from_slice(&((SLOT - (l + 8)) as i32).to_le_bytes()); + } + c +} + +/// `mov eax, kind ; ret`. +pub fn picker_code(kind: u32) -> Vec<u8> { + let mut c = vec![0xb8]; + c.extend(kind.to_le_bytes()); + c.push(0xc3); + c +} + +/// Compares `site`'s bytes in the image of `size` bytes at `base`. +/// +/// # Safety +/// The image is mapped. +pub unsafe fn matches(base: usize, size: usize, site: &Site) -> Patched { + if site.at.checked_add(site.bytes.len()).is_none_or(|end| end > size) { + return Patched::Failed("outside the image"); + } + // SAFETY: inside the mapped image (checked above). + let there = unsafe { std::slice::from_raw_parts((base + site.at) as *const u8, site.bytes.len()) }; + if there == site.bytes { Patched::Done } else { Patched::Differs } +} + +/// Writes `code` over `site` if its bytes are the expected ones. +/// +/// # Safety +/// The image stays mapped and no thread runs its code yet. +#[cfg(windows)] +pub unsafe fn write(base: usize, size: usize, site: &Site, code: &[u8]) -> Patched { + use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; + use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if code.len() > site.bytes.len() { + return Patched::Failed("replacement longer than the bytes compared"); + } + // SAFETY: the caller's promise. + let found = unsafe { matches(base, size, site) }; + if found != Patched::Done { + return found; + } + let at = base + site.at; + let mut old = 0; + // SAFETY: inside the image (checked); made writable for this and put + // back; nothing runs it yet. + unsafe { + if VirtualProtect(at as *const _, code.len(), PAGE_EXECUTE_READWRITE, &mut old) == 0 { + return Patched::Failed("Windows would not make it writable"); + } + std::ptr::copy_nonoverlapping(code.as_ptr(), at as *mut u8, code.len()); + VirtualProtect(at as *const _, code.len(), old, &mut old); + FlushInstructionCache(GetCurrentProcess(), at as *const _, code.len()); + } + Patched::Done +} + +/// Applies what the switches ask for; a line each in the log and on +/// standard output. +/// +/// # Safety +/// The image of `size` bytes at `base` stays mapped and no thread runs its +/// code yet. +#[cfg(windows)] +pub unsafe fn apply_asked(base: usize, size: usize) { + let mut asked: Vec<(&Site, Vec<u8>, String)> = Vec::new(); + if let Some((w, h)) = asked_output() { + asked.push((&OUTPUT, output_code(w, h), format!("{w}x{h}"))); + if (w, h) != (3840, 2160) { + asked.push((&POOL_CHECK, pool_check_code(), format!("{w}x{h}"))); + } + } + if let Some(s) = asked_render_scale() { + asked.push((&OWN_SCALE, own_scale_code(s), format!("{s}"))); + } + if let Some(s) = asked_ffx_scale() { + asked.push((&FFX_SCALE, ffx_scale_code(s), format!("{s}"))); + } + if let Some(kind) = asked_upscaler() { + asked.push((&PICKER, picker_code(kind), format!("returns {kind}"))); + } + for (site, code, value) in asked { + // SAFETY: the caller's promise. + let done = unsafe { write(base, size, site, &code) }; + let offset = format!("{:#x}", site.at); + match done { + Patched::Done => tracing::info!(site = %offset, what = site.what, value, "resolution: patched"), + Patched::Differs => tracing::warn!(site = %offset, what = site.what, "resolution: not patched, the title's bytes there are not the ones expected (another build?)"), + Patched::Failed(why) => tracing::warn!(site = %offset, what = site.what, why, "resolution: not patched"), + } + println!("resolution: {} ({value}) at title+{offset}: {done:?}", site.what); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn switches_parse() { + assert_eq!(parse_output("1920x1080"), Some((1920, 1080))); + assert_eq!(parse_output(" 2560X1440 "), Some((2560, 1440))); + assert_eq!(parse_output("1600x900"), None); + assert_eq!(parse_output("1080p"), None); + assert_eq!(parse_render_scale("0.67"), Some(0.67)); + assert_eq!(parse_render_scale("0.5"), Some(0.5)); + assert_eq!(parse_render_scale("1"), Some(1.0)); + assert_eq!(parse_render_scale("0.4"), None); + assert_eq!(parse_render_scale("1.5"), None); + } + + /// The calls and loads in the bytes compared are the ones the + /// replacement keeps. + #[test] + fn the_output_block_is_the_titles() { + let b = OUTPUT.bytes; + assert_eq!(b.len(), 61); + let target = |op_end: usize| (OUTPUT.at + op_end) as i64 + i64::from(i32::from_le_bytes(b[op_end - 4..op_end].try_into().unwrap())); + assert_eq!(target(27), SET_SCREEN_SIZE as i64); + assert_eq!(target(50), SET_SCREEN_SIZE as i64); + assert_eq!(target(61), HEIGHT_CHANGED as i64); + assert_eq!(target(41), SCREEN_HEIGHT as i64); + assert_eq!(target(6), (SCREEN_HEIGHT - 4) as i64, "the width before it"); + // jne to the else path at 29; jmp +0x20 and je +7 both land at the end. + assert_eq!((b[14], 16 + b[15] as usize), (0x75, 29)); + assert_eq!((b[27], 29 + b[28] as usize), (0xeb, 61)); + assert_eq!((b[52], 54 + b[53] as usize), (0x74, 61)); + } + + #[test] + fn the_output_code_keeps_the_titles_else_path() { + let c = output_code(1920, 1080); + assert_eq!(c.len(), OUTPUT.bytes.len()); + assert_eq!(c[0], 0xb8); + assert_eq!(c[1..5], 1920u32.to_le_bytes()); + assert_eq!(c[5..11], [0x89, 0x86, 0x04, 0x02, 0x00, 0x00]); + assert_eq!(c[12..16], 1080u32.to_le_bytes()); + assert_eq!(c[16..22], [0x89, 0xbe, 0x08, 0x02, 0x00, 0x00]); + let target = |op_end: usize| (OUTPUT.at + op_end) as i64 + i64::from(i32::from_le_bytes(c[op_end - 4..op_end].try_into().unwrap())); + assert_eq!(c[22..24], [0x8b, 0x2d]); + assert_eq!(target(28), SCREEN_HEIGHT as i64); + assert_eq!(c[32], 0xe8); + assert_eq!(target(37), SET_SCREEN_SIZE as i64); + assert_eq!(c[37..40], [0x39, 0xfd, 0x74]); + assert_eq!(41 + c[40] as usize, 61, "je lands at the end"); + assert_eq!(c[43], 0xe8); + assert_eq!(target(48), HEIGHT_CHANGED as i64); + assert_eq!(c[48], 0xeb); + assert_eq!(50 + c[49] as usize, 61, "jmp lands at the end"); + assert!(c[50..].iter().all(|&x| x == 0xcc)); + } + + #[test] + fn the_scale_codes() { + let own = own_scale_code(0.5); + assert_eq!(own[..6], OWN_SCALE.bytes[..6]); + assert_eq!(own[6..], 0.5f32.to_le_bytes()); + assert_eq!(OWN_SCALE.bytes[6..], (2.0f32 / 3.0).to_le_bytes()); + let ffx = ffx_scale_code(0.75); + assert_eq!(ffx.len(), FFX_SCALE.bytes.len()); + assert_eq!(ffx[0x64..0x68], 0.75f32.to_le_bytes()); + for at in [0x28, 0x32] { + assert_eq!(ffx[at..at + 4], [0xc5, 0xfa, 0x10, 0x05], "vmovss xmm0, [rip+d]"); + let disp = i32::from_le_bytes(ffx[at + 4..at + 8].try_into().unwrap()); + assert_eq!(at as i32 + 8 + disp, 0x64); + } + // Only the two displacements and the padding change. + let changed: Vec<usize> = (0..ffx.len()).filter(|&i| ffx[i] != FFX_SCALE.bytes[i]).collect(); + assert!(changed.iter().all(|&i| (0x2c..0x30).contains(&i) || (0x36..0x3a).contains(&i) || (0x64..0x68).contains(&i))); + assert_eq!(picker_code(7), [0xb8, 7, 0, 0, 0, 0xc3]); + assert_eq!(pool_check_code(), [0x48, 0x3d, 0xff, 0xff, 0x1f, 0x00, 0xeb, 0x01]); + } + + #[cfg(windows)] + #[test] + fn a_site_is_written_only_over_its_bytes() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READ, VirtualAlloc, VirtualFree}; + // SAFETY: fresh memory of our own, read-only to code as the image's is. + unsafe { + let place = VirtualAlloc(std::ptr::null(), 0x1000, MEM_COMMIT | MEM_RESERVE, 0x40) as *mut u8; + assert!(!place.is_null()); + let site = Site { at: 0x100, what: "test", bytes: OWN_SCALE.bytes }; + std::ptr::copy_nonoverlapping(site.bytes.as_ptr(), place.add(0x100), site.bytes.len()); + let mut old = 0; + windows_sys::Win32::System::Memory::VirtualProtect(place.cast(), 0x1000, PAGE_EXECUTE_READ, &mut old); + assert_eq!(write(place as usize, 0x1000, &site, &own_scale_code(0.5)), Patched::Done); + assert_eq!(std::slice::from_raw_parts(place.add(0x106), 4), 0.5f32.to_le_bytes()); + // Already changed: its bytes differ now, nothing is written again. + assert_eq!(write(place as usize, 0x1000, &site, &own_scale_code(0.75)), Patched::Differs); + assert_eq!(std::slice::from_raw_parts(place.add(0x106), 4), 0.5f32.to_le_bytes()); + let far = Site { at: 0xffa, what: "test", bytes: OWN_SCALE.bytes }; + assert!(matches!(write(place as usize, 0x1000, &far, &own_scale_code(0.5)), Patched::Failed(_))); + VirtualFree(place.cast(), 0, MEM_RELEASE); + } + } +} diff --git a/crates/victory-loader/src/stacks.rs b/crates/victory-loader/src/stacks.rs index 214dda908e..1d309109cb 100644 --- a/crates/victory-loader/src/stacks.rs +++ b/crates/victory-loader/src/stacks.rs @@ -27,30 +27,21 @@ pub fn dump_stacks_on_schedule() { let Ok(list) = std::env::var("VICTORY_STACKS") else { return; }; - let times = schedule(&list); + let mut times: Vec<f64> = list + .split(',') + .filter_map(|t| t.trim().parse().ok()) + .collect(); + times.sort_by(f64::total_cmp); let start = std::time::Instant::now(); std::thread::spawn(move || { - for at in times { + for t in times { + let at = std::time::Duration::from_secs_f64(t.max(0.0)); std::thread::sleep(at.saturating_sub(start.elapsed())); dump_stacks(); } }); } -/// The times in a `VICTORY_STACKS` list (seconds, comma-separated), in -/// order. Negative times are now; times no `Duration` holds (`inf`, `NaN`, -/// `1e20`) are left out instead of panicking the dump thread. -fn schedule(list: &str) -> Vec<std::time::Duration> { - let mut times: Vec<_> = list - .split(',') - .filter_map(|t| t.trim().parse::<f64>().ok()) - .filter(|t| !t.is_nan()) - .filter_map(|t| std::time::Duration::try_from_secs_f64(t.max(0.0)).ok()) - .collect(); - times.sort(); - times -} - /// `THREAD_BASIC_INFORMATION` (ntddk). #[repr(C)] struct BasicInfo { @@ -134,12 +125,6 @@ fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32)) { priority: 0, base_priority: 0, }; - // Suspended first: a running thread may exit and free its TEB between - // the query and the read below. - // SAFETY: a thread of this process that is not this one. - if unsafe { SuspendThread(thread) } == u32::MAX { - return (frames, (0, 0)); - } // SAFETY: writes `info`, whose layout and size are the system's. let status = unsafe { NtQueryInformationThread( @@ -151,20 +136,21 @@ fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32)) { ) }; if status != 0 || info.teb.is_null() { - // SAFETY: suspended above. - unsafe { ResumeThread(thread) }; return (frames, (0, 0)); } - // SAFETY: the TEB of a suspended thread of this process: its NT_TIB - // holds the stack base at +8 and the stack limit at +0x10. + // SAFETY: the TEB of a live thread of this process: its NT_TIB holds + // the stack base at +8 and the stack limit at +0x10. let (high, low) = unsafe { (info.teb.add(1).read(), info.teb.add(2).read()) }; // SAFETY: zeroed is a valid CONTEXT. let mut context = Aligned(unsafe { std::mem::zeroed() }); context.0.ContextFlags = CONTEXT_FULL_AMD64; - // SAFETY: reads and resumes the thread suspended above; nothing until - // the resume allocates or takes a lock the thread could hold besides - // the unwinder's own. + // SAFETY: suspends, reads and resumes a thread that is not this one; + // nothing between suspend and resume allocates or takes a lock the + // thread could hold besides the unwinder's own. unsafe { + if SuspendThread(thread) == u32::MAX { + return (frames, (info.priority, info.base_priority)); + } if GetThreadContext(thread, &mut context.0) != 0 { unwind_into(context.0, low, high, &mut frames); } @@ -235,18 +221,4 @@ mod tests { stop_tx.send(()).unwrap(); parked.join().unwrap(); } - - /// Times no `Duration` holds are left out instead of panicking the dump - /// thread (`from_secs_f64` panicked on `inf`); the rest come in order. - #[test] - fn schedules_skip_times_out_of_range() { - let secs = |list| { - schedule(list) - .iter() - .map(|d| d.as_secs_f64()) - .collect::<Vec<_>>() - }; - assert_eq!(secs("30, 5,x,-2,inf,NaN,1e20"), [0.0, 5.0, 30.0]); - assert!(schedule("").is_empty()); - } } diff --git a/crates/victory-loader/src/threads.rs b/crates/victory-loader/src/threads.rs index a7a85d0486..903aebd4cf 100644 --- a/crates/victory-loader/src/threads.rs +++ b/crates/victory-loader/src/threads.rs @@ -164,8 +164,8 @@ fn end_other_threads(keep: &[u32]) { CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, }; use windows_sys::Win32::System::Threading::{ - GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_QUERY_INFORMATION, - THREAD_TERMINATE, TerminateThread, + GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_TERMINATE, TerminateThread, + THREAD_QUERY_INFORMATION, }; // SAFETY: plain queries of the calling process and thread. let (process, me) = unsafe { (GetCurrentProcessId(), GetCurrentThreadId()) }; @@ -323,10 +323,7 @@ impl OwnTls { /// title callbacks. fn started_by_rust() -> bool { // SAFETY: the calling thread's pseudo handle. - starts_in( - unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, - c"", - ) + starts_in(unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, c"") } /// Whether `thread`'s start routine lies in the module named `module` diff --git a/crates/victory-loader/src/tls.rs b/crates/victory-loader/src/tls.rs index 317b5aee6e..3f65dd2306 100644 --- a/crates/victory-loader/src/tls.rs +++ b/crates/victory-loader/src/tls.rs @@ -78,14 +78,11 @@ pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result<usize> { fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize { let mut count = 0; let mut i = 0; - // The scan jumps between offsets that start like a load instead of - // testing the whole pattern at every byte. - while let Some(next) = next_candidate(code, i) { - i = next; + while i + LOAD_LEN <= code.len() { let c = &code[i..i + LOAD_LEN]; let rex = c[1]; let reg = usize::from((c[3] >> 3) & 7) | if rex & 4 != 0 { 8 } else { 0 }; - // shortcut: a byte match, not a decode. In Grand Theft Auto VI all + // shortcut: a byte match, not a decode. In the title all // 53,246 hits are instruction starts and none is missed (checked // against a full disassembly); decode .text if a title shows one. if c[0] == 0x65 @@ -108,49 +105,6 @@ fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize { count } -/// The `gs` segment prefix that starts every TLS-array load. -const GS: u8 = 0x65; - -/// The first offset from `from` where a load could start: a whole load's -/// room, `gs` at the offset, `mov` (8B) two bytes on and the `[disp32]` -/// SIB byte (25) four on, so `patch` tests the rest of the pattern only -/// there. Sixteen offsets at a time with SSE2, which every x86-64 has. -fn next_candidate(code: &[u8], from: usize) -> Option<usize> { - // One past the last offset a whole load fits at. - let end = (code.len() + 1).checked_sub(LOAD_LEN)?; - let mut i = from; - #[cfg(target_arch = "x86_64")] - { - use std::arch::x86_64::{ - __m128i, _mm_and_si128, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, - _mm_set1_epi8, - }; - // SAFETY: SSE2 is part of x86-64. Each load reads 16 bytes from - // `i`, `i + 2` or `i + 4`, which end by `i + 20 <= end + 4`, inside - // the code (`end + LOAD_LEN - 1` is its length). - unsafe { - let at = |k: usize| _mm_loadu_si128(code.as_ptr().add(k).cast::<__m128i>()); - let (gs, mov, sib) = ( - _mm_set1_epi8(GS as i8), - _mm_set1_epi8(0x8B_u8 as i8), - _mm_set1_epi8(0x25), - ); - while i + 16 <= end { - let hits = _mm_and_si128( - _mm_and_si128(_mm_cmpeq_epi8(at(i), gs), _mm_cmpeq_epi8(at(i + 2), mov)), - _mm_cmpeq_epi8(at(i + 4), sib), - ); - let mask = _mm_movemask_epi8(hits); - if mask != 0 { - return Some(i + mask.trailing_zeros() as usize); - } - i += 16; - } - } - } - (i..end).find(|&j| code[j] == GS) -} - /// Fills `block` with one thunk per register: `mov r, gs:[0x58]; /// lea r, [r + index * 8]; ret` (flags untouched, like the load it replaces). fn thunks(block: *mut u8, index: u32) -> Result<usize> { @@ -228,150 +182,6 @@ mod tests { array } - /// The byte-at-a-time scan `patch` had before it searched for - /// candidates: the reference its results must match exactly. - fn patch_bytewise(code: &mut [u8], at: usize, thunks: usize) -> usize { - let mut count = 0; - let mut i = 0; - while i + LOAD_LEN <= code.len() { - let c = &code[i..i + LOAD_LEN]; - let rex = c[1]; - let reg = usize::from((c[3] >> 3) & 7) | if rex & 4 != 0 { 8 } else { 0 }; - if c[0] == 0x65 - && (rex == 0x48 || rex == 0x4C) - && c[2] == 0x8B - && c[3] & 0xC7 == 0x04 - && c[4..] == [0x25, 0x58, 0, 0, 0] - && reg != 4 - { - let rel = (thunks + reg * THUNK_SIZE) as i64 - (at + i + 5) as i64; - code[i] = 0xE8; - code[i + 1..i + 5].copy_from_slice(&(rel as i32).to_le_bytes()); - code[i + 5..i + 9].copy_from_slice(&[0x0F, 0x1F, 0x40, 0x00]); - count += 1; - i += LOAD_LEN; - } else { - i += 1; - } - } - count - } - - /// xorshift64*: reproducible bytes without a dependency. - struct Rng(u64); - - impl Rng { - fn next(&mut self) -> u64 { - self.0 ^= self.0 >> 12; - self.0 ^= self.0 << 25; - self.0 ^= self.0 >> 27; - self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) - } - } - - /// `len` bytes of noise, rich in `gs` prefixes, with `loads` TLS-array - /// loads (and near misses of them) written at random offsets: any REX - /// or ModRM, so some are refused, and some overlapping one another. - fn code_with_loads(rng: &mut Rng, len: usize, loads: usize) -> Vec<u8> { - let mut code: Vec<u8> = (0..len) - .map(|_| match rng.next() % 16 { - 0 => GS, - _ => rng.next() as u8, - }) - .collect(); - for _ in 0..loads { - let Some(room) = len.checked_sub(LOAD_LEN - 1) else { - break; - }; - let at = (rng.next() as usize) % room.max(1); - let r = rng.next(); - let rex = [0x48, 0x4C, 0x49, 0x65][(r & 3) as usize]; - let modrm = (r >> 8) as u8 & 0x3F | [0x04, 0x44][(r >> 16 & 1) as usize] & 0xC7; - let mut load = [GS, rex, 0x8B, modrm, 0x25, 0x58, 0, 0, 0]; - if r >> 20 & 7 == 0 { - // A near miss in one byte of the tail. - load[4 + (r >> 24) as usize % 5] ^= 1; - } - let n = load.len().min(len - at); - code[at..at + n].copy_from_slice(&load[..n]); - } - code - } - - #[test] - fn candidate_search_patches_exactly_what_the_bytewise_scan_does() { - let mut rng = Rng(0x9E37_79B9_7F4A_7C15); - let (at, thunks) = (0x1_4000_0000, 0x1_3FFF_0000); - let mut patched = 0; - for len in (0..64).chain([255, 256, 257, 4093, 4096, 65_537]) { - for round in 0..40 { - let loads = (len / LOAD_LEN).min(round * 3); - let code = code_with_loads(&mut rng, len, loads); - // Every offset too, so each word alignment of the search - // is covered. - let shift = round % 8; - let (mut fast, mut slow) = (code.clone(), code.clone()); - let n = patch(&mut fast[shift.min(len)..], at, thunks); - let m = patch_bytewise(&mut slow[shift.min(len)..], at, thunks); - assert_eq!((n, &fast), (m, &slow), "len {len} round {round}"); - patched += n; - } - } - assert!(patched > 200, "{patched} loads patched"); - // Back to back, a prefix inside a load, and a load ending the code. - let load = [GS, 0x48, 0x8B, 0x04, 0x25, 0x58, 0, 0, 0]; - let mut code = Vec::new(); - for _ in 0..3 { - code.extend(load); - } - code.extend([GS, GS]); - code.extend(load); - let (mut fast, mut slow) = (code.clone(), code); - assert_eq!(patch(&mut fast, at, thunks), 4); - assert_eq!(patch_bytewise(&mut slow, at, thunks), 4); - assert_eq!(fast, slow); - } - - /// `cargo test -p victory-loader --release -- --ignored --nocapture - /// tls_scan_speed`: both scans over synthetic code sections. - #[test] - #[ignore = "benchmark"] - fn tls_scan_speed() { - use std::time::Instant; - let mut rng = Rng(0xD1B5_4A32_D192_ED03); - for (name, mib, per_mib) in [("small", 1, 512), ("medium", 16, 512), ("large", 128, 512)] { - let len = mib << 20; - // Code-like noise: each byte a gs prefix with chance 1/256. - let mut code: Vec<u8> = (0..len).map(|_| rng.next() as u8).collect(); - for _ in 0..mib * per_mib { - let i = rng.next() as usize % (len - LOAD_LEN); - code[i..i + LOAD_LEN].copy_from_slice(&[GS, 0x48, 0x8B, 0x04, 0x25, 0x58, 0, 0, 0]); - } - let best = |f: fn(&mut [u8], usize, usize) -> usize| { - let mut times = Vec::new(); - let mut out = (0, Vec::new()); - for _ in 0..5 { - let mut c = code.clone(); - let t = Instant::now(); - let n = f(&mut c, 0x1_4000_0000, 0x1_3FFF_0000); - times.push(t.elapsed().as_secs_f64()); - out = (n, c); - } - (times.into_iter().fold(f64::MAX, f64::min), out) - }; - let (old, a) = best(patch_bytewise); - let (new, b) = best(patch); - assert_eq!(a, b); - println!( - "{name:6} {mib:4} MiB, {:6} loads: bytewise {:8.3} ms, candidate search {:8.3} ms, {:5.1}x", - a.0, - old * 1e3, - new * 1e3, - old / new - ); - } - } - #[test] fn loads_become_calls_that_yield_the_title_slot() { let page = near(tls_array as *const () as usize, 0).unwrap(); diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index bdcede78d3..b5a6472479 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -8,7 +8,6 @@ use std::sync::Arc; use std::sync::atomic::AtomicU64; use anyhow::{Context, Result, bail}; -use victory_core::diagnostics::{self, IoOperation}; use victory_pe::{ImageInfo, ImportSymbol}; use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE}; use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW}; @@ -55,25 +54,26 @@ pub struct BindReport { /// `dir` receives derived game data, so it must be outside the repository. pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> { victory_core::ensure_outside_repo(dir)?; - let started = diagnostics::operation_started(); - std::fs::create_dir_all(dir) - .inspect_err(|error| IoOperation::CreateImageDirectory.failed(error, started)) - .with_context(|| format!("creating {}", dir.display()))?; + std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; let path = dir.join(prepared.file_name()); write_if_changed(&path, &prepared.bytes)?; - // SAFETY: the prepared image has no entry point or imports. - let module = unsafe { map_image(&path) }.with_context(|| { - format!( - "LoadLibraryExW({}) failed{}", + let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect(); + // SAFETY: `wide` is a NUL-terminated path. The image has no entry point + // and no imports, so loading it runs no title code. + let module = unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0) }; + if module.is_null() { + bail!( + "LoadLibraryExW({}) failed: {}{}", path.display(), + std::io::Error::last_os_error(), if prepared.info.has_relocations { "" } else { " (image has no relocations; its preferred base may be taken)" } - ) - })?; + ); + } let loaded = LoadedImage { module, path, @@ -84,15 +84,9 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> { // SAFETY: just mapped, and no title code has run. unsafe { crate::tls::redirect(loaded.base(), &loaded.info) }?; } - if std::env::var_os(crate::hooks::NO_WATCHDOG_ENV).is_some() { + if !loaded.info.is_dll() && std::env::var_os(crate::pool_asserts::ENV).is_some_and(|v| v != "0") { // SAFETY: just mapped, and no title code has run. - let applied = - unsafe { crate::hooks::disarm_watchdog(loaded.base(), &prepared.original_hash) }; - tracing::info!( - applied, - "title watchdog hooks ({})", - crate::hooks::NO_WATCHDOG_ENV - ); + unsafe { crate::pool_asserts::disarm(loaded.base(), &loaded.info, &prepared.original_hash) }; } tracing::info!( base = format_args!("{:#x}", loaded.base()), @@ -214,37 +208,6 @@ impl ImportResolver for WithTitleDlls<'_> { } } -/// The caller supplies an image safe to map with the default loader flags. -unsafe fn map_image(path: &Path) -> std::io::Result<HMODULE> { - let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect(); - let started = diagnostics::operation_started(); - // SAFETY: `wide` is terminated and the caller checked the image. - let module = unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0) }; - if module.is_null() { - let error = std::io::Error::last_os_error(); - IoOperation::MapImage.failed(&error, started); - return Err(error); - } - Ok(module) -} - -#[cfg(test)] -#[test] -fn maps_missing_dll_to_its_original_win32_error() { - let directory = tempfile::tempdir().unwrap(); - let output = directory.path().join("diagnostics.jsonl"); - diagnostics::start(&output).unwrap(); - // SAFETY: the path points into a fresh directory and has no DLL to load. - let error = - unsafe { map_image(&directory.path().join("absent-victory-test.dll")) }.unwrap_err(); - diagnostics::finish(false); - assert_eq!(error.raw_os_error(), Some(126)); - let output = std::fs::read_to_string(output).unwrap(); - assert!(output.contains("ERROR_MOD_NOT_FOUND")); - assert!(output.contains("\"value\":126")); - assert!(!output.contains("absent-victory-test.dll")); -} - fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<()> { if std::fs::read(path).is_ok_and(|existing| existing == bytes) { return Ok(()); diff --git a/crates/victory-loader/tests/crash_log.rs b/crates/victory-loader/tests/crash_log.rs deleted file mode 100644 index a0c26f851b..0000000000 --- a/crates/victory-loader/tests/crash_log.rs +++ /dev/null @@ -1,65 +0,0 @@ -#![cfg(windows)] - -use std::path::PathBuf; -use std::process::Command; - -use windows_sys::Win32::Foundation::EXCEPTION_BREAKPOINT; -use windows_sys::Win32::System::Diagnostics::Debug::{ - AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, - EXCEPTION_POINTERS, RaiseException, -}; - -const TEST_LOG: &str = "VICTORY_TEST_CRASH_LOG"; - -#[test] -fn first_chance_breakpoint_logging() { - if let Some(log) = std::env::var_os(TEST_LOG) { - victory_loader::log_crashes_to(PathBuf::from(log)); - victory_loader::note_title_output("synthetic title output"); - victory_loader::report_crashes(); - - unsafe extern "system" fn handle_breakpoint(info: *mut EXCEPTION_POINTERS) -> i32 { - // SAFETY: the system passes valid exception pointers. - if unsafe { (*(*info).ExceptionRecord).ExceptionCode } == EXCEPTION_BREAKPOINT { - EXCEPTION_CONTINUE_EXECUTION - } else { - EXCEPTION_CONTINUE_SEARCH - } - } - - // SAFETY: register after VIctory's vectored handler. This synthetic - // breakpoint is continuable and the handler needs no extra data. - unsafe { - assert!(!AddVectoredExceptionHandler(0, Some(handle_breakpoint)).is_null()); - RaiseException(EXCEPTION_BREAKPOINT as u32, 0, 0, std::ptr::null()); - } - return; - } - - let dir = tempfile::tempdir().unwrap(); - for opt_in in [false, true] { - let log = dir.path().join(format!("breakpoint-{opt_in}.log")); - let mut child = Command::new(std::env::current_exe().unwrap()); - child - .args(["--exact", "first_chance_breakpoint_logging", "--nocapture"]) - .env(TEST_LOG, &log) - .env_remove("VICTORY_CRASH_BREAKPOINTS"); - if opt_in { - child.env("VICTORY_CRASH_BREAKPOINTS", "1"); - } - let output = child.output().unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(output.status.success(), "{}\n{stderr}", output.status); - assert!(stderr.contains("first-chance exception 0x80000003")); - - if cfg!(feature = "diagnostics") && opt_in { - let report = std::fs::read_to_string(&log).unwrap(); - assert!(report.contains("first-chance exception 0x80000003 at ")); - assert!(report.contains(" #0 ")); - assert!(report.contains(" title said: synthetic title output")); - assert!(!report.contains("unhandled exception")); - } else { - assert!(!log.exists()); - } - } -} diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs index 6f78f7674b..cf1111bda1 100644 --- a/crates/victory-loader/tests/load_probe.rs +++ b/crates/victory-loader/tests/load_probe.rs @@ -24,10 +24,6 @@ fn workspace_root() -> PathBuf { /// for tests, so that it follows `CARGO_TARGET_DIR` like the rest of the /// build. fn build_probe() -> PathBuf { - // Under Proton the Windows test process cannot invoke the Linux Cargo. - if let Some(path) = std::env::var_os("VICTORY_HLE_PROBE") { - return PathBuf::from(path); - } let manifest = workspace_root().join("tests/fixtures/hle-probe/Cargo.toml"); let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("hle-probe"); let status = Command::new(env!("CARGO")) diff --git a/crates/victory-loader/tests/synthetic_prepare.rs b/crates/victory-loader/tests/synthetic_prepare.rs deleted file mode 100644 index 54e884a3c5..0000000000 --- a/crates/victory-loader/tests/synthetic_prepare.rs +++ /dev/null @@ -1,1202 +0,0 @@ -//! `prepare` on a PE32+ executable built byte by byte here, so the patching -//! is covered on every host. The unit tests in `src/prepare.rs` use the test -//! binary itself, which is a PE image only on Windows. - -use victory_loader::prepare; -use victory_pe::ImageInfo; -use victory_pe::layout::{self, dir, dll_flags, file_flags}; - -const IMAGE_BASE: u64 = 0x1_4000_0000; -const SECTION_RVA: u32 = 0x1000; -const SECTION_FILE: usize = 0x200; -const SECTION_SIZE: usize = 0x400; - -// RVAs inside the one section. -const IMPORTS: u32 = 0x1000; // one descriptor, then the null terminator -const INT: u32 = 0x1040; -const IAT: u32 = 0x1060; -const HINT_NAME: u32 = 0x1080; -const DLL_NAME: u32 = 0x10A0; -const TLS: u32 = 0x1100; -const TLS_INDEX: u32 = 0x1180; -const CALLBACKS: u32 = 0x1140; -const CODE: u32 = 0x1200; -const RELOCS: u32 = 0x1300; - -const NT: usize = 0x40; -const FILE_HEADER: usize = NT + 4; -const OPT: usize = FILE_HEADER + 20; -const SECTIONS: usize = OPT + 240; - -const CHECKSUM: u32 = 0x0001_2345; -const DLL_CHARACTERISTICS: u16 = dll_flags::HIGH_ENTROPY_VA - | dll_flags::DYNAMIC_BASE - | dll_flags::NX_COMPAT - | dll_flags::FORCE_INTEGRITY; -/// The bound-import directory as an old linker might leave it. -const BOUND: [u8; 8] = [0xF0, 0x01, 0, 0, 0x10, 0, 0, 0]; - -fn put(b: &mut [u8], at: usize, v: &[u8]) { - b[at..at + v.len()].copy_from_slice(v); -} -fn put16(b: &mut [u8], at: usize, v: u16) { - put(b, at, &v.to_le_bytes()); -} -fn put32(b: &mut [u8], at: usize, v: u32) { - put(b, at, &v.to_le_bytes()); -} -fn put64(b: &mut [u8], at: usize, v: u64) { - put(b, at, &v.to_le_bytes()); -} -fn file(rva: u32) -> usize { - SECTION_FILE + (rva - SECTION_RVA) as usize -} -fn set_dir(b: &mut [u8], index: usize, rva: u32, size: u32) { - let at = OPT + layout::OPT_DATA_DIRECTORY + index * layout::DATA_DIRECTORY_SIZE; - put32(b, at, rva); - put32(b, at + 4, size); -} - -/// An executable with one import module (`ExitProcess` by name, ordinal 5), -/// one TLS callback and DIR64 relocations for the TLS directory's pointers. -fn image() -> Vec<u8> { - let mut b = vec![0u8; SECTION_FILE + SECTION_SIZE]; - put(&mut b, 0, b"MZ"); - put32(&mut b, layout::DOS_E_LFANEW, NT as u32); - put(&mut b, NT, b"PE\0\0"); - - put16(&mut b, FILE_HEADER, 0x8664); // AMD64 - put16(&mut b, FILE_HEADER + 2, 1); // sections - put32(&mut b, FILE_HEADER + 4, 0x6000_0000); // timestamp - put16(&mut b, FILE_HEADER + 16, 240); // optional header size - put16(&mut b, FILE_HEADER + 18, 0x0022); // executable, large address aware - - put16(&mut b, OPT, 0x20B); // PE32+ - put32(&mut b, OPT + layout::OPT_ADDRESS_OF_ENTRY_POINT, CODE); - put64(&mut b, OPT + 24, IMAGE_BASE); - put32(&mut b, OPT + 32, 0x1000); // section alignment - put32(&mut b, OPT + 36, 0x200); // file alignment - put16(&mut b, OPT + 40, 6); // OS version - put16(&mut b, OPT + 48, 6); // subsystem version - put32(&mut b, OPT + 56, 0x2000); // size of image - put32(&mut b, OPT + 60, SECTION_FILE as u32); // size of headers - put32(&mut b, OPT + layout::OPT_CHECKSUM, CHECKSUM); - put16(&mut b, OPT + 68, layout::subsystem::WINDOWS_CUI); - put16( - &mut b, - OPT + layout::OPT_DLL_CHARACTERISTICS, - DLL_CHARACTERISTICS, - ); - put64(&mut b, OPT + 72, 0x10_0000); // stack reserve - put64(&mut b, OPT + 80, 0x1000); // stack commit - put32(&mut b, OPT + layout::OPT_NUMBER_OF_RVA_AND_SIZES, 16); - set_dir(&mut b, dir::IMPORT, IMPORTS, 2 * 20); - set_dir(&mut b, dir::BASERELOC, RELOCS, 16); - set_dir(&mut b, 9, TLS, 40); // TLS - put( - &mut b, - OPT + layout::OPT_DATA_DIRECTORY + dir::BOUND_IMPORT * layout::DATA_DIRECTORY_SIZE, - &BOUND, - ); - set_dir(&mut b, dir::IAT, IAT, 24); - - put(&mut b, SECTIONS, b".data\0\0\0"); - put32(&mut b, SECTIONS + 8, SECTION_SIZE as u32); // virtual size - put32(&mut b, SECTIONS + 12, SECTION_RVA); - put32(&mut b, SECTIONS + 16, SECTION_SIZE as u32); // raw size - put32(&mut b, SECTIONS + 20, SECTION_FILE as u32); - put32(&mut b, SECTIONS + 36, 0xE000_0060); // code, data, rwx - - // Import descriptor: name table, DLL name, IAT. The terminator is zeros. - put32(&mut b, file(IMPORTS), INT); - put32(&mut b, file(IMPORTS) + 12, DLL_NAME); - put32(&mut b, file(IMPORTS) + 16, IAT); - for table in [INT, IAT] { - put64(&mut b, file(table), u64::from(HINT_NAME)); - put64(&mut b, file(table) + 8, 0x8000_0000_0000_0005); - } - put16(&mut b, file(HINT_NAME), 7); - put(&mut b, file(HINT_NAME) + 2, b"ExitProcess\0"); - put(&mut b, file(DLL_NAME), b"KERNEL32.dll\0"); - - // TLS directory: no template, an index slot and one callback. - put64(&mut b, file(TLS) + 16, IMAGE_BASE + u64::from(TLS_INDEX)); - put64( - &mut b, - file(TLS) + layout::TLS64_ADDRESS_OF_CALLBACKS, - IMAGE_BASE + u64::from(CALLBACKS), - ); - put64(&mut b, file(CALLBACKS), IMAGE_BASE + u64::from(CODE)); - b[file(CODE)] = 0xC3; // ret - - // One block of base relocations for the page at SECTION_RVA. - put32(&mut b, file(RELOCS), SECTION_RVA); - put32(&mut b, file(RELOCS) + 4, 16); - for (i, field) in [TLS + 16, callbacks_field(), CALLBACKS] - .into_iter() - .enumerate() - { - put16(&mut b, file(RELOCS) + 8 + i * 2, dir64(field)); - } - b -} - -fn callbacks_field() -> u32 { - TLS + layout::TLS64_ADDRESS_OF_CALLBACKS as u32 -} -fn dir64(rva: u32) -> u16 { - (10 << 12) | (rva - SECTION_RVA) as u16 -} -/// File offset of the relocation entry for the TLS callbacks pointer. -fn callbacks_reloc() -> usize { - file(RELOCS) + 8 + 2 -} - -fn dir_offset(index: usize) -> usize { - OPT + layout::OPT_DATA_DIRECTORY + index * layout::DATA_DIRECTORY_SIZE -} - -#[test] -fn the_synthetic_image_parses_as_built() { - let info = ImageInfo::parse(&image()).unwrap(); - assert!(!info.is_dll()); - assert_eq!(info.entry_rva, CODE); - assert_eq!(info.import_count(), 2); - assert_eq!(info.imports[0].dll, "KERNEL32.dll"); - let tls = info.tls.as_ref().unwrap(); - assert_eq!(tls.directory_rva, TLS); - assert_eq!(tls.callback_rvas, [CODE]); - assert!(info.has_relocations); -} - -#[test] -fn prepare_maps_an_inert_dll_and_keeps_what_the_title_expects() { - let original = image(); - let prepared = prepare(&original).unwrap(); - - // `info` describes the original image. - assert!(!prepared.info.is_dll()); - assert_eq!(prepared.info.entry_rva, CODE); - assert_eq!(prepared.info.import_count(), 2); - let slots: Vec<u32> = prepared.info.imports[0] - .entries - .iter() - .map(|e| e.iat_slot_rva) - .collect(); - assert_eq!(slots, [IAT, IAT + 8]); - assert_eq!(prepared.info.tls.as_ref().unwrap().callback_rvas, [CODE]); - assert_eq!(prepared.original_hash, blake3::hash(&original)); - - let patched = ImageInfo::parse(&prepared.bytes).unwrap(); - assert!(patched.is_dll()); - assert_eq!( - patched.characteristics, - prepared.info.characteristics | file_flags::DLL - ); - assert_eq!(patched.entry_rva, 0); - assert!(patched.imports.is_empty()); - assert_eq!( - patched.dll_characteristics, - DLL_CHARACTERISTICS & !dll_flags::FORCE_INTEGRITY - ); - assert_eq!( - layout::read_u32(&prepared.bytes, OPT + layout::OPT_CHECKSUM), - Some(0) - ); - let tls = patched.tls.as_ref().unwrap(); - assert_eq!(tls.directory_rva, TLS); - assert_eq!(tls.callbacks_va, 0); - assert!(tls.callback_rvas.is_empty()); - - // The import directory points at the empty terminator. - let import = dir_offset(dir::IMPORT); - assert_eq!( - layout::read_u32(&prepared.bytes, import), - Some(IMPORTS + 20) - ); - assert_eq!(layout::read_u32(&prepared.bytes, import + 4), Some(20)); - assert_eq!(&prepared.bytes[file(IMPORTS + 20)..][..20], &[0; 20]); - - // Only the callbacks pointer's relocation became a no-op. - assert_eq!(&prepared.bytes[callbacks_reloc()..][..2], &[0, 0]); - assert_ne!(&original[callbacks_reloc()..][..2], &[0, 0]); - - // Nothing else changed: the IAT, its directory, the name tables, the - // callback array and the other relocations are as the title left them. - assert_eq!(prepared.bytes.len(), original.len()); - let expected = expected_changes(); - let differing: Vec<usize> = (0..original.len()) - .filter(|&i| original[i] != prepared.bytes[i]) - .collect(); - assert!( - differing - .iter() - .all(|i| expected.iter().any(|r| r.contains(i))), - "unexpected bytes changed: {:#x?}", - differing - .iter() - .filter(|i| !expected.iter().any(|r| r.contains(i))) - .collect::<Vec<_>>() - ); -} - -/// Byte ranges `prepare` may write. -fn expected_changes() -> Vec<std::ops::Range<usize>> { - let field = |at: usize, len: usize| at..at + len; - vec![ - field(FILE_HEADER + layout::FILE_HEADER_CHARACTERISTICS, 2), - field(OPT + layout::OPT_ADDRESS_OF_ENTRY_POINT, 4), - field(OPT + layout::OPT_CHECKSUM, 4), - field(OPT + layout::OPT_DLL_CHARACTERISTICS, 2), - field(dir_offset(dir::IMPORT), layout::DATA_DIRECTORY_SIZE), - field(dir_offset(dir::BOUND_IMPORT), layout::DATA_DIRECTORY_SIZE), - field(file(callbacks_field()), 8), - field(callbacks_reloc(), 2), - ] -} - -#[test] -fn prepare_clears_the_bound_import_directory() { - let original = image(); - let at = dir_offset(dir::BOUND_IMPORT); - assert_eq!(&original[at..][..8], &BOUND); - let prepared = prepare(&original).unwrap(); - assert_eq!(&prepared.bytes[at..][..8], &[0; 8]); -} - -#[test] -fn import_size_that_excludes_the_terminator_still_finds_it() { - // Some linkers count the descriptors for real modules only. - let mut original = image(); - put32(&mut original, dir_offset(dir::IMPORT) + 4, 20); - let prepared = prepare(&original).unwrap(); - assert_eq!(prepared.info.import_count(), 2); - let import = dir_offset(dir::IMPORT); - assert_eq!( - layout::read_u32(&prepared.bytes, import), - Some(IMPORTS + 20) - ); - assert_eq!(layout::read_u32(&prepared.bytes, import + 4), Some(20)); - assert!( - ImageInfo::parse(&prepared.bytes) - .unwrap() - .imports - .is_empty() - ); -} - -#[test] -fn the_terminator_follows_every_import_descriptor() { - // Three descriptors, the third for the same DLL as the first in another - // case, as linkers emit when objects spell it differently. Each one is - // its own module, so the terminator sits 3 * 20 bytes in. - const TABLE: u32 = 0x1380; // 4 * 20 bytes, up to the section end - const IAT2: u32 = 0x1210; - const IAT3: u32 = 0x1220; - const NAME2: u32 = 0x1230; - const NAME3: u32 = 0x1240; - let mut original = image(); - let old = file(IMPORTS); - let descriptor = original[old..old + 20].to_vec(); - put(&mut original, file(TABLE), &descriptor); - for (i, (iat, name, thunk)) in [ - (IAT2, NAME2, u64::from(HINT_NAME)), - (IAT3, NAME3, 0x8000_0000_0000_0001), - ] - .into_iter() - .enumerate() - { - // No name table: old linkers leave OriginalFirstThunk at 0. - let at = file(TABLE) + (i + 1) * 20; - put32(&mut original, at + 12, name); - put32(&mut original, at + 16, iat); - put64(&mut original, file(iat), thunk); - } - put(&mut original, file(NAME2), b"USER32.dll\0"); - put(&mut original, file(NAME3), b"kernel32.dll\0"); - set_dir(&mut original, dir::IMPORT, TABLE, 4 * 20); - - let prepared = prepare(&original).unwrap(); - let modules: Vec<(&str, Vec<u32>)> = prepared - .info - .imports - .iter() - .map(|m| { - let slots = m.entries.iter().map(|e| e.iat_slot_rva).collect(); - (m.dll.as_str(), slots) - }) - .collect(); - assert_eq!( - modules, - [ - ("KERNEL32.dll", vec![IAT, IAT + 8]), - ("USER32.dll", vec![IAT2]), - ("kernel32.dll", vec![IAT3]), - ] - ); - - let import = dir_offset(dir::IMPORT); - assert_eq!( - layout::read_u32(&prepared.bytes, import), - Some(TABLE + 3 * 20) - ); - assert_eq!(layout::read_u32(&prepared.bytes, import + 4), Some(20)); - assert_eq!(&prepared.bytes[file(TABLE + 3 * 20)..][..20], &[0; 20]); - assert!( - ImageInfo::parse(&prepared.bytes) - .unwrap() - .imports - .is_empty() - ); - // The descriptors and the IATs the title binds against are untouched. - let differing: Vec<usize> = (0..original.len()) - .filter(|&i| original[i] != prepared.bytes[i]) - .collect(); - let expected = expected_changes(); - assert!( - differing - .iter() - .all(|i| expected.iter().any(|r| r.contains(i))), - "unexpected bytes changed: {differing:#x?}" - ); -} - -#[test] -fn an_image_without_imports_or_tls_only_changes_its_headers() { - let mut original = image(); - set_dir(&mut original, dir::IMPORT, 0, 0); - set_dir(&mut original, dir::IAT, 0, 0); - set_dir(&mut original, 9, 0, 0); - let prepared = prepare(&original).unwrap(); - assert!(prepared.info.imports.is_empty()); - assert!(prepared.info.tls.is_none()); - let import = dir_offset(dir::IMPORT); - assert_eq!(&prepared.bytes[import..][..8], &[0; 8]); - // The section, relocations included, is untouched. - assert_eq!(&prepared.bytes[SECTION_FILE..], &original[SECTION_FILE..]); - assert!(ImageInfo::parse(&prepared.bytes).unwrap().is_dll()); -} - -#[test] -fn file_name_names_the_original_build() { - let original = image(); - let a = prepare(&original).unwrap(); - let b = prepare(&original).unwrap(); - assert_eq!(a.file_name(), b.file_name()); - let hex = &blake3::hash(&original).to_hex()[..16]; - assert_eq!(a.file_name(), format!("victory-image-{hex}.dll")); - - let mut other = original; - put32(&mut other, FILE_HEADER + 4, 0x6000_0001); // another timestamp - assert_ne!(prepare(&other).unwrap().file_name(), a.file_name()); -} - -#[test] -fn what_is_not_a_pe32_plus_image_is_an_error() { - assert!(prepare(&[]).is_err()); - assert!(prepare(b"MZ").is_err()); - let original = image(); - for len in [0x40, 0x100, SECTIONS + 20] { - assert!(prepare(&original[..len]).is_err(), "truncated to {len:#x}"); - } - let mut x86 = original; - put16(&mut x86, FILE_HEADER, 0x014C); - assert!(prepare(&x86).is_err()); -} - -/// Applies every base relocation in `bytes` for a load `delta` bytes above -/// the preferred base, as the Windows or Wine loader does on a rebase: -/// HIGH, LOW, HIGHLOW and DIR64 add the matching part of `delta` to the -/// bytes they name, and HIGHADJ adds the high half and skips its parameter. -fn rebase(bytes: &mut [u8], delta: u64) { - let info = ImageInfo::parse(bytes).unwrap(); - let d = dir_offset(dir::BASERELOC); - let (rva, size) = ( - layout::read_u32(bytes, d).unwrap(), - layout::read_u32(bytes, d + 4).unwrap(), - ); - if rva == 0 || size == 0 { - return; - } - // The headers are mapped at the RVA equal to their file offset. - let start = match info.rva_to_file_offset(rva) { - Some(offset) => offset as usize, - None if (rva as usize) < SECTION_FILE => rva as usize, - None => panic!("relocation table at RVA {rva:#x} is not mapped"), - }; - let end = start + size as usize; - let mut at = start; - while at + 8 <= end { - let page = layout::read_u32(bytes, at).unwrap(); - let block = layout::read_u32(bytes, at + 4).unwrap() as usize; - assert!(block >= 8 && at + block <= end, "well-formed blocks only"); - let mut entry = at + 8; - while entry < at + block { - let e = u16::from_le_bytes([bytes[entry], bytes[entry + 1]]); - entry += 2; - if e >> 12 == 0 { - continue; - } - let target = info - .rva_to_file_offset(page + u32::from(e & 0xFFF)) - .unwrap() as usize; - let add16 = |b: &mut [u8], v: u16| { - let old = u16::from_le_bytes([b[target], b[target + 1]]); - put16(b, target, old.wrapping_add(v)); - }; - match e >> 12 { - 1 => add16(bytes, (delta >> 16) as u16), - 2 => add16(bytes, delta as u16), - 3 => { - let v = layout::read_u32(bytes, target).unwrap(); - put32(bytes, target, v.wrapping_add(delta as u32)); - } - 4 => { - add16(bytes, (delta >> 16) as u16); - entry += 2; - } - 10 => { - let v = layout::read_u64(bytes, target).unwrap(); - put64(bytes, target, v.wrapping_add(delta)); - } - kind => panic!("relocation type {kind} is not modelled"), - } - } - at += block; - } -} - -#[test] -fn a_rebase_keeps_the_cleared_callback_pointer_at_zero() { - // Wine maps DYNAMIC_BASE images away from their preferred base, so the - // loader applies every relocation before it looks at the TLS directory. - let delta = 0x7_0000_0000; - let original = image(); - let mut mapped = prepare(&original).unwrap().bytes; - rebase(&mut mapped, delta); - let tls = file(TLS); - assert_eq!( - layout::read_u64(&mapped, tls + layout::TLS64_ADDRESS_OF_CALLBACKS), - Some(0), - "a relocated 0 would point the loader at callbacks below the image" - ); - // The other pointers still move with the image. - assert_eq!( - layout::read_u64(&mapped, tls + 16), - Some(IMAGE_BASE + u64::from(TLS_INDEX) + delta) - ); - assert_eq!( - layout::read_u64(&mapped, file(CALLBACKS)), - Some(IMAGE_BASE + u64::from(CODE) + delta) - ); - - // Without prepare's no-op, the same rebase would leave `delta` there. - let mut unpatched = original; - put64( - &mut unpatched, - file(callbacks_field()), - 0, // what prepare writes, relocation left alone - ); - rebase(&mut unpatched, delta); - assert_eq!( - layout::read_u64(&unpatched, file(callbacks_field())), - Some(delta) - ); -} - -#[test] -fn the_callback_relocation_is_found_in_a_later_block() { - // Two blocks: the first holds the index pointer's DIR64 entry and a - // HIGHLOW entry for an import-table RVA, the second the DIR64 entry for - // the callbacks pointer. - let mut original = image(); - let first = file(RELOCS); - put32(&mut original, first, SECTION_RVA); - put32(&mut original, first + 4, 12); - put16( - &mut original, - first + 8, - (3 << 12) | (INT - SECTION_RVA) as u16, - ); - put16(&mut original, first + 10, dir64(TLS + 16)); - let second = first + 12; - put32(&mut original, second, SECTION_RVA); - put32(&mut original, second + 4, 12); - put16(&mut original, second + 8, dir64(callbacks_field())); - put16(&mut original, second + 10, 0); // ABSOLUTE padding - set_dir(&mut original, dir::BASERELOC, RELOCS, 24); - - let prepared = prepare(&original).unwrap(); - assert_eq!(&prepared.bytes[second + 8..][..2], &[0, 0]); - assert_eq!( - &prepared.bytes[first + 8..first + 12], - &original[first + 8..first + 12], - "the HIGHLOW entry and the index pointer's entry are left alone" - ); -} - -#[test] -fn damaged_or_missing_relocations_still_clear_the_callback_pointer() { - type Damage = (&'static str, fn(&mut Vec<u8>)); - let cases: [Damage; 5] = [ - ("no relocation directory", |b| { - set_dir(b, dir::BASERELOC, 0, 0) - }), - ("relocation directory of size 0", |b| { - set_dir(b, dir::BASERELOC, RELOCS, 0) - }), - ("relocation directory outside the file", |b| { - set_dir(b, dir::BASERELOC, 0x8000, 16) - }), - ("block shorter than its header", |b| { - put32(b, file(RELOCS) + 4, 4) - }), - ("block longer than the directory", |b| { - put32(b, file(RELOCS) + 4, 0x1000) - }), - ]; - for (what, damage) in cases { - let mut original = image(); - damage(&mut original); - let prepared = prepare(&original).unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!( - layout::read_u64(&prepared.bytes, file(callbacks_field())), - Some(0), - "{what}" - ); - // No relocation entry was rewritten from a block that was not read. - assert_eq!( - &prepared.bytes[file(RELOCS)..file(RELOCS) + 16], - &original[file(RELOCS)..file(RELOCS) + 16], - "{what}" - ); - } -} - -#[test] -fn tls_without_callbacks_leaves_its_relocations_alone() { - let mut original = image(); - put64(&mut original, file(callbacks_field()), 0); - let prepared = prepare(&original).unwrap(); - assert!(prepared.info.tls.as_ref().unwrap().callback_rvas.is_empty()); - assert_eq!( - &prepared.bytes[file(RELOCS)..file(RELOCS) + 16], - &original[file(RELOCS)..file(RELOCS) + 16] - ); -} - -#[test] -fn preparing_a_prepared_image_changes_nothing() { - let once = prepare(&image()).unwrap(); - let twice = prepare(&once.bytes).unwrap(); - assert_eq!(twice.bytes, once.bytes); - assert!(twice.info.is_dll()); - assert!(twice.info.imports.is_empty()); - assert_ne!(twice.file_name(), once.file_name()); -} - -#[test] -fn a_title_dll_stays_a_dll_with_its_other_flags() { - let mut original = image(); - let flags = FILE_HEADER + layout::FILE_HEADER_CHARACTERISTICS; - put16(&mut original, flags, 0x0022 | file_flags::DLL); - let prepared = prepare(&original).unwrap(); - assert!(prepared.info.is_dll()); - assert_eq!( - ImageInfo::parse(&prepared.bytes).unwrap().characteristics, - 0x0022 | file_flags::DLL - ); -} - -#[test] -fn directory_slots_past_number_of_rva_and_sizes_are_not_written() { - // A shorter optional header with 10 directories (through TLS): the - // section table follows directly, so the slot where the bound-import - // directory would be (index 11) holds the section's virtual size and - // RVA. Writing it would unmap the section the title runs from. - const COUNT: usize = 10; - let opt_size = layout::OPT_DATA_DIRECTORY + COUNT * layout::DATA_DIRECTORY_SIZE; - let mut original = image(); - put16(&mut original, FILE_HEADER + 16, opt_size as u16); - put32( - &mut original, - OPT + layout::OPT_NUMBER_OF_RVA_AND_SIZES, - COUNT as u32, - ); - let section = original[SECTIONS..SECTIONS + 40].to_vec(); - put(&mut original, SECTIONS, &[0; 40]); - put(&mut original, OPT + opt_size, §ion); - assert!((OPT + opt_size..OPT + opt_size + 40).contains(&dir_offset(dir::BOUND_IMPORT))); - - let info = ImageInfo::parse(&original).unwrap(); - assert_eq!(info.sections[0].rva, SECTION_RVA); - let prepared = prepare(&original).unwrap(); - let section_table = OPT + opt_size..OPT + opt_size + 40; - assert_eq!( - &prepared.bytes[section_table.clone()], - &original[section_table] - ); - let patched = ImageInfo::parse(&prepared.bytes).unwrap(); - assert!(patched.is_dll()); - assert!(patched.imports.is_empty()); - assert_eq!(patched.sections[0].rva, SECTION_RVA); - assert_eq!(patched.sections[0].virtual_size, SECTION_SIZE as u32); - // The rest of the patch still happened. - assert_eq!(patched.tls.as_ref().unwrap().callbacks_va, 0); - assert_eq!(&prepared.bytes[callbacks_reloc()..][..2], &[0, 0]); -} - -#[test] -fn every_relocation_of_the_callback_pointer_becomes_a_no_op() { - // A linker that merges relocation tables can leave two DIR64 entries for - // one field. Either one alone would turn the cleared pointer into - // `delta` on a rebase, so both are neutralised. - let mut original = image(); - let second = file(RELOCS) + 16; - put32(&mut original, second, SECTION_RVA); - put32(&mut original, second + 4, 12); - put16(&mut original, second + 8, dir64(callbacks_field())); - put16(&mut original, second + 10, 0); // ABSOLUTE padding - set_dir(&mut original, dir::BASERELOC, RELOCS, 28); - - let prepared = prepare(&original).unwrap(); - assert_eq!(&prepared.bytes[callbacks_reloc()..][..2], &[0, 0]); - assert_eq!(&prepared.bytes[second + 8..][..2], &[0, 0]); - let mut mapped = prepared.bytes; - let delta = 0x2_0000_0000; - rebase(&mut mapped, delta); - assert_eq!(layout::read_u64(&mapped, file(callbacks_field())), Some(0)); - assert_eq!( - layout::read_u64(&mapped, file(TLS) + 16), - Some(IMAGE_BASE + u64::from(TLS_INDEX) + delta) - ); -} - -#[test] -fn an_import_directory_of_only_a_terminator_points_at_it() { - // A title that imports nothing through the ordinary table but keeps an - // import directory (its delay imports or IAT are elsewhere): the empty - // table is the directory itself, given the size of one descriptor - // whatever size the linker recorded. - let mut original = image(); - put(&mut original, file(IMPORTS), &[0; 20]); - set_dir(&mut original, dir::IMPORT, IMPORTS, 2 * 20); - let prepared = prepare(&original).unwrap(); - assert!(prepared.info.imports.is_empty()); - let import = dir_offset(dir::IMPORT); - assert_eq!(layout::read_u32(&prepared.bytes, import), Some(IMPORTS)); - assert_eq!(layout::read_u32(&prepared.bytes, import + 4), Some(20)); - assert!( - ImageInfo::parse(&prepared.bytes) - .unwrap() - .imports - .is_empty() - ); -} - -#[test] -fn damaged_images_return_a_result_without_panicking() { - // Every truncation, and every byte of the headers, directories and - // tables set to 0x00 and to 0xFF in turn. A patched copy, when there is - // one, keeps the original's length: `prepare` only overwrites fields. - let original = image(); - let check = |bytes: &[u8], what: &str| { - if let Ok(prepared) = prepare(bytes) { - assert_eq!(prepared.bytes.len(), bytes.len(), "{what}"); - assert_eq!(prepared.original_hash, blake3::hash(bytes), "{what}"); - } - }; - for len in 0..original.len() { - check(&original[..len], &format!("truncated to {len:#x}")); - } - for at in 0..original.len() { - for value in [0x00, 0xFF] { - let mut damaged = original.clone(); - damaged[at] = value; - check(&damaged, &format!("byte {at:#x} set to {value:#04x}")); - } - } -} - -#[test] -fn relocations_in_their_own_section_are_read_through_the_section_table() { - // Linkers put base relocations in a `.reloc` section of their own, at a - // file offset that is not the `.data` section's. A stale copy of the old - // block stays in `.data`: the directory no longer points there, so it is - // left alone. The first `.reloc` block covers another page, with a DIR64 - // entry whose page offset equals the callbacks pointer's: its target is - // a different RVA, so it is not the pointer's relocation. - const RELOC_RVA: u32 = 0x2000; - const RELOC_FILE: usize = SECTION_FILE + SECTION_SIZE; - const RELOC_SIZE: usize = 0x200; - let offset = (callbacks_field() - SECTION_RVA) as u16; - let mut original = image(); - original.resize(RELOC_FILE + RELOC_SIZE, 0); - put16(&mut original, FILE_HEADER + 2, 2); // sections - put32(&mut original, OPT + 56, RELOC_RVA + 0x1000); // size of image - let sec = SECTIONS + 40; - put(&mut original, sec, b".reloc\0\0"); - put32(&mut original, sec + 8, RELOC_SIZE as u32); - put32(&mut original, sec + 12, RELOC_RVA); - put32(&mut original, sec + 16, RELOC_SIZE as u32); - put32(&mut original, sec + 20, RELOC_FILE as u32); - put32(&mut original, sec + 36, 0x4200_0040); // data, discardable, read - - let other = RELOC_FILE; - put32(&mut original, other, RELOC_RVA); - put32(&mut original, other + 4, 12); - put16(&mut original, other + 8, (10 << 12) | offset); - put16(&mut original, other + 10, 0); // ABSOLUTE padding - let ours = other + 12; - let block = original[file(RELOCS)..file(RELOCS) + 16].to_vec(); - put(&mut original, ours, &block); - set_dir(&mut original, dir::BASERELOC, RELOC_RVA, 12 + 16); - - let info = ImageInfo::parse(&original).unwrap(); - assert_eq!(info.sections.len(), 2); - assert_eq!(info.rva_to_file_offset(RELOC_RVA), Some(RELOC_FILE as u32)); - - let prepared = prepare(&original).unwrap(); - assert_eq!( - layout::read_u64(&prepared.bytes, file(callbacks_field())), - Some(0) - ); - // Only the entry in the block for the callbacks pointer's page changes. - assert_eq!(&prepared.bytes[ours + 8 + 2..][..2], &[0, 0]); - assert_eq!( - &prepared.bytes[other..other + 12], - &original[other..other + 12], - "same page offset, different page" - ); - let ours_rest = [ours..ours + 10, ours + 12..ours + 16]; - for range in ours_rest { - assert_eq!(&prepared.bytes[range.clone()], &original[range]); - } - assert_eq!( - &prepared.bytes[file(RELOCS)..file(RELOCS) + 16], - &original[file(RELOCS)..file(RELOCS) + 16], - "the stale block in `.data` is not a relocation table any more" - ); - - let delta = 0x3_0000_0000; - let mut mapped = prepared.bytes; - rebase(&mut mapped, delta); - assert_eq!(layout::read_u64(&mapped, file(callbacks_field())), Some(0)); - assert_eq!( - layout::read_u64(&mapped, file(TLS) + 16), - Some(IMAGE_BASE + u64::from(TLS_INDEX) + delta) - ); - assert_eq!( - layout::read_u64(&mapped, file(CALLBACKS)), - Some(IMAGE_BASE + u64::from(CODE) + delta) - ); -} - -#[test] -fn an_import_directory_without_an_rva_is_left_as_it_is() { - // A size with no RVA is no import table. There is no terminator to point - // at, so the slot is kept rather than aimed at the headers. - let mut original = image(); - set_dir(&mut original, dir::IMPORT, 0, 40); - set_dir(&mut original, dir::IAT, 0, 0); - let prepared = prepare(&original).unwrap(); - assert!(prepared.info.imports.is_empty()); - let import = dir_offset(dir::IMPORT); - assert_eq!( - &prepared.bytes[import..import + 8], - &original[import..import + 8] - ); - // The rest of the patch still happened. - let patched = ImageInfo::parse(&prepared.bytes).unwrap(); - assert!(patched.is_dll()); - assert_eq!(patched.entry_rva, 0); - assert_eq!(patched.tls.as_ref().unwrap().callbacks_va, 0); - assert_eq!( - &prepared.bytes[dir_offset(dir::BOUND_IMPORT)..][..8], - &[0; 8] - ); -} - -#[test] -fn a_section_table_that_hides_the_tls_directory_is_an_error() { - // A first section with no virtual size but raw data at the headers, - // over the same RVAs as `.data`. The parser skips it and reads the TLS - // directory from `.data`; the RVA-to-file mapping, which treats a zero - // virtual size as the raw size, lands in the headers. Clearing the - // pointer there would leave the real callbacks armed, so `prepare` - // must fail instead of handing out a copy the OS would run. - let mut original = image(); - let data = original[SECTIONS..SECTIONS + 40].to_vec(); - put(&mut original, SECTIONS + 40, &data); - put16(&mut original, FILE_HEADER + 2, 2); // sections - put(&mut original, SECTIONS, b".ghost\0\0"); - put32(&mut original, SECTIONS + 8, 0); // virtual size - put32(&mut original, SECTIONS + 20, 0); // raw data at the headers - - let info = ImageInfo::parse(&original).unwrap(); - let tls = info.tls.as_ref().unwrap(); - assert_eq!(tls.callbacks_va, IMAGE_BASE + u64::from(CALLBACKS)); - assert_eq!(info.rva_to_file_offset(TLS), Some(TLS - SECTION_RVA)); - - assert!(matches!( - prepare(&original), - Err(victory_loader::PrepareError::Patch(_)) - )); -} - -#[test] -fn only_relocations_that_write_into_the_callback_field_are_cleared() { - // A DIR64 entry four bytes past the callbacks pointer (misaligned, as a - // damaged table might hold) writes its upper half, so it goes too. One - // eight bytes past it patches SizeOfZeroFill and Characteristics, and - // one eight bytes before it patches the end of the index pointer's - // neighbour; neither touches the pointer, so they stay. - let mut original = image(); - let block = file(RELOCS); - put32(&mut original, block + 4, 20); - let near = block + 14; - put16(&mut original, near, dir64(callbacks_field() + 4)); - put16(&mut original, near + 2, dir64(callbacks_field() + 8)); - put16(&mut original, near + 4, dir64(callbacks_field() - 8)); - set_dir(&mut original, dir::BASERELOC, RELOCS, 20); - - let prepared = prepare(&original).unwrap(); - assert_eq!(&prepared.bytes[callbacks_reloc()..][..2], &[0, 0]); - assert_eq!(&prepared.bytes[near..][..2], &[0, 0], "the upper half"); - assert_eq!( - &prepared.bytes[near + 2..near + 6], - &original[near + 2..near + 6], - "entries beside the field are left alone" - ); - assert_eq!( - &prepared.bytes[block + 8..block + 10], - &original[block + 8..block + 10], - "so is the index pointer's entry" - ); - let patched = ImageInfo::parse(&prepared.bytes).unwrap(); - assert_eq!(patched.tls.unwrap().callbacks_va, 0); -} - -/// `image()` with the callbacks pointer's DIR64 entry replaced by the -/// 16-bit `entries` (in the same block, padded with ABSOLUTE to a multiple -/// of four bytes), as a table from a linker that emits 32-bit fixups might. -fn with_callback_entries(entries: &[u16]) -> Vec<u8> { - let mut b = image(); - let block = file(RELOCS); - // Slot 0: the index pointer, slot 1 onward: `entries`, then the - // callback array's own entry, then padding. - let mut slots = vec![dir64(TLS + 16)]; - slots.extend_from_slice(entries); - slots.push(dir64(CALLBACKS)); - if slots.len() % 2 == 1 { - slots.push(0); - } - let size = 8 + 2 * slots.len(); - assert!(size <= 0x100, "room before the end of the section"); - put32(&mut b, block + 4, size as u32); - for (i, e) in slots.iter().enumerate() { - put16(&mut b, block + 8 + 2 * i, *e); - } - set_dir(&mut b, dir::BASERELOC, RELOCS, size as u32); - b -} - -#[test] -fn a_32_bit_relocation_of_the_callback_field_cannot_rearm_it() { - // HIGHLOW on the field, or on its upper half; HIGH and LOW on parts of - // it; HIGHADJ (with its parameter slot). Each one adds a piece of - // `delta` to the cleared pointer on a rebase, and the loader would then - // call through whatever that names. 0x7_1234_5000 has bits in every - // 16-bit lane a fixup can touch. - let delta: u64 = 0x7_1234_5000; - let at = - |kind: u16, offset: u32| (kind << 12) | (callbacks_field() + offset - SECTION_RVA) as u16; - let cases: [(&str, Vec<u16>); 6] = [ - ("HIGHLOW", vec![at(3, 0)]), - ("HIGHLOW on the upper half", vec![at(3, 4)]), - ("HIGH", vec![at(1, 0)]), - ("LOW", vec![at(2, 2)]), - ("HIGHADJ", vec![at(4, 0), 0x8000]), - ( - "DIR64 and HIGHLOW", - vec![dir64(callbacks_field()), at(3, 0)], - ), - ]; - for (what, entries) in cases { - let original = with_callback_entries(&entries); - // The table is as built: without prepare's no-op, a rebase of the - // cleared pointer would leave something other than 0 there. - let mut unpatched = original.clone(); - put64(&mut unpatched, file(callbacks_field()), 0); - rebase(&mut unpatched, delta); - assert_ne!( - layout::read_u64(&unpatched, file(callbacks_field())), - Some(0), - "{what}: the fixture relocates the field" - ); - - let mut mapped = prepare(&original) - .unwrap_or_else(|e| panic!("{what}: {e}")) - .bytes; - rebase(&mut mapped, delta); - assert_eq!( - layout::read_u64(&mapped, file(callbacks_field())), - Some(0), - "{what}: the cleared callback pointer survives the rebase" - ); - // The index pointer and the callback array still move. - assert_eq!( - layout::read_u64(&mapped, file(TLS) + 16), - Some(IMAGE_BASE + u64::from(TLS_INDEX) + delta), - "{what}" - ); - assert_eq!( - layout::read_u64(&mapped, file(CALLBACKS)), - Some(IMAGE_BASE + u64::from(CODE) + delta), - "{what}" - ); - } -} - -#[test] -fn a_highadj_parameter_is_not_mistaken_for_a_callback_relocation() { - // HIGHADJ's second slot is a 16-bit addend, not an entry. Here it reads - // as a DIR64 entry for the callbacks pointer, but the HIGHADJ itself - // patches the index pointer, so neither slot is the field's. - let highadj = (4 << 12) | (TLS + 16 + 2 - SECTION_RVA) as u16; - let mut original = with_callback_entries(&[highadj, dir64(callbacks_field())]); - // Drop the index pointer's own DIR64 so only the HIGHADJ remains for it. - put16(&mut original, file(RELOCS) + 8, 0); - let slots = file(RELOCS) + 10; - let prepared = prepare(&original).unwrap(); - assert_eq!( - &prepared.bytes[slots..slots + 4], - &original[slots..slots + 4], - "the HIGHADJ entry and its parameter are left as they were" - ); -} - -#[test] -fn a_tls_va_past_the_32_bit_rva_range_is_refused_not_truncated() { - // Truncating `IMAGE_BASE + 4 GiB + CALLBACKS` to 32 bits would land on - // the real callback array; the image is damaged and must not be prepared. - let far = IMAGE_BASE + (1 << 32); - let mut pointer = image(); - put64( - &mut pointer, - file(callbacks_field()), - far + u64::from(CALLBACKS), - ); - let mut callback = image(); - put64(&mut callback, file(CALLBACKS), far + u64::from(CODE)); - for (what, bytes) in [("callback array", pointer), ("callback", callback)] { - assert!( - matches!( - prepare(&bytes), - Err(victory_loader::PrepareError::Pe( - victory_pe::PeError::Malformed(_) - )) - ), - "{what} more than 4 GiB above the image base" - ); - } -} - -/// Unused bytes in the headers, after the section table and before -/// `SizeOfHeaders`. They are mapped at the RVA equal to their offset. -const HEADER_SLACK: u32 = 0x1C0; - -#[test] -fn a_relocation_table_in_the_headers_is_read_where_the_loader_reads_it() { - // The loaders find the table through the directory RVA in the mapped - // image, headers included. A copy of the block moved into the header - // slack must have its callback entry cleared as well. - let mut original = image(); - let block = original[file(RELOCS)..file(RELOCS) + 16].to_vec(); - put(&mut original, HEADER_SLACK as usize, &block); - // The old block stays in `.data`, but nothing points at it any more. - set_dir(&mut original, dir::BASERELOC, HEADER_SLACK, 16); - let info = ImageInfo::parse(&original).unwrap(); - assert_eq!(info.rva_to_file_offset(HEADER_SLACK), None); - - let prepared = prepare(&original).unwrap(); - let entry = HEADER_SLACK as usize + 8 + 2; - assert_eq!(&prepared.bytes[entry..entry + 2], &[0, 0]); - for range in [ - HEADER_SLACK as usize..entry, - entry + 2..HEADER_SLACK as usize + 16, - ] { - assert_eq!(&prepared.bytes[range.clone()], &original[range]); - } - assert_eq!( - &prepared.bytes[file(RELOCS)..file(RELOCS) + 16], - &original[file(RELOCS)..file(RELOCS) + 16], - "the stale block in `.data` is not a relocation table any more" - ); - - let delta = 0x5_0000_0000; - let mut mapped = prepared.bytes; - rebase(&mut mapped, delta); - assert_eq!(layout::read_u64(&mapped, file(callbacks_field())), Some(0)); - assert_eq!( - layout::read_u64(&mapped, file(CALLBACKS)), - Some(IMAGE_BASE + u64::from(CODE) + delta) - ); -} - -#[test] -fn a_relocation_table_in_the_headers_stops_at_size_of_headers() { - // A directory that starts in the header slack but claims to run past - // `SizeOfHeaders` is read only up to there: past it the mapped image - // is not the file. The block that fits is still read; the walk does - // not continue into the section's file bytes. - let mut original = image(); - let block = original[file(RELOCS)..file(RELOCS) + 16].to_vec(); - put(&mut original, HEADER_SLACK as usize, &block); - set_dir(&mut original, dir::BASERELOC, HEADER_SLACK, 0x1000); - let prepared = prepare(&original).unwrap(); - let entry = HEADER_SLACK as usize + 8 + 2; - assert_eq!(&prepared.bytes[entry..entry + 2], &[0, 0]); - assert_eq!( - &prepared.bytes[SECTION_FILE..file(TLS)], - &original[SECTION_FILE..file(TLS)] - ); - - // A block that would cross `SizeOfHeaders` is not read at all, so the - // only thing that still clears the callback pointer is the TLS write. - // Only its first 12 bytes fit; the header still claims all 16. - let mut crossing = image(); - let at = SECTION_FILE - 12; - put(&mut crossing, at, &block[..12]); - set_dir(&mut crossing, dir::BASERELOC, at as u32, 16); - let prepared = prepare(&crossing).unwrap(); - assert_eq!(&prepared.bytes[at..at + 12], &crossing[at..at + 12]); - assert_eq!( - layout::read_u64(&prepared.bytes, file(callbacks_field())), - Some(0) - ); -} - -#[test] -fn a_relocation_rva_past_the_headers_and_sections_is_not_read() { - // Between `SizeOfHeaders` and the first section, and past the last one, - // nothing is mapped from the file: no table is read there. - for rva in [SECTION_FILE as u32, 0x0800, 0x1_0000] { - let mut original = image(); - set_dir(&mut original, dir::BASERELOC, rva, 16); - let prepared = prepare(&original).unwrap_or_else(|e| panic!("{rva:#x}: {e}")); - assert_eq!( - &prepared.bytes[SECTION_FILE..], - &{ - let mut expected = original[SECTION_FILE..].to_vec(); - let at = file(callbacks_field()) - SECTION_FILE; - expected[at..at + 8].fill(0); - expected - }[..], - "{rva:#x}" - ); - } -} - -#[test] -fn relocation_types_x64_loaders_do_not_define_are_taken_as_pointer_wide() { - // Types 5 to 9 and 11 to 15 are machine-specific or reserved; Windows - // and Wine refuse to load an x64 image that uses them, so prepare cannot - // know how many bytes one would write. It takes each as a whole pointer: - // one on the callbacks pointer, or one four bytes before it (whose upper - // half would land on the pointer), becomes a no-op. One eight bytes - // before or past the pointer cannot reach it and stays as it is. - let at = |kind: u16, rva: u32| (kind << 12) | (rva - SECTION_RVA) as u16; - let field = callbacks_field(); - for kind in (5..=9).chain(11..=15) { - let entries = [ - at(kind, field), - at(kind, field - 4), - at(kind, field - 8), - at(kind, field + 8), - ]; - let original = with_callback_entries(&entries); - let prepared = prepare(&original) - .unwrap_or_else(|e| panic!("type {kind}: {e}")) - .bytes; - // `with_callback_entries` puts `entries` after the index pointer's - // DIR64 entry in the only block. - let first = file(RELOCS) + 10; - let slot = - |b: &[u8], i: usize| u16::from_le_bytes([b[first + 2 * i], b[first + 2 * i + 1]]); - assert_eq!( - (0..4).map(|i| slot(&prepared, i)).collect::<Vec<_>>(), - [0, 0, entries[2], entries[3]], - "type {kind}" - ); - // The index pointer's and the callback array's entries stay. - assert_eq!( - &prepared[file(RELOCS)..first], - &original[file(RELOCS)..first], - "type {kind}" - ); - assert_eq!(slot(&prepared, 4), dir64(CALLBACKS), "type {kind}"); - let tls = ImageInfo::parse(&prepared).unwrap().tls.unwrap(); - assert_eq!(tls.callbacks_va, 0, "type {kind}"); - } -} - -#[test] -fn a_block_page_that_is_not_page_aligned_still_names_the_callback_field() { - // The loaders add each entry's offset to its block's page RVA without - // checking that the page is 4 KiB aligned. A block for page `TLS` whose - // entry is the pointer's offset inside the TLS directory patches the - // pointer just as the aligned form does. - let mut original = image(); - let second = file(RELOCS) + 16; - put32(&mut original, second, TLS); - put32(&mut original, second + 4, 12); - put16( - &mut original, - second + 8, - (10 << 12) | layout::TLS64_ADDRESS_OF_CALLBACKS as u16, - ); - put16(&mut original, second + 10, 0); // ABSOLUTE padding - // Only the unaligned block names the field. - put16(&mut original, callbacks_reloc(), 0); - set_dir(&mut original, dir::BASERELOC, RELOCS, 28); - - let prepared = prepare(&original).unwrap(); - assert_eq!(&prepared.bytes[second + 8..second + 10], &[0, 0]); - assert_eq!( - &prepared.bytes[file(RELOCS)..second + 8], - &original[file(RELOCS)..second + 8], - "the first block and the second block's header are left alone" - ); - let mut mapped = prepared.bytes; - rebase(&mut mapped, 0x3_0000_0000); - assert_eq!(layout::read_u64(&mapped, file(callbacks_field())), Some(0)); -} - -#[test] -fn bytes_after_the_last_whole_block_end_the_walk_but_not_the_patch() { - // Some linkers round the directory up past the last block, and some - // leave a zeroed block header there. Neither is a block of entries, and - // the callback entry before it is cleared all the same. - for (what, size, tail) in [ - ("four stray bytes", 20u32, &[0xAA, 0xBB, 0xCC, 0xDD][..]), - ("a zeroed block header", 24, &[0; 8][..]), - ( - "a header of size 8 and no entries", - 24, - &[0, 0x10, 0, 0, 8, 0, 0, 0][..], - ), - ] { - let mut original = image(); - put(&mut original, file(RELOCS) + 16, tail); - set_dir(&mut original, dir::BASERELOC, RELOCS, size); - let prepared = prepare(&original).unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!(&prepared.bytes[callbacks_reloc()..][..2], &[0, 0], "{what}"); - let tail_at = file(RELOCS) + 16; - assert_eq!( - &prepared.bytes[tail_at..tail_at + tail.len()], - tail, - "{what}: the bytes past the last block are left as they were" - ); - } -} diff --git a/crates/victory-pe/src/image.rs b/crates/victory-pe/src/image.rs index f9fab9e2d7..fc8f0f6585 100644 --- a/crates/victory-pe/src/image.rs +++ b/crates/victory-pe/src/image.rs @@ -106,17 +106,15 @@ pub struct CodeViewInfo { impl CodeViewInfo { /// The key symbol servers use: GUID (Windows byte order) + age. pub fn symbol_key(&self) -> String { - use std::fmt::Write; let g = &self.guid; let d1 = u32::from_le_bytes([g[0], g[1], g[2], g[3]]); let d2 = u16::from_le_bytes([g[4], g[5]]); let d3 = u16::from_le_bytes([g[6], g[7]]); - let mut s = String::with_capacity(40); - let _ = write!(s, "{d1:08X}{d2:04X}{d3:04X}"); + let mut s = format!("{d1:08X}{d2:04X}{d3:04X}"); for b in &g[8..] { - let _ = write!(s, "{b:02X}"); + s.push_str(&format!("{b:02X}")); } - let _ = write!(s, "{:X}", self.age); + s.push_str(&format!("{:X}", self.age)); s } } @@ -145,7 +143,7 @@ impl ImageInfo { ))); } - let sections: Vec<SectionInfo> = file + let sections = file .section_table() .iter() .map(|s| SectionInfo { @@ -158,31 +156,6 @@ impl ImageInfo { }) .collect(); - // Validate section raw-data boundaries before accepting - // the PE image. - for section in §ions { - if section.file_size == 0 { - continue; - } - - let start = u64::from(section.file_offset); - let size = u64::from(section.file_size); - - let Some(end) = start.checked_add(size) else { - return Err(PeError::Malformed(format!( - "section '{}' has invalid raw-data bounds", - section.name - ))); - }; - - if end > data.len() as u64 { - return Err(PeError::Malformed(format!( - "section '{}' extends beyond file bounds", - section.name - ))); - } - } - let dir_present = |index: usize| { file.data_directory(index) .is_some_and(|d| d.virtual_address.get(LE) != 0 && d.size.get(LE) != 0) @@ -407,23 +380,13 @@ fn parse_tls( let array = sections .pe_data_at(data, array_rva) .ok_or_else(|| PeError::Malformed("TLS callback array outside of sections".into()))?; - let mut terminated = false; - for slot in array.as_chunks::<8>().0 { + for slot in array.as_chunks::<8>().0.iter().take(MAX_TLS_CALLBACKS) { let va = u64::from_le_bytes(*slot); if va == 0 { - terminated = true; break; } - if callback_rvas.len() == MAX_TLS_CALLBACKS { - return Err(PeError::Malformed( - "TLS callback count exceeds limit".into(), - )); - } callback_rvas.push(va_to_rva(va, image_base)?); } - if !terminated { - return Err(PeError::Malformed("unterminated TLS callback array".into())); - } } Ok(Some(TlsInfo { directory_rva, @@ -542,175 +505,6 @@ mod tests { d } - fn synthetic_tls(terminated: bool) -> Vec<u8> { - let mut body = vec![0u8; 0x200]; - let base = 0x1_8000_0000u64; - let callback_rva = if terminated { 0x11f0 } else { 0x11f8 }; - - body[24..32].copy_from_slice(&(base + callback_rva).to_le_bytes()); - - let off = (callback_rva - 0x1000) as usize; - body[off..off + 8].copy_from_slice(&(base + 0x1010).to_le_bytes()); - - let mut data = synthetic_image(&body); - - let export = layout::data_directory_offset(&data, 0).unwrap(); - data[export..export + 8].fill(0); - - let tls = layout::data_directory_offset(&data, 9).unwrap(); - data[tls..tls + 4].copy_from_slice(&0x1000u32.to_le_bytes()); - data[tls + 4..tls + 8].copy_from_slice(&40u32.to_le_bytes()); - - data - } - - #[test] - fn tls_probe_accepts_terminated_callbacks() { - let info = ImageInfo::parse(&synthetic_tls(true)).unwrap(); - assert_eq!(info.tls.unwrap().callback_rvas, vec![0x1010]); - } - - #[test] - fn tls_probe_rejects_unterminated_callbacks() { - let result = ImageInfo::parse(&synthetic_tls(false)); - assert!( - matches!(result, Err(PeError::Malformed(_))), - "Expected malformed TLS array, got {result:?}" - ); - } - - fn synthetic_tls_many(count: usize) -> Vec<u8> { - let mut data = synthetic_tls(true); - let base = 0x1_8000_0000u64; - let sec = 0x58 + 240; - - data.resize(0x2600, 0); - - for offset in [sec + 8, sec + 16] { - data[offset..offset + 4].copy_from_slice(&0x2400u32.to_le_bytes()); - } - - data[0x90..0x94].copy_from_slice(&0x4000u32.to_le_bytes()); - - data[0x218..0x220].copy_from_slice(&(base + 0x1040).to_le_bytes()); - - for i in 0..count { - let off = 0x240 + i * 8; - data[off..off + 8].copy_from_slice(&(base + 0x1010).to_le_bytes()); - } - - let end = 0x240 + count * 8; - data[end..end + 8].fill(0); - - data - } - - #[test] - fn tls_probe_accepts_exact_callback_limit() { - let info = ImageInfo::parse(&synthetic_tls_many(MAX_TLS_CALLBACKS)).unwrap(); - - assert_eq!(info.tls.unwrap().callback_rvas.len(), MAX_TLS_CALLBACKS); - } - - #[test] - fn tls_probe_rejects_callbacks_over_limit() { - let data = synthetic_tls_many(MAX_TLS_CALLBACKS + 1); - - assert!(matches!( - ImageInfo::parse(&data), - Err(PeError::Malformed(_)) - )); - } - - #[test] - fn tls_probe_accepts_empty_callback_list() { - let mut data = synthetic_tls(true); - data[0x3f0..0x3f8].fill(0); - - let info = ImageInfo::parse(&data).unwrap(); - assert!(info.tls.unwrap().callback_rvas.is_empty()); - } - - #[test] - fn tls_probe_accepts_null_callback_pointer() { - let mut data = synthetic_tls(true); - data[0x218..0x220].fill(0); - - let info = ImageInfo::parse(&data).unwrap(); - let tls = info.tls.unwrap(); - - assert_eq!(tls.callbacks_va, 0); - assert!(tls.callback_rvas.is_empty()); - } - - #[test] - fn rejects_section_extending_beyond_file() { - // Create a synthetic PE image. - let mut data = synthetic_image(&vec![0u8; 0x200]); - - // Remove the export directory to isolate section validation. - let opt = 0x58; - data[opt + 112..opt + 120].fill(0); - - // Verify the baseline PE is accepted. - assert!( - ImageInfo::parse(&data).is_ok(), - "baseline synthetic image must be valid" - ); - - // The section header starts after the 240-byte optional header. - let sec = opt + 240; - - // Declare 4096 bytes of raw section data. - // The actual file contains only 1024 bytes. - data[sec + 16..sec + 20].copy_from_slice(&0x1000u32.to_le_bytes()); - - // Investigate whether the parser rejects this malformed image. - assert!( - ImageInfo::parse(&data).is_err(), - "section extends beyond physical file bounds" - ); - } - - #[test] - fn accepts_section_ending_at_file_boundary() { - let mut data = synthetic_image(&vec![0u8; 0x200]); - - // Disable the export directory to isolate section validation. - let opt = 0x58; - data[opt + 112..opt + 120].fill(0); - - // Raw section: offset 0x200 + size 0x200 = file length 0x400. - let info = ImageInfo::parse(&data); - - assert!( - info.is_ok(), - "section ending exactly at EOF should be accepted" - ); - } - - #[test] - fn accepts_section_with_zero_raw_size() { - let mut data = synthetic_image(&vec![0u8; 0x200]); - - // Disable the export directory. - let opt = 0x58; - data[opt + 112..opt + 120].fill(0); - - // Section header begins after the optional header. - let sec = opt + 240; - - // A section may occupy virtual memory without having raw data. - data[sec + 16..sec + 20].copy_from_slice(&0u32.to_le_bytes()); - - let info = ImageInfo::parse(&data); - - assert!( - info.is_ok(), - "section with zero raw size should be accepted" - ); - } - #[test] fn unused_export_slots_are_not_exports() { // Ordinal base 1; three address slots: "alpha", an unused hole (0), @@ -750,17 +544,4 @@ mod tests { ] ); } - - #[test] - fn symbol_key_matches_pdb_convention() { - let cv = CodeViewInfo { - pdb_path: "test.pdb".into(), - guid: [ - 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, - 0x77, 0x88, - ], - age: 1, - }; - assert_eq!(cv.symbol_key(), "78563412BC9AF0DE11223344556677881"); - } } diff --git a/crates/victory-pe/src/implib.rs b/crates/victory-pe/src/implib.rs index 24b07d565c..234c1ecf01 100644 --- a/crates/victory-pe/src/implib.rs +++ b/crates/victory-pe/src/implib.rs @@ -4,10 +4,8 @@ //! console title may link against. That is the map the runtime needs to //! decide which of our implementations answers which import. -use object::Object; -use object::ObjectSymbol; use object::read::archive::ArchiveFile; -use object::read::coff::{CoffFile, ImportFile, ImportName, ImportType}; +use object::read::coff::{ImportFile, ImportName, ImportType}; use crate::{ImportSymbol, PeError}; @@ -30,167 +28,34 @@ pub enum LibImportKind { #[derive(Debug, Default)] pub struct ImportLibrary { pub imports: Vec<LibImport>, - /// Members that are not short-format imports (regular objects, long - /// import descriptors and their null thunks). Reported so nothing is - /// silently lost. + /// Members that are not short-format import objects (regular objects, + /// long-format import descriptors). Reported so nothing is silently lost. pub other_members: usize, } -// Values from the COFF import-object header. They are kept as plain integers -// here because the `object` crate exposes them as newtypes whose constants -// cannot be compared with bytes read from an archive. -const SIG1: u16 = 0; // IMAGE_FILE_MACHINE_UNKNOWN -const SIG2: u16 = 0xffff; // IMPORT_OBJECT_HDR_SIG2 -#[cfg(test)] -const TYPE_CODE: u16 = 0; -const TYPE_DATA: u16 = 1; -const TYPE_CONST: u16 = 2; -const NAME_ORDINAL: u16 = 0; -const NAME: u16 = 1; -const NAME_NO_PREFIX: u16 = 2; -const NAME_UNDECORATE: u16 = 3; -const NAME_EXPORTAS: u16 = 4; - -/// A long import descriptor has the same 20-byte prefix as a short import -/// object but carries no inline string data. The names live in the COFF -/// object that follows the null descriptor and null thunk members. -fn import_header(bytes: &[u8]) -> Option<(u16, u32, u16, u16)> { - if bytes.len() < 20 { - return None; - } - let sig1 = u16::from_le_bytes(bytes[0..2].try_into().ok()?); - let sig2 = u16::from_le_bytes(bytes[2..4].try_into().ok()?); - if sig1 != SIG1 || sig2 != SIG2 { - return None; - } - Some(( - u16::from_le_bytes(bytes[8..10].try_into().ok()?), // machine - u32::from_le_bytes(bytes[12..16].try_into().ok()?), // size_of_data - u16::from_le_bytes(bytes[16..18].try_into().ok()?), // ordinal/hint - u16::from_le_bytes(bytes[18..20].try_into().ok()?), // type/name type - )) -} - -fn import_kind(flags: u16) -> LibImportKind { - match flags & 0b11 { - TYPE_DATA => LibImportKind::Data, - TYPE_CONST => LibImportKind::Const, - _ => LibImportKind::Code, - } -} - -/// Names defined by the COFF object that belongs to a long descriptor. -fn coff_symbols(bytes: &[u8]) -> Vec<String> { - let Ok(file) = CoffFile::<_, object::pe::ImageFileHeader>::parse(bytes) else { - return Vec::new(); - }; - file.symbols() - .filter_map(|symbol| symbol.name().ok().map(str::to_owned)) - .collect() -} - -fn strip_decoration(name: &str, name_type: u16) -> String { - // `IMPORT_OBJECT_NAME` is passed through as-is; only the no-prefix and - // undecorate forms ask us to remove a leading decoration. - if name_type == NAME { - return name.to_owned(); - } - let stripped = if matches!(name_type, NAME_NO_PREFIX | NAME_UNDECORATE) { - name.strip_prefix(['?', '@', '_']).unwrap_or(name) - } else { - name - }; - if name_type == NAME_UNDECORATE { - stripped.split('@').next().unwrap_or(stripped).to_owned() - } else { - stripped.to_owned() - } -} - impl ImportLibrary { pub fn parse(data: &[u8]) -> Result<Self, PeError> { let archive = ArchiveFile::parse(data)?; let mut lib = ImportLibrary::default(); - let members: Vec<_> = archive.members().collect::<Result<Vec<_>, _>>()?; - let contents: Vec<Vec<u8>> = members - .iter() - .map(|member| member.data(data).map(<[u8]>::to_vec)) - .collect::<Result<_, _>>()?; - let mut consumed = vec![false; contents.len()]; - - for (index, member) in contents.iter().enumerate() { - if consumed[index] { - continue; - } - if let Some((_, size, ordinal, flags)) = import_header(member) { - if size == 0 { - // Long-format descriptor. Its DLL and export names live - // in the COFF object(s) that follow the null members. - consumed[index] = true; - lib.other_members += 1; - let kind = import_kind(flags); - let name_type = flags >> 2 & 0b111; - let mut dll = None; - let mut names = Vec::new(); - for (next, object) in contents.iter().enumerate().skip(index + 1) { - if consumed[next] || import_header(object).is_some() { - break; - } - let symbols = coff_symbols(object); - if symbols.is_empty() { - continue; - } - consumed[next] = true; - lib.other_members += 1; - for symbol in symbols { - if let Some(d) = symbol.strip_prefix("__IMPORT_DESCRIPTOR_") { - dll = Some(d.to_owned()); - } else if let Some(export) = symbol.strip_prefix("__imp_") { - names.push(export.to_owned()); - } - } - } - let Some(dll) = dll else { - continue; - }; - for name in names { - let export = if name_type == NAME_ORDINAL { - ImportSymbol::Ordinal(ordinal) - } else if name_type == NAME_EXPORTAS { - ImportSymbol::Name { hint: 0, name } - } else { - ImportSymbol::Name { - hint: 0, - name: strip_decoration(&name, name_type), - } - }; - lib.imports.push(LibImport { - dll: dll.clone(), - export, - kind, - }); - } - continue; - } - } - match ImportFile::parse(&member[..]) { - Ok(import) => { - lib.imports.push(LibImport { - dll: String::from_utf8_lossy(import.dll()).into_owned(), - export: match import.import() { - ImportName::Name(name) => ImportSymbol::Name { - hint: 0, - name: String::from_utf8_lossy(name).into_owned(), - }, - ImportName::Ordinal(o) => ImportSymbol::Ordinal(o), - }, - kind: match import.import_type() { - ImportType::Code => LibImportKind::Code, - ImportType::Data => LibImportKind::Data, - ImportType::Const => LibImportKind::Const, + for member in archive.members() { + let member = member?; + let bytes = member.data(data)?; + match ImportFile::parse(bytes) { + Ok(import) => lib.imports.push(LibImport { + dll: String::from_utf8_lossy(import.dll()).into_owned(), + export: match import.import() { + ImportName::Name(name) => ImportSymbol::Name { + hint: 0, + name: String::from_utf8_lossy(name).into_owned(), }, - }); - } + ImportName::Ordinal(o) => ImportSymbol::Ordinal(o), + }, + kind: match import.import_type() { + ImportType::Code => LibImportKind::Code, + ImportType::Data => LibImportKind::Data, + ImportType::Const => LibImportKind::Const, + }, + }), Err(_) => lib.other_members += 1, } } @@ -199,602 +64,3 @@ impl ImportLibrary { Ok(lib) } } - -#[cfg(test)] -mod tests { - use super::*; - - /// A short-format import object: `IMPORT_OBJECT_HEADER`, then the - /// symbol and the DLL name, each NUL-terminated. - fn short_import( - dll: &str, - symbol: &str, - ordinal_or_hint: u16, - ty: u16, - name_ty: u16, - ) -> Vec<u8> { - let data_len = symbol.len() + 1 + dll.len() + 1; - let mut out = Vec::new(); - out.extend_from_slice(&0u16.to_le_bytes()); // Sig1 - out.extend_from_slice(&0xFFFFu16.to_le_bytes()); // Sig2 - out.extend_from_slice(&0u16.to_le_bytes()); // Version - out.extend_from_slice(&crate::MACHINE_AMD64.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); // TimeDateStamp - out.extend_from_slice(&(data_len as u32).to_le_bytes()); - out.extend_from_slice(&ordinal_or_hint.to_le_bytes()); - out.extend_from_slice(&(ty | name_ty << 2).to_le_bytes()); - for s in [symbol, dll] { - out.extend_from_slice(s.as_bytes()); - out.push(0); - } - out - } - - /// A `!<arch>` archive of `members`, each under a short GNU-style name. - fn archive(members: &[Vec<u8>]) -> Vec<u8> { - let names: Vec<String> = (0..members.len()).map(|i| format!("m{i}.obj/")).collect(); - let named: Vec<(&str, &[u8])> = names - .iter() - .zip(members) - .map(|(name, data)| (name.as_str(), data.as_slice())) - .collect(); - archive_named(&named) - } - - /// A `!<arch>` archive whose members carry the raw header names given. - fn archive_named(members: &[(&str, &[u8])]) -> Vec<u8> { - let mut out = b"!<arch>\n".to_vec(); - for (name, data) in members { - let header = format!( - "{:<16}{:<12}{:<6}{:<6}{:<8}{:<10}`\n", - name, - 0, - 0, - 0, - 644, - data.len() - ); - assert_eq!(header.len(), 60); - out.extend_from_slice(header.as_bytes()); - out.extend_from_slice(data); - if data.len() % 2 == 1 { - out.push(b'\n'); - } - } - out - } - - const CODE: u16 = 0; - const DATA: u16 = 1; - const CONST: u16 = 2; - const BY_ORDINAL: u16 = 0; - const BY_NAME: u16 = 1; - const NO_PREFIX: u16 = 2; - const UNDECORATE: u16 = 3; - - fn name(dll: &str, name: &str, kind: LibImportKind) -> LibImport { - LibImport { - dll: dll.into(), - export: ImportSymbol::Name { - hint: 0, - name: name.into(), - }, - kind, - } - } - - #[test] - fn reads_short_imports_sorted_and_deduplicated() { - let lib = ImportLibrary::parse(&archive(&[ - short_import("b.dll", "_Stdcall@8", 7, CODE, UNDECORATE), - short_import("a.dll", "Plain", 3, CODE, BY_NAME), - short_import("a.dll", "_Prefixed", 0, DATA, NO_PREFIX), - short_import("a.dll", "Ignored", 42, CONST, BY_ORDINAL), - // The same export again, under another hint: one entry. - short_import("a.dll", "Plain", 9, CODE, BY_NAME), - // Not a short import object: counted, not dropped silently. - b"not an import".to_vec(), - ])) - .unwrap(); - - assert_eq!( - lib.imports, - [ - name("a.dll", "Plain", LibImportKind::Code), - name("a.dll", "Prefixed", LibImportKind::Data), - LibImport { - dll: "a.dll".into(), - export: ImportSymbol::Ordinal(42), - kind: LibImportKind::Const, - }, - name("b.dll", "Stdcall", LibImportKind::Code), - ] - ); - assert_eq!(lib.other_members, 1); - } - - #[test] - fn rejects_what_is_not_an_archive() { - assert!(ImportLibrary::parse(b"MZ not an archive").is_err()); - assert!( - ImportLibrary::parse(&archive(&[])) - .unwrap() - .imports - .is_empty() - ); - } - - /// The layout `lib.exe` writes: a first and a second linker member - /// (both named `/`), a `//` long-names member, then the import objects - /// under `/<offset>` names. The bookkeeping members are not imports and - /// not "other" members either. - #[test] - fn reads_msvc_layout_with_linker_and_long_name_members() { - // First linker member: big-endian symbol count, no symbols. - let first_linker = 0u32.to_be_bytes(); - // Second linker member: member count and symbol count, both 0. - let second_linker = [0u8; 8]; - let long_names = - b"a_member_name_too_long_for_the_header.obj\0another_long_member_name.obj\0"; - let first = short_import( - "xboxkrnl.exe", - "KeQueryPerformanceCounter", - 1, - CODE, - BY_NAME, - ); - let second = short_import("kernelx.dll", "GetTickCount64", 2, CODE, BY_NAME); - - let lib = ImportLibrary::parse(&archive_named(&[ - ("/", &first_linker), - ("/", &second_linker), - ("//", long_names), - ("/0", &first), - ("/42", &second), - ])) - .unwrap(); - - assert_eq!( - lib.imports, - [ - name("kernelx.dll", "GetTickCount64", LibImportKind::Code), - name( - "xboxkrnl.exe", - "KeQueryPerformanceCounter", - LibImportKind::Code - ), - ] - ); - assert_eq!(lib.other_members, 0); - } - - /// A damaged archive is an error, never a panic; a damaged member inside - /// an intact archive is counted, not read as an import. - #[test] - fn damaged_archives_and_members_do_not_panic() { - let good = short_import("a.dll", "Plain", 0, CODE, BY_NAME); - let whole = archive(std::slice::from_ref(&good)); - - // Every truncation of the archive either parses or errors. - for len in 0..whole.len() { - let _ = ImportLibrary::parse(&whole[..len]); - } - // A member header that claims more bytes than the file holds. - let mut oversized = whole.clone(); - let size_field = 8 + 48; - oversized[size_field..size_field + 10].copy_from_slice(b"999999 "); - assert!(ImportLibrary::parse(&oversized).is_err()); - // A long name that points past the names table. - assert!( - ImportLibrary::parse(&archive_named(&[("//", b"x.obj\0"), ("/99", &good)])).is_err() - ); - - // An import object whose SizeOfData runs past the member, and one cut - // short inside its fixed header: neither is an import. - let mut overlong = good.clone(); - overlong[12..16].copy_from_slice(&u32::MAX.to_le_bytes()); - let lib = - ImportLibrary::parse(&archive(&[overlong, good[..10].to_vec(), good.clone()])).unwrap(); - assert_eq!(lib.imports, [name("a.dll", "Plain", LibImportKind::Code)]); - assert_eq!(lib.other_members, 2); - } - - /// One export name in two DLLs, or once as code and once as data, is - /// two different imports: deduplication only drops exact repeats. - #[test] - fn keeps_the_same_name_from_other_dlls_and_of_other_kinds() { - let lib = ImportLibrary::parse(&archive(&[ - short_import("b.dll", "Shared", 0, CODE, BY_NAME), - short_import("a.dll", "Shared", 0, DATA, BY_NAME), - short_import("a.dll", "Shared", 0, CODE, BY_NAME), - short_import("a.dll", "Shared", 0, CODE, BY_NAME), - ])) - .unwrap(); - assert_eq!( - lib.imports, - [ - name("a.dll", "Shared", LibImportKind::Code), - name("a.dll", "Shared", LibImportKind::Data), - name("b.dll", "Shared", LibImportKind::Code), - ] - ); - assert_eq!(lib.other_members, 0); - } - - /// Names that are not UTF-8 are read lossily rather than rejected. - #[test] - fn reads_names_that_are_not_utf8() { - let mut member = short_import("x.dll", "Ab", 0, CODE, BY_NAME); - // After the 20-byte header: `Ab\0x.dll\0`. Damage one byte of the - // symbol and one of the DLL name. - member[20 + 1] = 0xFF; - member[20 + 3] = 0xFE; - let lib = ImportLibrary::parse(&archive(&[member])).unwrap(); - assert_eq!( - lib.imports, - [name("\u{FFFD}.dll", "A\u{FFFD}", LibImportKind::Code)] - ); - } - - /// A member that looks like an import object but lacks its `0xFFFF` - /// signature is a regular member, not an import. - #[test] - fn a_member_with_a_bad_signature_is_another_member() { - let mut member = short_import("a.dll", "Plain", 0, CODE, BY_NAME); - member[2] = 0xFE; // Sig2 is no longer 0xFFFF - let lib = ImportLibrary::parse(&archive(&[member])).unwrap(); - assert!(lib.imports.is_empty()); - assert_eq!(lib.other_members, 1); - } - - const EXPORT_AS: u16 = 4; - - /// A short-format import object with the extra export name that - /// `IMPORT_OBJECT_NAME_EXPORTAS` places after the DLL name. - fn export_as_import(dll: &str, symbol: &str, export: &str) -> Vec<u8> { - let mut out = short_import(dll, symbol, 0, CODE, EXPORT_AS); - out.extend_from_slice(export.as_bytes()); - out.push(0); - let data_len = (out.len() - 20) as u32; - out[12..16].copy_from_slice(&data_len.to_le_bytes()); - out - } - - /// `EXPORTAS` names the export with its third string, not the symbol; - /// one that lacks that string is not an import. - #[test] - fn reads_the_export_name_of_an_export_as_import() { - let lib = ImportLibrary::parse(&archive(&[ - export_as_import("a.dll", "__imp_Decorated@4", "Exported"), - // Same header, but SizeOfData stops after the DLL name. - short_import("a.dll", "Missing", 0, CODE, EXPORT_AS), - ])) - .unwrap(); - assert_eq!( - lib.imports, - [name("a.dll", "Exported", LibImportKind::Code)] - ); - assert_eq!(lib.other_members, 1); - } - - /// Import type 3 and name types 5 to 7 are not defined. Such members - /// are counted, and the members around them are still read. - #[test] - fn undefined_import_and_name_types_are_other_members() { - let lib = ImportLibrary::parse(&archive(&[ - short_import("a.dll", "BadType", 0, 3, BY_NAME), - short_import("a.dll", "Name5", 0, CODE, 5), - short_import("a.dll", "Kept", 0, CODE, BY_NAME), - short_import("a.dll", "Name6", 0, DATA, 6), - short_import("a.dll", "Name7", 0, CONST, 7), - ])) - .unwrap(); - assert_eq!(lib.imports, [name("a.dll", "Kept", LibImportKind::Code)]); - assert_eq!(lib.other_members, 4); - } - - /// `NO_PREFIX` drops one leading `?`, `@` or `_`; `UNDECORATE` also - /// drops everything from the first `@` after that. Names without a - /// prefix are kept as written. - #[test] - fn strips_one_prefix_and_the_stdcall_suffix() { - let cases = [ - ("?Question", NO_PREFIX, "Question"), - ("@At", NO_PREFIX, "At"), - ("__Twice", NO_PREFIX, "_Twice"), - ("Bare@4", NO_PREFIX, "Bare@4"), - ("_std@12", UNDECORATE, "std"), - ("@fast@8", UNDECORATE, "fast"), - ("?cpp@@YAXXZ", UNDECORATE, "cpp"), - ("plain", UNDECORATE, "plain"), - ]; - for (symbol, name_ty, expected) in cases { - let lib = - ImportLibrary::parse(&archive(&[short_import("a.dll", symbol, 0, CODE, name_ty)])) - .unwrap(); - assert_eq!( - lib.imports, - [name("a.dll", expected, LibImportKind::Code)], - "{symbol} with name type {name_ty}" - ); - } - } - - #[test] - fn ordinal_imports_keep_their_dll_and_kind() { - // By-ordinal objects still carry a symbol name; it is not the export, - // so two objects with one ordinal and different names are one entry. - let lib = ImportLibrary::parse(&archive(&[ - short_import("b.dll", "x", 1, DATA, BY_ORDINAL), - short_import("a.dll", "y", 1, CODE, BY_ORDINAL), - short_import("a.dll", "z", 1, CODE, BY_ORDINAL), - short_import("a.dll", "w", 2, CODE, BY_ORDINAL), - short_import("a.dll", "Named", 1, CODE, BY_NAME), - ])) - .unwrap(); - let ordinal = |dll: &str, o: u16, kind| LibImport { - dll: dll.into(), - export: ImportSymbol::Ordinal(o), - kind, - }; - assert_eq!( - lib.imports, - [ - name("a.dll", "Named", LibImportKind::Code), - ordinal("a.dll", 1, LibImportKind::Code), - ordinal("a.dll", 2, LibImportKind::Code), - ordinal("b.dll", 1, LibImportKind::Data), - ] - ); - assert_eq!(lib.other_members, 0); - } - - /// BSD archives keep a long member name in front of the member data - /// (`#1/<len>`); the import object starts after that name. - #[test] - fn reads_members_with_bsd_long_names() { - let member_name = b"a_long_bsd_member_name.obj\0\0"; - let mut member = member_name.to_vec(); - member.extend_from_slice(&short_import("a.dll", "Bsd", 0, CODE, BY_NAME)); - let header = format!("#1/{}", member_name.len()); - let lib = ImportLibrary::parse(&archive_named(&[(&header, &member)])).unwrap(); - assert_eq!(lib.imports, [name("a.dll", "Bsd", LibImportKind::Code)]); - assert_eq!(lib.other_members, 0); - - // A name length past the member is an error, not a panic. - let header = format!("#1/{}", member.len() + 1); - assert!(ImportLibrary::parse(&archive_named(&[(&header, &member)])).is_err()); - } - - /// The members of a thin archive live in other files, so the archive - /// holds no import objects; each member is counted, none is read. - #[test] - fn thin_archive_members_are_counted_not_read() { - // A thin archive's member headers are not followed by their data; - // each header carries the size of the outside file. - let mut out = b"!<thin>\n".to_vec(); - for i in 0..2 { - let header = format!( - "{:<16}{:<12}{:<6}{:<6}{:<8}{:<10}`\n", - format!("m{i}.obj/"), - 0, - 0, - 0, - 644, - 100 - ); - out.extend_from_slice(header.as_bytes()); - } - let lib = ImportLibrary::parse(&out).unwrap(); - assert!(lib.imports.is_empty()); - assert_eq!(lib.other_members, 2); - } - - /// A long-format import member is an ordinary COFF object: it starts - /// with its machine, not the `0, 0xFFFF` signature, so it is counted. - #[test] - fn a_coff_object_member_is_another_member() { - let mut coff = Vec::new(); - coff.extend_from_slice(&crate::MACHINE_AMD64.to_le_bytes()); - coff.extend_from_slice(&0u16.to_le_bytes()); // NumberOfSections - coff.extend_from_slice(&[0u8; 16]); // the rest of IMAGE_FILE_HEADER - let lib = ImportLibrary::parse(&archive(&[ - coff, - short_import("a.dll", "Kept", 0, CODE, BY_NAME), - ])) - .unwrap(); - assert_eq!(lib.imports, [name("a.dll", "Kept", LibImportKind::Code)]); - assert_eq!(lib.other_members, 1); - } - - /// GNU `ar` writes a `/SYM64/` symbol table for large archives. Like - /// the `/` linker members it is bookkeeping: neither an import nor an - /// other member. - #[test] - fn the_gnu_64_bit_symbol_table_is_skipped() { - let sym64 = 0u64.to_be_bytes(); - let import = short_import("a.dll", "After", 0, CODE, BY_NAME); - let lib = ImportLibrary::parse(&archive_named(&[("/SYM64/", &sym64), ("a.obj/", &import)])) - .unwrap(); - assert_eq!(lib.imports, [name("a.dll", "After", LibImportKind::Code)]); - assert_eq!(lib.other_members, 0); - } - - /// The symbol and the DLL name must both end inside `SizeOfData`. An - /// object whose DLL name is cut before its NUL is not an import. - #[test] - fn a_dll_name_without_its_terminator_is_not_an_import() { - let mut member = short_import("a.dll", "Cut", 0, CODE, BY_NAME); - member.pop(); // drop the DLL name's NUL - let data_len = (member.len() - 20) as u32; - member[12..16].copy_from_slice(&data_len.to_le_bytes()); - let lib = ImportLibrary::parse(&archive(&[member])).unwrap(); - assert!(lib.imports.is_empty()); - assert_eq!(lib.other_members, 1); - } - - /// `ar` pads a member of odd length with one `\n` so the next header - /// starts on an even offset. The member after the pad is read too. - #[test] - fn a_member_of_odd_length_is_followed_by_its_padding() { - let odd = short_import("a.dll", "Od", 0, CODE, BY_NAME); - assert_eq!(odd.len() % 2, 1, "the fixture needs an odd member"); - let whole = archive(&[odd, short_import("b.dll", "Even", 0, DATA, BY_NAME)]); - let lib = ImportLibrary::parse(&whole).unwrap(); - assert_eq!( - lib.imports, - [ - name("a.dll", "Od", LibImportKind::Code), - name("b.dll", "Even", LibImportKind::Data), - ] - ); - assert_eq!(lib.other_members, 0); - } - - /// A member with no bytes at all is not an import object: it is - /// counted, and the members after it are still read. - #[test] - fn an_empty_member_is_another_member() { - let lib = ImportLibrary::parse(&archive(&[ - Vec::new(), - short_import("a.dll", "After", 0, CODE, BY_NAME), - ])) - .unwrap(); - assert_eq!(lib.imports, [name("a.dll", "After", LibImportKind::Code)]); - assert_eq!(lib.other_members, 1); - } - - /// The machine field is not filtered: an umbrella library is read for - /// its DLL map, and an import object for another machine names the same - /// `dll!export` pair. - #[test] - fn an_import_object_for_another_machine_is_still_read() { - let mut member = short_import("a.dll", "Arm", 0, CODE, BY_NAME); - member[6..8].copy_from_slice(&0xAA64u16.to_le_bytes()); // ARM64 - let lib = ImportLibrary::parse(&archive(&[member])).unwrap(); - assert_eq!(lib.imports, [name("a.dll", "Arm", LibImportKind::Code)]); - assert_eq!(lib.other_members, 0); - } - - /// A symbol that is nothing but the prefix `NO_PREFIX` strips, or an - /// empty symbol read by name, names the empty export rather than - /// failing the library. - #[test] - fn a_symbol_that_is_only_a_prefix_names_the_empty_export() { - let lib = ImportLibrary::parse(&archive(&[ - short_import("a.dll", "_", 0, CODE, NO_PREFIX), - short_import("a.dll", "", 0, CODE, BY_NAME), - short_import("a.dll", "_@4", 0, CODE, UNDECORATE), - ])) - .unwrap(); - assert_eq!(lib.imports, [name("a.dll", "", LibImportKind::Code)]); - assert_eq!(lib.other_members, 0); - } - - fn long_descriptor(ordinal: u16, flags: u16) -> Vec<u8> { - let mut out = vec![0u8; 20]; - out[2..4].copy_from_slice(&SIG2.to_le_bytes()); - out[8..10].copy_from_slice(&0x8664u16.to_le_bytes()); - out[16..18].copy_from_slice(&ordinal.to_le_bytes()); - out[18..20].copy_from_slice(&flags.to_le_bytes()); - out - } - - /// A minimal COFF object with undefined external symbols. - fn coff_object(names: &[&str]) -> Vec<u8> { - let mut strings = Vec::new(); - let mut offsets = Vec::new(); - for name in names { - offsets.push(strings.len() as u32 + 4); - strings.extend_from_slice(name.as_bytes()); - strings.push(0); - } - let mut out = Vec::new(); - out.extend_from_slice(&0x8664u16.to_le_bytes()); // machine - out.extend_from_slice(&0u16.to_le_bytes()); // sections - out.extend_from_slice(&0u32.to_le_bytes()); // timestamp - out.extend_from_slice(&20u32.to_le_bytes()); // symbol table offset - out.extend_from_slice(&(names.len() as u32).to_le_bytes()); - out.extend_from_slice(&0u16.to_le_bytes()); // optional header - out.extend_from_slice(&0u16.to_le_bytes()); // characteristics - for offset in offsets { - out.extend_from_slice(&0u32.to_le_bytes()); - out.extend_from_slice(&offset.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); // value - out.extend_from_slice(&0i16.to_le_bytes()); // undefined section - out.extend_from_slice(&0u16.to_le_bytes()); // type - out.push(2); // external - out.push(0); // no aux records - } - out.extend_from_slice(&(strings.len() as u32 + 4).to_le_bytes()); - out.extend_from_slice(&strings); - out - } - - #[test] - fn short_imports_are_read() { - let bytes = archive(&[short_import( - "xsystem.dll", - "XSystemGetDeviceType", - 0, - TYPE_CODE, - NAME, - )]); - let lib = ImportLibrary::parse(&bytes).unwrap(); - assert_eq!(lib.imports.len(), 1); - assert_eq!(lib.imports[0].dll, "xsystem.dll"); - assert_eq!( - lib.imports[0].export, - ImportSymbol::Name { - hint: 0, - name: "XSystemGetDeviceType".into() - } - ); - assert_eq!(lib.other_members, 0); - } - - #[test] - fn long_imports_take_their_names_from_the_coff_object() { - let object = coff_object(&[ - "__IMPORT_DESCRIPTOR_xsystem.dll", - "__imp_XSystemGetDeviceType", - "__imp_XSystemSetDeviceType", - ]); - let bytes = archive(&[ - long_descriptor(0, TYPE_CODE | NAME << 2), - vec![0u8; 20], - vec![0u8; 8], - object, - ]); - let lib = ImportLibrary::parse(&bytes).unwrap(); - let exports: Vec<_> = lib - .imports - .iter() - .filter(|i| i.dll == "xsystem.dll") - .map(|i| i.export.to_string()) - .collect(); - assert_eq!(exports, ["XSystemGetDeviceType", "XSystemSetDeviceType"]); - // Descriptor, null descriptor, null thunk and the symbols object. - assert_eq!(lib.other_members, 4); - } - - #[test] - fn long_import_by_ordinal_uses_the_header_value() { - let object = coff_object(&[ - "__IMPORT_DESCRIPTOR_xsystem.dll", - "__imp_XSystemGetDeviceType", - ]); - let bytes = archive(&[long_descriptor(42, NAME_ORDINAL), object]); - let lib = ImportLibrary::parse(&bytes).unwrap(); - assert_eq!(lib.imports.len(), 1); - assert_eq!(lib.imports[0].export, ImportSymbol::Ordinal(42)); - } - - #[test] - fn unknown_members_are_reported_not_silently_dropped() { - let bytes = archive(&[vec![1, 2, 3]]); - let lib = ImportLibrary::parse(&bytes).unwrap(); - assert!(lib.imports.is_empty()); - assert_eq!(lib.other_members, 1); - } -} diff --git a/crates/victory-pe/src/layout.rs b/crates/victory-pe/src/layout.rs index 52fff0884a..888f9d23fd 100644 --- a/crates/victory-pe/src/layout.rs +++ b/crates/victory-pe/src/layout.rs @@ -16,8 +16,6 @@ pub const FILE_HEADER_CHARACTERISTICS: usize = 18; /// `IMAGE_OPTIONAL_HEADER64::AddressOfEntryPoint` (u32). pub const OPT_ADDRESS_OF_ENTRY_POINT: usize = 16; -/// `IMAGE_OPTIONAL_HEADER64::SizeOfHeaders` (u32). -pub const OPT_SIZE_OF_HEADERS: usize = 60; /// `IMAGE_OPTIONAL_HEADER64::CheckSum` (u32). pub const OPT_CHECKSUM: usize = 64; /// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` (u16). @@ -103,118 +101,10 @@ pub fn read_u64(data: &[u8], at: usize) -> Option<u64> { mod tests { use super::*; - #[test] - fn header_offsets_follow_the_dos_header_pointer() { - let mut data = [0u8; 0x100]; - data[DOS_E_LFANEW..DOS_E_LFANEW + 4].copy_from_slice(&0x40u32.to_le_bytes()); - - assert_eq!(file_header_offset(&data), Some(0x44)); - assert_eq!(optional_header_offset(&data), Some(0x58)); - } - - #[test] - fn data_directory_offsets_respect_declared_entry_count() { - let mut data = vec![0u8; 0x200]; - data[DOS_E_LFANEW..DOS_E_LFANEW + 4].copy_from_slice(&0x40u32.to_le_bytes()); - - let optional = 0x58; - let count_at = optional + OPT_NUMBER_OF_RVA_AND_SIZES; - data[count_at..count_at + 4].copy_from_slice(&2u32.to_le_bytes()); - - let first = optional + OPT_DATA_DIRECTORY; - assert_eq!(data_directory_offset(&data, 0), Some(first)); - assert_eq!( - data_directory_offset(&data, 1), - Some(first + DATA_DIRECTORY_SIZE) - ); - assert_eq!(data_directory_offset(&data, 2), None); - } - - #[test] - fn header_offset_helpers_reject_truncated_headers() { - let truncated_dos = [0u8; DOS_E_LFANEW + 3]; - assert_eq!(file_header_offset(&truncated_dos), None); - assert_eq!(optional_header_offset(&truncated_dos), None); - - let mut truncated_optional = [0u8; 0x100]; - truncated_optional[DOS_E_LFANEW..DOS_E_LFANEW + 4].copy_from_slice(&0x40u32.to_le_bytes()); - - assert_eq!(data_directory_offset(&truncated_optional, 0), None); - } - #[test] fn reads_reject_overflowing_offsets() { let data = [0u8; 16]; assert_eq!(read_u32(&data, usize::MAX - 1), None); assert_eq!(read_u64(&data, usize::MAX - 2), None); } - - /// Just enough of a PE32+ header for the offset helpers: `e_lfanew` and - /// `NumberOfRvaAndSizes`. - fn headers(lfanew: u32, directories: u32) -> Vec<u8> { - let mut data = vec![0u8; 0x200]; - data[DOS_E_LFANEW..DOS_E_LFANEW + 4].copy_from_slice(&lfanew.to_le_bytes()); - let count = - lfanew as usize + NT_SIGNATURE_SIZE + FILE_HEADER_SIZE + OPT_NUMBER_OF_RVA_AND_SIZES; - data[count..count + 4].copy_from_slice(&directories.to_le_bytes()); - data - } - - #[test] - fn header_offsets_follow_e_lfanew() { - let data = headers(0x80, 16); - assert_eq!(file_header_offset(&data), Some(0x84)); - assert_eq!(optional_header_offset(&data), Some(0x98)); - assert_eq!(data_directory_offset(&data, 0), Some(0x98 + 112)); - assert_eq!(data_directory_offset(&data, 15), Some(0x98 + 112 + 15 * 8)); - } - - #[test] - fn offsets_need_the_bytes_they_are_read_from() { - // No `e_lfanew`: no header offsets at all. - assert_eq!(file_header_offset(&[0; DOS_E_LFANEW + 3]), None); - assert_eq!(optional_header_offset(&[0; DOS_E_LFANEW + 3]), None); - // `e_lfanew` is read, but `NumberOfRvaAndSizes` is past the end. - let mut data = vec![0u8; DOS_E_LFANEW + 4]; - data[DOS_E_LFANEW..].copy_from_slice(&0x40u32.to_le_bytes()); - assert_eq!(file_header_offset(&data), Some(0x44)); - assert_eq!(data_directory_offset(&data, 0), None); - // A huge `e_lfanew` is an offset past the file, never a panic. - let data = { - let mut d = vec![0u8; 0x40]; - d[DOS_E_LFANEW..DOS_E_LFANEW + 4].copy_from_slice(&u32::MAX.to_le_bytes()); - d - }; - assert_eq!( - optional_header_offset(&data), - Some(u32::MAX as usize + NT_SIGNATURE_SIZE + FILE_HEADER_SIZE) - ); - assert_eq!(data_directory_offset(&data, 0), None); - } - - #[test] - fn directories_past_number_of_rva_and_sizes_are_absent() { - let data = headers(0x40, 10); - assert!(data_directory_offset(&data, 9).is_some()); - assert_eq!(data_directory_offset(&data, 10), None); - assert_eq!(data_directory_offset(&data, dir::BOUND_IMPORT), None); - assert_eq!(data_directory_offset(&headers(0x40, 0), 0), None); - // A count far beyond the 16 defined slots is taken as written; the - // offset it allows may lie past the file, for the read to refuse. - let data = headers(0x40, u32::MAX); - let far = data_directory_offset(&data, 100).unwrap(); - assert_eq!(far, 0x40 + 24 + OPT_DATA_DIRECTORY + 800); - assert_eq!(read_u32(&data, far), None); - assert_eq!(data_directory_offset(&data, u32::MAX as usize), None); - } - - #[test] - fn reads_are_little_endian_and_bounded() { - let data = [1, 2, 3, 4, 5, 6, 7, 8]; - assert_eq!(read_u32(&data, 0), Some(0x0403_0201)); - assert_eq!(read_u32(&data, 4), Some(0x0807_0605)); - assert_eq!(read_u32(&data, 5), None); - assert_eq!(read_u64(&data, 0), Some(0x0807_0605_0403_0201)); - assert_eq!(read_u64(&data, 1), None); - } } diff --git a/crates/victory-pe/tests/synthetic_image.rs b/crates/victory-pe/tests/synthetic_image.rs deleted file mode 100644 index fb723150be..0000000000 --- a/crates/victory-pe/tests/synthetic_image.rs +++ /dev/null @@ -1,1074 +0,0 @@ -//! `ImageInfo` against a small PE32+ image built in the test, so these checks -//! run on every host. The unit tests that parse the test binary itself only -//! run where that binary is a PE image (Windows). - -use victory_pe::layout::{self, dir}; -use victory_pe::{ImageInfo, ImportSymbol, MACHINE_AMD64, PeError}; - -const IMAGE_BASE: u64 = 0x1_4000_0000; -/// The one section: RVA 0x1000, file offset 0x200, 0x400 bytes. -const SECTION_RVA: u32 = 0x1000; -const SECTION_FILE_OFFSET: u32 = 0x200; -const SECTION_SIZE: u32 = 0x400; -const SIZE_OF_IMAGE: u32 = 0x2000; -const OPT: usize = 0x58; -const DIR_TLS: usize = 9; - -/// Section contents, by RVA. -const ENTRY: u32 = 0x1000; -const IMPORT_DESCRIPTORS: u32 = 0x1100; -const NAME_TABLE: u32 = 0x1180; -const IAT: u32 = 0x11A0; -const DLL_NAME: u32 = 0x11C0; -const HINT_NAME: u32 = 0x11D0; -const TLS_DIRECTORY: u32 = 0x1200; -const TLS_CALLBACKS: u32 = 0x1240; - -fn put16(d: &mut [u8], at: usize, v: u16) { - d[at..at + 2].copy_from_slice(&v.to_le_bytes()); -} - -fn put32(d: &mut [u8], at: usize, v: u32) { - d[at..at + 4].copy_from_slice(&v.to_le_bytes()); -} - -fn put64(d: &mut [u8], at: usize, v: u64) { - d[at..at + 8].copy_from_slice(&v.to_le_bytes()); -} - -/// File offset of an RVA inside the section. -fn at(rva: u32) -> usize { - (rva - SECTION_RVA + SECTION_FILE_OFFSET) as usize -} - -/// An x86-64 executable importing `KERNEL32.dll!ExitProcess` (hint 0x123) -/// and ordinal 5 from it, with two TLS callbacks. -fn image() -> Vec<u8> { - let mut d = vec![0u8; (SECTION_FILE_OFFSET + SECTION_SIZE) as usize]; - d[0..2].copy_from_slice(b"MZ"); - put32(&mut d, layout::DOS_E_LFANEW, 0x40); - d[0x40..0x44].copy_from_slice(b"PE\0\0"); - put16(&mut d, 0x44, MACHINE_AMD64); - put16(&mut d, 0x46, 1); // sections - put32(&mut d, 0x48, 0x6000_0000); // timestamp - put16(&mut d, 0x54, 240); // optional header size - put16(&mut d, 0x56, 0x0022); // executable, large address aware - - put16(&mut d, OPT, 0x20B); - put32(&mut d, OPT + 16, ENTRY); - put64(&mut d, OPT + 24, IMAGE_BASE); - put32(&mut d, OPT + 32, 0x1000); // section alignment - put32(&mut d, OPT + 36, 0x200); // file alignment - put32(&mut d, OPT + 56, SIZE_OF_IMAGE); - put32(&mut d, OPT + 60, 0x200); // size of headers - put16(&mut d, OPT + 68, layout::subsystem::WINDOWS_CUI); - put64(&mut d, OPT + 72, 0x10_0000); // stack reserve - put64(&mut d, OPT + 80, 0x1000); // stack commit - put32(&mut d, OPT + 108, 16); - let dd = |index: usize| OPT + layout::OPT_DATA_DIRECTORY + index * 8; - put32(&mut d, dd(dir::IMPORT), IMPORT_DESCRIPTORS); - put32(&mut d, dd(dir::IMPORT) + 4, 40); - put32(&mut d, dd(DIR_TLS), TLS_DIRECTORY); - put32(&mut d, dd(DIR_TLS) + 4, 40); - - let sec = OPT + 240; - d[sec..sec + 5].copy_from_slice(b".text"); - put32(&mut d, sec + 8, SECTION_SIZE); - put32(&mut d, sec + 12, SECTION_RVA); - put32(&mut d, sec + 16, SECTION_SIZE); - put32(&mut d, sec + 20, SECTION_FILE_OFFSET); - put32(&mut d, sec + 36, 0xE000_0020); // code, read, write, execute - - d[at(ENTRY)] = 0xC3; // ret - - // One descriptor, then the all-zero terminator. - let desc = at(IMPORT_DESCRIPTORS); - put32(&mut d, desc, NAME_TABLE); - put32(&mut d, desc + 12, DLL_NAME); - put32(&mut d, desc + 16, IAT); - for table in [NAME_TABLE, IAT] { - put64(&mut d, at(table), u64::from(HINT_NAME)); - put64(&mut d, at(table) + 8, (1 << 63) | 5); - } - let name = b"KERNEL32.dll\0"; - d[at(DLL_NAME)..at(DLL_NAME) + name.len()].copy_from_slice(name); - put16(&mut d, at(HINT_NAME), 0x123); - let func = b"ExitProcess\0"; - d[at(HINT_NAME) + 2..at(HINT_NAME) + 2 + func.len()].copy_from_slice(func); - - put64( - &mut d, - at(TLS_DIRECTORY) + layout::TLS64_ADDRESS_OF_CALLBACKS, - IMAGE_BASE + u64::from(TLS_CALLBACKS), - ); - put64(&mut d, at(TLS_CALLBACKS), IMAGE_BASE + 0x1010); - put64(&mut d, at(TLS_CALLBACKS) + 8, IMAGE_BASE + 0x1020); - d -} - -#[test] -fn reads_headers_and_sections() { - let info = ImageInfo::parse(&image()).unwrap(); - assert_eq!(info.machine, MACHINE_AMD64); - assert!(!info.is_dll()); - assert_eq!(info.timestamp, 0x6000_0000); - assert_eq!(info.image_base, IMAGE_BASE); - assert_eq!(info.size_of_image, SIZE_OF_IMAGE); - assert_eq!(info.entry_rva, ENTRY); - assert_eq!(info.subsystem_name(), "windows-cui"); - assert_eq!((info.stack_reserve, info.stack_commit), (0x10_0000, 0x1000)); - assert_eq!(info.sections.len(), 1); - let s = &info.sections[0]; - assert!(s.name.starts_with(".text")); - assert_eq!((s.rva, s.virtual_size), (SECTION_RVA, SECTION_SIZE)); - assert_eq!( - (s.file_offset, s.file_size), - (SECTION_FILE_OFFSET, SECTION_SIZE) - ); - assert!(!info.has_relocations); - assert!(!info.has_exception_table); - assert!(info.exports.is_empty()); - assert!(info.delay_imports.is_empty()); - assert!(info.codeview.is_none()); -} - -#[test] -fn reads_imports_with_their_iat_slots() { - let info = ImageInfo::parse(&image()).unwrap(); - assert_eq!(info.imports.len(), 1); - let kernel32 = &info.imports[0]; - assert_eq!(kernel32.dll, "KERNEL32.dll"); - let entries: Vec<_> = kernel32 - .entries - .iter() - .map(|e| (e.symbol.clone(), e.iat_slot_rva)) - .collect(); - assert_eq!( - entries, - [ - ( - ImportSymbol::Name { - hint: 0x123, - name: "ExitProcess".into() - }, - IAT - ), - (ImportSymbol::Ordinal(5), IAT + 8), - ] - ); - assert_eq!(info.import_count(), 2); -} - -#[test] -fn reads_tls_callbacks_in_order() { - let tls = ImageInfo::parse(&image()).unwrap().tls.unwrap(); - assert_eq!(tls.directory_rva, TLS_DIRECTORY); - assert_eq!(tls.callbacks_va, IMAGE_BASE + u64::from(TLS_CALLBACKS)); - assert_eq!(tls.callback_rvas, [0x1010, 0x1020]); -} - -#[test] -fn tls_callback_below_the_image_base_is_malformed() { - let mut d = image(); - put64(&mut d, at(TLS_CALLBACKS) + 8, IMAGE_BASE - 0x1000); - assert!(matches!(ImageInfo::parse(&d), Err(PeError::Malformed(_)))); -} - -#[test] -fn rva_to_file_offset_maps_section_data() { - let data = image(); - let mut info = ImageInfo::parse(&data).unwrap(); - let entry = info.rva_to_file_offset(info.entry_rva).unwrap() as usize; - assert_eq!(data[entry], 0xC3); - assert_eq!( - info.rva_to_file_offset(HINT_NAME), - Some(at(HINT_NAME) as u32) - ); - // Headers and the end of the section are not section data. - assert_eq!(info.rva_to_file_offset(0x40), None); - assert_eq!(info.rva_to_file_offset(SECTION_RVA + SECTION_SIZE), None); - // Raw data past the virtual size is padding, not part of the section. - info.sections[0].virtual_size = 0x100; - assert_eq!(info.rva_to_file_offset(SECTION_RVA + 0xFF), Some(0x2FF)); - assert_eq!(info.rva_to_file_offset(SECTION_RVA + 0x100), None); - // An offset near 4 GiB does not wrap. - info.sections[0].file_offset = u32::MAX - 0x10; - assert_eq!(info.rva_to_file_offset(SECTION_RVA + 0x20), None); -} - -#[test] -fn rejects_iat_outside_image() { - for iat in [SIZE_OF_IMAGE - 8, 0xFFFF_FFF8] { - let mut d = image(); - // The second slot (or the first, at the 4 GiB limit) runs past the end. - put32(&mut d, at(IMPORT_DESCRIPTORS) + 16, iat); - assert!( - matches!(ImageInfo::parse(&d), Err(PeError::Malformed(_))), - "IAT at {iat:#x}" - ); - } -} - -#[test] -fn rejects_other_machines() { - let mut d = image(); - put16(&mut d, 0x44, 0xAA64); // ARM64 - assert!(matches!(ImageInfo::parse(&d), Err(PeError::Unsupported(_)))); -} - -#[test] -fn rejects_truncated_images_without_panicking() { - let d = image(); - for len in [0, 2, 0x40, 0x58, 0x150, 0x200] { - assert!(ImageInfo::parse(&d[..len]).is_err(), "{len} bytes"); - } -} - -// Optional directories, each added to the image by the test that needs it. -// They live in the free tail of the section (0x1280..0x1400). -const DIR_EXPORT: usize = 0; -const DIR_DEBUG: usize = 6; -const DIR_DELAY_IMPORT: usize = 13; - -const DELAY_DESCRIPTORS: u32 = 0x1280; -const DELAY_NAME_TABLE: u32 = 0x12C0; -const DELAY_IAT: u32 = 0x12D0; -const DELAY_DLL_NAME: u32 = 0x12E0; -const DELAY_HINT_NAME: u32 = 0x12F0; -const DEBUG_DIRECTORY: u32 = 0x1300; -const CODEVIEW: u32 = 0x1320; -const EXPORT_DIRECTORY: u32 = 0x1350; -const EXPORT_DIRECTORY_END: u32 = 0x1400; - -fn put_bytes(d: &mut [u8], rva: u32, bytes: &[u8]) { - d[at(rva)..at(rva) + bytes.len()].copy_from_slice(bytes); -} - -fn set_directory(d: &mut [u8], index: usize, rva: u32, size: u32) { - let entry = OPT + layout::OPT_DATA_DIRECTORY + index * layout::DATA_DIRECTORY_SIZE; - put32(d, entry, rva); - put32(d, entry + 4, size); -} - -/// Delay-loads `USER32.dll!MessageBoxW` (hint 7) with an RVA-based descriptor. -fn add_delay_import(d: &mut [u8]) { - set_directory(d, DIR_DELAY_IMPORT, DELAY_DESCRIPTORS, 64); - let desc = at(DELAY_DESCRIPTORS); - put32(d, desc, 1); // attributes: RVA based - put32(d, desc + 4, DELAY_DLL_NAME); - put32(d, desc + 12, DELAY_IAT); - put32(d, desc + 16, DELAY_NAME_TABLE); - put64(d, at(DELAY_NAME_TABLE), u64::from(DELAY_HINT_NAME)); - put_bytes(d, DELAY_DLL_NAME, b"USER32.dll\0"); - put16(d, at(DELAY_HINT_NAME), 7); - put_bytes(d, DELAY_HINT_NAME + 2, b"MessageBoxW\0"); -} - -/// A CodeView debug directory entry whose record has signature `sig`. -fn add_codeview(d: &mut [u8], sig: &[u8; 4]) { - set_directory(d, DIR_DEBUG, DEBUG_DIRECTORY, 28); - let dbg = at(DEBUG_DIRECTORY); - put32(d, dbg + 12, 2); // IMAGE_DEBUG_TYPE_CODEVIEW - put32(d, dbg + 16, 4 + 16 + 4 + 6); // size of data - put32(d, dbg + 20, CODEVIEW); - put32(d, dbg + 24, at(CODEVIEW) as u32); // pointer to raw data - put_bytes(d, CODEVIEW, sig); - let guid: Vec<u8> = (0..16).collect(); - put_bytes(d, CODEVIEW + 4, &guid); - put32(d, at(CODEVIEW) + 20, 0x2A); // age - put_bytes(d, CODEVIEW + 24, b"t.pdb\0"); -} - -/// Exports ordinal 1 `local` at the entry point, ordinal 2 `fwdname` forwarded -/// to `NTDLL.RtlFoo` and ordinal 3 `fwdord` forwarded to `NTDLL.#7`. -fn add_exports(d: &mut [u8]) { - set_directory( - d, - DIR_EXPORT, - EXPORT_DIRECTORY, - EXPORT_DIRECTORY_END - EXPORT_DIRECTORY, - ); - let (addresses, names, ordinals) = (0x1378, 0x1384, 0x1390); - let (dll, local, fwdname, fwdord) = (0x1398, 0x13A0, 0x13A8, 0x13B0); - let (to_name, to_ordinal) = (0x13B8, 0x13C8); - let ed = at(EXPORT_DIRECTORY); - put32(d, ed + 12, dll); - put32(d, ed + 16, 1); // ordinal base - put32(d, ed + 20, 3); // functions - put32(d, ed + 24, 3); // names - put32(d, ed + 28, addresses); - put32(d, ed + 32, names); - put32(d, ed + 36, ordinals); - // A forwarder is an address inside the export directory. - for (i, rva) in [ENTRY, to_name, to_ordinal].into_iter().enumerate() { - put32(d, at(addresses) + i * 4, rva); - } - // The name pointer table is sorted; each name maps to its ordinal index. - for (i, (name, index)) in [(fwdname, 1u16), (fwdord, 2), (local, 0)] - .into_iter() - .enumerate() - { - put32(d, at(names) + i * 4, name); - put16(d, at(ordinals) + i * 2, index); - } - put_bytes(d, dll, b"t.dll\0"); - put_bytes(d, local, b"local\0"); - put_bytes(d, fwdname, b"fwdname\0"); - put_bytes(d, fwdord, b"fwdord\0"); - put_bytes(d, to_name, b"NTDLL.RtlFoo\0"); - put_bytes(d, to_ordinal, b"NTDLL.#7\0"); -} - -#[test] -fn reads_delay_imports_with_their_iat_slots() { - let mut d = image(); - add_delay_import(&mut d); - let info = ImageInfo::parse(&d).unwrap(); - assert_eq!(info.delay_imports.len(), 1); - let user32 = &info.delay_imports[0]; - assert_eq!(user32.dll, "USER32.dll"); - assert_eq!(user32.entries.len(), 1); - assert_eq!( - user32.entries[0].symbol, - ImportSymbol::Name { - hint: 7, - name: "MessageBoxW".into() - } - ); - assert_eq!(user32.entries[0].iat_slot_rva, DELAY_IAT); - // Delay imports are kept apart from the ordinary imports. - assert_eq!(info.import_count(), 2); -} - -#[test] -fn rejects_delay_iat_outside_image() { - for iat in [SIZE_OF_IMAGE - 4, 0xFFFF_FFFC] { - let mut d = image(); - add_delay_import(&mut d); - put32(&mut d, at(DELAY_DESCRIPTORS) + 12, iat); - assert!( - matches!(ImageInfo::parse(&d), Err(PeError::Malformed(_))), - "delay IAT at {iat:#x}" - ); - } -} - -#[test] -fn reads_exports_and_forwarders() { - let mut d = image(); - add_exports(&mut d); - let info = ImageInfo::parse(&d).unwrap(); - let mut exports: Vec<_> = info - .exports - .iter() - .map(|e| (e.ordinal, e.name.as_deref(), e.rva, e.forward.as_deref())) - .collect(); - exports.sort(); - assert_eq!( - exports, - [ - (1, Some("local"), Some(ENTRY), None), - (2, Some("fwdname"), None, Some("NTDLL.RtlFoo")), - (3, Some("fwdord"), None, Some("NTDLL.#7")), - ] - ); -} - -#[test] -fn reads_codeview_record_and_symbol_key() { - let mut d = image(); - add_codeview(&mut d, b"RSDS"); - let cv = ImageInfo::parse(&d).unwrap().codeview.unwrap(); - assert_eq!(cv.pdb_path, "t.pdb"); - assert_eq!(cv.age, 0x2A); - let guid: Vec<u8> = (0..16).collect(); - assert_eq!(cv.guid[..], guid[..]); - // The first three GUID fields are little endian; the age is hex, unpadded. - assert_eq!(cv.symbol_key(), "030201000504070608090A0B0C0D0E0F2A"); -} - -#[test] -fn ignores_codeview_records_that_are_not_rsds() { - let mut d = image(); - add_codeview(&mut d, b"NB10"); - assert!(ImageInfo::parse(&d).unwrap().codeview.is_none()); -} - -#[test] -fn reports_relocation_exception_and_load_config_directories() { - let mut d = image(); - // Only the directory entries matter; their contents are not parsed. - set_directory(&mut d, dir::BASERELOC, 0x1380, 12); - set_directory(&mut d, dir::EXCEPTION, 0x1390, 12); - set_directory(&mut d, dir::LOAD_CONFIG, 0x13A0, 0x40); - let info = ImageInfo::parse(&d).unwrap(); - assert!(info.has_relocations); - assert!(info.has_exception_table); - assert!(info.has_load_config); - - // Stripped relocations win over a leftover directory entry. - let fh = layout::file_header_offset(&d).unwrap(); - let at_flags = fh + layout::FILE_HEADER_CHARACTERISTICS; - let flags = u16::from_le_bytes([d[at_flags], d[at_flags + 1]]); - put16( - &mut d, - at_flags, - flags | layout::file_flags::RELOCS_STRIPPED, - ); - assert!(!ImageInfo::parse(&d).unwrap().has_relocations); - - // An entry with an RVA but no size is absent. - set_directory(&mut d, dir::EXCEPTION, 0x1390, 0); - assert!(!ImageInfo::parse(&d).unwrap().has_exception_table); -} - -#[test] -fn names_subsystems_and_dll_flag() { - use layout::subsystem::*; - for (value, name) in [ - (WINDOWS_GUI, "windows-gui"), - (WINDOWS_CUI, "windows-cui"), - (XBOX, "xbox"), - (XBOX_CODE_CATALOG, "xbox-code-catalog"), - (1, "other"), - ] { - let mut d = image(); - put16(&mut d, OPT + 68, value); - let info = ImageInfo::parse(&d).unwrap(); - assert_eq!((info.subsystem, info.subsystem_name()), (value, name)); - } - let mut d = image(); - put16(&mut d, 0x56, 0x0022 | layout::file_flags::DLL); - assert!(ImageInfo::parse(&d).unwrap().is_dll()); -} - -#[test] -fn layout_offsets_match_the_image() { - let mut d = image(); - assert_eq!(layout::file_header_offset(&d), Some(0x44)); - assert_eq!(layout::optional_header_offset(&d), Some(OPT)); - assert_eq!( - layout::data_directory_offset(&d, DIR_TLS), - Some(OPT + layout::OPT_DATA_DIRECTORY + DIR_TLS * layout::DATA_DIRECTORY_SIZE) - ); - assert_eq!(layout::data_directory_offset(&d, 16), None); - let tls = layout::data_directory_offset(&d, DIR_TLS).unwrap(); - assert_eq!(layout::read_u32(&d, tls), Some(TLS_DIRECTORY)); - - // Fewer directories than the index: none. - put32(&mut d, OPT + layout::OPT_NUMBER_OF_RVA_AND_SIZES, 2); - assert!(layout::data_directory_offset(&d, dir::IMPORT).is_some()); - assert_eq!(layout::data_directory_offset(&d, DIR_TLS), None); - - // Headers that point past the data, or nowhere at all, give None. - assert_eq!(layout::file_header_offset(&d[..0x3C]), None); - put32(&mut d, layout::DOS_E_LFANEW, u32::MAX); - assert_eq!(layout::data_directory_offset(&d, dir::IMPORT), None); -} - -#[test] -fn reads_names_from_the_iat_when_the_name_table_is_absent() { - // Old linkers leave OriginalFirstThunk at 0; the IAT holds the names. - let mut d = image(); - put32(&mut d, at(IMPORT_DESCRIPTORS), 0); - d[at(NAME_TABLE)..at(NAME_TABLE) + 16].fill(0); - let info = ImageInfo::parse(&d).unwrap(); - let entries: Vec<_> = info.imports[0] - .entries - .iter() - .map(|e| (e.symbol.clone(), e.iat_slot_rva)) - .collect(); - assert_eq!( - entries, - [ - ( - ImportSymbol::Name { - hint: 0x123, - name: "ExitProcess".into() - }, - IAT - ), - (ImportSymbol::Ordinal(5), IAT + 8), - ] - ); -} - -#[test] -fn tls_directory_without_callbacks_or_without_an_rva() { - // A TLS directory with no callback array is still TLS (static data). - let mut d = image(); - put64( - &mut d, - at(TLS_DIRECTORY) + layout::TLS64_ADDRESS_OF_CALLBACKS, - 0, - ); - let tls = ImageInfo::parse(&d).unwrap().tls.unwrap(); - assert_eq!((tls.callbacks_va, tls.callback_rvas.len()), (0, 0)); - - // A directory entry with RVA 0 means no TLS at all. - let mut d = image(); - set_directory(&mut d, DIR_TLS, 0, 40); - assert!(ImageInfo::parse(&d).unwrap().tls.is_none()); - - // So does an image whose header lists no TLS directory slot. - let mut d = image(); - put32( - &mut d, - OPT + layout::OPT_NUMBER_OF_RVA_AND_SIZES, - DIR_TLS as u32, - ); - assert!(ImageInfo::parse(&d).unwrap().tls.is_none()); -} - -#[test] -fn tls_callback_array_running_off_the_section_is_refused() { - // The last slot of the section, with no null terminator after it: the - // list is incomplete, so the image is refused rather than half-run. - let last = SECTION_RVA + SECTION_SIZE - 8; - let mut d = image(); - put64( - &mut d, - at(TLS_DIRECTORY) + layout::TLS64_ADDRESS_OF_CALLBACKS, - IMAGE_BASE + u64::from(last), - ); - put64(&mut d, at(last), IMAGE_BASE + 0x1030); - assert!(matches!(ImageInfo::parse(&d), Err(PeError::Malformed(_)))); -} - -#[test] -fn rejects_tls_outside_the_sections() { - let malformed = |d: &[u8], what: &str| { - assert!( - matches!(ImageInfo::parse(d), Err(PeError::Malformed(_))), - "{what}" - ); - }; - let callbacks = at(TLS_DIRECTORY) + layout::TLS64_ADDRESS_OF_CALLBACKS; - - // Inside the image but past the only section. - let mut d = image(); - set_directory(&mut d, DIR_TLS, SECTION_RVA + SECTION_SIZE + 0x100, 40); - malformed(&d, "directory past the section"); - - // Too close to the end of the section to hold AddressOfCallBacks. - let mut d = image(); - set_directory(&mut d, DIR_TLS, SECTION_RVA + SECTION_SIZE - 0x10, 40); - malformed(&d, "truncated directory"); - - let mut d = image(); - put64( - &mut d, - callbacks, - IMAGE_BASE + u64::from(SECTION_RVA + SECTION_SIZE + 0x100), - ); - malformed(&d, "callback array past the section"); - - let mut d = image(); - put64(&mut d, callbacks, IMAGE_BASE - 8); - malformed(&d, "callback array below the image base"); - - // A callback 4 GiB or more above the base has no RVA. - let mut d = image(); - put64(&mut d, at(TLS_CALLBACKS) + 8, IMAGE_BASE + (1 << 32)); - malformed(&d, "callback past 4 GiB"); -} - -#[test] -fn rejects_pe32_images() { - // Same image, 32-bit optional header magic: PE32 is not supported. - let mut d = image(); - put16(&mut d, OPT, 0x10B); - assert!(matches!(ImageInfo::parse(&d), Err(PeError::Unsupported(_)))); -} - -#[test] -fn import_symbols_display_as_their_name_or_ordinal() { - let info = ImageInfo::parse(&image()).unwrap(); - let shown: Vec<_> = info.imports[0] - .entries - .iter() - .map(|e| e.symbol.to_string()) - .collect(); - assert_eq!(shown, ["ExitProcess", "#5"]); -} - -#[test] -fn tls_callbacks_over_the_limit_are_refused() { - // Grow the section so a 1100-entry callback array, with no terminator, - // fits after the existing contents. More than 1024 callbacks is garbage. - const SIZE: u32 = 0x3000; - const ARRAY: u32 = 0x1400; - const COUNT: usize = 1100; - let mut d = image(); - d.resize((SECTION_FILE_OFFSET + SIZE) as usize, 0); - let sec = OPT + 240; - put32(&mut d, sec + 8, SIZE); - put32(&mut d, sec + 16, SIZE); - put32(&mut d, OPT + 56, SECTION_RVA + SIZE); - put64( - &mut d, - at(TLS_DIRECTORY) + layout::TLS64_ADDRESS_OF_CALLBACKS, - IMAGE_BASE + u64::from(ARRAY), - ); - for i in 0..COUNT { - put64(&mut d, at(ARRAY) + i * 8, IMAGE_BASE + 0x1000 + i as u64); - } - assert!(matches!(ImageInfo::parse(&d), Err(PeError::Malformed(_)))); -} - -#[test] -fn reads_exports_without_a_name() { - // Only two names: the export at ordinal 1 (`local`) is by ordinal only. - let mut d = image(); - add_exports(&mut d); - put32(&mut d, at(EXPORT_DIRECTORY) + 24, 2); - let info = ImageInfo::parse(&d).unwrap(); - let mut exports: Vec<_> = info - .exports - .iter() - .map(|e| (e.ordinal, e.name.as_deref(), e.rva, e.forward.as_deref())) - .collect(); - exports.sort(); - assert_eq!( - exports, - [ - (1, None, Some(ENTRY), None), - (2, Some("fwdname"), None, Some("NTDLL.RtlFoo")), - (3, Some("fwdord"), None, Some("NTDLL.#7")), - ] - ); -} - -#[test] -fn reads_delay_imports_by_ordinal() { - let mut d = image(); - add_delay_import(&mut d); - put64(&mut d, at(DELAY_NAME_TABLE), (1 << 63) | 9); - let info = ImageInfo::parse(&d).unwrap(); - let user32 = &info.delay_imports[0]; - assert_eq!(user32.entries.len(), 1); - assert_eq!(user32.entries[0].symbol, ImportSymbol::Ordinal(9)); - assert_eq!(user32.entries[0].symbol.to_string(), "#9"); - assert_eq!(user32.entries[0].iat_slot_rva, DELAY_IAT); -} - -#[test] -fn rva_to_file_offset_picks_the_section_that_holds_the_rva() { - // A second section, `.data` at RVA 0x2000 and file offset 0x600, with a - // virtual size of 0: its raw size is then its size in memory. - const DATA_RVA: u32 = 0x2000; - const DATA_FILE_OFFSET: u32 = SECTION_FILE_OFFSET + SECTION_SIZE; - const DATA_SIZE: u32 = 0x200; - let mut d = image(); - d.resize((DATA_FILE_OFFSET + DATA_SIZE) as usize, 0); - put16(&mut d, 0x46, 2); - put32(&mut d, OPT + 56, DATA_RVA + 0x1000); - let sec = OPT + 240 + 40; - d[sec..sec + 5].copy_from_slice(b".data"); - put32(&mut d, sec + 12, DATA_RVA); - put32(&mut d, sec + 16, DATA_SIZE); - put32(&mut d, sec + 20, DATA_FILE_OFFSET); - put32(&mut d, sec + 36, 0xC000_0040); // initialised data, read, write - - let info = ImageInfo::parse(&d).unwrap(); - let sections: Vec<_> = info - .sections - .iter() - .map(|s| (s.name.trim_end_matches('\0'), s.rva, s.virtual_size)) - .collect(); - assert_eq!( - sections, - [(".text", SECTION_RVA, SECTION_SIZE), (".data", DATA_RVA, 0)] - ); - assert_eq!( - info.rva_to_file_offset(HINT_NAME), - Some(at(HINT_NAME) as u32) - ); - assert_eq!(info.rva_to_file_offset(DATA_RVA), Some(DATA_FILE_OFFSET)); - assert_eq!( - info.rva_to_file_offset(DATA_RVA + DATA_SIZE - 1), - Some(DATA_FILE_OFFSET + DATA_SIZE - 1) - ); - // The gap between the sections and the end of `.data` map nowhere. - assert_eq!( - info.rva_to_file_offset(SECTION_RVA + SECTION_SIZE + 0x10), - None - ); - assert_eq!(info.rva_to_file_offset(DATA_RVA + DATA_SIZE), None); -} - -#[test] -fn rejects_damaged_dos_and_nt_signatures() { - // No `MZ`: not a PE file at all. - let mut d = image(); - d[0..2].copy_from_slice(b"ZM"); - assert!(ImageInfo::parse(&d).is_err()); - - // `MZ`, but the NT signature is wrong. - let mut d = image(); - d[0x40..0x44].copy_from_slice(b"NE\0\0"); - assert!(ImageInfo::parse(&d).is_err()); - - // `e_lfanew` points past the end of the file, or right at its last bytes. - for lfanew in [u32::MAX, d.len() as u32, d.len() as u32 - 2] { - let mut d = image(); - put32(&mut d, layout::DOS_E_LFANEW, lfanew); - assert!(ImageInfo::parse(&d).is_err(), "e_lfanew {lfanew:#x}"); - } -} - -#[test] -fn rejects_an_import_name_outside_the_sections() { - for name in [SIZE_OF_IMAGE + 0x100, 0xFFFF_FFF0] { - let mut d = image(); - put32(&mut d, at(IMPORT_DESCRIPTORS) + 12, name); - assert!(ImageInfo::parse(&d).is_err(), "DLL name at {name:#x}"); - } - for hint_name in [SIZE_OF_IMAGE + 0x100, 0x7FFF_FFF0] { - let mut d = image(); - put64(&mut d, at(NAME_TABLE), u64::from(hint_name)); - assert!(ImageInfo::parse(&d).is_err(), "hint/name at {hint_name:#x}"); - } -} - -#[test] -fn import_and_tls_directories_pointing_outside_the_image_do_not_panic() { - for rva in [SIZE_OF_IMAGE, SIZE_OF_IMAGE + 0x1000, 0xFFFF_FFF0] { - for index in [ - dir::IMPORT, - DIR_TLS, - DIR_EXPORT, - DIR_DEBUG, - DIR_DELAY_IMPORT, - ] { - let mut d = image(); - set_directory(&mut d, index, rva, 0x40); - // Either outcome is acceptable; the parse must simply return. - let _ = ImageInfo::parse(&d); - } - } -} - -#[test] -fn corrupting_any_header_byte_does_not_panic() { - // Every byte of the headers, the section table and the directories in - // the section, set to each of a few hostile values. - let clean = image(); - let ranges = [ - 0..OPT + 240 + 40, - at(IMPORT_DESCRIPTORS)..at(HINT_NAME) + 16, - at(TLS_DIRECTORY)..at(TLS_CALLBACKS) + 16, - ]; - for range in ranges { - for i in range { - for v in [0x00, 0x7F, 0x80, 0xFF] { - if clean[i] == v { - continue; - } - let mut d = clean.clone(); - d[i] = v; - let _ = ImageInfo::parse(&d); - } - } - } -} - -#[test] -fn every_truncation_of_the_image_returns() { - let d = image(); - for len in 0..d.len() { - let _ = ImageInfo::parse(&d[..len]); - } -} - -/// A second import descriptor, `XAPI.dll!Sleep` (hint 9), in the free gap -/// between the first descriptor's terminator and the first name table. -#[test] -fn reads_every_import_module_in_descriptor_order() { - const SECOND_DESCRIPTOR: u32 = IMPORT_DESCRIPTORS + 20; - // Past the new terminator, which ends at 0x113C. - const NAMES: u32 = 0x1140; - const SLOTS: u32 = 0x1150; - const DLL: u32 = 0x1160; - const HINT: u32 = 0x1170; - let mut d = image(); - set_directory(&mut d, dir::IMPORT, IMPORT_DESCRIPTORS, 60); - let desc = at(SECOND_DESCRIPTOR); - put32(&mut d, desc, NAMES); - put32(&mut d, desc + 12, DLL); - put32(&mut d, desc + 16, SLOTS); - for table in [NAMES, SLOTS] { - put64(&mut d, at(table), u64::from(HINT)); - } - put_bytes(&mut d, DLL, b"XAPI.dll\0"); - put16(&mut d, at(HINT), 9); - put_bytes(&mut d, HINT + 2, b"Sleep\0"); - - let info = ImageInfo::parse(&d).unwrap(); - let modules: Vec<_> = info - .imports - .iter() - .map(|m| (m.dll.as_str(), m.entries.len())) - .collect(); - assert_eq!(modules, [("KERNEL32.dll", 2), ("XAPI.dll", 1)]); - let sleep = &info.imports[1].entries[0]; - assert_eq!( - sleep.symbol, - ImportSymbol::Name { - hint: 9, - name: "Sleep".into() - } - ); - assert_eq!(sleep.iat_slot_rva, SLOTS); - assert_eq!(info.import_count(), 3); -} - -#[test] -fn section_names_fill_all_eight_bytes_and_keep_their_flags() { - let mut d = image(); - let sec = OPT + 240; - d[sec..sec + 8].copy_from_slice(b".textbss"); - let info = ImageInfo::parse(&d).unwrap(); - assert_eq!(info.sections[0].name, ".textbss"); - assert_eq!(info.sections[0].characteristics, 0xE000_0020); - // A shorter name loses its NUL padding. - let info = ImageInfo::parse(&image()).unwrap(); - assert_eq!(info.sections[0].name, ".text"); -} - -#[test] -fn rva_to_file_offset_stops_at_the_virtual_size_and_never_overflows() { - // Raw data padded past a smaller virtual size: the padding is not mapped. - let mut d = image(); - put32(&mut d, OPT + 240 + 8, 0x300); - let info = ImageInfo::parse(&d).unwrap(); - assert_eq!( - info.rva_to_file_offset(SECTION_RVA + 0x2FF), - Some(at(SECTION_RVA + 0x2FF) as u32) - ); - assert_eq!(info.rva_to_file_offset(SECTION_RVA + 0x300), None); - // Below every section, and far past it. - assert_eq!(info.rva_to_file_offset(0), None); - assert_eq!(info.rva_to_file_offset(u32::MAX), None); - - // A section claiming a file offset near 4 GiB maps nothing instead of - // wrapping around. Built by hand: such an image does not parse. - let mut info = ImageInfo::parse(&image()).unwrap(); - info.sections[0].file_offset = u32::MAX - 0x10; - assert_eq!(info.rva_to_file_offset(SECTION_RVA), Some(u32::MAX - 0x10)); - assert_eq!(info.rva_to_file_offset(SECTION_RVA + 0x10), Some(u32::MAX)); - assert_eq!(info.rva_to_file_offset(SECTION_RVA + 0x11), None); -} - -#[test] -fn delay_import_slots_follow_the_name_table_eight_bytes_apart() { - // Move the delay name table and IAT to the free tail so each holds two - // entries: a name, then an ordinal, then the terminator. - const NAMES: u32 = 0x1350; - const SLOTS: u32 = 0x1370; - let mut d = image(); - add_delay_import(&mut d); - put32(&mut d, at(DELAY_DESCRIPTORS) + 12, SLOTS); - put32(&mut d, at(DELAY_DESCRIPTORS) + 16, NAMES); - put64(&mut d, at(NAMES), u64::from(DELAY_HINT_NAME)); - put64(&mut d, at(NAMES) + 8, (1 << 63) | 4); - let info = ImageInfo::parse(&d).unwrap(); - let entries: Vec<_> = info.delay_imports[0] - .entries - .iter() - .map(|e| (e.symbol.clone(), e.iat_slot_rva)) - .collect(); - assert_eq!( - entries, - [ - ( - ImportSymbol::Name { - hint: 7, - name: "MessageBoxW".into() - }, - SLOTS - ), - (ImportSymbol::Ordinal(4), SLOTS + 8), - ] - ); - // Ordinary imports are reported apart from delay imports. - assert_eq!(info.import_count(), 2); -} - -#[test] -fn an_iat_that_ends_exactly_at_the_size_of_image_is_inside_it() { - // Two slots, the second's last byte the image's last byte: accepted. - // One slot further is the case `rejects_iat_outside_image` covers. - let mut d = image(); - let iat = SIZE_OF_IMAGE - 16; - put32(&mut d, at(IMPORT_DESCRIPTORS) + 16, iat); - let info = ImageInfo::parse(&d).unwrap(); - let slots: Vec<_> = info.imports[0] - .entries - .iter() - .map(|e| e.iat_slot_rva) - .collect(); - assert_eq!(slots, [iat, iat + 8]); -} - -#[test] -fn section_names_that_are_not_utf8_are_read_lossily() { - let mut d = image(); - let name = OPT + 240; - d[name..name + 8].copy_from_slice(b".t\xFFxt\0\0\0"); - let info = ImageInfo::parse(&d).unwrap(); - assert_eq!(info.sections[0].name, ".t\u{FFFD}xt"); - // The rest of the image is unaffected by the name. - assert_eq!(info.rva_to_file_offset(ENTRY), Some(SECTION_FILE_OFFSET)); -} - -#[test] -fn tls_vas_more_than_4_gib_above_the_image_base_are_malformed() { - // An RVA is 32 bits: a VA that far above the base names nothing in the - // image and must not be truncated to some low RVA inside it. - let far = IMAGE_BASE + (1 << 32); - for callback in [far + 0x1010, u64::MAX] { - let mut d = image(); - put64(&mut d, at(TLS_CALLBACKS), callback); - assert!( - matches!(ImageInfo::parse(&d), Err(PeError::Malformed(_))), - "callback at {callback:#x}" - ); - } - let mut d = image(); - put64( - &mut d, - at(TLS_DIRECTORY) + layout::TLS64_ADDRESS_OF_CALLBACKS, - far + u64::from(TLS_CALLBACKS), - ); - assert!(matches!(ImageInfo::parse(&d), Err(PeError::Malformed(_)))); - // The last RVA that fits is still read as an RVA (and then found to be - // outside the sections), not rejected as a VA. - let mut d = image(); - put64( - &mut d, - at(TLS_DIRECTORY) + layout::TLS64_ADDRESS_OF_CALLBACKS, - IMAGE_BASE + u64::from(u32::MAX), - ); - match ImageInfo::parse(&d) { - Err(PeError::Malformed(message)) => assert!( - message.contains("outside of sections"), - "unexpected message: {message}" - ), - other => panic!("expected a malformed image, got {other:?}"), - } -} - -#[test] -fn export_ordinals_start_at_the_ordinal_base() { - let mut d = image(); - add_exports(&mut d); - put32(&mut d, at(EXPORT_DIRECTORY) + 16, 10); - let info = ImageInfo::parse(&d).unwrap(); - let mut exports: Vec<_> = info - .exports - .iter() - .map(|e| (e.ordinal, e.name.as_deref())) - .collect(); - exports.sort(); - assert_eq!( - exports, - [ - (10, Some("local")), - (11, Some("fwdname")), - (12, Some("fwdord")) - ] - ); -} - -#[test] -fn unused_export_slots_are_left_out() { - // A zero address marks an ordinal the DLL does not export; it is gone - // even though the name table still points at it. - let mut d = image(); - add_exports(&mut d); - put32(&mut d, at(0x1378), 0); - let info = ImageInfo::parse(&d).unwrap(); - let mut exports: Vec<_> = info - .exports - .iter() - .map(|e| (e.ordinal, e.name.as_deref(), e.rva)) - .collect(); - exports.sort(); - assert_eq!( - exports, - [(2, Some("fwdname"), None), (3, Some("fwdord"), None)] - ); - assert!(info.exports.iter().all(|e| e.forward.is_some())); -} - -#[test] -fn a_directory_with_a_size_but_no_rva_is_absent() { - let mut d = image(); - set_directory(&mut d, dir::BASERELOC, 0, 12); - set_directory(&mut d, dir::EXCEPTION, 0, 12); - set_directory(&mut d, dir::LOAD_CONFIG, 0, 0x40); - let info = ImageInfo::parse(&d).unwrap(); - assert!(!info.has_relocations); - assert!(!info.has_exception_table); - assert!(!info.has_load_config); -} - -#[test] -fn header_flag_words_are_passed_through_unchanged() { - let mut d = image(); - // High entropy VA, dynamic base, NX compatible, terminal server aware. - put16(&mut d, OPT + 70, 0x8160); - let info = ImageInfo::parse(&d).unwrap(); - assert_eq!(info.characteristics, 0x0022); - assert_eq!(info.dll_characteristics, 0x8160); - assert!(!info.is_dll()); -} - -#[test] -fn names_come_from_the_name_table_when_the_iat_is_bound() { - // A bound image has absolute addresses already written into its IAT; - // the unbound name table still says what each slot imports. - let mut d = image(); - put64(&mut d, at(IAT), 0x7FF8_0000_1000); - put64(&mut d, at(IAT) + 8, 0x7FF8_0000_2000); - let info = ImageInfo::parse(&d).unwrap(); - let entries: Vec<_> = info.imports[0] - .entries - .iter() - .map(|e| (e.symbol.clone(), e.iat_slot_rva)) - .collect(); - assert_eq!( - entries, - [ - ( - ImportSymbol::Name { - hint: 0x123, - name: "ExitProcess".into() - }, - IAT - ), - (ImportSymbol::Ordinal(5), IAT + 8), - ] - ); -} - -#[test] -fn an_import_module_with_an_empty_name_table_has_no_entries() { - let mut d = image(); - d[at(NAME_TABLE)..at(NAME_TABLE) + 16].fill(0); - let info = ImageInfo::parse(&d).unwrap(); - assert_eq!(info.imports.len(), 1); - assert_eq!(info.imports[0].dll, "KERNEL32.dll"); - assert!(info.imports[0].entries.is_empty()); - assert_eq!(info.import_count(), 0); -} - -#[test] -fn an_import_directory_holding_only_the_terminator_has_no_modules() { - let mut d = image(); - d[at(IMPORT_DESCRIPTORS)..at(IMPORT_DESCRIPTORS) + 20].fill(0); - let info = ImageInfo::parse(&d).unwrap(); - assert!(info.imports.is_empty()); - assert_eq!(info.import_count(), 0); -} diff --git a/crates/victory-pipeline/Cargo.toml b/crates/victory-pipeline/Cargo.toml index f5d5ccb338..21b0a3e31e 100644 --- a/crates/victory-pipeline/Cargo.toml +++ b/crates/victory-pipeline/Cargo.toml @@ -12,8 +12,6 @@ victory-core.workspace = true anyhow.workspace = true blake3.workspace = true tracing.workspace = true - -[dev-dependencies] tempfile.workspace = true [lints] diff --git a/crates/victory-pipeline/src/cache.rs b/crates/victory-pipeline/src/cache.rs index ea88f7cc09..48ed2223f6 100644 --- a/crates/victory-pipeline/src/cache.rs +++ b/crates/victory-pipeline/src/cache.rs @@ -1,5 +1,5 @@ use std::io::Write; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use anyhow::{Context, Result}; @@ -37,6 +37,9 @@ impl Cache { /// Opens (creating) a cache at `root`. Refuses locations inside the repo. pub fn open(root: impl Into<PathBuf>) -> Result<Self> { let root = root.into(); + // The title can change the process's working directory after startup. + let root = + std::path::absolute(&root).with_context(|| format!("resolving {}", root.display()))?; victory_core::ensure_outside_repo(&root)?; std::fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?; Ok(Cache { root }) @@ -60,33 +63,20 @@ impl Cache { .with_context(|| format!("converter {} v{}", converter.id(), converter.version()))?; let dir = path.parent().expect("hashed path has a parent"); std::fs::create_dir_all(dir)?; - // Write-then-rename so readers never see partial output. - let tmp = tempfile_in(dir); - let mut file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&tmp)?; - let written = file.write_all(&output); - drop(file); - let published = written.and_then(|()| std::fs::rename(&tmp, &path)); - if published.is_err() { - let _ = std::fs::remove_file(&tmp); - } - published?; + // Write to a temporary file on the same filesystem and then publish. + let mut file = tempfile::NamedTempFile::new_in(dir)?; + file.write_all(&output)?; + file.persist(&path) + .map_err(|err| err.error) + .with_context(|| format!("publishing {}", path.display()))?; Ok(path) } } -fn tempfile_in(dir: &Path) -> PathBuf { - use std::sync::atomic::{AtomicU64, Ordering}; - static COUNTER: AtomicU64 = AtomicU64::new(0); - let n = COUNTER.fetch_add(1, Ordering::Relaxed); - dir.join(format!(".tmp-{}-{n}", std::process::id())) -} - #[cfg(test)] mod tests { use super::*; + use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; struct Upper { @@ -107,6 +97,72 @@ mod tests { } } + fn in_child(test: &str) -> bool { + const CHILD: &str = "VICTORY_TEST_CACHE_CHILD"; + if std::env::var(CHILD).as_deref() == Ok(test) { + return true; + } + let tmp = tempfile::tempdir().unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &format!("cache::tests::{test}")]) + .env(CHILD, test) + .current_dir(tmp.path()) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("1 passed"), + "{stdout}{}", + String::from_utf8_lossy(&output.stderr) + ); + false + } + + #[test] + fn relative_cache_survives_a_working_directory_change() { + // Changing the working directory must not affect other tests. + if !in_child("relative_cache_survives_a_working_directory_change") { + return; + } + + let startup_dir = std::env::current_dir().unwrap(); + let cache = Cache::open("cache").unwrap(); + let title_dir = startup_dir.join("title"); + std::fs::create_dir(&title_dir).unwrap(); + std::env::set_current_dir(&title_dir).unwrap(); + let converter = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let path = cache.get_or_convert(&converter, b"abc").unwrap(); + assert!(path.starts_with(startup_dir.join("cache"))); + assert_eq!(std::fs::read(path).unwrap(), b"ABC"); + assert!(!title_dir.join("cache").exists()); + } + + #[test] + fn recycled_process_id_can_stage_a_new_entry() { + // A fresh process starts with the old staging counter at zero. + if !in_child("recycled_process_id_can_stage_a_new_entry") { + return; + } + + let cache = Cache::open("cache").unwrap(); + let converter = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let path = cache.path_for(&CacheKey::new(&converter, b"abc")); + let dir = path.parent().unwrap(); + std::fs::create_dir_all(dir).unwrap(); + let stale = dir.join(format!(".tmp-{}-0", std::process::id())); + std::fs::write(&stale, b"abandoned").unwrap(); + + assert_eq!(cache.get_or_convert(&converter, b"abc").unwrap(), path); + assert_eq!(std::fs::read(path).unwrap(), b"ABC"); + assert_eq!(std::fs::read(stale).unwrap(), b"abandoned"); + } + #[test] fn converts_once_then_hits() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/victory-shader/Cargo.toml b/crates/victory-shader/Cargo.toml index 80a9b0c5af..280bd44720 100644 --- a/crates/victory-shader/Cargo.toml +++ b/crates/victory-shader/Cargo.toml @@ -9,8 +9,7 @@ publish.workspace = true [dependencies] thiserror.workspace = true -miniz_oxide.workspace = true -memchr.workspace = true +zlib-rs.workspace = true [features] # Host D3D12 pipeline checks (`emit::host`). diff --git a/crates/victory-shader/build.rs b/crates/victory-shader/build.rs index f85fb2091c..b102125075 100644 --- a/crates/victory-shader/build.rs +++ b/crates/victory-shader/build.rs @@ -1,36 +1,65 @@ -use std::path::PathBuf; +//! Fingerprint of the translator's own source, for the shader cache key +//! (`victory-gpu`'s `shader_cache`): a rebuilt executable whose translator did +//! not change keeps its cached translations. Also lists every `VICTORY_*` +//! switch the translator reads, whose values join the key at run time. +//! Reads only this crate's `src` folder; writes nothing but cargo directives. -fn main() { - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { - return; - } +use std::path::{Path, PathBuf}; - // `OUT_DIR` is `target/<profile>/build/<pkg>-<hash>/out`; the profile directory is three - // levels up. The application looks for the runtime in `target/<profile>/D3D12/`, so this - // crate reads it from the same place instead of inventing a second convention. - let out = PathBuf::from(std::env::var("OUT_DIR").unwrap()); - let profile = out - .ancestors() - .nth(3) - .expect("a profile directory above OUT_DIR") - .to_path_buf(); - let runtime = profile.join("D3D12").join("D3D12Core.dll"); - println!("cargo:rerun-if-changed={}", runtime.display()); - if !runtime.is_file() { - // No app-local runtime: leave the in-box one alone, exactly as a build without - // the opt-in would. +fn files(dir: &Path, out: &mut Vec<PathBuf>) { + let Ok(entries) = std::fs::read_dir(dir) else { return; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + files(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } } +} - // The loader resolves `D3D12SDKPath` next to the running module, and test binaries run - // from `deps`, so mirror the runtime there before the tests need it. - let deps = profile.join("deps").join("D3D12"); - let _ = std::fs::create_dir_all(&deps); - let _ = std::fs::copy(&runtime, deps.join("D3D12Core.dll")); +/// FNV-1a, 64 bits, two lanes with different offsets: a mismatch only costs +/// a cache miss, so this need not be cryptographic. +fn fnv(state: &mut [u64; 2], bytes: &[u8]) { + for &b in bytes { + for (i, s) in state.iter_mut().enumerate() { + *s ^= u64::from(b) ^ (i as u64 * 0x9e); + *s = s.wrapping_mul(0x0000_0100_0000_01b3); + } + } +} - // Export the two symbols the Agility SDK loader looks for in the host module, so - // d3d12.dll loads that runtime instead of the in-box copy. Without them Windows 10 - // reports shader model 6.5 and every SM 6.6 test is skipped. - println!("cargo:rustc-link-arg=/EXPORT:D3D12SDKVersion,DATA"); - println!("cargo:rustc-link-arg=/EXPORT:D3D12SDKPath,DATA"); +fn main() { + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + println!("cargo:rerun-if-changed=src"); + println!("cargo:rerun-if-changed=Cargo.toml"); + let mut list = Vec::new(); + files(&src, &mut list); + list.sort(); + let mut state = [0xcbf2_9ce4_8422_2325u64, 0x8422_2325_cbf2_9ce4u64]; + let mut switches = std::collections::BTreeSet::new(); + for p in &list { + let rel = p.strip_prefix(&src).unwrap_or(p).to_string_lossy().replace('\\', "/"); + let text = std::fs::read(p).unwrap_or_default(); + fnv(&mut state, rel.as_bytes()); + fnv(&mut state, &(text.len() as u64).to_le_bytes()); + fnv(&mut state, &text); + let s = String::from_utf8_lossy(&text); + let mut rest = &s[..]; + while let Some(at) = rest.find("\"VICTORY_") { + let tail = &rest[at + 1..]; + let end = tail + .find(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')) + .unwrap_or(tail.len()); + if tail[end..].starts_with('"') { + switches.insert(tail[..end].to_string()); + } + rest = &tail[end..]; + } + } + println!("cargo:rustc-env=VICTORY_SHADER_SOURCE_HASH={:016x}{:016x}", state[0], state[1]); + let joined: Vec<_> = switches.into_iter().collect(); + println!("cargo:rustc-env=VICTORY_SHADER_SWITCHES={}", joined.join(",")); } diff --git a/crates/victory-shader/src/agility.rs b/crates/victory-shader/src/agility.rs deleted file mode 100644 index d28afae7b4..0000000000 --- a/crates/victory-shader/src/agility.rs +++ /dev/null @@ -1,21 +0,0 @@ -//! Agility SDK opt-in. -//! -//! Windows 10's in-box D3D12 runtime tops out at shader model 6.5, and this crate emits -//! SM 6.6 (dynamic resources, `WaveSize`, compute derivatives). The Agility SDK loader in -//! `d3d12.dll` switches to a redistributable `D3D12Core.dll` when the host module exports -//! the two symbols below; `D3D12SDKPath` names the folder holding it, relative to the -//! executable, and `D3D12SDKVersion` must match the `D3D12_SDK_VERSION` in the SDK's -//! `d3d12.h` (620 for package 1.620.2). -//! -//! `build.rs` exports them with the linker's `/EXPORT:...,DATA` option. Once the exports are -//! present the loader refuses to create a device when the DLL is missing (`0x887e0003`), so -//! the DLL has to ship next to the executable under `D3D12\`. - -#[allow(dead_code)] -#[unsafe(no_mangle)] -pub static D3D12SDKVersion: u32 = 620; - -/// A `const char*`, not a char array: the loader dereferences this symbol. -#[allow(dead_code)] -#[unsafe(no_mangle)] -pub static D3D12SDKPath: &[u8; 9] = b".\\D3D12\\\0"; diff --git a/crates/victory-shader/src/bvh.rs b/crates/victory-shader/src/bvh.rs new file mode 100644 index 0000000000..9f5400114c --- /dev/null +++ b/crates/victory-shader/src/bvh.rs @@ -0,0 +1,696 @@ +//! The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and +//! `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the +//! instruction returns for one ray and one node. The emitter lowers the +//! instruction to the same arithmetic in the same order +//! (`emit/intersect.rs`), so its code can be compared against this dword +//! for dword. +//! +//! The instruction tests one ray against one 64-byte node of a bounding +//! volume hierarchy and returns four dwords. Traversal (the stack, instance +//! transforms, culling, the hit distance `numerator / denominator`) is the +//! program's own code. +//! +//! # Node pointers +//! +//! A node pointer's low three bits are the node's kind, the rest its byte +//! offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the +//! base address of the descriptor (40 bits in dword 0 and the low byte of +//! dword 1, in 256-byte units). The 32-bit form takes a 32-bit pointer; +//! the 64-bit form a 64-bit one, with which a program uses one descriptor +//! with base 0 for every structure and adds `address >> 3` itself. +//! +//! | kind | node | +//! |---|---| +//! | 0-3 | triangle 0-3 of a triangle node | +//! | 4 | box node, 16-bit floats (64 bytes) | +//! | 5 | box node, 32-bit floats (128 bytes) | +//! | 6 | instance: not read by the instruction | +//! | 7 | procedural primitive: not read by the instruction | +//! +//! # Box nodes +//! +//! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four +//! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16 +//! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes +//! 112-127 are not read). The result is the pointers of the children whose +//! box the ray enters before its extent, nearest entry first when the +//! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest. +//! +//! # Triangle nodes +//! +//! Five vertices of three 32-bit floats at bytes 0-59 and a dword at byte +//! 60 with one byte per triangle: bits 1:0 name the triangle's vertex that +//! barycentric I weighs, bits 3:2 the one J weighs (the builder stores an +//! input triangle's second vertex at the former, its third at the latter +//! and its first at the remaining one, so I and J are the weights of the +//! input triangle's second and third vertices). Triangle `k` of the node +//! uses the node's vertices [`TRIANGLE_VERTICES`]`[k]`. A program that +//! keeps fewer triangles in a node uses the bytes of the unused vertices +//! for its own data. +//! +//! With the descriptor's triangle return mode set (bit 120) the result is +//! the hit distance's numerator, its denominator, and the numerators of I +//! and J over the same denominator, as floats. The denominator is positive +//! for a triangle whose vertices run clockwise seen from the ray's origin +//! in a left-handed coordinate system. A miss returns +infinity, 1.0, 0, 0. +//! The ray's extent is not tested for triangles. +//! +//! # Where this comes from +//! +//! The node formats, the descriptor bits and the tests are those of the +//! public software emulation of this instruction in the open-source Vulkan +//! driver for this GPU family (box test and sorting network as there; the +//! triangle test is the watertight one it uses, Woop, Benthin and Wald, +//! JCGT 2013), and agree with what the title's own structure +//! builder writes and its trace programs read. Not known from either: how +//! the console rounds, which of two boxes entered at the same distance it +//! returns first, and what it returns for a ray exactly through an edge +//! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here: +//! a triangle miss; the title's programs do not read it). + +/// The result dword for a box the ray misses, or a child that is not there. +pub const NONE: u32 = 0xffff_ffff; + +/// The node's vertices that make triangle 0-3, by the triangle's own +/// vertex numbers 0-2. +pub const TRIANGLE_VERTICES: [[u32; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]]; + +/// Descriptor dword 1: boxes are returned nearest first. +pub const BOX_SORT: u32 = 1 << 31; +/// Descriptor dword 3: triangles return the numerators of I and J (clear: +/// a triangle id and a hit status, which nothing here produces). +pub const RETURN_BARYCENTRICS: u32 = 1 << 24; +/// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing +/// structure. +pub const DESCRIPTOR_TYPE: u32 = 8; + +/// The ray as the instruction takes it. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Ray { + pub extent: f32, + pub origin: [f32; 3], + pub direction: [f32; 3], + /// What the program computed as `1 / direction`. + pub inverse: [f32; 3], +} + +impl Ray { + /// A ray with the inverse direction a program computes by division. + pub fn new(origin: [f32; 3], direction: [f32; 3], extent: f32) -> Self { + Self { + extent, + origin, + direction, + inverse: direction.map(|d| 1.0 / d), + } + } +} + +/// The kind of the node a pointer names. +pub fn kind(pointer: u64) -> u32 { + (pointer & 7) as u32 +} + +/// The byte address of the node `pointer` names, for a descriptor whose +/// first two dwords are `word0` and `word1`. +pub fn node_address(word0: u32, word1: u32, pointer: u64) -> u64 { + let base = (u64::from(word1 & 0xff) << 32 | u64::from(word0)) << 8; + base.wrapping_add((pointer >> 3) << 6) +} + +/// What the instruction returns for the node at `words` (its first 28 +/// dwords; a 64-byte node's dwords 16-27 are not read) named by a pointer +/// of this `kind`, with box sorting as `sort` says and the triangle return +/// mode set. +pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4] { + match kind & 7 { + 4 => boxes(&children(words), &boxes16(words), ray, sort), + 5 => boxes(&children(words), &boxes32(words), ray, sort), + k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits), + _ => MISS.map(f32::to_bits), + } +} + +/// A box node's four child pointers. +pub fn children(words: &[u32; 28]) -> [u32; 4] { + [words[0], words[1], words[2], words[3]] +} + +/// The four boxes of a 16-bit box node: minimum x y z, maximum x y z. +pub fn boxes16(words: &[u32; 28]) -> [[f32; 6]; 4] { + std::array::from_fn(|b| { + std::array::from_fn(|k| { + let half = 6 * b + k; + half_to_f32((words[4 + half / 2] >> (16 * (half % 2))) as u16) + }) + }) +} + +/// The four boxes of a 32-bit box node. +pub fn boxes32(words: &[u32; 28]) -> [[f32; 6]; 4] { + std::array::from_fn(|b| std::array::from_fn(|k| f32::from_bits(words[4 + 6 * b + k]))) +} + +/// [`TRIANGLE_VERTICES`] of triangle `k` in four bits each, vertex 0 lowest +/// (as the public descriptions of the format give it: 0x210, 0x231, 0x432, +/// 0x042). +pub fn vertex_map(k: u32) -> u32 { + let v = TRIANGLE_VERTICES[(k & 3) as usize]; + v[0] | v[1] << 4 | v[2] << 8 +} + +/// The vertices of triangle `k` (0-3) of a triangle node, the first being +/// the one neither barycentric weighs, then I's, then J's. +pub fn triangle_vertices(words: &[u32; 28], k: u32) -> [[f32; 3]; 3] { + let id = words[15] >> (8 * k); + let (i, j) = (id & 3, id >> 2 & 3); + // An id naming one vertex twice, or a vertex 3, is malformed; it reads + // what this arithmetic lands on (a vertex of the node), as the emitted + // code does. + let first = 3u32.wrapping_sub(i).wrapping_sub(j) & 3; + [first, i, j].map(|n| { + let vertex = (vertex_map(k) >> (4 * n) & 0xf) as usize; + std::array::from_fn(|c| f32::from_bits(words[3 * vertex + c])) + }) +} + +/// The box test: child pointers of the boxes the ray enters, `NONE` for +/// the others; sorted by entry distance when `sort`, in child order +/// otherwise. +pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) -> [u32; 4] { + // An infinite inverse (a direction component of 0) would turn an + // origin exactly on a box's face into a NaN. (Maximum then minimum, as + // the emitted code: a NaN becomes the lower bound, where `clamp` would + // keep it.) + #[allow(clippy::manual_clamp)] + let inverse = ray.inverse.map(|x| x.max(-f32::MAX).min(f32::MAX)); + let mut ids = [NONE; 4]; + let mut distances = [f32::INFINITY; 4]; + for (n, b) in boxes.iter().enumerate() { + let (mut near, mut far) = ([0f32; 3], [0f32; 3]); + for a in 0..3 { + let low = (b[a] - ray.origin[a]) * inverse[a]; + let high = (b[3 + a] - ray.origin[a]) * inverse[a]; + near[a] = low.min(high); + far[a] = low.max(high); + } + let enter = near[0].max(near[1]).max(near[2]); + let leave = far[0].min(far[1]).min(far[2]); + // A box whose minimum x is NaN is switched off. + if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent { + ids[n] = children[n]; + distances[n] = enter; + } + } + if sort { + for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] { + if distances[b] < distances[a] { + distances.swap(a, b); + ids.swap(a, b); + } + } + } + ids +} + +/// What a triangle the ray misses returns. +pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0]; + +/// The triangle test: the hit distance's numerator, the denominator, and +/// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise. +/// Watertight: the vertices are sheared so the ray runs along its largest +/// axis, and the signs of the three edge functions decide, so a ray +/// between two triangles that share an edge cannot miss both. Any NaN +/// misses, and so does a triangle seen edge-on. +pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] { + let d = ray.direction; + let size = d.map(f32::abs); + // The largest axis, and the other two in an order that keeps the + // triangle's winding. + let kz = if size[0] >= size[1] { + if size[0] >= size[2] { 0 } else { 2 } + } else if size[1] >= size[2] { + 1 + } else { + 2 + }; + let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3); + if d[kz] < 0.0 { + std::mem::swap(&mut kx, &mut ky); + } + let sz = ray.inverse[kz]; + let (sx, sy) = (d[kx] * sz, d[ky] * sz); + let sheared = |v: &[f32; 3]| { + let r = [ + v[0] - ray.origin[0], + v[1] - ray.origin[1], + v[2] - ray.origin[2], + ]; + (r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz]) + }; + let (ax, ay, az) = sheared(&p[0]); + let (bx, by, bz) = sheared(&p[1]); + let (cx, cy, cz) = sheared(&p[2]); + let u = cx * by - cy * bx; + let v = ax * cy - ay * cx; + let w = bx * ay - by * ax; + let behind = u < 0.0 || v < 0.0 || w < 0.0; + let before = u > 0.0 || v > 0.0 || w > 0.0; + let det = u + (v + w); + let t = (u * az + v * bz) + w * cz; + let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0; + if !(behind && before) && ahead { + [t, det, v, w] + } else { + MISS + } +} + +/// A 16-bit float as a 32-bit one (exact). +pub fn half_to_f32(h: u16) -> f32 { + let sign = u32::from(h >> 15) << 31; + let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff)); + let bits = match exponent { + 0 if mantissa == 0 => sign, + 0 => { + // Subnormal: normalise. + let shift = mantissa.leading_zeros() - 21; + sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13 + } + 0x1f => sign | 0xff << 23 | mantissa << 13, + e => sign | (e + 112) << 23 | mantissa << 13, + }; + f32::from_bits(bits) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// The smallest 16-bit float not below `x` (`up`) or not above it. + pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 { + let mut best: Option<u16> = None; + for h in 0..=0xffffu16 { + let f = half_to_f32(h); + if f.is_nan() || if up { f < x } else { f > x } { + continue; + } + best = match best { + Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b), + _ => Some(h), + }; + } + best.expect("a half") + } + + /// A 32-bit box node. + pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] { + let mut w = [0u32; 28]; + w[..4].copy_from_slice(&children); + for (b, bx) in boxes.iter().enumerate() { + for (k, x) in bx.iter().enumerate() { + w[4 + 6 * b + k] = x.to_bits(); + } + } + w + } + + /// A 16-bit box node holding `boxes` rounded outward. + pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] { + let mut w = [0u32; 28]; + w[..4].copy_from_slice(&children); + for (b, bx) in boxes.iter().enumerate() { + for (k, x) in bx.iter().enumerate() { + let half = 6 * b + k; + let h = if x.is_nan() { + 0x7e00 + } else { + f32_to_half(*x, k >= 3) + }; + w[4 + half / 2] |= u32::from(h) << (16 * (half % 2)); + } + } + w + } + + /// A triangle node: up to five vertices, and the dword at byte 60. + pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] { + let mut w = [0u32; 28]; + for (n, v) in vertices.iter().enumerate() { + for (c, x) in v.iter().enumerate() { + w[3 * n + c] = x.to_bits(); + } + } + w[15] = id; + w + } + + const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0]; + + fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] { + std::array::from_fn(|k| b[k] + by[k % 3]) + } + + const OFF: [f32; 6] = [f32::NAN; 6]; + + #[test] + fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() { + // The 64-bit form as the title uses it: base 0, the structure's + // address folded into the pointer. + let structure = 0x12_3456_7800u64; + let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5); + assert_eq!(kind(pointer), 5); + assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40); + // The 32-bit form: the base in the descriptor. + let word0 = (structure >> 8) as u32; + let word1 = (structure >> 40) as u32 | BOX_SORT; + assert_eq!( + node_address(word0, word1, 0x1000 >> 3 | 4), + structure + 0x1000 + ); + // A base past 4 GiB of 256-byte units. + assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64); + } + + #[test] + fn halves_convert_exactly() { + assert_eq!(half_to_f32(0x3c00), 1.0); + assert_eq!(half_to_f32(0xc000), -2.0); + assert_eq!(half_to_f32(0x7c00), f32::INFINITY); + assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); + assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24)); + assert_eq!(half_to_f32(0x7bff), 65504.0); + assert!(half_to_f32(0x7e00).is_nan()); + assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000); + // Outward rounding of the test helper. + assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1); + assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1); + } + + #[test] + fn boxes_are_returned_nearest_first_and_misses_last() { + let children = [0x105, 0x20c, 0x304, 0x400]; + // Along +x from the origin: boxes at x = 30, 10, (off axis), 20. + let node = box32( + children, + [ + moved(UNIT, [30.0, 0.0, 0.0]), + moved(UNIT, [10.0, 0.0, 0.0]), + moved(UNIT, [10.0, 5.0, 0.0]), + moved(UNIT, [20.0, 0.0, 0.0]), + ], + ); + let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0); + assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]); + // Without sorting: child order, the miss in its place. + assert_eq!( + intersect(&node, 5, &ray, false), + [0x105, 0x20c, NONE, 0x400] + ); + // The extent cuts the far ones off (entered at 9, 19, 29). + let short = Ray { + extent: 19.5, + ..ray + }; + assert_eq!( + intersect(&node, 5, &short, true), + [0x20c, 0x400, NONE, NONE] + ); + // An entry exactly at the extent is no hit. + let exact = Ray { + extent: 19.0, + ..ray + }; + assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]); + // Backwards: nothing. + let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0); + assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]); + } + + #[test] + fn a_ray_starting_inside_a_box_enters_it_at_its_origin() { + let node = box32( + [8, 16, NONE, NONE], + [UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF], + ); + let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0); + // Box 0 is entered at -1 (behind the origin), box 1 at 2. + assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]); + // Even with a tiny extent the box around the origin is a hit. + let tiny = Ray { + extent: 1e-6, + ..ray + }; + assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]); + } + + #[test] + fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() { + let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]); + // Direction components of 0: the inverse is infinite. + let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0); + assert!(ray.inverse[1].is_infinite()); + // The origin lies in the plane of the box's -y face: (-1 - -1) x inf + // would be a NaN; with the inverse held finite it is 0, and the ray + // running along the face is inside. + assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]); + // Along the +y face it is outside: the face's plane is left at 0 + // and the box is entered at 4 (as the public emulation has it). + let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]); + let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]); + // -0 gives -infinity. + let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0); + assert_eq!(minus.inverse[1], f32::NEG_INFINITY); + assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]); + } + + #[test] + fn a_box_switched_off_and_a_missing_child_return_none() { + let node = box32( + [8, NONE, 24, 32], + [UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF], + ); + let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0); + // Child 1 is hit but is not there: its pointer is what "none" is. + assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]); + } + + #[test] + fn equal_distances_keep_child_order() { + let node = box32([8, 16, 24, 32], [UNIT; 4]); + let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]); + } + + #[test] + fn half_float_boxes_test_like_their_widened_values() { + let boxes = [ + moved(UNIT, [30.0, 0.1, 0.0]), + moved(UNIT, [10.0, 0.0, 0.3]), + moved(UNIT, [10.0, 5.0, 0.0]), + moved(UNIT, [20.7, 0.0, 0.0]), + ]; + let children = [0x105, 0x20c, 0x304, 0x400]; + let node = box16(children, boxes); + let wide = boxes16(&node); + for (w, b) in wide.iter().zip(&boxes) { + for k in 0..3 { + assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward"); + } + } + let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0); + assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]); + assert_eq!( + intersect(&node, 4, &ray, true), + intersect(&box32(children, wide), 5, &ray, true) + ); + } + + /// The hit a result describes: distance, I, J, front face. + fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> { + let [t, det, i, j] = r.map(f32::from_bits); + (t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0)) + } + + /// Clockwise seen from the origin looking down +z in a left-handed + /// system (x right, y up): the front face. + const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]]; + + #[test] + fn a_triangle_returns_distance_and_weights_over_one_denominator() { + let node = triangles(&TRIANGLE, 9); + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit"); + assert_eq!(t, 5.0); + // (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2. + assert_eq!((i, j), (0.25, 0.25)); + assert!(front); + // Near vertex 1: I near 1. + let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0); + let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit"); + assert!(i > 0.85 && j < 0.1, "{i} {j}"); + // From behind: the same weights, the back face. + let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0); + let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit"); + assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false)); + // An unnormalised direction: the distance is in its units. + let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0); + assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25); + } + + #[test] + fn a_triangle_is_missed_beside_behind_and_edge_on() { + let node = triangles(&TRIANGLE, 9); + let miss = MISS.map(f32::to_bits); + // Beside it. + let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&node, 0, &ray, true), miss); + // It lies behind the origin. + let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&node, 0, &ray, true), miss); + // In its plane. + let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0); + assert_eq!(intersect(&node, 0, &ray, true), miss); + // A triangle with no area. + let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9); + let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&flat, 0, &ray, true), miss); + // A vertex that is not a number, a direction of zero. + let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9); + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + assert_eq!(intersect(&nan, 0, &ray, true), miss); + let still = Ray::new([0.0; 3], [0.0; 3], 100.0); + assert_eq!(intersect(&node, 0, &still, true), miss); + // The extent is the program's to test: a far triangle is a hit. + let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0); + assert!(hit(intersect(&node, 0, &short, true)).is_some()); + } + + #[test] + fn a_ray_through_a_shared_edge_misses_neither_triangle() { + // Two triangles of a quad sharing the diagonal, wound alike. + let quad = [ + [-1.0, -1.0, 4.0], + [-1.0, 1.0, 4.0], + [1.0, 1.0, 4.0], + [1.0, -1.0, 4.0], + ]; + let first = triangles(&[quad[0], quad[1], quad[2]], 9); + let second = triangles(&[quad[0], quad[2], quad[3]], 9); + // A fan of rays crossing the diagonal, some exactly on it. + for n in -40..=40 { + let x = n as f32 / 64.0; + for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] { + for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] { + // Aim at (ox, oy, 4). + let s = 4.0 / d[2]; + let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0); + let a = hit(intersect(&first, 0, &ray, true)); + let b = hit(intersect(&second, 0, &ray, true)); + assert!( + a.is_some() || b.is_some(), + "a hole at {ox} {oy} along {d:?}" + ); + for h in [a, b].into_iter().flatten() { + assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}"); + } + } + } + } + } + + #[test] + fn the_id_dword_says_which_vertices_the_weights_belong_to() { + // What the title's builder does with an input triangle (a, b, c) + // and an id byte: a at the vertex neither field names, b at I's, + // c at J's. + let [a, b, c] = TRIANGLE; + let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0); + let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true); + for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] { + let mut stored = [[0f32; 3]; 3]; + stored[(3 - i - j) as usize] = a; + stored[i as usize] = b; + stored[j as usize] = c; + let node = triangles(&stored, i | j << 2); + assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}"); + } + // The higher bits of the byte (opaque and the like) change nothing. + let node = triangles(&[a, b, c], 9 | 0x80); + assert_eq!(intersect(&node, 0, &ray, true), plain); + } + + #[test] + fn triangles_one_to_three_take_their_vertices_and_their_id_byte() { + let [a, b, c] = TRIANGLE; + let far = [50.0, 50.0, 50.0]; + let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0); + let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true); + for k in 1..4u32 { + // Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`. + let mut vertices = [far; 5]; + let at = TRIANGLE_VERTICES[k as usize]; + vertices[at[0] as usize] = a; + vertices[at[1] as usize] = b; + vertices[at[2] as usize] = c; + // Triangle 0's byte would be malformed here; only byte k counts. + let node = triangles(&vertices, 9 << (8 * k)); + assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}"); + } + // A pair as the title's builder stores it: the second triangle's + // own vertex at node vertex 3, named by I. + let d = [2.0, 2.0, 5.0]; + // Input triangles (a, b, c) and (a, d, b): they share a and b. + let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8); + // Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2. + let got = triangle_vertices(&node, 1); + assert_eq!(got, [b, d, c]); + } + + #[test] + fn instances_and_procedural_nodes_return_a_triangle_miss() { + let node = triangles(&TRIANGLE, 9); + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + for k in [6, 7] { + assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits)); + } + } + + #[test] + fn the_largest_axis_and_its_sign_do_not_change_the_answer() { + // The same triangle and ray turned so the ray's largest axis is each + // of the three, forwards and backwards. Both turns are rotations, + // so the facing stays. + let turn = |v: [f32; 3], axis: usize, flip: bool| { + let mut r = v; + for _ in 0..axis { + r = [r[2], r[0], r[1]]; + } + if flip { + // Half a turn about the axis after the largest one's next. + let largest = (2 + axis) % 3; + r[largest] = -r[largest]; + r[(largest + 1) % 3] = -r[(largest + 1) % 3]; + } + r + }; + let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0); + let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit"); + for axis in 0..3 { + for flip in [false, true] { + let p = TRIANGLE.map(|v| turn(v, axis, flip)); + let r = Ray::new( + turn(ray.origin, axis, flip), + turn(ray.direction, axis, flip), + 100.0, + ); + let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit"); + assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}"); + assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5); + assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}"); + } + } + } +} diff --git a/crates/victory-shader/src/dxbc.rs b/crates/victory-shader/src/dxbc.rs index c95e32ebb5..8d5bd73ee2 100644 --- a/crates/victory-shader/src/dxbc.rs +++ b/crates/victory-shader/src/dxbc.rs @@ -17,6 +17,8 @@ pub struct FourCC(pub [u8; 4]); impl FourCC { pub const DXIL: FourCC = FourCC(*b"DXIL"); + /// Native code another compiler made, in place of `DXIL` (VIctory upstream 0b35b7f). + pub const ACCC: FourCC = FourCC(*b"ACCC"); pub const STAT: FourCC = FourCC(*b"STAT"); pub const RTS0: FourCC = FourCC(*b"RTS0"); pub const PSV0: FourCC = FourCC(*b"PSV0"); @@ -111,36 +113,6 @@ impl<'a> Container<'a> { } } -/// Every container stored as is in `data`, found by its magic, as its offset -/// and its bytes (`total size` long), in file order. A `DXBC` inside one of -/// a found container's parts (a container kept in a part, say) is part of -/// that container, not another one. Its header is not such a place: a magic -/// in bytes before a real container may read its header from the real one, -/// and must not hide it. Offsets for which `skip` is true are not looked at -/// (bytes that belong to something else, such as a packed record). -pub fn find_all(data: &[u8], skip: impl Fn(usize) -> bool) -> Vec<(usize, &[u8])> { - let mut out = Vec::new(); - // Parts of the containers found so far that may still hold a magic. - let mut parts: Vec<std::ops::Range<usize>> = Vec::new(); - for offset in memchr::memmem::find_iter(data, b"DXBC") { - parts.retain(|p| p.end > offset); - if parts.iter().any(|p| p.contains(&offset)) || skip(offset) { - continue; - } - let Ok(container) = Container::parse(&data[offset..]) else { - continue; - }; - // `parse` checked the size against the data. - let total = u32_at(data, offset + 0x18).expect("parsed header") as usize; - parts.extend(container.parts.iter().map(|p| { - let start = offset + p.offset + 8; - start..start + p.data.len() - })); - out.push((offset, &data[offset..offset + total])); - } - out -} - pub(crate) fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> { data.get(at..at + 2) .map(|b| u16::from_le_bytes(b.try_into().expect("2 bytes"))) @@ -198,58 +170,6 @@ mod tests { assert!(c.part(FourCC::DXIL).is_none()); } - #[test] - fn container_in_a_part_is_not_another_container() { - let inner = build(&[(FourCC::SFI0, &[1, 2, 3, 4])]); - let outer = build(&[(FourCC::ILDB, &inner), (FourCC::HASH, &[9; 20])]); - let other = build(&[(FourCC::STAT, &[7; 12])]); - let mut data = b"gap".to_vec(); - let outer_at = data.len(); - data.extend_from_slice(&outer); - data.extend_from_slice(b"gap"); - let other_at = data.len(); - data.extend_from_slice(&other); - let inner_at = outer_at + memchr::memmem::find(&outer[4..], b"DXBC").unwrap() + 4; - // The nested one parses on its own. - assert!(Container::parse(&data[inner_at..]).is_ok()); - - let found = find_all(&data, |_| false); - let offsets: Vec<_> = found.iter().map(|&(o, _)| o).collect(); - assert_eq!(offsets, [outer_at, other_at]); - assert_eq!(found[0].1, &outer[..]); - assert_eq!(found[1].1, &other[..]); - - // Skipping the outer one exposes the one it holds. - let found = find_all(&data, |o| o == outer_at); - let offsets: Vec<_> = found.iter().map(|&(o, _)| o).collect(); - assert_eq!(offsets, [inner_at, other_at]); - assert_eq!(found[0].1, &inner[..]); - } - - #[test] - fn header_reading_into_a_container_does_not_hide_it() { - // A magic 21 bytes before a real container: its digest and version - // are the junk, its size and part count come from the real header - // (0x43, the real "C", and 0 parts), so it parses, with no parts. - let real = build(&[(FourCC::SFI0, &[1, 2, 3, 4])]); - let mut data = b"DXBC not a container ".to_vec(); - let real_at = data.len(); - data.extend_from_slice(&real); - assert_eq!(Container::parse(&data).unwrap().parts.len(), 0); - - let offsets: Vec<_> = find_all(&data, |_| false).iter().map(|&(o, _)| o).collect(); - assert_eq!(offsets, [0, real_at]); - } - - #[test] - fn finds_nothing_in_noise() { - assert!(find_all(b"", |_| false).is_empty()); - assert!(find_all(b"DXBC", |_| false).is_empty()); - let mut bytes = build(&[(FourCC::SFI0, &[0; 8])]); - bytes.pop(); // the stated size runs past the end - assert!(find_all(&bytes, |_| false).is_empty()); - } - #[test] fn rejects_bad_input() { assert_eq!(Container::parse(b"nope").unwrap_err(), ShaderError::NotDxbc); diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 2a0ba3cb59..8d2b5fe6aa 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -7,14 +7,30 @@ use std::collections::HashMap; +pub mod census; +pub mod opt; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub(crate) struct Ty(u32); +/// What the lowering made an instruction for, where it says so (counted by +/// [`census`], nothing else reads it). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Tag { + /// The select that keeps a register's old value in lanes a guard masks. + Guard, + /// An index clamp the translation adds (the console has none). + Clamp, + /// The iteration counter and limit test the translation adds to a loop. + Counter, +} + #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum TypeDef { Void, Int(u32), Float, + Double, /// Pointee and address space. Ptr(Ty, u32), Struct(Option<String>, Vec<Ty>), @@ -212,15 +228,11 @@ pub(crate) struct Module { blocks: Vec<Block>, mds: Vec<MdDef>, named: Vec<(String, Vec<Md>)>, + /// See [`Tag`]: by instruction. + tags: HashMap<u32, Tag>, } impl Module { - /// The names of the declared and defined functions. - #[cfg(test)] - pub fn func_names(&self) -> Vec<String> { - self.funcs.iter().map(|f| f.name.clone()).collect() - } - fn ty(&mut self, def: TypeDef) -> Ty { if let Some(&t) = self.type_ids.get(&def) { return Ty(t); @@ -240,6 +252,9 @@ impl Module { pub fn float(&mut self) -> Ty { self.ty(TypeDef::Float) } + pub fn double(&mut self) -> Ty { + self.ty(TypeDef::Double) + } pub fn ptr(&mut self, to: Ty) -> Ty { self.ty(TypeDef::Ptr(to, 0)) } @@ -365,6 +380,16 @@ impl Module { g } + /// Notes what instruction `v` is for (see [`Tag`]); only when modules + /// are counted. + pub fn tag(&mut self, v: V, tag: Tag) { + if let V::Inst(i) = v + && census::enabled() + { + self.tags.insert(i, tag); + } + } + pub fn new_block(&mut self) -> usize { self.blocks.push(Block::default()); self.blocks.len() - 1 @@ -496,27 +521,6 @@ impl Module { self.named.push((name.into(), nodes)); } - #[cfg(test)] - pub(crate) fn has_dx_op(&self, name: &str, opcode: i64) -> bool { - self.insts.iter().any(|inst| match &inst.op { - Op::Call(fid, args) => { - self.funcs[*fid as usize].name == name - && matches!( - args.first(), - Some(V::Const(cid)) if matches!(self.consts[*cid as usize].1, Const::Int(n) if n == opcode) - ) - } - _ => false, - }) - } - - #[cfg(test)] - pub(crate) fn has_cmp(&self, predicate: u8) -> bool { - self.insts - .iter() - .any(|inst| matches!(inst.op, Op::Cmp(p, _, _) if p == predicate)) - } - /// The module as bitcode. /// Which instructions are written: every body instruction, the branch /// conditions, and whatever they read, transitively (a phi nothing reads @@ -582,6 +586,7 @@ impl Module { match t { TypeDef::Void => w.record(2, &[]), TypeDef::Float => w.record(3, &[]), + TypeDef::Double => w.record(4, &[]), TypeDef::Int(b) => w.record(7, &[u64::from(*b)]), TypeDef::Ptr(p, space) => w.record(8, &[u64::from(p.0), u64::from(*space)]), TypeDef::Array(n, e) => w.record(11, &[u64::from(*n), u64::from(e.0)]), diff --git a/crates/victory-shader/src/emit/bitcode/census.rs b/crates/victory-shader/src/emit/bitcode/census.rs new file mode 100644 index 0000000000..03eeccfd7b --- /dev/null +++ b/crates/victory-shader/src/emit/bitcode/census.rs @@ -0,0 +1,174 @@ +//! Counts of a module's instructions by kind (a diagnostic): what a +//! translated program costs before the driver's compiler sees it. +//! +//! `VICTORY_SHADER_CENSUS` (any value) turns the counting on; the counts of +//! the module a thread wrote last are read with [`take`]. The `translate` +//! command writes them as a table (see `apps/victory/src/translate.rs`). + +use super::{Cast, Module, Op, Tag, Term, V}; +use std::cell::RefCell; + +/// The kinds, in the order of [`Census::counts`]. +pub const KINDS: [&str; 26] = [ + "total", + "arith", + "math_call", + "bitcast", + "cast", + "select", + "guard_select", + "phi", + "extract", + "buffer_load", + "cbuffer_load", + "texture_read", + "lds_load", + "buffer_store", + "lds_store", + "atomic", + "handle", + "annotate", + "dimensions", + "barrier", + "wave_op", + "io_other", + "gep", + "clamp", + "loop_counter", + "blocks", +]; + +/// Instruction counts of one written module, by [`KINDS`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Census { + pub counts: [u32; KINDS.len()], +} + +thread_local! { + /// The modules this thread wrote since the last [`take`]: the length and + /// a hash of each one's bitcode, with its counts (a program may be + /// emitted in several forms before one is kept). + static WRITTEN: RefCell<Vec<(usize, u64, Census)>> = const { RefCell::new(Vec::new()) }; +} + +fn fnv(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| { + (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) + }) +} + +/// Whether modules are counted (`VICTORY_SHADER_CENSUS` set). +pub fn enabled() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SHADER_CENSUS").is_some()) +} + +/// The counts of the module whose bitcode the container `dxil` holds, if +/// this thread wrote it since the last call (which forgets the others). +pub fn take(dxil: &[u8]) -> Option<Census> { + let written = WRITTEN.with(|l| std::mem::take(&mut *l.borrow_mut())); + let at = dxil.windows(4).position(|w| w == b"BC\xC0\xDE")?; + written + .into_iter() + .rev() + .find(|(len, hash, _)| dxil.get(at..at + len).is_some_and(|b| fnv(b) == *hash)) + .map(|w| w.2) +} + +/// Counts `m`, whose written form is `bitcode`, and keeps the result for +/// [`take`]. +pub(crate) fn note(m: &Module, bitcode: &[u8]) { + if !enabled() { + return; + } + let c = m.census(); + WRITTEN.with(|l| l.borrow_mut().push((bitcode.len(), fnv(bitcode), c))); +} + +fn kind(name: &str) -> usize { + let n = name.strip_prefix("dx.op.").unwrap_or(name); + let n = n.split('.').next().unwrap_or(n); + let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind"); + match n { + "unary" | "binary" | "tertiary" | "unaryBits" | "legacyF16ToF32" | "legacyF32ToF16" + | "isSpecialFloat" | "dot2" | "dot3" | "dot4" | "quaternary" => k("math_call"), + "bufferLoad" | "rawBufferLoad" => k("buffer_load"), + "cbufferLoadLegacy" | "cbufferLoad" => k("cbuffer_load"), + "bufferStore" | "rawBufferStore" | "textureStore" => k("buffer_store"), + "atomicBinOp" | "atomicCompareExchange" => k("atomic"), + "createHandle" | "createHandleFromBinding" | "createHandleFromHeap" => k("handle"), + "annotateHandle" => k("annotate"), + "getDimensions" => k("dimensions"), + "barrier" => k("barrier"), + _ if n.starts_with("wave") || n.starts_with("quad") => k("wave_op"), + _ if n.starts_with("textureLoad") + || n.starts_with("sample") + || n.starts_with("textureGather") + || n.starts_with("calculateLOD") => + { + k("texture_read") + } + _ => k("io_other"), + } +} + +impl Module { + /// The instructions [`Module::write`] writes, by kind. + pub(crate) fn census(&self) -> Census { + let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind"); + let call_kind: Vec<usize> = self.funcs.iter().map(|f| kind(&f.name)).collect(); + let live = self.live(); + // The blocks `write` lays out: those reached from the entry. + let mut seen = vec![false; self.blocks.len()]; + let mut stack = vec![0usize]; + if !self.blocks.is_empty() { + seen[0] = true; + } + while let Some(b) = stack.pop() { + for &s in super::successors(self.blocks[b].term).iter() { + if !seen[s] { + seen[s] = true; + stack.push(s); + } + } + } + let mut c = Census::default(); + for (b, blk) in self.blocks.iter().enumerate() { + if !seen[b] { + continue; + } + c.counts[k("blocks")] += 1; + let _: Option<Term> = blk.term; + for &i in blk + .phis + .iter() + .filter(|&&i| live[i as usize]) + .chain(&blk.body) + { + c.counts[0] += 1; + let at = match &self.insts[i as usize].op { + Op::Bin(..) | Op::Cmp(..) => k("arith"), + Op::Cast(Cast::Bitcast, _) => k("bitcast"), + Op::Cast(..) => k("cast"), + Op::Select(..) => k("select"), + Op::Extract(..) => k("extract"), + Op::Phi(_) => k("phi"), + Op::Gep(..) => k("gep"), + Op::Load(_) => k("lds_load"), + Op::Store(..) => k("lds_store"), + Op::AtomicRmw(..) | Op::CmpXchg(..) => k("atomic"), + Op::Call(f, _) => call_kind[*f as usize], + }; + c.counts[at] += 1; + match self.tags.get(&i) { + Some(Tag::Guard) => c.counts[k("guard_select")] += 1, + Some(Tag::Clamp) => c.counts[k("clamp")] += 1, + Some(Tag::Counter) => c.counts[k("loop_counter")] += 1, + None => {} + } + let _ = V::Inst(i); + } + } + c + } +} diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs new file mode 100644 index 0000000000..83ab973ae9 --- /dev/null +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -0,0 +1,2148 @@ +//! Clean-up of a finished module before it is written: the lowering emits +//! one instruction after another as the console code names them, and +//! nothing stands between it and the driver's compiler. Every pass here is +//! exact: the module computes the same values and has the same effects for +//! every input. +//! +//! - [`DEAD`]: instructions without an effect whose result nothing reads +//! are left out (the lowering computes every dword of every register a +//! console instruction writes; a guarded write reads the register's old +//! value whether anything reads the new one or not). +//! - [`FOLD`]: integer arithmetic on constants is done here, and identities +//! (`x + 0`, `x & -1`, a select between a value and itself, a cast there +//! and back, a join of one value) give their operand. Float arithmetic is +//! left alone: `x + 0.0` and `x * 1.0` are not `x` for every `x`. +//! - [`REUSE`]: an instruction without an effect whose operands are those +//! of an earlier one that every path to it has run gives that one's +//! result (a descriptor handle made again in each block, an index clamped +//! again, a register read as a float again). +//! - [`FACTS`]: in the blocks only one side of a branch leads to, the +//! branch's condition is that side's constant, and so is what the +//! condition was made of (both terms of an `and` that held, the opposite +//! comparison). The lowering branches on a lane's condition and then +//! guards each instruction behind the branch with the same condition. +//! - [`LOADS`]: within a block, a read of the same place as an earlier read +//! gives that one's result while no store, atomic, barrier or other call +//! with an effect stands between them (another thread's unsynchronised +//! store may fall between any two reads or before both: the title's code +//! cannot tell which). +//! +//! Which passes run is `emit::shader_opt()` (`VICTORY_SHADER_OPT`), part of +//! the translation and so of the shader cache's key. + +use std::collections::HashMap; + +use super::{ + Attr, Bin, Cast, Const, Func, MdDef, Module, Op, Term, Ty, TypeDef, V, for_each_operand, pred, + successors, +}; + +/// Dead-code elimination. +pub const DEAD: u32 = 1; +/// Constants folded, identities removed. +pub const FOLD: u32 = 2; +/// One instruction for one value. +pub const REUSE: u32 = 4; +/// What a branch taken says about its condition. +pub const FACTS: u32 = 8; +/// One read for one place within a block, while nothing is stored. +pub const LOADS: u32 = 16; +/// Not a pass over the module: the lowering of a first-lane read in a +/// wave64 program run as two host waves skips the exchange that asks which +/// half has a lane where every lane is in EXEC (`lower.rs`, +/// `v_readfirstlane_b32`). +pub const FIRST: u32 = 32; +/// Not a pass over the module either: the lowering reads the dwords of one +/// console load (`s_buffer_load_dwordx2` to `x16` from an SRV, a +/// `global_load_dwordx2` to `x4`) by one call for every four of them, not +/// by a call each (`lower.rs`, `raw_dwords`). NOT the same result on the card in every case: run 277 +/// had the water black with it (lead: a four-dword load whose last dwords +/// lie past the view's end, which the card may answer with zeros for the +/// whole call), so it stays off unless asked for. +pub const WIDE: u32 = 64; +/// The passes over the module. +pub const MODULE: u32 = DEAD | FOLD | REUSE | FACTS | LOADS; +/// Every pass. +pub const ALL: u32 = MODULE | FIRST | WIDE; +/// The passes that run when nothing says which: every one but [`WIDE`], +/// which no card has shown a gain for yet (`VICTORY_SHADER_OPT=127` asks +/// for it). +pub const DEFAULT: u32 = ALL & !WIDE; + +/// What the instructions a module writes use, of the features a shader +/// declares by flag (the validator's "flags must match usage"). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct Usage { + /// A wave or quad operation. + pub wave_ops: bool, + /// A 64-bit integer, as a result or an operand. + pub int64: bool, + /// A typed load of several components from a UAV. + pub typed_uav_loads: bool, + /// A handle from the view heap. + pub heap_views: bool, + /// A handle from the sampler heap. + pub heap_samplers: bool, + /// A 64-bit atomic. + pub atomic64: bool, +} + +/// What makes two instructions without an effect the same value. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Key { + Bin(u8, V, V), + Cast(u8, Ty, V), + Cmp(u8, V, V), + Select(V, V, V), + Extract(V, u32), + Call(u32, Vec<V>), + Gep(Ty, V, Vec<V>), + Load(V), +} + +/// The blocks reached from the entry, each after the blocks that dominate +/// it, and each block's children in the dominator tree. +struct Tree { + order: Vec<usize>, + children: Vec<Vec<usize>>, + /// Per block: the reached blocks that branch to it, once per edge. + preds: Vec<Vec<usize>>, +} + +/// The comparison that holds exactly when `p` does not (floats 0-15, +/// integers 32-41). +fn opposite(p: u8) -> u8 { + match p { + 0..=15 => 15 - p, + pred::EQ => pred::NE, + pred::NE => pred::EQ, + pred::IUGT => pred::IULE, + pred::IULE => pred::IUGT, + pred::IUGE => pred::IULT, + pred::IULT => pred::IUGE, + pred::SGT => pred::SLE, + pred::SLE => pred::SGT, + pred::SGE => pred::SLT, + _ => pred::SGE, + } +} + +/// What holds in the block being walked: values that are a known bit there, +/// and comparisons (by their operands) with a known outcome. +#[derive(Default)] +struct Facts { + bits: HashMap<V, bool>, + compares: HashMap<(u8, V, V), bool>, +} + +/// The facts a block added, to forget when its part of the tree is done. +#[derive(Default)] +struct Learned { + bits: Vec<V>, + compares: Vec<(u8, V, V)>, +} + +fn mask(bits: u32) -> u64 { + if bits >= 64 { !0 } else { (1 << bits) - 1 } +} + +/// `x` of `bits` bits as a signed number. +fn signed(bits: u32, x: u64) -> i64 { + if bits < 64 && x >> (bits - 1) & 1 != 0 { + (x | !mask(bits)) as i64 + } else { + x as i64 + } +} + +/// What `v` stands for after the replacements so far. +fn resolve(repl: &[Option<V>], mut v: V) -> V { + while let V::Inst(i) = v { + match repl[i as usize] { + Some(r) => v = r, + None => break, + } + } + v +} + +/// Replaces every value `op` reads by `f` of it. +fn map_operands(op: &mut Op, mut f: impl FnMut(V) -> V) { + match op { + Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => { + *a = f(*a); + *b = f(*b); + } + Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => *v = f(*v), + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { + *a = f(*a); + *b = f(*b); + *c = f(*c); + } + Op::Call(_, args) => args.iter_mut().for_each(|a| *a = f(*a)), + Op::Phi(inc) => inc.iter_mut().for_each(|x| x.0 = f(x.0)), + Op::Gep(_, p, idx) => { + *p = f(*p); + idx.iter_mut().for_each(|i| *i = f(*i)); + } + } +} + +/// What a call does besides returning its result. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Effect { + /// Nothing, and the result depends on the arguments alone for the whole + /// run of the shader (arithmetic, handles, inputs, constant buffers, + /// resource sizes). + Pure, + /// Nothing, but the result depends on memory a store may change + /// (buffer and texture reads). + Reads, + /// Nothing, but the result depends on which lanes run the instruction + /// (wave and quad operations). + Lanes, + /// Stores, atomics, barriers, outputs, discards: always kept. + Writes, +} + +pub(super) fn effect(f: &Func) -> Effect { + let name = f.name.strip_prefix("dx.op.").unwrap_or(&f.name); + match f.attr { + Some(Attr::ReadNone) => Effect::Pure, + // A shader cannot write a constant buffer or resize a resource. + Some(Attr::ReadOnly) + if name.starts_with("cbufferLoadLegacy") || name.starts_with("getDimensions") => + { + Effect::Pure + } + Some(Attr::ReadOnly) if name.starts_with("wave") => Effect::Lanes, + Some(Attr::ReadOnly) => Effect::Reads, + // Declared with the attribute of calls that have effects, and have + // none: they read the other lanes' values. + _ if name.starts_with("wave") || name.starts_with("quad") => Effect::Lanes, + _ => Effect::Writes, + } +} + +impl Module { + /// Runs the clean-up passes named in `passes` ([`ALL`]: every one). + pub(crate) fn optimise(&mut self, passes: u32) { + if passes & (FOLD | REUSE | FACTS | LOADS) != 0 { + // Values merged in one round can make two joins the same in + // the next (a loop's registers that only go round), and a + // branch that goes one way leaves blocks with one way in. + for _ in 0..4 { + let mut changed = self.merge(passes); + if passes & FOLD != 0 { + changed |= self.prune(); + } + if !changed { + break; + } + } + } + if passes & DEAD != 0 { + self.drop_dead(); + } + } + + /// Per function: what a call of it does. + pub(super) fn effects(&self) -> Vec<Effect> { + self.funcs.iter().map(effect).collect() + } + + /// The blocks reached from the entry. + pub(super) fn reached(&self) -> Vec<bool> { + let mut seen = vec![false; self.blocks.len()]; + if self.blocks.is_empty() { + return seen; + } + let mut stack = vec![0usize]; + seen[0] = true; + while let Some(b) = stack.pop() { + for &s in successors(self.blocks[b].term).iter() { + if !seen[s] { + seen[s] = true; + stack.push(s); + } + } + } + seen + } + + fn dominator_tree(&self) -> Tree { + let n = self.blocks.len(); + let succs = |b: usize| successors(self.blocks[b].term); + // Reverse postorder, as `write` lays the blocks out. + let mut seen = vec![false; n]; + let mut post = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, k) = *top; + top.1 += 1; + match succs(b).get(k) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + let order = post; + let mut number = vec![usize::MAX; n]; + for (k, &b) in order.iter().enumerate() { + number[b] = k; + } + let mut preds = vec![Vec::new(); n]; + for &b in &order { + for &s in succs(b).iter() { + preds[s].push(b); + } + } + // Immediate dominators (Cooper, Harvey and Kennedy's iteration). + let mut idom = vec![usize::MAX; n]; + idom[0] = 0; + let mut changed = true; + while changed { + changed = false; + for &b in &order[1..] { + let mut new = usize::MAX; + for &p in &preds[b] { + if idom[p] == usize::MAX { + continue; + } + if new == usize::MAX { + new = p; + continue; + } + let (mut x, mut y) = (p, new); + while x != y { + while number[x] > number[y] { + x = idom[x]; + } + while number[y] > number[x] { + y = idom[y]; + } + } + new = x; + } + if idom[b] != new { + idom[b] = new; + changed = true; + } + } + } + let mut children = vec![Vec::new(); n]; + for &b in &order[1..] { + children[idom[b]].push(b); + } + Tree { + order, + children, + preds, + } + } + + /// Notes that `v` (an i1) is `holds` in the block being walked, and what + /// follows from it for the values `v` was made of. + fn learn(&self, v: V, holds: bool, facts: &mut Facts, learned: &mut Learned, depth: u32) { + let V::Inst(i) = v else { return }; + if facts.bits.contains_key(&v) { + return; + } + facts.bits.insert(v, holds); + learned.bits.push(v); + if depth == 0 { + return; + } + match self.insts[i as usize].op { + // Both terms of an `and` that holds hold; neither of an `or` + // that does not. + Op::Bin(Bin::And, a, b) if holds => { + self.learn(a, true, facts, learned, depth - 1); + self.learn(b, true, facts, learned, depth - 1); + } + Op::Bin(Bin::Or, a, b) if !holds => { + self.learn(a, false, facts, learned, depth - 1); + self.learn(b, false, facts, learned, depth - 1); + } + Op::Bin(Bin::Xor, a, b) => { + let (x, k) = match (self.int_k(a), self.int_k(b)) { + (None, Some((1, k))) => (a, k), + (Some((1, k)), None) => (b, k), + _ => return, + }; + self.learn(x, holds != (k != 0), facts, learned, depth - 1); + } + // The opposite comparison of the same operands. + Op::Cmp(p, a, b) => { + let key = (opposite(p), a, b); + if let std::collections::hash_map::Entry::Vacant(e) = facts.compares.entry(key) { + e.insert(!holds); + learned.compares.push(key); + } + } + _ => {} + } + } + + fn int_bits(&self, ty: Ty) -> Option<u32> { + match self.types[ty.0 as usize] { + TypeDef::Int(bits) => Some(bits), + _ => None, + } + } + + /// An integer constant's width and value (the bits of that width). + fn int_k(&self, v: V) -> Option<(u32, u64)> { + let V::Const(i) = v else { return None }; + let (ty, Const::Int(x)) = &self.consts[i as usize] else { + return None; + }; + let bits = self.int_bits(*ty)?; + Some((bits, *x as u64 & mask(bits))) + } + + /// The constant `x` of the integer type `ty`, kept sign-extended as + /// [`Module::i32`] and [`Module::bool`] keep theirs. + fn k(&mut self, ty: Ty, bits: u32, x: u64) -> V { + self.int_const(ty, signed(bits, x & mask(bits))) + } + + /// The value instruction `i` is known to have without it, if any: a + /// constant or an earlier value. May instead give `i` simpler operands + /// (`changed` says so). + fn simplify(&mut self, i: u32, changed: &mut bool) -> Option<V> { + let ty = self.insts[i as usize].ty; + match self.insts[i as usize].op { + Op::Bin(op, a, b) => { + // Floats: `x + 0.0`, `x * 1.0` and the like are not `x` for + // every `x` (a negative zero, a signalling NaN). + let bits = self.int_bits(ty)?; + let (ka, kb) = (self.int_k(a).map(|k| k.1), self.int_k(b).map(|k| k.1)); + let all = mask(bits); + if let (Some(x), Some(y)) = (ka, kb) { + // A shift by the width or more and a division by zero + // have no defined result: left as they are. + let amount = u32::try_from(y).ok().filter(|&y| y < bits); + let r = match op { + Bin::Add => x.wrapping_add(y), + Bin::Sub => x.wrapping_sub(y), + Bin::Mul => x.wrapping_mul(y), + Bin::And => x & y, + Bin::Or => x | y, + Bin::Xor => x ^ y, + Bin::Shl => x << amount?, + Bin::LShr => x >> amount?, + Bin::AShr => (signed(bits, x) >> amount?) as u64, + Bin::UDiv if y != 0 => x / y, + Bin::URem if y != 0 => x % y, + _ => return None, + }; + return Some(self.k(ty, bits, r)); + } + match (op, ka, kb) { + ( + Bin::Add | Bin::Sub | Bin::Or | Bin::Xor | Bin::Shl | Bin::LShr | Bin::AShr, + _, + Some(0), + ) => Some(a), + (Bin::Add | Bin::Or | Bin::Xor, Some(0), _) => Some(b), + (Bin::Mul | Bin::UDiv, _, Some(1)) => Some(a), + (Bin::Mul, Some(1), _) => Some(b), + (Bin::Mul | Bin::And, _, Some(0)) => Some(b), + (Bin::Mul | Bin::And, Some(0), _) => Some(a), + (Bin::And, _, Some(m)) if m == all => Some(a), + (Bin::And, Some(m), _) if m == all => Some(b), + (Bin::Or, _, Some(m)) if m == all => Some(b), + (Bin::Or, Some(m), _) if m == all => Some(a), + (Bin::And | Bin::Or, _, _) if a == b => Some(a), + _ => None, + } + } + Op::Cmp(p, a, b) if p <= pred::TRUE => { + // Two float constants compare one way (`v_mul_legacy` asks + // whether its constant factor is zero). + let (V::Const(x), V::Const(y)) = (a, b) else { + return None; + }; + let (Const::Float(x), Const::Float(y)) = + (&self.consts[x as usize].1, &self.consts[y as usize].1) + else { + return None; + }; + let (x, y) = (f32::from_bits(*x), f32::from_bits(*y)); + let unordered = x.is_nan() || y.is_nan(); + // Bits 0-2 of a predicate: equal, greater, less; bit 3: + // or unordered. + let holds = if unordered { + p & 8 != 0 + } else { + (p & 1 != 0 && x == y) || (p & 2 != 0 && x > y) || (p & 4 != 0 && x < y) + }; + Some(self.bool(holds)) + } + Op::Cmp(p, a, b) => { + if !(pred::EQ..=pred::SLE).contains(&p) { + return None; + } + let holds = |x: u64, y: u64, bits: u32| { + let (sx, sy) = (signed(bits, x), signed(bits, y)); + match p { + pred::EQ => x == y, + pred::NE => x != y, + pred::IUGT => x > y, + pred::IUGE => x >= y, + pred::IULT => x < y, + pred::IULE => x <= y, + pred::SGT => sx > sy, + pred::SGE => sx >= sy, + pred::SLT => sx < sy, + _ => sx <= sy, + } + }; + if let (Some((bits, x)), Some((_, y))) = (self.int_k(a), self.int_k(b)) { + return Some(self.bool(holds(x, y, bits))); + } + if a == b { + return Some(self.bool(holds(0, 0, 32))); + } + // A bit widened and tested again is the bit. + if p == pred::NE + && self.int_k(b).is_some_and(|k| k.1 == 0) + && let V::Inst(z) = a + && let Op::Cast(Cast::ZExt, x) = self.insts[z as usize].op + && self.type_of(x) == ty + { + return Some(x); + } + None + } + Op::Select(c, mut t, mut f) => { + if let Some((_, c)) = self.int_k(c) { + return Some(if c != 0 { t } else { f }); + } + // Under the same condition an inner select is one of its + // operands (two guarded writes of one register in a row). + let mut inner = false; + while let V::Inst(x) = t + && let Op::Select(c2, t2, _) = self.insts[x as usize].op + && c2 == c + { + (t, inner) = (t2, true); + } + while let V::Inst(x) = f + && let Op::Select(c2, _, f2) = self.insts[x as usize].op + && c2 == c + { + (f, inner) = (f2, true); + } + if t == f { + return Some(t); + } + if self.int_bits(ty) == Some(1) + && self.int_k(t).is_some_and(|k| k.1 == 1) + && self.int_k(f).is_some_and(|k| k.1 == 0) + { + return Some(c); + } + if inner { + self.insts[i as usize].op = Op::Select(c, t, f); + *changed = true; + } + None + } + Op::Cast(op, x) => { + let from = self.type_of(x); + let through = match x { + V::Inst(y) => match self.insts[y as usize].op { + Op::Cast(op2, z) => Some((op2, z)), + _ => None, + }, + _ => None, + }; + match op { + Cast::Bitcast => { + if from == ty { + return Some(x); + } + // There and back: the bits are the same. + if let Some((Cast::Bitcast, z)) = through + && self.type_of(z) == ty + { + return Some(z); + } + let V::Const(c) = x else { return None }; + let to_float = matches!(self.types[ty.0 as usize], TypeDef::Float); + match self.consts[c as usize].1 { + Const::Int(bits) if to_float && self.int_bits(from) == Some(32) => { + Some(self.f32(bits as u32)) + } + Const::Float(bits) if self.int_bits(ty) == Some(32) => { + Some(self.int_const(ty, i64::from(bits as i32))) + } + _ => None, + } + } + Cast::ZExt | Cast::SExt | Cast::Trunc => { + let to = self.int_bits(ty)?; + if let Some((bits, k)) = self.int_k(x) { + let k = if op == Cast::SExt { + signed(bits, k) as u64 + } else { + k + }; + return Some(self.k(ty, to, k)); + } + // Widened and narrowed again. + if op == Cast::Trunc + && let Some((Cast::ZExt | Cast::SExt, z)) = through + && self.type_of(z) == ty + { + return Some(z); + } + None + } + _ => None, + } + } + _ => None, + } + } + + /// What kind of instruction `i` is for merging. + fn class(&self, effects: &[Effect], i: u32) -> Effect { + match &self.insts[i as usize].op { + Op::Bin(..) + | Op::Cast(..) + | Op::Cmp(..) + | Op::Select(..) + | Op::Extract(..) + | Op::Gep(..) => Effect::Pure, + Op::Load(p) => { + // A constant table reads the same whatever is stored. + let base = match *p { + V::Inst(g) => match &self.insts[g as usize].op { + Op::Gep(_, base, _) => *base, + _ => *p, + }, + _ => *p, + }; + match base { + V::Global(g) if self.globals[g as usize].init.is_some() => Effect::Pure, + _ => Effect::Reads, + } + } + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => Effect::Writes, + Op::Phi(_) => Effect::Lanes, + Op::Call(f, _) => effects[*f as usize], + } + } + + fn key(&self, i: u32) -> Option<Key> { + let inst = &self.insts[i as usize]; + Some(match &inst.op { + Op::Bin(op, a, b) => { + // Integer sums, products and bit operations whichever way + // round; float ones as written (which NaN an operation of + // two NaNs gives is the hardware's choice by operand). + let commutes = matches!(op, Bin::Add | Bin::Mul | Bin::And | Bin::Or | Bin::Xor) + && self.int_bits(inst.ty).is_some(); + let (a, b) = if commutes && b < a { + (*b, *a) + } else { + (*a, *b) + }; + Key::Bin(*op as u8, a, b) + } + Op::Cast(op, v) => Key::Cast(*op as u8, inst.ty, *v), + Op::Cmp(p, a, b) => Key::Cmp(*p, *a, *b), + Op::Select(c, t, f) => Key::Select(*c, *t, *f), + Op::Extract(a, n) => Key::Extract(*a, *n), + Op::Call(f, args) => Key::Call(*f, args.clone()), + Op::Gep(ty, p, idx) => Key::Gep(*ty, *p, idx.clone()), + Op::Load(p) => Key::Load(*p), + _ => return None, + }) + } + + /// [`FOLD`], [`REUSE`], [`FACTS`] and [`LOADS`]: one walk over the + /// dominator tree. Returns whether anything changed. + fn merge(&mut self, passes: u32) -> bool { + if self.blocks.is_empty() { + return false; + } + let effects = self.effects(); + let tree = self.dominator_tree(); + let mut repl: Vec<Option<V>> = vec![None; self.insts.len()]; + let mut changed = false; + // Joins of one value: until none is left (one gone can leave + // another with one value). + if passes & FOLD != 0 { + let mut again = true; + while again { + again = false; + for &b in &tree.order { + for &p in &self.blocks[b].phis { + if repl[p as usize].is_some() { + continue; + } + let Op::Phi(incoming) = &self.insts[p as usize].op else { + continue; + }; + let mut one = None; + let mut same = true; + for &(v, _) in incoming { + let v = resolve(&repl, v); + if v == V::Inst(p) { + continue; + } + match one { + None => one = Some(v), + Some(o) if o == v => {} + Some(_) => same = false, + } + } + if let (true, Some(v)) = (same, one) { + repl[p as usize] = Some(v); + again = true; + changed = true; + } + } + } + } + } + // The values every path to the block being walked has computed + // (those of the blocks above it in the tree, and its own so far). + let mut known: HashMap<Key, V> = HashMap::new(); + // The reads of the block being walked since its last store. + let mut read: HashMap<Key, V> = HashMap::new(); + let mut facts = Facts::default(); + let (yes, no) = (self.bool(true), self.bool(false)); + enum Step { + Enter(usize), + Leave(Vec<Key>, Learned), + } + let mut steps = vec![Step::Enter(0)]; + while let Some(step) = steps.pop() { + let b = match step { + Step::Enter(b) => b, + Step::Leave(keys, learned) => { + for k in keys { + known.remove(&k); + } + for v in learned.bits { + facts.bits.remove(&v); + } + for k in learned.compares { + facts.compares.remove(&k); + } + continue; + } + }; + let mut added = Vec::new(); + // Reached from one block alone, by one side of its branch: the + // condition is that side's, here and in every block below. + let mut learned = Learned::default(); + if passes & FACTS != 0 + && let [p] = tree.preds[b][..] + && let Some(Term::CondBr(c, t, f)) = self.blocks[p].term + && t != f + { + self.learn(resolve(&repl, c), b == t, &mut facts, &mut learned, 8); + } + let known_bit = |facts: &Facts, v: V| match facts.bits.get(&v) { + Some(true) => yes, + Some(false) => no, + None => v, + }; + read.clear(); + // Two joins of the same values from the same blocks are one. + if passes & REUSE != 0 && self.blocks[b].phis.len() > 1 { + let mut joins: HashMap<Vec<(usize, V)>, V> = HashMap::new(); + for &p in &self.blocks[b].phis { + if repl[p as usize].is_some() { + continue; + } + let ty = self.insts[p as usize].ty; + let Op::Phi(incoming) = &self.insts[p as usize].op else { + continue; + }; + let mut key: Vec<(usize, V)> = incoming + .iter() + .map(|&(v, from)| (from, resolve(&repl, v))) + .collect(); + key.sort(); + // The type too: an undefined value of one type is not + // that of another. + key.push((ty.0 as usize, V::Global(u32::MAX))); + match joins.get(&key) { + Some(&first) => { + repl[p as usize] = Some(first); + changed = true; + } + None => { + joins.insert(key, V::Inst(p)); + } + } + } + } + let body = std::mem::take(&mut self.blocks[b].body); + let mut kept = Vec::with_capacity(body.len()); + for i in body { + map_operands(&mut self.insts[i as usize].op, |v| { + let v = resolve(&repl, v); + let bit = known_bit(&facts, v); + changed |= bit != v; + bit + }); + if let Op::Cmp(p, x, y) = self.insts[i as usize].op + && let Some(&holds) = facts.compares.get(&(p, x, y)) + { + repl[i as usize] = Some(if holds { yes } else { no }); + changed = true; + continue; + } + if passes & FOLD != 0 + && let Some(v) = self.simplify(i, &mut changed) + { + repl[i as usize] = Some(v); + changed = true; + continue; + } + let class = self.class(&effects, i); + if passes & REUSE != 0 + && class == Effect::Pure + && let Some(key) = self.key(i) + { + if let Some(&first) = known.get(&key) { + repl[i as usize] = Some(first); + changed = true; + continue; + } + known.insert(key.clone(), V::Inst(i)); + added.push(key); + } + // Reads of memory, and wave operations (the same lanes run + // the whole block): the block's own earlier one. + if passes & LOADS != 0 + && matches!(class, Effect::Reads | Effect::Lanes) + && let Some(key) = self.key(i) + { + if let Some(&first) = read.get(&key) { + repl[i as usize] = Some(first); + changed = true; + continue; + } + read.insert(key, V::Inst(i)); + } + if class == Effect::Writes { + read.clear(); + } + kept.push(i); + } + self.blocks[b].body = kept; + if let Some(Term::CondBr(c, t, f)) = self.blocks[b].term { + let c = known_bit(&facts, resolve(&repl, c)); + self.blocks[b].term = Some(Term::CondBr(c, t, f)); + } + steps.push(Step::Leave(added, learned)); + for &c in tree.children[b].iter().rev() { + steps.push(Step::Enter(c)); + } + } + if !changed { + return false; + } + // Everything that read a replaced value reads its replacement + // (joins read values from blocks walked after them). + for blk in &mut self.blocks { + blk.phis.retain(|&p| repl[p as usize].is_none()); + if let Some(Term::CondBr(c, t, f)) = blk.term { + blk.term = Some(Term::CondBr(resolve(&repl, c), t, f)); + } + } + let (blocks, insts) = (&self.blocks, &mut self.insts); + for blk in blocks { + for &i in blk.phis.iter().chain(&blk.body) { + map_operands(&mut insts[i as usize].op, |v| resolve(&repl, v)); + } + } + true + } + + /// [`FOLD`]: a branch on a constant goes one way. The side not taken + /// loses the branching block's values at its joins, and so do the joins + /// of blocks that nothing reaches any more. Returns whether a branch + /// changed. + fn prune(&mut self) -> bool { + let mut changed = false; + for b in 0..self.blocks.len() { + let Some(Term::CondBr(c, t, f)) = self.blocks[b].term else { + continue; + }; + // Both sides one block: two edges into it, left as they are. + if t == f { + continue; + } + let Some((_, k)) = self.int_k(c) else { + continue; + }; + let (taken, not) = if k != 0 { (t, f) } else { (f, t) }; + self.blocks[b].term = Some(Term::Br(taken)); + changed = true; + for n in 0..self.blocks[not].phis.len() { + let p = self.blocks[not].phis[n]; + if let Op::Phi(incoming) = &mut self.insts[p as usize].op { + incoming.retain(|&(_, from)| from != b); + } + } + } + if !changed { + return false; + } + let reached = self.reached(); + let (blocks, insts) = (&self.blocks, &mut self.insts); + for (_, blk) in blocks.iter().enumerate().filter(|(b, _)| reached[*b]) { + for &p in &blk.phis { + if let Op::Phi(incoming) = &mut insts[p as usize].op { + incoming.retain(|&(_, from)| reached[from]); + } + } + } + true + } + + /// Whether instruction `i` must stay whatever reads it. + fn has_effect(&self, effects: &[Effect], i: u32) -> bool { + match &self.insts[i as usize].op { + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => true, + Op::Call(f, _) => effects[*f as usize] == Effect::Writes, + _ => false, + } + } + + /// [`DEAD`]: keeps the instructions with an effect, the branch + /// conditions, and what they read, transitively; the rest leave their + /// blocks. Blocks no branch reaches are emptied (they are not written). + fn drop_dead(&mut self) { + let effects = self.effects(); + let reached = self.reached(); + let mut live = vec![false; self.insts.len()]; + let mut work: Vec<u32> = Vec::new(); + let mark = |live: &mut [bool], work: &mut Vec<u32>, v: V| { + if let V::Inst(i) = v + && !live[i as usize] + { + live[i as usize] = true; + work.push(i); + } + }; + for (b, blk) in self.blocks.iter().enumerate() { + if !reached[b] { + continue; + } + for &i in &blk.body { + if self.has_effect(&effects, i) { + mark(&mut live, &mut work, V::Inst(i)); + } + } + if let Some(Term::CondBr(c, ..)) = blk.term { + mark(&mut live, &mut work, c); + } + } + while let Some(i) = work.pop() { + for_each_operand(&self.insts[i as usize].op, |v| { + mark(&mut live, &mut work, v) + }); + } + for (b, blk) in self.blocks.iter_mut().enumerate() { + if reached[b] { + blk.body.retain(|&i| live[i as usize]); + blk.phis.retain(|&i| live[i as usize]); + } else { + blk.body.clear(); + blk.phis.clear(); + } + } + self.drop_unused_functions(); + self.drop_unused_tables(); + } + + /// See [`Usage`]: over the blocks reached from the entry. + pub(crate) fn usage(&self) -> Usage { + let mut u = Usage::default(); + let reached = self.reached(); + let wide = |ty: Ty| self.types[ty.0 as usize] == TypeDef::Int(64); + // The first field of a handle's annotation: its kind, with the UAV + // bit; the second: the component type and count. + let annotation = |h: V| -> Option<(i64, i64)> { + let V::Inst(a) = h else { return None }; + let Op::Call(f, args) = &self.insts[a as usize].op else { + return None; + }; + if self.funcs[*f as usize].name != "dx.op.annotateHandle" { + return None; + } + let V::Const(props) = *args.get(2)? else { + return None; + }; + let Const::Aggregate(fields) = &self.consts[props as usize].1 else { + return None; + }; + match ( + &self.consts[fields[0] as usize].1, + &self.consts[fields[1] as usize].1, + ) { + (Const::Int(kind), Const::Int(components)) => Some((*kind, *components)), + _ => None, + } + }; + for (_, blk) in self.blocks.iter().enumerate().filter(|(b, _)| reached[*b]) { + for &i in blk.phis.iter().chain(&blk.body) { + let inst = &self.insts[i as usize]; + u.int64 |= wide(inst.ty); + for_each_operand(&inst.op, |v| u.int64 |= wide(self.type_of(v))); + let Op::Call(f, args) = &inst.op else { + continue; + }; + let name = self.funcs[*f as usize].name.as_str(); + let name = name.strip_prefix("dx.op.").unwrap_or(name); + if name.starts_with("wave") || name.starts_with("quad") { + u.wave_ops = true; + } else if name == "createHandleFromHeap" { + match args.get(2).and_then(|&s| self.int_k(s)) { + Some((_, 0)) => u.heap_views = true, + _ => u.heap_samplers = true, + } + } else if name.starts_with("atomic") && name.ends_with(".i64") { + u.atomic64 = true; + } else if name.starts_with("textureLoad") || name.starts_with("bufferLoad") { + u.typed_uav_loads |= args.get(1).and_then(|&h| annotation(h)).is_none_or( + |(kind, components)| kind & 0x1000 != 0 && components >> 8 & 0xff > 1, + ); + } + } + } + u + } + + /// A constant table no remaining load reads leaves the module (the + /// validator refuses an internal declaration nothing uses). Shared + /// memory stays declared whether it is read or not. + fn drop_unused_tables(&mut self) { + let mut used: Vec<bool> = self.globals.iter().map(|g| g.init.is_none()).collect(); + if used.iter().all(|&u| u) { + return; + } + for blk in &self.blocks { + for &i in blk.phis.iter().chain(&blk.body) { + for_each_operand(&self.insts[i as usize].op, |v| { + if let V::Global(g) = v { + used[g as usize] = true; + } + }); + } + } + for md in &self.mds { + if let MdDef::Value(_, V::Global(g)) = md { + used[*g as usize] = true; + } + } + if used.iter().all(|&u| u) { + return; + } + let mut new = vec![u32::MAX; used.len()]; + for (next, (old, _)) in used.iter().enumerate().filter(|u| *u.1).enumerate() { + new[old] = next as u32; + } + let mut old = 0; + self.globals.retain(|_| { + old += 1; + used[old - 1] + }); + let renumber = |v: V| match v { + V::Global(g) if used[g as usize] => V::Global(new[g as usize]), + v => v, + }; + for inst in &mut self.insts { + map_operands(&mut inst.op, renumber); + } + for md in &mut self.mds { + if let MdDef::Value(_, v) = md { + *v = renumber(*v); + } + } + } + + /// Declarations no remaining call names leave the module (the validator + /// refuses an external function nothing uses); the others keep their + /// order, so `main` stays function 0. + fn drop_unused_functions(&mut self) { + let mut used: Vec<bool> = self.funcs.iter().map(|f| f.body).collect(); + for blk in &self.blocks { + for &i in blk.phis.iter().chain(&blk.body) { + if let Op::Call(f, _) = self.insts[i as usize].op { + used[f as usize] = true; + } + } + } + for md in &self.mds { + if let MdDef::Value(_, V::Func(f)) = md { + used[*f as usize] = true; + } + } + if used.iter().all(|&u| u) { + return; + } + let mut new = vec![u32::MAX; used.len()]; + for (next, (old, _)) in used.iter().enumerate().filter(|u| *u.1).enumerate() { + new[old] = next as u32; + } + let mut old = 0; + self.funcs.retain(|_| { + old += 1; + used[old - 1] + }); + self.func_ids = self + .funcs + .iter() + .enumerate() + .map(|(i, f)| (f.name.clone(), i as u32)) + .collect(); + // Instructions that left their block keep a stale number: nothing + // reads them again. + for inst in &mut self.insts { + if let Op::Call(f, _) = &mut inst.op + && used[*f as usize] + { + *f = new[*f as usize]; + } + } + for md in &mut self.mds { + if let MdDef::Value(_, V::Func(f)) = md { + *f = new[*f as usize]; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `main` with one block and a function of each kind of effect. + struct Kit { + m: Module, + b: usize, + pure: V, + reads: V, + writes: V, + } + + fn kit() -> Kit { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let fty = m.func_ty(i32t, vec![i32t, i32t]); + m.ptr(fty); + let pure = m.function("dx.op.binary.i32", fty, Some(Attr::ReadNone), false); + let reads = m.function("dx.op.bufferLoad.i32", fty, Some(Attr::ReadOnly), false); + let writes = m.function("dx.op.bufferStore.i32", fty, Some(Attr::NoUnwind), false); + let main_ty = m.func_ty(void, vec![]); + m.ptr(main_ty); + m.function("main", main_ty, None, true); + let b = m.new_block(); + Kit { + m, + b, + pure, + reads, + writes, + } + } + + fn body(m: &Module, b: usize) -> usize { + m.blocks[b].body.len() + } + + #[test] + fn unread_results_without_effect_are_dropped() { + let Kit { + mut m, + b, + pure, + reads, + writes, + } = kit(); + let (one, two) = (m.i32(1), m.i32(2)); + let used = m.call(b, reads, vec![one, two]); + let dead = m.call(b, reads, vec![two, one]); + let chain = m.bin(b, Bin::Add, dead, one); + let _unread = m.call(b, pure, vec![chain, two]); + // A store's result is unread and stays, with what it reads. + let kept = m.bin(b, Bin::Add, used, two); + m.call(b, writes, vec![kept, one]); + m.terminate(b, Term::Ret); + m.optimise(DEAD); + assert_eq!(body(&m, b), 3, "the load, the add and the store"); + m.write(); + } + + #[test] + fn branch_conditions_and_phi_cycles() { + let Kit { + mut m, + b, + reads, + writes, + .. + } = kit(); + let i32t = m.int(32); + let (zero, one) = (m.i32(0), m.i32(1)); + let (head, exit) = (m.new_block(), m.new_block()); + m.terminate(b, Term::Br(head)); + // A counter that decides the branch, and a register that only + // feeds itself round the loop. + let count = m.phi(head, i32t); + let idle = m.phi(head, i32t); + let next = m.bin(head, Bin::Add, count, one); + let idle_next = m.call(head, reads, vec![idle, one]); + let more = m.cmp(head, pred::IULT, next, one); + m.terminate(head, Term::CondBr(more, head, exit)); + m.set_phi(count, vec![(zero, b), (next, head)]); + m.set_phi(idle, vec![(zero, b), (idle_next, head)]); + m.call(exit, writes, vec![zero, one]); + m.terminate(exit, Term::Ret); + m.optimise(DEAD); + assert_eq!(m.blocks[head].phis.len(), 1, "the counter"); + assert_eq!(body(&m, head), 2, "the step and the test"); + assert_eq!(body(&m, exit), 1); + m.write(); + } + + #[test] + fn wave_operations_have_no_effect_of_their_own() { + let mut k = kit(); + let i32t = k.m.int(32); + let fty = k.m.func_ty(i32t, vec![i32t, i32t]); + let first = k.m.function( + "dx.op.waveReadLaneFirst.i32", + fty, + Some(Attr::NoUnwind), + false, + ); + let barrier = + k.m.function("dx.op.barrier", fty, Some(Attr::NoDuplicate), false); + let one = k.m.i32(1); + k.m.call(k.b, first, vec![one, one]); + k.m.call(k.b, barrier, vec![one, one]); + k.m.terminate(k.b, Term::Ret); + k.m.optimise(DEAD); + assert_eq!(body(&k.m, k.b), 1, "the barrier"); + // The declarations nothing calls any more are gone, and the call + // that stayed names its function by the new number. + let names: Vec<&str> = k.m.funcs.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["main", "dx.op.barrier"]); + let Op::Call(f, _) = k.m.insts[k.m.blocks[k.b].body[0] as usize].op else { + panic!("a call"); + }; + assert_eq!(k.m.funcs[f as usize].name, "dx.op.barrier"); + k.m.write(); + } + + /// The operands of each store left in block `b`. + fn stores(m: &Module, b: usize) -> Vec<Vec<V>> { + m.blocks[b] + .body + .iter() + .filter_map(|&i| match &m.insts[i as usize].op { + Op::Call(g, args) if m.funcs[*g as usize].name.contains("Store") => { + Some(args.clone()) + } + _ => None, + }) + .collect() + } + + #[test] + fn constants_and_identities_fold() { + let Kit { + mut m, + b, + reads, + writes, + .. + } = kit(); + let (i32t, f32t) = (m.int(32), m.float()); + let (zero, one, all) = (m.i32(0), m.i32(1), m.i32(u32::MAX)); + let x = m.call(b, reads, vec![one, one]); + // x + 0, -1 & x, x >> 0, x * 1, x | x: all x. + let a = m.bin(b, Bin::Add, x, zero); + let a = m.bin(b, Bin::And, all, a); + let a = m.bin(b, Bin::LShr, a, zero); + let a = m.bin(b, Bin::Mul, a, one); + let a = m.bin(b, Bin::Or, a, a); + // There and back. + let f = m.cast(b, Cast::Bitcast, a, f32t); + let a = m.cast(b, Cast::Bitcast, f, i32t); + // Constants: (262168 >> 16) & 127 = 4, 7 & 31 = 7, -8 >>s 1 = -4. + let k = m.i32(262168); + let sixteen = m.i32(16); + let k = m.bin(b, Bin::LShr, k, sixteen); + let k127 = m.i32(127); + let k = m.bin(b, Bin::And, k, k127); + let minus8 = m.i32(-8i32 as u32); + let s = m.bin(b, Bin::AShr, minus8, one); + // A shift by the width is left alone. + let k32 = m.i32(32); + let wide = m.bin(b, Bin::Shl, one, k32); + // A select between a value and itself, and on a constant. + let c = m.cmp(b, pred::IULT, zero, one); + let sel = m.select(b, c, a, wide); + let same = m.select(b, c, sel, sel); + m.call(b, writes, vec![same, k]); + m.call(b, writes, vec![s, wide]); + m.terminate(b, Term::Ret); + m.optimise(FOLD | DEAD); + assert_eq!(body(&m, b), 4, "the read, the wide shift and two stores"); + let four = m.i32(4); + let minus4 = m.i32(-4i32 as u32); + let stores = stores(&m, b); + assert_eq!(stores, [vec![x, four], vec![minus4, wide]]); + m.write(); + } + + #[test] + fn float_arithmetic_is_not_folded() { + let Kit { + mut m, b, writes, .. + } = kit(); + let f32t = m.float(); + let fty = m.func_ty(f32t, vec![f32t, f32t]); + let input = m.function("dx.op.loadInput.f32", fty, Some(Attr::ReadNone), false); + let (zero, one, two) = (m.f32(0), m.f32(1.0f32.to_bits()), m.f32(2.0f32.to_bits())); + let x = m.call(b, input, vec![zero, zero]); + let y = m.call(b, input, vec![one, one]); + let a = m.bin(b, Bin::Add, x, zero); + let p = m.bin(b, Bin::Mul, a, one); + // The same sum the other way round is another instruction. + let xy = m.bin(b, Bin::Add, x, y); + let yx = m.bin(b, Bin::Add, y, x); + // Constants compare here: 1 < 2, and nothing equals a NaN. + let nan = m.f32(f32::NAN.to_bits()); + let lt = m.cmp(b, pred::OLT, one, two); + let eq = m.cmp(b, pred::OEQ, nan, nan); + let une = m.cmp(b, pred::UNE, nan, one); + let sel = m.select(b, lt, xy, yx); + let sel = m.select(b, eq, p, sel); + let sel = m.select(b, une, sel, p); + m.call(b, writes, vec![sel, p]); + m.terminate(b, Term::Ret); + m.optimise(ALL); + // Two inputs, x + 0.0, * 1.0, x + y and the store: y + x and the + // selects are gone. + assert_eq!(body(&m, b), 6); + assert_eq!(stores(&m, b), [[xy, p]]); + m.write(); + } + + /// entry: `c = x < y`, branch to `then` or `other`, which join. + struct Diamond { + k: Kit, + x: V, + y: V, + c: V, + then: usize, + other: usize, + join: usize, + } + + fn diamond() -> Diamond { + let mut k = kit(); + let (one, two) = (k.m.i32(1), k.m.i32(2)); + let x = k.m.call(k.b, k.reads, vec![one, one]); + let y = k.m.call(k.b, k.reads, vec![two, two]); + let c = k.m.cmp(k.b, pred::IULT, x, y); + let (then, other, join) = (k.m.new_block(), k.m.new_block(), k.m.new_block()); + k.m.terminate(k.b, Term::CondBr(c, then, other)); + k.m.terminate(then, Term::Br(join)); + k.m.terminate(other, Term::Br(join)); + k.m.terminate(join, Term::Ret); + Diamond { + k, + x, + y, + c, + then, + other, + join, + } + } + + #[test] + fn a_value_is_reused_below_its_block_and_not_beside_it() { + let Diamond { + k: + Kit { + mut m, + b, + pure, + writes, + .. + }, + x, + y, + then, + other, + join, + .. + } = diamond(); + // The entry's value again in a branch; a branch's value again in + // the other branch and in the join (neither is on every path). + let top = m.call(b, pure, vec![x, y]); + m.call(b, writes, vec![top, top]); + let again = m.call(then, pure, vec![x, y]); + let side = m.bin(then, Bin::Add, y, x); + m.call(then, writes, vec![again, side]); + let beside = m.bin(other, Bin::Add, x, y); + m.call(other, writes, vec![beside, beside]); + let after = m.bin(join, Bin::Add, x, y); + m.call(join, writes, vec![after, after]); + m.optimise(REUSE); + assert_eq!(stores(&m, then), [[top, side]]); + assert_eq!(body(&m, then), 2); + assert_eq!(body(&m, other), 2); + assert_eq!(body(&m, join), 2); + m.write(); + } + + #[test] + fn a_branch_taken_says_what_its_condition_is() { + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + c, + then, + other, + join, + } = diamond(); + let three = m.i32(3); + let d = m.call(b, reads, vec![three, three]); + let d = m.cmp(b, pred::NE, d, three); + let both = m.bin(b, Bin::And, c, d); + // Behind the branch: the condition again (a guard), its opposite + // comparison, and a guarded write. + let guard = m.bin(then, Bin::And, c, d); + let old = m.select(then, guard, x, y); + let not = m.cmp(then, pred::IUGE, x, y); + let new = m.select(then, not, y, old); + m.call(then, writes, vec![new, new]); + let kept = m.select(other, c, x, y); + m.call(other, writes, vec![kept, kept]); + // After the join nothing is known. + let open = m.select(join, c, x, y); + m.call(join, writes, vec![open, open]); + m.optimise(FOLD | FACTS); + // then: select(d, x, y) and the store; other: y is stored. + assert_eq!(body(&m, then), 2); + let V::Inst(sel) = stores(&m, then)[0][0] else { + panic!() + }; + assert!(matches!(m.insts[sel as usize].op, Op::Select(g, a, z) if (g, a, z) == (d, x, y))); + assert_eq!(stores(&m, other), [[y, y]]); + assert_eq!(body(&m, join), 2); + let _ = both; + m.write(); + + // Both terms of an `and` that held hold behind it. + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + c, + .. + } = diamond(); + let three = m.i32(3); + let d = m.call(b, reads, vec![three, three]); + let d = m.cmp(b, pred::NE, d, three); + let both = m.bin(b, Bin::And, c, d); + let (inner, out) = (m.new_block(), m.new_block()); + m.terminate(b, Term::CondBr(both, inner, out)); + let a = m.select(inner, c, x, y); + let z = m.select(inner, d, a, y); + m.call(inner, writes, vec![z, z]); + m.terminate(inner, Term::Br(out)); + // Where the `and` did not hold either term may. + let w = m.select(out, d, x, y); + m.call(out, writes, vec![w, w]); + m.terminate(out, Term::Ret); + m.optimise(FOLD | FACTS); + assert_eq!(stores(&m, inner), [[x, x]]); + assert_eq!(body(&m, out), 2); + m.write(); + } + + #[test] + fn a_branch_on_a_constant_goes_one_way() { + let Diamond { + k: Kit { + mut m, b, writes, .. + }, + x, + y, + c, + then, + other, + join, + } = diamond(); + let i32t = m.int(32); + // Behind the branch the same test again: its other side is never + // run, and the join behind it has one value. + let (deep, never, meet) = (m.new_block(), m.new_block(), m.new_block()); + m.terminate(then, Term::CondBr(c, deep, never)); + m.terminate(deep, Term::Br(meet)); + m.call(never, writes, vec![y, y]); + m.terminate(never, Term::Br(meet)); + let p = m.phi(meet, i32t); + m.set_phi(p, vec![(x, deep), (y, never)]); + m.call(meet, writes, vec![p, p]); + m.terminate(meet, Term::Br(join)); + let q = m.phi(join, i32t); + m.set_phi(q, vec![(p, meet), (y, other)]); + m.call(join, writes, vec![q, q]); + m.optimise(ALL); + assert!(matches!(m.blocks[then].term, Some(Term::Br(t)) if t == deep)); + assert_eq!(stores(&m, meet), [[x, x]]); + assert!(m.blocks[meet].phis.is_empty()); + assert_eq!(body(&m, never), 0, "emptied: nothing reaches it"); + let Op::Phi(incoming) = &m.insts[m.blocks[join].phis[0] as usize].op else { + panic!() + }; + assert_eq!(incoming, &vec![(x, meet), (y, other)]); + let _ = b; + m.write(); + } + + #[test] + fn a_read_is_reused_within_its_block_until_a_store() { + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + then, + .. + } = diamond(); + let i32t = m.int(32); + // The entry reads (1, 1) for x: again in the entry it is x; in the + // next block it is read again. + let one = m.i32(1); + let again = m.call(b, reads, vec![one, one]); + m.call(b, writes, vec![again, y]); + let after = m.call(b, reads, vec![one, one]); + let twice = m.call(b, reads, vec![one, one]); + let sum = m.bin(b, Bin::Add, after, twice); + m.call(b, writes, vec![sum, sum]); + let below = m.call(then, reads, vec![one, one]); + m.call(then, writes, vec![below, below]); + // A constant buffer cannot change: one load for the function. + let cfty = m.func_ty(i32t, vec![i32t, i32t]); + let cb = m.function( + "dx.op.cbufferLoadLegacy.i32", + cfty, + Some(Attr::ReadOnly), + false, + ); + let top = m.call(b, cb, vec![one, one]); + m.call(b, writes, vec![top, top]); + let under = m.call(then, cb, vec![one, one]); + m.call(then, writes, vec![under, under]); + m.optimise(REUSE | LOADS); + let stores = stores(&m, b); + assert_eq!(stores[0], [x, y], "the second read is the first"); + let V::Inst(sum) = stores[1][0] else { panic!() }; + assert!( + matches!(m.insts[sum as usize].op, Op::Bin(Bin::Add, a, z) if a == after && z == after), + "read again after the store, once" + ); + assert_eq!(stores[2], [top, top]); + assert_eq!( + super::tests::stores(&m, then), + [vec![below, below], vec![top, top]] + ); + m.write(); + } + + #[test] + fn a_join_of_one_value_and_two_equal_joins() { + let Diamond { + k: Kit { mut m, writes, .. }, + x, + y, + then, + other, + join, + .. + } = diamond(); + let i32t = m.int(32); + let one = m.phi(join, i32t); + m.set_phi(one, vec![(x, then), (x, other)]); + let p = m.phi(join, i32t); + m.set_phi(p, vec![(x, then), (y, other)]); + let q = m.phi(join, i32t); + m.set_phi(q, vec![(y, other), (x, then)]); + m.call(join, writes, vec![one, p]); + let sum = m.bin(join, Bin::Add, p, q); + m.call(join, writes, vec![sum, q]); + m.optimise(FOLD | REUSE); + assert_eq!( + m.blocks[join].phis, + [match p { + V::Inst(i) => i, + _ => unreachable!(), + }] + ); + let stores = stores(&m, join); + assert_eq!(stores[0], [x, p]); + assert_eq!(stores[1][1], p); + m.write(); + } + + // ---- the passes against an interpreter, on random programs ---- + + /// Runs `m` on `inputs`: the stores it makes, in order (and how it + /// ended). Reads a value before its definition ran: a panic. + fn run(m: &Module, inputs: &[u32]) -> Vec<(String, Vec<u64>)> { + let mut vals: Vec<Option<u64>> = vec![None; m.insts.len()]; + let mut memory = [0u64; 16]; + let mut trace = Vec::new(); + let eval = |vals: &[Option<u64>], v: V| -> u64 { + match v { + V::Inst(i) => vals[i as usize].expect("a value defined before its use"), + V::Const(c) => { + match (&m.consts[c as usize].1, m.int_bits(m.consts[c as usize].0)) { + (Const::Int(x), Some(bits)) => *x as u64 & mask(bits), + (Const::Float(bits), _) => u64::from(*bits), + _ => 0, + } + } + _ => panic!("a global or function as a value"), + } + }; + let (mut b, mut from) = (0usize, usize::MAX); + for _ in 0..4000 { + let blk = &m.blocks[b]; + // Joins take their values together, before any is assigned. + let joined: Vec<(u32, u64)> = blk + .phis + .iter() + .map(|&p| { + let Op::Phi(incoming) = &m.insts[p as usize].op else { + panic!("a join") + }; + let v = incoming + .iter() + .find(|x| x.1 == from) + .expect("a value for the edge taken"); + (p, eval(&vals, v.0)) + }) + .collect(); + for (p, x) in joined { + vals[p as usize] = Some(x); + } + for &i in &blk.body { + let inst = &m.insts[i as usize]; + let bits = m.int_bits(inst.ty); + let float = |x: u64| f32::from_bits(x as u32); + let r = match &inst.op { + Op::Bin(op, x, y) => { + let (x, y) = (eval(&vals, *x), eval(&vals, *y)); + match bits { + Some(bits) => { + let r = match op { + Bin::Add => x.wrapping_add(y), + Bin::Sub => x.wrapping_sub(y), + Bin::Mul => x.wrapping_mul(y), + Bin::And => x & y, + Bin::Or => x | y, + Bin::Xor => x ^ y, + Bin::Shl => x << y, + Bin::LShr => x >> y, + Bin::AShr => (signed(bits, x) >> y) as u64, + _ => panic!("no divisions here"), + }; + r & mask(bits) + } + None => { + let (x, y) = (float(x), float(y)); + let r = match op { + Bin::Add => x + y, + Bin::Sub => x - y, + _ => x * y, + }; + u64::from(r.to_bits()) + } + } + } + Op::Cmp(p, x, y) => { + let wide = m.int_bits(m.type_of(*x)); + let (x, y) = (eval(&vals, *x), eval(&vals, *y)); + let holds = match wide { + Some(bits) => { + let (sx, sy) = (signed(bits, x), signed(bits, y)); + match *p { + pred::EQ => x == y, + pred::NE => x != y, + pred::IUGT => x > y, + pred::IUGE => x >= y, + pred::IULT => x < y, + pred::IULE => x <= y, + pred::SGT => sx > sy, + pred::SGE => sx >= sy, + pred::SLT => sx < sy, + _ => sx <= sy, + } + } + None => { + let (x, y) = (float(x), float(y)); + if x.is_nan() || y.is_nan() { + p & 8 != 0 + } else { + (p & 1 != 0 && x == y) + || (p & 2 != 0 && x > y) + || (p & 4 != 0 && x < y) + } + } + }; + u64::from(holds) + } + Op::Select(c, t, f) => { + if eval(&vals, *c) != 0 { + eval(&vals, *t) + } else { + eval(&vals, *f) + } + } + Op::Cast(op, x) => { + let from_bits = m.int_bits(m.type_of(*x)); + let x = eval(&vals, *x); + match (op, from_bits, bits) { + (Cast::Bitcast, _, _) => x, + (Cast::ZExt, _, _) => x, + (Cast::SExt, Some(f), Some(t)) => signed(f, x) as u64 & mask(t), + (Cast::Trunc, _, Some(t)) => x & mask(t), + _ => panic!("a cast the generator does not make"), + } + } + Op::Call(f, args) => { + let a: Vec<u64> = args.iter().map(|&v| eval(&vals, v)).collect(); + let name = m.funcs[*f as usize].name.as_str(); + match name { + "dx.op.loadInput.i32" => { + u64::from(inputs[(a[0] ^ a[1]) as usize % inputs.len()]) + } + "dx.op.binary.i32" => a[0].min(a[1]), + "dx.op.cbufferLoadLegacy.i32" => u64::from( + inputs[a[0] as usize % inputs.len()].rotate_left(a[1] as u32 & 31), + ), + "dx.op.bufferLoad.i32" => memory[(a[0] ^ a[1]) as usize % 16], + "dx.op.waveReadLaneFirst.i32" => a[0] ^ a[1], + _ => { + memory[a[0] as usize % 16] = a[1]; + trace.push((name.to_owned(), a)); + 0 + } + } + } + _ => panic!("an instruction the generator does not make"), + }; + vals[i as usize] = Some(r); + } + from = b; + b = match blk.term.expect("a terminator") { + Term::Ret => { + trace.push(("ret".into(), Vec::new())); + return trace; + } + Term::Br(t) => t, + Term::CondBr(c, t, f) => { + if eval(&vals, c) != 0 { + t + } else { + f + } + } + }; + } + trace.push(("still running".into(), Vec::new())); + trace + } + + /// A random structured program over a few registers, as the lowering + /// makes them: every register joined at every join, conditions tested + /// again behind their branch, values computed again. + struct Gen { + k: Kit, + rng: u64, + regs: Vec<V>, + conds: Vec<V>, + cur: usize, + input: V, + table: V, + wave: V, + /// The operands of the block's last read (to read the place again, + /// and to store to it). + last: Option<(V, V)>, + } + + impl Gen { + fn next(&mut self, n: u64) -> u64 { + self.rng ^= self.rng << 13; + self.rng ^= self.rng >> 7; + self.rng ^= self.rng << 17; + (self.rng >> 11) % n + } + + fn reg(&mut self) -> V { + let n = self.next(self.regs.len() as u64) as usize; + self.regs[n] + } + + /// A register or a small constant. + fn value(&mut self) -> V { + match self.next(4) { + 0 => { + let k = [0u32, 1, 2, 31, u32::MAX, 0x8000_0000, 7][self.next(7) as usize]; + self.k.m.i32(k) + } + _ => self.reg(), + } + } + + fn cond(&mut self) -> V { + let c = self.cur; + let made = match self.next(6) { + 0 if !self.conds.is_empty() => { + let n = self.next(self.conds.len() as u64) as usize; + return self.conds[n]; + } + 1 if self.conds.len() > 1 => { + let (a, b) = ( + self.next(self.conds.len() as u64), + self.next(self.conds.len() as u64), + ); + let op = [Bin::And, Bin::Or, Bin::Xor][self.next(3) as usize]; + self.k + .m + .bin(c, op, self.conds[a as usize], self.conds[b as usize]) + } + 2 if !self.conds.is_empty() => { + let n = self.next(self.conds.len() as u64) as usize; + let t = self.k.m.bool(true); + self.k.m.bin(c, Bin::Xor, self.conds[n], t) + } + _ => { + let p = pred::EQ + self.next(10) as u8; + let (x, y) = (self.reg(), self.value()); + self.k.m.cmp(c, p, x, y) + } + }; + self.conds.push(made); + made + } + + fn statement(&mut self) { + let c = self.cur; + let d = self.next(self.regs.len() as u64) as usize; + let i32t = self.k.m.int(32); + let f32t = self.k.m.float(); + let r = match self.next(14) { + 0..=3 => { + let op = [Bin::Add, Bin::Sub, Bin::Mul, Bin::And, Bin::Or, Bin::Xor] + [self.next(6) as usize]; + let (x, y) = (self.value(), self.value()); + self.k.m.bin(c, op, x, y) + } + 4 => { + let op = [Bin::Shl, Bin::LShr, Bin::AShr][self.next(3) as usize]; + let x = self.value(); + let by = self.next(32) as u32; + let by = self.k.m.i32(by); + self.k.m.bin(c, op, x, by) + } + 5 | 6 => { + // A guarded write: the old value where the guard fails. + let g = self.cond(); + let x = self.value(); + self.k.m.select(self.cur, g, x, self.regs[d]) + } + 7 => { + let (x, y) = (self.value(), self.value()); + let f = [self.k.pure, self.input, self.table, self.wave][self.next(4) as usize]; + self.k.m.call(c, f, vec![x, y]) + } + 8 | 9 => { + let again = self.next(2) == 0; + let (x, y) = match self.last { + Some(last) if again => last, + _ => (self.value(), self.value()), + }; + self.last = Some((x, y)); + self.k.m.call(c, self.k.reads, vec![x, y]) + } + 10 => { + // A store, half the time to the place read last. + let (mut x, y) = (self.value(), self.value()); + let there = self.next(2) == 0; + if let Some((a, b)) = self.last + && there + { + x = self.k.m.bin(c, Bin::Xor, a, b); + } + self.k.m.call(c, self.k.writes, vec![x, y]); + return; + } + 11 => { + // Float arithmetic, read back as bits. + let (x, y) = (self.value(), self.value()); + let (x, y) = ( + self.k.m.cast(c, Cast::Bitcast, x, f32t), + self.k.m.cast(c, Cast::Bitcast, y, f32t), + ); + let op = [Bin::Add, Bin::Sub, Bin::Mul][self.next(3) as usize]; + let f = self.k.m.bin(c, op, x, y); + if self.next(2) == 0 { + let p = self.next(16) as u8; + let t = self.k.m.cmp(c, p, f, y); + self.conds.push(t); + } + self.k.m.cast(c, Cast::Bitcast, f, i32t) + } + 12 => { + let g = self.cond(); + self.k.m.cast(self.cur, Cast::ZExt, g, i32t) + } + _ => { + let x = self.value(); + let f = self.k.m.cast(c, Cast::Bitcast, x, f32t); + self.k.m.cast(c, Cast::Bitcast, f, i32t) + } + }; + self.regs[d] = r; + } + + fn code(&mut self, depth: u32) { + for _ in 0..1 + self.next(6) { + match self.next(8) { + 0 | 1 if depth > 0 => self.branch(depth - 1), + 2 if depth > 0 => self.repeat(depth - 1), + _ => self.statement(), + } + } + } + + /// if / else, every register joined. + fn branch(&mut self, depth: u32) { + let c = self.cond(); + let i32t = self.k.m.int(32); + let (then, other, join) = ( + self.k.m.new_block(), + self.k.m.new_block(), + self.k.m.new_block(), + ); + self.k.m.terminate(self.cur, Term::CondBr(c, then, other)); + let (before, known) = (self.regs.clone(), self.conds.len()); + self.cur = then; + self.last = None; + self.code(depth); + let (then_regs, then_end) = (std::mem::replace(&mut self.regs, before), self.cur); + self.k.m.terminate(then_end, Term::Br(join)); + self.conds.truncate(known); + self.cur = other; + self.last = None; + if self.next(3) != 0 { + self.code(depth); + } + let other_end = self.cur; + self.k.m.terminate(other_end, Term::Br(join)); + self.conds.truncate(known); + for (r, &t) in then_regs.iter().enumerate() { + let p = self.k.m.phi(join, i32t); + self.k + .m + .set_phi(p, vec![(t, then_end), (self.regs[r], other_end)]); + self.regs[r] = p; + } + self.cur = join; + self.last = None; + } + + /// A loop that runs at most a few times, every register joined at + /// its head. + fn repeat(&mut self, depth: u32) { + let i32t = self.k.m.int(32); + let (head, exit) = (self.k.m.new_block(), self.k.m.new_block()); + let before = self.cur; + self.k.m.terminate(before, Term::Br(head)); + let entering = self.regs.clone(); + let joins: Vec<V> = (0..self.regs.len()) + .map(|_| self.k.m.phi(head, i32t)) + .collect(); + let count = self.k.m.phi(head, i32t); + self.regs = joins.clone(); + let known = self.conds.len(); + self.cur = head; + self.last = None; + self.code(depth); + let one = self.k.m.i32(1); + let next = self.k.m.bin(self.cur, Bin::Add, count, one); + let limit = 1 + self.next(3) as u32; + let limit = self.k.m.i32(limit); + let mut more = self.k.m.cmp(self.cur, pred::IULT, next, limit); + if self.next(2) == 0 { + let c = self.cond(); + more = self.k.m.bin(self.cur, Bin::And, more, c); + } + let latch = self.cur; + self.k.m.terminate(latch, Term::CondBr(more, head, exit)); + for (r, &p) in joins.iter().enumerate() { + self.k + .m + .set_phi(p, vec![(entering[r], before), (self.regs[r], latch)]); + } + let zero = self.k.m.i32(0); + self.k.m.set_phi(count, vec![(zero, before), (next, latch)]); + self.conds.truncate(known); + self.cur = exit; + self.last = None; + } + } + + fn random_program(seed: u64) -> Module { + let mut k = kit(); + let i32t = k.m.int(32); + let fty = k.m.func_ty(i32t, vec![i32t, i32t]); + let input = + k.m.function("dx.op.loadInput.i32", fty, Some(Attr::ReadNone), false); + let table = k.m.function( + "dx.op.cbufferLoadLegacy.i32", + fty, + Some(Attr::ReadOnly), + false, + ); + let wave = k.m.function( + "dx.op.waveReadLaneFirst.i32", + fty, + Some(Attr::NoUnwind), + false, + ); + let b = k.b; + let mut g = Gen { + k, + rng: seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1, + regs: Vec::new(), + conds: Vec::new(), + cur: b, + input, + table, + wave, + last: None, + }; + for r in 0..5 { + let (x, y) = (g.k.m.i32(r), g.k.m.i32(r * 3)); + let v = g.k.m.call(b, input, vec![x, y]); + g.regs.push(v); + } + g.code(3); + g.code(2); + // Every register is read at the end. + for r in 0..g.regs.len() { + let at = g.k.m.i32(r as u32); + g.k.m.call(g.cur, g.k.writes, vec![at, g.regs[r]]); + } + g.k.m.terminate(g.cur, Term::Ret); + g.k.m + } + + #[test] + fn every_pass_leaves_what_random_programs_store() { + let mut removed = 0; + for seed in 1..=400u64 { + let plain = random_program(seed); + let inputs: Vec<Vec<u32>> = (0..6u32) + .map(|n| { + (0..7u32) + .map(|i| match n { + 0 => 0, + 1 => i, + 2 => u32::MAX - i, + _ => { + (seed as u32 ^ n) + .wrapping_mul(0x9E37_79B9) + .rotate_left(i * 5) + ^ (i << 28) + } + }) + .collect() + }) + .collect(); + let expected: Vec<_> = inputs.iter().map(|i| run(&plain, i)).collect(); + let written: usize = plain + .blocks + .iter() + .map(|b| b.body.len() + b.phis.len()) + .sum(); + for passes in [ + DEAD, + FOLD, + REUSE, + FACTS, + LOADS, + FOLD | FACTS, + FOLD | REUSE | DEAD, + ALL, + ] { + let mut m = random_program(seed); + m.optimise(passes); + for (i, want) in inputs.iter().zip(&expected) { + assert_eq!(&run(&m, i), want, "seed {seed}, passes {passes}"); + } + if passes == ALL { + let left: usize = m.blocks.iter().map(|b| b.body.len() + b.phis.len()).sum(); + removed += written - left; + } + m.write(); + } + } + // The programs are of the wasteful kind: the passes find work. + assert!(removed > 4000, "{removed} instructions removed"); + } +} diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 8b05b12a08..3c346d9a62 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -44,6 +44,7 @@ impl SigElement { 18 => 68, 19 => 67, 20 => 69, + 28 => 23, // barycentrics 30 => 25, // cull primitive _ => 0, } @@ -114,10 +115,27 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> { out } +/// The most a mesh shader's outputs may take, in bytes (D3D12). +pub(crate) const MESH_OUTPUT_LIMIT: u64 = 32 * 1024; + +/// A mesh shader's output size as the DXIL validator measures it against +/// [`MESH_OUTPUT_LIMIT`]: 4 bytes per component of every vertex element +/// and primitive element, times the maxima rounded up to multiples of 32. +pub(crate) fn mesh_output_bytes( + vertex: &[SigElement], + primitive: &[SigElement], + max_vertices: u32, + max_primitives: u32, +) -> u64 { + let scalars = |els: &[SigElement]| els.iter().map(|e| u64::from(e.cols)).sum::<u64>(); + let align = |n: u32| u64::from(n).next_multiple_of(32); + 4 * (scalars(vertex) * align(max_vertices) + scalars(primitive) * align(max_primitives)) +} + /// A resource bound by register, as `PSV0` lists it. #[derive(Debug, Clone, Copy)] pub(crate) struct Binding { - /// PSV resource type: 1 sampler, 2 CBV. + /// PSV resource type: 1 sampler, 2 CBV, 4 raw SRV, 7 raw UAV. pub kind: u32, pub space: u32, pub register: u32, @@ -126,7 +144,7 @@ pub(crate) struct Binding { } pub(crate) struct Psv<'a> { - /// PSV shader kind: 0 pixel, 1 vertex, 5 compute. + /// PSV shader kind: 0 pixel, 1 vertex, 2 geometry, 5 compute. pub stage: u8, /// Vertex: writes `SV_Position`. Pixel: writes depth. pub flag: bool, @@ -136,6 +154,9 @@ pub(crate) struct Psv<'a> { pub prims: &'a [SigElement], /// Mesh: its state and the group-shared bytes it declares. pub mesh: Option<(super::shader::Mesh, u32)>, + /// Geometry (triangles in, triangle strips out on stream 0): its + /// maximum vertex count. `flag`: writes `SV_Position`. + pub geometry: Option<u32>, pub bindings: &'a [Binding], /// Compute: thread-group size and required wave size. pub threads: [u32; 3], @@ -189,6 +210,15 @@ pub(crate) fn psv(p: &Psv) -> Vec<u8> { info[27] = mesh.topology; info[30] = p.prims.len() as u8; } + if let Some(max_vertices) = p.geometry { + // Input primitive (3: triangles), output topology (5: triangle + // strips), stream mask, position written; the vertex maximum. + info[0..4].copy_from_slice(&3u32.to_le_bytes()); + info[4..8].copy_from_slice(&5u32.to_le_bytes()); + info[8..12].copy_from_slice(&1u32.to_le_bytes()); + info[12] = u8::from(p.flag); + info[26..28].copy_from_slice(&(max_vertices as u16).to_le_bytes()); + } out.extend(info); u32s(&mut out, &[p.bindings.len() as u32]); if !p.bindings.is_empty() { diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 1676c75015..97f5dc7ba3 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -142,7 +142,7 @@ const CASES: &[(&str, &str)] = &[ }"#, ), // 16-bit outputs and inputs (one value per dword with the 2020 - // compiler; Grand Theft Auto VI's two per dword cannot be compiled + // compiler; the title's two per dword cannot be compiled // here) and the front face. ( "16-bit varyings and front face", @@ -355,7 +355,7 @@ const CS_CASES: &[(&str, &str)] = &[ uint4(w * 7 + h, l + asuint(r), n * 5 + ns * 3 + st, b + raw.Load(4 * (i & 31)))); }"#, ), - // Typed loads (`tbuffer_load_format_*`, Grand Theft Auto VI's vertex + // Typed loads (`tbuffer_load_format_*`, the title's vertex // fetch) convert by the format the instruction names: the PC reads the // same bytes through typed views in those formats. Channels past the // format's read (0, 0, 0, 1); a byte format at unaligned offsets. @@ -588,7 +588,7 @@ const MS_CASES: &[(&str, u32, &str)] = &[ } }"#, ), - // Two waves per group, as Grand Theft Auto VI's mesh programs run: the + // Two waves per group, as the title's mesh programs run: the // second wave's lanes are threads 64-127. ( "two waves", @@ -606,7 +606,7 @@ const MS_CASES: &[(&str, u32, &str)] = &[ tris[i] = i & 1 ? uint3(c + 1, c + 10, c + 9) : uint3(c, c + 1, c + 9); }"#, ), - // Quad reads (DPP quad permutations on the console; Grand Theft Auto VI's + // Quad reads (DPP quad permutations on the console; the title's // tessellating mesh programs swizzle within quads too). ( "quad reads", @@ -743,9 +743,6 @@ fn user_data(s: &HostShader, k: &[u32; 4]) -> Vec<u32> { (RootType::Table, 3) => 5 * 32, // The typed views of `raw` (compute) from 9. (RootType::Table, 6) => 9 * 32, - // The bytes of the root CBV (slot 4) and SRV (slot 5) bound. - (RootType::Descriptor, 4) => 64 * 4, - (RootType::Descriptor, 5) => 32 * 4, other => panic!("unexpected user data {other:?}"), }; } @@ -1257,6 +1254,12 @@ fn translated_compute_matches_pc() { root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true))); root_views.sort_unstable(); for (n, (slot, srv)) in root_views.into_iter().enumerate() { + // (the table of view kinds of d16 typed accesses through tables: + // no integer views here) + if srv && slot == super::SLOT_TABLE_STRIDES { + roots.push((1 + n as u32, Root::View { srv, data: vec![0u32; 1024] })); + continue; + } assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); let data = if srv { root_srv.clone() @@ -1265,7 +1268,24 @@ fn translated_compute_matches_pc() { }; roots.push((1 + n as u32, Root::View { srv, data })); } - let ours = host.dispatch(&root_t, &pso_t, &dispatch(roots)); + // A buffer of halves the translated program moves as unsigned + // integers is shown to it as its unsigned twin, as the host does + // (`HostShader::half_views`); the PC program keeps the float view. + let twins: Vec<View> = views + .iter() + .map(|&v| match v { + View::HalfUav(n) if !cs_c.half_views.is_empty() => View::HalfUintUav(n), + v => v, + }) + .collect(); + let ours = host.dispatch( + &root_t, + &pso_t, + &Dispatch { + views: &twins, + ..dispatch(roots) + }, + ); if name.starts_with("terminates") { match ours { Ok(_) => eprintln!("{name}: finished"), diff --git a/crates/victory-shader/src/emit/dispatch_threads.rs b/crates/victory-shader/src/emit/dispatch_threads.rs new file mode 100644 index 0000000000..e1f4d9ce6c --- /dev/null +++ b/crates/victory-shader/src/emit/dispatch_threads.rs @@ -0,0 +1,99 @@ +//! Threads past a `DispatchX` thread count (after fork pull request #646, +//! mynzjerko). +//! +//! The console's `DispatchX(x, y, z, flags)` with bit 5 of its flags +//! (`COMPUTE_DISPATCH_INITIATOR.USE_THREAD_DIMENSIONS`, 0x20) counts +//! threads, not groups: the card runs the groups that hold them, and in the +//! last group of an axis the threads at or past the count are not in EXEC. +//! The ray-tracing structure builder's two box stages dispatch this way +//! (`28918b7150a7aad5`, `caa78b8ca62bc3d6`; 0x8020 on `4ddd6f9702fab2a7`, +//! `5062bc7a48e842f8`). Taken as groups they ran up to 64 times the threads +//! asked for and wrote nodes megabytes past the structure, over the title's +//! own objects: the title died seconds after the builder started (fork +//! testers on 32-lane cards, and our run 336). +//! +//! The host dispatches whole groups ([`super::super::shader::USER_DISPATCH_THREADS`] +//! gives the count per axis, 0 for whole groups); here the threads past it +//! leave at once where nothing makes them wait, else stay for the group's +//! barriers and the halves' exchange and do nothing that shows. + +use super::super::shader::USER_DISPATCH_THREADS; +use super::{Bin, Lower, Term, V, Val, Why, pred}; +use crate::native::RootType; + +impl<'a> Lower<'a> { + /// The guard of an instruction with an effect (a memory or LDS access, + /// a sample): [`Self::guard`], and within the `DispatchX` thread count + /// when the threads past it stay ([`Self::partial_active`]). + pub(super) fn effect_guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> { + let g = self.guard(b, i)?; + Ok(match (g, self.partial_active) { + (Some(g), Some(a)) => Some(self.s.m.bin(self.cur, Bin::And, g, a)), + (g, a) => g.or(a), + }) + } + + /// For a compute program with a spilled user-data table: whether this + /// thread lies within the `DispatchX` thread count of each axis whose + /// group is wider than one thread (`USER_DISPATCH_THREADS`, 0: no + /// count). Without a group barrier, a halves' exchange or a loop back to + /// the first block, the threads past it return from the entry block, so + /// EXEC, ballots and wave reductions see the console's lanes with no + /// guard on each instruction; else they stay and [`Self::partial_active`] + /// leaves them out of memory accesses, ballots and reductions. + pub(super) fn dispatch_threads_prologue(&mut self, order: &[usize]) { + let Some(threads) = self.s.threads else { + return; + }; + let e = self.s.entry; + let zero = self.s.m.i32(0); + let mut active: Option<V> = None; + for (c, &dim) in threads.iter().enumerate() { + if dim <= 1 { + continue; + } + let limit = self.host_word(RootType::Other(USER_DISPATCH_THREADS), 0, c as u32); + let Val::I32(tid) = self.thread_id(c as u8) else { + unreachable!() + }; + let Val::I32(gid) = self.compute_id("groupId.i32", 94, c as u8) else { + unreachable!() + }; + let g = self.s.m.i32(dim); + let base = self.s.m.bin(e, Bin::Mul, gid, g); + let global = self.s.m.bin(e, Bin::Add, base, tid); + let no_limit = self.s.m.cmp(e, pred::EQ, limit, zero); + let within = self.s.m.cmp(e, pred::IULT, global, limit); + let ok = self.s.m.bin(e, Bin::Or, no_limit, within); + active = Some(match active { + None => ok, + Some(prev) => self.s.m.bin(e, Bin::And, prev, ok), + }); + } + let Some(active) = active else { + return; + }; + let barrier = self.x.p.blocks.iter().enumerate().any(|(b, blk)| { + !self.no_barrier.contains(&b) && blk.insts.iter().any(|i| i.name() == "s_barrier") + }); + // (Not where the translation adds group barriers of its own: two host + // waves per console wave, `halves` or `split_lds`. Fork #646 checks the + // exchange and `s_barrier` only.) + let leave = self.exchange.is_none() + && self.halves.is_none() + && !self.split_lds + && !barrier + && self.x.p.blocks[order[0]].preds.is_empty(); + if leave { + let body = self.s.m.new_block(); + let exit = self.s.m.new_block(); + self.s.m.terminate(e, Term::CondBr(active, body, exit)); + self.s.m.terminate(exit, Term::Ret); + self.body_entry = body; + self.block[order[0]] = Some(body); + self.cur = body; + } else { + self.partial_active = Some(active); + } + } +} diff --git a/crates/victory-shader/src/emit/halves.rs b/crates/victory-shader/src/emit/halves.rs new file mode 100644 index 0000000000..adf296975b --- /dev/null +++ b/crates/victory-shader/src/emit/halves.rs @@ -0,0 +1,148 @@ +//! Typed buffer loads that move 16-bit halves without the d16 form: a +//! format load of whole dwords whose result the program reads only one +//! half of, as a half float, moves 16-bit integers, like a d16 access +//! ([`super::super::HostShader::half_views`]). + +use std::collections::HashSet; + +use super::{Fields, Inst, Lower, Operand, Reg, Role, RootType, Source, Value}; + +impl<'a> Lower<'a> { + /// Whether every use of `value`, a typed buffer load's result, reads + /// one 16-bit half of it as a half float: a `v_fma_mix*` source with + /// its `op_sel_hi` bit set, or `v_cvt_f32_f16`. A program that takes a + /// format load apart like that reads a 16-bit integer view on the + /// console (the load gives the zero-extended integer, whose bits are a + /// half; a float view's value it would not take apart). A use is a + /// read as an operand ([`crate::ir::operand_reads`]): a later write of + /// the register reads the value only to keep it in the lanes EXEC + /// leaves alone, and a phi carries it on, its own uses counting. False + /// without a use. + pub(super) fn read_only_as_halves(&self, value: Value) -> bool { + let p = self.x.p; + let mut used = false; + let mut seen = HashSet::from([value]); + let mut todo = vec![value]; + while let Some(value) = todo.pop() { + for b in &p.blocks { + for phi in b.phis.iter().filter(|phi| phi.args.contains(&value)) { + if seen.insert(phi.value) { + todo.push(phi.value); + } + } + for i in &b.insts { + if !i.reads.iter().any(|r| r.1 == value) { + continue; + } + let operands = crate::ir::operand_reads(p, i); + let regs: Vec<Reg> = i + .reads + .iter() + .filter(|r| r.1 == value && operands.contains(&r.0)) + .map(|r| r.0) + .collect(); + if regs.is_empty() { + continue; + } + used = true; + let Fields::Valu(v) = &i.fields else { + return false; + }; + match i.name() { + "v_cvt_f32_f16" => {} + "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { + let whole = v.src.iter().enumerate().any(|(k, op)| { + matches!(*op, Operand::Vector { reg, .. } if regs.contains(&Reg::V(reg))) + && v.opsel_hi >> k & 1 == 0 + }); + if whole { + return false; + } + } + _ => return false, + } + } + } + } + used + } + + /// Whether `inst` is a format load of whole dwords (not d16) whose + /// every channel is read only as halves ([`Self::read_only_as_halves`]). + pub(super) fn format_load_read_as_halves(&self, inst: &Inst) -> bool { + let Fields::Buffer { + data: Some(Operand::Vector { reg, .. }), + .. + } = inst.fields + else { + return false; + }; + let name = inst.name(); + let count = match name + .strip_prefix("buffer_load_format_") + .or(name.strip_prefix("tbuffer_load_format_")) + { + Some("x") => 1, + Some("xy") => 2, + Some("xyz") => 3, + Some("xyzw") => 4, + _ => return false, + }; + (0..count).all(|k| { + inst.write(Reg::V(reg + k)) + .is_some_and(|v| self.read_only_as_halves(v)) + }) + } + + /// The table places ([`Self::table_place`]) every access through which + /// moves halves: a d16 access, or a format load read only as halves + /// ([`Self::format_load_read_as_halves`]). A place the program reaches + /// otherwise too is left out (a format load of numbers beside one of + /// halves, a raw or scalar load, a descriptor chosen by control flow), + /// and so is every place of a table the program also picks from at run + /// time: what the program makes of such a view is not halves alone. + pub(super) fn places_read_as_halves(&self) -> std::collections::BTreeSet<(u8, u32)> { + let mut halves = std::collections::BTreeSet::new(); + let mut other = std::collections::BTreeSet::new(); + let mut picked = HashSet::new(); + for d in &self.x.res.descriptors { + if d.role == Role::Sampler { + continue; + } + let inst = self + .x + .p + .blocks + .get(d.site.0) + .and_then(|b| b.insts.get(d.site.1)); + let half = matches!(d.source, Source::Loaded { .. }) + && inst.is_some_and(|i| { + (i.name().starts_with("buffer_") && i.name().contains("_format_d16_")) + || self.format_load_read_as_halves(i) + }); + for leaf in d.source.leaves() { + let Source::Loaded { load, .. } = leaf else { + continue; + }; + let Some(a) = self.scalar.get(load) else { + continue; + }; + if a.dynamic.is_some() { + if let Some(rp) = self.x.native.layout.get(a.param) + && rp.root == RootType::Table + { + picked.insert(rp.slot); + } + } else if let Some(place) = self.table_place(leaf) { + if half { + halves.insert(place); + } else { + other.insert(place); + } + } + } + } + halves.retain(|p| !other.contains(p) && !picked.contains(&p.0)); + halves + } +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 32c63b36c2..f5e64dc822 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -62,69 +62,22 @@ fn err(e: windows::core::Error) -> String { e.message().to_string() } -fn pick_adapter(filter: Option<&str>) -> Result<IDXGIAdapter1, String> { - let needle = filter.map(|s| s.trim().to_ascii_lowercase()); - // SAFETY: plain DXGI enumeration and D3D12 capability probe. - unsafe { - let factory: IDXGIFactory4 = - CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; - let factory6 = factory.cast::<IDXGIFactory6>().ok(); - let mut i = 0u32; - loop { - let adapter: IDXGIAdapter1 = match &factory6 { - Some(f6) => { - match f6.EnumAdapterByGpuPreference(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE) { - Ok(a) => a, - Err(e) if e.code() == DXGI_ERROR_NOT_FOUND => break, - Err(e) => return Err(err(e)), - } - } - None => match factory.EnumAdapters1(i) { - Ok(a) => a, - Err(e) if e.code() == DXGI_ERROR_NOT_FOUND => break, - Err(e) => return Err(err(e)), - }, - }; - i += 1; - let desc = adapter.GetDesc1().map_err(err)?; - let is_sw = desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0; - if let Some(ref want) = needle { - let len = desc - .Description - .iter() - .position(|&c| c == 0) - .unwrap_or(desc.Description.len()); - let name = String::from_utf16_lossy(&desc.Description[..len]).to_ascii_lowercase(); - if !name.contains(want) { - continue; - } - } else if is_sw { - continue; - } - if D3D12CreateDevice( - &adapter, - D3D_FEATURE_LEVEL_12_0, - std::ptr::null_mut::<Option<ID3D12Device>>(), - ) - .is_ok() - { - return Ok(adapter); - } - } - Err(match filter { - Some(f) => format!("no D3D12 adapter matching VICTORY_ADAPTER={f:?}"), - None => "no hardware D3D12 adapter found".into(), - }) - } -} - impl Host { - /// The high-performance adapter (or `VICTORY_ADAPTER` substring match), or - /// WARP with `warp` (or `VICTORY_WARP=1`). + /// The default adapter, or WARP with `warp` (or `VICTORY_WARP=1`). pub fn new(warp: bool) -> Result<Self, String> { let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1"); // SAFETY: plain D3D12/DXGI calls with valid out pointers. unsafe { + // `VICTORY_D3D12_DEBUG`: the debug layer, whose messages a + // refused pipeline's error then carries. + if std::env::var_os("VICTORY_D3D12_DEBUG").is_some() { + let mut debug: Option<ID3D12Debug> = None; + if D3D12GetDebugInterface(&mut debug).is_ok() + && let Some(debug) = debug + { + debug.EnableDebugLayer(); + } + } let mut device: Option<ID3D12Device> = None; if warp { let factory: IDXGIFactory4 = @@ -132,18 +85,20 @@ impl Host { let adapter: IDXGIAdapter = factory.EnumWarpAdapter().map_err(err)?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; } else { - let filter = std::env::var("VICTORY_ADAPTER") - .ok() - .filter(|s| !s.trim().is_empty()); - match pick_adapter(filter.as_deref()) { - Ok(adapter) => { - D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device) - .map_err(err)?; - } - Err(e) if filter.is_some() => return Err(e), - Err(_) => { - D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device) - .map_err(err)?; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; + // A machine without a graphics card gives the software + // adapter as its default device (a hosted test runner, + // whose first adapter is a display stub that cannot make a + // device): that is no hardware device, and the tests that + // ask for one skip it, as they do where there is none. + if let Some(made) = &device { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; + if let Ok(adapter) = factory.EnumAdapterByLuid::<IDXGIAdapter1>(made.GetAdapterLuid()) + && let Ok(desc) = adapter.GetDesc1() + && (desc.Flags & 2 != 0 || (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)) + { + return Err("the default device is the software adapter".to_owned()); } } } @@ -202,21 +157,23 @@ impl Host { ShaderVisibility: vis, }) .collect(); - let mut views: Vec<(u8, bool)> = stages + // By slot, then kind: 0 CBV, 1 SRV, 2 UAV. + let mut views: Vec<(u8, u8)> = stages .iter() .flat_map(|(s, _)| { - let cbvs = s.root_cbvs.iter().map(|&r| (r, false)); - cbvs.chain(s.root_srvs.iter().map(|&r| (r, true))) + let cbvs = s.root_cbvs.iter().map(|&r| (r, 0)); + let srvs = s.root_srvs.iter().map(|&r| (r, 1)); + cbvs.chain(srvs).chain(s.root_uavs.iter().map(|&r| (r, 2))) }) .collect(); views.sort_unstable(); views.dedup(); - for (slot, srv) in views { + for (slot, kind) in views { params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: if srv { - D3D12_ROOT_PARAMETER_TYPE_SRV - } else { - D3D12_ROOT_PARAMETER_TYPE_CBV + ParameterType: match kind { + 1 => D3D12_ROOT_PARAMETER_TYPE_SRV, + 2 => D3D12_ROOT_PARAMETER_TYPE_UAV, + _ => D3D12_ROOT_PARAMETER_TYPE_CBV, }, Anonymous: D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { @@ -228,12 +185,24 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + // SAFETY: the feature query writes the structure of the given size. + // Older runtimes may not recognize OPTIONS19; that means no support. + let aniso_point_mip_supported = unsafe { + self.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS19, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_ok() + && options.AnisoFilterWithPointMipSupported.as_bool(); let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { let [u, v, w] = d.address.map(|a| D3D12_TEXTURE_ADDRESS_MODE(a as i32)); samplers.push(D3D12_STATIC_SAMPLER_DESC { - Filter: D3D12_FILTER(d.filter as i32), + Filter: D3D12_FILTER(d.filter_for_host(aniso_point_mip_supported) as i32), AddressU: u, AddressV: v, AddressW: w, @@ -303,7 +272,34 @@ impl Host { ..Default::default() }; // SAFETY: the description points at live data. - unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(err) + unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(|e| self.explained(e)) + } + + /// The error with the debug layer's messages since the last call, if + /// the layer is on (`VICTORY_D3D12_DEBUG`). + fn explained(&self, e: windows::core::Error) -> String { + let mut text = err(e); + let Ok(queue) = self.device.cast::<ID3D12InfoQueue>() else { + return text; + }; + // SAFETY: each message is read into a buffer of the size the queue + // asks for, aligned for the message header. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut len = 0usize; + let _ = queue.GetMessage(i, None, &mut len); + let mut buffer = vec![0u64; len.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>(); + if queue.GetMessage(i, Some(message), &mut len).is_ok() { + let m = &*message; + let bytes = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength.saturating_sub(1)); + text.push_str(" | "); + text.push_str(&String::from_utf8_lossy(bytes)); + } + } + queue.ClearStoredMessages(); + } + text } /// A graphics pipeline from a vertex and a pixel shader, with float or @@ -325,6 +321,18 @@ impl Host { root: &ID3D12RootSignature, vs: &[u8], ps: &[u8], + ) -> Result<ID3D12PipelineState, String> { + self.pipeline_with_gs(root, vs, None, ps) + } + + /// As [`Host::pipeline_with`], with a geometry shader between the two + /// (the rectangle stage, `rect_list_gs`). + pub fn pipeline_with_gs( + &self, + root: &ID3D12RootSignature, + vs: &[u8], + gs: Option<&[u8]>, + ps: &[u8], ) -> Result<ID3D12PipelineState, String> { let inputs = sig(vs, FourCC::ISG1)?; let names: Vec<CString> = inputs @@ -357,6 +365,10 @@ impl Host { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len(), }, + GS: gs.map_or(D3D12_SHADER_BYTECODE::default(), |gs| D3D12_SHADER_BYTECODE { + pShaderBytecode: gs.as_ptr().cast(), + BytecodeLength: gs.len(), + }), SampleMask: u32::MAX, RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, @@ -598,6 +610,9 @@ fn stub(pixel: bool, outputs: Vec<SigElement>) -> HostShader { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), } } @@ -977,6 +992,7 @@ fn transition( /// A view in the heap for [`Host::dispatch`]. #[cfg(test)] +#[derive(Clone, Copy)] pub enum View<'a> { /// An RGBA32F texture SRV (width, height, texels). Texture(u32, u32, &'a [[f32; 4]]), @@ -990,6 +1006,9 @@ pub enum View<'a> { UintTextureUav(u32, u32), /// A typed RGBA16F buffer UAV of this many elements, zeroed. HalfUav(u32), + /// The same buffer viewed as R16G16B16A16_UINT: what a translated + /// program that moves halves is shown ([`super::HostShader::half_views`]). + HalfUintUav(u32), /// A constant buffer of these dwords. Cbv(&'a [u32]), /// A buffer SRV over these dwords. @@ -1222,7 +1241,7 @@ impl Host { ); keep.push(tex); } - View::RawUav(_) | View::HalfUav(_) => { + View::RawUav(_) | View::HalfUav(_) | View::HalfUintUav(_) => { // (dwords, format, elements, flags) let (n, format, elements, flags) = match *v { View::HalfUav(e) => ( @@ -1231,6 +1250,12 @@ impl Host { e, D3D12_BUFFER_UAV_FLAG_NONE, ), + View::HalfUintUav(e) => ( + 2 * e, + DXGI_FORMAT_R16G16B16A16_UINT, + e, + D3D12_BUFFER_UAV_FLAG_NONE, + ), View::RawUav(n) => { (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) } diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs new file mode 100644 index 0000000000..a30eb0d9c8 --- /dev/null +++ b/crates/victory-shader/src/emit/intersect.rs @@ -0,0 +1,638 @@ +//! The console's ray-tracing node test, `image_bvh_intersect_ray` and +//! `image_bvh64_intersect_ray`, as inline DXIL: the host has no instruction +//! that tests one ray against one node of the title's own structures. +//! +//! [`crate::bvh`] says what the instruction computes and is the reference: +//! the code made here does the same float operations in the same order +//! (DXIL float operations carry no fast-math flags, so the host may not +//! reorder or fuse them), and the tests in `intersect_tests.rs` run it on +//! the card against the reference. +//! +//! The title's nodes are in title memory, named by address: they are read +//! through the host's copies of title memory ([`Lower::memory`]), one look +//! in its directory per node (two for a 128-byte box node). +//! +//! Shape of the code, under the instruction's lane guard: +//! +//! ```text +//! kind = pointer & 7 +//! box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4); +//! four slab tests; the sorting network +//! triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test +//! other (6, 7): a triangle miss +//! ``` +//! +//! Each lane reads only the dwords its node's kind needs: 28 for a 32-bit +//! box node, 16 for a 16-bit one, 10 for a triangle. + +use super::{Attr, Bin, Fields, Inst, Lower, Operand, Reg, Term, V, Why, flags, pred}; +use crate::bvh; +use crate::resource::BvhNodes; + +#[cfg(test)] +thread_local! { + /// The tests' stand-in for title memory ([`Lower::bvh_memory`]): a + /// heap slot holding a raw buffer, and the title address of its first + /// byte. (The card tests have no host to keep copies of title memory + /// and their directory.) + pub(in crate::emit) static TEST_MEMORY: std::cell::Cell<Option<(u32, u64)>> = + const { std::cell::Cell::new(None) }; + /// The tests' way to translate as with `VICTORY_BVH_NO_HIT=1` + /// ([`no_hit`]). + pub(in crate::emit) static TEST_NO_HIT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// Whether a node test answers "no hit" and reads nothing +/// (`VICTORY_BVH_NO_HIT=1`; off by default; never with +/// `VICTORY_BVH_BUILDER=1`, which has the structures built). +/// +/// The title's structure builder does not run in the layer unless asked +/// for, and the title's ray-traced passes run all the same: each node test +/// then reads whatever bytes lie where a structure would be, in a walk the +/// title bounds at 65,535 steps a wave. What comes back is not the scene: +/// it differs from launch to launch, and how long a pass runs depends on +/// those bytes. With the switch a box node enters no child and any other +/// node is missed, as in a scene with nothing in it: every ray leaves at +/// its first test, shadow rays find no occluder, and the answer is the same +/// in every run. (The idea is fork pull request #994's, which asks a host +/// word at run time; here it is a translation, since the builder's state +/// does not change during a run of ours.) +fn no_hit() -> bool { + #[cfg(test)] + if TEST_NO_HIT.get() { + return true; + } + std::env::var_os("VICTORY_BVH_NO_HIT").is_some_and(|v| v == "1") + && std::env::var_os("VICTORY_BVH_BUILDER").is_none_or(|v| v != "1") +} + +/// Where the instruction's node is. +#[derive(Clone, Copy)] +enum NodeAt { + /// At this byte of a raw buffer of the host. + Buffer { handle: V, byte: V }, + /// In title memory: the raw view of the host copy holding the node's + /// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]), + /// and the node's address, for the second half of a 128-byte node. + Memory { handle: V, byte: V, low: V, high: V }, +} + +/// The ray operands, as floats. +struct Ray { + extent: V, + origin: [V; 3], + direction: [V; 3], + inverse: [V; 3], +} + +/// Skip ray tracing (Try 4.2, idea 3, after the mods that turn a game's +/// ray tracing off): with `VICTORY_SKIP_RT=1` every ray-tracing node test +/// misses at once ([`Lower::bvh_miss`]). The console's structure builder +/// does not run here (`VICTORY_BVH_BUILDER`), so the title's rays walked +/// memory that holds no structure: work for the card that gave garbage +/// (black shadows, overbright lighting). A ray that misses everything +/// ends at its first node: no shadow from it, and the title's own +/// fallback for a miss (the sky, no occluder). It also lets the trace +/// programs translate whatever their structure's descriptor says. +fn skip_rays() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SKIP_RT").is_some_and(|v| v == "1")) +} + +impl<'a> Lower<'a> { + /// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`. + pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Image { + data, + addr, + rsrc, + dmask, + a16, + d16, + tfe, + lwe, + .. + } = &inst.fields + else { + unreachable!() + }; + if *a16 || *d16 || *tfe || *lwe || *dmask != 0xf { + return Err("a ray-tracing node test with 16-bit operands or a partial result"); + } + let wide = inst.name() == "image_bvh64_intersect_ray"; + // Operand VGPRs in order: the node pointer (two dwords in the + // 64-bit form), the ray's extent, origin, direction and inverse + // direction. + let mut regs = Vec::new(); + for a in addr { + if let Operand::Vector { reg, dwords } = *a { + regs.extend((0..dwords).map(|k| reg + k)); + } + } + if regs.len() != if wide { 12 } else { 11 } { + return Err("a ray-tracing node test's operands"); + } + let Operand::Vector { reg: dst, .. } = *data else { + return Err("a ray-tracing node test's result"); + }; + if skip_rays() { + return self.bvh_miss(inst, regs[0], dst, b, i); + } + let site = (b, i); + let nodes = self + .x + .res + .bvh + .iter() + .find(|n| n.0 == site) + .map(|n| n.1) + .ok_or("an untracked ray-tracing structure")?; + let (sort, barycentrics) = match nodes { + BvhNodes::Resource => (true, true), + BvhNodes::Memory { word1, word3 } => ( + word1 & bvh::BOX_SORT != 0, + word3 & bvh::RETURN_BARYCENTRICS != 0, + ), + }; + if !barycentrics { + // Mode 0 returns a triangle id and a hit status in the last two + // dwords; no program of the title asks for it. + return Err("a ray-tracing structure that returns triangle ids"); + } + let guard = self.guard(b, i)?; + let mut x = Vec::with_capacity(regs.len()); + for &r in ®s { + let v = inst.read(Reg::V(r)).ok_or("an unread operand")?; + x.push(self.i32_of(v)?); + } + let pointer = x[0]; + let pointer_high = wide.then(|| x[1]); + let f: Vec<V> = x[1 + usize::from(wide)..] + .iter() + .map(|&v| self.as_float(v)) + .collect(); + let ray = Ray { + extent: f[0], + origin: [f[1], f[2], f[3]], + direction: [f[4], f[5], f[6]], + inverse: [f[7], f[8], f[9]], + }; + let c = self.cur; + if no_hit() { + // No structures: a box enters no child, anything else is + // missed ([`no_hit`]). Nothing is read, and nothing asked of + // the directory of title memory. + let _ = &ray; + let (k4, k6) = (self.s.m.i32(4), self.s.m.i32(6)); + let pair = self.s.m.bin(c, Bin::And, pointer, k6); + let is_box = self.s.m.cmp(c, pred::EQ, pair, k4); + let none = self.s.m.i32(bvh::NONE); + for (k, miss) in bvh::MISS.into_iter().enumerate() { + let miss = self.s.m.i32(miss.to_bits()); + let r = self.s.m.select(c, is_box, none, miss); + self.write(inst, Reg::V(dst + k as u8), r, guard); + } + return Ok(()); + } + let at = match nodes { + BvhNodes::Resource => { + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked ray-tracing structure")?; + let handle = self.handle(site, src, false, (11, 0))?; + // (pointer >> 3) << 6 from the buffer's start. + let (kind_bits, k3) = (self.s.m.i32(!7), self.s.m.i32(3)); + let byte = self.s.m.bin(c, Bin::And, pointer, kind_bits); + let byte = self.s.m.bin(c, Bin::Shl, byte, k3); + NodeAt::Buffer { handle, byte } + } + BvhNodes::Memory { .. } => { + let Operand::Scalar { code, .. } = *rsrc else { + return Err("a ray-tracing structure descriptor not in SGPRs"); + }; + let mut words = [pointer; 2]; + for (k, w) in words.iter_mut().enumerate() { + let v = inst + .read(Reg::S(code + k as u8)) + .ok_or("an unread operand")?; + *w = self.i32_of(v)?; + } + let (low, high) = self.bvh_address(words[0], words[1], pointer, pointer_high); + // One look for the node's copy, before the branches: a + // node is 64 bytes on 64, so its first half lies in one + // 64 KiB page whatever its kind. + let (handle, byte) = self.bvh_memory(low, high, guard); + NodeAt::Memory { + handle, + byte, + low, + high, + } + } + }; + let zero = self.s.m.i32(0); + let gate = self.begin_guarded(guard); + let head = self.cur; + let (k4, k6, k7) = (self.s.m.i32(4), self.s.m.i32(6), self.s.m.i32(7)); + let kind = self.s.m.bin(head, Bin::And, pointer, k7); + let pair = self.s.m.bin(head, Bin::And, pointer, k6); + let is_box = self.s.m.cmp(head, pred::EQ, pair, k4); + let is_triangle = self.s.m.cmp(head, pred::IULT, kind, k4); + let (box_block, leaf_block) = (self.s.m.new_block(), self.s.m.new_block()); + let (triangle_block, join) = (self.s.m.new_block(), self.s.m.new_block()); + self.s + .m + .terminate(head, Term::CondBr(is_box, box_block, leaf_block)); + self.s + .m + .terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join)); + self.cur = box_block; + let boxes = self.bvh_boxes(at, kind, &ray, sort); + let box_end = self.cur; + self.s.m.terminate(box_end, Term::Br(join)); + self.cur = triangle_block; + let triangle = self.bvh_triangle(at, kind, &ray); + let triangle_end = self.cur; + self.s.m.terminate(triangle_end, Term::Br(join)); + self.cur = join; + // Kinds 6 and 7 (an instance, a procedural primitive): not known + // what the console returns; the title's programs do not read it. + let other = bvh::MISS.map(|f| self.s.m.i32(f.to_bits())); + let i32t = self.s.t.i32; + let mut results = Vec::with_capacity(4); + for k in 0..4 { + let phi = self.s.m.phi(join, i32t); + self.s.m.set_phi( + phi, + vec![ + (boxes[k], box_end), + (triangle[k], triangle_end), + (other[k], leaf_block), + ], + ); + results.push((phi, zero)); + } + let results = self.end_guarded(gate, &results); + for (k, &r) in results.iter().enumerate() { + self.write(inst, Reg::V(dst + k as u8), r, guard); + } + Ok(()) + } + + /// [`skip_rays`]: every node test misses at once, read from nothing: + /// a box node returns no child ([`bvh::NONE`] four times), any other + /// node a triangle miss ([`bvh::MISS`]). The node's kind is in its + /// pointer's low bits, so nothing of the structure is read. + fn bvh_miss(&mut self, inst: &Inst, pointer: u8, dst: u8, b: usize, i: usize) -> Result<(), Why> { + let guard = self.guard(b, i)?; + let v = inst.read(Reg::V(pointer)).ok_or("an unread operand")?; + let pointer = self.i32_of(v)?; + let c = self.cur; + let (k4, k6) = (self.s.m.i32(4), self.s.m.i32(6)); + let pair = self.s.m.bin(c, Bin::And, pointer, k6); + let is_box = self.s.m.cmp(c, pred::EQ, pair, k4); + let none = self.s.m.i32(bvh::NONE); + for (k, miss) in bvh::MISS.iter().enumerate() { + let miss = self.s.m.i32(miss.to_bits()); + let r = self.s.m.select(c, is_box, none, miss); + self.write(inst, Reg::V(dst + k as u8), r, guard); + } + Ok(()) + } + + /// Title memory at `low`/`high` for a node's bytes: the raw view of the + /// host copy holding the address and the byte in that view + /// ([`Lower::memory`]: a page the host has no copy of reads zeros and + /// is left for the host to fetch, for lanes that run). + fn bvh_memory(&mut self, low: V, high: V, guard: Option<V>) -> (V, V) { + #[cfg(test)] + if let Some((slot, base)) = TEST_MEMORY.get() { + // The buffer at heap slot `slot` holds the bytes from title + // address `base` on; any other address reads past its end, + // which is zeros. + let c = self.cur; + let slot = self.s.m.i32(slot); + let handle = self.s.heap_handle(c, slot, false, false, (11, 0)); + let (base_low, base_high) = + (self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32)); + let at = self.s.m.bin(c, Bin::Sub, low, base_low); + let in_low = self.s.m.cmp(c, pred::IUGE, low, base_low); + let in_high = self.s.m.cmp(c, pred::EQ, high, base_high); + let inside = self.s.m.bin(c, Bin::And, in_low, in_high); + let outside = self.s.m.i32(0xffff_ff00); + let at = self.s.m.select(c, inside, at, outside); + return (handle, at); + } + self.memory(low, high, guard) + } + + /// `count` dwords of the node from its byte `base` + `offset` (`base` + /// computed, `offset` fixed; none of the node's bytes past 127), read + /// four at a time. + fn bvh_node_words(&mut self, at: NodeAt, base: Option<V>, offset: u32, count: u32) -> Vec<V> { + let c = self.cur; + let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + // The second half of a 128-byte node may lie in the next 64 KiB + // page, which may be in another copy: its own look, made once. + let mut second = None; + let mut out = Vec::with_capacity(count as usize); + for start in (0..count).step_by(4) { + let n = (count - start).min(4); + let node_byte = offset + 4 * start; + let (handle, mut byte) = match at { + NodeAt::Buffer { handle, byte } => (handle, byte), + NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte), + NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| { + let (low, high) = self.address_plus(low, high, 64); + // Every lane in this block runs the instruction. + let (handle, byte) = self.bvh_memory(low, high, None); + let k64 = self.s.m.i32(64); + (handle, self.s.m.bin(c, Bin::Sub, byte, k64)) + }), + }; + if let Some(b) = base { + byte = self.s.m.bin(c, Bin::Add, byte, b); + } + let k = self.s.m.i32(node_byte); + let byte = self.s.m.bin(c, Bin::Add, byte, k); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[handle, byte, undef, mask, align], + ); + for k in 0..n { + let f = self.s.m.extract(c, r, k); + out.push(self.as_int(f)); + } + } + out + } + + /// The node's title address, [`bvh::node_address`]: the descriptor's + /// base (dword 0 and the low byte of dword 1, in 256-byte units) plus + /// `(pointer >> 3) << 6`. + fn bvh_address(&mut self, word0: V, word1: V, pointer: V, pointer_high: Option<V>) -> (V, V) { + let c = self.cur; + let i64t = self.s.m.int(64); + let (zero, byte) = (self.s.m.i32(0), self.s.m.i32(0xff)); + let base_high = self.s.m.bin(c, Bin::And, word1, byte); + let base = self.join64(word0, base_high); + let k8 = self.s.m.int_const(i64t, 8); + let base = self.s.m.bin(c, Bin::Shl, base, k8); + let p = self.join64(pointer, pointer_high.unwrap_or(zero)); + let (k3, k6) = (self.s.m.int_const(i64t, 3), self.s.m.int_const(i64t, 6)); + let p = self.s.m.bin(c, Bin::LShr, p, k3); + let p = self.s.m.bin(c, Bin::Shl, p, k6); + let a = self.s.m.bin(c, Bin::Add, base, p); + self.s.flags |= flags::INT64; + self.split64(a) + } + + /// The box test ([`bvh::boxes`]): four result dwords. Starts in the + /// current block and leaves `self.cur` at the block it ends in. + fn bvh_boxes(&mut self, at: NodeAt, kind: V, ray: &Ray, sort: bool) -> [V; 4] { + let head = self.cur; + let children = self.bvh_node_words(at, None, 0, 4); + let k5 = self.s.m.i32(5); + let wide = self.s.m.cmp(head, pred::EQ, kind, k5); + let (wide_block, half_block) = (self.s.m.new_block(), self.s.m.new_block()); + let join = self.s.m.new_block(); + self.s + .m + .terminate(head, Term::CondBr(wide, wide_block, half_block)); + // 32-bit floats: 24 dwords from byte 16. + self.cur = wide_block; + let k16 = self.s.m.i32(16); + let words = self.bvh_node_words(at, None, 16, 24); + let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect(); + self.s.m.terminate(wide_block, Term::Br(join)); + // 16-bit floats: 24 halves in 12 dwords from byte 16, the low half + // of a dword first. + self.cur = half_block; + let words = self.bvh_node_words(at, None, 16, 12); + let f32t = self.s.t.f32; + let mut halves = Vec::with_capacity(24); + for n in 0..24 { + let mut h = words[n / 2]; + if n % 2 == 1 { + h = self.s.m.bin(half_block, Bin::LShr, h, k16); + } + // The conversion reads the low 16 bits. + halves.push(self.s.op( + half_block, + "legacyF16ToF32", + Attr::ReadNone, + f32t, + 131, + &[h], + )); + } + self.s.m.terminate(half_block, Term::Br(join)); + self.cur = join; + let mut coords = Vec::with_capacity(24); + for n in 0..24 { + let phi = self.s.m.phi(join, f32t); + self.s + .m + .set_phi(phi, vec![(floats[n], wide_block), (halves[n], half_block)]); + coords.push(phi); + } + // The inverse direction held finite ([`bvh::boxes`]). + let (most, least) = ( + self.s.m.f32(f32::MAX.to_bits()), + self.s.m.f32((-f32::MAX).to_bits()), + ); + let inverse = ray.inverse.map(|x| { + let x = self.binary(35, x, least); + self.binary(36, x, most) + }); + let c = join; + let (none, infinity, fzero) = ( + self.s.m.i32(bvh::NONE), + self.s.m.f32(f32::INFINITY.to_bits()), + self.s.m.f32(0), + ); + let mut ids = [none; 4]; + let mut distances = [infinity; 4]; + for n in 0..4 { + let bx = &coords[6 * n..6 * n + 6]; + let (mut near, mut far) = ([fzero; 3], [fzero; 3]); + for a in 0..3 { + let low = self.s.m.bin(c, Bin::Sub, bx[a], ray.origin[a]); + let low = self.s.m.bin(c, Bin::Mul, low, inverse[a]); + let high = self.s.m.bin(c, Bin::Sub, bx[3 + a], ray.origin[a]); + let high = self.s.m.bin(c, Bin::Mul, high, inverse[a]); + near[a] = self.binary(36, low, high); + far[a] = self.binary(35, low, high); + } + let enter = self.binary(35, near[0], near[1]); + let enter = self.binary(35, enter, near[2]); + let leave = self.binary(36, far[0], far[1]); + let leave = self.binary(36, leave, far[2]); + let from = self.binary(35, enter, fzero); + // Ordered compares: a NaN anywhere is a miss. + let through = self.s.m.cmp(c, pred::OGE, leave, from); + let before = self.s.m.cmp(c, pred::OLT, enter, ray.extent); + let off = self.is_nan_f32(bx[0]); + let on = self.s.m.bool(true); + let on = self.s.m.bin(c, Bin::Xor, off, on); + let hit = self.s.m.bin(c, Bin::And, through, before); + let hit = self.s.m.bin(c, Bin::And, hit, on); + ids[n] = self.s.m.select(c, hit, children[n], none); + distances[n] = self.s.m.select(c, hit, enter, infinity); + } + if sort { + for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] { + let swap = self.s.m.cmp(c, pred::OLT, distances[b], distances[a]); + let (da, db) = (distances[a], distances[b]); + distances[a] = self.s.m.select(c, swap, db, da); + distances[b] = self.s.m.select(c, swap, da, db); + let (ia, ib) = (ids[a], ids[b]); + ids[a] = self.s.m.select(c, swap, ib, ia); + ids[b] = self.s.m.select(c, swap, ia, ib); + } + } + ids + } + + /// The triangle test ([`bvh::triangle`] of [`bvh::triangle_vertices`]): + /// four result dwords, made in the current block. + fn bvh_triangle(&mut self, at: NodeAt, kind: V, ray: &Ray) -> [V; 4] { + let c = self.cur; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + // The triangle's byte of the dword at byte 60: which of its + // vertices barycentric I and J weigh. + let id = self.bvh_node_words(at, None, 60, 1)[0]; + let (k2, k3, k12, k15) = (k(self, 2), k(self, 3), k(self, 12), k(self, 15)); + let shift = self.s.m.bin(c, Bin::Shl, kind, k3); + let id = self.s.m.bin(c, Bin::LShr, id, shift); + let i = self.s.m.bin(c, Bin::And, id, k3); + let j = self.s.m.bin(c, Bin::LShr, id, k2); + let j = self.s.m.bin(c, Bin::And, j, k3); + let first = self.s.m.bin(c, Bin::Sub, k3, i); + let first = self.s.m.bin(c, Bin::Sub, first, j); + let first = self.s.m.bin(c, Bin::And, first, k3); + // The node's vertices the triangle is made of, four bits each. + let (k0, k1) = (k(self, 0), k(self, 1)); + let maps: [V; 4] = std::array::from_fn(|n| k(self, bvh::vertex_map(n as u32))); + let (is0, is1, is2) = ( + self.s.m.cmp(c, pred::EQ, kind, k0), + self.s.m.cmp(c, pred::EQ, kind, k1), + self.s.m.cmp(c, pred::EQ, kind, k2), + ); + let map = self.s.m.select(c, is2, maps[2], maps[3]); + let map = self.s.m.select(c, is1, maps[1], map); + let map = self.s.m.select(c, is0, maps[0], map); + let mut p = Vec::with_capacity(3); + for n in [first, i, j] { + let nibble = self.s.m.bin(c, Bin::Shl, n, k2); + let vertex = self.s.m.bin(c, Bin::LShr, map, nibble); + let vertex = self.s.m.bin(c, Bin::And, vertex, k15); + let byte = self.s.m.bin(c, Bin::Mul, vertex, k12); + let words = self.bvh_node_words(at, Some(byte), 0, 3); + // Relative to the ray's origin. + let r: Vec<V> = (0..3) + .map(|a| { + let f = self.as_float(words[a]); + self.s.m.bin(c, Bin::Sub, f, ray.origin[a]) + }) + .collect(); + p.push([r[0], r[1], r[2]]); + } + // The ray's largest axis z, and x and y after it in an order that + // keeps the winding. + let fzero = self.s.m.f32(0); + let size = ray.direction.map(|d| self.unary(6, d)); + let xy = self.s.m.cmp(c, pred::OGE, size[0], size[1]); + let xz = self.s.m.cmp(c, pred::OGE, size[0], size[2]); + let yz = self.s.m.cmp(c, pred::OGE, size[1], size[2]); + let z0 = self.s.m.bin(c, Bin::And, xy, xz); + let on = self.s.m.bool(true); + let not_xy = self.s.m.bin(c, Bin::Xor, xy, on); + let z1 = self.s.m.bin(c, Bin::And, not_xy, yz); + // Component (kz + n) % 3 of `q`. + let pick = |l: &mut Self, q: [V; 3], n: usize| { + let rest = l.s.m.select(c, z1, q[(1 + n) % 3], q[(2 + n) % 3]); + l.s.m.select(c, z0, q[n % 3], rest) + }; + let dz = pick(self, ray.direction, 0); + let backwards = self.s.m.cmp(c, pred::OLT, dz, fzero); + // (x, y, z) of `q`: the two after the largest axis, swapped for a + // ray that runs backwards along it. + let axes = |l: &mut Self, q: [V; 3]| { + let (x, y) = (pick(l, q, 1), pick(l, q, 2)); + [ + l.s.m.select(c, backwards, y, x), + l.s.m.select(c, backwards, x, y), + pick(l, q, 0), + ] + }; + let d = axes(self, ray.direction); + let sz = pick(self, ray.inverse, 0); + let sx = self.s.m.bin(c, Bin::Mul, d[0], sz); + let sy = self.s.m.bin(c, Bin::Mul, d[1], sz); + let mut sheared = Vec::with_capacity(3); + for r in p { + let r = axes(self, r); + let x = self.s.m.bin(c, Bin::Mul, sx, r[2]); + let x = self.s.m.bin(c, Bin::Sub, r[0], x); + let y = self.s.m.bin(c, Bin::Mul, sy, r[2]); + let y = self.s.m.bin(c, Bin::Sub, r[1], y); + let z = self.s.m.bin(c, Bin::Mul, sz, r[2]); + sheared.push((x, y, z)); + } + let [(ax, ay, az), (bx, by, bz), (cx, cy, cz)] = sheared[..] else { + unreachable!() + }; + // p * q - r * s. + let cross = |l: &mut Self, p: V, q: V, r: V, s: V| { + let a = l.s.m.bin(c, Bin::Mul, p, q); + let b = l.s.m.bin(c, Bin::Mul, r, s); + l.s.m.bin(c, Bin::Sub, a, b) + }; + let u = cross(self, cx, by, cy, bx); + let v = cross(self, ax, cy, ay, cx); + let w = cross(self, bx, ay, by, ax); + let any = |l: &mut Self, p: u8| { + let a = l.s.m.cmp(c, p, u, fzero); + let b = l.s.m.cmp(c, p, v, fzero); + let d = l.s.m.cmp(c, p, w, fzero); + let a = l.s.m.bin(c, Bin::Or, a, b); + l.s.m.bin(c, Bin::Or, a, d) + }; + let behind = any(self, pred::OLT); + let before = any(self, pred::OGT); + let outside = self.s.m.bin(c, Bin::And, behind, before); + let inside = self.s.m.bin(c, Bin::Xor, outside, on); + let det = self.s.m.bin(c, Bin::Add, v, w); + let det = self.s.m.bin(c, Bin::Add, u, det); + let t = self.s.m.bin(c, Bin::Mul, u, az); + let t2 = self.s.m.bin(c, Bin::Mul, v, bz); + let t = self.s.m.bin(c, Bin::Add, t, t2); + let t2 = self.s.m.bin(c, Bin::Mul, w, cz); + let t = self.s.m.bin(c, Bin::Add, t, t2); + // The distance is not negative: the numerator has the + // denominator's sign (or is 0). Ordered compares: a denominator + // of 0 or a NaN is a miss. + let front = self.s.m.cmp(c, pred::OGT, det, fzero); + let front_ahead = self.s.m.cmp(c, pred::OGE, t, fzero); + let front = self.s.m.bin(c, Bin::And, front, front_ahead); + let back = self.s.m.cmp(c, pred::OLT, det, fzero); + let back_ahead = self.s.m.cmp(c, pred::OLE, t, fzero); + let back = self.s.m.bin(c, Bin::And, back, back_ahead); + let ahead = self.s.m.bin(c, Bin::Or, front, back); + let hit = self.s.m.bin(c, Bin::And, inside, ahead); + let miss = bvh::MISS.map(|f| self.s.m.f32(f.to_bits())); + let out = [t, det, v, w]; + std::array::from_fn(|n| { + let f = self.s.m.select(c, hit, out[n], miss[n]); + self.as_int(f) + }) + } +} diff --git a/crates/victory-shader/src/emit/intersect_tests.rs b/crates/victory-shader/src/emit/intersect_tests.rs new file mode 100644 index 0000000000..8a500d774c --- /dev/null +++ b/crates/victory-shader/src/emit/intersect_tests.rs @@ -0,0 +1,710 @@ +//! The ray-tracing node test end to end: a synthetic compute program that +//! runs `image_bvh64_intersect_ray` (or the 32-bit form) once per thread, +//! lowered to DXIL, validated by `dxil.dll` when present, run on the host +//! GPU and WARP, and compared dword for dword with the CPU reference +//! ([`crate::bvh`]). +//! +//! The nodes are in a raw buffer. Two ways to name it are run: the +//! buffer's descriptor from the program's table (a resource of the host, +//! [`crate::resource::BvhNodes::Resource`]), and the title's way, a +//! descriptor of numbers over title memory with the structure's address in +//! the node pointer or in the descriptor. These tests have no host that +//! keeps copies of title memory and their directory, so for the second +//! they put a stand-in under the node reader +//! (`lower::intersect::TEST_MEMORY`); without it the same program reads +//! through the directory, which is only checked to lower and validate. + +use super::host::{Dispatch, Host, Root, Stride, View}; +use super::lower::intersect::TEST_MEMORY; +use super::{HostShader, lower, validator}; +use crate::bvh::{self, Ray, tests as nodes}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::resource::BvhNodes; +use crate::{ShaderError, io, ir, resource, structure}; + +/// Threads of one group, each with its own record. +const THREADS: u32 = 32; +/// Bytes of a thread's record: the node pointer (two dwords), the ray's +/// extent, origin, direction and inverse direction, and whether the +/// thread runs the instruction. +const RECORD: u32 = 64; +/// Where the nodes start in the buffer. +const NODES: u32 = THREADS * RECORD; +/// What the result registers hold before the instruction. +const BEFORE: [u32; 4] = [1, 2, 3, 4]; + +/// How the program names the nodes' memory. +#[derive(Clone, Copy, PartialEq)] +enum Descriptor { + /// The buffer's descriptor from the table. + Table, + /// Numbers, as the title builds it: dwords 0 and 1 (the base address + /// in 256-byte units and the box sorting bit); the size and the rest of + /// the flags as the title sets them. + Numbers(u32, u32), +} + +/// The descriptor the title builds for the 64-bit form: the whole address +/// space, sorted boxes, barycentrics returned. +const WHOLE: Descriptor = Descriptor::Numbers(0, bvh::BOX_SORT); + +/// The program: per thread, the record's twelve operand dwords in v1-v12, +/// the instruction's result in v13-v16 (under a lane mask of the threads +/// whose record says so), stored to the UAV at 16 bytes a thread. +fn program(wide: bool, descriptor: Descriptor) -> Vec<u32> { + let mut w = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 + 0xF408_0302, + 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 + 0x3428_0086, // v_lshlrev_b32 v20, 6, v0 + 0xE038_1000, + 0x8002_0114, // buffer_load_dwordx4 v[1:4], v20, s[8:11], 0 offen + 0xE038_1010, + 0x8002_0514, // buffer_load_dwordx4 v[5:8], v20, s[8:11], 0 offen offset:16 + 0xE038_1020, + 0x8002_0914, // buffer_load_dwordx4 v[9:12], v20, s[8:11], 0 offen offset:32 + 0xE030_1030, + 0x8002_1114, // buffer_load_dword v17, v20, s[8:11], 0 offen offset:48 + ]; + for k in 0..4u32 { + // v_mov_b32 v13+k, 1+k + w.push(0x7E00_0200 | (13 + k) << 17 | (0x81 + k)); + } + let rsrc = match descriptor { + Descriptor::Table => 8, + Descriptor::Numbers(word0, word1) => { + // s_mov_b32 s24, word0 + w.extend([0xBE98_03FF, word0]); + if word1 == bvh::BOX_SORT { + // As the title makes it. + w.push(0xBE99_0B81); // s_brev_b32 s25, 1 + } else { + w.extend([0xBE99_03FF, word1]); // s_mov_b32 s25, word1 + } + w.extend([ + 0xBE9A_03C1, // s_mov_b32 s26, -1 + 0xBE9B_03FF, + 0x8900_03FF, // s_mov_b32 s27, 0x890003ff + ]); + 24 + } + }; + w.extend([ + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7DAA_2280, // v_cmpx_ne_u32 exec_lo, 0, v17 + ]); + let first = 0x0000_0D01 | (rsrc >> 2) << 16; + if wide { + // image_bvh64_intersect_ray v[13:16], [v1 .. v12], s[rsrc:rsrc+3] + w.extend([0xF19C_9F07, first, 0x0504_0302, 0x0908_0706, 0x000C_0B0A]); + } else { + // image_bvh_intersect_ray v[13:16], [v1, v3 .. v12], s[rsrc:rsrc+3] + w.extend([0xF198_9F07, first, 0x0605_0403, 0x0A09_0807, 0x0000_0C0B]); + } + w.extend([ + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0x342A_0084, // v_lshlrev_b32 v21, 4, v0 + 0xE078_1000, + 0x8003_0D15, // buffer_store_dwordx4 v[13:16], v21, s[12:15], 0 offen + 0xBF81_0000, // s_endpgm + ]); + w +} + +fn native(words: &[u32]) -> NativeProgram { + let table = |kind, at| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: at, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }; + NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 22, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![table(ResourceType::Srv, 0), table(ResourceType::Uav, 8)], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [THREADS, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// Lowers the program; the DXIL is validated when the validator is there. +fn build( + wide: bool, + descriptor: Descriptor, +) -> Result<(HostShader, resource::Resources), ShaderError> { + let native = native(&program(wide, descriptor)); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + })?; + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views.clone(), + half_views: lowered.half_views, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + Ok((shader, res)) +} + +/// One thread's test: a node (by its index in the node list), the kind its +/// pointer carries, and the ray; `None` leaves the thread masked out. +type Case = Option<(usize, u32, Ray)>; + +/// The scene: node dwords (a 32-bit box node takes 32, the others 16) and +/// where each node starts, in dwords from the first node. +struct Scene { + words: Vec<u32>, + starts: Vec<usize>, +} + +impl Scene { + fn new() -> Self { + Self { + words: Vec::new(), + starts: Vec::new(), + } + } + + /// Adds a node of `dwords` (16 or 32) and returns its index. + fn add(&mut self, node: [u32; 28], dwords: usize) -> usize { + self.starts.push(self.words.len()); + let mut padded = [0u32; 32]; + padded[..28].copy_from_slice(&node); + // Bytes the instruction must not read as part of the node: what + // follows a 64-byte node, and a box node's last 16 bytes. + for w in padded.iter_mut().skip(if dwords == 16 { 16 } else { 28 }) { + *w = 0x7fc0_dead; + } + self.words.extend(&padded[..dwords]); + self.starts.len() - 1 + } + + /// The pointer of node `n` with `kind`, counted from the first node. + fn pointer(&self, n: usize, kind: u32) -> u32 { + (4 * self.starts[n] as u32) >> 3 | kind + } + + /// What the instruction reads of node `n`. + fn node(&self, n: usize) -> [u32; 28] { + std::array::from_fn(|k| self.words.get(self.starts[n] + k).copied().unwrap_or(0)) + } +} + +/// A small generator of repeatable numbers. +struct Numbers(u64); + +impl Numbers { + fn next(&mut self) -> u32 { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (self.0 >> 33) as u32 + } + + /// A float in -1..1 in steps of 1/4096 (exactly representable). + fn unit(&mut self) -> f32 { + (self.next() % 8193) as f32 / 4096.0 - 1.0 + } + + fn vector(&mut self, scale: f32) -> [f32; 3] { + [ + self.unit() * scale, + self.unit() * scale, + self.unit() * scale, + ] + } +} + +/// The scene and batches of cases over it. +fn scene() -> (Scene, Vec<Vec<Case>>) { + let mut s = Scene::new(); + let mut g = Numbers(0x5eed); + const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0]; + let moved = + |b: [f32; 6], by: [f32; 3]| -> [f32; 6] { std::array::from_fn(|k| b[k] + by[k % 3]) }; + let off = [f32::NAN; 6]; + let mut box_nodes = Vec::new(); + // The boxes of the reference's own tests, in both widths. + let lined = [ + moved(UNIT, [30.0, 0.0, 0.0]), + moved(UNIT, [10.0, 0.0, 0.0]), + moved(UNIT, [10.0, 5.0, 0.0]), + moved(UNIT, [20.0, 0.0, 0.0]), + ]; + let ids = [0x105, 0x20c, 0x304, 0x400]; + box_nodes.push((s.add(nodes::box32(ids, lined), 32), 5)); + box_nodes.push((s.add(nodes::box16(ids, lined), 16), 4)); + // Boxes around the origin, one switched off, one child missing. + let around = [ + UNIT, + moved(UNIT, [0.5, 0.5, 0.5]), + off, + [-4.0, -0.25, -0.25, 4.0, 0.25, 0.25], + ]; + let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc]; + box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5)); + box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4)); + // Random boxes. + for n in 0..6 { + let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| { + let (c, h) = (g.vector(8.0), g.vector(2.0).map(f32::abs)); + std::array::from_fn(|k| c[k % 3] + if k < 3 { -h[k] } else { h[k - 3] }) + }); + let ids: [u32; 4] = std::array::from_fn(|k| 0x1000 * (n + 1) + 8 * k as u32 + 5); + if n % 2 == 0 { + box_nodes.push((s.add(nodes::box32(ids, boxes), 32), 5)); + } else { + box_nodes.push((s.add(nodes::box16(ids, boxes), 16), 4)); + } + } + // Triangles: one of the reference's tests, a pair as the title's + // builder stores it, all four triangles of a full node with turned + // ids, random ones. + let mut triangle_nodes = Vec::new(); + let front = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]]; + triangle_nodes.push((s.add(nodes::triangles(&front, 9), 16), 0)); + let pair = s.add( + nodes::triangles( + &[front[0], front[1], front[2], [2.0, 2.0, 5.0]], + 9 | 0x80 | 6 << 8, + ), + 16, + ); + triangle_nodes.extend([(pair, 0), (pair, 1)]); + let five = [ + [-3.0, -1.0, 6.0], + [-1.0, 2.0, 6.5], + [1.0, -1.0, 6.0], + [3.0, 2.0, 6.5], + [5.0, -1.0, 7.0], + ]; + // I and J per triangle: (1, 2), (2, 0), (0, 1), (1, 2). + let full = s.add(nodes::triangles(&five, 9 | 2 << 8 | 4 << 16 | 9 << 24), 16); + triangle_nodes.extend((0..4).map(|k| (full, k))); + for _ in 0..5 { + let c = g.vector(6.0); + let v: [[f32; 3]; 3] = std::array::from_fn(|_| { + let d = g.vector(3.0); + [c[0] + d[0], c[1] + d[1], c[2] + d[2]] + }); + triangle_nodes.push((s.add(nodes::triangles(&v, 9), 16), 0)); + } + let mut cases: Vec<Case> = Vec::new(); + // Rays of the reference's tests against the lined-up boxes. + for &(n, kind) in &box_nodes[..2] { + for (origin, direction, extent) in [ + ([0.0; 3], [1.0, 0.0, 0.0], 1000.0), + ([0.0; 3], [1.0, 0.0, 0.0], 19.5), + ([0.0; 3], [1.0, 0.0, 0.0], 19.0), + ([0.0; 3], [-1.0, 0.0, 0.0], 1000.0), + ([40.0, 0.0, 0.0], [-2.0, 0.0, 0.0], 1000.0), + ([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], 1000.0), + ([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1000.0), + ([0.0, 0.5, 0.25], [1.0, -0.0, 0.0], 1000.0), + ([0.0; 3], [0.0; 3], 1000.0), + ] { + cases.push(Some((n, kind, Ray::new(origin, direction, extent)))); + } + } + // Random rays at every box node, half of them aimed at a box. + for &(n, kind) in &box_nodes { + let words = s.node(n); + let boxes = if kind == 5 { + bvh::boxes32(&words) + } else { + bvh::boxes16(&words) + }; + for k in 0..12 { + let origin = g.vector(12.0); + let direction = if k % 2 == 0 { + let b = boxes[(k / 2) % 4]; + if b[0].is_nan() { + g.vector(1.0) + } else { + std::array::from_fn(|a| (b[a] + b[3 + a]) / 2.0 - origin[a] + g.unit() / 2.0) + } + } else { + g.vector(1.0) + }; + let extent = if k % 3 == 0 { 6.0 } else { 100.0 }; + cases.push(Some((n, kind, Ray::new(origin, direction, extent)))); + } + } + // Rays at every triangle: aimed inside, at an edge, at a vertex, past + // it, from both sides, along each axis. + for &(n, kind) in &triangle_nodes { + let p = bvh::triangle_vertices(&s.node(n), kind); + let at = |w: [f32; 3]| -> [f32; 3] { + std::array::from_fn(|a| w[0] * p[0][a] + w[1] * p[1][a] + w[2] * p[2][a]) + }; + for (k, w) in [ + [0.5, 0.25, 0.25], + [0.125, 0.75, 0.125], + [0.5, 0.5, 0.0], + [0.0, 0.5, 0.5], + [1.0, 0.0, 0.0], + [0.75, 0.75, -0.5], + [-0.25, 0.5, 0.75], + [0.25, 0.25, 0.5], + ] + .into_iter() + .enumerate() + { + let target = at(w); + let origin = if k % 2 == 0 { [0.0; 3] } else { g.vector(16.0) }; + let mut direction: [f32; 3] = std::array::from_fn(|a| target[a] - origin[a]); + if k == 7 { + // The triangle lies behind. + direction = direction.map(|d| -d); + } + cases.push(Some((n, kind, Ray::new(origin, direction, 100.0)))); + } + for axis in 0..3 { + for sign in [1.0f32, -1.0] { + let target = at([0.25, 0.5, 0.25]); + let mut origin = target; + origin[axis] -= 8.0 * sign; + let mut direction = [0.0; 3]; + direction[axis] = sign; + cases.push(Some((n, kind, Ray::new(origin, direction, 100.0)))); + } + } + } + // Kinds the instruction does not read, and threads masked out. + let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); + cases.extend([ + Some((triangle_nodes[0].0, 6, ray)), + Some((triangle_nodes[0].0, 7, ray)), + None, + Some(( + box_nodes[0].0, + 5, + Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0), + )), + None, + ]); + let batches = cases + .chunks(THREADS as usize) + .map(<[Case]>::to_vec) + .collect(); + (s, batches) +} + +/// The buffer for one batch: the threads' records, then the nodes. Node +/// pointers count from `base` before the first node, in bytes. +fn buffer(scene: &Scene, batch: &[Case], base: u64) -> Vec<u32> { + let mut data = vec![0u32; (NODES / 4) as usize]; + for (t, case) in batch.iter().enumerate() { + let Some((n, kind, ray)) = case else { continue }; + let r = &mut data[t * (RECORD / 4) as usize..][..13]; + let pointer = (base >> 3) + u64::from(scene.pointer(*n, *kind)); + (r[0], r[1]) = (pointer as u32, (pointer >> 32) as u32); + r[2] = ray.extent.to_bits(); + for a in 0..3 { + r[3 + a] = ray.origin[a].to_bits(); + r[6 + a] = ray.direction[a].to_bits(); + r[9 + a] = ray.inverse[a].to_bits(); + } + r[12] = 1; + } + data.extend(&scene.words); + data +} + +fn expected(scene: &Scene, case: &Case, sort: bool) -> [u32; 4] { + match case { + Some((n, kind, ray)) => bvh::intersect(&scene.node(*n), *kind, ray, sort), + None => BEFORE, + } +} + +/// Sets the tests' title memory for this thread until dropped. +struct Memory; + +impl Memory { + fn at(base: u64) -> Self { + // Heap slot 0: the buffer of records and nodes. + TEST_MEMORY.set(Some((0, base))); + Self + } +} + +impl Drop for Memory { + fn drop(&mut self) { + TEST_MEMORY.set(None); + } +} + +/// Runs every batch on the hardware adapter and WARP and compares with +/// the reference. `pointers` is what node pointers count from, in bytes +/// before the first node. +fn run(wide: bool, descriptor: Descriptor, pointers: u64, sort: bool) { + let (shader, res) = build(wide, descriptor).expect("the program lowers"); + assert_eq!(res.bvh.len(), 1); + let (scene, batches) = scene(); + // The reference must see a bit of everything, or the comparison + // proves little. + let all: Vec<&Case> = batches.iter().flatten().collect(); + let results: Vec<[u32; 4]> = all.iter().map(|c| expected(&scene, c, sort)).collect(); + let boxes = |hits: usize| { + all.iter() + .zip(&results) + .filter(|(c, r)| { + matches!(c, Some((_, 4 | 5, _))) + && r.iter().filter(|&&x| x != bvh::NONE).count() == hits + }) + .count() + }; + let triangles = |hit: bool| { + all.iter() + .zip(&results) + .filter(|(c, r)| { + matches!(c, Some((_, 0..=3, _))) && (r[0] != f32::INFINITY.to_bits()) == hit + }) + .count() + }; + assert!( + boxes(0) > 5 && boxes(1) > 5 && boxes(2) > 5 && boxes(3) > 0, + "box cases" + ); + assert!( + triangles(true) > 30 && triangles(false) > 30, + "triangle cases" + ); + // Sorting must matter to some case, or the unsorted run proves nothing. + assert!( + all.iter() + .any(|c| expected(&scene, c, true) != expected(&scene, c, false)), + "no case tells sorted from unsorted" + ); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + for (b, batch) in batches.iter().enumerate() { + let data = buffer(&scene, batch, pointers); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(vec![0; 5]))], + views: &[ + View::Buffer { + data: &data, + stride: Stride::Raw, + }, + View::RawUav(4 * THREADS), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + for t in 0..THREADS as usize { + let case = batch.get(t).copied().flatten(); + let want = match batch.get(t) { + Some(c) => expected(&scene, c, sort), + // A thread past the batch: its record is zeros, so it + // is masked out. + None => BEFORE, + }; + let got = &out[0][4 * t..4 * t + 4]; + assert_eq!( + got, + want, + "{label}, batch {b} thread {t}: {case:x?}\n got {:x?} = {:?}\nwant {:x?} = {:?}", + got, + got.iter().map(|&x| f32::from_bits(x)).collect::<Vec<_>>(), + want, + want.map(f32::from_bits), + ); + } + } + ran += 1; + } + assert!(ran > 0, "no SM 6.6 device available"); +} + +#[test] +fn the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() { + // Pointers count from the buffer's start. + run(true, Descriptor::Table, u64::from(NODES), true); + assert_eq!( + build(true, Descriptor::Table).unwrap().1.bvh[0].1, + BvhNodes::Resource + ); +} + +#[test] +fn the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() { + run(false, Descriptor::Table, u64::from(NODES), true); +} + +/// Where the tests' title memory puts the buffer: past 4 GiB, on 256 bytes. +const BASE: u64 = 0x12_3456_7800; + +#[test] +fn the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card() { + // The title's way: one descriptor for all of memory, the structure's + // address folded into a 64-bit pointer. + let _memory = Memory::at(BASE); + run(true, WHOLE, BASE + u64::from(NODES), true); +} + +#[test] +fn the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card() { + // The title's other way: the structure's address in the descriptor + // (in 256-byte units, 40 bits), a 32-bit pointer from there. Here with + // an address past 2^40 bytes, and without box sorting. + let base = 0x312_3456_7800u64; + let structure = base + u64::from(NODES); + let _memory = Memory::at(base); + let descriptor = Descriptor::Numbers((structure >> 8) as u32, (structure >> 40) as u32); + run(false, descriptor, 0, false); + // And sorted. + let descriptor = Descriptor::Numbers( + (structure >> 8) as u32, + (structure >> 40) as u32 | bvh::BOX_SORT, + ); + run(false, descriptor, 0, true); +} + +#[test] +fn a_descriptor_of_numbers_is_title_memory_read_through_the_directory() { + for wide in [true, false] { + let native = native(&program(wide, WHOLE)); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked"); + // The flags the title sets: sorted boxes, barycentrics, a + // ray-tracing structure. No resource is taken for it: the buffer + // loads' and the store's descriptors are all there is. + assert_eq!(res.bvh.len(), 1); + assert_eq!( + res.bvh[0].1, + BvhNodes::Memory { + word1: 0x8000_0000, + word3: 0x8900_03ff + } + ); + assert_eq!(res.descriptors.len(), 5); + // Without the tests' stand-in the nodes are read as the title's + // programs will read them: through the host's directory of title + // memory. The program lowers and validates, and asks the host for + // the directory and for the list of pages it found no copy of. + let (shader, _) = build(wide, WHOLE).expect("lowers through the directory"); + assert!(shader.root_srvs.contains(&super::SLOT_MEMORY)); + assert!(shader.root_uavs.contains(&super::SLOT_FAULTS)); + } +} + +/// With `VICTORY_BVH_NO_HIT=1` a node test over title memory lowers and +/// validates, and reads nothing: the program asks the host neither for the +/// directory of title memory nor for the list of pages it found no copy +/// of, which it does without the switch (the test above). +#[test] +fn a_node_test_that_answers_no_hit_reads_nothing() { + for wide in [true, false] { + super::lower::intersect::TEST_NO_HIT.set(true); + let built = build(wide, WHOLE); + super::lower::intersect::TEST_NO_HIT.set(false); + let (shader, _) = built.expect("lowers with no hit"); + assert!(!shader.root_srvs.contains(&super::SLOT_MEMORY)); + assert!(!shader.root_uavs.contains(&super::SLOT_FAULTS)); + // And with it off again, as before. + let (shader, _) = build(wide, WHOLE).expect("lowers through the directory"); + assert!(shader.root_srvs.contains(&super::SLOT_MEMORY)); + } +} + +#[test] +fn a_structure_that_returns_triangle_ids_is_refused_by_name() { + // Triangle return mode 0 (bit 24 of dword 3 clear): the last two + // result dwords would be a triangle id and a hit status. + let mut words = program(true, WHOLE); + let flags = words.iter().position(|&w| w == 0x8900_03FF).unwrap(); + words[flags] = 0x8800_03FF; + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked"); + let io = io::raise(&p, &native).expect("io::raise"); + let r = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + match r { + Err(ShaderError::Unsupported { what, .. }) => { + assert_eq!(what, "a ray-tracing structure that returns triangle ids"); + } + other => panic!("{:?}", other.map(|_| ())), + } +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ae6df472f3..ff63e3c689 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -9,7 +9,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use super::UserData; -use super::bitcode::{Attr, Bin, Cast, Term, V, pred}; +use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, V, pred}; use super::container::SigElement; use super::shader::{Shader, flags}; use crate::ShaderError; @@ -17,11 +17,40 @@ use crate::gfx10::{Dpp, Fields, NULL, Operand}; use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource}; -use crate::resource::{Address, CODE, Resources, Role, Site, Source}; +use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source}; use crate::structure::{Atom, Bool, LaneExit, Structured}; +/// The ray-tracing node test (`image_bvh_intersect_ray`), a child module so +/// it shares the emitter's state. +#[path = "intersect.rs"] +pub(super) mod intersect; + +/// Format loads that move 16-bit halves without the d16 form, a child +/// module so it shares the emitter's state. +#[path = "halves.rs"] +mod halves; + +/// Threads past a `DispatchX` thread count (`USER_DISPATCH_THREADS`), a +/// child module so it shares the emitter's state (fork pull request #646). +#[path = "dispatch_threads.rs"] +mod dispatch_threads; + type Why = &'static str; +/// How an interpolation evaluates an input channel. +#[derive(Debug, Clone, Copy)] +enum Eval { + /// Loaded with this DXIL interpolation mode (1: constant, P0). + Mode(u8), + /// From the vertex values of a constant element: P0 when `p0`, plus + /// i (P1 - P0), plus j (P2 - P0), weights as floats. + Weights { + p0: bool, + i: Option<V>, + j: Option<V>, + }, +} + #[derive(Debug, Clone, Copy)] enum Val { I32(V), @@ -35,18 +64,13 @@ pub(crate) struct Lowered { pub cmp_samplers: u64, pub root_cbvs: Vec<u8>, pub root_srvs: Vec<u8>, + pub root_uavs: Vec<u8>, + /// See [`super::HostShader::half_views`]. + pub half_views: Vec<(u8, u32)>, pub user_data: Vec<UserData>, pub samplers: Vec<[u32; 4]>, - #[cfg(test)] - pub has_isnan_op: bool, - #[cfg(test)] - pub has_fcmp_uno: bool, - /// Whether an unsigned integer `>` compare was emitted. - #[cfg(test)] - pub has_iugt: bool, - /// The props of each heap handle, in creation order. - #[cfg(test)] - pub handle_props: Vec<(u32, u32)>, + /// The wave size the shader requires of the host, if any. + pub wave_size: Option<u32>, /// Heap handles made with a non-uniform index. #[cfg(test)] pub nonuniform_handles: u32, @@ -56,15 +80,6 @@ pub(crate) struct Lowered { /// Whether the program uses wave operations. #[cfg(test)] pub wave_ops: bool, - /// The functions the module declares. - #[cfg(test)] - pub funcs: Vec<String>, - /// Mesh primitive exports bounded by the declared vertex count. - #[cfg(test)] - pub bounded_prims: u32, - /// Back edges that count against the spin-wait limit. - #[cfg(test)] - pub spin_loops: usize, } pub(crate) struct Parts<'a> { @@ -78,8 +93,6 @@ pub(crate) struct Parts<'a> { pub prims: Vec<SigElement>, /// Mesh: what the group id arrives multiplied by. pub mesh_stride: u32, - /// The host runs 64-lane waves ([`super::host_wave64`]). - pub host_wave64: bool, } enum Stop { @@ -88,22 +101,17 @@ enum Stop { Fail(ShaderError), } -const UNTRACKED_SELECT: Why = "a select on an untracked mask"; - -pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> { - match lower_program(parts, false) { - Err(ShaderError::Unsupported { - what: UNTRACKED_SELECT, - .. - }) if parts.native.stage == HwStage::Cs => lower_program(parts, true), - result => result, - } +/// Try 6.12, ported from trustno1-coder/VIctory-NVIDIA 77e13a97: +/// `VICTORY_NAN_SCRUB=1` (off by default): see `Lower::scrub_nan`. +pub(crate) fn nan_scrub() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_NAN_SCRUB").is_some_and(|v| v == "1")) } -fn lower_program(parts: &Parts, numeric_selects: bool) -> Result<Lowered, ShaderError> { +pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> { let mut bad = HashMap::new(); loop { - match Lower::new(parts, &bad, numeric_selects).run() { + match Lower::new(parts, &bad).run() { Ok(l) => return Ok(l), Err(Stop::Retry(v, why)) => { if bad.insert(v, why).is_some() { @@ -122,6 +130,14 @@ const TWO_PI: f32 = std::f32::consts::TAU; /// `s_sendmsg` id of a mesh or NGG stage's output allocation request. const GS_ALLOC_REQ: u16 = 9; +/// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0, +/// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)). +fn inline_f16(c: u8) -> u32 { + [ + 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, + ][usize::from(c - 240)] +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Numeric { Unorm, @@ -183,10 +199,6 @@ fn half_shift(width: u32) -> u32 { if width == 16 { 0 } else { 15 - width } } -/// A cached descriptor handle: block, the load site, its first dword, whether -/// it is a sampler, and the resource properties. -type HandleKey = (usize, Site, u8, bool, (u32, u32)); - struct Lower<'a> { s: Shader, x: &'a Parts<'a>, @@ -197,10 +209,22 @@ struct Lower<'a> { /// DXIL block per IR block (unreachable: none). block: Vec<Option<usize>>, cur: usize, + /// The DXIL block the program's body begins in: `s.entry`, or after + /// the threads past a `DispatchX` thread count have left + /// ([`Self::dispatch_threads_prologue`]). EXEC on entry is read there. + body_entry: usize, + /// Whether this thread is within a `DispatchX` thread count, where its + /// threads past the count stay for the group's barriers or the halves' + /// exchange: memory accesses, ballots and wave reductions leave the + /// others out ([`Self::dispatch_threads_prologue`]). + partial_active: Option<V>, bools: HashMap<(usize, Bool), V>, lane_bits: HashMap<Value, V>, /// IR phi location by value. phi_at: HashMap<Value, (usize, usize)>, + /// Descriptor dwords with no host value (addresses, formats, all of a constant + /// buffer's): no program reads them as numbers ([`Self::dead`]). + stale: HashSet<Value>, mask_phis: HashMap<Value, V>, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -208,14 +232,20 @@ struct Lower<'a> { params: HashMap<Value, (usize, u32)>, user_data: Option<V>, user_reads: BTreeMap<u32, UserData>, - /// Bytes each root view holds, by root parameter (see [`Self::root_view_size`]). - root_sizes: HashMap<usize, V>, + /// Table descriptors read or written sixteen bits a channel + /// ([`super::HostShader::half_views`]): root parameter, dword offset. + half_views: std::collections::BTreeSet<(u8, u32)>, + /// [`Self::places_read_as_halves`], found before the code is lowered. + halves_only: std::collections::BTreeSet<(u8, u32)>, samplers: Vec<[u32; 4]>, descriptors: HashMap<(Site, bool), &'a Source>, scalar: HashMap<Site, Address>, exports: HashMap<Site, &'a Export>, interps: HashMap<Site, &'a Interp>, - handles: HashMap<HandleKey, V>, + handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>, + /// Element strides read from the host's table by heap slot + /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load. + strides: HashMap<(usize, Site, u8), V>, /// Blocks splitting the edge from one IR block to another. edges: HashMap<(usize, usize), usize>, /// Per IR block: a `done` export is behind every lane entering it. @@ -231,13 +261,47 @@ struct Lower<'a> { /// Compute code that reads other lanes: thread ids follow the host /// lanes, so lane n is console lane n. console_lanes: bool, - /// Retry a compute shader with numeric selects only when the normal - /// translation needs one. Unused selects need no fixed wave size. - numeric_selects: bool, /// Mesh: the thread index in the group (made in the entry block). flat: Option<V>, /// Mesh: IR blocks whose `s_barrier` is left out. no_barrier: HashSet<usize>, + /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane + /// branch lies between the entry and the block, or the program has a + /// loop a lane can be cut out of): the barrier there keeps its fences + /// and does not wait for the group ([`super::group_sync`]). + fence_only: HashSet<usize>, + /// A group barrier before every LDS access (a console wave run as two host waves). + split_lds: bool, + /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs + /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]). + lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)>, + /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first + /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per + /// IR block whether every lane runs it (exchanges need both halves there). + exchange: Option<(u32, bool, Vec<bool>)>, + /// With `exchange`: nothing is exchanged, each host wave acts as a wave + /// of its own ([`with_local_waves`]). + local: bool, + /// The instruction being lowered may read a lane mask as a number under + /// `local` (a bit count, a first set bit, `v_mbcnt`). + local_ok: bool, + /// With `local`: every mask read and lane read is taken per host wave + /// ([`with_local_waves_any`]). + local_any: bool, + /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane + /// read of one needs nothing from the other host wave. + uniform: HashSet<Value>, + /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which + /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]). + own_bits: super::own_bits::OwnBits, + /// The console lane (0..63) of this thread, made in the entry block. + clane: Option<V>, + /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]). + pair: Option<V>, + /// A console wave64 program in host waves of 32: the LDS dword counting the console threads + /// handed to host waves (`wave_base`), and the base made in the entry block. + halves: Option<u32>, + wave_base: Option<V>, /// Vertex and mesh outputs holding 16-bit values: row, whether two per /// dword, and the row packed after it. half_outputs: HashMap<u8, (bool, Option<u8>)>, @@ -267,188 +331,850 @@ struct Lower<'a> { counters: HashMap<usize, (V, Vec<(V, usize)>)>, /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. abort: Option<usize>, - /// Headers of loops that only wait for memory to change: they stop - /// at [`super::spin_limit`] instead. - spin: HashSet<usize>, - /// Back edges given the spin-wait limit. - #[cfg(test)] - spun: usize, - /// Compute needing the console's 64-lane wave on a host without one, - /// in a group that is that one wave: cross-lane steps go through - /// group-shared memory ([`Emulated`]). - emulated: Option<Emulated>, - /// Compute needing the console's 64-lane waves on a host without them, - /// in a group of several waves: refused. - wave64_refused: bool, - /// Guarded code being lowered ([`Lower::begin_guarded`] depth). - guard_depth: u32, - /// The one block that returns: every end of the program branches to it, - /// so the function has a single exit as DXC emits it (dxil-spirv, under - /// Proton, cannot structure a loop left by both a break and a return). - ret: Option<usize>, } -/// The console's 64-lane wave as one thread group on a host whose waves -/// are narrower (NVIDIA's 32). Console lane n is the thread with flattened -/// id n; a step that reads other lanes (a lane read, a ballot, a wave -/// reduction) stores each lane's value in group-shared slots and reads -/// them back between two group barriers, and LDS accesses, which the -/// console's lanes make in lockstep, get a barrier before each. A barrier -/// must be reached by every thread of the group, so these steps are only -/// allowed where every lane runs: blocks no lane-dependent branch decides -/// on ([`uniform_blocks`]), outside guarded code; elsewhere the program -/// is refused with a reason. Scalar branches stay uniform because every -/// scalar value made from vector data comes through these same steps. -struct Emulated { - /// Threads in the group (at most 64): the console lanes that exist. - lanes: u32, - /// Per IR block: every lane that runs the program runs it. - uniform: Vec<bool>, - /// The exchange slots, `[64 x i32]` in group-shared memory. - slots: Option<V>, +/// Iterations after which a loop is left (per entry into it), unless +/// [`super::loop_limit`] says otherwise. The console runs a loop as long as +/// its data says; data the host has not mirrored yet (a null view reads +/// zeros) can make that four billion iterations, which hangs the host GPU +/// until the driver resets it. A lane that reaches the limit leaves the +/// program as killed (a pixel discards). +// shortcut: a genuine loop of more iterations than this is cut short too. +pub(super) const LOOP_LIMIT: u32 = 1 << 20; + +/// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar +/// compares, bit tests) are ballots of the lanes' booleans, taken where the +/// mask is written: structurisation's `active` masks hold only lanes that +/// reach that block, so the ballot misses none. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum MaskData { + /// Compute: host lane n is console lane n (the program declares the + /// console's wave size), so ballots are the console's masks bit for bit + /// and any use is exact. + Console, + /// Pixel and vertex programs: ballots over the host's wave, whatever its + /// size. Only uses that mean the same on any wave are allowed: counts, + /// the first lane, the count below a lane, equality (the HLSL wave + /// operations the console compiler expands). Lane numbers stay host + /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane). + Host, + /// Mesh programs: their lanes and waves (LDS per console wave) are the + /// console's but no host wave size can be declared. + None, +} + +/// What a value holding a lane mask read as a number stops with. +pub(super) const LANE_MASK: Why = "a lane mask read as data"; +pub(super) const DIVERGENT_MASK_EXCHANGE: Why = "a lane mask exchanged where not every lane runs"; +/// A mask with lanes outside EXEC where it is written, read as a number where the lanes that +/// run that block are not all of the wave. +pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; +/// An interpolation instruction with no interpolation raised for it: a +/// first half whose result is also read beside its second half +/// (`emit::translate` then retries with `io::raise_keeping_first_halves`). +pub(super) const FIRST_HALF: Why = "the first half of an interpolation"; + +/// Instructions that read a lane mask (not EXEC implicitly, not a lane's +/// bit) as a number. +/// Per IR block: every lane of the wave that started the program runs it – no per-lane branch +/// separates it from the entry (it lies in no lane branch's region: the blocks reachable from +/// the branch that do not post-dominate it). None with an indirect exit (not followed). +fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> { + let n = st.exits.len(); + let mut all = vec![true; n]; + for (_, region) in lane_regions(st)? { + for b in (0..n).filter(|&b| region[b]) { + all[b] = false; + } + } + Some(all) } -/// Per IR block of `st`: whether every lane that runs the program reaches -/// it when any does. A block is not uniform when a branch on a per-lane -/// condition reaches it without strictly post-dominating that branch -/// (lanes reconverge only there), or when it cannot reach the end of the -/// program (no post-dominance to rely on). -fn uniform_blocks(st: &Structured) -> Vec<bool> { +/// Every per-lane branch (by its block) with its region: the blocks reachable from it that do +/// not post-dominate it, which only some lanes run. Not the branches the wave takes together +/// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit. +fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> { let n = st.exits.len(); - let words = n.div_ceil(64); - let succs: Vec<Vec<usize>> = st - .exits - .iter() - .map(|e| match *e { - LaneExit::Jump(t) => vec![t], - LaneExit::Branch { - taken, not_taken, .. - } => vec![taken, not_taken], - LaneExit::End | LaneExit::Indirect => Vec::new(), - }) - .collect(); - // Post-dominators as bit sets: pd(b) = {b} + the meet over successors. - let mut pd: Vec<Vec<u64>> = (0..n) - .map(|b| { - if succs[b].is_empty() { - let mut v = vec![0u64; words]; - v[b / 64] |= 1 << (b % 64); - v - } else { - vec![u64::MAX; words] + let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n]; + for (b, e) in st.exits.iter().enumerate() { + match *e { + LaneExit::Jump(t) => succ[b].push(t), + LaneExit::Branch { taken, not_taken, .. } => { + succ[b].push(taken); + succ[b].push(not_taken); } - }) - .collect(); + LaneExit::End => {} + LaneExit::Indirect => return None, + } + } + // post-dominators (bitsets; a virtual exit after every End) + let words = n.div_ceil(64); + let full = vec![u64::MAX; words]; + let mut pdom: Vec<Vec<u64>> = (0..n).map(|b| if succ[b].is_empty() { let mut v = vec![0; words]; v[b / 64] |= 1 << (b % 64); v } else { full.clone() }).collect(); let mut changed = true; while changed { changed = false; for b in (0..n).rev() { - if succs[b].is_empty() { + if succ[b].is_empty() { continue; } - let mut v = vec![u64::MAX; words]; - for &t in &succs[b] { - for (w, x) in v.iter_mut().zip(&pd[t]) { - *w &= x; + let mut v = full.clone(); + for &t in &succ[b] { + for w in 0..words { + v[w] &= pdom[t][w]; } } v[b / 64] |= 1 << (b % 64); - if v != pd[b] { - pd[b] = v; + if v != pdom[b] { + pdom[b] = v; changed = true; } } } - let mut preds = vec![Vec::new(); n]; - for (b, ss) in succs.iter().enumerate() { - for &t in ss { - preds[t].push(b); + let mut regions = Vec::new(); + for (d, e) in st.exits.iter().enumerate() { + let LaneExit::Branch { when, .. } = *e else { continue }; + if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) { + continue; // a wave-wide or uniform branch: all lanes go the same way } + // blocks reachable from the lane branch that do not post-dominate it + let mut seen = vec![false; n]; + let mut stack: Vec<usize> = succ[d].clone(); + while let Some(b) = stack.pop() { + if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 { + continue; + } + seen[b] = true; + stack.extend(succ[b].iter().copied()); + } + regions.push((d, seen)); } - let mut ends = vec![false; n]; - let mut stack: Vec<usize> = (0..n).filter(|&b| succs[b].is_empty()).collect(); - while let Some(b) = stack.pop() { - if !std::mem::replace(&mut ends[b], true) { - stack.extend(preds[b].iter().copied()); + Some(regions) +} + +/// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two +/// host waves must meet, [`take_needs`]): the ones to take wave-wide +/// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one +/// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]). +pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<usize>> { + let mut out = Vec::new(); + for (d, region) in lane_regions(st)? { + if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) { + st.wave_any.get(d).copied().flatten()?; + out.push(d); } } - let mut uniform = ends; - for (d, e) in st.exits.iter().enumerate() { - let LaneExit::Branch { when, .. } = *e else { - continue; + Some(out) +} + +/// Whether a refusal is of code that needs every lane of the wave where it stands (two host +/// waves meeting there), which the other forms of the program may give it. +pub(super) fn needs_every_lane(what: &str) -> bool { + what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE +} + +/// The blocks where the last lowering on this thread wanted every lane and did not have it +/// (its "... where not every lane runs" refusals), which it forgets. +pub(super) fn take_needs() -> Vec<usize> { + NEEDS.take() +} + +fn need(block: usize) { + NEEDS.with_borrow_mut(|n| { + if !n.contains(&block) { + n.push(block); + } + }); +} + +/// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]): +/// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars, +/// constants and such values; or loaded from an address made of them. The compiler keeps +/// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. +/// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes +/// run (no lane branch can have split the arriving lanes); loop-carried values never do. +fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> { + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let mut same: HashSet<Value> = HashSet::new(); + for b in crate::ir::reverse_postorder(&p.blocks) { + let block = &p.blocks[b]; + let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); + for phi in &block.phis { + if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) { + same.insert(phi.value); + } + } + for (i, inst) in block.insts.iter().enumerate() { + let name = inst.name(); + if st.guards[b][i].is_some() { + continue; // lanes outside EXEC keep another value + } + let alike = match &inst.fields { + Fields::Valu(v) + if v.dpp.is_none() + && v.sdwa.is_none() + && !name.starts_with("v_mbcnt") + && !name.starts_with("v_cmpx") + && !name.contains("lane") => + { + v.src.iter().all(|op| match *op { + Operand::Vector { reg, dwords } => { + // every dword of the operand the instruction reads (not the old value + // of a higher-numbered destination register that IR keeps for guards) + let end = reg.saturating_add(dwords); + let read: Vec<Value> = inst + .reads + .iter() + .filter(|r| matches!(r.0, Reg::V(x) if x >= reg && x < end)) + .map(|r| r.1) + .collect(); + !read.is_empty() && read.iter().all(|x| same.contains(x)) + } + // a scalar is one value; a lane mask is not, unless a compare of such values made it + Operand::Scalar { code, dwords } if code != NULL => { + (code..code.saturating_add(dwords)).all(|c| { + inst.read(Reg::S(c)).is_none_or(|x| !is_mask(x) || same.contains(&x)) + }) + } + _ => true, + }) + } + Fields::Ds { + addr: Some(Operand::Vector { reg, .. }), + gds: false, + .. + } if name.starts_with("ds_read") && !name.contains("_d16") => { + // An unguarded LDS read from a wave-uniform address gives the same value + // in every arriving lane. `_d16` forms preserve the other half of the + // destination register and are left out. + inst.read(Reg::V(*reg)).is_some_and(|x| same.contains(&x)) + } + _ => false, + }; + if alike { + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + } + } + } + same +} + +/// What a register value holds, for [`wave_local`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Wave { + /// Nothing that depends on how the threads are divided into waves. + Plain, + /// The number of the wave's first lane in a mask (`s_ff1`). + First, + /// A reduction over the wave's lanes: a count, a sum, a minimum... + Total(super::wave::Op), + /// A count or sum over the lanes below this one. + Prefix, + /// Derived from what a first-lane atomic returned: the slots the wave reserved. + Base, + /// A mix the idiom does not make. + Mixed, +} + +/// Whether a console wave64 program may run with each host wave as a wave of its own +/// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses +/// them, which does not care how the threads are divided into waves. A first-lane number only +/// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter; +/// a prefix only goes onto the base that atomic returned; the first lane does nothing else. +/// Anything else done with them takes one wave to be the whole thread group (a tile's result, +/// say) and is refused, with the offset and what was found. +/// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections +/// are stopped by the lowering itself. +// shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this +// host wave's first lane), and a guarded write of a plain value over a wave-dependent one is +// the only mix of old and new lanes that is looked at. +pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> { + use super::wave::{Op, Shape}; + const FIRST: Why = "a wave's first-lane number used as data"; + const TOTAL: Why = "a count or sum over the wave used as data"; + const PREFIX: Why = "a count or sum over the lanes below used without a reserved base"; + const MIXED: Why = "a value that depends on the wave on some paths only"; + const EFFECT: Why = "a write by the wave's first lane other than its reservation"; + fn of(kind: &HashMap<Value, Wave>, v: Option<Value>) -> Wave { + v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain) + } + fn put(kind: &mut HashMap<Value, Wave>, v: Value, k: Wave) { + if k == Wave::Plain { + kind.remove(&v); + } else { + kind.insert(v, k); + } + } + let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base); + let why = |k: Wave| match k { + Wave::First => FIRST, + Wave::Total(_) => TOTAL, + Wave::Prefix => PREFIX, + _ => MIXED, + }; + // a mask (by its low dword) under which only a wave's first lane runs + let first_mask = |firsts: &HashSet<Value>, m: Option<Value>| { + m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| { + st.bools + .support(b) + .iter() + .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v))) + }) + }; + // One instruction outside a section: the kind of what it writes, and whether it is a + // first lane's reservation. + let step = |inst: &Inst, kind: &HashMap<Value, Wave>, firsts: &mut HashSet<Value>| -> Result<(Wave, bool), Why> { + let name = inst.name(); + let val = |op: &Operand| match *op { + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + _ => None, }; - if st - .bools - .support(when) - .iter() - .all(|a| matches!(a, Atom::Uniform(_))) - { + let ops: Vec<Operand> = match &inst.fields { + Fields::Valu(v) => v.src.clone(), + Fields::Sop { dst, src, .. } => { + let mut o = src.clone(); + if matches!(name, "s_addk_i32" | "s_mulk_i32") { + o.extend(dst.iter().copied()); + } + o + } + Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => { + data.iter().copied().collect() + } + _ => Vec::new(), + }; + let kinds: Vec<Wave> = ops.iter().map(|o| of(kind, val(o))).collect(); + // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide + // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it + // writes, which only the lanes outside EXEC keep. + let named: Vec<Value> = ops.iter().filter_map(&val).collect(); + for &(r, v) in &inst.reads { + let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r); + if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) { + continue; + } + let k = of(kind, Some(v)); + if wild(k) { + return Err(why(k)); + } + } + let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed); + let sum = |k: Wave| k == Wave::Total(Op::AddU); + let is_mask = |o: &Operand| { + val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v)) + }; + let mut reserved = false; + let out = match (name, &kinds[..]) { + ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First, + ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => { + Wave::Total(Op::AddU) + } + // bits of a mask below the lane; with -1 for the mask, the lane's number + ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => { + match (matches!(ops[0], Operand::Scalar { .. }), *b) { + (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix, + (false, Wave::Plain | Wave::Base) => Wave::Plain, + (_, k) => return Err(why(k)), + } + } + // nothing wave-dependent goes in; what derives from a reserved base stays marked + _ if !kinds.iter().any(|&k| wild(k)) => { + let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. }); + if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain } + } + ("v_mov_b32" | "s_mov_b32", [k]) => *k, + ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => { + // the lane whose own number is the first lane's + let lane = match (*a, *b) { + (Wave::First, k) if !wild(k) => &ops[1], + (k, Wave::First) if !wild(k) => &ops[0], + _ => return Err(why(w)), + }; + if !matches!(lane, Operand::Vector { .. }) { + return Err(FIRST); + } + let mask = match &inst.fields { + _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)), + Fields::Valu(v) => match v.dst { + Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)), + _ => None, + }, + _ => None, + }; + firsts.extend(mask); + Wave::Plain + } + ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) { + (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix, + (x, y) if sum(x) && sum(y) => x, + _ => return Err(why(w)), + }, + ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) { + (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain) => Wave::Prefix, + (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y, + _ => return Err(why(w)), + }, + ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) { + (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x, + _ => return Err(why(w)), + }, + ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x]) + if sum(*x) || *x == Wave::Prefix => + { + *x + } + ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => { + if *c == Wave::Base { Wave::Base } else { Wave::Prefix } + } + // the reservation: the first lane adds its wave's total to a shared counter + (_, [Wave::Total(op)]) if name.contains("_atomic_") => { + let want = match op { + Op::AddU => "buffer_atomic_add", + Op::MinU => "buffer_atomic_umin", + Op::MaxU => "buffer_atomic_umax", + Op::MinI => "buffer_atomic_smin", + Op::MaxI => "buffer_atomic_smax", + Op::Or => "buffer_atomic_or", + Op::And => "buffer_atomic_and", + Op::Xor => "buffer_atomic_xor", + _ => "", + }; + if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err(TOTAL); + } + reserved = true; + Wave::Base + } + _ => return Err(why(w)), + }; + Ok((out, reserved)) + }; + let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect(); + let order = crate::ir::reverse_postorder(&p.blocks); + let pass = |kind: &mut HashMap<Value, Wave>, firsts: &mut HashSet<Value>, check: bool| -> Result<(), (usize, Why)> { + for &b in &order { + let block = &p.blocks[b]; + for phi in &block.phis { + let mut k = Wave::Plain; + for (n, &a) in phi.args.iter().enumerate() { + let x = of(kind, Some(a)); + k = match (k, x) { + _ if n == 0 => x, + (k, x) if k == x => k, + (Wave::Plain, m @ (Wave::Base | Wave::Prefix)) + | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m, + _ => Wave::Mixed, + }; + } + put(kind, phi.value, k); + } + for (i, inst) in block.insts.iter().enumerate() { + // inside a whole-wave section: what the simulation found each value to be + if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) { + for &(_, w) in &inst.writes { + let k = match sec.shapes.get(&w) { + None => Wave::Mixed, + Some(&Shape::K(_)) => Wave::Plain, + Some(&Shape::Value(v)) => of(kind, Some(v)), + Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)), + Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Total(op), + // the first lane's own sum of a total is that total + Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op), + _ => Wave::Mixed, + }, + Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Prefix, + Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix, + _ => Wave::Mixed, + }, + Some(_) => Wave::Mixed, + }; + put(kind, w, k); + } + continue; + } + let name = inst.name(); + if name.starts_with("s_cbranch") { + continue; // with the block's exit, below + } + let (k, reserved) = match step(inst, kind, firsts) { + Ok(r) => r, + Err(why) if check => return Err((inst.machine.offset, why)), + Err(_) => (Wave::Mixed, false), + }; + // the same test as `Lower::inst`'s `effect` + let effect = matches!(inst.fields, Fields::Exp { .. }) + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || name.contains("store") + || name.contains("atomic") + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") + || name.starts_with("ds_swizzle") + || name.contains("permute")); + if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err((inst.machine.offset, EFFECT)); + } + let guarded = st.guards[b][i].is_some(); + for &(r, w) in &inst.writes { + let mut kw = match r { + // "some lane is counted" keeps the count's kind; any other SCC is one bit of data + Reg::Scc if !name.starts_with("s_bcnt1") => { + if wild(k) { Wave::Mixed } else { Wave::Plain } + } + _ => k, + }; + // a guarded write leaves the old value in the lanes outside EXEC + if guarded + && matches!(r, Reg::V(_)) + && kw == Wave::Plain + && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix) + { + kw = Wave::Mixed; + } + put(kind, w, kw); + } + } + // a branch on "some lane is counted": fine where the structure made it the lane's + // own bit (the mask is EXEC under a scalar condition) + if check + && let Some(last) = block.insts.last() + && last.name().starts_with("s_cbranch_scc") + && let Some(scc) = last.read(Reg::Scc) + && wild(of(kind, Some(scc))) + { + let own = matches!(st.exits[b], LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc))); + if !own { + return Err((last.machine.offset, TOTAL)); + } + } + } + Ok(()) + }; + let mut kind: HashMap<Value, Wave> = HashMap::new(); + let mut firsts: HashSet<Value> = HashSet::new(); + // to a fixpoint (values carried around loops), then once more to say what is wrong + let mut settled = false; + for _ in 0..16 { + let before = (kind.clone(), firsts.len()); + pass(&mut kind, &mut firsts, false)?; + if (&before.0, before.1) == (&kind, firsts.len()) { + settled = true; + break; + } + } + if !settled { + return Err((0, MIXED)); + } + pass(&mut kind, &mut firsts, true) +} + +/// Whether the last resort splits console waves the host waves cannot meet around +/// (`VICTORY_WAVE_FORCE_SPLIT=0`: those keep 64-lane waves and are refused by 32-lane hosts). +fn force_split_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_FORCE_SPLIT").is_none_or(|v| v != "0")) +} + +/// The mode of a group barrier the translation adds (host waves meeting): +/// a wait for the group with a shared-memory fence; the fence alone with +/// `VICTORY_GROUP_SYNC=0` ([`super::group_sync`]). +fn meeting_mode() -> u32 { + if super::group_sync() == 0 { 8 } else { 1 | 8 } +} + +/// LDS accesses of a console wave run as two host waves, where some sit in blocks that only +/// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a +/// group barrier) at its start and before its exit. `None` if barriers cannot keep the +/// console's order. +/// +/// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two +/// host waves keep that order if they meet between any two accesses of which one writes. A +/// barrier must be run by every thread, so it cannot stand in a lane branch's region; but +/// every way into and out of such a region passes a block all lanes run, and the waves meet +/// there: before the exit of an all-lane block into a region with LDS accesses, and at the +/// start of an all-lane block entered from one. Accesses in all-lane blocks get their own +/// barrier as before. What that cannot order is a write and a read inside one region (blocks +/// joined without an all-lane block between them): refused. +/// shortcut: two writes in one region are taken not to hit the same dword from both halves. +fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option<Vec<(bool, bool)>> { + let n = st.exits.len(); + let succ = |b: usize| -> Vec<usize> { + match st.exits[b] { + LaneExit::Jump(t) => vec![t], + LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken], + LaneExit::End | LaneExit::Indirect => Vec::new(), + } + }; + // regions: blocks not every lane runs, joined by the edges between them + let mut region: Vec<usize> = (0..n).collect(); + fn find(region: &mut [usize], mut b: usize) -> usize { + while region[b] != b { + region[b] = region[region[b]]; + b = region[b]; + } + b + } + for b in 0..n { + for t in succ(b) { + if !all[b] && !all[t] { + let (x, y) = (find(&mut region, b), find(&mut region, t)); + region[x] = y; + } + } + } + // per region: LDS reads, LDS writes + let mut reads = vec![false; n]; + let mut writes = vec![false; n]; + for (b, block) in p.blocks.iter().enumerate().take(n) { + if all[b] { continue; } - let mut seen = vec![false; n]; - let mut stack = succs[d].clone(); - while let Some(x) = stack.pop() { - if std::mem::replace(&mut seen[x], true) { + let r = find(&mut region, b); + for i in &block.insts { + let name = i.name(); + if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") { continue; } - if x == d || pd[d][x / 64] >> (x % 64) & 1 == 0 { - uniform[x] = false; + if name.starts_with("ds_read") { + reads[r] = true; + } else { + writes[r] = true; + } + } + } + if (0..n).any(|r| reads[r] && writes[r]) { + if std::env::var_os("VICTORY_WAVE_WHY").is_some() { + for r in (0..n).filter(|&r| reads[r] && writes[r]) { + let mut list = Vec::new(); + for (b, block) in p.blocks.iter().enumerate().take(n) { + if all[b] || find(&mut region, b) != r { + continue; + } + for i in &block.insts { + let name = i.name(); + if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") { + continue; + } + // the address register and the instruction that wrote it + let addr = match &i.fields { + Fields::Ds { addr: Some(Operand::Vector { reg, .. }), offset0, offset1, .. } => { + let made = i.read(Reg::V(*reg)).and_then(|v| { + p.blocks + .iter() + .flat_map(|bl| &bl.insts) + .find(|x| x.writes.iter().any(|w| w.1 == v)) + .map(|x| format!("{:#x} {}", x.machine.offset, x.name())) + }); + format!("v{reg} off {offset0}/{offset1} made by {}", made.as_deref().unwrap_or("an input or a phi")) + } + _ => "no address".to_string(), + }; + list.push(format!("{:#x} {name} [{addr}]", i.machine.offset)); + } + } + eprintln!("WAVE64-LDS region with reads and writes: {}", list.join("; ")); } - stack.extend(succs[x].iter().copied()); } + return None; } - uniform + let mut meet = vec![(false, false); n]; + for b in 0..n { + for t in succ(b) { + if all[b] && !all[t] { + let r = find(&mut region, t); + meet[b].1 |= reads[r] || writes[r]; + } else if !all[b] && all[t] { + let r = find(&mut region, b); + meet[t].0 |= reads[r] || writes[r]; + } + } + } + Some(meet) } -/// Iterations after which a loop is left (per entry into it), unless -/// [`super::loop_limit`] says otherwise. The console runs a loop as long as -/// its data says; data the host has not mirrored yet (a null view reads -/// zeros) can make that four billion iterations, which hangs the host GPU -/// until the driver resets it. A lane that reaches the limit leaves the -/// program as killed (a pixel discards). -// shortcut: a genuine loop of more iterations than this is cut short too. -pub(super) const LOOP_LIMIT: u32 = 1 << 20; +/// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its +/// own bit by its console lane. +fn lane_constant_masks(st: &Structured) -> bool { + let whens = st.exits.iter().filter_map(|e| match *e { + LaneExit::Branch { when, .. } => Some(when), + _ => None, + }); + let mut work: Vec<Bool> = st.guards.iter().flatten().flatten().copied().chain(whens).collect(); + // Through lane-mask joins too: an edge that brings a number or a constant lane set needs + // the lane's own bit of it. + // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such + // a program still stops with "a constant lane mask" or "an opaque lane mask". + let (mut seen, mut joins) = (HashSet::new(), HashSet::new()); + while let Some(g) = work.pop() { + if !seen.insert(g) { + continue; + } + for a in st.bools.support(g) { + match a { + Atom::Opaque(_) | Atom::Constant(_) => return true, + Atom::Phi(id) if joins.insert(id) => { + if let Some(edges) = st.phi_masks.get(&id) { + work.extend(edges.iter().copied()); + } + } + _ => {} + } + } + } + false +} -/// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar -/// compares, bit tests) are ballots of the lanes' booleans, taken where the -/// mask is written: structurisation's `active` masks hold only lanes that -/// reach that block, so the ballot misses none. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum MaskData { - /// Compute: host lane n is console lane n (the program declares the - /// console's wave size), so ballots are the console's masks bit for bit - /// and any use is exact. - Console, - /// Pixel and vertex programs: ballots over the host's wave, whatever its - /// size. Only uses that mean the same on any wave are allowed: counts, - /// the first lane, the count below a lane, equality (the HLSL wave - /// operations the console compiler expands). Lane numbers stay host - /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane). - Host, - /// Mesh programs: their lanes and waves (LDS per console wave) are the - /// console's but no host wave size can be declared. - None, +/// The widest wave the host GPU runs (0: not known – no host-specific forms); see +/// [`set_host_max_wave`]. +static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane +/// code stays inside 32-lane halves run in waves of 32 instead of being refused. +pub fn set_host_max_wave(lanes: u32) { + HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed); } -/// What a value holding a lane mask read as a number stops with. -const LANE_MASK: Why = "a lane mask read as data"; - -/// Samples whose level comes from derivatives across each quad of lanes. -fn implicit_derivatives(name: &str) -> bool { - matches!( - name, - "image_sample" - | "image_sample_cl" - | "image_sample_o" - | "image_sample_b" - | "image_sample_b_cl" - ) +thread_local! { + /// See [`take_needs`]. + static NEEDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) }; + /// See [`with_local_waves`]. + static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// See [`with_local_waves_any`]. + static LOCAL_ANY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; } -/// Instructions that read a lane mask (not EXEC implicitly, not a lane's -/// bit) as a number. -fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { +/// As [`with_local_waves`], with every other use of a lane mask as a number +/// and every lane read and write taken per host wave too: the program runs +/// as it would on a console of 32-lane waves, lanes numbered 0..31 or +/// 32..63 by half. Right for code that only relies on what HLSL's wave +/// operations promise; a program that takes one wave to be its whole +/// thread group gets per-half results. The last resort for programs that +/// do not translate otherwise. +pub(super) fn with_local_waves_any<R>(f: impl FnOnce() -> R) -> R { + // (also splits console waves around LDS the host waves cannot meet for: see `Lower::new`) + let was = LOCAL_ANY.replace(true); + let r = with_local_waves(f); + LOCAL_ANY.set(was); + r +} + +thread_local! { + /// While [`with_approximate_first_halves`] runs `f`. + static APPROX_FIRST_HALVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +thread_local! { + /// While [`with_masks_elsewhere`] runs `f`. + static MASKS_ELSEWHERE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` (a lowering) with a lane mask that holds lanes outside EXEC where +/// it is written read as the ballot of the lanes that reach the block that +/// writes it. Exact for the loop idiom that stopped 7f05ddab771799a9 at +/// 0x89ec (`s_and_saveexec` then `s_andn2 rest, rest, exec`: the lanes still +/// looping, every one of which reached the block); approximate for a mask +/// with bits for lanes that never get there (the complement of EXEC): those +/// read 0. `emit::translate` takes this only for programs that stop on such +/// a mask; `VICTORY_MASK_ELSEWHERE=0` refuses it. +pub(super) fn with_masks_elsewhere<R>(f: impl FnOnce() -> R) -> R { + let was = MASKS_ELSEWHERE.replace(true); + let r = f(); + MASKS_ELSEWHERE.set(was); + r +} + +/// Runs `f` (a lowering) with every first half of an interpolation that a +/// second half completes lowered as the whole pair: approximate where its +/// result is also read as data (P0 + i P10 on the console). `emit::translate` +/// takes this last, after the exact form (`io::raise_keeping_first_halves`) +/// did not translate; `VICTORY_FIRST_HALF=0` refuses it. +pub(super) fn with_approximate_first_halves<R>(f: impl FnOnce() -> R) -> R { + let was = APPROX_FIRST_HALVES.replace(true); + let r = f(); + APPROX_FIRST_HALVES.set(was); + r +} + +/// Runs `f` with console wave64 programs on 32-lane hosts lowered with each +/// host wave as a wave of its own ("local"): no exchange between the two +/// halves of a console wave, so no barriers and no need for every lane to +/// reach the code. What HLSL's wave operations promise holds for any +/// division of the threads into waves, and the idiom the title's compute +/// programs use them for does not care which wave a thread is in: count or +/// sum over the wave, the first lane reserves that many slots with an atomic +/// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix. +/// Each lane still gets a slot of its own; only the order differs. +/// Only that idiom's operations are lowered this way: a lane mask read as +/// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and +/// lane reads and writes outside whole-wave sections, stop the translation. +/// shortcut: where a count or sum goes is not checked. A program that uses +/// a wave-wide result as data for the whole console wave (a tile's maximum, +/// say, with one wave per thread group) gets its half's result. It is used +/// only for programs that do not translate otherwise. +pub(super) fn with_local_waves<R>(f: impl FnOnce() -> R) -> R { + let was = LOCAL_WAVES.replace(true); + let r = f(); + LOCAL_WAVES.set(was); + r +} + +/// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`, +/// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them +/// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA: +/// the last place of a result that is not exact is then one lower than the console's). +/// Off by default: it is exact but untried in a game run, and adds instructions to every +/// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact. +fn f16_nearest_on() -> bool { + #[cfg(test)] + if let Some(on) = TEST_F16_NEAREST.get() { + return on; + } + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1")) +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`f16_nearest_on`], for its thread only. + pub(super) static TEST_F16_NEAREST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; +} + +/// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before +/// ([`super::own_bits`]). +fn own_bits_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0")) +} + +/// Whether lowering uses the forms for an adapter limited to 32 lanes. +pub fn host_uses_wave32() -> bool { + #[cfg(test)] + if let Some(lanes) = TEST_HOST_WAVE.get() { + return lanes == 32; + } + HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed) == 32 +} + +#[cfg(test)] +thread_local! { + /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's). + pub(super) static TEST_HOST_WAVE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) }; +} + +pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + // (also a vector instruction reading that SCC, a v_cndmask on it say: + // codec_d, cool_fox 8cc31ab) + if matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_)) + && i.read(Reg::Scc).is_some_and(|v| st.scc_some.contains_key(&v)) + { + return true; + } let ops: Vec<&Operand> = match &i.fields { // A mask operation (its result a mask) is no data use. Fields::Sop { .. } @@ -472,50 +1198,105 @@ fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { }) } -/// A select or carry-in that needs the actual scalar mask words and console -/// lane index. -fn numeric_select(st: &Structured, inst: &Inst) -> bool { - let Fields::Valu(v) = &inst.fields else { - return false; - }; - let Some(&Operand::Scalar { code, .. }) = v.src.get(2) else { - return false; +/// The parameters packing 16-bit rows two per dword and where each lays +/// its elements out: (first row, [(dword, register, column, columns)]). +/// +/// The console gives every 16-bit element whole dwords. A parameter leads +/// with the first element of its first row, then the first element of its +/// second row. An element that shares a register behind another one (the +/// signature packs a short element into the free columns of an earlier +/// register) is NOT in that row's halves: it follows in the first +/// parameter, in row order, that has whole dwords left. +/// The title's packed pedestrian shaders show both cases: TEXCOORD7 (register 1, +/// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3 +/// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4, +/// column 3, behind the three columns of TEXCOORD4) in dword 3 of +/// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of +/// TEXCOORD4's second dword stays zero. +type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>; + +fn packed_layout(elements: &[SigElement], packs: &[(u8, Option<u8>)]) -> PackedLayout { + let of_row = |r: u8| { + let mut of: Vec<&SigElement> = elements + .iter() + .filter(|e| e.row == Some(u32::from(r))) + .collect(); + of.sort_by_key(|e| e.col); + of }; - if code == NULL { - return false; - } - match inst.name() { - "v_cndmask_b32" => inst - .writes - .first() - .is_some_and(|&(_, v)| !st.select_masks.contains_key(&v)), - "v_add_co_ci_u32" | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => inst - .read(Reg::S(code)) - .is_none_or(|m| !st.masks.contains_key(&m)), - _ => false, + let mut packs = packs.to_vec(); + packs.sort_unstable(); + packs.dedup_by_key(|p| p.0); + // Per parameter: its first row, the dwords used, the elements. + let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new(); + let mut behind = Vec::new(); + for &(a, b) in &packs { + let mut placed = Vec::new(); + let mut at = 0u8; + if !of_row(a).is_empty() { + for r in [Some(a), b].into_iter().flatten() { + let of = of_row(r); + let Some((lead, more)) = of.split_first() else { + continue; + }; + placed.push((at, r, lead.col, lead.cols)); + at += lead.cols.div_ceil(2); + behind.extend(more.iter().map(|e| (r, e.col, e.cols))); + } + } + layout.push((a, at, placed)); + } + behind.sort_unstable(); + for (r, col, cols) in behind { + let need = cols.div_ceil(2); + if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) { + p.2.push((p.1, r, col, cols)); + p.1 += need; + } } + layout.into_iter().map(|(a, _, of)| (a, of)).collect() } -/// Where half `h` (dword h / 2, the high half when odd) of a parameter -/// packing 16-bit rows `a` and `b` two per dword comes from: a row and -/// channel of `elements`, none for padding. Channel c of `a` is half c; -/// `b` starts at the dword after `a`'s last channel. -fn packed_half(elements: &[SigElement], a: u8, b: Option<u8>, h: u8) -> Option<(u8, u8)> { - let extent = |r: u8| { - elements - .iter() - .filter(|e| e.row == Some(u32::from(r))) - .map(|e| e.col + e.cols) - .max() +/// Where half `h` (dword h / 2, the high half when odd) of the parameter +/// whose first 16-bit row is `a` comes from: a register and column of +/// `elements`, none for padding ([`packed_layout`]; `packs` lists every +/// parameter packing two 16-bit rows per dword). +fn packed_half( + elements: &[SigElement], + packs: &[(u8, Option<u8>)], + a: u8, + h: u8, +) -> Option<(u8, u8)> { + let layout = packed_layout(elements, packs); + let (_, of) = layout.iter().find(|p| p.0 == a)?; + of.iter().find_map(|&(dword, row, col, cols)| { + let k = h.checked_sub(2 * dword)?; + (k < cols).then_some((row, col + k)) + }) +} + +/// The pixel inputs packing two 16-bit rows per dword, as (first row, +/// second row) ([`packed_layout`]). +fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option<u8>)> { + let StageIo::Ps { + inputs: entries, .. + } = io + else { + return Vec::new(); }; - let na = extent(a)?; - let a_halves = na.div_ceil(2) * 2; - if h < a_halves { - return (h < na).then_some((a, h)); - } - let b = b?; - let c = h - a_halves; - (c < extent(b)?).then_some((b, c)) + let partners = half_input_partners(io, inputs); + entries + .iter() + .filter(|i| i.fp16 && i.pack2) + .map(|i| { + let b = if i.row2 != i.row { + Some(i.row2) + } else { + partners.get(&i.row).copied() + }; + (i.row, b) + }) + .collect() } /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]): @@ -550,12 +1331,45 @@ fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Opti .collect() } +/// Pixel inputs packing two 16-bit rows per dword whose second row the +/// metadata leaves out (`row2` = `row`): as for outputs +/// ([`half_outputs`]), the next 16-bit row of the signature that no input +/// entry names, taken in row order (rows the metadata does give are taken +/// first). +fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap<u8, u8> { + let StageIo::Ps { + inputs: entries, .. + } = io + else { + return HashMap::new(); + }; + let packed = || entries.iter().filter(|i| i.fp16 && i.pack2); + let mut free: Vec<u8> = inputs + .iter() + .filter(|e| e.half && e.kind == 0) + .filter_map(|e| u8::try_from(e.row?).ok()) + .filter(|&r| !entries.iter().any(|i| i.row == r)) + .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r)) + .collect(); + free.sort_unstable(); + free.dedup(); + let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect(); + missing.sort_by_key(|i| i.row); + let mut partners = HashMap::new(); + for i in missing { + if let Some(k) = free.iter().position(|&r| r > i.row) { + partners.insert(i.row, free.remove(k)); + } + } + partners +} + fn unsupported(offset: usize, what: Why) -> Stop { Stop::Fail(ShaderError::Unsupported { offset, what }) } impl<'a> Lower<'a> { - fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>, numeric_selects: bool) -> Self { + fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self { let p = x.p; let mut phi_at = HashMap::new(); for (b, block) in p.blocks.iter().enumerate() { @@ -572,13 +1386,27 @@ impl<'a> Lower<'a> { && (i.name().contains("store") || i.name().contains("atomic")) }); let mut console_lanes = false; - let (mut emulated, mut wave64_refused) = (None, false); + // LDS accesses get a group barrier each (a console wave split in two host waves) + let mut split_lds = false; + // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and + // where the host waves meet around those branches (`lds_meetings`) + let mut lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)> = None; + // a console wave64 program in two host waves of 32 (`exchange`) + let mut exchange: Option<(u32, bool, Vec<bool>)> = None; + // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter + let mut halves: Option<u32> = None; if let StageIo::Cs(cs) = x.native.io { s.threads = Some(cs.threads); s.lds_dwords = cs.lds_bytes() / 4; // Code reading other lanes needs the console's wave size and // lane order; so do lane masks read as numbers, and LDS shared // within one wave, where the console compiler leaves out barriers. + let scc_phi_mask = p.blocks.iter().any(|b| { + b.phis.iter().any(|phi| { + phi.reg == Reg::Scc + && phi.args.iter().any(|v| x.st.scc_some.contains_key(v)) + }) + }); console_lanes = insts().any(|i| { let n = i.name(); n.starts_with("ds_swizzle") @@ -586,53 +1414,176 @@ impl<'a> Lower<'a> { || n.starts_with("v_permlane") || n.starts_with("v_mbcnt") || matches!(n, "v_readlane_b32" | "v_writelane_b32") - || implicit_derivatives(n) || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some()) || reads_mask_as_data(x.st, i) - || numeric_selects && numeric_select(x.st, i) - }) || { - // Masks held as numbers or constant lane sets: the lane - // tests its own bit by its console lane. - let whens = x.st.exits.iter().filter_map(|e| match *e { - LaneExit::Branch { when, .. } => Some(when), - _ => None, - }); - let mut all: Vec<Bool> = - x.st.guards - .iter() - .flatten() - .flatten() - .copied() - .chain(whens) - .collect(); - all.sort_unstable(); - all.dedup(); - all.into_iter().any(|g| { - x.st.bools - .support(g) - .iter() - .any(|a| matches!(a, Atom::Opaque(_) | Atom::Constant(_))) - }) - }; - let wave = if x.native.wave64 { 64 } else { 32 }; - let lanes = cs.threads.iter().product::<u32>(); - let one_wave = lanes <= wave; - if console_lanes || one_wave && s.lds_dwords > 0 { - if wave == 64 && !x.host_wave64 { - if one_wave { - emulated = Some(Emulated { - lanes, - uniform: uniform_blocks(x.st), - slots: None, + }) || scc_phi_mask + || lane_constant_masks(x.st) + // (a branch the wave takes together asks the wave) + || !x.st.wide.is_empty(); + let mut wave = if x.native.wave64 { 64 } else { 32 }; + let group = cs.threads.iter().product::<u32>(); + let one_wave = group <= wave; + // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console + // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows, + // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs + // exactly in waves of 32: the thread relabelling makes each host wave one half of a + // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`, + // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant + // masks), nor when LDS may be shared within the console wave without barriers (a + // group over 32 threads with LDS): those still need 64-lane waves. + if wave == 64 && host_uses_wave32() && (console_lanes || one_wave && s.lds_dwords > 0) { + let crosses = insts().any(|i| { + let n = i.name(); + n.starts_with("v_mbcnt") + || matches!(n, "v_readlane_b32" | "v_writelane_b32") + || n.starts_with("ds_permute") + || n.starts_with("ds_bpermute") + || reads_mask_as_data(x.st, i) + }) || scc_phi_mask + || lane_constant_masks(x.st) + || !x.st.wide.is_empty(); + if !crosses && (s.lds_dwords == 0 || group <= 32) { + wave = 32; + } else { + // (Groups of several console waves too: each console wave is two host + // waves, which exchange through their own pair of dwords.) + // LDS the console shares within its one wave without barriers: split into + // two waves of 32, a group barrier before every LDS access keeps their order + // – where every thread of the group gets there (no lane branch around it, + // no guard), else a barrier would hang the group + let lds = |i: &Inst| { + matches!(i.fields, Fields::Ds { .. }) + && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute")) + }; + // The last resort (`LOCAL_ANY`, every mask and lane read per host wave) splits + // the console wave even where the host waves cannot meet around some LDS + // accesses (they meet where every lane runs, as before; not inside those + // lane branches, where a barrier would hang the group), and in programs with + // an indirect exit (no block taken as one every lane runs). Approximate where + // one half reads in such a branch what the other half wrote there without a + // barrier; the alternative is a pipeline a 32-lane host refuses + // (`WaveSize(64)`, E_INVALIDARG: six in every run on an RTX 4060, their + // dispatches dropped). `VICTORY_WAVE_FORCE_SPLIT=0` keeps those refused. + let force = LOCAL_ANY.get() && force_split_on(); + let all_found = all_lane_blocks(x.st).or_else(|| force.then(|| vec![false; p.blocks.len()])); + if let Some(all) = all_found { + let ok = p.blocks.iter().enumerate().all(|(b, blk)| { + blk.insts.iter().all(|inst| { + !lds(inst) || all.get(b).copied().unwrap_or(false) + }) }); - } else { - wave64_refused = true; + let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok; + if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) { + lds_meet = Some((all.clone(), meet)); + lds_ok = true; + } + if !lds_ok { + // (the blocks whose LDS accesses not every lane runs: with the + // branches around them taken wave-wide they get their barriers) + for (b, blk) in p.blocks.iter().enumerate() { + if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) { + need(b); + } + } + } + if !lds_ok && force { + lds_meet = Some((all.clone(), vec![(false, false); p.blocks.len()])); + lds_ok = true; + } + if lds_ok { + wave = 32; + split_lds = s.lds_dwords > 0 && group > 32; + if crosses { + // lanes 32..63 are the other host wave: masks, lane reads and lane + // numbers go through two exchange dwords past the program's LDS + exchange = Some((s.lds_dwords, group <= 32, all)); + s.lds_dwords += 2 * group.div_ceil(64); + } + } } - } else { - s.wave_size = Some(wave); } + // `VICTORY_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason) + if wave == 64 && std::env::var_os("VICTORY_WAVE_WHY").is_some() { + let mut why: Vec<&str> = Vec::new(); + for i in insts() { + let n = i.name(); + let r = if n.starts_with("v_mbcnt") { + "v_mbcnt" + } else if n == "v_readlane_b32" { + "v_readlane" + } else if n == "v_writelane_b32" { + "v_writelane" + } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") { + "ds_(b)permute" + } else if reads_mask_as_data(x.st, i) { + "mask as data" + } else { + continue; + }; + if !why.contains(&r) { + why.push(r); + } + } + if lane_constant_masks(x.st) { + why.push("lane-constant mask"); + } + if s.lds_dwords > 0 && group > 32 { + why.push("LDS in a group over 32"); + match all_lane_blocks(x.st) { + None => why.push("an indirect exit"), + Some(all) if lds_meetings(p, x.st, &all).is_none() => { + why.push("an LDS read and write in one lane-branch region") + } + Some(_) => {} + } + } + why.sort_unstable(); + eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", ")); + } + } + if wave == 32 && x.native.wave64 { + // console threads go to host waves in the order the waves take them (`wave_base`) + halves = Some(s.lds_dwords); + s.lds_dwords += 1; + } + if console_lanes || one_wave && s.lds_dwords > 0 { + s.wave_size = Some(wave); } } + // The title's barriers a thread of the group may never reach, which + // leaves the others waiting on the host: those in blocks some lanes + // do not run, and all of them in a program with a loop closed by a + // plain jump (a lane still in it at the iteration limit leaves the + // program there, `abort_block`). + let fence_only: HashSet<usize> = if insts().any(|i| i.name() == "s_barrier") { + let order = crate::ir::reverse_postorder(&p.blocks); + let mut place = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + place[b] = n; + } + let back = |from: usize, to: usize| { + let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX); + at(from) != usize::MAX && at(to) <= at(from) + }; + let cut_short = x + .st + .exits + .iter() + .enumerate() + .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t))); + let all = all_lane_blocks(x.st); + (0..p.blocks.len()) + .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier")) + .filter(|&b| { + cut_short + || all + .as_ref() + .is_none_or(|all| !all.get(b).copied().unwrap_or(false)) + }) + .collect() + } else { + HashSet::new() + }; let mut no_barrier = HashSet::new(); if let StageIo::Ms(ms) = &x.native.io { s.prims = x.prims.clone(); @@ -678,6 +1629,7 @@ impl<'a> Lower<'a> { } } } + let entry = s.entry; Lower { s, x, @@ -687,6 +1639,8 @@ impl<'a> Lower<'a> { floats: HashMap::new(), block: vec![None; p.blocks.len()], cur: 0, + body_entry: entry, + partial_active: None, bools: HashMap::new(), lane_bits: HashMap::new(), phi_at, @@ -694,10 +1648,12 @@ impl<'a> Lower<'a> { pending_masks: Vec::new(), data_phis: Vec::new(), read_phis: HashSet::new(), + stale: HashSet::new(), params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), user_data: None, user_reads: BTreeMap::new(), - root_sizes: HashMap::new(), + half_views: Default::default(), + halves_only: Default::default(), samplers: Vec::new(), descriptors: x .res @@ -707,8 +1663,25 @@ impl<'a> Lower<'a> { .collect(), scalar: x.res.scalar.iter().copied().collect(), exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), - interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(), + interps: { + let mut m: HashMap<Site, &Interp> = x.io.interps.iter().map(|(s, i)| (*s, i)).collect(); + // A first half whose result is also read as data (an f16 second half keeps + // the other half of its dst, PS_DeferredTextured): evaluated as the pair it + // starts. Approximate for those other bits (P0 + i P10 on the console); a + // first half only the second half reads is gone before lowering. + if APPROX_FIRST_HALVES.get() && std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") { + for (_, i) in &x.io.interps { + if let Interp::Interpolated { first, .. } = i { + for s in first { + m.entry(*s).or_insert(i); + } + } + } + } + m + }, handles: HashMap::new(), + strides: HashMap::new(), edges: HashMap::new(), exported: vec![false; p.blocks.len()], rpo: vec![usize::MAX; p.blocks.len()], @@ -716,9 +1689,29 @@ impl<'a> Lower<'a> { writes_uavs, src0: None, console_lanes, - numeric_selects, + split_lds, + lds_meet, + local: exchange.is_some() && LOCAL_WAVES.get(), + local_ok: false, + local_any: LOCAL_ANY.get(), + uniform: match &exchange { + Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), + _ => HashSet::new(), + }, + own_bits: match &exchange { + Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => { + super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some()) + } + _ => Default::default(), + }, + exchange, + clane: None, + pair: None, + halves, + wave_base: None, flat: None, no_barrier, + fence_only, half_outputs: half_outputs(&x.native.io, &x.outputs), mask_data: match x.native.stage { HwStage::Cs => MaskData::Console, @@ -746,13 +1739,6 @@ impl<'a> Lower<'a> { code_table: None, counters: HashMap::new(), abort: None, - spin: HashSet::new(), - #[cfg(test)] - spun: 0, - emulated, - wave64_refused, - guard_depth: 0, - ret: None, } } @@ -822,6 +1808,9 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) { + return self.memory_flat(inst, b, i); + } let rest = name .strip_prefix("global_load_") .ok_or("a global memory write")?; @@ -840,7 +1829,7 @@ impl<'a> Lower<'a> { .scalar .get(&(b, i)) .ok_or("an untracked global address")?; - let guard = self.guard(b, i)?; + let guard = self.effect_guard(b, i)?; let Some(Operand::Vector { reg, .. }) = *dst else { return Err("a global load result"); }; @@ -858,28 +1847,10 @@ impl<'a> Lower<'a> { bits: 0, words: [0, 0], }; - Some(self.handle((b, i), &src, false, (11, 0))?) - }; - // Root views: the dwords read checked against the view's size. - let root = if a.param == CODE { - None - } else { - self.root_view_size(&Source::Built { - address: a, - bits: 0, - words: [0, 0], - }) - }; - let (off, ok) = match root { - Some(size) => { - let bytes = if sub.is_some() { 4 } else { 4 * n }; - let not3 = self.s.m.i32(!3); - let at = self.s.m.bin(c, Bin::And, off, not3); - let (ok, _) = self.in_root_view(size, at, bytes); - let zero = self.s.m.i32(0); - (self.s.m.select(c, ok, off, zero), Some(ok)) + if let Some(bias) = self.root_bias(a.param) { + off = self.s.m.bin(c, Bin::Add, off, bias); } - None => (off, None), + Some(self.handle((b, i), &src, false, (11, 0))?) }; let dword = |l: &mut Self, byte: V| -> Result<V, Why> { match h { @@ -900,6 +1871,12 @@ impl<'a> Lower<'a> { } } }; + if let (None, Some(h), true) = (sub, h, n > 1 && Self::wide_loads()) { + for (k, x) in self.raw_dwords(h, off, n).into_iter().enumerate() { + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } for k in 0..n { let x = match sub { None => { @@ -922,7 +1899,6 @@ impl<'a> Lower<'a> { .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left) } }; - let x = self.zero_unless(ok, x); self.write(inst, Reg::V(reg + k as u8), x, guard); } Ok(()) @@ -973,7 +1949,8 @@ impl<'a> Lower<'a> { for &(_, w) in &inst.writes { let val = if self.section_out.contains(&w) { let shape = self.sections[&b][&start].shapes.get(&w).copied(); - match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh)) { + let own = self.own_bits.totals.contains(&w); + match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) { Ok(x) => Val::I32(x), Err(why) => Val::Missing(why), } @@ -988,12 +1965,19 @@ impl<'a> Lower<'a> { /// host's active lanes: the console's result with console lanes; on /// another wave size, what the HLSL wave operation the console compiler /// expanded gives on that wave. - fn shape(&mut self, shape: super::wave::Shape) -> Result<V, Why> { + /// + /// `own`: a wave OR that only steers a loop over each lane's own bits + /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is + /// this host wave's. + fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result<V, Why> { use super::wave::{Op, Shape}; let (op, src, mask, ident, prefix) = match shape { Shape::K(k) => return Ok(self.s.m.i32(k)), Shape::Value(v) => return self.i32_of(v), Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), + Shape::ActiveF64(lo, hi, mask, high) => { + return self.active_f64_sum(lo, hi, mask, high); + } Shape::Masked(src, mask, ident) => { let c = self.cur; let &m = self @@ -1002,7 +1986,13 @@ impl<'a> Lower<'a> { .masks .get(&mask) .ok_or("a wave reduction's untracked mask")?; - let on = self.boolean(m, c)?; + let mut on = self.boolean(m, c)?; + // (EXEC on entry leaves out the threads past a DispatchX count) + if let Some(active) = self.partial_active + && self.x.st.active.contains(&mask) + { + on = self.s.m.bin(c, Bin::And, on, active); + } let x = self.i32_of(src)?; let id = self.s.m.i32(ident); return Ok(self.s.m.select(c, on, x, id)); @@ -1011,7 +2001,18 @@ impl<'a> Lower<'a> { (op, src, mask, ident, Some(inclusive)) } }; - if self.mask_data == MaskData::None { + // Mesh: no host wave size can be declared, so a reduction is over this host wave + // only. A minimum or maximum is taken that way: the compiler's "next distinct + // value" loop (the wave's minimum, then the lanes that hold it) serves every + // lane however the lanes are divided into waves. A sum, a bit reduction or a + // prefix would be of part of a console wave: still refused. + if self.mask_data == MaskData::None + && (prefix.is_some() + || !matches!( + op, + Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF + )) + { return Err("a wave reduction in a mesh shader"); } let c = self.cur; @@ -1021,14 +2022,22 @@ impl<'a> Lower<'a> { .masks .get(&mask) .ok_or("a wave reduction's untracked mask")?; - let on = self.boolean(m, c)?; + let mut on = self.boolean(m, c)?; + if let Some(active) = self.partial_active + && self.x.st.active.contains(&mask) + { + on = self.s.m.bin(c, Bin::And, on, active); + } let x = self.i32_of(src)?; let id = self.s.m.i32(ident); let x = self.s.m.select(c, on, x, id); - if self.emulated.is_some() { - return self.emulated_shape(op, x, prefix); - } self.s.flags |= flags::WAVE_OPS; + if op == Op::AddH { + return match prefix { + Some(_) => Err("a wave prefix of an operation other than a sum"), + None => self.half_sum(x), + }; + } let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF); let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); let arg = if float { self.as_float(x) } else { x }; @@ -1081,80 +2090,286 @@ impl<'a> Lower<'a> { ) } }; + // two host waves of 32 hold the console's 64 lanes: their results combine + let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) { + // this host wave's own result (and prefix): each wave on its own, or a group of + // 32 threads or fewer, which one host wave holds whole (combining with the 0 a + // missing half "gives" broke AND, MIN and signed MAX) + r + } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) { + // each thread walks the bits of this value and works only at its own, which the + // host wave's OR holds: the same run as with the console wave's OR + r + } else if self.exchange.is_some() { + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a wave reduction where not every lane runs"); + } + let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v }; + let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v }; + match prefix { + Some(_) => { + // the upper half adds the lower half's total to its prefix + let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float))); + let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]); + let tb = bits(self, total); + let c = self.cur; + let (lo, _) = self.exchange_halves(c, tb); + let lo = back(self, lo); + let cl = self.console_lane(); + let k32 = self.s.m.i32(32); + let upper = self.s.m.cmp(c, pred::IUGE, cl, k32); + let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) }; + let add = self.s.m.select(c, upper, lo, zero); + self.s.m.bin(c, Bin::Add, r, add) + } + None => { + let rb = bits(self, r); + let c = self.cur; + let (lo, hi) = self.exchange_halves(c, rb); + let (lo, hi) = (back(self, lo), back(self, hi)); + match op { + Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi), + Op::Or => self.s.m.bin(c, Bin::Or, lo, hi), + Op::And => self.s.m.bin(c, Bin::And, lo, hi), + Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi), + _ => { + // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40 + let code = match op { + Op::MaxF => 35, + Op::MinF => 36, + Op::MinU => 40, + Op::MaxU => 39, + Op::MinI => 38, + _ => 37, + }; + self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi]) + } + } + } + } + } else { + r + }; Ok(if float { self.as_int(r) } else { r }) } - /// [`Emulated`]: the reduction (or, with `prefix` set to whether it is - /// inclusive, the prefix sum) of `x` over the console lanes; lanes - /// outside the operation's mask already hold its identity. - fn emulated_shape( + /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere), + /// returning the low (`!high`) or high (`high`) 32-bit word. + fn active_f64_sum( &mut self, - op: super::wave::Op, - x: V, - prefix: Option<bool>, + lo: Value, + hi: Value, + mask: Value, + high: bool, ) -> Result<V, Why> { - use super::wave::Op; + if self.mask_data == MaskData::None { + return Err("a wave reduction in a mesh shader"); + } let c = self.cur; - self.emulated_here(self.cur_ir, c)?; - if prefix.is_some() && !matches!(op, Op::AddU | Op::AddF) { - return Err("a wave prefix of an operation other than a sum"); + let &m = self + .x + .st + .masks + .get(&mask) + .ok_or("a wave reduction's untracked mask")?; + let mut on = self.boolean(m, c)?; + if let Some(active) = self.partial_active + && self.x.st.active.contains(&mask) + { + on = self.s.m.bin(c, Bin::And, on, active); } - let vals = self.gather(c, x); - let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF); - let me = self.mesh_thread(); - let mut acc: Option<V> = None; - for (n, v) in vals.into_iter().enumerate() { - let v = if float { self.as_float(v) } else { v }; - let v = match prefix { - Some(inclusive) => { - // Lanes below this one (and this one when inclusive). - let k = self.s.m.i32(n as u32); - let p = if inclusive { pred::IULE } else { pred::IULT }; - let below = self.s.m.cmp(c, p, k, me); - let zero = if float { - self.s.m.f32(0) - } else { - self.s.m.i32(0) - }; - self.s.m.select(c, below, v, zero) - } - None => v, - }; - acc = Some(match acc { - None => v, - Some(a) => match op { - Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, a, v), - Op::Or => self.s.m.bin(c, Bin::Or, a, v), - Op::And => self.s.m.bin(c, Bin::And, a, v), - Op::Xor => self.s.m.bin(c, Bin::Xor, a, v), - Op::MaxF => self.binary(35, a, v), - Op::MinF => self.binary(36, a, v), - Op::MinU | Op::MaxU | Op::MinI | Op::MaxI => { - let p = match op { - Op::MinU => pred::IULT, - Op::MaxU => pred::IUGT, - Op::MinI => pred::SLT, - _ => pred::SGT, - }; - let keep = self.s.m.cmp(c, p, a, v); - self.s.m.select(c, keep, a, v) - } - }, - }); + let lo = self.i32_of(lo)?; + let hi = self.i32_of(hi)?; + let z = self.s.m.i32(0); + let lo = self.s.m.select(c, on, lo, z); + let hi = self.s.m.select(c, on, hi, z); + self.s.flags |= flags::WAVE_OPS | flags::DOUBLES; + let f64t = self.s.m.double(); + let i32t = self.s.t.i32; + let split_ty = self + .s + .m + .named_struct("dx.types.splitdouble", vec![i32t, i32t]); + let arg = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]); + let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0)); + let sum = self + .s + .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]); + let split = self + .s + .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]); + let mut r_lo = self.s.m.extract(c, split, 0); + let mut r_hi = self.s.m.extract(c, split, 1); + if self.exchange.is_some() { + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a wave reduction where not every lane runs"); + } + let (lo0, lo1) = self.exchange_halves(self.cur, r_lo); + let (hi0, hi1) = self.exchange_halves(self.cur, r_hi); + let c = self.cur; + let d0 = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]); + let d1 = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]); + let total = self.s.m.bin(c, Bin::Add, d0, d1); + let split = self + .s + .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]); + r_lo = self.s.m.extract(c, split, 0); + r_hi = self.s.m.extract(c, split, 1); } - let r = acc.ok_or("a wave reduction over no lanes")?; - Ok(if float { self.as_int(r) } else { r }) + Ok(if high { r_hi } else { r_lo }) } - fn run(mut self) -> Result<Lowered, Stop> { - if self.wave64_refused { - return Err(unsupported( - 0, - "a compute group of several 64-lane waves that reads across lanes \ - on a host without 64-lane waves", - )); + /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's + /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest + /// ([`Self::f16_nearest`]). + fn add_halves(&mut self, a: V, b: V) -> V { + let c = self.cur; + let f32t = self.s.t.f32; + let low = self.s.m.i32(0xFFFF); + let wide = |l: &mut Self, x: V| { + let h = l.s.m.bin(c, Bin::And, x, low); + l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]) + }; + let (fa, fb) = (wide(self, a), wide(self, b)); + let f = self.s.m.bin(c, Bin::Add, fa, fb); + self.f16_nearest(f) + } + + /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the + /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to + /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes + /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves; + /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the + /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange + /// their halves' sums for the last addition. The high half of the result is lane 0's, + /// which no `v_add_f16` writes. + /// That needs every lane of a full wave there to be read: refused where not every lane + /// runs, in a thread group that does not fill its waves, and for each half-wave on its + /// own (half a sum is no sum). + fn half_sum(&mut self, x: V) -> Result<V, Why> { + const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs"; + let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?; + if threads.iter().product::<u32>() % 64 != 0 { + return Err("a wave sum of 16-bit floats in a wave that is not full"); + } + if self.local && !self.local_any { + return Err("a wave sum of 16-bit floats in a half-wave"); + } + // the last resort: this host wave's half of the sum, its own 32 lanes (approximate) + let own_half = self.local && self.local_any; + // two host waves of 32 that exchange, or one host wave of 64 lanes + let halves = match (&self.exchange, self.s.wave_size) { + _ if own_half => true, + (Some((_, false, _)), _) => true, + (None, Some(64)) if self.x.p.wave64 => false, + _ => return Err("a wave sum of 16-bit floats on these waves"), + }; + let every = if own_half { + true + } else if halves { + self.all_lanes(self.cur_ir) + } else { + all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false)) + }; + if !every { + if halves { + need(self.cur_ir); + return Err(WHERE); + } + return Ok(self.half_sum_present(x)); } + let c = self.cur; + let i32t = self.s.t.i32; + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let mut sum = x; + for step in 0..if halves { 5 } else { 6 } { + let bit = self.s.m.i32(1 << step); + let partner = self.s.m.bin(c, Bin::Xor, lane, bit); + let theirs = self.read_lane(sum, partner); + sum = self.add_halves(sum, theirs); + } + let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); + let first = self.read_lane(x, zero); + let first = self.s.m.bin(c, Bin::And, first, high); + let sum = self.s.m.bin(c, Bin::And, sum, low); + let mine = self.s.m.bin(c, Bin::Or, first, sum); + if !halves || own_half { + return Ok(mine); + } + let (lo, hi) = self.exchange_halves(c, mine); + let c = self.cur; + let total = self.add_halves(lo, hi); + let total = self.s.m.bin(c, Bin::And, total, low); + let first = self.s.m.bin(c, Bin::And, lo, high); + Ok(self.s.m.bin(c, Bin::Or, first, total)) + } + + /// [`Self::half_sum`] in one host wave of 64 where some lanes have left (a thread past + /// the end of the data returns early): the console runs the sum in every lane, a lane + /// outside EXEC with +0, so after step k every lane of an aligned run of 2^k lanes holds + /// that run's partial sum, the lanes that left included. A lane reads its partner run's + /// sum from the first lane of that run that is here, and +0 where none is (every lane of + /// the run left, so its terms were all +0). Lane 0's high half likewise: 0 if it left. + fn half_sum_present(&mut self, x: V) -> V { + let c = self.cur; + let i32t = self.s.t.i32; + self.s.flags |= flags::WAVE_OPS; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let here = self.s.m.bool(true); + let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]); + let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1)); + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k)); + // The lanes of the run of `size` lanes at `base` that are here, from bit 0. + let present = |l: &mut Self, base: V, size: u32| -> V { + let upper = l.s.m.cmp(c, pred::IUGE, base, k32); + let word = l.s.m.select(c, upper, bhi, blo); + let at = l.s.m.bin(c, Bin::And, base, k31); + let bits = l.s.m.bin(c, Bin::LShr, word, at); + if size >= 32 { + bits + } else { + let m = l.s.m.i32((1u32 << size) - 1); + l.s.m.bin(c, Bin::And, bits, m) + } + }; + let mut sum = x; + for step in 0..6u32 { + let size = 1u32 << step; + let (bit, run) = (self.s.m.i32(size), self.s.m.i32(!(size - 1))); + let other = self.s.m.bin(c, Bin::Xor, lane, bit); + let base = self.s.m.bin(c, Bin::And, other, run); + let bits = present(self, base, size); + // FirstbitLo (dx.op 32): the run's first lane that is here + let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]); + let any = self.s.m.cmp(c, pred::NE, bits, zero); + let first = self.s.m.select(c, any, first, zero); + let from = self.s.m.bin(c, Bin::Add, base, first); + let theirs = self.read_lane(sum, from); + let theirs = self.s.m.select(c, any, theirs, zero); + sum = self.add_halves(sum, theirs); + } + let (high, low, one) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(1)); + let lane0 = self.s.m.bin(c, Bin::And, blo, one); + let lane0 = self.s.m.cmp(c, pred::NE, lane0, zero); + let first = self.read_lane(x, zero); + let first = self.s.m.select(c, lane0, first, zero); + let first = self.s.m.bin(c, Bin::And, first, high); + let sum = self.s.m.bin(c, Bin::And, sum, low); + self.s.m.bin(c, Bin::Or, first, sum) + } + + fn run(mut self) -> Result<Lowered, Stop> { let p = self.x.p; + self.halves_only = self.places_read_as_halves(); let order = crate::ir::reverse_postorder(&p.blocks); for (n, &b) in order.iter().enumerate() { self.rpo[b] = n; @@ -1166,8 +2381,7 @@ impl<'a> Lower<'a> { self.s.m.new_block() }); } - // Loop headers count iterations (`LOOP_LIMIT`; spin waits less). - self.spin = super::spin::spin_loops(p); + // Loop headers count iterations (`LOOP_LIMIT`). for &b in &order { let header = p.blocks[b] .preds @@ -1182,9 +2396,26 @@ impl<'a> Lower<'a> { self.cur = self.s.entry; self.find_sections(); self.inputs()?; + // A compute program that reads its group id x may run spread across + // z (`USER_DISPATCH_SPREAD`). Not a spilled one (the builder's + // stages, near the root signature's 64 dwords), nor one whose first + // block is a loop header (its counter sits in the entry block). + if self.x.native.stage == HwStage::Cs + && self.user_first() == 0 + && !self.counters.contains_key(&order[0]) + && self.x.io.inputs.iter().any(|&(_, i)| i == Input::GroupId(0)) + { + self.cs_spread_prologue(); + self.block[order[0]] = Some(self.cur); + } if let Some(mesh) = self.s.mesh { self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; self.block[order[0]] = Some(self.cur); + } else if self.x.native.stage == HwStage::Cs && crate::spill::is_spilled(self.x.native) { + // The structure builder's stages: a DispatchX may name threads, + // not groups (`USER_DISPATCH_THREADS`; fork pull request #646). + // They never take the spread prologue above (`user_first`). + self.dispatch_threads_prologue(&order); } for &b in &order { self.cur = self.block[b].expect("reachable"); @@ -1213,6 +2444,9 @@ impl<'a> Lower<'a> { }; self.vals.insert(phi.value, val); } + if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) { + self.lds_meeting(); + } let mut i = 0; while i < p.blocks[b].insts.len() { self.inst(b, i)?; @@ -1226,6 +2460,9 @@ impl<'a> Lower<'a> { i += 1; } self.mask_ok = self.mask_data == MaskData::Console; + if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) { + self.lds_meeting(); + } self.tail[b] = Some(self.cur); self.exit(b)?; } @@ -1234,46 +2471,26 @@ impl<'a> Lower<'a> { self.s.samplers = self.samplers.len() as u32; let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect(); + let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect(); + let half_views = std::mem::take(&mut self.half_views).into_iter().collect(); let cmp_samplers = self.s.cmp_samplers; - #[cfg(test)] - let has_isnan_op = self.s.m.has_dx_op("dx.op.isSpecialFloat.f32", 8); - #[cfg(test)] - let has_fcmp_uno = self.s.m.has_cmp(pred::UNO); - #[cfg(test)] - let has_iugt = self.s.m.has_cmp(pred::IUGT); - #[cfg(test)] - let handle_props = { - let mut h: Vec<_> = self.handles.iter().map(|(k, v)| (*v, k.4)).collect(); - h.sort_unstable(); - h.into_iter().map(|(_, p)| p).collect() - }; + let wave_size = self.s.wave_size; Ok(Lowered { + wave_size, cmp_samplers, root_cbvs, root_srvs, + root_uavs, + half_views, #[cfg(test)] nonuniform_handles: self.s.nonuniform_handles, #[cfg(test)] heap_props: std::mem::take(&mut self.s.heap_props), #[cfg(test)] wave_ops: self.s.flags & flags::WAVE_OPS != 0, - #[cfg(test)] - funcs: self.s.m.func_names(), - #[cfg(test)] - bounded_prims: self.s.bounded_prims, - #[cfg(test)] - spin_loops: self.spun, dxil: self.s.finish(), user_data, samplers: self.samplers, - #[cfg(test)] - has_isnan_op, - #[cfg(test)] - has_fcmp_uno, - #[cfg(test)] - has_iugt, - #[cfg(test)] - handle_props, }) } @@ -1292,6 +2509,11 @@ impl<'a> Lower<'a> { for &(reg, v) in &self.x.p.inputs { let val = match reg { Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use + // Most programs only interpolate with them: loaded on first + // use as a value (`get`). + Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => { + continue; + } Reg::S(n) => match io_inputs.get(&v) { Some(&input) => self.input(input), // Above the SGPRs the hardware initializes, a register @@ -1302,6 +2524,10 @@ impl<'a> Lower<'a> { None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => { Val::I32(self.s.m.i32(0)) } + // A scalar parked in a VGPR lane (`ir::unspill`), read where the + // paths only seem to allow it before any save: the lane of a VGPR + // nobody wrote, and VGPRs nobody set read as zero. + None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)), None => Val::Missing("a hardware SGPR input"), }, Reg::Scc => Val::Missing("SCC on entry"), @@ -1328,7 +2554,7 @@ impl<'a> Lower<'a> { None => Val::Missing("a vertex input the signature lacks"), }; } - Input::Barycentric { .. } => return Val::Missing("barycentrics read directly"), + Input::Barycentric { kind, index } => return self.barycentric(kind, index), Input::PrimitiveId => return Val::Missing("the primitive id"), // The console code tests it against 0 (`v_cmp_ne_u32`), as the // host's value can be. @@ -1400,6 +2626,50 @@ impl<'a> Lower<'a> { } /// A component of a compute thread or group id, read in the entry block. + /// A dispatch the host spread across z (`USER_DISPATCH_SPREAD`): the + /// group id as the title asked it, `(x + z * row, y, 0)`, for every input + /// that reads it, and the groups past the asked count leave before the + /// body (whole groups: no barrier is split). `row` 0: as dispatched. + /// The entry block ends here; the first block's code goes to the next. + /// (After upstream VIctory pull request #2312.) + fn cs_spread_prologue(&mut self) { + use super::shader::USER_DISPATCH_SPREAD; + let row = self.host_word(RootType::Other(USER_DISPATCH_SPREAD), 0, 0); + let asked = self.host_word(RootType::Other(USER_DISPATCH_SPREAD), 0, 1); + let Val::I32(gx) = self.compute_id("groupId.i32", 94, 0) else { + unreachable!() + }; + let Val::I32(gz) = self.compute_id("groupId.i32", 94, 2) else { + unreachable!() + }; + let e = self.s.entry; + let zero = self.s.m.i32(0); + let unspread = self.s.m.cmp(e, pred::EQ, row, zero); + let mul = self.s.m.bin(e, Bin::Mul, gz, row); + let spread_x = self.s.m.bin(e, Bin::Add, gx, mul); + let eff_x = self.s.m.select(e, unspread, gx, spread_x); + let eff_z = self.s.m.select(e, unspread, gz, zero); + let in_x = self.s.m.cmp(e, pred::IULT, eff_x, asked); + let keep = self.s.m.bin(e, Bin::Or, unspread, in_x); + let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect(); + for (&v, &inp) in &io_inputs { + match inp { + Input::GroupId(0) => { + self.vals.insert(v, Val::I32(eff_x)); + } + Input::GroupId(2) => { + self.vals.insert(v, Val::I32(eff_z)); + } + _ => {} + } + } + let body = self.s.m.new_block(); + let ret = self.s.m.new_block(); + self.s.m.terminate(ret, Term::Ret); + self.s.m.terminate(e, Term::CondBr(keep, body, ret)); + self.cur = body; + } + fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val { let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c))); Val::I32( @@ -1481,6 +2751,13 @@ impl<'a> Lower<'a> { Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => { return self.mask_dword(v).map(Val::I32); } + Some(&Val::Missing(_)) | None + if self.mask_ok + && self.mask_data == MaskData::Console + && self.x.st.scc_some.contains_key(&v) => + { + return self.scc_some(v).map(Val::Bit); + } Some(&Val::Missing(w)) => return Err(w), Some(&val) => return Ok(val), None => {} @@ -1490,9 +2767,87 @@ impl<'a> Lower<'a> { self.vals.insert(v, val); return Ok(val); } + if let Some(loaded) = self.lazy_barycentric(v) { + loaded?; + return Ok(self.vals[&v]); + } Err("a value defined after its use") } + /// Loads `v` if it is a barycentric input VGPR not loaded yet (see + /// `inputs`): `None` if it is not one. + fn lazy_barycentric(&mut self, v: Value) -> Option<Result<(), Why>> { + let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i { + Input::Barycentric { kind, index } if w == v => Some((kind, index)), + _ => None, + })?; + let val = self.barycentric(kind, index); + self.vals.insert(v, val); + Some(match val { + Val::Missing(w) => Err(w), + _ => Ok(()), + }) + } + + /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of + /// `SV_Barycentrics` declared with the same interpolation mode. + /// + /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are + /// the weights of vertices 1 and 2. The host's weights (x, y, z) are + /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex, + /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat + /// input): i is y and j is z. + /// shortcut: triangles only; on lines and points the console's i and j + /// are not checked against the host's weights. + fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val { + let Some(mode) = interp_mode(kind) else { + return Val::Missing("pull-model barycentrics"); + }; + if index > 1 { + return Val::Missing("pull-model barycentrics"); + } + // One element per interpolation mode (the console's own, if its + // signature declares one): DXIL allows two. + let bary = |e: &SigElement| e.kind == 28; + let id = match self + .s + .inputs + .iter() + .position(|e| bary(e) && (e.interp == mode || e.usage == 0)) + { + Some(id) => id, + None => { + let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32; + if index >= 2 { + return Val::Missing("barycentrics of a third interpolation mode"); + } + // A system value the validator wants unpacked (packing + // location -1), like other non-packed system values. + self.s.inputs.push(SigElement { + name: "SV_Barycentrics".into(), + index, + kind: 28, + comp: 9, + interp: mode, + row: None, + col: 0, + cols: 3, + usage: 0, + half: false, + }); + self.s.inputs.len() - 1 + } + }; + let e = &mut self.s.inputs[id]; + if e.col != 0 || e.cols < 3 { + return Val::Missing("a console barycentrics element without i and j"); + } + e.row = None; + e.interp = mode; + self.s.flags |= flags::BARYCENTRICS; + self.load_any_input(id, index + 1) + } + fn i32_of(&mut self, v: Value) -> Result<V, Why> { match self.get(v)? { Val::I32(x) => Ok(x), @@ -1509,7 +2864,7 @@ impl<'a> Lower<'a> { RootType::Constants | RootType::Table => {} _ => return Val::Missing("a root descriptor"), } - let index = u32::from(rp.user_data) + dword; + let index = u32::from(rp.user_data) + dword - self.user_first(); self.user_reads.insert( index, UserData { @@ -1519,6 +2874,63 @@ impl<'a> Lower<'a> { dword, }, ); + Val::I32(self.user_at(index)) + } + + /// The user-data index that is dword 0 of the host's user data: 0, or + /// 16 for a program with a spilled user-data table, whose parameters + /// all sit at 16 and above. (The host's root signature has 64 dwords: + /// a builder stage with constants up to index 45, eight root views, + /// their biases and the memory directory would not fit with 16 dwords + /// nothing reads in front.) + fn user_first(&self) -> u32 { + if crate::spill::is_spilled(self.x.native) { + 16 + } else { + 0 + } + } + + /// A user-data dword no register of the console's holds: one the host + /// computes when it binds (`root` says what, an `Other` code of + /// `shader.rs`), placed after the layout's own dwords. + fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V { + let known = self + .user_reads + .values() + .find(|u| u.root == root && u.slot == slot && u.dword == dword) + .map(|u| u.index); + let index = match known { + Some(index) => index, + None => { + let first = self.user_first(); + let layout = &self.x.native.layout; + let mut index = layout + .iter() + .map(|e| u32::from(e.user_data) + e.sgprs) + .max() + .unwrap_or(0) + .saturating_sub(first); + while self.user_reads.contains_key(&index) { + index += 1; + } + self.user_reads.insert( + index, + UserData { + index, + slot, + root, + dword, + }, + ); + index + } + }; + self.user_at(index) + } + + /// User-data dword `index`, loaded in the entry block. + fn user_at(&mut self, index: u32) -> V { self.s.user_data = self.s.user_data.max(index + 1); let h = match self.user_data { Some(h) => h, @@ -1538,94 +2950,439 @@ impl<'a> Lower<'a> { 59, &[h, row], ); - Val::I32(self.s.m.extract(entry, r, index % 4)) - } - - /// For a root view (a root CBV, SRV or UAV), the bytes the host's view - /// holds from its start, which the host passes in the user-data dword of - /// the view's address. A root view has no bounds on the host: an access - /// past what the host mapped (an offset from data the host has not - /// mirrored) is a GPU page fault, which some hosts' GPUs stall on until - /// the driver resets the device. Accesses are checked against this size - /// as the console's bounded buffer views are. - fn root_view_size(&mut self, src: &Source) -> Option<V> { - let Source::Built { address, .. } = src else { - return None; - }; - if address.param == CODE { + self.s.m.extract(entry, r, index % 4) + } + + /// Whether some instruction computes with `v` (scalar or vector + /// arithmetic), rather than only naming it in a descriptor operand, + /// moving it (at most `depth` moves are followed) or comparing it: a + /// waterfall loop keeps a descriptor's dwords per lane, reads the first + /// lane's back and compares the lanes' with them. + /// Whether any instruction reads `v`. + fn read_anywhere(&self, v: Value) -> bool { + self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.reads.iter().any(|r| r.1 == v)) + } + + /// The record count (dword 2) of the buffer view whose descriptor the + /// scalar load at `site` reads from the start of a table entry: the host + /// view's size, in elements for a structured view and bytes for a raw + /// one, as the console counts them; 0 for a view that is not there. + fn record_count(&mut self, site: Site) -> Option<V> { + let src = Source::Loaded { load: site, first: 0 }; + let used = self.used_kind(&src); + let (uav, stride) = match used { + Some(u) if matches!(u.kind, ResourceType::Srv | ResourceType::Uav) => { + (u.kind == ResourceType::Uav, u.stride) + } + _ => return None, + }; + let u = if uav { 0x1000 } else { 0 }; + let props = if stride >= 4 && stride.is_multiple_of(4) { (12 | u, stride) } else { (11 | u, 0) }; + let h = self.handle(site, &src, false, props).ok()?; + let c = self.cur; + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let mip = self.s.m.undef(i32t); + let d = self.s.op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + Some(self.s.m.extract(c, d, 0)) + } + + fn computed_with(&self, v: Value, depth: u32) -> bool { + self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| { + if !i.reads.iter().any(|r| r.1 == v) { + return false; + } + let name = i.name(); + let moves = matches!( + name, + "s_mov_b32" + | "s_mov_b64" + | "v_mov_b32" + | "v_readfirstlane_b32" + | "v_readlane_b32" + | "v_writelane_b32" + | "v_cndmask_b32" + ); + match &i.fields { + Fields::Sop { .. } | Fields::Valu(_) if moves => { + depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1)) + } + Fields::Sop { .. } | Fields::Valu(_) => { + !(name.starts_with("v_cmp") || name.starts_with("s_cmp")) + } + _ => false, + } + }) + } + + /// The title address (low dword, bits from 32 up) of the buffer view + /// whose descriptor the scalar load at `site` reads from the start of + /// a table entry, as the host tells it when it binds (`shader.rs` + /// `USER_VIEW_ADDRESS`); none for anything else. (The console's + /// descriptor holds more in the second dword, the stride from bit 16 + /// up; code that takes the address masks those away.) + fn view_address(&mut self, site: Site) -> Option<(V, V)> { + use super::shader::USER_VIEW_ADDRESS; + let a = self.scalar.get(&site).copied()?; + let rp = *self.x.native.layout.get(a.param)?; + if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 { return None; } - let rp = *self.x.native.layout.get(address.param)?; - if rp.root != RootType::Descriptor { + let dword = a.offset / 4; + let used = self + .x + .native + .used + .iter() + .filter(|u| { + u.root == RootType::Table + && u.user_data == rp.user_data + && u.table_offset_dwords <= dword + }) + .max_by_key(|u| u.table_offset_dwords)?; + if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) { return None; } - if let Some(&v) = self.root_sizes.get(&address.param) { - return Some(v); + let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword); + let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword); + Some((lo, hi)) + } + + /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry. + fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) { + if off == 0 { + return (lo, hi); } - let index = u32::from(rp.user_data); - self.user_reads.insert( - index, - UserData { - index, - slot: rp.slot, - root: RootType::Descriptor, - dword: 0, - }, + let c = self.cur; + let i32t = self.s.t.i32; + let k = self.s.m.i32(off as u32); + let sum = self.s.m.bin(c, Bin::Add, lo, k); + // Up: a carry when the sum wrapped below `lo`. Down: a borrow when + // it wrapped above. + let wrapped = self + .s + .m + .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo); + let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t); + let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one); + (sum, hi) + } + + /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs` + /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding + /// it and the byte in that view. A page without a copy reads zeros + /// (and drops writes) through the null view at the first slot, and its + /// number is left for the host, for lanes that run (`guard`). + fn memory(&mut self, lo: V, hi: V, guard: Option<V>) -> (V, V) { + use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; + let c = self.cur; + let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (k16, k8) = (k(self, 16), k(self, 0xFF)); + let low = self.s.m.bin(c, Bin::LShr, lo, k16); + let high = self.s.m.bin(c, Bin::And, hi, k8); + let high = self.s.m.bin(c, Bin::Shl, high, k16); + let page = self.s.m.bin(c, Bin::Or, low, high); + // Inside the directory whatever the address (lanes that do not run + // compute one too); its last entry is never filled. + let last = k(self, MEMORY_PAGES - 1); + let page = self + .s + .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]); + self.s.m.tag(page, Tag::Clamp); + let k3 = k(self, 3); + let at = self.s.m.bin(c, Bin::Shl, page, k3); + let directory = self.s.root_srv_handle(SLOT_MEMORY); + let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4)); + let entry = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[directory, at, iu, both, align], ); - self.s.user_data = self.s.user_data.max(index + 1); - let h = match self.user_data { - Some(h) => h, + let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1)); + let (copy, start) = (self.as_int(copy), self.as_int(start)); + // A page without a copy: its number, at a place by the number, or + // at the sink for lanes that do not run and pages that have one. + let zero = k(self, 0); + let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero); + if let Some(g) = guard { + missing = self.s.m.bin(c, Bin::And, missing, g); + } + let places = k(self, MEMORY_FAULTS - 1); + let place = self.s.m.bin(c, Bin::URem, page, places); + let one = k(self, 1); + let place = self.s.m.bin(c, Bin::Add, place, one); + let k2 = k(self, 2); + let place = self.s.m.bin(c, Bin::Shl, place, k2); + let place = self.s.m.select(c, missing, place, zero); + let faults = self.s.root_uav_handle(SLOT_FAULTS); + let void = self.s.t.void; + let mask = self.s.m.i8(1); + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[faults, place, iu, page, iu, iu, iu, mask, align], + ); + let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); + let slot = self.s.m.bin(c, Bin::Add, base, copy); + let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0)); + let k64k = k(self, 0xFFFF); + let within = self.s.m.bin(c, Bin::And, lo, k64k); + let byte = self.s.m.bin(c, Bin::Add, start, within); + (h, byte) + } + + /// `global_load_*`, `global_store_*` and `global_atomic_*` on title + /// memory by address (`resource::MEMORY`): the address is the VGPR + /// pair, each lane its own. + fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Flat { + dst, + addr, + data, + saddr, + offset, + lds, + cache, + } = &inst.fields + else { + unreachable!() + }; + if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) { + return Err("a global address with a scalar base"); + } + let Some(Operand::Vector { reg: areg, .. }) = *addr else { + return Err("a global address not in VGPRs"); + }; + let word = |l: &mut Self, k: u8| -> Result<V, Why> { + let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?; + l.i32_of(v) + }; + let (lo, hi) = (word(self, 0)?, word(self, 1)?); + let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset)); + let guard = self.effect_guard(b, i)?; + let c = self.cur; + let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void); + let iu = self.s.m.undef(i32t); + let align = self.s.m.i32(4); + let name = inst.name(); + let count = |rest: &str| match rest { + "dword" => Ok(1u8), + "dwordx2" => Ok(2), + "dwordx3" => Ok(3), + "dwordx4" => Ok(4), + _ => Err(name), + }; + if let Some(rest) = name.strip_prefix("global_load_") { + let n = count(rest)?; + let Some(Operand::Vector { reg, .. }) = *dst else { + return Err("a global load result"); + }; + let (h, byte) = self.memory(lo, hi, guard); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + for k in 0..n { + let x = self.s.m.extract(c, r, u32::from(k)); + let x = self.as_int(x); + self.write(inst, Reg::V(reg + k), x, guard); + } + return Ok(()); + } + if let Some(rest) = name.strip_prefix("global_store_") { + let n = count(rest)?; + let d = data.as_ref().ok_or("global store data")?; + let vals = self.vgprs(inst, d, n)?; + let (h, byte) = self.memory(lo, hi, guard); + let mut args = vec![h, byte, iu]; + args.extend(&vals); + args.resize(3 + 4, iu); + args.push(self.s.m.i8((1u8 << n) - 1)); + args.push(align); + let at = self.begin_guarded(guard); + self.s + .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args); + self.end_guarded(at, &[]); + return Ok(()); + } + let Some(op) = name.strip_prefix("global_atomic_") else { + return Err(name); + }; + let d = data.as_ref().ok_or("global atomic data")?; + let v = self.vgprs(inst, d, 1)?[0]; + // With `glc` the value from before comes back, in the result + // register the instruction names. + let back = match (*dst, cache.glc) { + (Some(Operand::Vector { reg, .. }), true) => Some(reg), + _ => None, + }; + let old = match back.and_then(|reg| inst.read(Reg::V(reg))) { + Some(x) => self.i32_of(x)?, + None => self.s.m.i32(0), + }; + let (h, byte) = self.memory(lo, hi, guard); + // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed + // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8. + let simple = match op { + "add" => Some((0, v)), + "sub" => { + let zero = self.s.m.i32(0); + Some((0, self.s.m.bin(c, Bin::Sub, zero, v))) + } + "and" => Some((1, v)), + "or" => Some((2, v)), + "xor" => Some((3, v)), + "smin" => Some((4, v)), + "smax" => Some((5, v)), + "umin" => Some((6, v)), + "umax" => Some((7, v)), + "swap" => Some((8, v)), + "fmin" | "fmax" => None, + _ => return Err(name), + }; + let at = self.begin_guarded(guard); + let was = match simple { + Some((code, x)) => { + let code = self.s.m.i32(code); + self.s.op( + self.cur, + "atomicBinOp.i32", + Attr::NoUnwind, + i32t, + 78, + &[h, code, byte, iu, iu, x], + ) + } None => { - let h = self.s.user_data_handle(); - self.user_data = Some(h); - h + // A float minimum or maximum has no atomic operation on + // the host: the dword is exchanged for the smaller (larger) + // of itself and the value until no other thread got in + // between. Each failed pass means another one's succeeded; + // the limit only keeps a broken card from hanging. + let head = self.cur; + let mask = self.s.m.i8(1); + let first = self.s.op( + head, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + let first = self.s.m.extract(head, first, 0); + let first = self.as_int(first); + let (pass, done) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(head, Term::Br(pass)); + self.cur = pass; + let seen = self.s.m.phi(pass, i32t); + let n = self.s.m.phi(pass, i32t); + let (f32t, fv) = (self.s.t.f32, self.as_float(v)); + let fseen = self.as_float(seen); + // `dx.op.binary`: FMax 35, FMin 36. + let pick = if op == "fmin" { 36 } else { 35 }; + let wanted = self + .s + .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]); + let wanted = self.as_int(wanted); + let found = self.s.op( + pass, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &[h, byte, iu, iu, seen, wanted], + ); + let one = self.s.m.i32(1); + let n1 = self.s.m.bin(pass, Bin::Add, n, one); + let lost = self.s.m.cmp(pass, pred::NE, found, seen); + let limit = self.s.m.i32(1 << 16); + let more = self.s.m.cmp(pass, pred::IULT, n1, limit); + let again = self.s.m.bin(pass, Bin::And, lost, more); + self.s.m.terminate(pass, Term::CondBr(again, pass, done)); + let zero = self.s.m.i32(0); + self.s.m.set_phi(seen, vec![(first, head), (found, pass)]); + self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]); + self.cur = done; + found } }; - let entry = self.s.entry; - let row = self.s.m.i32(index / 4); - let r = self.s.op( - entry, - "cbufferLoadLegacy.i32", - Attr::ReadOnly, - self.s.t.cbuf_ret, - 59, - &[h, row], - ); - let v = self.s.m.extract(entry, r, index % 4); - self.root_sizes.insert(address.param, v); - Some(v) - } - - /// Whether `bytes` bytes at byte `off` lie in a root view of `size` - /// bytes, and the offset to access instead (0 when they do not). - fn in_root_view(&mut self, size: V, off: V, bytes: u32) -> (V, V) { - let c = self.cur; - let below = self.s.m.cmp(c, pred::IULT, off, size); - let left = self.s.m.bin(c, Bin::Sub, size, off); - let n = self.s.m.i32(bytes); - let fits = self.s.m.cmp(c, pred::IUGE, left, n); - let ok = self.s.m.bin(c, Bin::And, below, fits); - let zero = self.s.m.i32(0); - (ok, self.s.m.select(c, ok, off, zero)) - } - - /// `guard` (lanes that run an access) narrowed to `ok`. - fn narrow(&mut self, guard: Option<V>, ok: Option<V>) -> Option<V> { - match (guard, ok) { - (Some(g), Some(k)) => Some(self.s.m.bin(self.cur, Bin::And, g, k)), - (g, k) => g.or(k), + let was = self.end_guarded(at, &[(was, old)])[0]; + if let Some(reg) = back { + self.write(inst, Reg::V(reg), was, None); } + Ok(()) } - /// `x` where `ok` holds, else 0 (`ok` none: always `x`). - fn zero_unless(&mut self, ok: Option<V>, x: V) -> V { - match ok { - Some(k) => { - let zero = self.s.m.i32(0); - self.s.m.select(self.cur, k, x, zero) + /// `s_load_dword*` from title memory by address (`resource::MEMORY`): + /// the SGPR pair plus the instruction's offsets. + fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> { + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + base: Operand::Scalar { code: base, .. }, + offset, + soffset, + .. + } = inst.fields + else { + return Err("a scalar load from memory"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u8, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar memory access by address"), + }; + let word = |l: &mut Self, k: u8| -> Result<V, Why> { + let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?; + l.i32_of(v) + }; + let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?); + let c = self.cur; + let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + // An offset register counts up from the address. + let so = self.operand(inst, &soffset)?; + let sum = self.s.m.bin(c, Bin::Add, lo, so); + let carry = self.s.m.cmp(c, pred::IULT, sum, lo); + let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t); + hi = self.s.m.bin(c, Bin::Add, hi, carry); + lo = sum; + } + let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4)); + for first in (0..count).step_by(4) { + let n = (count - first).min(4); + let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first)); + let (h, byte) = self.memory(lo, hi, None); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + for k in 0..n { + let x = self.s.m.extract(c, r, u32::from(k)); + let x = self.as_int(x); + self.write(inst, Reg::S(code + first + k), x, None); } - None => x, } + Ok(()) } /// A dword of a lane mask as a number: the ballot of the lanes' bits, @@ -1636,15 +3393,23 @@ impl<'a> Lower<'a> { None => (v, false), }; let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?; - if !self.x.st.active.contains(&lo) { - return Err("a lane mask holding lanes elsewhere read as data"); + // A mask that holds lanes outside EXEC where it is written (the complement of one, + // say) is the ballot of the lanes that are there: all of them, where two exchanging + // host waves know every lane runs that block. + let made = self.def_block.get(&lo).copied(); + let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); + if !self.x.st.active.contains(&lo) && !whole && !MASKS_ELSEWHERE.get() && !self.local_any { + if self.exchange.is_some() && !self.local { + need(made.unwrap_or(0)); + } + return Err(MASK_ELSEWHERE); } let (x, y) = match self.ballots.get(&lo) { Some(&xy) => xy, None => { let at = match self.def_block.get(&lo) { // Program inputs (EXEC on entry). - None => self.s.entry, + None => self.body_entry, Some(&b) if b == self.cur_ir => self.cur, Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?, }; @@ -1653,25 +3418,11 @@ impl<'a> Lower<'a> { } let bit = self.boolean(m, at); self.balloting.remove(&lo); - let bit = bit?; - if self.emulated.is_some() { - let ir = self.def_block.get(&lo).copied().unwrap_or(0); - self.emulated_here(ir, at)?; - let i32t = self.s.t.i32; - let one = self.s.m.cast(at, Cast::ZExt, bit, i32t); - let bits = self.gather(at, one); - let (mut x, mut y) = (self.s.m.i32(0), self.s.m.i32(0)); - for (n, b) in bits.into_iter().enumerate() { - let sh = self.s.m.i32(n as u32 % 32); - let b = self.s.m.bin(at, Bin::Shl, b, sh); - if n < 32 { - x = self.s.m.bin(at, Bin::Or, x, b); - } else { - y = self.s.m.bin(at, Bin::Or, y, b); - } - } - self.ballots.insert(lo, (x, y)); - return Ok(if high { y } else { x }); + let mut bit = bit?; + if let Some(active) = self.partial_active + && self.x.st.active.contains(&lo) + { + bit = self.s.m.bin(at, Bin::And, bit, active); } let i32t = self.s.t.i32; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); @@ -1679,7 +3430,21 @@ impl<'a> Lower<'a> { .s .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]); self.s.flags |= flags::WAVE_OPS; - let xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1)); + let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1)); + if self.exchange.is_some() { + // a host wave's ballot is its half's 32 bits: the halves exchange them + let b = self.def_block.get(&lo).copied(); + if self.local { + if !self.local_ok && !self.local_any { + return Err("a lane mask read as data in a half-wave"); + } + } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) { + // (a group of 32 or fewer has no other half to exchange with) + need(b.unwrap_or(0)); + return Err(DIVERGENT_MASK_EXCHANGE); + } + xy = self.exchange_halves(at, xy.0); + } self.ballots.insert(lo, xy); xy } @@ -1708,15 +3473,13 @@ impl<'a> Lower<'a> { } } - /// GFX10 puts an inline f16 constant in the low half of the operand. + /// An operand read as f16 data: GFX10 puts an inline f16 constant in + /// the low half of the operand (upstream PR #637, checked there against + /// the instruction encodings; the half-and-half reading taken from PR + /// #458 gave the high half the constant too). fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> { match *op { - Operand::Const(c @ 240..=248) => { - let h = [ - 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, - ][usize::from(c - 240)]; - Ok(self.s.m.i32(h)) - } + Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))), _ => self.operand(inst, op), } } @@ -1826,6 +3589,27 @@ impl<'a> Lower<'a> { } } + /// With `VICTORY_NAN_SCRUB=1` (off by default), `f` or 0 where it is + /// NaN or infinite (ported from trustno1-coder/VIctory-NVIDIA 77e13a97). + /// Used on the colours pixel shaders write: a NaN that reaches the + /// title's bloom, blur or temporal upscaler spreads into black blocks + /// that stay in its history (black blobs on faces and in the air, and + /// blocky shine where light reflects, on NVIDIA), and an infinity turns + /// the picture white at some angles. Not what the console does, so it + /// is a switch; part of the shader cache key. + fn scrub_nan(&mut self, f: V) -> V { + if !nan_scrub() { + return f; + } + // |f| >= inf, unordered: true for NaN too. + let c = self.cur; + let a = self.unary(6, f); + let inf = self.s.m.f32(0x7f80_0000); + let bad = self.s.m.cmp(c, pred::UGE, a, inf); + let zero = self.s.m.f32(0); + self.s.m.select(c, bad, zero, f) + } + fn unary(&mut self, op: u32, f: V) -> V { self.s.op( self.cur, @@ -1878,83 +3662,15 @@ impl<'a> Lower<'a> { ) } - /// `f` as an f16 in the low bits, rounded to nearest even as the - /// console does (MODE's default): a tie goes to the even half, a finite - /// value from 65520 up becomes infinity, results below 2^-14 stay - /// subnormal, NaN stays NaN (quiet, top payload bits kept). Worked on - /// the bits: the host's f32-to-f16 conversion (DXIL op 130) rounds - /// toward zero on NVIDIA and WARP alike (1 + 3/2048 gives 0x3C01, 1e6 - /// gives 0x7BFF). - fn f16_nearest(&mut self, f: V) -> V { - let c = self.cur; - let x = self.as_int(f); - let k = |l: &mut Self, v: u32| l.s.m.i32(v); - let (k0, k1, k13, k16, k23) = ( - k(self, 0), - k(self, 1), - k(self, 13), - k(self, 16), - k(self, 23), - ); - let sign = self.s.m.bin(c, Bin::LShr, x, k16); - let sign_mask = k(self, 0x8000); - let sign = self.s.m.bin(c, Bin::And, sign, sign_mask); - let abs_mask = k(self, 0x7FFF_FFFF); - let a = self.s.m.bin(c, Bin::And, x, abs_mask); - // Normal halves: rebias the exponent (127 - 15) and round on bit 13. - let odd = self.s.m.bin(c, Bin::LShr, a, k13); - let odd = self.s.m.bin(c, Bin::And, odd, k1); - let bias = k(self, 0xFFF_u32.wrapping_sub(112 << 23)); - let n = self.s.m.bin(c, Bin::Add, a, bias); - let n = self.s.m.bin(c, Bin::Add, n, odd); - let normal = self.s.m.bin(c, Bin::LShr, n, k13); - // Subnormal halves: the 24-bit significand shifted down by - // 126 - exponent (at least 14, at most 31), rounded to nearest even. - let e = self.s.m.bin(c, Bin::LShr, a, k23); - let man_mask = k(self, 0x7F_FFFF); - let man = self.s.m.bin(c, Bin::And, a, man_mask); - let implicit = k(self, 0x80_0000); - let m = self.s.m.bin(c, Bin::Or, man, implicit); - let k126 = k(self, 126); - let sh = self.s.m.bin(c, Bin::Sub, k126, e); - let k31 = k(self, 31); - let wide = self.s.m.cmp(c, pred::IUGT, sh, k31); - let sh = self.s.m.select(c, wide, k31, sh); - let q = self.s.m.bin(c, Bin::LShr, m, sh); - let one_s = self.s.m.bin(c, Bin::Shl, k1, sh); - let low = self.s.m.bin(c, Bin::Sub, one_s, k1); - let rem = self.s.m.bin(c, Bin::And, m, low); - let half = self.s.m.bin(c, Bin::LShr, one_s, k1); - let above = self.s.m.cmp(c, pred::IUGT, rem, half); - let tie = self.s.m.cmp(c, pred::EQ, rem, half); - let q_odd = self.s.m.bin(c, Bin::And, q, k1); - let q_odd = self.s.m.cmp(c, pred::NE, q_odd, k0); - let tie_up = self.s.m.bin(c, Bin::And, tie, q_odd); - let up = self.s.m.bin(c, Bin::Or, above, tie_up); - let inc = self.s.m.select(c, up, k1, k0); - let sub = self.s.m.bin(c, Bin::Add, q, inc); - let min_normal = k(self, 0x3880_0000); - let is_sub = self.s.m.cmp(c, pred::IULT, a, min_normal); - let r = self.s.m.select(c, is_sub, sub, normal); - let overflow = k(self, 0x477F_F000); - let big = self.s.m.cmp(c, pred::IUGE, a, overflow); - let inf = k(self, 0x7C00); - let r = self.s.m.select(c, big, inf, r); - let f32_inf = k(self, 0x7F80_0000); - let nan = self.s.m.cmp(c, pred::IUGT, a, f32_inf); - let payload = self.s.m.bin(c, Bin::LShr, man, k13); - let quiet = k(self, 0x7E00); - let qnan = self.s.m.bin(c, Bin::Or, quiet, payload); - let r = self.s.m.select(c, nan, qnan, r); - self.s.m.bin(c, Bin::Or, r, sign) - } - /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even /// conversion, one step back toward zero where it rounded away (which /// also turns an overflow to infinity into the largest finite half). fn f16_toward_zero(&mut self, f: V) -> V { let c = self.cur; - let h = self.f16_nearest(f); + let i32t = self.s.t.i32; + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); let back = self .s .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]); @@ -1966,6 +3682,44 @@ impl<'a> Lower<'a> { self.s.m.select(c, away, stepped, h) } + /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's + /// 16-bit float operations round, whatever the host's own conversion does: D3D lets + /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070: + /// `wave64_tests`). The conversion toward zero, or the next half away from zero where + /// that one is nearer, or as near and the first one odd. Past the largest half the next + /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity. + /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the + /// rounding of the exact result, 24 bits being more than twice 11 and two.) + fn f16_nearest(&mut self, f: V) -> V { + let c = self.cur; + let f32t = self.s.t.f32; + let lo = self.f16_toward_zero(f); + let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0)); + let hi = self.s.m.bin(c, Bin::Add, lo, one); + let size = |l: &mut Self, h: V| { + let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + l.unary(6, w) + }; + let (below, above) = (size(self, lo), size(self, hi)); + let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00)); + let m = self.s.m.bin(c, Bin::And, hi, magnitude); + let top = self.s.m.cmp(c, pred::EQ, m, infinity); + let bound = self.s.m.f32(65536.0f32.to_bits()); + let above = self.s.m.select(c, top, bound, above); + let fa = self.unary(6, f); + // (both differences are exact: the three values lie within one half's step) + let under = self.s.m.bin(c, Bin::Sub, fa, below); + let over = self.s.m.bin(c, Bin::Sub, above, fa); + // Ordered: never for NaN, which stays what the conversion made of it. + let nearer = self.s.m.cmp(c, pred::OLT, over, under); + let tie = self.s.m.cmp(c, pred::OEQ, over, under); + let odd = self.s.m.bin(c, Bin::And, lo, one); + let odd = self.s.m.cmp(c, pred::NE, odd, zero); + let tie = self.s.m.bin(c, Bin::And, tie, odd); + let up = self.s.m.bin(c, Bin::Or, nearer, tie); + self.s.m.select(c, up, hi, lo) + } + /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's /// top bit when `signed`; widths from 32 on take every bit. A signed /// field that runs past bit 31 extends from bit 31, as the hardware @@ -2001,15 +3755,20 @@ impl<'a> Lower<'a> { self.s.m.select(c, keep, r, t) } + /// Whether an f32 value is NaN, tested in integer arithmetic so host + /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math. + fn is_nan_f32(&mut self, f: V) -> V { + let c = self.cur; + let bits = self.as_int(f); + let mask = self.s.m.i32(0x7FFF_FFFF); + let abs = self.s.m.bin(c, Bin::And, bits, mask); + let inf = self.s.m.i32(0x7F80_0000); + self.s.m.cmp(c, pred::IUGT, abs, inf) + } + /// The median of three. With a NaN among them the hardware gives the /// minimum of the three instead (the host's minimum skips NaNs, so that /// is the smallest number among them). - /// - /// The NaN test is on the operands' bits ([`Self::is_nan_bits`]), not a - /// float compare: drivers fold `fcmp uno x, x` to false under default - /// shader fast-math (observed on Intel Iris Xe and NVIDIA, upstream - /// #726, #745), returning the median where the hardware gives the - /// least operand. An integer compare leaves them nothing to assume. fn med3(&mut self, a: V, b: V, third: V) -> V { let c = self.cur; let lo = self.binary(36, a, b); @@ -2017,26 +3776,14 @@ impl<'a> Lower<'a> { let t = self.binary(36, hi, third); let median = self.binary(35, lo, t); let least = self.binary(36, lo, third); - let na = self.is_nan_bits(a); - let nb = self.is_nan_bits(b); - let n3 = self.is_nan_bits(third); - let ab = self.s.m.bin(c, Bin::Or, na, nb); - let nan = self.s.m.bin(c, Bin::Or, ab, n3); + let nan_a = self.is_nan_f32(a); + let nan_b = self.is_nan_f32(b); + let nan_3 = self.is_nan_f32(third); + let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b); + let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3); self.s.m.select(c, nan, least, median) } - /// Whether `f` is a NaN, tested on its bits (`|f| > +inf` as integers). - /// A float `fcmp uno` is not used: drivers (observed on NVIDIA) assume - /// no NaNs there and fold it to false, so the NaN case was lost. - fn is_nan_bits(&mut self, f: V) -> V { - let c = self.cur; - let bits = self.as_int(f); - let abs = self.s.m.i32(0x7FFF_FFFF); - let inf = self.s.m.i32(0x7F80_0000); - let mag = self.s.m.bin(c, Bin::And, bits, abs); - self.s.m.cmp(c, pred::IUGT, mag, inf) - } - /// `a - floor(a)`, which on the hardware never reaches 1.0: where it /// would round to it (a tiny negative `a`), the result is `below_one`, /// the largest value under 1.0 in the operation's width. Hosts differ @@ -2078,85 +3825,6 @@ impl<'a> Lower<'a> { self.s.m.select(c, exact, zero, r) } - /// `x * 2^e` for any i32 `e`, rounded once unless the result is a - /// denormal. DXIL has no ldexp: `x` is multiplied by three powers of - /// two that are each a normal float. Past ±375 any finite nonzero `x` - /// is already at zero or infinity, so `e` is clamped to [-375, 378], - /// which keeps each of q, q and e - 2q (q = e / 3) inside [-126, 127]. - fn ldexp(&mut self, x: V, e: V) -> V { - let c = self.cur; - let (lo, hi) = (self.s.m.i32(-375i32 as u32), self.s.m.i32(378)); - let below = self.s.m.cmp(c, pred::SLT, e, lo); - let e = self.s.m.select(c, below, lo, e); - let above = self.s.m.cmp(c, pred::SGT, e, hi); - let e = self.s.m.select(c, above, hi, e); - let three = self.s.m.i32(3); - let q = self.s.m.bin(c, Bin::SDiv, e, three); - let two_q = self.s.m.bin(c, Bin::Add, q, q); - let rest = self.s.m.bin(c, Bin::Sub, e, two_q); - let mut r = x; - for k in [q, q, rest] { - // 2^k for k in [-126, 127]: the biased exponent alone. - let (bias, at) = (self.s.m.i32(127), self.s.m.i32(23)); - let biased = self.s.m.bin(c, Bin::Add, k, bias); - let bits = self.s.m.bin(c, Bin::Shl, biased, at); - let factor = self.as_float(bits); - r = self.s.m.bin(c, Bin::Mul, r, factor); - } - r - } - - /// The significand (bits of a float with magnitude in [0.5, 1), the - /// sign kept) and the exponent of the f32 with bits `x`, so that - /// x = significand * 2^exponent, worked on the bits so that denormals - /// are normalized whatever the host's float mode. Zero gives itself and - /// 0; infinity and NaN give themselves and 0. - fn frexp(&mut self, x: V) -> (V, V) { - let c = self.cur; - let k = |l: &mut Self, v: u32| l.s.m.i32(v); - let (at, ff) = (k(self, 23), k(self, 0xFF)); - let field = self.s.m.bin(c, Bin::LShr, x, at); - let field = self.s.m.bin(c, Bin::And, field, ff); - let frac_mask = k(self, 0x7F_FFFF); - let frac = self.s.m.bin(c, Bin::And, x, frac_mask); - let sign_mask = k(self, 0x8000_0000); - let sign = self.s.m.bin(c, Bin::And, x, sign_mask); - // A denormal's leading one at bit 31 - lz moves to bit 23. - let lz = self.s.op( - c, - "unaryBits.i32", - Attr::ReadNone, - self.s.t.i32, - 33, - &[frac], - ); - let (eight, k31) = (k(self, 8), k(self, 31)); - let sh = self.s.m.bin(c, Bin::Sub, lz, eight); - let sh = self.s.m.bin(c, Bin::And, sh, k31); - let normalized = self.s.m.bin(c, Bin::Shl, frac, sh); - let normalized = self.s.m.bin(c, Bin::And, normalized, frac_mask); - let zero = k(self, 0); - let denormal = self.s.m.cmp(c, pred::EQ, field, zero); - let frac = self.s.m.select(c, denormal, normalized, frac); - let half = k(self, 0x3F00_0000); - let m = self.s.m.bin(c, Bin::Or, sign, half); - let m = self.s.m.bin(c, Bin::Or, m, frac); - // Exponents: field - 126, or -117 - lz for a denormal. - let (k126, k117) = (k(self, 126), k(self, -117i32 as u32)); - let e_normal = self.s.m.bin(c, Bin::Sub, field, k126); - let e_denormal = self.s.m.bin(c, Bin::Sub, k117, lz); - let e = self.s.m.select(c, denormal, e_denormal, e_normal); - // Zero, infinity and NaN. - let magnitude = k(self, 0x7FFF_FFFF); - let magnitude = self.s.m.bin(c, Bin::And, x, magnitude); - let is_zero = self.s.m.cmp(c, pred::EQ, magnitude, zero); - let special = self.s.m.cmp(c, pred::EQ, field, ff); - let keep = self.s.m.bin(c, Bin::Or, is_zero, special); - let m = self.s.m.select(c, keep, x, m); - let e = self.s.m.select(c, keep, zero, e); - (m, e) - } - /// The high dword of a 32 × 32-bit product. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V { let c = self.cur; @@ -2171,38 +3839,45 @@ impl<'a> Lower<'a> { self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32) } - /// `0 × anything = 0`, as in D3D9. As on RDNA2, a denormal operand counts - /// as zero, so the test is on the exponent bits rather than a float - /// compare (whose result would depend on the host's denormal mode). + /// `0 × anything = 0`, as in D3D9. fn legacy_mul(&mut self, a: V, b: V) -> V { let c = self.cur; let m = self.s.m.bin(c, Bin::Mul, a, b); - let exp = self.s.m.i32(0x7F80_0000); - let izero = self.s.m.i32(0); - let is_zero = |l: &mut Self, v: V| { - let bits = l.as_int(v); - let e = l.s.m.bin(c, Bin::And, bits, exp); - l.s.m.cmp(c, pred::EQ, e, izero) - }; - let az = is_zero(self, a); - let bz = is_zero(self, b); - let z = self.s.m.bin(c, Bin::Or, az, bz); let zero = self.s.m.f32(0); + let az = self.s.m.cmp(c, pred::OEQ, a, zero); + let bz = self.s.m.cmp(c, pred::OEQ, b, zero); + let z = self.s.m.bin(c, Bin::Or, az, bz); self.s.m.select(c, z, zero, m) } - /// `a × b + addend` fused, with `0 × anything = 0` as in D3D9 - /// (`v_fma_legacy_f32`). - fn fma_legacy(&mut self, a: V, b: V, addend: V) -> V { + /// Flushes f32 subnormals to signed zero, keeping all other values and + /// the sign of zero intact. + fn ftz(&mut self, x: V) -> V { let c = self.cur; + let bits = self.as_int(x); + let exp_mask = self.s.m.i32(0x7F80_0000); + let sign_mask = self.s.m.i32(0x8000_0000); + let zero = self.s.m.i32(0); + let exp = self.s.m.bin(c, Bin::And, bits, exp_mask); + let sub = self.s.m.cmp(c, pred::EQ, exp, zero); + let signed_zero = self.s.m.bin(c, Bin::And, bits, sign_mask); + let flushed = self.s.m.select(c, sub, signed_zero, bits); + self.as_float(flushed) + } + + /// A legacy multiply-add as RDNA 2 runs it: fused (`v_fma_legacy_f32`), + /// with the legacy rule that a zero factor makes the product a +0 rather + /// than turning an infinite or NaN factor into a NaN. + fn legacy_fmad(&mut self, a: V, b: V, c: V) -> V { + let cur = self.cur; + let fused = self.fmad(a, b, c); let zero = self.s.m.f32(0); - let az = self.s.m.cmp(c, pred::OEQ, a, zero); - let bz = self.s.m.cmp(c, pred::OEQ, b, zero); - let z = self.s.m.bin(c, Bin::Or, az, bz); - let product_zero = self.s.m.bin(c, Bin::Add, zero, addend); - // shortcut: FMad lets the driver fuse, as for `v_fma_f32`. - let fused = self.fmad(a, b, addend); - self.s.m.select(c, z, product_zero, fused) + let az = self.s.m.cmp(cur, pred::OEQ, a, zero); + let bz = self.s.m.cmp(cur, pred::OEQ, b, zero); + let z = self.s.m.bin(cur, Bin::Or, az, bz); + // +0 + c, so the sign of a zero addend follows the addition. + let addend = self.s.m.bin(cur, Bin::Add, zero, c); + self.s.m.select(cur, z, addend, fused) } // ---- lane booleans ---- @@ -2301,19 +3976,262 @@ impl<'a> Lower<'a> { } } + /// A console wave64 program in host waves of 32: the first console thread of this host wave + /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's + /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread + /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it + /// found. Branch-free, in the entry block, which every thread runs. + fn wave_base(&mut self) -> Option<V> { + let slot = self.halves?; + if let Some(v) = self.wave_base { + return Some(v); + } + let (e, i32t) = (self.s.entry, self.s.t.i32); + let lds = self.s.lds(); + let k = self.s.m.i32(slot); + let ptr = self.s.m.element(e, lds, k); + let zero = self.s.m.i32(0); + self.s.m.store(e, ptr, zero); + self.group_sync(e); + let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let first = self.s.m.cmp(e, pred::EQ, lane, zero); + let k32 = self.s.m.i32(32); + let add = self.s.m.select(e, first, k32, zero); + let ptr = self.s.m.element(e, lds, k); + let old = self.s.m.atomic(e, Rmw::Add, ptr, add); + let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]); + self.s.flags |= flags::WAVE_OPS; + self.wave_base = Some(base); + Some(base) + } + + /// The console thread index of this thread in the group: `wave_base` plus the host lane + /// (host waves of 32), else the wave's first thread index rounded down plus the lane. + fn console_thread(&mut self) -> V { + let (e, i32t) = (self.s.entry, self.s.t.i32); + let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + if let Some(base) = self.wave_base() { + return self.s.m.bin(e, Bin::Add, base, lane); + } + let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]); + let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]); + let wave = self.s.wave_size.unwrap_or(32); + let mask = self.s.m.i32(!(wave - 1)); + let base = self.s.m.bin(e, Bin::And, first, mask); + self.s.m.bin(e, Bin::Add, base, lane) + } + + /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host + /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane. + fn console_lane(&mut self) -> V { + if self.exchange.is_none() { + return self.lane_index(); + } + if let Some(v) = self.clane { + return v; + } + let (e, i32t) = (self.s.entry, self.s.t.i32); + let f = self.console_thread(); + let _ = i32t; + let k63 = self.s.m.i32(63); + let cl = self.s.m.bin(e, Bin::And, f, k63); + self.s.flags |= flags::WAVE_OPS; + self.clane = Some(cl); + cl + } + + /// A group barrier with an LDS fence in `block`. + fn group_sync(&mut self, block: usize) { + let mode = self.s.m.i32(meeting_mode()); + let void = self.s.t.void; + self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + + /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get + /// (lower half's, upper half's). A group with no upper half gets 0 for it. + fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) { + let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else { + let z = self.s.m.i32(0); + return (mine, z); + }; + if small { + let z = self.s.m.i32(0); + return (mine, z); + } + if self.local { + // each host wave on its own: its half holds `mine`, the other nothing + let cl = self.console_lane(); + let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0)); + let upper = self.s.m.cmp(at, pred::IUGE, cl, k32); + let lo = self.s.m.select(at, upper, z, mine); + let hi = self.s.m.select(at, upper, mine, z); + return (lo, hi); + } + // the pair of dwords of this thread's console wave: its half's, then both + let pair = self.exchange_pair(slot); + let cl = self.console_lane(); + let five = self.s.m.i32(5); + let half = self.s.m.bin(at, Bin::LShr, cl, five); + let index = self.s.m.bin(at, Bin::Add, pair, half); + let lds = self.s.lds(); + let ptr = self.s.m.element(at, lds, index); + self.s.m.store(at, ptr, mine); + self.group_sync(at); + let one = self.s.m.i32(1); + let k1 = self.s.m.bin(at, Bin::Add, pair, one); + let p0 = self.s.m.element(at, lds, pair); + let p1 = self.s.m.element(at, lds, k1); + let lo = self.s.m.load(at, p0); + let hi = self.s.m.load(at, p1); + // the slots are written again only after every thread read them + self.group_sync(at); + (lo, hi) + } + + /// The first of the two exchange dwords of this thread's console wave (made in the entry + /// block): a group of several console waves has a pair for each. + fn exchange_pair(&mut self, slot: u32) -> V { + if let Some(v) = self.pair { + return v; + } + let e = self.s.entry; + let thread = self.console_thread(); + let six = self.s.m.i32(6); + let wave = self.s.m.bin(e, Bin::LShr, thread, six); + let one = self.s.m.i32(1); + let twice = self.s.m.bin(e, Bin::Shl, wave, one); + let base = self.s.m.i32(slot); + let v = self.s.m.bin(e, Bin::Add, base, twice); + self.pair = Some(v); + v + } + + /// The console's decision of the branch closing IR block `b`, which the wave takes + /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken + /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or + /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`]. + /// Each host wave asks its lanes and the halves exchange the answers, so both go the + /// same way and can meet again inside the branch. + /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the + /// console wave has its bit of the result, asked where the operation stands. The lanes + /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with + /// the console's waves the host wave's answer is the console's; two host waves of 32 + /// exchange theirs, which needs every lane there. + fn scc_some(&mut self, scc: Value) -> Result<V, Why> { + let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?; + // (not for a console wave cut into host waves that do not exchange, + // unless `local_any` takes every mask read per host wave) + if !self.console_lanes + || self.local && !self.local_any + || self.exchange.is_none() && self.halves.is_some() + { + return Err(LANE_MASK); + } + let made = self.def_block.get(&scc).copied(); + let at = match made { + None => self.body_entry, + Some(b) if b == self.cur_ir => self.cur, + Some(b) => self.tail[b].ok_or("a lane mask written after its use")?, + }; + let mut bit = self.boolean(m, at)?; + if let Some(active) = self.partial_active { + bit = self.s.m.bin(at, Bin::And, bit, active); + } + let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); + let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); + self.s.flags |= flags::WAVE_OPS; + if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) { + return Ok(some); + } + if !made.is_none_or(|b| self.all_lanes(b)) { + need(made.unwrap_or(0)); + return Err(DIVERGENT_MASK_EXCHANGE); + } + let some = self.s.m.cast(at, Cast::ZExt, some, i32t); + let (lo, hi) = self.exchange_halves(at, some); + let both = self.s.m.bin(at, Bin::Or, lo, hi); + let z = self.s.m.i32(0); + Ok(self.s.m.cmp(at, pred::NE, both, z)) + } + + fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> { + const WHY: Why = "a wave-wide branch where not every lane runs"; + let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?; + if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console { + // The host's waves are the console's: the wave's own answer. The lanes that are + // elsewhere have no bit set, as on the console, so "some lane" needs no one but + // the lanes here, and "every lane's bit is clear" is true of the others anyway. + let c = self.cur; + let mut mine = self.boolean(when, c)?; + // Threads past a DispatchX count speak neither for nor against. + if let Some(active) = self.partial_active { + mine = if any { + self.s.m.bin(c, Bin::And, mine, active) + } else { + let t = self.s.m.bool(true); + let off = self.s.m.bin(c, Bin::Xor, active, t); + self.s.m.bin(c, Bin::Or, mine, off) + }; + } + let i1t = self.s.t.i1; + self.s.flags |= flags::WAVE_OPS; + let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) }; + return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine])); + } + if self.local && self.local_any { + // the last resort: each host wave asks its own 32 lanes (approximate where the + // other half would have decided it) + let c = self.cur; + let mine = self.boolean(when, c)?; + let i1t = self.s.t.i1; + self.s.flags |= flags::WAVE_OPS; + let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) }; + return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine])); + } + if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) { + return Err(WHY); + } + if !self.all_lanes(b) { + need(b); + return Err(WHY); + } + let c = self.cur; + let mine = self.boolean(when, c)?; + // what the halves exchange is "some lane speaks against" either way (for `any`: + // some lane's `when` holds; else: some lane's does not), so a half with no lane says + // nothing + let mut set = if any { + mine + } else { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, mine, t) + }; + if let Some(active) = self.partial_active { + set = self.s.m.bin(c, Bin::And, set, active); + } + let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); + let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); + self.s.flags |= flags::WAVE_OPS; + let some = self.s.m.cast(c, Cast::ZExt, some, i32t); + let (lo, hi) = self.exchange_halves(c, some); + let c = self.cur; + let both = self.s.m.bin(c, Bin::Or, lo, hi); + let z = self.s.m.i32(0); + Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z)) + } + + /// Whether every lane runs IR block `b` (always true without `exchange`). + fn all_lanes(&self, b: usize) -> bool { + self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false)) + } + /// This lane's bit of the mask `lo`, `hi` (wave64). fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V { - let lane = if self.emulated.is_some() { - self.mesh_thread() + self.s.flags |= flags::WAVE_OPS; + let lane = if self.exchange.is_some() { + self.console_lane() } else { - self.s.op( - at, - "waveGetLaneIndex", - Attr::ReadOnly, - self.s.t.i32, - 111, - &[], - ) + self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[]) }; let (k31, k32, one, z) = ( self.s.m.i32(31), @@ -2334,46 +4252,6 @@ impl<'a> Lower<'a> { self.s.m.cmp(at, pred::NE, t, z) } - fn select_condition(&mut self, inst: &Inst, mask: Option<&Operand>) -> Result<V, Why> { - if let Some(&m) = inst - .writes - .first() - .and_then(|&(_, v)| self.x.st.select_masks.get(&v)) - { - return self.boolean(m, self.cur); - } - self.numeric_mask(inst, mask) - } - - /// This lane's bit of a select or carry-in mask `structure` did not - /// follow: inline 0 and -1 are constants; a scalar register (pair in - /// wave64) is tested by the console lane, in compute programs run with - /// console lanes (the retry after [`UNTRACKED_SELECT`]). - fn numeric_mask(&mut self, inst: &Inst, mask: Option<&Operand>) -> Result<V, Why> { - let code = match mask { - Some(&Operand::Scalar { code, .. }) => code, - Some(&Operand::Const(128)) => return Ok(self.s.m.bool(false)), - Some(&Operand::Const(193)) => return Ok(self.s.m.bool(true)), - _ => return Err(UNTRACKED_SELECT), - }; - if code == NULL { - return Ok(self.s.m.bool(false)); - } - if !self.numeric_selects || !self.console_lanes { - return Err(UNTRACKED_SELECT); - } - // A scalar operation can define either dword independently. The SSA - // operands at this use give the actual pair, even across a join. - let lo = self.i32_of(inst.read(Reg::S(code)).ok_or(UNTRACKED_SELECT)?)?; - let hi = if self.x.p.wave64 { - Some(self.i32_of(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED_SELECT)?)?) - } else { - None - }; - self.s.flags |= flags::WAVE_OPS; - Ok(self.lane_bit(self.cur, lo, hi)) - } - /// The value of the high dword of the wave64 register pair whose low /// dword holds `lo` (none in wave32). fn pair_high(&self, lo: Value) -> Option<Value> { @@ -2440,7 +4318,9 @@ impl<'a> Lower<'a> { // The validator refuses reads of undef. _ => self.s.m.i32(0), }; - self.s.m.select(self.cur, g, x, old) + let v = self.s.m.select(self.cur, g, x, old); + self.s.m.tag(v, Tag::Guard); + v } _ => x, }; @@ -2534,7 +4414,6 @@ impl<'a> Lower<'a> { /// lane guard): returns where it started and the join block. fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> { let g = guard?; - self.guard_depth += 1; let (then, join) = (self.s.m.new_block(), self.s.m.new_block()); self.s.m.terminate(self.cur, Term::CondBr(g, then, join)); let head = self.cur; @@ -2547,7 +4426,6 @@ impl<'a> Lower<'a> { let Some((head, join)) = at else { return values.iter().map(|v| v.0).collect(); }; - self.guard_depth -= 1; let then = self.cur; self.s.m.terminate(then, Term::Br(join)); self.cur = join; @@ -2576,9 +4454,7 @@ impl<'a> Lower<'a> { return Err("a cross-lane operation outside compute"); } debug_assert!(self.s.threads.is_none() || self.console_lanes); - if self.emulated.is_none() { - self.s.flags |= flags::WAVE_OPS; - } + self.s.flags |= flags::WAVE_OPS; Ok(()) } @@ -2588,12 +4464,25 @@ impl<'a> Lower<'a> { /// plus the lane index. (A bijection while each host wave holds a /// wave-aligned run of flat ids, as the console's waves do.) fn thread_id(&mut self, c: u8) -> Val { - if !self.console_lanes || self.emulated.is_some() { + if !self.console_lanes { return self.compute_id("threadIdInGroup.i32", 95, c); } let [x, y, _] = self.s.threads.expect("compute"); let e = self.s.entry; let i32t = self.s.t.i32; + if self.halves.is_some() { + let f = self.console_thread(); + self.s.flags |= flags::WAVE_OPS; + let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y)); + return Val::I32(match c { + 0 => self.s.m.bin(e, Bin::URem, f, xk), + 1 => { + let t = self.s.m.bin(e, Bin::UDiv, f, xk); + self.s.m.bin(e, Bin::URem, t, yk) + } + _ => self.s.m.bin(e, Bin::UDiv, f, xy), + }); + } let flat = self.s.op( e, "flattenedThreadIdInGroup.i32", @@ -2635,7 +4524,7 @@ impl<'a> Lower<'a> { // program's count are culled and vertices past it unused; this costs // the host the unused vertex and primitive slots. Pass the program's own // counts if that shows in frame time. - fn mesh_prologue(&mut self, mesh: super::shader::Mesh) -> Result<(), Why> { + fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> { let threads = self.s.threads.expect("mesh")[0]; if mesh.topology != 2 { return Err("a mesh shader not drawing triangles"); @@ -2643,6 +4532,27 @@ impl<'a> Lower<'a> { if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 { return Err("a mesh shader beyond the host's limits"); } + // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n + // writes only vertex n and primitive n, so maxima past the lanes are + // never reached: they come down to the lane count when the outputs + // do not fit. + use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes}; + let (outputs, prims) = (&self.s.outputs, &self.s.prims); + let fits = |m: super::shader::Mesh| { + mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT + }; + if !fits(mesh) { + mesh.max_vertices = mesh.max_vertices.min(threads); + mesh.max_primitives = mesh.max_primitives.min(threads); + // shortcut: outputs past the cap even at the lane count are + // still emitted with the lower maxima (drivers take them); + // refuse them here if one hangs. + // Experiment (`VICTORY_MESH_OUTPUT_STRICT=1`): they are refused. + if !fits(mesh) && std::env::var_os("VICTORY_MESH_OUTPUT_STRICT").is_some() { + return Err("a mesh shader whose outputs pass the host's 32 KiB"); + } + self.s.mesh = Some(mesh); + } let e = self.s.entry; let void = self.s.t.void; let (v, p) = ( @@ -2652,18 +4562,33 @@ impl<'a> Lower<'a> { self.s .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); let flat = self.mesh_thread(); - let guard = (threads > mesh.max_primitives).then(|| self.s.m.cmp(e, pred::IULT, flat, p)); - let at = self.begin_guarded(guard); let z = self.s.m.i32(0); - self.s.op( - self.cur, - "emitIndices", - Attr::NoUnwind, - void, - 169, - &[flat, z, z, z], - ); - self.end_guarded(at, &[]); + // Every primitive of the declared count starts culled, also those + // past the lanes (a count of 256 with 128 lanes): lane n culls + // primitives n, n + lanes, ... The host draws all it was promised, + // and one never written has whatever indices its memory held: long + // triangles over the whole target, each pixel of them shaded. + let passes = mesh.max_primitives.div_ceil(threads.max(1)); + for pass in 0..passes { + let index = if pass == 0 { + flat + } else { + let past = self.s.m.i32(pass * threads); + self.s.m.bin(self.cur, Bin::Add, flat, past) + }; + let guard = ((pass + 1) * threads > mesh.max_primitives) + .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p)); + let at = self.begin_guarded(guard); + self.s.op( + self.cur, + "emitIndices", + Attr::NoUnwind, + void, + 169, + &[index, z, z, z], + ); + self.end_guarded(at, &[]); + } Ok(()) } @@ -2692,10 +4617,6 @@ impl<'a> Lower<'a> { } fn lane_index(&mut self) -> V { - if self.emulated.is_some() { - // Console lane n is the thread with flattened id n. - return self.mesh_thread(); - } if self.s.mesh.is_some() { // The console's lane: mesh code reads no other lanes, so host // waves need not match the console's. @@ -2713,6 +4634,17 @@ impl<'a> Lower<'a> { ) } + /// Whether a read of another lane of this lane's quad must reach helper + /// lanes: in a pixel shader, always. At a triangle's edge the quad's + /// other pixels are helpers (and so are discarded ones), which only quad + /// reads see: wave reads give 0 from them, so a derivative taken by hand + /// (`quad_perm`) was the whole value there, the texture read that used it + /// took its smallest level, and the triangles' edges showed as lines on + /// car paint, glass and skin (Belobug/VIctory-Belobug-AMD 03629f3). + fn helpers_read(&self, quad: bool) -> bool { + quad && self.s.pixel + } + /// `x` of lane `src` (in this lane's quad) through quad reads, whose /// lane must be a constant. fn quad_pick(&mut self, x: V, src: V) -> V { @@ -2737,116 +4669,45 @@ impl<'a> Lower<'a> { r } - fn read_lane(&mut self, x: V, lane: V) -> Result<V, Why> { - if self.emulated.is_some() { - let at = self.cur; - self.emulated_here(self.cur_ir, at)?; - let me = self.mesh_thread(); - let p = self.slot(at, me); - self.s.m.store(at, p, x); - self.group_sync(at); - let q = self.slot(at, lane); - let r = self.s.m.load(at, q); - self.group_sync(at); - return Ok(r); - } - Ok(self.s.op( + /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a + /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear + /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here. + fn first_lane(&mut self, x: V, guard: Option<V>) -> (V, V) { + let c = self.cur; + let i32t = self.s.t.i32; + self.s.flags |= flags::WAVE_OPS; + let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]); + let Some(g) = guard else { + return (first, self.s.m.bool(true)); + }; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]); + let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1)); + let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32)); + // FirstbitLo (dx.op 32): the lowest set bit + let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]); + let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]); + let fhi = self.s.m.bin(c, Bin::Add, fhi, k32); + let in_lo = self.s.m.cmp(c, pred::NE, lo, z); + let in_hi = self.s.m.cmp(c, pred::NE, hi, z); + let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi); + let lane = self.s.m.select(c, in_lo, flo, fhi); + // no lane in EXEC: read this lane (one that is here); the read is not used + let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self.s.m.select(c, any, lane, me); + let at = self.read_lane(x, lane); + (self.s.m.select(c, any, at, first), any) + } + + fn read_lane(&mut self, x: V, lane: V) -> V { + self.s.op( self.cur, "waveReadLaneAt.i32", Attr::NoUnwind, self.s.t.i32, 117, &[x, lane], - )) - } - - /// [`Emulated`]: whether a step reading other lanes may run in DXIL - /// block `at`, which IR block `ir` lowers to (every lane must get there). - fn emulated_here(&self, ir: usize, at: usize) -> Result<(), Why> { - let em = self.emulated.as_ref().expect("emulated"); - if !em.uniform[ir] || at == self.cur && self.guard_depth > 0 { - return Err("a step across lanes in lane-dependent code on a host \ - without 64-lane waves"); - } - Ok(()) - } - - /// [`Emulated`]: the exchange slot of console lane `lane` (modulo 64), - /// addressed in `at`. - fn slot(&mut self, at: usize, lane: V) -> V { - let g = match self.emulated.as_ref().and_then(|e| e.slots) { - Some(g) => g, - None => { - let arr = self.s.m.array(64, self.s.t.i32); - let g = self.s.m.global("xlane", arr, 3); - self.emulated.as_mut().expect("emulated").slots = Some(g); - g - } - }; - let k63 = self.s.m.i32(63); - let i = self.s.m.bin(at, Bin::And, lane, k63); - self.s.m.element(at, g, i) - } - - /// A group barrier with a group-shared memory fence, in `at`. - fn group_sync(&mut self, at: usize) { - let mode = self.s.m.i32(1 | 8); - let void = self.s.t.void; - self.s - .op(at, "barrier", Attr::NoDuplicate, void, 80, &[mode]); - } - - /// [`Emulated`]: every console lane's `x`, lane 0 first, in `at`. - fn gather(&mut self, at: usize, x: V) -> Vec<V> { - let me = self.mesh_thread(); - let p = self.slot(at, me); - self.s.m.store(at, p, x); - self.group_sync(at); - let lanes = self.emulated.as_ref().expect("emulated").lanes; - let out = (0..lanes) - .map(|n| { - let k = self.s.m.i32(n); - let q = self.slot(at, k); - self.s.m.load(at, q) - }) - .collect(); - self.group_sync(at); - out - } - - /// Coarse derivatives of `coords` across this lane's quad, as DXIL - /// gradients (x for up to three coordinates, then y), each times - /// `scale` if given. - fn quad_gradients(&mut self, coords: &[V], scale: Option<V>) -> Result<Vec<V>, Why> { - let c = self.cur; - let lane = self.lane_index(); - let top = self.s.m.i32(!3); - let base = self.s.m.bin(c, Bin::And, lane, top); - let lanes: Vec<V> = (1..3u32) - .map(|k| { - let k = self.s.m.i32(k); - self.s.m.bin(c, Bin::Or, base, k) - }) - .collect(); - let fu = self.s.m.undef(self.s.t.f32); - let mut g = vec![fu; 6]; - for (k, &x) in coords.iter().enumerate().take(3) { - let xi = self.as_int(x); - let at = |l: &mut Self, lane: V| -> Result<V, Why> { - let r = l.read_lane(xi, lane)?; - Ok(l.as_float(r)) - }; - let origin = at(self, base)?; - for (d, &lane) in lanes.iter().enumerate() { - let there = at(self, lane)?; - let mut diff = self.s.m.bin(c, Bin::Sub, there, origin); - if let Some(s) = scale { - diff = self.s.m.bin(c, Bin::Mul, diff, s); - } - g[3 * d + k] = diff; - } - } - Ok(g) + ) } /// The float value of a register value. @@ -2888,7 +4749,13 @@ impl<'a> Lower<'a> { return Err("GDS"); } let name = inst.name(); - let guard = self.guard(b, i)?; + // Lanes past a DispatchX count neither read nor write LDS; a + // swizzle or permute moves registers only, under its own guard. + let guard = if name == "ds_swizzle_b32" || name.contains("permute") { + self.guard(b, i)? + } else { + self.effect_guard(b, i)? + }; let c = self.cur; let offset = u32::from(*offset0) | u32::from(*offset1) << 8; let dst_reg = match dst { @@ -2928,44 +4795,67 @@ impl<'a> Lower<'a> { let t = self.s.m.bin(c, Bin::Or, t, or); self.s.m.bin(c, Bin::Xor, t, xor) }; - let r = if mesh_quad { + let r = if mesh_quad || self.helpers_read(quad) { self.quad_pick(x, src) } else { - self.read_lane(x, src)? + self.read_lane(x, src) }; let reg = dst_reg.ok_or("a swizzle result")?; self.write(inst, Reg::V(reg), r, guard); return Ok(()); } + if name == "ds_bpermute_b32" { + // Backward permute: no LDS is touched. Each lane takes the data + // register of the lane its address names, (address + offset) / 4 + // within the wave; a source lane outside EXEC gives 0. ( + // the title's checkerboard shadow-mask generators read their + // neighbours' samples with it; without them every shadowed light + // was multiplied by an empty mask.) + // shortcut: a source lane that is not at this instruction on the + // host (it left through a branch, not a guard) is read as the + // host gives it; the console reads 0. + self.cross_lane(false)?; + // a console wave of 64 run as two host waves: the lane named may be in the other + // one (the last resort reads this host wave's lane of that number instead) + let own_half = self.local && self.local_any; + if self.exchange.as_ref().is_some_and(|e| !e.1) && !own_half { + return Err("a lane permute across two host waves"); + } + let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0]; + let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0]; + let o = self.s.m.i32(offset); + let at = self.s.m.bin(c, Bin::Add, at, o); + let two = self.s.m.i32(2); + let src = self.s.m.bin(c, Bin::LShr, at, two); + let last = self.s.m.i32(if own_half { 31 } else { self.wave() - 1 }); + let src = self.s.m.bin(c, Bin::And, src, last); + let x = match guard { + Some(g) => { + let z = self.s.m.i32(0); + self.s.m.select(c, g, x, z) + } + None => x, + }; + let r = self.read_lane(x, src); + let reg = dst_reg.ok_or("a permute result")?; + self.write(inst, Reg::V(reg), r, guard); + return Ok(()); + } if self.s.lds_dwords == 0 { return Err("LDS the program does not allocate"); } - if self.emulated.is_some() { - // The console's lanes reach each LDS access together; the - // host's two waves wait for each other before one. - let at = self.cur; - self.emulated_here(self.cur_ir, at)?; - self.group_sync(at); - } let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0]; - // shortcut: LDS addresses are taken as aligned and in bounds + // shortcut: LDS addresses are taken as dword-aligned and in bounds // (out-of-bounds console accesses read 0 and drop writes). - let byte_addr = |l: &mut Self, bytes: u32| -> V { + let dword = |l: &mut Self, bytes: u32| -> V { let c = l.cur; let o = l.s.m.i32(bytes); - l.s.m.bin(c, Bin::Add, a, o) - }; - let dword_at = |l: &mut Self, at: V| -> V { - let c = l.cur; + let at = l.s.m.bin(c, Bin::Add, a, o); let two = l.s.m.i32(2); let index = l.s.m.bin(c, Bin::LShr, at, two); let lds = l.s.lds(); l.s.m.element(c, lds, index) }; - let dword = |l: &mut Self, bytes: u32| -> V { - let at = byte_addr(l, bytes); - dword_at(l, at) - }; let width = |n: &str| match n.rsplit('_').next() { Some("b64") => 2, Some("b96") => 3, @@ -2982,119 +4872,121 @@ impl<'a> Lower<'a> { (u32::from(*offset1) * scale, w), ] }; - if let Some(rest) = name.strip_prefix("ds_read") { - let reg = dst_reg.ok_or("an LDS read result")?; - if rest.starts_with('2') || matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { - let elements = if rest.starts_with('2') { - pair(name) + // Bytes and halves: the dword holding them, and their bit position + // in it (naturally aligned, so they never straddle dwords). + // `_d16` reads fill a register's low half (`_d16_hi` its high half) + // and keep the other; `_d16_hi` writes take the data's high half. + let base = name.trim_end_matches("_hi").trim_end_matches("_d16"); + let sub = match base { + "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32), + "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16), + _ => None, + }; + let sub = sub.filter(|_| { + base == name + || name.ends_with("_d16") && base.starts_with("ds_read") + || name.ends_with("_d16_hi") + }); + if let Some(bits) = sub { + let p = dword(self, offset); + let o = self.s.m.i32(offset); + let at = self.s.m.bin(c, Bin::Add, a, o); + let three = self.s.m.i32(3); + let byte = self.s.m.bin(c, Bin::And, at, three); + let sh = self.s.m.bin(c, Bin::Shl, byte, three); + let mask = self.s.m.i32((1u32 << bits) - 1); + if name.starts_with("ds_read") { + let reg = dst_reg.ok_or("an LDS read result")?; + let w = self.s.m.load(c, p); + let x = self.s.m.bin(c, Bin::LShr, w, sh); + let x = if base.contains("_i") { + let k = self.s.m.i32(32 - bits); + let x = self.s.m.bin(c, Bin::Shl, x, k); + self.s.m.bin(c, Bin::AShr, x, k) } else { - vec![(offset, width(name))] + self.s.m.bin(c, Bin::And, x, mask) }; - let mut n = 0; - for (off, w) in elements { - for k in 0..w { - let p = dword(self, off + 4 * k); - let x = self.s.m.load(self.cur, p); - self.write(inst, Reg::V(reg + n), x, guard); - n += 1; - } + let x = if base == name { + x + } else { + let old = match inst.read(Reg::V(reg)) { + Some(v) => self.i32_of(v)?, + None => self.s.m.i32(0), + }; + let half = self.s.m.i32(0xFFFF); + let x = self.s.m.bin(c, Bin::And, x, half); + let (x, keep) = if name.ends_with("_hi") { + let k16 = self.s.m.i32(16); + (self.s.m.bin(c, Bin::Shl, x, k16), half) + } else { + (x, self.s.m.i32(0xFFFF_0000)) + }; + let old = self.s.m.bin(c, Bin::And, old, keep); + self.s.m.bin(c, Bin::Or, old, x) + }; + self.write(inst, Reg::V(reg), x, guard); + } else { + // Clear, then set: two atomics, so lanes writing other + // bytes of the dword keep theirs. + let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0]; + if name != base { + // The data's high half. + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); } - return Ok(()); + let x = self.s.m.bin(c, Bin::And, x, mask); + let x = self.s.m.bin(c, Bin::Shl, x, sh); + let m = self.s.m.bin(c, Bin::Shl, mask, sh); + let ones = self.s.m.i32(u32::MAX); + let keep = self.s.m.bin(c, Bin::Xor, m, ones); + use super::bitcode::Rmw; + let at = self.begin_guarded(guard); + self.s.m.atomic(self.cur, Rmw::And, p, keep); + self.s.m.atomic(self.cur, Rmw::Or, p, x); + self.end_guarded(at, &[]); } - let (bytes, signed, d16) = match rest { - "_u8" => (1u32, false, None), - "_i8" => (1, true, None), - "_u16" => (2, false, None), - "_i16" => (2, true, None), - "_u8_d16" => (1, false, Some(false)), - "_u8_d16_hi" => (1, false, Some(true)), - "_i8_d16" => (1, true, Some(false)), - "_i8_d16_hi" => (1, true, Some(true)), - "_u16_d16" => (2, false, Some(false)), - "_u16_d16_hi" => (2, false, Some(true)), - _ => return Err("an LDS read of bytes or halves"), - }; - let at = byte_addr(self, offset); - let p = dword_at(self, at); - let word = self.s.m.load(self.cur, p); - let c = self.cur; - let lane_mask = self.s.m.i32(if bytes == 1 { 3 } else { 2 }); - let three = self.s.m.i32(3); - let off_in_word = self.s.m.bin(c, Bin::And, at, lane_mask); - let shift = self.s.m.bin(c, Bin::Shl, off_in_word, three); - let raw = self.s.m.bin(c, Bin::LShr, word, shift); - let ext = if signed { - let k = self.s.m.i32(32 - 8 * bytes); - let hi = self.s.m.bin(c, Bin::Shl, raw, k); - self.s.m.bin(c, Bin::AShr, hi, k) + return Ok(()); + } + if let Some(rest) = name.strip_prefix("ds_read") { + let elements = if rest.starts_with('2') { + pair(name) + } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { + vec![(offset, width(name))] } else { - let m = self.s.m.i32(if bytes == 1 { 0xFF } else { 0xFFFF }); - self.s.m.bin(c, Bin::And, raw, m) - }; - let x = match d16 { - None => ext, - Some(false) => self.low_half(inst, reg, ext), - Some(true) => self.high_half(inst, reg, ext), + return Err("an LDS read of bytes or halves"); }; - self.write(inst, Reg::V(reg), x, guard); + let reg = dst_reg.ok_or("an LDS read result")?; + let mut n = 0; + for (off, w) in elements { + for k in 0..w { + let p = dword(self, off + 4 * k); + let x = self.s.m.load(self.cur, p); + self.write(inst, Reg::V(reg + n), x, guard); + n += 1; + } + } return Ok(()); } if let Some(rest) = name.strip_prefix("ds_write") { - if rest.starts_with('2') || matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { - let elements = if rest.starts_with('2') { - pair(name) - } else { - vec![(offset, width(name))] - }; - let mut stores = Vec::new(); - for (e, (off, w)) in elements.into_iter().enumerate() { - let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?; - for (k, x) in vals.into_iter().enumerate() { - stores.push((off + 4 * k as u32, x)); - } - } - let at = self.begin_guarded(guard); - for (off, x) in stores { - let p = dword(self, off); - self.s.m.store(self.cur, p, x); - } - self.end_guarded(at, &[]); - return Ok(()); - } - let (bytes, hi_src) = match rest { - "_b8" => (1u32, false), - "_b16" => (2, false), - "_b8_d16_hi" => (1, true), - "_b16_d16_hi" => (2, true), - _ => return Err("an LDS write of bytes or halves"), + let elements = if rest.starts_with('2') { + pair(name) + } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { + vec![(offset, width(name))] + } else { + return Err("an LDS write of bytes or halves"); }; - let mut val = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0]; - let at_bytes = byte_addr(self, offset); - let p = dword_at(self, at_bytes); - let c = self.cur; - if hi_src { - let k16 = self.s.m.i32(16); - val = self.s.m.bin(c, Bin::LShr, val, k16); + let mut stores = Vec::new(); + for (e, (off, w)) in elements.into_iter().enumerate() { + let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?; + for (k, x) in vals.into_iter().enumerate() { + stores.push((off + 4 * k as u32, x)); + } } - let mask_val = self.s.m.i32(if bytes == 1 { 0xFF } else { 0xFFFF }); - let val = self.s.m.bin(c, Bin::And, val, mask_val); - let lane_mask = self.s.m.i32(if bytes == 1 { 3 } else { 2 }); - let three = self.s.m.i32(3); - let off_in_word = self.s.m.bin(c, Bin::And, at_bytes, lane_mask); - let shift = self.s.m.bin(c, Bin::Shl, off_in_word, three); - let shifted_mask = self.s.m.bin(c, Bin::Shl, mask_val, shift); - let all_ones = self.s.m.i32(!0u32); - let clear_mask = self.s.m.bin(c, Bin::Xor, shifted_mask, all_ones); - let shifted_val = self.s.m.bin(c, Bin::Shl, val, shift); - // Atomic clear + set so concurrent lanes writing adjacent bytes or - // halves within the same 32-bit dword do not race. let at = self.begin_guarded(guard); - self.s - .m - .atomic(self.cur, super::bitcode::Rmw::And, p, clear_mask); - self.s - .m - .atomic(self.cur, super::bitcode::Rmw::Or, p, shifted_val); + for (off, x) in stores { + let p = dword(self, off); + self.s.m.store(self.cur, p, x); + } self.end_guarded(at, &[]); return Ok(()); } @@ -3115,7 +5007,7 @@ impl<'a> Lower<'a> { "min_u32" => Some(Rmw::UMin), "max_u32" => Some(Rmw::UMax), "wrxchg_b32" => Some(Rmw::Xchg), - "cmpst_b32" => None, + "cmpst_b32" | "max_f32" | "min_f32" => None, _ => return Err("an LDS operation"), }; let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0]; @@ -3129,6 +5021,19 @@ impl<'a> Lower<'a> { None => self.s.m.i32(0), }; let p = dword(self, offset); + if let Some(max) = match op.as_str() { + "max_f32" => Some(true), + "min_f32" => Some(false), + _ => None, + } { + let at = self.begin_guarded(guard); + let r = self.lds_float_min_max(p, v0, max); + let r = self.end_guarded(at, &[(r, outside)])[0]; + if let Some(reg) = dst_reg { + self.write(inst, Reg::V(reg), r, None); + } + return Ok(()); + } let at = self.begin_guarded(guard); let r = match rmw { Some(op) => self.s.m.atomic(self.cur, op, p, v0), @@ -3145,12 +5050,98 @@ impl<'a> Lower<'a> { Ok(()) } + /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with + /// the float bits `data`; the old bits return. + /// + /// DXIL has no float atomics on group-shared memory, so this is a + /// compare-exchange loop around [`Lower::lds_float_pick`], which gives + /// what RDNA2 writes (measured on gfx1036, reported on the pull + /// request): an sNaN, data first, then memory, is written quieted; + /// otherwise a NaN loses to a number (two quiet NaNs give the data); + /// numbers compare as floats with -0 below +0. + // shortcut: f32 denormals compare as kept; with the console's MODE + // flushing them they would order as ±0 first (MODE is not modelled). + fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V { + let pre = self.cur; + let init = self.s.m.load(pre, p); + let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(pre, Term::Br(lp)); + let i32t = self.s.t.i32; + let old = self.s.m.phi(lp, i32t); + self.cur = lp; + let new = self.lds_float_pick(old, data, max); + let prev = self.s.m.cmpxchg(lp, p, old, new); + let done = self.s.m.cmp(lp, pred::EQ, prev, old); + self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]); + self.s.m.terminate(lp, Term::CondBr(done, exit, lp)); + self.cur = exit; + old + } + + /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword + /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]). + fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V { + let c = self.cur; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (abs_mask, inf, quiet, zero) = ( + k(self, 0x7FFF_FFFF), + k(self, 0x7F80_0000), + k(self, 0x40_0000), + k(self, 0), + ); + let nan = |l: &mut Self, x: V| { + let m = l.s.m.bin(c, Bin::And, x, abs_mask); + l.s.m.cmp(c, pred::IUGT, m, inf) + }; + let snan = |l: &mut Self, x: V| { + let n = nan(l, x); + let q = l.s.m.bin(c, Bin::And, x, quiet); + let sig = l.s.m.cmp(c, pred::EQ, q, zero); + l.s.m.bin(c, Bin::And, n, sig) + }; + // A total order of the numbers as signed integers, -0 below +0: + // negative floats' magnitude bits reversed. + let key = |l: &mut Self, x: V| { + let k31 = l.s.m.i32(31); + let sign = l.s.m.bin(c, Bin::AShr, x, k31); + let flip = l.s.m.bin(c, Bin::And, sign, abs_mask); + l.s.m.bin(c, Bin::Xor, x, flip) + }; + let (dk, mk) = (key(self, data), key(self, mem)); + let take = self + .s + .m + .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk); + let r = self.s.m.select(c, take, data, mem); + let (dn, mn) = (nan(self, data), nan(self, mem)); + // One NaN: the number; two quiet NaNs: the data. + let r = self.s.m.select(c, mn, data, r); + let both = self.s.m.bin(c, Bin::And, dn, mn); + let only_data = { + let t = self.s.m.bool(true); + let not_both = self.s.m.bin(c, Bin::Xor, both, t); + self.s.m.bin(c, Bin::And, dn, not_both) + }; + let r = self.s.m.select(c, only_data, mem, r); + // Signalling NaNs win, quieted: the data's first. + let qm = self.s.m.bin(c, Bin::Or, mem, quiet); + let sm = snan(self, mem); + let r = self.s.m.select(c, sm, qm, r); + let qd = self.s.m.bin(c, Bin::Or, data, quiet); + let sd = snan(self, data); + self.s.m.select(c, sd, qd, r) + } + + // ---- instructions ---- // ---- instructions ---- fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> { let inst: &'a Inst = &self.x.p.blocks[b].insts[i]; let offset = inst.machine.offset; let name = inst.name(); + self.local_ok = name.starts_with("s_bcnt1_i32_") + || name.starts_with("s_ff1_i32_") + || name.starts_with("v_mbcnt_"); self.mask_ok = match self.mask_data { MaskData::Console => true, MaskData::Host => { @@ -3162,7 +5153,9 @@ impl<'a> Lower<'a> { "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64" ) } - MaskData::None => false, + // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which + // each host wave answers for itself. + MaskData::None => self.uniform_test(inst), }; let effect = matches!(inst.fields, Fields::Exp { .. }) || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") @@ -3173,6 +5166,17 @@ impl<'a> Lower<'a> { && !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute")); + if self.split_lds + && matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_swizzle") || name.contains("permute")) + && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b]) + { + // the two host waves of a console wave meet before each LDS access: what the other + // half wrote is visible, and what it still reads is not overwritten + let mode = self.s.m.i32(meeting_mode()); + let void = self.s.t.void; + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } let r = match &inst.fields { Fields::Sop { .. } => self.sop(inst), Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()), @@ -3180,7 +5184,17 @@ impl<'a> Lower<'a> { // Thread-group sync with a shared-memory fence, and a UAV // fence when the program writes UAVs (the waits before an // s_barrier make those writes visible on the console). - let mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 }; + let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 }; + // Without the wait for the group (bit 0) where not every + // lane arrives, or where the switch says so. + let waits = match super::group_sync() { + 0 => false, + 1 => !self.fence_only.contains(&b), + _ => true, + }; + if !waits { + mode &= !1; + } let mode = self.s.m.i32(mode); let void = self.s.t.void; self.s @@ -3192,6 +5206,15 @@ impl<'a> Lower<'a> { Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)), Fields::Valu(_) => self.valu(inst, b, i), Fields::Vintrp { .. } => self.interp(inst, (b, i)), + // The ray and node test. A failure is a refusal at once: an + // instruction without a side effect otherwise only stops the + // program where its results are needed, and two trace programs + // came out without their test that way. + Fields::Image { .. } if name.starts_with("image_bvh") => { + return self + .bvh(inst, b, i) + .map_err(|why| unsupported(offset, why)); + } Fields::Image { .. } => self.image(inst, b, i), Fields::Buffer { .. } => self.buffer(inst, b, i), Fields::Exp { .. } => self.export(b, i), @@ -3211,6 +5234,103 @@ impl<'a> Lower<'a> { } } + /// The two host waves of a console wave meet (a group barrier with a shared-memory + /// fence): LDS writes before are seen by reads after. + fn lds_meeting(&mut self) { + let mode = self.s.m.i32(meeting_mode()); + let void = self.s.t.void; + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + + /// Whether `v` is a register no program reads as a number: a descriptor dword without + /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot + /// gives the mask as data), or a join of only such values. Compiled code joins numbers + /// with numbers: where one of these meets numbers at a join, the register is dead on + /// that path (a variable set in one arm of a branch, its use behind a flag kept in a + /// VGPR). + fn dead(&self, v: Value, seen: &mut Vec<Value>) -> bool { + if self.stale.contains(&v) { + return true; + } + let st = self.x.st; + if self.mask_data != MaskData::Console + && (st.masks.contains_key(&v) || st.highs.contains_key(&v)) + { + return true; + } + let Some(&(b, i)) = self.phi_at.get(&v) else { + return false; + }; + if seen.contains(&v) { + return true; + } + seen.push(v); + self.x.p.blocks[b].phis[i] + .args + .iter() + .all(|&a| self.dead(a, seen)) + } + + /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value: + /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The + /// compiler tests a value for being the same in the whole wave this way, to take a + /// scalar path; both paths give each lane the same result, so the lanes of a host + /// wave may ask it of their own first lane, whatever the wave's size. + fn uniform_test(&self, inst: &Inst) -> bool { + let p = self.x.p; + let writer = |v: Value| -> Option<&'a Inst> { + let b = *self.def_block.get(&v)?; + p.blocks[b] + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == v)) + }; + let scalar = |i: &Inst, op: &Operand| match *op { + Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)), + _ => None, + }; + if !inst.name().starts_with("s_bcnt1_i32_") { + return false; + } + let Fields::Sop { src, .. } = &inst.fields else { + return false; + }; + let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else { + return false; + }; + let Fields::Sop { src, .. } = &xor.fields else { + return false; + }; + if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32") + || !src + .iter() + .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. })) + { + return false; + } + let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else { + return false; + }; + let Fields::Valu(f) = &cmp.fields else { + return false; + }; + if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() { + return false; + } + let lanes = f.src.iter().find_map(|o| match *o { + Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)), + _ => None, + }); + let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer); + lanes.is_some() + && first.is_some_and(|fl| { + fl.name() == "v_readfirstlane_b32" + && matches!(&fl.fields, Fields::Valu(g) + if matches!(g.src.first(), Some(&Operand::Vector { reg, .. }) + if fl.read(Reg::V(reg)) == lanes)) + }) + } + fn is_mask(&self, v: Option<Value>) -> bool { v.is_some_and(|v| self.x.st.masks.contains_key(&v)) } @@ -3238,6 +5358,19 @@ impl<'a> Lower<'a> { // vertex fetch call, whose results arrive as inputs. return Err("a register the emitter does not model"); } + if name == "s_getpc_b64" { + // The address of the next instruction is no number the host has: tables in + // the code are read by their tracked address. As a number the counter is + // that instruction's offset in the code, so an address paths join before + // one load is the byte in the code, whichever table each path took + // (resource tracking gives such a join as the computed term, with no base). + let z = self.s.m.i32(0); + let at = self.s.m.i32(inst.machine.offset as u32 + 4); + let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1))); + self.set(lo, Val::I32(at)); + self.set(hi, Val::I32(z)); + return Ok(()); + } let c = self.cur; let src32 = |l: &mut Self, k: usize| -> Result<V, Why> { // SOPK arithmetic reads its destination as the first source. @@ -3261,13 +5394,32 @@ impl<'a> Lower<'a> { let x = crate::resource::inline(*k).ok_or("a special operand")?; Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) } - // Of a signed operand, a literal sign-extends too. - Some(&Operand::Literal(x)) if name.ends_with("_i64") => { - Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) - } _ => Ok(l.s.m.i32(0)), } }; + if let Some(op) = name.strip_prefix("s_bitcmp") { + // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form) + // of src0 is clear (bitcmp0) or set (bitcmp1). + let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31)); + let idx = self.s.m.bin(c, Bin::And, bit, k31); + let word = if op.ends_with("_b64") { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let k32 = self.s.m.i32(32); + let upper = self.s.m.bin(c, Bin::And, bit, k32); + let z = self.s.m.i32(0); + let upper = self.s.m.cmp(c, pred::NE, upper, z); + self.s.m.select(c, upper, b, a) + } else { + src32(self, 0)? + }; + let shifted = self.s.m.bin(c, Bin::LShr, word, idx); + let one = self.s.m.i32(1); + let tested = self.s.m.bin(c, Bin::And, shifted, one); + let want = self.s.m.i32(u32::from(op.starts_with('1'))); + let r = self.s.m.cmp(c, pred::EQ, tested, want); + self.set(scc, Val::Bit(r)); + return Ok(()); + } if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) { // eq and lg only: both dwords. let mut r = None; @@ -3319,31 +5471,6 @@ impl<'a> Lower<'a> { self.set(scc, Val::Bit(r)); return Ok(()); } - if matches!( - name, - "s_bitcmp0_b32" | "s_bitcmp1_b32" | "s_bitcmp0_b64" | "s_bitcmp1_b64" - ) { - let want_one = name.starts_with("s_bitcmp1_"); - let wide = name.ends_with("_b64"); - let bit = src32(self, 1)?; - let (k31, one, zero) = (self.s.m.i32(31), self.s.m.i32(1), self.s.m.i32(0)); - let word = if wide { - let (lo_w, hi_w) = (half(self, 0, 0)?, half(self, 0, 1)?); - let k32 = self.s.m.i32(32); - let hi_bit = self.s.m.bin(c, Bin::And, bit, k32); - let is_hi = self.s.m.cmp(c, pred::NE, hi_bit, zero); - self.s.m.select(c, is_hi, hi_w, lo_w) - } else { - src32(self, 0)? - }; - let shift = self.s.m.bin(c, Bin::And, bit, k31); - let shifted = self.s.m.bin(c, Bin::LShr, word, shift); - let masked = self.s.m.bin(c, Bin::And, shifted, one); - let p = if want_one { pred::NE } else { pred::EQ }; - let r = self.s.m.cmp(c, p, masked, zero); - self.set(scc, Val::Bit(r)); - return Ok(()); - } let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64"); if wide { let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1))); @@ -3450,9 +5577,15 @@ impl<'a> Lower<'a> { Ok(()) } "s_mov_b64" => { - let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); - self.set(lo, Val::I32(a)); - self.set(hi, Val::I32(b)); + // Each half by itself: two numbers that travel as a pair (two scalars + // parked in neighbouring VGPR lanes, say) need not both have a value. + for (h, v) in [(0, lo), (1, hi)] { + let val = match half(self, 0, h) { + Ok(a) => Val::I32(a), + Err(why) => Val::Missing(why), + }; + self.set(v, val); + } Ok(()) } "s_cselect_b64" => { @@ -3484,12 +5617,6 @@ impl<'a> Lower<'a> { .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]); (r, None) } - "s_sext_i32_i8" | "s_sext_i32_i16" => { - let a = src32(self, 0)?; - let shift = self.s.m.i32(if name == "s_sext_i32_i8" { 24 } else { 16 }); - let t = self.s.m.bin(c, Bin::Shl, a, shift); - (self.s.m.bin(c, Bin::AShr, t, shift), None) - } "s_not_b32" => { let a = src32(self, 0)?; let ones = self.s.m.i32(u32::MAX); @@ -3652,8 +5779,6 @@ impl<'a> Lower<'a> { | "s_movk_i32" | "s_cselect_b32" | "s_brev_b32" - | "s_sext_i32_i8" - | "s_sext_i32_i16" | "s_mul_i32" | "s_mulk_i32" ) => @@ -3700,12 +5825,60 @@ impl<'a> Lower<'a> { fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> { let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; + // SCC of a mask operation that nothing gave a value as data: "some lane + // of the wave has its bit", asked now (codec_d, cool_fox 8cc31ab). + if self.x.st.scc_some.contains_key(&v) && matches!(self.vals.get(&v), None | Some(Val::Missing(_))) { + let x = self.scc_some(v)?; + self.vals.insert(v, Val::Bit(x)); + return Ok(x); + } match self.get(v)? { Val::Bit(x) => Ok(x), _ => Err("SCC without a value"), } } + /// Whether the dwords of one console load are read by one call for up + /// to four of them (`bitcode::opt::WIDE` of `VICTORY_SHADER_OPT`), not + /// by a call each. + fn wide_loads() -> bool { + super::shader_opt() & super::bitcode::opt::WIDE != 0 + } + + /// `count` dwords from byte `addr` on of the raw view `h`, as integers, + /// read in the current block by one call for every four of them + /// ([`Self::wide_loads`]). They are the dwords of ONE console load, + /// which the console reads as one (address plus 4, 8, ... without + /// wrapping at 32 bits): the same bytes as a call a dword reads. Loads + /// of different console instructions are never joined: the program + /// computes their offsets in 32-bit registers, and `x - 4` and `x` at + /// `x = 0` are one dword out of the view and its first one, where one + /// call from `x - 4` on would read both out of it. + fn raw_dwords(&mut self, h: V, addr: V, count: u32) -> Vec<V> { + let c = self.cur; + let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let mut out = Vec::with_capacity(count as usize); + for first in (0..count).step_by(4) { + let n = (count - first).min(4); + let off = self.s.m.i32(4 * first); + let a = self.s.m.bin(c, Bin::Add, addr, off); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, a, u, mask, al], + ); + for k in 0..n { + let x = self.s.m.extract(c, r, k); + out.push(self.as_int(x)); + } + } + out + } + fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Fields::Smem { data, @@ -3720,6 +5893,9 @@ impl<'a> Lower<'a> { if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { return self.code_smem(inst, a); } + if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) { + return self.memory_smem(inst); + } let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { return self.descriptor_data(inst, site); }; @@ -3740,7 +5916,6 @@ impl<'a> Lower<'a> { .copied() .ok_or("an untracked descriptor")?; let kind = self.used_kind(src); - let size = self.root_view_size(src); let c = self.cur; let (base, extra) = self.built_offset(src)?; let offset = &((*offset as u32).wrapping_add(base) as i32); @@ -3762,21 +5937,81 @@ impl<'a> Lower<'a> { } return Ok(()); } - // A buffer view read as scalars: raw loads (constant buffers are the - // rest). A UAV, known as one or written elsewhere, keeps its kind. - let u = self.uav_bits(src, kind); - if u != 0 || matches!(kind, Some(k) if k.kind == ResourceType::Srv) { - let h = self.handle(site, src, false, (11 | u, 0))?; + // A buffer the program picks from the view heap by an index it + // computes (`ResourceHeap`) has no used-resource entry, and the + // heap holds a buffer view there, not a constant buffer: read as + // raw bytes, as a table's SRV is below. Read as a constant buffer + // (the host's validation: "Descriptor Type in Heap: SRV, Register + // Type: CBV", heap index 17) the loads gave nothing: + // the title's meshlet culling (BatchCullMeshlets, + // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its + // batch records, mesh headers and instance transforms this way, so + // it passed no meshlet and every indirect mesh draw ran empty. + // The host's table of strides by heap slot tells a buffer view + // (not 0) from anything else, which is still read as a constant + // buffer; only the load that fits the slot runs. + let picked = match kind { + None => self.slot_stride(src)?, + Some(_) => None, + }; + if let Some(stride) = picked { + let zero = self.s.m.i32(0); + let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero); + let at = self.begin_guarded(Some(is_buffer)); + let h = self.handle(site, src, false, (11, 0))?; + let mut raw = Vec::new(); + let wide = Self::wide_loads(); + if wide { + let dwords = self.raw_dwords(h, addr, count); + raw.extend(dwords.into_iter().map(|x| (x, zero))); + } + for k in 0..if wide { 0 } else { count } { + let b = self.cur; + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(b, Bin::Add, addr, off); + let mask = self.s.m.i8(1); + let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let r = self.s.op( + b, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, a, u, mask, al], + ); + let x = self.s.m.extract(b, r, 0); + let x = self.as_int(x); + raw.push((x, zero)); + } + let raw = self.end_guarded(at, &raw); + let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero); + let at = self.begin_guarded(Some(other)); + let h = self.handle(site, src, false, (13, 0x1_0000))?; + let mut both = Vec::new(); + for (k, &r) in raw.iter().enumerate() { + let b = self.cur; + let off = self.s.m.i32(4 * k as u32); + let a = self.s.m.bin(b, Bin::Add, addr, off); + let x = self.cbuffer_dword(h, a); + both.push((x, r)); + } + let both = self.end_guarded(at, &both); + for (k, x) in both.into_iter().enumerate() { + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { + let h = self.handle(site, src, false, (11, 0))?; + if Self::wide_loads() { + for (k, x) in self.raw_dwords(h, addr, count).into_iter().enumerate() { + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } for k in 0..count { let off = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, addr, off); - let (a, ok) = match size { - Some(size) => { - let (ok, a) = self.in_root_view(size, a, 4); - (a, Some(ok)) - } - None => (a, None), - }; let mask = self.s.m.i8(1); let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); let r = self.s.op( @@ -3789,7 +6024,6 @@ impl<'a> Lower<'a> { ); let x = self.s.m.extract(c, r, 0); let x = self.as_int(x); - let x = self.zero_unless(ok, x); self.write(inst, Reg::S(code + k as u8), x, None); } return Ok(()); @@ -3829,14 +6063,7 @@ impl<'a> Lower<'a> { None => { let off = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, addr, off); - match size { - Some(size) => { - let (ok, a) = self.in_root_view(size, a, 4); - let x = self.cbuffer_dword(h, a); - self.zero_unless(Some(ok), x) - } - None => self.cbuffer_dword(h, a), - } + self.cbuffer_dword(h, a) } }; self.write(inst, Reg::S(code + k as u8), x, None); @@ -3856,72 +6083,6 @@ impl<'a> Lower<'a> { // level 0, so sizes the code shifts by it come out right) and the other // dwords (addresses, formats, tiling) have no host value: reading them // stops the program. - /// Two scalar loads of the same dwords: same opcode and immediate - /// offset, base read from the same values, and the same or an - /// equivalent register offset. - fn twin_loads(&self, a: Site, b: Site) -> bool { - let (ia, ib): (&Inst, &Inst) = ( - &self.x.p.blocks[a.0].insts[a.1], - &self.x.p.blocks[b.0].insts[b.1], - ); - let ( - Fields::Smem { - base: Operand::Scalar { code: ba, .. }, - offset: oa, - soffset: sa, - .. - }, - Fields::Smem { - base: Operand::Scalar { code: bb, .. }, - offset: ob, - soffset: sb, - .. - }, - ) = (&ia.fields, &ib.fields) - else { - return false; - }; - let same_base = (0..2).all(|k| { - let va = ia.read(Reg::S(ba + k)); - va.is_some() && va == ib.read(Reg::S(bb + k)) - }); - let same_soffset = match (sa, sb) { - (Operand::Scalar { code: NULL, .. }, Operand::Scalar { code: NULL, .. }) => true, - (Operand::Scalar { code: ca, .. }, Operand::Scalar { code: cb, .. }) => { - match (ia.read(Reg::S(*ca)), ib.read(Reg::S(*cb))) { - (Some(x), Some(y)) => self.same_scalar(x, y), - _ => false, - } - } - _ => false, - }; - ia.name() == ib.name() && oa == ob && same_base && same_soffset - } - - /// The same value, or two `v_readfirstlane_b32` of the same VGPR value - /// (each waterfall loop reads the index anew). - fn same_scalar(&self, x: Value, y: Value) -> bool { - if x == y { - return true; - } - let first_lane_of = |v: Value| { - self.x - .p - .blocks - .iter() - .flat_map(|b| &b.insts) - .find(|i| i.writes.iter().any(|w| w.1 == v)) - .filter(|i| i.name() == "v_readfirstlane_b32") - .and_then(|i| { - i.reads - .iter() - .find(|r| matches!(r.0, Reg::V(_))) - .map(|r| r.1) - }) - }; - matches!((first_lane_of(x), first_lane_of(y)), (Some(a), Some(b)) if a == b) - } - fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { const OTHER: Why = "a descriptor's address or format read as data"; let Fields::Smem { @@ -3939,104 +6100,205 @@ impl<'a> Lower<'a> { Some("x16") => 16, _ => return Err("a scalar memory read as data"), }; - // How the program uses the descriptor tells the view's kind: its - // own uses, else those of a twin load of the same dwords (a - // non-uniform index reloads the descriptor in each waterfall loop, - // one for the size bits, another for the access). - let uses = |twin: &dyn Fn(Site) -> bool| { - self.x - .res + // How the program uses the descriptor tells the view's kind: an image or buffer + // instruction before a scalar buffer load, which reads any buffer. + let x = self.x; + let uses = |of: Site| { + x.res .descriptors .iter() .filter(|d| d.role == Role::Resource) - .find_map(|d| { + .filter_map(move |d| { d.source.leaves().into_iter().find_map(|l| match *l { - Source::Loaded { load, first } if twin(load) => Some((d.site, first)), + Source::Loaded { load, first } if load == of => Some((d.site, first)), _ => None, }) }) }; - let use_at = - uses(&|load| load == site).or_else(|| uses(&|load| self.twin_loads(site, load))); - let (first, src, props, image, uav) = if let Some((at, first)) = use_at { - let src = Source::Loaded { load: site, first }; - let used = self.used_kind(&src); - let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; - let un = ui.name(); - let written = un.contains("store") || un.contains("atomic"); - let u = self.uav_bits(&src, used) | if written { 0x1000 } else { 0 }; - let uav = u & 0x1000 != 0; - let (props, image) = match &ui.fields { - Fields::Image { dim, .. } => { - let kind = match dim { - 0 => 1, - 1 => 2, - 2 => 4, - 4 => 6, - 5 => 7, - _ => return Err("an image dimension (cube or MSAA)"), - }; - ((kind | u, 0x409), Some(kind)) - } - Fields::Buffer { idxen, format, .. } => { - let stride = used.map_or(0, |u| u.stride); - let props = if un.starts_with("buffer_load_format") - || un.starts_with("buffer_store_format") - { - (10 | u, 0x409) - } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) - { - (12 | u, stride) - } else { - (11 | u, 0) - }; - if used.is_some_and(|u| u.kind == ResourceType::Cbv) { - return Err("a constant buffer's descriptor read as data"); + let by_scalar_load = |u: &(Site, u8)| { + matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }) + }; + let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next()); + // The console compiler loads a descriptor again wherever it needs it, and for a + // size it reads the dwords of a load that nothing uses as a descriptor (a texture + // picked from the heap by an index held per lane: one load for its width, one for + // its base level, one for each read of the image). Another load of as many dwords + // from the same address reads the same descriptor, so what uses that one tells + // this one's kind. The handle is still made from this load's own operands, which + // hold here. + let address = self.scalar.get(&site).copied(); + let twin = || { + let a = address?; + let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name(); + x.res + .scalar + .iter() + .filter(|(s, b)| *s != site && *b == a && same(*s)) + .find_map(|(s, _)| use_of(*s)) + }; + let use_at = use_of(site).or_else(twin); + // Whether the kind came from the descriptor's own dwords + // (`unused_descriptor_kind`): its address is then given as well. + let mut unused: Option<()> = None; + let (src, first, uav, props, image, used) = match use_at { + Some((at, first)) => { + let src = Source::Loaded { load: site, first }; + let used = self.used_kind(&src); + let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; + let un = ui.name(); + let uav = un.contains("store") + || un.contains("atomic") + || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + let (props, image) = match &ui.fields { + // A ray-tracing structure in a buffer of the host: read raw. + Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), + Fields::Image { dim, .. } => { + let kind = match dim { + 0 => 1, + 1 => 2, + 2 => 4, + 4 => 6, + 5 => 7, + _ => return Err("an image dimension (cube or MSAA)"), + }; + ((kind | u, 0x409), Some(kind)) + } + Fields::Buffer { idxen, format, .. } => { + let stride = used.map_or(0, |u| u.stride); + let props = if un.starts_with("buffer_load_format") + || un.starts_with("buffer_store_format") + { + // (Unsigned integers where the access moves halves.) + let halves = self + .table_place(&Source::Loaded { load: site, first }) + .is_some_and(|p| { + self.halves_only.contains(&p) + && (un.contains("_format_d16_") + || self.format_load_read_as_halves(ui)) + }); + (10 | u, if halves { 0x405 } else { 0x409 }) + } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { + (12 | u, stride) + } else { + (11 | u, 0) + }; + if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); + } + (props, None) } - (props, None) - } - // A descriptor that `s_buffer_load` reads is a raw buffer - // to the host when the load is a raw one (#798): a UAV or a - // known SRV. Else the load is a constant buffer, whose size - // no handle of the same slot can query. - Fields::Smem { .. } if un.starts_with("s_buffer_load") => { - if u == 0 && !used.is_some_and(|u| u.kind == ResourceType::Srv) { + // Read by scalar buffer loads alone: the raw view `smem` reads it through. + Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => { + ((11, 0), None) + } + // A constant buffer: nothing of its descriptor is a number. + Fields::Smem { .. } => { + self.stale.extend(inst.writes.iter().map(|w| w.1)); return Err("a constant buffer's descriptor read as data"); } - ((11 | u, 0), None) + _ => return Err("a scalar memory read as data"), + }; + (src, first, uav, props, image, used) + } + None => { + // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only + // copies its dwords and compares them, lane against first lane, and every load + // that reaches those lanes reads one address. Each dword stands in as its place + // in the table, so the lanes compare equal as they do on the console. + if self.x.res.lane_copied.contains(&site) + && let Some(a) = self.scalar.get(&site).copied() + { + for k in 0..count { + let x = self.s.m.i32(a.offset / 4 + k); + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); } - _ => return Err("a scalar memory read as data"), - }; - (first, src, props, image, uav) - } else { - // A view the program only measures (it reads the size bits and - // uses the view in other programs). The table's range, when one - // names the entry, says what it is; else the dwords read do: - // eight are an image descriptor, taken here as a 2D texture, and - // four a buffer only when a range gives its kind. - // shortcut: a 3D or array image would report depth or layers 1. - const NONE: Why = "a descriptor read only as data"; - let src = Source::Loaded { - load: site, - first: 0, - }; - let used = self.used_kind(&src); - let (dwords, stride) = match used { - Some(u) if matches!(u.kind, ResourceType::Srv | ResourceType::Uav) => { - (u32::from(u.dwords), u.stride) + // A sampler's descriptor: no program reads its dwords as numbers, so where one + // meets numbers at a join the register is dead on that path (`dead`), as a + // descriptor's address or format is. + let sampler = x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) + }); + if sampler { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a sampler's descriptor read as data"); + } + // A buffer view the code only takes the address of, to walk + // the memory behind it (a ray-tracing structure): the address + // from the host, the other dwords have no value. + if count <= 4 + && let Some((lo, hi)) = self.view_address(site) + { + for k in 0..count { + let reg = Reg::S(code + k as u8); + // Its record count where the code reads it (a buffer + // left empty is skipped by testing it against 0: + // ceb5eb68cd99cb07 at 0x34): the host view's size. + let records = match (k, inst.write(reg)) { + (2, Some(v)) if self.read_anywhere(v) => self.record_count(site), + _ => None, + }; + match k { + 0 => self.write(inst, reg, lo, None), + 1 => self.write(inst, reg, hi, None), + 2 if records.is_some() => self.write(inst, reg, records.expect("checked"), None), + _ => { + if let Some(v) = inst.write(reg) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + return Ok(()); } - None => (count, 0), - Some(_) => return Err(NONE), - }; - let u = self.uav_bits(&src, used); - let uav = u & 0x1000 != 0; - match dwords { - 8 => (0, src, (2 | u, 0x409), Some(2), uav), - 4 if stride >= 4 && stride.is_multiple_of(4) => { - (0, src, (12 | u, stride), None, uav) + // A descriptor nothing uses as one, whose size the code reads all the + // same (a texture picked from the heap by an index in a constant buffer, + // its width and height turned into a texel size): the kind from its + // dwords and its used-resource entry (fxceless). Else the table's range. + if let Some((first, props, image, uav, used)) = + self.unused_descriptor_kind(inst, site, code, count) + { + unused = Some(()); + (Source::Loaded { load: site, first }, first, uav, props, image, used) + } else { + // Read as data and never used (undeadhuman37, upstream #1067): the + // table's range says what the entry is, and an entry no range names + // (one a run-time index into the heap reaches) is an image if eight + // dwords. shortcut: an image is taken for 2D (its other kinds have + // other sizes) and a buffer for raw or structured; a view of another + // shape reads sizes of the wrong rank. + const NONE: Why = "a descriptor read only as data"; + let src = Source::Loaded { load: site, first: 0 }; + let used = self.used_kind(&src); + let in_views = self + .scalar + .get(&site) + .and_then(|a| self.x.native.layout.get(a.param)) + .is_some_and(|rp| matches!(rp.root, RootType::Table | RootType::ResourceHeap)); + let (uav, dwords, stride) = match used { + Some(u) if matches!(u.kind, ResourceType::Srv | ResourceType::Uav) => { + (u.kind == ResourceType::Uav, u.dwords, u.stride) + } + None if in_views => (false, count as u8, 0), + _ => return Err(NONE), + }; + let u = if uav { 0x1000 } else { 0 }; + match dwords { + 8 => (src, 0, uav, (2 | u, 0x409), Some(2), used), + 4 if stride >= 4 && stride.is_multiple_of(4) => { + (src, 0, uav, (12 | u, stride), None, used) + } + 4 if used.is_some() => (src, 0, uav, (11 | u, 0), None, used), + _ => return Err(NONE), + } } - 4 if used.is_some() => (0, src, (11 | u, 0), None, uav), - _ => return Err(NONE), } }; let h = self.handle(site, &src, false, props)?; @@ -4062,19 +6324,7 @@ impl<'a> Lower<'a> { 6 => (one, field(self, 1)), _ => (field(self, 1), field(self, 2)), }; - // The level count only feeds word 3. A level query of a 3D - // image inside a loop crashes NVIDIA's Vulkan compiler (vkd3d- - // proton turns it into OpImageQueryLevels), so query it only - // when the program reads that word as data. - let reads_word3 = (0..count) - .filter(|&k| k.wrapping_sub(u32::from(first)) == 3) - .filter_map(|k| inst.write(Reg::S(code + k as u8))) - .any(|v| self.read_as_data(v)); - let levels = if uav || !reads_word3 { - one - } else { - field(self, 3) - }; + let levels = if uav { one } else { field(self, 3) }; let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one); let (w, height, depth, levels) = ( less(self, w), @@ -4101,7 +6351,33 @@ impl<'a> Lower<'a> { let d3 = self.s.m.bin(c, Bin::Or, base, last); vec![(1, d1), (2, d2), (3, d3), (4, depth)] } - None => vec![(2, field(self, 0))], + None => { + // A raw view counts bytes; the descriptor's record count is in elements. + let n = field(self, 0); + let stride = used.map_or(0, |u| u.stride); + let n = if props.0 & 0xFF == 11 && stride > 1 { + let k = self.s.m.i32(stride); + self.s.m.bin(c, Bin::UDiv, n, k) + } else { + n + }; + let mut words = vec![(2, n)]; + // Its address too, where the code computes with it and the + // host can tell it. + let computed = (0..2u8).any(|k| { + inst.write(Reg::S(code + first + k)) + .is_some_and(|v| self.computed_with(v, 6)) + }); + // (A descriptor nothing uses as one gets it whenever the host can tell it, as + // a buffer whose address alone is read does.) + if first == 0 + && (computed || unused.is_some()) + && let Some((lo, hi)) = self.view_address(site) + { + words.extend([(0, lo), (1, hi)]); + } + words + } }; for k in 0..count { let rel = k.wrapping_sub(u32::from(first)); @@ -4110,6 +6386,7 @@ impl<'a> Lower<'a> { None => { if let Some(v) = inst.write(Reg::S(code + k as u8)) { self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); } } } @@ -4117,18 +6394,65 @@ impl<'a> Lower<'a> { Ok(()) } - /// Whether an instruction or phi reads `v` other than as a resource - /// operand of a memory instruction (which takes the descriptor whole). - fn read_as_data(&self, v: Value) -> bool { - self.x.p.blocks.iter().any(|b| { - b.phis.iter().any(|p| p.args.contains(&v)) - || b.insts.iter().any(|i| { - !matches!( - i.fields, - Fields::Image { .. } | Fields::Buffer { .. } | Fields::Smem { .. } - ) && i.reads.iter().any(|r| r.1 == v) - }) - }) + /// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a + /// descriptor but whose dwords the code reads: the first dword, the handle properties, + /// the image kind (none for a buffer), whether it is an unordered view, and its + /// used-resource entry. An image's eight dwords read as a 2D texture's, a buffer's four + /// as a raw view's where the code reads its record count (dword 2); none for anything + /// else (a constant buffer, a sampler, a buffer whose address alone is read). + // shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's + // reads are texel sizes of 2D textures: puddle masks, shadow masks); a host view of + // another kind would answer its own sizes. + #[allow(clippy::type_complexity)] + fn unused_descriptor_kind( + &self, + inst: &Inst, + site: Site, + code: u8, + count: u32, + ) -> Option<(u8, (u32, u32), Option<u32>, bool, Option<&'a UsedResource>)> { + // Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases + // `descriptor_data` handles on their own. + if self.x.res.lane_copied.contains(&site) + || self.x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) + }) + { + return None; + } + let used = self.used_kind(&Source::Loaded { + load: site, + first: 0, + }); + if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) { + return None; + } + let read = |k: u32| { + inst.write(Reg::S(code + k as u8)).is_some_and(|v| { + self.x + .p + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.reads.iter().any(|r| r.1 == v)) + }) + }; + let uav = used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + match count { + // width (dwords 1-2), height (2), levels (3), depth (4) + 8 if (1..5).any(read) && used.is_none_or(|u| u.dwords == 8) => { + Some((0, (2 | u, 0x409), Some(2), uav, used)) + } + // the record count + 4 if read(2) && used.is_none_or(|u| u.dwords == 4) => { + Some((0, (11 | u, 0), None, uav, used)) + } + _ => None, + } } /// `s_load_dword*` from the program's constant table. @@ -4150,8 +6474,19 @@ impl<'a> Lower<'a> { }; let c = self.cur; let mut addr = self.s.m.i32(a.offset); - if let Some(d) = a.dynamic { - let d = self.i32_of(d)?; + if let Some(value) = a.dynamic { + let mut d = self.i32_of(value)?; + // A term held per lane reached the address through + // `v_readfirstlane_b32`: the first lane's. + let per_lane = self.def_block.get(&value).is_some_and(|&b| { + let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_))); + self.x.p.blocks[b].insts.iter().any(writes) + }); + if per_lane { + self.s.flags |= flags::WAVE_OPS; + let i32t = self.s.t.i32; + d = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]); + } addr = self.s.m.bin(c, Bin::Add, addr, d); } for k in 0..count { @@ -4195,10 +6530,7 @@ impl<'a> Lower<'a> { /// typed loads do (channels past the format's read 0, 0, 0, 1). // shortcut: the descriptor's channel swizzle is taken as the identity // (it is for raw views and the descriptors code builds), elements of 4 - // bytes or more as dword-aligned. Norm formats divide, which the AMD - // driver does 1 ULP off the hardware's correctly rounded conversion for - // some values; correct it with an integer check if a title compares - // converted values exactly. + // bytes or more as dword-aligned. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> { let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?; let c = self.cur; @@ -4257,12 +6589,48 @@ impl<'a> Lower<'a> { }; let f32t = self.s.t.f32; let x = match numeric { + // Codes of 16 bits or fewer give the float nearest to the + // quotient, as the console's buffer unit does + // ([`Self::norm_quotient`]; avatarmanz/VIctory-7900XTX + // 9a6c829d after VIctory da82e444): the host's division was + // an ulp off for some, and a material index a title cut from + // one became the code below. + Numeric::Unorm if w <= 16 => { + let top = (1u32 << w) - 1; + let q = self.norm_quotient(field, w); + let q = self.as_float(q); + let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits())); + let at_top = self.s.m.cmp(c, pred::EQ, field, high); + let q = self.s.m.select(c, at_top, one, q); + float(self, q) + } Numeric::Unorm => { let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits()); let q = self.s.m.bin(c, Bin::SDiv, f, max); float(self, q) } + Numeric::Snorm if (2..=17).contains(&w) => { + let s = signed(self); + let top = (1u32 << (w - 1)) - 1; + // The magnitude's quotient, signed; the top code is 1.0, + // and the two lowest -1.0. + let (zero, sign) = (self.s.m.i32(0), self.s.m.i32(0x8000_0000)); + let neg = self.s.m.cmp(c, pred::SLT, s, zero); + let minus = self.s.m.bin(c, Bin::Sub, zero, s); + let m = self.s.m.select(c, neg, minus, s); + let q = self.norm_quotient(m, w - 1); + let sign = self.s.m.select(c, neg, sign, zero); + let q = self.s.m.bin(c, Bin::Or, q, sign); + let q = self.as_float(q); + let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits())); + let at_top = self.s.m.cmp(c, pred::SGE, s, high); + let q = self.s.m.select(c, at_top, one, q); + let (low, minus_one) = (self.s.m.i32(top.wrapping_neg()), self.s.m.f32((-1.0f32).to_bits())); + let at_bottom = self.s.m.cmp(c, pred::SLE, s, low); + let q = self.s.m.select(c, at_bottom, minus_one, q); + float(self, q) + } Numeric::Snorm => { let s = signed(self); let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); @@ -4311,40 +6679,142 @@ impl<'a> Lower<'a> { Ok(out) } - /// The dwords a `tbuffer_store_format_*` writes: its `channels` data - /// channels in buffer format `format`, as RDNA2 lays them out (see - /// [`buffer_format`]). Formats of 32-bit channels store the data's bits; - /// the `_d16_` forms of the 16-bit float formats store their halves as - /// they are. - // shortcut: only stores that need no conversion, with every channel of - // the format supplied, are lowered. Others need conversions (norm, - // scaled, narrow integers; f32 to f16, whose DXIL op rounds toward zero - // where the console rounds to nearest even, see #422) or elements under - // a dword (a read-modify-write lanes would race on); refused until a - // program needs them. - fn format_store_words( - &mut self, - inst: &Inst, - data: Option<&Operand>, - format: u8, - channels: u32, - ) -> Result<Vec<V>, Why> { - let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?; - if bits.len() != channels as usize { - return Err("a typed-format store of some of its format's channels"); - } - if !bits.iter().sum::<u32>().is_multiple_of(32) { - return Err("a typed-format store of an element under a dword"); - } - let d16 = inst.name().contains("_d16_"); - let data = data.ok_or("buffer store data")?; - match (bits[0], numeric, d16) { - (32, Numeric::Uint | Numeric::Sint | Numeric::Float, false) => { - self.vgprs(inst, data, channels as u8) - } - (16, Numeric::Float, true) => self.vgprs(inst, data, channels.div_ceil(2) as u8), - _ => Err("a typed-format store of a converted or narrow format"), + /// The bits of the float nearest to `a / d`, `d = 2^w - 1`, for codes + /// `0 <= a < d` and `w <= 16`: what the console's buffer unit gives for + /// a normalized code. The host's division is not exact (the RX 6700 XT + /// returns 8-bit codes one ulp high and some 16-bit codes one ulp low), + /// and titles truncate `x * d` back to the code (a material index in a + /// vertex colour's alpha), which a quotient one ulp low turns into the + /// code below. + /// + /// `Q = floor(a * 2^32 / d) = a * K + floor(a * r / d)` with `K = + /// floor(2^32 / d)` and `r = 2^32 mod d` (no division when `r` is 1: + /// widths dividing 32). `a / d` is never exact for `0 < a < d` (`d` + /// odd, `r` coprime to it), so `Q` rounds to 24 bits up exactly when + /// its highest dropped bit is set, and the result is that integer (at + /// most 2^24, so its conversion is exact on any host) scaled by a power + /// of two; `Q` itself when it fits, the quotient's further bits then + /// lying below half an ulp. That holds for every code of every width but + /// 11 and 12 (checked for all codes of widths 2 to 16), which take + /// [`Self::exact_norm`]. The host's conversion of a larger integer is + /// not relied on: WARP rounds those above 2^31 otherwise. + fn norm_quotient(&mut self, a: V, w: u32) -> V { + if matches!(w, 11 | 12) { + return self.exact_norm(a, w); } + let c = self.cur; + let d = (1u64 << w) - 1; + let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d); + let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32); + let (one, kv) = (k(self, 1), k(self, kk)); + let mut q = self.s.m.bin(c, Bin::Mul, a, kv); + if r != 1 { + let (rv, dv) = (k(self, r), k(self, d)); + let t = self.s.m.bin(c, Bin::Mul, a, rv); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + q = self.s.m.bin(c, Bin::Add, q, more); + } + // The bits to drop (1 to 8) from the exponent of `q >> 8`, which + // converts exactly (fewer than 25 bits); none when `q` fits. + let k8 = k(self, 8); + let top = self.s.m.bin(c, Bin::LShr, q, k8); + let top = self.s.m.cast(c, Cast::UiToFp, top, self.s.t.f32); + let top = self.as_int(top); + let k23 = k(self, 23); + let e = self.s.m.bin(c, Bin::LShr, top, k23); + let bias = k(self, 127 + 15); + let shift = self.s.m.bin(c, Bin::Sub, e, bias); + let (zero, b24) = (k(self, 0), k(self, 1 << 24)); + let fits = self.s.m.cmp(c, pred::IULT, q, b24); + let shift = self.s.m.select(c, fits, zero, shift); + // Rounded up when the highest dropped bit is set: `a / d` is never + // exact, so a dropped half is more than half, never a tie. + let up = self.s.m.bin(c, Bin::Shl, q, one); + let up = self.s.m.bin(c, Bin::LShr, up, shift); + let up = self.s.m.bin(c, Bin::And, up, one); + let m = self.s.m.bin(c, Bin::LShr, q, shift); + let m = self.s.m.bin(c, Bin::Add, m, up); + // At most 2^24: exact as a float, and so its scale by 2^(shift - 32). + let f = self.s.m.cast(c, Cast::UiToFp, m, self.s.t.f32); + let b95 = k(self, 127 - 32); + let scale = self.s.m.bin(c, Bin::Add, shift, b95); + let scale = self.s.m.bin(c, Bin::Shl, scale, k23); + let scale = self.as_float(scale); + let f = self.s.m.bin(c, Bin::Mul, f, scale); + self.as_int(f) + } + + /// [`Self::norm_quotient`] in integers only, for any width up to 16: `Q` + /// as there, 8 more bits when that leaves fewer than 25 (codes of wide + /// formats near 0), then rounded to 24 bits to nearest even with the + /// remainder as sticky bit, and assembled as float bits. + fn exact_norm(&mut self, a: V, w: u32) -> V { + let c = self.cur; + let d = (1u64 << w) - 1; + let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d); + let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32); + let (one, zero, dv, k8) = (k(self, 1), k(self, 0), k(self, d), k(self, 8)); + let kv = k(self, kk); + let mut q = self.s.m.bin(c, Bin::Mul, a, kv); + let mut rem = a; + if r != 1 { + let rv = k(self, r); + let t = self.s.m.bin(c, Bin::Mul, a, rv); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + q = self.s.m.bin(c, Bin::Add, q, more); + rem = self.s.m.bin(c, Bin::URem, t, dv); + } + // The exponent's bias less the 32 (or 40) fraction bits of `q`; the + // shift below is added. + let mut bias = k(self, 127 + 23 - 32); + if kk < 1 << 24 { + // Fewer than 25 bits for the smallest codes: 8 more. + let t = self.s.m.bin(c, Bin::Shl, rem, k8); + let more = self.s.m.bin(c, Bin::UDiv, t, dv); + let rest = self.s.m.bin(c, Bin::URem, t, dv); + let wide = self.s.m.bin(c, Bin::Shl, q, k8); + let wide = self.s.m.bin(c, Bin::Or, wide, more); + let limit = k(self, 1 << 24); + let small = self.s.m.cmp(c, pred::IULT, q, limit); + q = self.s.m.select(c, small, wide, q); + rem = self.s.m.select(c, small, rest, rem); + let b40 = k(self, 127 + 23 - 40); + bias = self.s.m.select(c, small, b40, bias); + } + // Bits to drop: the bit length less 24, 1 to 8. + let mut shift = one; + for bit in 25..32 { + let at = k(self, 1 << bit); + let ge = self.s.m.cmp(c, pred::IUGE, q, at); + let add = self.s.m.select(c, ge, one, zero); + shift = self.s.m.bin(c, Bin::Add, shift, add); + } + let mant = self.s.m.bin(c, Bin::LShr, q, shift); + let below = self.s.m.bin(c, Bin::Sub, shift, one); + let half = self.s.m.bin(c, Bin::LShr, q, below); + let half = self.s.m.bin(c, Bin::And, half, one); + let low = self.s.m.bin(c, Bin::Shl, one, below); + let low = self.s.m.bin(c, Bin::Sub, low, one); + let low = self.s.m.bin(c, Bin::And, q, low); + let rest = self.s.m.bin(c, Bin::Or, low, rem); + let sticky = self.s.m.cmp(c, pred::NE, rest, zero); + let odd = self.s.m.bin(c, Bin::And, mant, one); + let tie = self.s.m.select(c, sticky, one, odd); + let up = self.s.m.bin(c, Bin::And, half, tie); + let mant = self.s.m.bin(c, Bin::Add, mant, up); + // Rounding up to 2^24 moves to the next exponent. + let k24 = k(self, 24); + let carry = self.s.m.bin(c, Bin::LShr, mant, k24); + let mant = self.s.m.bin(c, Bin::LShr, mant, carry); + let e = self.s.m.bin(c, Bin::Add, bias, shift); + let e = self.s.m.bin(c, Bin::Add, e, carry); + let k23 = k(self, 23); + let e = self.s.m.bin(c, Bin::Shl, e, k23); + let fraction = k(self, 0x7F_FFFF); + let m = self.s.m.bin(c, Bin::And, mant, fraction); + let bits = self.s.m.bin(c, Bin::Or, e, m); + let is_zero = self.s.m.cmp(c, pred::EQ, a, zero); + self.s.m.select(c, is_zero, zero, bits) } /// The byte offset a buffer descriptor built around a root descriptor adds @@ -4352,16 +6822,64 @@ impl<'a> Lower<'a> { fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> { match src { Source::Built { address, .. } => { - let x = match address.dynamic { + let mut x = match address.dynamic { Some(v) => Some(self.i32_of(v)?), None => None, }; + if let Some(bias) = self.root_bias(address.param) { + x = Some(match x { + Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias), + None => bias, + }); + } Ok((address.offset, x)) } _ => Ok((0, None)), } } + /// For a root view the host binds as a raw view that may begin before + /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add + /// to offsets through it. Every root UAV, and the root SRVs of programs + /// with a spilled user-data table (the others keep the views they + /// have). + fn root_bias(&mut self, param: usize) -> Option<V> { + use super::shader::USER_VIEW_BIAS; + let rp = *self.x.native.layout.get(param)?; + if rp.root != RootType::Descriptor { + return None; + } + let kind = self + .x + .native + .used + .iter() + .find(|u| u.user_data == rp.user_data) + .map(|u| u.kind); + let biased = match kind { + Some(ResourceType::Uav) => true, + Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native), + _ => false, + }; + biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0)) + } + + /// The table descriptor `src` is, as (root parameter, dword in the + /// table), when the code loads it from a fixed place in a table: the + /// load's own place, not the start of the range its used-resource + /// entry describes (a range of several descriptors starts before most + /// of them). `None` for a descriptor picked at run time, built in the + /// code or chosen by control flow. + fn table_place(&self, src: &Source) -> Option<(u8, u32)> { + let Source::Loaded { load, first } = src else { + return None; + }; + let a = self.scalar.get(load)?; + let rp = self.x.native.layout.get(a.param)?; + (rp.root == RootType::Table && a.dynamic.is_none()) + .then(|| (rp.slot, a.offset / 4 + u32::from(*first))) + } + /// The used-resource entry a descriptor loaded from a table falls in. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } = @@ -4402,200 +6920,6 @@ impl<'a> Lower<'a> { .max_by_key(|u| u.table_offset_dwords) } - /// Every instruction that reads or writes through the resource - /// descriptor `src`: the same dwords of the same scalar load, or of a - /// twin load of them. - fn accesses(&self, src: &Source) -> Vec<&'a Inst> { - let p: &'a Program = self.x.p; - let leaves: Vec<(Site, u8)> = src - .leaves() - .into_iter() - .filter_map(|l| match *l { - Source::Loaded { load, first } => Some((load, first)), - _ => None, - }) - .collect(); - let same = |other: &Source| { - other.leaves().into_iter().any(|l| match *l { - Source::Loaded { load, first } => leaves - .iter() - .any(|&(at, f)| f == first && (at == load || self.twin_loads(at, load))), - _ => false, - }) || other == src - }; - self.x - .res - .descriptors - .iter() - .filter(|d| d.role == Role::Resource && same(&d.source)) - .map(|d| &p.blocks[d.site.0].insts[d.site.1]) - .collect() - } - - /// Whether the cube image `src` is a cube array: some sample or gather - /// through it passes a slice in its face operand. The console has no - /// array bit in the instruction; it takes the face operand as - /// `8 × slice + face` (Mesa's `prepare_cube_coords` builds it with one - /// multiply-add by 8.0), so a face operand built that way, or a - /// constant of 8 or more, names a slice. Every access through the - /// descriptor then takes the array's kind, as the view is one. - // shortcut: a cube array only ever sampled at slice 0 (or with the slice - // multiplied in some other way, or 16-bit coordinates) stays a cube. - fn cube_array(&self, src: &Source) -> bool { - self.accesses(src).into_iter().any(|i| { - let Fields::Image { - addr, - dim: 3, - a16: false, - .. - } = &i.fields - else { - return false; - }; - let n = i.name(); - if !n.starts_with("image_sample") && !n.starts_with("image_gather") { - return false; - } - // s, t, face after the offset, bias and reference words (cube - // samples take no gradients). - let first = usize::from(n.ends_with("_o")) - + usize::from(n.starts_with("image_sample_b")) - + usize::from(n.starts_with("image_sample_c")); - let regs: Vec<u8> = addr - .iter() - .filter_map(|a| match *a { - Operand::Vector { reg, dwords } => Some((0..dwords).map(move |k| reg + k)), - _ => None, - }) - .flatten() - .collect(); - regs.get(first + 2) - .and_then(|&r| i.read(Reg::V(r))) - .is_some_and(|face| self.slice_in_face(face, 8)) - }) - } - - /// The instruction writing `v` (none for a phi or an input). - fn writer(&self, v: Value) -> Option<&'a Inst> { - let p: &'a Program = self.x.p; - let b = *self.def_block.get(&v)?; - p.blocks[b] - .insts - .iter() - .find(|i| i.writes.iter().any(|w| w.1 == v)) - } - - /// The bits of `op` as `inst` reads it, if a constant: inline, literal, - /// or moved into the register from one (at most `depth` moves back). - fn constant_bits(&self, inst: &Inst, op: &Operand, depth: u8) -> Option<u32> { - let moved = |reg: Reg, mov: &str| { - let w = self.writer(inst.read(reg)?)?; - if depth == 0 || w.name() != mov { - return None; - } - let src = match &w.fields { - Fields::Sop { src, .. } => src.first()?, - Fields::Valu(v) if v.sdwa.is_none() && v.dpp.is_none() => v.src.first()?, - _ => return None, - }; - self.constant_bits(w, src, depth - 1) - }; - match *op { - Operand::Literal(x) => Some(x), - Operand::Const(code) => crate::resource::inline(code), - Operand::Scalar { code, .. } => moved(Reg::S(code), "s_mov_b32"), - Operand::Vector { reg, .. } => moved(Reg::V(reg), "v_mov_b32"), - Operand::Attr { .. } => None, - } - } - - /// Whether the cube face operand `face` carries a slice (`8 × slice + - /// face`, see [`Self::cube_array`]), following at most `depth` moves. - fn slice_in_face(&self, face: Value, depth: u8) -> bool { - let Some(w) = self.writer(face) else { - return false; - }; - let Fields::Valu(v) = &w.fields else { - return false; - }; - let eight = 8.0f32.to_bits(); - let bits = |n: usize| { - v.src - .get(n) - .and_then(|o| self.constant_bits(w, o, 4)) - .filter(|_| v.neg >> n & 1 == 0 && v.abs >> n & 1 == 0) - }; - let at_least_eight = |x: Option<u32>| x.is_some_and(|x| f32::from_bits(x) >= 8.0); - match w.name() { - "v_mov_b32" if depth > 0 && v.sdwa.is_none() && v.dpp.is_none() => { - match v.src.first() { - Some(&Operand::Vector { reg, .. }) => w - .read(Reg::V(reg)) - .is_some_and(|x| self.slice_in_face(x, depth - 1)), - _ => at_least_eight(bits(0)), - } - } - // slice × 8.0 + face (the multiplied operands come first). - "v_fma_f32" | "v_fmac_f32" | "v_fmamk_f32" | "v_fmaak_f32" | "v_mad_f32" - | "v_mac_f32" | "v_madmk_f32" | "v_madak_f32" => { - bits(0) == Some(eight) || bits(1) == Some(eight) - } - // face + (slice × 8.0), or face plus a constant slice folded in. - "v_add_f32" => (0..2).any(|n| { - let product = match v.src.get(n) { - Some(&Operand::Vector { reg, .. }) => w - .read(Reg::V(reg)) - .and_then(|x| self.writer(x)) - .is_some_and(|m| { - let Fields::Valu(mv) = &m.fields else { - return false; - }; - m.name() == "v_mul_f32" - && (0..2).any(|k| { - mv.src.get(k).and_then(|o| self.constant_bits(m, o, 4)) - == Some(eight) - }) - }), - _ => false, - }; - product || at_least_eight(bits(n)) - }), - _ => false, - } - } - - /// The `IsUAV` and `IsGloballyCoherent` bits of every handle of the - /// resource descriptor `src`, from all of its uses in the program, not - /// only the access at hand: one descriptor read by a load and written by - /// a store is one UAV, and both handles must say so. `used` is what the - /// root signature says of it (heap descriptors: nothing). - /// - /// A UAV is globally coherent when some plain access through it has - /// `glc` (it skips the per-CU cache, as LLVM's GFX10 memory model lowers - /// a device-scope atomic load, to see other groups' writes). On atomics - /// `glc` only asks for the old value. - fn uav_bits(&self, src: &Source, used: Option<&UsedResource>) -> u32 { - let (mut written, mut coherent) = (false, false); - for i in self.accesses(src) { - let (Fields::Buffer { cache, .. } - | Fields::Image { cache, .. } - | Fields::Smem { cache, .. }) = &i.fields - else { - continue; - }; - let n = i.name(); - let atomic = n.contains("atomic"); - written |= atomic || n.contains("store"); - coherent |= cache.glc && !atomic; - } - let uav = used.map_or(written, |u| u.kind == ResourceType::Uav); - match (uav, coherent) { - (false, _) => 0, - (true, false) => 0x1000, - (true, true) => 0x1000 | 0x4000, - } - } - /// A handle for the descriptor `src` read at `site`. fn handle( &mut self, @@ -4663,30 +6987,22 @@ impl<'a> Lower<'a> { (RootType::Descriptor, Some(ResourceType::Srv), 11) => { Ok(self.s.root_srv_handle(rp.slot)) } - _ => Err("a root UAV or typed root view"), + // A root UAV: a raw buffer whether the access reads + // (11) or writes (11 with the UAV bit). Indexed + // accesses reach here as raw ones at index times the + // entry's stride (`buffer`). + (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => { + Ok(self.s.root_uav_handle(rp.slot)) + } + (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => { + Err("a write through a root SRV") + } + _ => Err("a typed root view"), } } Source::Phi { block, args } => { - // Each predecessor computes its heap index at its end; the - // join picks one with a phi. let _ = site; - let mut incoming = Vec::new(); - for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { - if self.block[q].is_none() { - continue; - } - let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else { - return Err("a descriptor chosen by control flow"); - }; - let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); - let here = std::mem::replace(&mut self.cur, at); - let index = self.heap_index(*load, *first, sampler); - self.cur = here; - incoming.push((index?, at)); - } - let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; - let phi = self.s.m.phi(join, self.s.t.i32); - self.s.m.set_phi(phi, incoming); + let phi = self.descriptor_phi(*block, args, sampler, 8)?; Ok(self.s.heap_handle(self.cur, phi, sampler, false, props)) } Source::Select { scc, args } => { @@ -4717,6 +7033,243 @@ impl<'a> Lower<'a> { } } + /// The heap index a descriptor phi picks. Each predecessor computes its + /// heap index at its end and the join picks one with a phi; a + /// predecessor whose descriptor is itself chosen by control flow (a + /// phi of an earlier join, which dominates it) gives that join's phi, + /// at most `depth` joins deep. + fn descriptor_phi( + &mut self, + block: usize, + args: &[Source], + sampler: bool, + depth: u32, + ) -> Result<V, Why> { + const WHY: Why = "a descriptor chosen by control flow"; + let p = self.x.p; + let mut incoming = Vec::new(); + for (&q, arg) in p.blocks[block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = self.tail[q].ok_or(WHY)?; + let at = self.edges.get(&(q, block)).copied().unwrap_or(tail); + let index = match arg { + Source::Loaded { load, first } => { + let here = std::mem::replace(&mut self.cur, at); + let index = self.heap_index(*load, *first, sampler); + self.cur = here; + index? + } + Source::Phi { block: inner, args: inner_args } if depth > 0 => { + self.descriptor_phi(*inner, inner_args, sampler, depth - 1)? + } + _ => return Err(WHY), + }; + incoming.push((index, at)); + } + let join = self.block[block].ok_or(WHY)?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + + /// Registers an immediate sampler constant and returns its slot index. + fn register_sampler(&mut self, words: &[u32], cmp: bool) -> Result<u32, Why> { + let words: [u32; 4] = words + .get(..4) + .and_then(|w| w.try_into().ok()) + .ok_or("a sampler constant")?; + let n = match self.samplers.iter().position(|w| *w == words) { + Some(n) => n, + None => { + self.samplers.push(words); + self.samplers.len() - 1 + } + }; + if cmp && n < 64 { + self.s.cmp_samplers |= 1 << n; + } + Ok(n as u32) + } + + /// Resolves a control-flow phi of immediate sampler constants into either a + /// single static sampler register (`One`) or a uniform `i32` phi index over + /// `regs` (`Many`) for branch dispatch at the sample site. + fn sampler_phi_choice( + &mut self, + block: usize, + args: &[Source], + cmp: bool, + depth: u32, + ) -> Result<(Option<V>, Vec<u32>), Why> { + const WHY: Why = "a descriptor chosen by control flow"; + let mut distinct: Vec<[u32; 4]> = Vec::new(); + self.collect_constant_samplers(block, args, depth, &mut distinct)?; + if distinct.is_empty() { + return Err(WHY); + } + let mut regs = Vec::with_capacity(distinct.len()); + for w in &distinct { + regs.push(self.register_sampler(w, cmp)?); + } + if regs.len() == 1 { + return Ok((None, regs)); + } + let idx = self.sampler_index_phi(block, args, 0, &distinct, depth)?; + Ok((Some(idx), regs)) + } + + fn collect_constant_samplers( + &self, + block: usize, + args: &[Source], + depth: u32, + distinct: &mut Vec<[u32; 4]>, + ) -> Result<(), Why> { + const WHY: Why = "a descriptor chosen by control flow"; + let p = self.x.p; + for (&q, arg) in p.blocks[block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + match arg { + Source::Constant(w) if w.len() >= 4 => { + let k: [u32; 4] = w[..4].try_into().unwrap(); + if !distinct.contains(&k) { + distinct.push(k); + } + } + Source::Phi { + block: inner, + args: inner_args, + } if depth > 0 => { + self.collect_constant_samplers(*inner, inner_args, depth - 1, distinct)?; + } + _ => return Err(WHY), + } + } + Ok(()) + } + + fn sampler_index_phi( + &mut self, + block: usize, + args: &[Source], + lower: u32, + distinct: &[[u32; 4]], + depth: u32, + ) -> Result<V, Why> { + const WHY: Why = "a descriptor chosen by control flow"; + let p = self.x.p; + let mut incoming = Vec::new(); + for (&q, arg) in p.blocks[block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = self.tail[q].ok_or(WHY)?; + let at = self.edges.get(&(q, block)).copied().unwrap_or(tail); + let idx = match arg { + Source::Constant(w) if w.len() >= 4 => { + let k: [u32; 4] = w[..4].try_into().unwrap(); + let pos = distinct.iter().position(|d| *d == k).ok_or(WHY)? as u32; + self.s.m.i32(lower + pos) + } + Source::Phi { + block: inner, + args: inner_args, + } if depth > 0 => { + self.sampler_index_phi(*inner, inner_args, lower, distinct, depth - 1)? + } + _ => return Err(WHY), + }; + incoming.push((idx, at)); + } + let join = self.block[block].ok_or(WHY)?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + + /// The bytes per element of the buffer view `src` names, if the program + /// picks it from the view heap at an index it computes (root type + /// `ResourceHeap`): read from the host's table by heap slot in the + /// current block. + fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> { + let word = self.slot_word(src, false)?; + Ok(word.map(|word| { + let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS); + self.s.m.bin(self.cur, Bin::And, word, bits) + })) + } + + /// Whether the typed buffer view `src` names is one of an integer format, + /// and whether a signed one (`ResourceHeap` or `Table`; `None`: neither). + /// (VIctory 4243a96a via avatarmanz 9a6c829d; tables: codec_d, cool_fox + /// f4b48ad.) + fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> { + let Some(word) = self.slot_word(src, true)? else { + return Ok(None); + }; + let c = self.cur; + let zero = self.s.m.i32(0); + let [int, signed] = [super::shader::VIEW_INTEGER, super::shader::VIEW_SIGNED].map(|bit| { + let bit = self.s.m.i32(bit); + let x = self.s.m.bin(c, Bin::And, word, bit); + self.s.m.cmp(c, pred::NE, x, zero) + }); + Ok(Some((int, signed))) + } + + /// The host's word for the buffer view `src` names: its stride and + /// format kind ([`super::shader::SLOT_STRIDES`] for `ResourceHeap`, + /// [`super::shader::SLOT_TABLE_STRIDES`] for `Table` when `allow_table`). + fn slot_word(&mut self, src: &Source, allow_table: bool) -> Result<Option<V>, Why> { + let Source::Loaded { load, first } = src else { + return Ok(None); + }; + let srv_slot = match self + .scalar + .get(load) + .and_then(|a| self.x.native.layout.get(a.param)) + .map(|p| p.root) + { + Some(RootType::ResourceHeap) => super::shader::SLOT_STRIDES, + Some(RootType::Table) if allow_table => super::shader::SLOT_TABLE_STRIDES, + _ => return Ok(None), + }; + let key = (self.cur, *load, *first); + if let Some(&v) = self.strides.get(&key) { + return Ok(Some(v)); + } + let c = self.cur; + let slot = self.heap_index(*load, *first, false)?; + // Inside the table whatever the index (lanes that do not run + // compute one too): a root view has no bounds of its own. + let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1); + let i32t = self.s.t.i32; + let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]); + self.s.m.tag(slot, Tag::Clamp); + let two = self.s.m.i32(2); + let byte = self.s.m.bin(c, Bin::Shl, slot, two); + let h = self.s.root_srv_handle(srv_slot); + let iu = self.s.m.undef(self.s.t.i32); + let mask = self.s.m.i8(1); + let align = self.s.m.i32(4); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, align], + ); + let f = self.s.m.extract(c, r, 0); + let v = self.as_int(f); + self.strides.insert(key, v); + Ok(Some(v)) + } + /// The heap index of a descriptor that may differ between lanes, /// computed in the current block (or, chosen by control flow, at the /// join). @@ -4867,6 +7420,16 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if let Some(&source) = self.x.res.restored_lanes.get(&(b, i)) { + // A lane a uniform scalar was saved to and read back in one block + // (codec_d, cool_fox 8cc31ab): the scalar, whatever the VGPR's + // other lanes hold (a reduction scratch). + let word = match source { + crate::resource::Moved::Value(v) => self.i32_of(v)?, + crate::resource::Moved::Const(k) => self.s.m.i32(k), + }; + return self.write_i(inst, word, None); + } if self.x.res.waterfall.compares.contains(&(b, i)) { // The first lane's dwords of a waterfall loop are each lane's // own (see `resource::Waterfall`). @@ -4991,10 +7554,10 @@ impl<'a> Lower<'a> { (src, inside, masks, bound_ctrl) } }; - let mut r = if mesh_quad { + let mut r = if mesh_quad || self.helpers_read(quad) { self.quad_pick(x, src) } else { - self.read_lane(x, src)? + self.read_lane(x, src) }; let mut enable = None; if let Some(inside) = inside { @@ -5044,6 +7607,36 @@ impl<'a> Lower<'a> { return self.packed16(inst, op, guard); } match name { + "v_mad_u64_u32" => { + // a * b + c, c and the result 64 bits wide; the carry out + // of the sum is this lane's bit of the mask it names. + let (a, b) = (s(self, 0)?, s(self, 1)?); + let x = self.src64(inst, 2)?; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let a = self.s.m.cast(c, Cast::ZExt, a, i64t); + let b = self.s.m.cast(c, Cast::ZExt, b, i64t); + let product = self.s.m.bin(c, Bin::Mul, a, b); + let r = self.s.m.bin(c, Bin::Add, product, x); + let carry = self.s.m.cmp(c, pred::IULT, r, x); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 64-bit result"); + }; + let (lo, hi) = self.split64(r); + self.write(inst, Reg::V(reg), lo, guard); + self.write(inst, Reg::V(reg + 1), hi, guard); + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, carry); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => { let n = s(self, 0)?; let x = self.src64(inst, 1)?; @@ -5185,22 +7778,6 @@ impl<'a> Lower<'a> { } Ok(()) } - "v_ldexp_f32" => { - let (x, e) = (f(self, 0)?, s(self, 1)?); - let r = self.ldexp(x, e); - float(self, r) - } - "v_frexp_mant_f32" | "v_frexp_exp_i32_f32" => { - let x = f(self, 0)?; - let x = self.as_int(x); - let (m, e) = self.frexp(x); - if name == "v_frexp_mant_f32" { - let m = self.as_float(m); - float(self, m) - } else { - int(self, e) - } - } "v_ffbh_u32" | "v_ffbh_i32" => { // Counted from the top bit, -1 when none (DXIL's too). let a = s(self, 0)?; @@ -5238,7 +7815,153 @@ impl<'a> Lower<'a> { let r = self.fmad(a, bb, cc); float(self, r) } - "v_fmac_f32" | "v_mac_f32" | "v_fmac_legacy_f32" => { + "v_div_scale_f32" => { + // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator. + let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den)); + let (k23, k255, kabs) = ( + self.s.m.i32(23), + self.s.m.i32(0xFF), + self.s.m.i32(0x7FFF_FFFF), + ); + let (zero, k23_exp, k232_exp, k96) = ( + self.s.m.i32(0), + self.s.m.i32(23), + self.s.m.i32(232), + self.s.m.i32(96), + ); + let exp_of = |l: &mut Self, x: V| { + let s = l.s.m.bin(c, Bin::LShr, x, k23); + l.s.m.bin(c, Bin::And, s, k255) + }; + let (e1, e2) = (exp_of(self, ni), exp_of(self, di)); + let n_abs = self.s.m.bin(c, Bin::And, ni, kabs); + let d_abs = self.s.m.bin(c, Bin::And, di, kabs); + let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero); + let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero); + let any_zero = self.s.m.bin(c, Bin::Or, z1, z2); + let special = { + let s1 = self.s.m.cmp(c, pred::EQ, e1, k255); + let s2 = self.s.m.cmp(c, pred::EQ, e2, k255); + let a12 = self.s.m.bin(c, Bin::Or, s1, s2); + self.s.m.bin(c, Bin::Or, a12, any_zero) + }; + let is_den = self.s.m.cmp(c, pred::EQ, ai, di); + let diff = self.s.m.bin(c, Bin::Sub, e2, e1); + let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp); + let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp); + let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp); + let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp); + let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96); + let not_den_huge = { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, den_huge, t) + }; + let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge); + let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap); + let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny); + let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge); + let not_special = { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, special, t) + }; + let up = self.s.m.bin(c, Bin::And, up_raw, not_special); + let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special); + let uncancelled = { + let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny); + let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge); + self.s.m.bin(c, Bin::Or, x_tiny, x_huge) + }; + let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw); + let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special); + let k_up = self.s.m.f32(0x5F80_0000); + let k_dn = self.s.m.f32(0x1F80_0000); + let a_up = self.s.m.bin(c, Bin::Mul, a, k_up); + let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn); + let r = self.s.m.select(c, dn, a_dn, a); + let r = self.s.m.select(c, up, a_up, r); + let qnan = self.s.m.f32(0x7FC0_0000); + let r = self.s.m.select(c, any_zero, qnan, r); + float(self, r)?; + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, flag); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } + "v_div_fmas_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let m = inst + .read(Reg::S(crate::ir::VCC)) + .and_then(|v| self.x.st.masks.get(&v).copied()) + .ok_or("v_div_fmas_f32 without VCC")?; + let vcc = self.boolean(m, c)?; + let tmp = self.fmad(a, bb, cc); + let ci = self.as_int(cc); + let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128)); + let sh = self.s.m.bin(c, Bin::LShr, ci, k23); + let exp = self.s.m.bin(c, Bin::And, sh, k255); + let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128); + let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000)); + let scale = self.s.m.select(c, exp_ge, k_up, k_dn); + let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale); + let r = self.s.m.select(c, vcc, scaled, tmp); + float(self, r) + } + "v_div_fixup_f32" => { + let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num)); + let (ksign, kabs, kinf) = ( + self.s.m.i32(0x8000_0000), + self.s.m.i32(0x7FFF_FFFF), + self.s.m.i32(0x7F80_0000), + ); + let (kqnan_bit, kneg_qnan, zero) = ( + self.s.m.i32(0x0040_0000), + self.s.m.i32(0xFFC0_0000), + self.s.m.i32(0), + ); + let sign = { + let x = self.s.m.bin(c, Bin::Xor, ni, di); + self.s.m.bin(c, Bin::And, x, ksign) + }; + let q_abs = self.s.m.bin(c, Bin::And, qi, kabs); + let d_abs = self.s.m.bin(c, Bin::And, di, kabs); + let n_abs = self.s.m.bin(c, Bin::And, ni, kabs); + let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf); + let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf); + let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf); + let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf); + let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf); + let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero); + let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero); + let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf); + let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero); + let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero); + let make_inf = { + let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero); + self.s.m.bin(c, Bin::Or, t, q_nan) + }; + let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero); + let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs); + let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf); + let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit); + let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit); + let r = self.s.m.select(c, make_zero, sign, signed_q); + let r = self.s.m.select(c, make_inf, signed_inf, r); + let r = self.s.m.select(c, invalid, kneg_qnan, r); + let r = self.s.m.select(c, d_nan, d_qnan, r); + let r = self.s.m.select(c, n_nan, n_qnan, r); + let rf = self.as_float(r); + float(self, rf) + } + "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => { let (a, bb) = (f(self, 0)?, f(self, 1)?); let Some(Operand::Vector { reg, .. }) = v.dst else { return Err("an accumulator"); @@ -5257,21 +7980,28 @@ impl<'a> Lower<'a> { let m = self.s.m.bin(c, Bin::Mul, a, bb); self.s.m.bin(c, Bin::Add, m, acc) } - _ => self.fma_legacy(a, bb, acc), + // On RDNA 2 the legacy encoding decodes as fused + // (`v_fma_legacy_f32`) and flushes its sources; the + // zero-factor rule of the legacy multiply comes with it. + _ => { + let (a, bb, acc) = (self.ftz(a), self.ftz(bb), self.ftz(acc)); + self.legacy_fmad(a, bb, acc) + } }; float(self, r) } - "v_fma_legacy_f32" => { - let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); - let r = self.fma_legacy(a, bb, cc); - float(self, r) - } "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" => { let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); let m = self.s.m.bin(c, Bin::Mul, a, bb); let r = self.s.m.bin(c, Bin::Add, m, cc); float(self, r) } + "v_mad_legacy_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (a, bb, cc) = (self.ftz(a), self.ftz(bb), self.ftz(cc)); + let r = self.legacy_fmad(a, bb, cc); + float(self, r) + } "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => { let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); let r = match name { @@ -5354,14 +8084,20 @@ impl<'a> Lower<'a> { let r = self.s.m.cast(c, op, a, self.s.t.f32); float(self, r) } + "v_cvt_f32_f64" => { + let (lo, hi) = self.f64_pair(inst, 0)?; + let bits = self.f64_to_f32_bits(lo, hi); + let r = self.as_float(bits); + float(self, r) + } "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { // Each source is f32, or with op_sel_hi the low (op_sel: high) // f16 half; neg_hi is the absolute value here. let mut xs = Vec::new(); for i in 0..3 { let op = v.src.get(i).ok_or("a missing operand")?; - let x = self.operand(inst, op)?; let mut x = if v.opsel_hi >> i & 1 != 0 { + let x = self.f16_operand(inst, op)?; let h = if v.opsel >> i & 1 != 0 { let k16 = self.s.m.i32(16); self.s.m.bin(c, Bin::LShr, x, k16) @@ -5371,6 +8107,7 @@ impl<'a> Lower<'a> { self.s .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]) } else { + let x = self.operand(inst, op)?; self.as_float(x) }; if v.neg_hi >> i & 1 != 0 { @@ -5393,13 +8130,13 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = v.dst else { return Err("a mixed-precision result"); }; - // An unavailable old value is zero, as for other partial - // writes; never resurrect bits from before a full write. - let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { - Some(Ok(o)) => o, - _ => self.s.m.i32(0), + let old = match inst.read(Reg::V(reg)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), }; - let h = self.f16_nearest(r); + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]); let (keep, h) = if name == "v_fma_mixhi_f16" { let k16 = self.s.m.i32(16); (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16)) @@ -5424,7 +8161,9 @@ impl<'a> Lower<'a> { "v_cvt_f16_f32" if v.opsel == 0 => { // Rounded to nearest even (the MODE default) into the low half. let a = f(self, 0)?; - let r = self.f16_nearest(a); + let r = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]); let Some(Operand::Vector { reg, .. }) = v.dst else { return Err("a 16-bit result outside a VGPR"); }; @@ -5437,7 +8176,7 @@ impl<'a> Lower<'a> { let mut halves = Vec::new(); for k in 0..2 { let op = v.src.get(k).ok_or("a missing operand")?; - let mut x = self.operand(inst, op)?; + let mut x = self.f16_operand(inst, op)?; if v.opsel >> k & 1 != 0 { let k16 = self.s.m.i32(16); x = self.s.m.bin(c, Bin::LShr, x, k16); @@ -5464,7 +8203,42 @@ impl<'a> Lower<'a> { float(self, r) } "v_cndmask_b32" => { - let cond = self.select_condition(inst, v.src.get(2))?; + let mask = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + _ => None, + }; + const UNTRACKED: Why = "a select on an untracked mask"; + let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) { + Some(m) => self.boolean(m, c)?, + // A mask the code holds as a number (a constant bit + // pattern: every other lane, every other pair...): + // this lane's bit of it. Exact where host lanes are + // the console's. + None if self.mask_data == MaskData::Console => { + // (Also with each host wave taken as a wave of its + // own: a thread still knows its console lane, the + // relabelled thread index (`console_lane`), and the + // bit it picks is its own; nothing crosses lanes. + // Refused once, it was all that stopped 64-lane + // compute programs a 32-lane card then refused.) + let m = mask.ok_or(UNTRACKED)?; + let lo = self.i32_of(m).map_err(|_| UNTRACKED)?; + // wave64: the register after it holds lanes 32-63. + let high = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => { + Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?) + } + _ => None, + }; + let hi = match high { + Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?), + None => None, + }; + self.cross_lane(false)?; + self.lane_bit(c, lo, hi) + } + None => return Err(UNTRACKED), + }; if v.abs != 0 || v.neg != 0 { let (a, bb) = (f(self, 0)?, f(self, 1)?); let r = self.s.m.select(c, cond, bb, a); @@ -5486,12 +8260,10 @@ impl<'a> Lower<'a> { Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), _ => None, }; - // An untracked carry-in fails as an untracked select - // does, so compute retries it with console lanes. - match m.and_then(|m| self.x.st.masks.get(&m).copied()) { - Some(m) => Some(self.boolean(m, c)?), - None => Some(self.numeric_mask(inst, v.src.get(2))?), - } + let m = m + .and_then(|m| self.x.st.masks.get(&m).copied()) + .ok_or("a carry-in from an untracked mask")?; + Some(self.boolean(m, c)?) } else { None }; @@ -5509,43 +8281,80 @@ impl<'a> Lower<'a> { } Ok(()) } - "v_mad_u64_u32" | "v_mad_i64_i32" => { - // D.64 = S0.32 * S1.32 + S2.64. The 32 × 32-bit product - // always fits in 64 bits, so only the addition wraps. - let signed = name == "v_mad_i64_i32"; - let (a, bb) = (s(self, 0)?, s(self, 1)?); - let addend = self.src64(inst, 2)?; - let i64t = self.s.m.int(64); - let ext = if signed { Cast::SExt } else { Cast::ZExt }; - let a = self.s.m.cast(c, ext, a, i64t); - let bb = self.s.m.cast(c, ext, bb, i64t); - let product = self.s.m.bin(c, Bin::Mul, a, bb); - let r = self.s.m.bin(c, Bin::Add, product, addend); - if v.clamp { - return Err("a clamped 64-bit multiply-add"); + "v_permlane16_b32" | "v_permlanex16_b32" => { + // RDNA2 ISA 12.12: each nibble of {src2, src1} selects a lane + // in this row of 16, or the other row of the same 32-lane half. + // OP_SEL[0:1] are fetch-inactive and bound-control, not half selects. + if v.abs != 0 || v.neg != 0 || v.opsel & !3 != 0 { + return Err("permlane input modifiers"); } - let Some(Operand::Vector { reg, .. }) = v.dst else { - return Err("a 64-bit result"); - }; - let (lo, hi) = self.split64(r); - self.write(inst, Reg::V(reg), lo, guard); - self.write(inst, Reg::V(reg + 1), hi, guard); - // The carry out of the unsigned addition, a lane mask: this - // lane's bit. Left untracked for the signed form, whose - // carry nothing documents. - if !signed - && let Some(Operand::Scalar { code, .. }) = v.carry - && let Some(w) = inst.write(Reg::S(code)) + self.cross_lane(false)?; + let fetch_inactive = v.opsel & 1 != 0; + if fetch_inactive + && !all_lane_blocks(self.x.st).is_some_and(|all| all[self.cur_ir]) { - let carry = self.s.m.cmp(c, pred::IULT, r, addend); - self.lane_bits.insert(w, carry); - } - for &(_, w) in &inst.writes { - self.vals - .entry(w) - .or_insert(Val::Missing("a lane mask read as data")); + // DXIL cannot read the last VGPR value of a host invocation + // that has left through a lane branch. A guard keeps it here. + return Err("a permlane fetch from lanes outside the host branch"); } - Ok(()) + let (x, lo, hi) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let lane = self.lane_index(); + let (k7, k8, k15, k16, k31, k32, k4, one, zero) = ( + self.s.m.i32(7), + self.s.m.i32(8), + self.s.m.i32(15), + self.s.m.i32(16), + self.s.m.i32(31), + self.s.m.i32(32), + self.s.m.i32(4), + self.s.m.i32(1), + self.s.m.i32(0), + ); + let pos = self.s.m.bin(c, Bin::And, lane, k15); + let lower = self.s.m.cmp(c, pred::IULT, pos, k8); + let packed = self.s.m.select(c, lower, lo, hi); + let shift = self.s.m.bin(c, Bin::And, pos, k7); + let shift = self.s.m.bin(c, Bin::Mul, shift, k4); + let pick = self.s.m.bin(c, Bin::LShr, packed, shift); + let pick = self.s.m.bin(c, Bin::And, pick, k15); + let not15 = self.s.m.i32(!15); + let mut row = self.s.m.bin(c, Bin::And, lane, not15); + if name == "v_permlanex16_b32" { + row = self.s.m.bin(c, Bin::Xor, row, k16); + } + let src = self.s.m.bin(c, Bin::Or, row, pick); + let r = if fetch_inactive { + self.read_lane(x, src) + } else { + // Ballot the console EXEC guard as well as the host's active + // invocations. Never shuffle from an inactive host lane. + let enabled = guard.unwrap_or_else(|| self.s.m.bool(true)); + let i32t = self.s.t.i32; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let mask = self.s.op( + c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[enabled], + ); + let lo = self.s.m.extract(c, mask, 0); + let hi = self.s.m.extract(c, mask, 1); + let lower = self.s.m.cmp(c, pred::IULT, src, k32); + let word = self.s.m.select(c, lower, lo, hi); + let bit = self.s.m.bin(c, Bin::And, src, k31); + let bit = self.s.m.bin(c, Bin::LShr, word, bit); + let bit = self.s.m.bin(c, Bin::And, bit, one); + let active = self.s.m.cmp(c, pred::NE, bit, zero); + let safe = self.s.m.select(c, active, src, lane); + let read = self.read_lane(x, safe); + let fallback = if v.opsel & 2 != 0 { + zero + } else { + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a permlane result outside a VGPR"); + }; + self.i32_of(inst.read(Reg::V(reg)).ok_or("a permlane old value")?)? + }; + self.s.m.select(c, active, read, fallback) + }; + int(self, r) } "v_readlane_b32" => { let (a, lane) = (s(self, 0)?, s(self, 1)?); @@ -5556,7 +8365,43 @@ impl<'a> Lower<'a> { } else { self.cross_lane(false)?; } - let r = self.read_lane(a, lane)?; + if let Some(slot) = self.exchange.as_ref().map(|e| e.0) { + if self.local && self.local_any { + // this host wave's lane of that number (lanes 32..63 are 0..31 here) + let k31 = self.s.m.i32(31); + let here = self.s.m.bin(self.cur, Bin::And, lane, k31); + let r = self.read_lane(a, here); + return int(self, r); + } + if self.local { + return Err("a lane read in a half-wave"); + } + if self.exchange.as_ref().is_some_and(|e| e.1) { + // a group of 32 or fewer: the lane is in this host wave + let r = self.read_lane(a, lane); + return int(self, r); + } + // the lane that holds it may be in the other host wave: it gives it through LDS + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a lane read where not every lane runs"); + } + let cl = self.console_lane(); + let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane); + let k = self.exchange_pair(slot); + let at = self.begin_guarded(Some(is)); + let lds = self.s.lds(); + let ptr = self.s.m.element(self.cur, lds, k); + self.s.m.store(self.cur, ptr, a); + self.end_guarded(at, &[]); + let c2 = self.cur; + self.group_sync(c2); + let ptr = self.s.m.element(c2, lds, k); + let r = self.s.m.load(c2, ptr); + self.group_sync(c2); + return int(self, r); + } + let r = self.read_lane(a, lane); int(self, r) } "v_writelane_b32" => { @@ -5570,46 +8415,13 @@ impl<'a> Lower<'a> { None => self.s.m.i32(0), }; self.cross_lane(false)?; - let me = self.lane_index(); + // (Each host wave on its own too: the lane named compares + // its own console lane, and nothing crosses lanes.) + let me = self.console_lane(); let is = self.s.m.cmp(c, pred::EQ, me, lane); let r = self.s.m.select(c, is, a, old); int(self, r) } - "v_permlanex16_b32" => { - // Each lane reads src0 of a lane of the *other* row of 16 in - // its 32-lane half; lane i's pick is nibble i of the {src2, - // src1} selector (v_permlane16_b32 reads the same row). Both - // stay inside a 32-lane half, so the lane math is unchanged - // when a console wave64 program runs as two wave32 halves. - if v.opsel != 0 { - return Err("op_sel on v_permlanex16_b32"); - } - let (a, lo, hi) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); - self.cross_lane(false)?; - let lane = self.lane_index(); - let (k2, k8, k15, k16, k31, n31) = ( - self.s.m.i32(2), - self.s.m.i32(8), - self.s.m.i32(15), - self.s.m.i32(16), - self.s.m.i32(31), - self.s.m.i32(!31), - ); - let nib = self.s.m.bin(c, Bin::And, lane, k15); - let sh = self.s.m.bin(c, Bin::Shl, nib, k2); - let sh = self.s.m.bin(c, Bin::And, sh, k31); - let top = self.s.m.cmp(c, pred::IUGE, nib, k8); - let word = self.s.m.select(c, top, hi, lo); - let pick = self.s.m.bin(c, Bin::LShr, word, sh); - let pick = self.s.m.bin(c, Bin::And, pick, k15); - let half = self.s.m.bin(c, Bin::And, lane, n31); - let row = self.s.m.bin(c, Bin::And, lane, k16); - let row = self.s.m.bin(c, Bin::Xor, row, k16); - let base = self.s.m.bin(c, Bin::Or, half, row); - let idx = self.s.m.bin(c, Bin::Or, base, pick); - let val = self.read_lane(a, idx)?; - int(self, val) - } "v_readfirstlane_b32" if inst .writes @@ -5620,44 +8432,63 @@ impl<'a> Lower<'a> { let a = s(self, 0)?; int(self, a) } + "v_readfirstlane_b32" + if matches!(v.src.first(), Some(&Operand::Vector { reg, .. }) + if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) => + { + // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of + // the host wave holds the same, so the first lane's is the lane's own. + let a = s(self, 0)?; + int(self, a) + } "v_readfirstlane_b32" => { let a = s(self, 0)?; - if self.emulated.is_some() { - // Unguarded in a uniform block every lane is active, so - // the first is lane 0. - if guard.is_some() { - return Err("v_readfirstlane under a lane guard on a host \ - without 64-lane waves"); + let (mine, any) = self.first_lane(a, guard); + // two host waves that exchange: the console's first lane may be in the other + // one, unless every lane holds the same value + let alike = match v.src.first() { + Some(&Operand::Vector { reg, .. }) => { + inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x)) + } + _ => true, + }; + let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local; + let r = if halves && !alike { + if !self.all_lanes(self.cur_ir) { + // shortcut: `VICTORY_FIRSTLANE_OWN=1` takes the host wave's own + // first lane, exact when the value is the same in every lane of + // the console wave (the ray-tracing builder's scans read a sum of + // scalars this way, inside a loop whose exit is per console wave). + static OWN: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if *OWN.get_or_init(|| std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1")) { + return int(self, mine); + } + need(self.cur_ir); + return Err("a first-lane read where not every lane runs"); + } + let c = self.cur; + if guard.is_none() && super::shader_opt() & super::bitcode::opt::FIRST != 0 { + // Every lane is in EXEC: the console's first lane is + // lane 0, which the lower half of every console wave + // has. No half needs to ask the other whether it has + // a lane (an exchange of the constant 1: two group + // barriers), and the lower half's value is the answer. + let (lo, _) = self.exchange_halves(c, mine); + lo + } else { + let i32t = self.s.t.i32; + let has = self.s.m.cast(c, Cast::ZExt, any, i32t); + let (lo_has, hi_has) = self.exchange_halves(c, has); + let (lo, hi) = self.exchange_halves(c, mine); + let z = self.s.m.i32(0); + let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z); + let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z); + // neither half has a lane in EXEC: the console reads lane 0 + let hi = self.s.m.select(c, in_hi, hi, lo); + self.s.m.select(c, in_lo, lo, hi) } - let zero = self.s.m.i32(0); - let r = self.read_lane(a, zero)?; - return int(self, r); - } - self.s.flags |= flags::WAVE_OPS; - let first = self.s.op( - c, - "waveReadLaneFirst.i32", - Attr::NoUnwind, - self.s.t.i32, - 118, - &[a], - ); - let r = if self.s.pixel { - // The host's waveReadLaneFirst skips helper lanes, which - // the console's WQM keeps in EXEC: a waterfall loop on a - // helper lane would never match the value it reads and - // spin to the loop limit. A helper lane takes its own. - let helper = self.s.op( - c, - "isHelperLane.i1", - Attr::ReadOnly, - self.s.t.i1, - 221, - &[], - ); - self.s.m.select(c, helper, a, first) } else { - first + mine }; int(self, r) } @@ -5694,20 +8525,167 @@ impl<'a> Lower<'a> { let x = crate::resource::inline(k).ok_or("a special operand")?; Ok(self.s.m.int_const(i64t, i64::from(x as i32))) } - // A signed 64-bit operand sign-extends its 32-bit literal, as - // the hardware does (LLVM's AMDGPU operand rules). - Operand::Literal(x) if inst.name().ends_with("_i64") => { - Ok(self.s.m.int_const(i64t, i64::from(x as i32))) - } _ => { - // Literals (of unsigned and bit operands) and the null - // register: zero-extended. + // Literals and the null register: zero-extended. let x = self.operand(inst, &op)?; Ok(self.s.m.cast(c, Cast::ZExt, x, i64t)) } } } + /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying + /// `abs` and `neg` input modifiers on operand `k`. + fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.sdwa.is_some() || v.dpp.is_some() { + return Err("64-bit operand modifiers"); + } + let op = *v.src.get(k).ok_or("a missing operand")?; + let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> { + let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; + let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; + Ok((lo, hi)) + }; + let (lo, mut hi) = match op { + Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?, + Operand::Scalar { code, .. } if code != NULL => { + pair(self, Reg::S(code), Reg::S(code + 1))? + } + Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)), + Operand::Const(c @ 240..=248) => { + const INLINE_F64: [f64; 9] = [ + 0.5, + -0.5, + 1.0, + -1.0, + 2.0, + -2.0, + 4.0, + -4.0, + 1.0 / std::f64::consts::TAU, + ]; + let bits = INLINE_F64[(c - 240) as usize].to_bits(); + (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32)) + } + // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand. + Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)), + _ => return Err("a 64-bit float operand"), + }; + let c = self.cur; + if v.abs >> k & 1 != 0 { + let mask = self.s.m.i32(0x7FFF_FFFF); + hi = self.s.m.bin(c, Bin::And, hi, mask); + } + if v.neg >> k & 1 != 0 { + let sign = self.s.m.i32(0x8000_0000); + hi = self.s.m.bin(c, Bin::Xor, hi, sign); + } + Ok((lo, hi)) + } + + /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even, + /// without requiring host `DOUBLES` (`f64`) support. + fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let k0 = self.s.m.i32(0); + let k1 = self.s.m.i32(1); + let sign_mask = self.s.m.i32(0x8000_0000); + let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); + + let k20 = self.s.m.i32(20); + let k7ff = self.s.m.i32(0x7FF); + let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20); + let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff); + + let frac_mask = self.s.m.i32(0x000F_FFFF); + let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask); + let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo); + let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0); + + let k3 = self.s.m.i32(3); + let k29 = self.s.m.i32(29); + let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3); + let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29); + let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo); + + let rem_mask = self.s.m.i32(0x1FFF_FFFF); + let rem = self.s.m.bin(c, Bin::And, lo, rem_mask); + let half_rem = self.s.m.i32(0x1000_0000); + let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem); + let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem); + let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1); + let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0); + let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd); + let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up); + let norm_inc = self.s.m.select(c, norm_round, k1, k0); + + // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254]. + let k896 = self.s.m.i32(896); + let k23 = self.s.m.i32(23); + let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896); + let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23); + let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23); + let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc); + let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body); + + // Subnormal range: exp64 in [874, 896] -> shift in [1, 23]. + let k897 = self.s.m.i32(897); + let k32 = self.s.m.i32(32); + let k31 = self.s.m.i32(31); + let imp = self.s.m.i32(0x0080_0000); + let sig24 = self.s.m.bin(c, Bin::Or, imp, m23); + let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64); + // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch. + let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1); + let shift = self.s.m.select(c, lt1, k1, raw_shift); + let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23); + let shift = self.s.m.select(c, gt23, k23, shift); + let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift); + let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift); + let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift); + let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31); + let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0); + let low31 = self.s.m.i32(0x7FFF_FFFF); + let lost_lo = self.s.m.bin(c, Bin::And, lost, low31); + let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem); + let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0); + let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1); + let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0); + let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd); + let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie); + let sub_inc = self.s.m.select(c, sub_round, k1, k0); + let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc); + let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body); + + // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1). + let k873 = self.s.m.i32(873); + let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873); + let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz); + let min_bit = self.s.m.select(c, round_min, k1, k0); + let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit); + + // Overflow / Inf / NaN: exp64 >= 1151. + let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff); + let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz); + let inf_bits = self.s.m.i32(0x7F80_0000); + let qnan_bits = self.s.m.i32(0x7FC0_0000); + let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23); + let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits); + let over_res = self.s.m.bin(c, Bin::Or, sign, over_body); + + // Select final result by exponent range. + let k874 = self.s.m.i32(874); + let k1151 = self.s.m.i32(1151); + let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874); + let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897); + let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151); + let r = self.s.m.select(c, is_over, over_res, norm_res); + let r = self.s.m.select(c, is_sub, sub_res, r); + self.s.m.select(c, is_under, under_res, r) + } + fn join64(&mut self, lo: V, hi: V) -> V { let c = self.cur; let ty = self.s.m.int(64); @@ -5718,6 +8696,69 @@ impl<'a> Lower<'a> { self.s.m.bin(c, Bin::Or, lo, hi) } + /// The bits of the float nearest the double whose dwords are `lo` and + /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN + /// kept (a NaN stays quiet), a result below the smallest normal float + /// signed zero (flushed, as the console's default float mode does). + // The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's + // float mode for this instruction is checked. + #[allow(dead_code)] + fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23)); + let sign_mask = k(self, 0x8000_0000); + let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); + let e = self.s.m.bin(c, Bin::LShr, hi, k20); + let e_mask = k(self, 0x7ff); + let e = self.s.m.bin(c, Bin::And, e, e_mask); + // The top 23 bits of the 52-bit mantissa, and the 29 below them. + let m_mask = k(self, 0x000f_ffff); + let mh = self.s.m.bin(c, Bin::And, hi, m_mask); + let mh = self.s.m.bin(c, Bin::Shl, mh, k3); + let ml = self.s.m.bin(c, Bin::LShr, lo, k29); + let m = self.s.m.bin(c, Bin::Or, mh, ml); + let rest_mask = k(self, 0x1fff_ffff); + let rest = self.s.m.bin(c, Bin::And, lo, rest_mask); + // Round to nearest even: up past half, or at half when odd. + let half = k(self, 0x1000_0000); + let one = k(self, 1); + let above = self.s.m.cmp(c, pred::IUGT, rest, half); + let at = self.s.m.cmp(c, pred::EQ, rest, half); + let odd = self.s.m.bin(c, Bin::And, m, one); + let zero = k(self, 0); + let odd = self.s.m.cmp(c, pred::NE, odd, zero); + let tie = self.s.m.bin(c, Bin::And, at, odd); + let up = self.s.m.bin(c, Bin::Or, above, tie); + let up = self.s.m.select(c, up, one, zero); + // Rebias the exponent (1023 → 127); a carry out of the mantissa + // steps the exponent, up to infinity. + let bias = k(self, 1023 - 127); + let e32 = self.s.m.bin(c, Bin::Sub, e, bias); + let ex = self.s.m.bin(c, Bin::Shl, e32, k23); + let normal = self.s.m.bin(c, Bin::Add, ex, m); + let normal = self.s.m.bin(c, Bin::Add, normal, up); + let normal = self.s.m.bin(c, Bin::Or, normal, sign); + // Exponents out of the float's range (signed, after rebiasing). + let inf = k(self, 0x7f80_0000); + let inf = self.s.m.bin(c, Bin::Or, inf, sign); + let k255 = k(self, 255); + let big = self.s.m.cmp(c, pred::SGE, e32, k255); + let small = self.s.m.cmp(c, pred::SLE, e32, zero); + let r = self.s.m.select(c, big, inf, normal); + let r = self.s.m.select(c, small, sign, r); + // Infinity and NaN (a NaN with any mantissa bit set stays a NaN). + let all = k(self, 0x7ff); + let special = self.s.m.cmp(c, pred::EQ, e, all); + let any = self.s.m.bin(c, Bin::Or, mh, ml); + let any = self.s.m.bin(c, Bin::Or, any, rest); + let nan = self.s.m.cmp(c, pred::NE, any, zero); + let quiet = k(self, 0x0040_0000); + let quiet = self.s.m.select(c, nan, quiet, zero); + let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet); + self.s.m.select(c, special, special_bits, r) + } + /// The low and high dwords of an i64. fn split64(&mut self, x: V) -> (V, V) { let c = self.cur; @@ -5796,9 +8837,11 @@ impl<'a> Lower<'a> { return Err("a 16-bit result outside a VGPR"); }; let mut high = v.opsel >> 3 & 1 != 0; - // SDWA: the word written, the other one kept (preserve), sign-extended - // above the low word (sext), or zero (pad; a sign extension above the - // high word adds nothing, and bits below it pad with zero). + // SDWA: the word written, the other one kept (preserve), bit 15 + // copied upward (sext: dst_unused 1 with WORD_0), or zero (pad; a sign + // extension above the high word or a whole dword adds nothing). The + // reserved dst_unused 3 is refused. (Upstream VIctory #3124: a 16-bit + // -1 written with sext came out as 0x0000FFFF.) let mut keep = true; let mut sext = false; if let Some(sd) = v.sdwa { @@ -5806,7 +8849,7 @@ impl<'a> Lower<'a> { (4, 2) => {} (5, 2) => high = true, (4, 1) => (keep, sext) = (false, true), - (4, 0) | (6, _) => keep = false, + (4, 0) | (6, 0..=2) => keep = false, (5, 0 | 1) => (high, keep) = (true, false), _ => return Err("an SDWA destination of a 16-bit operation"), } @@ -5931,7 +8974,15 @@ impl<'a> Lower<'a> { if v.clamp { f = l.unary(7, f); } - let h = l.f16_nearest(f); + // The console rounds to nearest; the host's conversion may round toward zero + // (NVIDIA's does), one step of the last place lower where the two differ. + // shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1` + // ([`f16_nearest_on`]), which costs a dozen instructions per result. + let h = if f16_nearest_on() { + l.f16_nearest(f) + } else { + l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }; l.write_half(inst, h, guard) }; if name == "v_cvt_f16_f32" { @@ -6031,20 +9082,15 @@ impl<'a> Lower<'a> { }; return float_result(self, r); } - if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") { - if v.clamp || v.omod != 0 { - return Err("modifiers on a 16-bit integer operation"); - } - let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?; - return self.write_half(inst, r, guard); - } if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") { if v.clamp || v.omod != 0 { return Err("modifiers on a 16-bit integer operation"); } // Toward zero, saturating at the 16-bit range (infinities // included); NaN gives 0. Clamped in f32 first, where every - // f16 is exact, so the conversion never leaves i32's range. + // f16 is exact, so the conversion never leaves i32's range + // (upstream PR #384's arithmetic; the source's abs and neg + // modifiers are applied by `half_fsrc`, as before). let a = self.half_fsrc(inst, 0)?; let (lo, hi) = if name == "v_cvt_u16_f16" { (0.0f32, 65535.0f32) @@ -6060,6 +9106,13 @@ impl<'a> Lower<'a> { let r = self.s.m.select(c, nan, z, r); return self.write_half(inst, r, guard); } + if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") { + if v.clamp || v.omod != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?; + return self.write_half(inst, r, guard); + } // 16-bit integers: computed on the low halves, the low 16 bits kept. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 { return Err("modifiers on a 16-bit integer operation"); @@ -6227,7 +9280,7 @@ impl<'a> Lower<'a> { return Err("modifiers on a packed integer operation"); } let c = self.cur; - let f32t = self.s.t.f32; + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); let mut halves = Vec::new(); for high in [false, true] { let mut xs = Vec::new(); @@ -6259,7 +9312,8 @@ impl<'a> Lower<'a> { if v.clamp { f = self.unary(7, f); } - self.f16_nearest(f) + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) } else { let k16 = self.s.m.i32(16); let sext = |l: &mut Self, x: V| { @@ -6668,7 +9722,7 @@ impl<'a> Lower<'a> { } else if self.s.mesh.is_none() { self.cross_lane(false)?; } - let lane = self.lane_index(); + let lane = self.console_lane(); let below = if name == "v_mbcnt_lo_u32_b32" { lane } else { @@ -6900,93 +9954,177 @@ impl<'a> Lower<'a> { fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Some(&interp) = self.interps.get(&site) else { - return Err("the first half of an interpolation"); + return Err(FIRST_HALF); + }; + let name = inst.name(); + let (dst, src) = match &inst.fields { + Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)), + Fields::Valu(v) => { + if v.abs != 0 || v.neg != 0 { + return Err("interpolation operand modifiers"); + } + (v.dst.ok_or("an interpolation")?, v.src.get(1).copied()) + } + _ => unreachable!(), }; - let (attribute, mode) = match interp { + let Operand::Vector { reg, .. } = dst else { + return Err("an interpolation"); + }; + // A float operand of the instruction. + let float = |l: &mut Self, op: Option<Operand>| -> Result<V, Why> { + let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?; + Ok(l.as_float(x)) + }; + // What the result adds to the evaluated channel (a second half's + // first half, when the halves evaluate on their own). + let mut add = None; + let (attribute, eval) = match *interp { Interp::Interpolated { attribute, barycentric, .. - } => ( - attribute, - match barycentric { - Barycentric::PerspectiveCenter => 2, - Barycentric::PerspectiveCentroid => 3, - Barycentric::PerspectiveSample => 6, - Barycentric::LinearCenter => 4, - Barycentric::LinearCentroid => 5, - Barycentric::LinearSample => 7, - Barycentric::PerspectivePullModel => return Err("pull-model interpolation"), - }, - ), + } => { + let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?; + let eval = if self.per_vertex(attribute.row) { + // The element is read per vertex elsewhere, so it is + // constant: weigh its vertices with SV_Barycentrics. + let mut ij = [None; 2]; + for (index, w) in ij.iter_mut().enumerate() { + let x = match self.barycentric(barycentric, index as u8) { + Val::I32(x) => x, + Val::Missing(w) => return Err(w), + Val::Bit(_) => unreachable!(), + }; + *w = Some(self.as_float(x)); + } + Eval::Weights { + p0: true, + i: ij[0], + j: ij[1], + } + } else { + Eval::Mode(mode) + }; + (attribute, eval) + } // P0, the provoking vertex: a flat (nointerpolation) input. Interp::Vertex { attribute, vertex: 2, - } => (attribute, 1), - Interp::Vertex { .. } => return Err("a non-provoking vertex value"), - }; - let dst = match &inst.fields { - Fields::Vintrp { dst, .. } => *dst, - Fields::Valu(v) => v.dst.ok_or("an interpolation")?, - _ => unreachable!(), - }; - let Operand::Vector { reg, .. } = dst else { - return Err("an interpolation"); - }; - // A channel of an input element, interpolated as `mode` says. - let channel = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> { - let (id, col) = l - .find_input(row, ch) - .ok_or("an input the signature lacks")?; - let e = &mut l.s.inputs[id]; - if e.interp != mode && e.usage != 0 { - return Err("one input interpolated two ways"); - } - e.interp = mode; - match l.load_any_input(id, col) { - Val::I32(x) => Ok(x), - _ => Err("an input"), + } => (attribute, Eval::Mode(1)), + // P10 and P20: what the first and second halves weigh, P1 - P0 + // and P2 - P0, which is what the hardware holds for an + // attribute the program also interpolates. + Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => { + let one = Some(self.s.m.f32(1f32.to_bits())); + let (i, j) = if vertex == 0 { + (one, None) + } else { + (None, one) + }; + (attribute, Eval::Weights { p0: false, i, j }) + } + Interp::Vertex { .. } => return Err("a non-provoking vertex value"), + // A half of an interpolation with computed i or j: P0 + i P10, + // or the old dst (f16: the third operand) + j P20. + Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => { + let i = Some(float(self, src)?); + ( + attribute, + Eval::Weights { + p0: true, + i, + j: None, + }, + ) + } + Interp::Weighted { attribute } => { + let old = match &inst.fields { + Fields::Valu(v) => v.src.get(2).copied(), + _ => Some(dst), + }; + add = Some(float(self, old)?); + let j = Some(float(self, src)?); + ( + attribute, + Eval::Weights { + p0: false, + i: None, + j, + }, + ) } }; let packing = match &self.x.native.io { StageIo::Ps { inputs, .. } => inputs .iter() .find(|i| i.row == attribute.row && i.fp16) - .map(|i| (i.pack2, (i.row2 != i.row).then_some(i.row2))), + .map(|i| { + let packs = if i.pack2 { + input_packs(&self.x.native.io, &self.s.inputs) + } else { + Vec::new() + }; + (i.pack2, packs) + }), _ => None, }; - let f16 = inst.name().ends_with("_f16"); + let f16 = name.ends_with("_f16"); + // The evaluated channel plus `add`, as a float. + let total = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> { + let x = l.eval_channel(row, ch, eval)?; + let x = l.as_float(x); + Ok(match add { + Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x), + None => x, + }) + }; let x = match packing { None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"), - None => channel(self, attribute.row, attribute.channel)?, - Some((pack2, b)) => { + None => { + let x = total(self, attribute.row, attribute.channel)?; + self.as_int(x) + } + Some((pack2, packs)) => { // 16-bit values: one in the low half of each dword, or two // per dword (`packed_half`); the host's are 32-bit floats. let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> { let src = if pack2 { - packed_half(&l.s.inputs, attribute.row, b, h) + packed_half(&l.s.inputs, &packs, attribute.row, h) } else { h.is_multiple_of(2).then_some((attribute.row, h / 2)) }; - let Some((row, ch)) = src else { - return Ok(None); - }; - let x = channel(l, row, ch)?; - let f = l.as_float(x); - Ok(Some(l.f16_nearest(f))) + match src { + Some((row, ch)) => total(l, row, ch).map(Some), + None => Ok(None), + } }; - let h = 2 * attribute.channel; + let to_f16 = |l: &mut Self, f: V| { + let i32t = l.s.t.i32; + l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }; + let h = 2 * attribute.channel + u8::from(attribute.high); let c = self.cur; - if f16 { - let lo = half(self, h + u8::from(attribute.high))? - .ok_or("a packed input half no element holds")?; + if name == "v_interp_p1ll_f16" { + // An f32 result from 16-bit vertex values. + let f = half(self, h)?.ok_or("a packed input half no element holds")?; + self.as_int(f) + } else if f16 { + let f = half(self, h)?.ok_or("a packed input half no element holds")?; + let lo = to_f16(self, f); self.low_half(inst, reg, lo) - } else if mode == 1 { + } else if matches!(eval, Eval::Mode(1)) { // The whole dword of a flat input: both halves. + let h = 2 * attribute.channel; let z = self.s.m.i32(0); - let lo = half(self, h)?.unwrap_or(z); - let hi = half(self, h + 1)?.unwrap_or(z); + let lo = match half(self, h)? { + Some(f) => to_f16(self, f), + None => z, + }; + let hi = match half(self, h + 1)? { + Some(f) => to_f16(self, f), + None => z, + }; let k16 = self.s.m.i32(16); let hi = self.s.m.bin(c, Bin::Shl, hi, k16); self.s.m.bin(c, Bin::Or, lo, hi) @@ -7000,6 +10138,100 @@ impl<'a> Lower<'a> { Ok(()) } + /// Whether the program reads attribute row `row` per vertex (an + /// interpolation with computed barycentrics, or P10 or P20): then its + /// element is declared constant and read with `attributeAtVertex`. + fn per_vertex(&self, row: u8) -> bool { + self.x.io.interps.iter().any(|(_, i)| match *i { + Interp::Weighted { attribute } => attribute.row == row, + Interp::Vertex { attribute, vertex } => { + attribute.row == row && vertex != 2 && self.interpolated(row) + } + Interp::Interpolated { .. } => false, + }) + } + + /// Whether the program interpolates attribute row `row` (so the + /// hardware holds P1 - P0 and P2 - P0 for it). + fn interpolated(&self, row: u8) -> bool { + self.x.io.interps.iter().any(|(_, i)| match *i { + Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => { + attribute.row == row + } + Interp::Vertex { .. } => false, + }) + } + + /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits. + fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result<V, Why> { + let (id, col) = self + .find_input(row, ch) + .ok_or("an input the signature lacks")?; + let mode = match eval { + Eval::Mode(mode) => mode, + Eval::Weights { .. } => 1, + }; + let e = &mut self.s.inputs[id]; + if e.interp != mode && e.usage != 0 { + return Err("one input interpolated two ways"); + } + e.interp = mode; + let Eval::Weights { p0, i, j } = eval else { + return match self.load_any_input(id, col) { + Val::I32(x) => Ok(x), + _ => Err("an input"), + }; + }; + let v0 = self.vertex_input(id, col, 0); + let c = self.cur; + let mut acc = p0.then_some(v0); + for (k, w) in [(1, i), (2, j)] { + let Some(w) = w else { continue }; + let vk = self.vertex_input(id, col, k); + let d = self.s.m.bin(c, Bin::Sub, vk, v0); + acc = Some(match acc { + Some(a) => self.fmad(w, d, a), + None => self.s.m.bin(c, Bin::Mul, w, d), + }); + } + let acc = acc.ok_or("an interpolation")?; + Ok(self.as_int(acc)) + } + + /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them) + /// of a constant input element's channel, as a float. + fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V { + let e = &mut self.s.inputs[id]; + e.usage |= 1 << col; + let int = e.comp != 9; + let (ty, suffix) = if int { + (self.s.t.i32, ".i32") + } else { + (self.s.t.f32, ".f32") + }; + self.s.flags |= flags::BARYCENTRICS; + let entry = self.s.entry; + let args = [ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + self.s.m.i8(k), + ]; + let v = self.s.op( + entry, + &format!("attributeAtVertex{suffix}"), + Attr::ReadNone, + ty, + 137, + &args, + ); + if int { + self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32) + } else { + v + } + } + /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit /// results keep the register's high half (GFX10). fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V { @@ -7014,20 +10246,52 @@ impl<'a> Lower<'a> { self.s.m.bin(c, Bin::Or, old, x) } - /// `x` (low 16 bits) as the high half of VGPR `reg`, keeping its low half. - fn high_half(&mut self, inst: &Inst, reg: u8, x: V) -> V { - let c = self.cur; - let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { - Some(Ok(o)) => o, - _ => self.s.m.i32(0), - }; - let (low, k16) = (self.s.m.i32(0xFFFF), self.s.m.i32(16)); - let old = self.s.m.bin(c, Bin::And, old, low); - let x = self.s.m.bin(c, Bin::Shl, x, k16); - self.s.m.bin(c, Bin::Or, old, x) + fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let sampler = self.descriptors.get(&((b, i), true)).copied(); + if let Some(Source::Phi { block, args }) = sampler + && let [first @ Source::Constant(_), second @ Source::Constant(_)] = args.as_slice() + && let [left, right] = self.x.p.blocks[*block].preds.as_slice() + { + // Immediate samplers are separate static bindings. Sample both with + // the original derivatives, then select the texel on the same edge + // that supplied the console's sampler. + if self.block[*left].is_none() { + return self.image_with_sampler(inst, b, i, Some(second)); + } + if self.block[*right].is_none() { + return self.image_with_sampler(inst, b, i, Some(first)); + } + let edge = |pred: usize| { + self.edges.get(&(pred, *block)).copied().or(self.tail[pred]) + .ok_or("a sampler choice with an unfinished predecessor") + }; + let (left, right) = (edge(*left)?, edge(*right)?); + let join = self.block[*block].ok_or("a sampler choice without a host block")?; + let chosen = self.s.m.phi(join, self.s.t.i1); + let (yes, no) = (self.s.m.bool(true), self.s.m.bool(false)); + self.s.m.set_phi(chosen, vec![(yes, left), (no, right)]); + self.image_with_sampler(inst, b, i, Some(first))?; + let left = inst.writes.iter() + .map(|&(_, v)| self.i32_of(v)) + .collect::<Result<Vec<_>, _>>()?; + self.image_with_sampler(inst, b, i, Some(second))?; + for (&(_, v), a) in inst.writes.iter().zip(left) { + let b = self.i32_of(v)?; + let result = self.s.m.select(self.cur, chosen, a, b); + self.vals.insert(v, Val::I32(result)); + } + return Ok(()); + } + self.image_with_sampler(inst, b, i, sampler) } - fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + fn image_with_sampler( + &mut self, + inst: &Inst, + b: usize, + i: usize, + sampler: Option<&Source>, + ) -> Result<(), Why> { let Fields::Image { data, addr, @@ -7050,7 +10314,7 @@ impl<'a> Lower<'a> { // A load or sample with no channel enabled returns the first. let dmask = if *dmask == 0 { &1 } else { dmask }; let site = (b, i); - let guard = self.guard(b, i)?; + let guard = self.effect_guard(b, i)?; let c = self.cur; let (kind, coords) = match dim { 0 => (1, 1), @@ -7098,17 +10362,12 @@ impl<'a> Lower<'a> { .get(&(site, false)) .copied() .ok_or("an untracked image")?; - // A cube array: its slice is in the face operand. - let kind = if kind == 5 && self.cube_array(src) { - 9 - } else { - kind - }; - let cube = matches!(kind, 5 | 9); let store = name.starts_with("image_store"); - let u = self.uav_bits(src, self.used_kind(src)) | if store { 0x1000 } else { 0 }; - let uav = u & 0x1000 != 0; - let props = (kind | u, 0x409); + let uav = store + || self + .used_kind(src) + .is_some_and(|u| u.kind == ResourceType::Uav); + let props = (kind | if uav { 0x1000 } else { 0 }, 0x409); if let Some(op) = name.strip_prefix("image_atomic_") { // GLC returns the old value. DXIL implements subtraction by adding // the two's complement of the operand at the same width. @@ -7165,7 +10424,7 @@ impl<'a> Lower<'a> { } else { original }; - let h = self.handle(site, src, false, (kind | 0x1000 | u, component))?; + let h = self.handle(site, src, false, (kind | 0x1000, component))?; let mut args = vec![h]; let (intrinsic, opcode) = if compare { let comparand = if wide { @@ -7265,20 +10524,18 @@ impl<'a> Lower<'a> { self.end_guarded(at, &[]); return Ok(()); } + let has_cl = name.ends_with("_cl"); let (op, sample) = match name { - "image_sample" | "image_sample_cl" | "image_sample_o" => (60, true), - "image_sample_lz" | "image_sample_l" => (62, true), + "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true), + "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true), "image_sample_b" | "image_sample_b_cl" => (61, true), "image_sample_c_lz" => (65, true), "image_sample_d" | "image_sample_d_cl" => (63, true), "image_get_lod" if self.s.pixel => (81, true), // Implicit derivatives: pixel shaders only. - "image_sample_c" | "image_sample_c_cl" if self.s.pixel => (64, true), - // The LOD of `_l` is not read: DXIL gathers from level 0, the - // one a title's gathers of shadow maps and G-buffers name. - // shortcut: a gather of a lower level reads level 0. - "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" - | "image_gather4_l_o" => (73, true), + "image_sample_c" if self.s.pixel => (64, true), + "image_sample_c_cl" if self.s.pixel => (64, true), + "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true), "image_load" | "image_load_mip" => (66, false), "image_get_resinfo" => (72, false), _ => return Err(name), @@ -7304,21 +10561,12 @@ impl<'a> Lower<'a> { 2 | 5 | 6 => [true, true, false, true], _ => [true, true, true, true], }; - // The console counts a cube array's layers in faces (Mesa - // lowers a cube array's size query to divide them by 6). - let layers = (kind == 9).then(|| { - let z = self.s.m.extract(c, d, 2); - let six = self.s.m.i32(6); - self.s.m.bin(c, Bin::Mul, z, six) - }); let Operand::Vector { reg, .. } = *data else { return Err("an image result"); }; for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() { let x = if ch == 3 && uav || !present[ch as usize] { one - } else if let (2, Some(layers)) = (ch, layers) { - layers } else { self.s.m.extract(c, d, ch) }; @@ -7332,33 +10580,56 @@ impl<'a> Lower<'a> { let h = self.handle(site, src, false, props)?; let fu = self.s.m.undef(self.s.t.f32); let iu = self.s.m.undef(self.s.t.i32); + // A gather at a named level, done as four texel reads (below). + let mut gathered: Option<[V; 4]> = None; let r = if sample { - let ss = self - .descriptors - .get(&(site, true)) - .copied() - .ok_or("an untracked sampler")?; + let ss = sampler.ok_or("an untracked sampler")?; // Comparison: the reference value is the first address after // the bias, and the sampler is a comparison sampler. let cmp = matches!(op, 64 | 65); if cmp && (*a16 || dmask.count_ones() != 1) { return Err("a comparison sample of 16-bit coordinates or several channels"); } - let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?; + let mut sampler_choice: Option<(V, Vec<u32>)> = None; + let sh = match ss { + Source::Phi { block, args } => { + match self.sampler_phi_choice(*block, args, cmp, 8) { + Ok((None, regs)) => self.s.sampler_handle(self.cur, regs[0]), + Ok((Some(idx), regs)) => { + let first = self.s.sampler_handle(self.cur, regs[0]); + sampler_choice = Some((idx, regs)); + first + } + Err(_) => { + self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))? + } + } + } + _ => self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?, + }; // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13, - // signed (programmable offsets: gathers only). Offset, bias and - // z-compare are always full 32-bit VGPRs even with a16. + // signed (programmable offsets: gathers only). let offset_word = name.ends_with("_o"); - let has_cl = name.ends_with("_cl"); - let first = usize::from(offset_word) + usize::from(op == 61) + usize::from(cmp); + let first = usize::from(offset_word) + + usize::from(name.starts_with("image_sample_b")) + + usize::from(cmp); // Coordinates the size divides (not the array slice); explicit - // gradients (x then y) come before the coordinates and remain - // 32-bit floats on GFX10.3 unless the opcode is a `_g16` form. + // gradients (x then y) come before the coordinates. let spatial = coords - usize::from(kind == 6 || kind == 7); - let deriv_regs = if op == 63 { spatial } else { 0 }; + // A cube's gradients are the two of its face coordinates. + let grads = if kind == 5 { 2 } else { spatial }; + let deriv_regs = if op == 63 { + if *a16 { + grads.div_ceil(2) + } else { + grads + } + } else { + 0 + }; let coord_base = first + 2 * deriv_regs; let mut cs = vec![fu; 4]; - // With a16, sampling coordinates, bias (low half), LOD and clamp are f16. + // With a16, sampling coordinates, gradients, LOD and clamp are f16. let to_float = |l: &mut Self, x: V| { if *a16 { let f = l.s.t.f32; @@ -7367,29 +10638,15 @@ impl<'a> Lower<'a> { l.as_float(x) } }; - if cube && (*unorm || op == 63 || op == 81) { - return Err("a cube sample with texel coordinates, gradients or a level query"); + if kind == 5 && (*unorm || op == 81) { + return Err("a cube sample with texel coordinates or a level query"); } for (k, slot) in cs.iter_mut().enumerate().take(coords) { let x = addr_packed(self, coord_base, k)?; *slot = to_float(self, x); } - if cube { - let face = if kind == 9 { - // 8 × slice + face: the slice is the fourth coordinate. - let (eighth, eight) = ( - self.s.m.f32(0.125f32.to_bits()), - self.s.m.f32(8.0f32.to_bits()), - ); - let x = self.s.m.bin(c, Bin::Mul, cs[2], eighth); - let slice = self.unary(27, x); - let whole = self.s.m.bin(c, Bin::Mul, slice, eight); - cs[3] = slice; - self.s.m.bin(c, Bin::Sub, cs[2], whole) - } else { - cs[2] - }; - let dir = self.cube_direction(cs[0], cs[1], face); + if kind == 5 { + let dir = self.cube_direction(cs[0], cs[1], cs[2]); cs[..3].copy_from_slice(&dir); } if *unorm { @@ -7427,7 +10684,7 @@ impl<'a> Lower<'a> { } return Ok(()); } - let offsets = if cube { + let offsets = if kind == 5 { 0 } else { (coords - usize::from(kind == 6 || kind == 7)).min(3) @@ -7437,22 +10694,14 @@ impl<'a> Lower<'a> { for o in os.iter_mut().take(offsets) { *o = zero; } - if offset_word && op != 73 { - // DXIL takes immediate offsets in -8..=7; the console's are - // 6-bit fields (x, y, z a byte apart) and may be computed. + if offset_word && offsets > 0 { let w = addr_val(self, 0)?; - let w = self - .s - .m - .int_value(w) - .ok_or("a sample offset that is not constant")? as u32; - for (k, o) in os.iter_mut().enumerate().take(offsets) { - let x = (w >> (8 * k) & 0x3F) as i32; - let x = if x >= 32 { x - 64 } else { x }; - if !(-8..=7).contains(&x) { - return Err("a sample offset past -8..7"); - } - *o = self.s.m.i32(x as u32); + for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) { + // Bits at..at+5 sign-extended: shift up, then down. + let left = self.s.m.i32(at); + let t = self.s.m.bin(c, Bin::Shl, w, left); + let k26 = self.s.m.i32(26); + os[k] = self.s.m.bin(c, Bin::AShr, t, k26); } } let mut args = vec![h, sh]; @@ -7463,82 +10712,177 @@ impl<'a> Lower<'a> { } else { fu }; - match op { - 60 | 61 if !self.s.pixel => { - // Outside pixel shaders the console still takes the level - // from each quad of lanes (lane 1 minus lane 0 across, - // lane 2 minus lane 0 down); DXIL before validator 1.8 - // has no implicit derivatives there, so the quad's - // differences become explicit gradients. A bias scales - // them by 2^bias, the same level for isotropic filtering. - self.cross_lane(true)?; - let scale = if op == 61 { - let bias = addr_val(self, 0)?; - let bias = self.as_float(bias); - Some(self.unary(21, bias)) + let call_sample = |l: &mut Self, + intrinsic: &str, + opcode: u32, + args: &[V], + gathered: &mut Option<[V; 4]>| + -> V { + let Some((idx, ref regs)) = sampler_choice else { + return l + .s + .op(c, intrinsic, Attr::ReadOnly, l.s.t.res_ret, opcode, args); + }; + let merge = l.s.m.new_block(); + let mut cur_test = c; + let mut per_ch: [Vec<(V, usize)>; 4] = Default::default(); + let mut last_r = args[0]; + for (i, ®) in regs.iter().enumerate() { + let arm = if i + 1 == regs.len() { + cur_test } else { - None + let arm = l.s.m.new_block(); + let next = l.s.m.new_block(); + let k = l.s.m.i32(i as u32); + let cond = l.s.m.cmp(cur_test, pred::EQ, idx, k); + l.s.m.terminate(cur_test, Term::CondBr(cond, arm, next)); + cur_test = next; + arm }; - let g = self.quad_gradients(&cs[..spatial], scale)?; - args.extend(&os); - args.extend(g); - args.push(fu); - self.s.op( - c, - "sampleGrad.f32", + let mut arm_args = args.to_vec(); + arm_args[1] = l.s.sampler_handle(arm, reg); + let r_i = l.s.op( + arm, + intrinsic, Attr::ReadOnly, - self.s.t.res_ret, - 63, - &args, - ) + l.s.t.res_ret, + opcode, + &arm_args, + ); + for (ch, slot) in per_ch.iter_mut().enumerate() { + let v = l.s.m.extract(arm, r_i, ch as u32); + slot.push((v, arm)); + } + l.s.m.terminate(arm, Term::Br(merge)); + last_r = r_i; + } + let mut phis = [fu; 4]; + for (ch, incoming) in per_ch.into_iter().enumerate() { + let phi = l.s.m.phi(merge, l.s.t.f32); + l.s.m.set_phi(phi, incoming); + phis[ch] = phi; + } + *gathered = Some(phis); + l.cur = merge; + last_r + }; + match op { + // Outside a pixel shader there are no screen derivatives: + // the validator refuses `sample` there ("features + // incompatible with the shader stage": 730 compute programs, + // among them the G-buffer resolves and the sky), and what a + // driver does with it is its own affair. + // shortcut: such a sample reads level 0 (a bias: that + // level). The console takes derivatives from neighbouring + // lanes there; compute them from the lanes if a resolve + // shows the wrong mip. + 60 if !self.s.pixel => { + args.extend(&os); + args.push(self.s.m.f32(0)); + call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered) } 60 => { + if offset_word { + // DXIL wants immediate offsets in -8..=7 here; the + // console's are 6-bit and may be computed. A + // constant word in range becomes immediates + // (upstream PR #634); anything else keeps the + // offsets computed above (upstream refuses those). + let w = addr_val(self, 0)?; + if let Some(w) = self.s.m.int_value(w) { + let w = w as u32; + let field = |k: usize| { + let x = (w >> (8 * k) & 0x3F) as i32; + if x >= 32 { x - 64 } else { x } + }; + let n = offsets.min(2); + if (0..n).all(|k| (-8..=7).contains(&field(k))) { + for (k, o) in os.iter_mut().enumerate().take(n) { + *o = self.s.m.i32(field(k) as u32); + } + } + } + } args.extend(&os); args.push(clamp); - self.s - .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args) + call_sample(self, "sample.f32", 60, &args, &mut gathered) } 61 => { - // With a16, bias occupies a full VGPR but holds an f16 in - // its low 16 bits (upper half undefined). + // With a16 the bias is an f16 in the low half of its + // word (the word is whole, the value is not). let bias = addr_u32(self, usize::from(offset_word))?; let bias = if *a16 { - let mask = self.s.m.i32(0xFFFF); - let lo = self.s.m.bin(c, Bin::And, bias, mask); - to_float(self, lo) + let low = self.s.m.i32(0xFFFF); + let bias = self.s.m.bin(c, Bin::And, bias, low); + to_float(self, bias) } else { self.as_float(bias) }; args.extend(&os); - args.extend([bias, clamp]); - self.s.op( - c, - "sampleBias.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 61, - &args, - ) + if self.s.pixel { + args.extend([bias, clamp]); + call_sample(self, "sampleBias.f32", 61, &args, &mut gathered) + } else { + // As above: the bias is the level. + args.push(bias); + call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered) + } + } + 63 if kind == 5 => { + // A cube with explicit gradients: the host wants them + // as changes of the direction, the console gives the + // changes of the face coordinates (the face is one + // unit wide). The level they select is taken from the + // longer of the two, in texels, and sampled directly. + // shortcut: no anisotropic filtering for these samples + // (the longer axis alone decides the level). + let mut len = [fu; 2]; + for (axis, slot) in len.iter_mut().enumerate() { + let mut sum = self.s.m.f32(0); + for k in 0..2 { + let x = addr_packed(self, first + axis * deriv_regs, k)?; + let x = to_float(self, x); + let sq = self.s.m.bin(c, Bin::Mul, x, x); + sum = self.s.m.bin(c, Bin::Add, sum, sq); + } + *slot = self.unary(24, sum); // square root + } + let longer = self.binary(35, len[0], len[1]); // maximum + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let z = self.s.m.i32(0); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]); + let width = self.s.m.extract(c, d, 0); + let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32); + let texels = self.s.m.bin(c, Bin::Mul, longer, width); + // DXIL's logarithm is the one to base 2 (it was taken for + // the natural one: every level came out 1.44 times too + // high, cube maps sampled blurrier than the console's; + // DexNom/VIctory 921d8d3b, by way of + // avatarmanz/VIctory-7900XTX 9a6c829d). A length of 0 + // gives minus infinity, which the sampler clamps to + // level 0. SampleLevel takes no clamp: the instruction's + // least level is applied here. + let lod = self.unary(23, texels); + let lod = if has_cl { self.binary(35, lod, clamp) } else { lod }; + args.extend(&os); + args.push(lod); + call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered) } 63 => { let mut g = vec![fu; 6]; for k in 0..spatial { - let x = addr_u32(self, first + k)?; - g[k] = self.as_float(x); - let y = addr_u32(self, first + deriv_regs + k)?; - g[3 + k] = self.as_float(y); + let x = addr_packed(self, first, k)?; + g[k] = to_float(self, x); + let y = addr_packed(self, first + deriv_regs, k)?; + g[3 + k] = to_float(self, y); } args.extend(&os); args.extend(g); args.push(clamp); - self.s.op( - c, - "sampleGrad.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 63, - &args, - ) + call_sample(self, "sampleGrad.f32", 63, &args, &mut gathered) } 64 | 65 => { let reference = addr_u32(self, first - 1)?; @@ -7551,8 +10895,7 @@ impl<'a> Lower<'a> { } else { "sampleCmpLevelZero.f32" }; - self.s - .op(c, name, Attr::ReadOnly, self.s.t.res_ret, op, &args) + call_sample(self, name, op, &args, &mut gathered) } 62 => { let lod = if name == "image_sample_l" { @@ -7563,14 +10906,7 @@ impl<'a> Lower<'a> { }; args.extend(&os); args.push(lod); - self.s.op( - c, - "sampleLevel.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 62, - &args, - ) + call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered) } _ => { if name == "image_gather4" { @@ -7579,26 +10915,81 @@ impl<'a> Lower<'a> { if dmask.count_ones() != 1 { return Err("a gather of several channels"); } - if offset_word { - let w = addr_u32(self, 0)?; - for (k, at) in [(0, 26), (1, 18)] { - // Bits at..at+5 sign-extended: shift up, then down. - let left = self.s.m.i32(at); - let t = self.s.m.bin(c, Bin::Shl, w, left); - let k26 = self.s.m.i32(26); - os[k] = self.s.m.bin(c, Bin::AShr, t, k26); + if matches!(name, "image_gather4_l" | "image_gather4_l_o") + && coords == 2 + && spatial == 2 + { + // The host's gather has no level: it read level 0 + // where the title names one (the depth pyramid its + // occlusion tests read: most of the world was + // culled against the wrong depths). The four texels + // are read at the level instead, in the gather's + // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0). + // With an offset too (`image_gather4_l_o`): the + // offset is in texels of that level. + // The title's meshlet culling takes a 4x4 block of + // the pyramid as one gather and three offset ones + // ((2,0), (0,2), (2,2)); the three read level 0, + // two texels beside the first one's place, so a + // meshlet three or four texels wide was tested + // against a quarter of what it covers. + // shortcut: the level is rounded to a whole one and + // coordinates past the edge are clamped, whatever + // the sampler says. + let lod = addr_packed(self, coord_base, coords)?; + let lod = to_float(self, lod); + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let zero = self.s.m.f32(0); + let lod = self.binary(35, lod, zero); // maximum + let lod = self.unary(26, lod); // round to nearest + let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t); + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let half = self.s.m.f32(0.5f32.to_bits()); + let one = self.s.m.f32(1.0f32.to_bits()); + let (mut lo, mut hi) = ([iu; 2], [iu; 2]); + for k in 0..2 { + let n = self.s.m.extract(c, d, k as u32); + let n = self.s.m.cast(c, Cast::UiToFp, n, f32t); + let last = self.s.m.bin(c, Bin::Sub, n, one); + let t = self.s.m.bin(c, Bin::Mul, cs[k], n); + let t = self.s.m.bin(c, Bin::Sub, t, half); + let first = self.unary(27, t); // round down + // The offset word's field (0 without one). + let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t); + let first = self.s.m.bin(c, Bin::Add, first, by); + let next = self.s.m.bin(c, Bin::Add, first, one); + for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] { + let x = self.binary(35, x, zero); // maximum + let x = self.binary(36, x, last); // minimum + *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t); + } } + let ch = dmask.trailing_zeros(); + let mut g = [fu; 4]; + let mut read = None; + let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])]; + for (slot, (x, y)) in g.iter_mut().zip(texels) { + let r = self.s.op( + c, + "textureLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 66, + &[h, mip, x, y, iu, iu, iu, iu], + ); + *slot = self.s.m.extract(c, r, ch); + read = Some(r); + } + gathered = Some(g); + read.expect("four reads") + } else { + args.extend(&os[..2]); + args.push(self.s.m.i32(dmask.trailing_zeros())); + call_sample(self, "textureGather.f32", 73, &args, &mut gathered) } - args.extend(&os[..2]); - args.push(self.s.m.i32(dmask.trailing_zeros())); - self.s.op( - c, - "textureGather.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 73, - &args, - ) } } } else { @@ -7637,11 +11028,16 @@ impl<'a> Lower<'a> { }; let mut xs = Vec::new(); for ch in channels { - let x = self.s.m.extract(c, r, ch); + let x = match gathered { + Some(g) => g[ch as usize], + None => self.s.m.extract(c, r, ch), + }; xs.push(if *d16 { // shortcut: d16 results are taken as floats (rounded to // nearest even); integer formats would keep 16 bits. - self.f16_nearest(x) + let i32t = self.s.t.i32; + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x]) } else { self.as_int(x) }); @@ -7669,8 +11065,9 @@ impl<'a> Lower<'a> { /// The direction a cube sample's face coordinates stand for: the /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the - /// host's cube sampling turns back into the same texel. A cube array's - /// slice is taken out of `face` first (see [`Self::cube_array`]). + /// host's cube sampling turns back into the same texel. + // shortcut: the view is taken as a cube, not a cube array (whose face + // operand adds 8 × the slice). fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] { let c = self.cur; let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits()); @@ -7721,29 +11118,19 @@ impl<'a> Lower<'a> { }; let name = inst.name(); if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" { - // Console cache coherence: gl0 writes back and invalidates the - // per-CU shader L0, gl1 invalidates GL1, so one wavefront's - // writes become visible to others. D3D12 already guarantees UAV - // coherence across wavefronts and dispatches, DXIL has no - // equivalent instruction, and this project's host-visible - // writeback comes from command-stream GpuWrite ranges rather - // than shader cache hints. Ordering is kept by the surrounding - // s_waitcnt/s_barrier, which the translator does lower. + // The host has no console buffer cache to invalidate. return Ok(()); } if *lds || *tfe { return Err("a buffer access to LDS or with tfe"); } - if format.is_some() - && !name.starts_with("tbuffer_load_format_") - && !name.starts_with("tbuffer_store_format_") - { + if format.is_some() && !name.starts_with("tbuffer_load_format_") { return Err(name); } let site = (b, i); - let guard = self.guard(b, i)?; + let guard = self.effect_guard(b, i)?; let c = self.cur; - let store = name.starts_with("buffer_store_") || name.starts_with("tbuffer_store_"); + let store = name.starts_with("buffer_store_"); // DXIL atomic operations: add, and, or, xor, signed and unsigned // min and max, exchange; compare-exchange apart. let atomic = match name.strip_prefix("buffer_atomic_") { @@ -7760,6 +11147,14 @@ impl<'a> Lower<'a> { Some("cmpswap") => Some(u32::MAX), Some(_) => return Err(name), }; + // Byte and 16-bit accesses: bits, and whether a load sign-extends. + let narrow = match name { + "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)), + "buffer_load_sbyte" => Some((8, true)), + "buffer_load_ushort" | "buffer_store_short" => Some((16, false)), + "buffer_load_sshort" => Some((16, true)), + _ => None, + }; // d16: two 16-bit channels per VGPR, low half first. let d16 = name.starts_with("buffer_") && name.contains("_format_d16_"); let plain = name.replace("_format_d16_", "_format_"); @@ -7767,9 +11162,8 @@ impl<'a> Lower<'a> { .strip_prefix("buffer_load_") .or(plain.strip_prefix("buffer_store_")) .or(plain.strip_prefix("tbuffer_load_")) - .or(plain.strip_prefix("tbuffer_store_")) { - _ if atomic.is_some() => (false, 1), + _ if atomic.is_some() || narrow.is_some() => (false, 1), Some("dword") => (false, 1), Some("dwordx2") => (false, 2), Some("dwordx3") => (false, 3), @@ -7806,6 +11200,23 @@ impl<'a> Lower<'a> { .copied() .ok_or("an untracked buffer")?; let used = self.used_kind(src); + // Sixteen bits a channel through a view of a table: the bits go as + // they are, as unsigned integers, and the host is told, which shows + // the shader a 16-bit float view there as its unsigned twin + // ([`super::HostShader::half_views`]). + // A format load of whole dwords whose every use reads one half of a + // result as a half float moves 16-bit integers too (the head + // program's reads of the face network's output), where every + // access through its view does ([`Self::places_read_as_halves`]). + // A d16 access too only where every access does: a whole float + // read through the same place would see the unsigned twin. + let place = typed.then(|| self.table_place(src)).flatten().filter(|p| { + self.halves_only.contains(p) && (d16 || self.format_load_read_as_halves(inst)) + }); + let halves = place.is_some(); + if let Some(place) = place { + self.half_views.insert(place); + } let (base, extra) = self.built_offset(src)?; if base != 0 { let b = self.s.m.i32(base); @@ -7814,6 +11225,36 @@ impl<'a> Lower<'a> { if let Some(x) = extra { off = self.s.m.bin(c, Bin::Add, off, x); } + // A buffer the program picks from the view heap by an index it + // computes: no used-resource entry gives its stride, the host's + // table by heap slot does; the access becomes a raw one at the + // element's byte. (Also tells the host this shader reads such + // buffers.) + let mut index = index; + if let Some(stride) = self.slot_stride(src)? + && let Some(element) = index + && !typed + && used.is_none() + { + let at = self.s.m.bin(c, Bin::Mul, element, stride); + off = self.s.m.bin(c, Bin::Add, at, off); + index = None; + } + // A structured buffer by its used-resource entry's stride: raw + // bytes too. The host makes its buffer views raw (a raw read + // through a structured view gives zeros on NVIDIA), and one kind + // of view can then serve every shader that reads the buffer. + if let (Some(element), Some(u)) = (index, used) + && !typed + && u.kind != ResourceType::Cbv + && u.stride >= 4 + && u.stride.is_multiple_of(4) + { + let k = self.s.m.i32(u.stride); + let at = self.s.m.bin(c, Bin::Mul, element, k); + off = self.s.m.bin(c, Bin::Add, at, off); + index = None; + } if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed { // A constant buffer read per lane (a dynamically indexed array). // shortcut: the console's CBV descriptor is taken to have a 16-byte @@ -7830,40 +11271,115 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = *data else { return Err("a buffer result"); }; - let size = self.root_view_size(src); for k in 0..count { let four = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, byte, four); - let (a, ok) = match size { - Some(size) => { - let (ok, a) = self.in_root_view(size, a, 4); - (a, Some(ok)) - } - None => (a, None), - }; let x = self.cbuffer_dword(h, a); - let x = self.zero_unless(ok, x); self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); } - let u = self.uav_bits(src, used) | if store || atomic.is_some() { 0x1000 } else { 0 }; - let uav = u & 0x1000 != 0; + let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; let iu = self.s.m.undef(self.s.t.i32); - // Root views: the bytes accessed checked against the view's size - // (raw accesses, and the raw loads formatted ones make). - let (off, root_ok) = match self.root_view_size(src) { - Some(size) if !typed || format.is_some() => { - let bytes = if format.is_some() { 16 } else { 4 * count }; - let (ok, at) = self.in_root_view(size, off, bytes); - (at, Some(ok)) + if let Some((bits, signed)) = narrow { + // Below a dword: raw buffers are read and written in dwords on + // 4 bytes, so the dword that holds the value is read and + // shifted, or changed with two atomic operations that touch + // only the value's own bits (other lanes may write the rest of + // the dword at the same time). A 16-bit value at a dword's + // last byte continues in the next dword. + let byte = match index { + None => off, + Some(index) if used.is_some_and(|u| u.stride == 1) => { + self.s.m.bin(c, Bin::Add, index, off) + } + Some(_) => return Err("a byte or 16-bit buffer access by index"), + }; + let h = self.handle(site, src, false, (11 | u, 0))?; + let k3 = self.s.m.i32(3); + let within = self.s.m.bin(c, Bin::And, byte, k3); + let aligned = self.s.m.bin(c, Bin::Sub, byte, within); + let shift = self.s.m.bin(c, Bin::Shl, within, k3); + let four = self.s.m.i32(4); + let next = self.s.m.bin(c, Bin::Add, aligned, four); + let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff }); + let zero = self.s.m.i32(0); + let k8 = self.s.m.i32(8); + let straddles = self.s.m.cmp(c, pred::EQ, within, k3); + if !store { + let mask = self.s.m.i8(1); + let align = self.s.m.i32(4); + let dword = |l: &mut Self, at: V| { + let r = l.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + l.s.t.res_ret, + 139, + &[h, at, iu, mask, align], + ); + let f = l.s.m.extract(c, r, 0); + l.as_int(f) + }; + let low = dword(self, aligned); + let mut x = self.s.m.bin(c, Bin::LShr, low, shift); + if bits == 16 { + let high = dword(self, next); + let high = self.s.m.bin(c, Bin::Shl, high, k8); + let high = self.s.m.select(c, straddles, high, zero); + x = self.s.m.bin(c, Bin::Or, x, high); + } + x = self.s.m.bin(c, Bin::And, x, ones); + if signed { + let up = self.s.m.i32(32 - bits); + x = self.s.m.bin(c, Bin::Shl, x, up); + x = self.s.m.bin(c, Bin::AShr, x, up); + } + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + self.write(inst, Reg::V(reg), x, guard); + return Ok(()); } - _ => (off, None), - }; + let d = data.as_ref().ok_or("buffer store data")?; + let v = self.vgprs(inst, d, 1)?[0]; + let v = self.s.m.bin(c, Bin::And, v, ones); + let all = self.s.m.i32(u32::MAX); + let clear = self.s.m.bin(c, Bin::Shl, ones, shift); + let keep = self.s.m.bin(c, Bin::Xor, clear, all); + let set = self.s.m.bin(c, Bin::Shl, v, shift); + let keep_next = self.s.m.i32(0xffff_ff00); + let set_next = self.s.m.bin(c, Bin::LShr, v, k8); + let (and, or) = (self.s.m.i32(1), self.s.m.i32(2)); + let i32t = self.s.t.i32; + let at = self.begin_guarded(guard); + for (op, x) in [(and, keep), (or, set)] { + let args = [h, op, aligned, iu, iu, x]; + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args); + } + if bits == 16 { + let second = self.begin_guarded(Some(straddles)); + for (op, x) in [(and, keep_next), (or, set_next)] { + let args = [h, op, next, iu, iu, x]; + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args); + } + self.end_guarded(second, &[]); + } + self.end_guarded(at, &[]); + return Ok(()); + } if let Some(op) = atomic { let d = data.as_ref().ok_or("buffer atomic data")?; let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?; let (h, coords) = match index { + // A raw buffer (stride 1) read by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu]) + } Some(index) => { let stride = used.map_or(0, |u| u.stride); if stride < 4 || !stride.is_multiple_of(4) { @@ -7882,8 +11398,7 @@ impl<'a> Lower<'a> { Some(v) if returns => self.i32_of(v)?, _ => self.s.m.i32(0), }; - let access = self.narrow(guard, root_ok); - let at = self.begin_guarded(access); + let at = self.begin_guarded(guard); let i32t = self.s.t.i32; let r = if op == u32::MAX { // cmpswap: data is (new, compare). @@ -7911,38 +11426,21 @@ impl<'a> Lower<'a> { } return Ok(()); } - if let (true, Some(f)) = (store, *format) { - if index.is_some() { - return Err("a typed-format store by index"); - } - let words = self.format_store_words(inst, data.as_ref(), f, count)?; - let iu = self.s.m.undef(self.s.t.i32); - let mut args = vec![self.handle(site, src, false, (11 | u, 0))?, off, iu]; - let n = words.len(); - args.extend(words); - args.resize(3 + 4, iu); - args.push(self.s.m.i8((1u8 << n) - 1)); - args.push(self.s.m.i32(4)); - let at = self.begin_guarded(guard); - let void = self.s.t.void; - self.s.op( - self.cur, - "rawBufferStore.i32", - Attr::NoUnwind, - void, - 140, - &args, - ); - self.end_guarded(at, &[]); - return Ok(()); - } if store { let regs = if d16 { count.div_ceil(2) } else { count }; let mut vals = self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?; if d16 { - // shortcut: d16 data is taken as f16 (integer formats would - // keep 16 bits), widened for the 32-bit float store. + // Through a view of a table each half is stored as it is + // (`halves`). Reached another way: + // d16 data is taken as f16, widened for the 32-bit float + // store; through a view of an integer format it is a 16-bit + // integer, zero- or sign-extended (VIctory 4243a96a: the face + // network keeps its halves in UINT views; its output was + // noise: faces deformed). Heap and table views both + // (avatarmanz 9a6c829d; codec_d, cool_fox f4b48ad); the + // handle stays a float one, whose bits the drivers pass. + let integer = if typed && !halves { self.integer_view(src)? } else { None }; let mut wide = Vec::new(); for k in 0..count { let mut x = vals[(k / 2) as usize]; @@ -7950,11 +11448,25 @@ impl<'a> Lower<'a> { let k16 = self.s.m.i32(16); x = self.s.m.bin(c, Bin::LShr, x, k16); } + if halves { + let low = self.s.m.i32(0xffff); + wide.push(self.s.m.bin(c, Bin::And, x, low)); + continue; + } let f32t = self.s.t.f32; let f = self .s .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); - wide.push(self.as_int(f)); + let mut w = self.as_int(f); + if let Some((int, signed)) = integer { + let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF)); + let zero_ext = self.s.m.bin(c, Bin::And, x, low); + let up = self.s.m.bin(c, Bin::Shl, x, k16); + let sign_ext = self.s.m.bin(c, Bin::AShr, up, k16); + let n = self.s.m.select(c, signed, sign_ext, zero_ext); + w = self.s.m.select(c, int, n, w); + } + wide.push(w); } vals = wide; } @@ -7965,14 +11477,29 @@ impl<'a> Lower<'a> { if count != 4 || *offen || *offset != 0 { return Err("a typed buffer store of some channels or at an offset"); } - args.push(self.handle(site, src, false, (10 | u, 0x409))?); + // Four unsigned integers for halves, four floats otherwise. + let component = if halves { 0x405 } else { 0x409 }; + args.push(self.handle(site, src, false, (10 | u, component))?); args.extend([index.unwrap_or(self.s.m.i32(0)), iu]); for x in vals { - args.push(self.as_float(x)); + args.push(if halves { x } else { self.as_float(x) }); } - (69, "bufferStore.f32") + ( + 69, + if halves { + "bufferStore.i32" + } else { + "bufferStore.f32" + }, + ) } else { match index { + // A raw buffer (stride 1) written by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + args.push(self.handle(site, src, false, (11 | u, 0))?); + args.extend([byte, iu]); + } Some(index) => { let stride = used.map_or(0, |u| u.stride); if stride < 4 || !stride.is_multiple_of(4) { @@ -7994,8 +11521,7 @@ impl<'a> Lower<'a> { if !typed { args.push(self.s.m.i32(4)); } - let access = self.narrow(guard, root_ok); - let at = self.begin_guarded(access); + let at = self.begin_guarded(guard); let void = self.s.t.void; self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args); self.end_guarded(at, &[]); @@ -8010,7 +11536,6 @@ impl<'a> Lower<'a> { return Err("a buffer result"); }; for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() { - let x = self.zero_unless(root_ok, x); self.write(inst, Reg::V(reg + k as u8), x, guard); } return Ok(()); @@ -8022,20 +11547,47 @@ impl<'a> Lower<'a> { if uav { self.s.flags |= flags::TYPED_UAV_LOADS; } - let h = self.handle(site, src, false, (10 | u, 0x409))?; let index = index.unwrap_or(self.s.m.i32(0)); - self.s.op( - c, - "bufferLoad.f32", - Attr::ReadOnly, - self.s.t.res_ret, - 68, - &[h, index, iu], - ) + if halves { + let h = self.handle(site, src, false, (10 | u, 0x405))?; + let i32t = self.s.t.i32; + let ret = self.s.m.named_struct("dx.types.ResRet.i32", vec![i32t; 5]); + self.s.op( + c, + "bufferLoad.i32", + Attr::ReadOnly, + ret, + 68, + &[h, index, iu], + ) + } else { + let h = self.handle(site, src, false, (10 | u, 0x409))?; + self.s.op( + c, + "bufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 68, + &[h, index, iu], + ) + } } else { let mask = self.s.m.i8((1u8 << count) - 1); let align = self.s.m.i32(4); match index { + // A raw buffer (stride 1) read by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + let h = self.handle(site, src, false, (11 | u, 0))?; + self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, align], + ) + } Some(index) => { let stride = used.map_or(0, |u| u.stride); if stride < 4 || !stride.is_multiple_of(4) { @@ -8068,13 +11620,30 @@ impl<'a> Lower<'a> { return Err("a buffer result"); }; if d16 { - // Two f16 channels per VGPR (an odd last high half 0). + // Two f16 channels per VGPR (an odd last high half 0); through + // a view of a table, the 16 bits of each as they are. + let integer = if typed && !halves { self.integer_view(src)? } else { None }; let k16 = self.s.m.i32(16); + let i32t = self.s.t.i32; for k in 0..count.div_ceil(2) { let mut x = None; for ch in (2 * k..(2 * k + 2).min(count)).rev() { let f = self.s.m.extract(c, r, ch); - let h = self.f16_nearest(f); + let h = if halves { + let low = self.s.m.i32(0xffff); + self.s.m.bin(c, Bin::And, f, low) + } else { + let mut h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + if let Some((int, _)) = integer { + let bits = self.as_int(f); + let low = self.s.m.i32(0xFFFF); + let low = self.s.m.bin(c, Bin::And, bits, low); + h = self.s.m.select(c, int, low, h); + } + h + }; x = Some(match x { Some(hi) => { let hi = self.s.m.bin(c, Bin::Shl, hi, k16); @@ -8089,8 +11658,8 @@ impl<'a> Lower<'a> { } for k in 0..count { let x = self.s.m.extract(c, r, k); - let x = self.as_int(x); - let x = self.zero_unless(root_ok, x); + // (Integers already where the load moved halves.) + let x = if halves { x } else { self.as_int(x) }; self.write(inst, Reg::V(reg + k as u8), x, guard); } Ok(()) @@ -8101,33 +11670,23 @@ impl<'a> Lower<'a> { .exports .get(&(b, i)) .ok_or("an export I/O raising did not see")?; - // Two f16 channels per source dword: only the pixel color and - // depth targets unpack them; the rest stay refused. - if e.compressed && !matches!(e.target, Target::Color(_) | Target::Depth) { + if e.compressed { return Err("a compressed export"); } - let mut guard = self.guard(b, i)?; + let guard = self.guard(b, i)?; let mesh = self.s.mesh.is_some(); - let pixel_done = self.s.pixel && e.done; let c = self.cur; if let Some(g) = guard && !mesh - && pixel_done { + if !(e.done && self.s.pixel) { + return Err("a conditional export"); + } let t = self.s.m.bool(true); let kill = self.s.m.bin(c, Bin::Xor, g, t); self.s .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]); } - // A console group can have more lanes than the mesh declares - // outputs; a host write past the declared count is undefined. - if let Some(m) = self.s.mesh { - let max = match e.target { - Target::Primitive | Target::PrimitiveParam { .. } => m.max_primitives, - _ => m.max_vertices, - }; - guard = self.mesh_output_guard(guard, max); - } if mesh && e.target == Target::Primitive { return self.emit_indices(e, guard); } @@ -8155,7 +11714,13 @@ impl<'a> Lower<'a> { } _ => None, }; - if let Some((row, (pack2, b))) = halves { + if let Some((row, (pack2, _))) = halves { + let packs: Vec<(u8, Option<u8>)> = self + .half_outputs + .iter() + .filter(|(_, h)| h.0) + .map(|(&r, h)| (r, h.1)) + .collect(); for ch in 0..4u8 { let Some(value) = e.values[usize::from(ch)] else { continue; @@ -8163,7 +11728,7 @@ impl<'a> Lower<'a> { for high in [false, true] { let h = 2 * ch + u8::from(high); let src = if pack2 { - packed_half(outputs, row, b, h) + packed_half(outputs, &packs, row, h) } else { (!high).then_some((row, ch)) }; @@ -8237,9 +11802,7 @@ impl<'a> Lower<'a> { Target::Primitive => return Err("a primitive export"), }; if let Some((id, col)) = found { - // Two f16 channels per dword: an odd channel the high half. - let half = e.compressed.then_some(ch % 2 == 1); - stores.push((id, col, value, half)); + stores.push((id, col, value, None)); } } fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> { @@ -8256,10 +11819,29 @@ impl<'a> Lower<'a> { return Err("a 16-bit output the stage data does not mark"); } // A mesh lane writes its own vertex or primitive, where it exports. - // Other conditional exports also run only for their enabled lanes; - // a pixel's final `done` export instead discards the other lanes. - let at = if mesh || !pixel_done { - self.begin_guarded(guard) + let at = if mesh { + let flat = self.mesh_thread(); + let limit = if let Some(m) = self.s.mesh { + if primitive { + m.max_primitives + } else { + m.max_vertices + } + } else { + 0 + }; + let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX); + let mesh_guard = if limit > 0 && threads > limit { + let lim = self.s.m.i32(limit); + let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim); + match guard { + Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)), + None => Some(in_bounds), + } + } else { + guard + }; + self.begin_guarded(mesh_guard) } else { None }; @@ -8268,6 +11850,8 @@ impl<'a> Lower<'a> { (true, false) => ("storeVertexOutput", 171), (true, true) => ("storePrimitiveOutput", 172), }; + // A colour a pixel shader writes (`VICTORY_NAN_SCRUB`). + let colour = self.s.pixel && matches!(e.target, Target::Color(_)); for (id, col, value, half) in stores { let mut x = self.i32_of(value)?; if let Some(high) = half { @@ -8286,12 +11870,20 @@ impl<'a> Lower<'a> { let el = &mut elements(self, primitive)[id]; el.usage |= 1 << col; let (suffix, x) = match el.comp { - 9 if half.is_some() => (".f32", self.as_float(x)), + 9 if half.is_some() => { + let f = self.as_float(x); + (".f32", if colour { self.scrub_nan(f) } else { f }) + } 9 => { let f = match self.floats.get(&value) { Some(&f) => f, None => self.as_float(x), }; + // `VICTORY_NAN_SCRUB=1`: a colour a pixel shader writes + // is 0 where it is NaN or infinite, so one bad value + // does not spread through the title's blur and temporal + // passes. + let f = if colour { self.scrub_nan(f) } else { f }; (".f32", f) } _ => (".i32", x), @@ -8319,54 +11911,55 @@ impl<'a> Lower<'a> { Ok(()) } - /// Keeps a mesh lane from writing past the output count the host - /// shader declares (`max`), when the console group has more lanes. - fn mesh_output_guard(&mut self, guard: Option<V>, max: u32) -> Option<V> { - let lanes = self.s.threads.map_or(u32::MAX, |t| t[0]); - if lanes <= max { - return guard; - } - let lane = self.mesh_thread(); - let limit = self.s.m.i32(max); - let within = self.s.m.cmp(self.cur, pred::IULT, lane, limit); - Some(match guard { - Some(guard) => self.s.m.bin(self.cur, Bin::And, guard, within), - None => within, - }) - } - /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all - /// indices 0: no area), and so does an index at or past the declared - /// vertex count: the console's 10-bit fields reach 1023, and an index - /// outside the mesh outputs is undefined on the host (an NVIDIA driver - /// was seen to hang on such a draw). + /// indices 0: no area). fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> { let v = e.values[0].ok_or("a primitive export without its indices")?; let x = self.i32_of(v)?; - let max_vertices = self - .s - .mesh - .ok_or("a primitive export outside a mesh shader")? - .max_vertices; + let flat = self.mesh_thread(); + let guard = if let Some(mesh) = self.s.mesh { + let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX); + if threads > mesh.max_primitives { + let p = self.s.m.i32(mesh.max_primitives); + let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p); + match guard { + Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)), + None => Some(in_bounds), + } + } else { + guard + } + } else { + guard + }; let at = self.begin_guarded(guard); let c = self.cur; let z = self.s.m.i32(0); - let limit = self.s.m.i32(max_vertices); let mut culled = self.s.m.cmp(c, pred::SLT, x, z); - let mut indices = Vec::with_capacity(3); - for k in 0..3 { - let (shift, mask) = (self.s.m.i32(10 * k), self.s.m.i32(0x3FF)); + // A primitive that names a vertex past the declared count, or one + // no lane writes (lane n writes vertex n alone), is culled too: the + // host would read a vertex nothing set, at any position. + let written = self.s.mesh.map(|m| { + m.max_vertices + .min(self.s.threads.map_or(u32::MAX, |t| t[0])) + }); + let mut indices = [z; 3]; + // Each corner is a 9-bit vertex index with its edge flag above it + // (bits 9, 19, 29), which only the console's edge-flag rasterising + // reads: with the flag in the index it named a vertex past the + // written ones, and the triangle was culled. + for (k, slot) in indices.iter_mut().enumerate() { + let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x1FF)); let i = self.s.m.bin(c, Bin::LShr, x, shift); let i = self.s.m.bin(c, Bin::And, i, mask); - let outside = self.s.m.cmp(c, pred::IUGE, i, limit); - culled = self.s.m.bin(c, Bin::Or, culled, outside); - indices.push(i); - } - #[cfg(test)] - { - self.s.bounded_prims += 1; + if let Some(n) = written { + let n = self.s.m.i32(n); + let past = self.s.m.cmp(c, pred::IUGE, i, n); + culled = self.s.m.bin(c, Bin::Or, culled, past); + } + *slot = i; } - let mut args = vec![self.mesh_thread()]; + let mut args = vec![flat]; for i in indices { args.push(self.s.m.select(c, culled, z, i)); } @@ -8424,6 +12017,10 @@ impl<'a> Lower<'a> { } => { // A negated condition branches the other way round. let (cond, taken, not_taken) = match self.x.st.bools.node(when) { + _ if self.x.st.wide.contains(&b) => { + let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?; + (c, taken, not_taken) + } Some((atom, Bool::TRUE, Bool::FALSE)) => { let a = self .atom(atom, self.cur) @@ -8474,7 +12071,7 @@ impl<'a> Lower<'a> { self.s .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); } - Term::Br(self.ret_block()) + Term::Ret } LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")), }; @@ -8500,14 +12097,24 @@ impl<'a> Lower<'a> { let (phi, _) = self.counters[&to]; let one = self.s.m.i32(1); let next = self.s.m.bin(c, Bin::Add, phi, one); - let limit = if self.spin.contains(&to) { - #[cfg(test)] - { - self.spun += 1; - } - super::spin_limit() - } else { - super::loop_limit() + self.s.m.tag(phi, Tag::Counter); + self.s.m.tag(next, Tag::Counter); + // Per stage unless the switch names one: a loop that never meets its + // exit (a count read from a buffer the host has not got yet, say) + // runs to the limit in every lane. A million iterations a pixel + // hung the GPU for seconds a draw until Windows reset it + // (PS_Textured_Eight, 2026-11-24, run 12). + // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop + // past 256 or a compute loop past 4,096 is cut short. (They were + // 1,024, 4,096 and 65,536: the opening cutscene then lost the card + // 14-25 frames in, in a minimap or shadow mesh draw; with every + // loop cut at 64 it ran 90 frames. Raise them again once shaders + // stop reading data that is not there yet.) + let limit = match super::loop_limit() { + LOOP_LIMIT if self.s.pixel => 1 << 7, + LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8, + LOOP_LIMIT => 1 << 12, + named => named, }; let limit = self.s.m.i32(limit); self.counters @@ -8515,7 +12122,9 @@ impl<'a> Lower<'a> { .expect("header") .1 .push((next, c)); - self.s.m.cmp(c, p, next, limit) + let over = self.s.m.cmp(c, p, next, limit); + self.s.m.tag(over, Tag::Counter); + over } /// The block a lane stopped by [`LOOP_LIMIT`] leaves through. @@ -8529,23 +12138,11 @@ impl<'a> Lower<'a> { self.s .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); } - let r = self.ret_block(); - self.s.m.terminate(a, Term::Br(r)); + self.s.m.terminate(a, Term::Ret); self.abort = Some(a); a } - /// The function's single returning block (see `ret`). - fn ret_block(&mut self) -> usize { - if let Some(r) = self.ret { - return r; - } - let r = self.s.m.new_block(); - self.s.m.terminate(r, Term::Ret); - self.ret = Some(r); - r - } - /// The DXIL block a branch from IR block `from` to `to` goes to. fn edge(&mut self, from: usize, to: usize) -> usize { let target = self.block[to].expect("reachable"); @@ -8564,126 +12161,141 @@ impl<'a> Lower<'a> { e } - /// A dword a scalar load writes, where the load is a descriptor the - /// program uses as a resource or sampler. - fn descriptor_dword(&self, v: Value) -> bool { - let Some(load) = self.x.p.blocks.iter().enumerate().find_map(|(b, block)| { - block - .insts - .iter() - .position(|i| i.writes.iter().any(|w| w.1 == v)) - .map(|i| (b, i)) - }) else { - return false; - }; - self.x.p.blocks[load.0].insts[load.1] - .name() - .starts_with("s_load_dword") - && self.x.res.descriptors.iter().any(|d| { - d.source - .leaves() - .iter() - .any(|l| matches!(l, Source::Loaded { load: at, .. } if *at == load)) - }) - } - - /// The phis a read phi takes a value from, through any number of joins, - /// that no instruction reads directly. A read only marks the phi it - /// takes the value from, so a join feeding another join looks unread. - fn phis_read_through_joins(&self) -> HashSet<Value> { + fn fill_phis(&mut self) -> Result<(), Stop> { let p = self.x.p; - let mut through = HashSet::new(); - let mut queue: Vec<Value> = self.read_phis.iter().copied().collect(); - while let Some(v) = queue.pop() { + // Lane-mask joins first (what an edge brings may ask for more joins, + // of masks and of numbers): each edge's mask as the structure + // tracked it, a constant or a scalar-built one included. + let st = self.x.st; + while let Some((v, b, i)) = self.pending_masks.pop() { + let phi = &p.blocks[b].phis[i]; + let offset = p.blocks[b].offset; + let args = st + .phi_masks + .get(&phi.value) + .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?; + let mut incoming = Vec::new(); + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + let Some(qb) = self.tail[q] else { continue }; + let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); + let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?; + incoming.push((x, qb)); + } + self.s.m.set_phi(v, incoming); + } + // A join that only another join reads is read wherever that one is. Left + // unmarked, a value without a DXIL form coming into it became zero without a + // word (the looked-up tint of the material resolve programs, whose size + // computation had no value, was zero in every lane that way). + // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack + // listing sets it to count them): 40 programs that translate today + // stop by name with it (vehicle paint pixel shaders at "the first + // half of an interpolation", foliage mesh shaders); until those are + // lowered they keep drawing with that zero. + static STRICT: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some()); + let mut work: Vec<Value> = if strict { + self.read_phis.iter().copied().collect() + } else { + Vec::new() + }; + while let Some(v) = work.pop() { let Some(&(b, i)) = self.phi_at.get(&v) else { continue; }; - for &arg in &p.blocks[b].phis[i].args { - if self.phi_at.contains_key(&arg) - && !self.read_phis.contains(&arg) - && through.insert(arg) - { - queue.push(arg); + for &a in &p.blocks[b].phis[i].args { + if self.phi_at.contains_key(&a) && self.read_phis.insert(a) { + work.push(a); } } } - through - } - - /// Whether `v` is a value zero would silently misrepresent if it - /// reached a read through joins: a timestamp, which counts up and - /// which titles compare and subtract. Other missing values that only - /// joins carry (descriptor dwords, lane masks, interpolation halves...) - /// are mostly registers reused after their last use, and keep becoming - /// zero there: refusing them stopped hundreds of programs that - /// translated and validated before (upstream #736). - fn zero_is_wrong(&self, v: Value) -> bool { - self.writer(v) - .is_some_and(|i| matches!(i.name(), "s_memtime" | "s_memrealtime")) - } - - fn fill_phis(&mut self) -> Result<(), Stop> { - // A phi read only through another phi is as live as its reader: a - // timestamp it carries stays missing (see `zero_is_wrong`). - let through = self.phis_read_through_joins(); - let p = self.x.p; for (v, b, i) in std::mem::take(&mut self.data_phis) { let phi = &p.blocks[b].phis[i]; let bit = phi.reg == Reg::Scc; + // A join of numbers with dead registers (`dead`): the paths that bring those + // never read the result, so they bring zero. Not for a join that is itself a + // lane mask (a ballot gives that one as data). + let st = self.x.st; + let numbers = !bit + && !st.masks.contains_key(&phi.value) + && !st.highs.contains_key(&phi.value) + && phi + .args + .iter() + .any(|a| matches!(self.vals.get(a), Some(Val::I32(_)))); let mut incoming = Vec::new(); for (n, &q) in p.blocks[b].preds.iter().enumerate() { let Some(qb) = self.tail[q] else { continue }; let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); let arg = phi.args[n]; - // A mask dword the other path left in the register: its - // ballot (a pixel or vertex program reads such a join only - // through a zero test or a count, the same on any wave size). - // shortcut: the ballot is the host wave's, so a join read - // some other way would differ from the console. - let val = self.vals.get(&arg).copied(); - let lo = self.x.st.highs.get(&arg).copied().unwrap_or(arg); - let ballot = if self.mask_data == MaskData::Host - && !bit - && matches!(val, None | Some(Val::Missing(_))) - && self.read_phis.contains(&phi.value) - && self.x.st.masks.contains_key(&lo) - && self.def_block.get(&lo).is_some_and(|&d| d != self.cur_ir) - { - self.mask_dword(arg).ok() - } else { - None - }; - let x = if let Some(x) = ballot { - x - } else { - match (val, bit) { - (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, - (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { - return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); + if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) { + let _ = self.lazy_barycentric(arg); + // A root parameter nothing read before the join (user + // data is loaded on first use, in the entry block). + if !self.vals.contains_key(&arg) + && let Some(&(param, dword)) = self.params.get(&arg) + { + let val = self.user(param, dword); + self.vals.insert(arg, val); + } + } + let x = match (self.vals.get(&arg).copied(), bit) { + (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, + (Some(Val::Missing(_)) | None, false) + if numbers && self.dead(arg, &mut Vec::new()) => + { + self.s.m.i32(0) + } + // A lane mask joined with numbers (a traversal that keeps its lanes' masks on + // a stack with its node numbers): the mask comes as the number it is, the + // ballot of its lanes where it is written. + (Some(Val::Missing(_)) | None, false) + if self.read_phis.contains(&phi.value) + && self.mask_data == MaskData::Console + && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) => + { + match self.mask_dword(arg) { + Ok(x) => x, + Err(why) => return Err(Stop::Retry(phi.value, why)), } - // A descriptor's dwords reaching a join that also takes - // data (the registers are reused after the last access). - // shortcut: undefined on that edge, assuming the program - // reads the joined value only after the data edge. - (Some(Val::Missing(_)), _) if self.descriptor_dword(arg) => { - if bit { - self.s.m.undef(self.s.t.i1) - } else { - self.s.m.undef(self.s.t.i32) + } + // SCC of a mask operation ("some lane is left") joined with a scalar test: + // the compiler branches around code that sets SCC and tests SCC after it, + // the skip bringing "no lane" along. As data it is "some lane of the wave + // has the bit" - right only if the wave took that skip together, as the + // console does: a lane that skipped alone would bring "some lane" where the + // console has the skipped code's SCC. So the branch must be one the wave + // takes together; else its region is named for `emit`'s retry to widen it. + (Some(Val::Missing(_)) | None, true) + if self.read_phis.contains(&phi.value) + && self.mask_data == MaskData::Console + && st.scc_some.contains_key(&arg) => + { + let per_lane = !st.wide.contains(&q) + && matches!(st.exits[q], LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_)))); + if per_lane { + for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) { + need(other); } + return Err(Stop::Retry(phi.value, LANE_MASK)); } - (Some(Val::Missing(why)), _) - if self.read_phis.contains(&phi.value) - || through.contains(&phi.value) && self.zero_is_wrong(arg) => - { - return Err(Stop::Retry(phi.value, why)); - } - _ if self.read_phis.contains(&phi.value) => { - return Err(Stop::Retry(phi.value, "a join of mismatched values")); + match self.scc_some(arg) { + Ok(x) => x, + Err(why) => return Err(Stop::Retry(phi.value, why)), } - _ if bit => self.s.m.bool(false), - _ => self.s.m.i32(0), } + (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); + } + (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, why)); + } + _ if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, "a join of mismatched values")); + } + _ if bit => self.s.m.bool(false), + _ => self.s.m.i32(0), }; incoming.push((x, qb)); } @@ -8692,1389 +12304,24 @@ impl<'a> Lower<'a> { for (phi, incoming) in std::mem::take(&mut self.counters).into_values() { self.s.m.set_phi(phi, incoming); } - while let Some((v, b, i)) = self.pending_masks.pop() { - let phi = &p.blocks[b].phis[i]; - let offset = p.blocks[b].offset; - let mut incoming = Vec::new(); - for (n, &q) in p.blocks[b].preds.iter().enumerate() { - let Some(qb) = self.tail[q] else { continue }; - let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); - let m = - *self.x.st.masks.get(&phi.args[n]).ok_or_else(|| { - unsupported(offset, "a lane-mask join of an untracked mask") - })?; - let x = self.boolean(m, qb).map_err(|w| unsupported(offset, w))?; - incoming.push((x, qb)); - } - self.s.m.set_phi(v, incoming); - } Ok(()) } } -#[cfg(test)] -mod tests { - use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; - use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, - }; - use crate::{io, ir, resource, structure}; - - const S_ENDPGM: u32 = 0xBF81_0000; - - /// Lowers a compute program of constants and returns the lowered result. - fn lower_words(words: &[u32]) -> Result<super::Lowered, crate::ShaderError> { - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 0, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); - let io = io::raise(&p, &native).unwrap(); - let st = structure::structure(&p).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - host_wave64: true, - }) - } - - /// Lowers a compute program of constants: whether it translates. - fn lowers(words: &[u32]) -> Result<(), crate::ShaderError> { - lower_words(words).map(|_| ()) - } - - /// image_sample_d_cl and image_gather4_l translate (upstream #694: - /// #293, #653), with the image table in user data 8, the sampler's in 9. - #[test] - fn image_sample_d_cl_and_gather4_l_translate() { - use crate::native::{RootParam, RootType}; - let param = |user_data: u8| RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data, - slot: 0, - }; - let run = |image: [u32; 2]| { - let words = [ - 0xBE82_0309, // s_mov_b32 s2, s9 - 0xBE89_0380, // s_mov_b32 s9, 0 - 0xBE83_0380, // s_mov_b32 s3, 0 - 0xF408_0204, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[8:9], null - 0xF40C_0001, - 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null - image[0], - image[1], - S_ENDPGM, - ]; - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![param(8), param(9)], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 0, - threads: [1, 1, 1], - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - host_wave64: true, - }) - .map(|_| ()) - }; - // image_sample_d_cl v[0:3], v[2:8], s[0:7], s[8:11] - run([0xF08C_0F08, 0x0040_0002]).unwrap(); - // image_gather4_l v[0:3], v[2:4], s[0:7], s[8:11] - run([0xF110_0108, 0x0040_0002]).unwrap(); - } - - #[test] - fn med3_f32_tests_nan_on_bits_not_a_float_compare() { - // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) - let src0 = 256 + 1u32; - let src1 = 256 + 2u32; - let src2 = 256 + 3u32; - let words = [ - 0x35 << 26 | (0x157u32 << 16), - src0 | (src1 << 9) | (src2 << 18), - S_ENDPGM, - ]; - let lowered = lower_words(&words).unwrap(); - assert!( - lowered.has_iugt, - "v_med3_f32 must test NaN as |bits| > +inf, unsigned" - ); - assert!( - !lowered.has_fcmp_uno && !lowered.has_isnan_op, - "v_med3_f32 must not test NaN with floats (folded away by drivers, #726, #745)" - ); - } - - #[test] - fn a_missing_value_stays_missing_through_two_live_joins() { - /// Whether the compute program translates with the group-id SGPRs - /// enabled (`rsrc2 = 3 << 7`). - fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); - let io = io::raise(&p, &native).unwrap(); - let st = structure::structure(&p).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - host_wave64: true, - }) - .map(|_| ()) - } - let mut words = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) - 0xBF85_0001, // skip the first overwrite - 0xBE86_0380, // s_mov_b32 s6, 0 - 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) - 0xBF85_0001, // skip the second overwrite - 0xBE86_0381, // s_mov_b32 s6, 1 - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, // use the result to branch - 0xBE83_0380, - S_ENDPGM, - ]; - let group_ids_xy = 3 << 7; - // Compare to a read with no joins, so the two agree. - let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { - Ok(()) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - let direct = [&words[..2], &words[8..]].concat(); - assert_eq!(refusal(&words), refusal(&direct)); - words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead - lowers(&words, group_ids_xy).expect("dead timestamp"); - // Other values with no DXIL form that only joins carry still become - // zero there, as before (refusing them stopped hundreds of programs - // that translated, upstream #736): only a direct read refuses. - words[8] = 0xBF07_8006; // read s6 again - words[0..2].copy_from_slice(&[0xBE86_1F00, 0xBF80_0000]); // s_getpc_b64 s[6:7]; s_nop - let direct = [&words[..2], &words[8..]].concat(); - assert!(refusal(&direct).is_some(), "s_getpc_b64 read as data"); - assert_eq!(refusal(&words), None); - } - - /// The props of the heap handles of a compute program whose s4 holds - /// the resource heap's address. - fn heap_props(words: &[u32]) -> Vec<(u32, u32)> { - heap_lower(words).unwrap().handle_props - } - - /// Lowers a compute program with a resource heap at s4. - fn heap_lower(words: &[u32]) -> Result<super::Lowered, crate::ShaderError> { - use crate::native::{RootParam, RootType}; - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![RootParam { - root: RootType::ResourceHeap, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 0, - }], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - host_wave64: true, - }) - } - - #[test] - fn compute_samples_with_implicit_levels_keep_console_lanes() { - // Outside pixel shaders these take their level from each quad of - // console lanes (`quad_gradients`), whatever the clamp or offset. - let head: [u32; 11] = [ - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF40C_0202, - 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0 - 0xF408_0502, - 0xFA00_0020, // s_load_dwordx4 s[20:23], s[4:5], 32 - 0xBE90_0380, // s_mov_b32 s16, 0 - 0xBE91_0380, // s_mov_b32 s17, 0 - 0xBE92_0380, // s_mov_b32 s18, 0 - 0xBE93_0380, // s_mov_b32 s19, 0 - 0x7E02_0280, // v_mov_b32 v1, 0 - 0x7E04_0280, // v_mov_b32 v2, 0 - ]; - let regs: [u32; 2] = [ - 0x7E06_0280, // v_mov_b32 v3, 0 - 0x7E08_0280, // v_mov_b32 v4, 0 - ]; - for (name, word) in [ - ("image_sample", 0xF080_0108), - ("image_sample_cl", 0xF084_0108), - ("image_sample_b", 0xF094_0108), - ("image_sample_b_cl", 0xF098_0108), - ("image_sample_o", 0xF0C0_0108), - ] { - let tail: [u32; 5] = [ - word, - 0x0082_0501, // <name> v5, v[1:], s[8:15], s[16:19] dmask:1 dim:2D - 0xE070_0000, - 0x8005_0500, // buffer_store_dword v5, off, s[20:23] - S_ENDPGM, - ]; - let words = [&head[..], ®s[..], &tail[..]].concat(); - if let Err(e) = heap_lower(&words) { - panic!("{name}: {e}"); - } - } - } - - #[test] - fn a_sample_with_constant_offsets_takes_them_as_immediates() { - // An image (heap view 0), a buffer (view 1), an immediate sampler, - // s = t = 1.5; then the offsets in v1, an image_sample_o of them and - // a store of the result (upstream #634). - let head: [u32; 13] = [ - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF40C_0202, - 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0 - 0xF408_0502, - 0xFA00_0020, // s_load_dwordx4 s[20:23], s[4:5], 32 - 0xBE90_0380, // s_mov_b32 s16, 0 - 0xBE91_0380, // s_mov_b32 s17, 0 - 0xBE92_0380, // s_mov_b32 s18, 0 - 0xBE93_0380, // s_mov_b32 s19, 0 - 0x7E04_02FF, - 0x3FC0_0000, // v_mov_b32 v2, 1.5 - 0x7E06_02FF, - 0x3FC0_0000, // v_mov_b32 v3, 1.5 - ]; - let tail: [u32; 5] = [ - 0xF0C0_0108, - 0x0082_0401, // image_sample_o v4, v[1:3], s[8:15], s[16:19] dmask:1 dim:2D - 0xE070_0000, - 0x8005_0400, // buffer_store_dword v4, off, s[20:23] - S_ENDPGM, - ]; - let sample = |offsets: &[u32]| heap_lower(&[&head[..], offsets, &tail[..]].concat()); - let refused = |offsets: &[u32]| match sample(offsets) { - Err(crate::ShaderError::Unsupported { what, .. }) => what, - other => panic!("{:?}", other.map(|_| ())), - }; - // x = 1, y = -1 (6-bit fields a byte apart; the rest ignored). - sample(&[0x7E02_02FF, 0xC0C0_3F01]).unwrap(); - // x = -8, y = 7: the ends of DXIL's range. - sample(&[0x7E02_02FF, 0x0000_0738]).unwrap(); - // x = 8 is past it. - assert_eq!( - refused(&[0x7E02_02FF, 0x0000_0008]), - "a sample offset past -8..7" - ); - // y = -9 too. - assert_eq!( - refused(&[0x7E02_02FF, 0x0000_3700]), - "a sample offset past -8..7" - ); - // Offsets computed per lane (v0, the thread id) cannot be immediates. - assert_eq!( - refused(&[0x7E02_0300]), // v_mov_b32 v1, v0 - "a sample offset that is not constant" - ); - } - - #[test] - fn a_heap_descriptor_written_anywhere_is_a_uav_in_every_access() { - const HEAP: [u32; 4] = [ - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 (the heap's first view) - 0x7E00_0280, // v_mov_b32 v0, 0 - ]; - const LOAD: [u32; 2] = [0xE030_1000, 0x8002_0100]; // buffer_load_dword v1, v0, s[8:11], 0 offen - const LOAD_GLC: [u32; 2] = [0xE030_5000, 0x8002_0100]; // ... glc - const STORE: [u32; 2] = [0xE070_1004, 0x8002_0100]; // buffer_store_dword v1, ... offset:4 - let program = |body: &[&[u32]]| { - let mut w = HEAP.to_vec(); - body.iter().for_each(|b| w.extend_from_slice(b)); - w.push(S_ENDPGM); - heap_props(&w) - }; - // Read only: a raw SRV, as before. - assert_eq!(program(&[&LOAD]), [(0xB, 0)]); - // Read and written: one raw UAV, the load's handle included (it was - // an SRV handle of the UAV descriptor). - assert_eq!(program(&[&LOAD, &STORE]), [(0x100B, 0)]); - assert_eq!(program(&[&STORE, &LOAD]), [(0x100B, 0)]); - // A glc load of it: globally coherent, in every handle. - assert_eq!(program(&[&LOAD_GLC, &STORE]), [(0x500B, 0)]); - assert_eq!(program(&[&LOAD, &LOAD_GLC, &STORE]), [(0x500B, 0)]); - // glc alone does not make an SRV a UAV. - assert_eq!(program(&[&LOAD_GLC]), [(0xB, 0)]); - // Scalar reads of a written view: a raw UAV, not a constant buffer. - let scalar: [u32; 3] = [ - 0xF420_0304, - 0xFA00_0000, // s_buffer_load_dword s12, s[8:11], 0 - 0x7E04_020C, // v_mov_b32 v2, s12 - ]; - let store_v2: [u32; 2] = [0xE070_1008, 0x8002_0200]; // buffer_store_dword v2, ... offset:8 - assert_eq!(program(&[&scalar, &store_v2]), [(0x100B, 0)]); - // Never written: a constant buffer, as before. - let props = program(&[&scalar]); - assert_eq!(props, [(13, 0x1_0000)]); - } - - #[test] - fn a_cube_sample_whose_face_operand_holds_a_slice_is_a_cube_array() { - // An image (heap view 0), a buffer (view 1), an immediate sampler, - // s = t = 1.5; then the face operand in v3, a cube sample of it - // and a store of the result (the reproducer of upstream #720). - let head: [u32; 14] = [ - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF40C_0202, - 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0 - 0xF408_0502, - 0xFA00_0020, // s_load_dwordx4 s[20:23], s[4:5], 32 - 0xBE90_0380, // s_mov_b32 s16, 0 - 0xBE91_0380, // s_mov_b32 s17, 0 - 0xBE92_0380, // s_mov_b32 s18, 0 - 0xBE93_0380, // s_mov_b32 s19, 0 - 0x7E02_02FF, - 0x3FC0_0000, // v_mov_b32 v1, 1.5 - 0x7E04_02FF, - 0x3FC0_0000, // v_mov_b32 v2, 1.5 - 0x7E0A_02F2, // v_mov_b32 v5, 1.0 (the slice) - ]; - let tail: [u32; 4] = [ - 0xF09C_0118, - 0x0082_0401, // image_sample_lz v4, v[1:3], s[8:15], s[16:19] dmask:1 dim:CUBE - 0xE070_0000, - 0x8005_0400, // buffer_store_dword v4, off, s[20:23] - ]; - let image_kind = |face: &[u32], extra: &[u32]| { - let words = [&head[..], face, &tail[..], extra, &[S_ENDPGM]].concat(); - let props = heap_props(&words); - let images: Vec<u32> = props - .iter() - .filter(|p| p.1 == 0x409) - .map(|p| p.0 & 0xFF) - .collect(); - assert_eq!(images.len(), 1, "{props:x?}"); - images[0] - }; - // A bare face id: a cube, as before. - assert_eq!(image_kind(&[0x7E06_02F4], &[]), 5); // v_mov_b32 v3, 2.0 - // 8 × slice + face, as the console compiler builds it. - let fmac = [ - 0x7E06_02F4, // v_mov_b32 v3, 2.0 - 0x5606_0AFF, - 0x4100_0000, // v_fmac_f32 v3, 8.0, v5 - ]; - assert_eq!(image_kind(&fmac, &[]), 9); - // The product and the sum apart. - let mul_add = [ - 0x7E12_02F4, // v_mov_b32 v9, 2.0 - 0x100C_0AFF, - 0x4100_0000, // v_mul_f32 v6, 8.0, v5 - 0x0606_1306, // v_add_f32 v3, v6, v9 - ]; - assert_eq!(image_kind(&mul_add, &[]), 9); - // A constant slice folded in: 10.0 is slice 1, face 2. - assert_eq!(image_kind(&[0x7E06_02FF, 0x4120_0000], &[]), 9); - // A multiply-add by something else is no slice. - let fmac_four = [0x7E06_02F4, 0x5606_0AF6]; // v_fmac_f32 v3, 4.0, v5 - assert_eq!(image_kind(&fmac_four, &[]), 5); - // A size query of the same view takes the array's kind too. - let resinfo = [ - 0x7E0E_0280, // v_mov_b32 v7, 0 - 0xF038_0718, - 0x0002_0607, // image_get_resinfo v[6:8], v7, s[8:15] dmask:0x7 dim:CUBE - ]; - assert_eq!(image_kind(&fmac, &resinfo), 9); - assert_eq!(image_kind(&[0x7E06_02F4], &resinfo), 5); - } - - #[test] - fn buffer_cache_invalidations_lower_as_no_ops() { - // MUBUF opcode 0x071/0x072 with no data operand: the title asks the - // host to invalidate its cached view of a buffer. - assert!( - lowers(&[0xE1C4_0000, 0, S_ENDPGM]).is_ok(), - "buffer_gl0_inv" - ); - assert!( - lowers(&[0xE1C8_0000, 0, S_ENDPGM]).is_ok(), - "buffer_gl1_inv" - ); - } - - /// Lowers a pixel program with one target: whether it translates. - fn lowers_ps(words: &[u32]) -> Result<(), crate::ShaderError> { - lower_ps(words).map(|_| ()) - } - - /// Lowers a pixel program with one target. - fn lower_ps(words: &[u32]) -> Result<super::Lowered, crate::ShaderError> { - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Ps, - wave64: false, - vgprs: 4, - layout: vec![], - used: vec![], - io: StageIo::Ps { - inputs: vec![], - input_addr: 0, - db_shader_control: 0, - patches: vec![], - }, - code, - }; - let p = ir::build(&native.code, false, 4).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); - let io = io::raise(&p, &native).unwrap(); - let st = structure::structure(&p).unwrap(); - let target = crate::emit::container::SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0, - half: false, - }; - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![target], - prims: vec![], - mesh_stride: 0, - host_wave64: true, - }) - } - - /// A pixel waterfall loop: each pass reads the first lane's v0 and - /// retires the lanes holding the same value. The host's - /// waveReadLaneFirst skips helper lanes, so a helper lane takes its own - /// value instead (else it never matches and spins to the loop limit). - #[test] - fn pixel_read_first_lane_gives_helper_lanes_their_own_value() { - let waterfall = [ - 0xD765_0000, - 0x0001_00C1, // v_mbcnt_lo_u32_b32 v0, -1, 0 - 0x7E02_0280, // v_mov_b32 v1, 0 - 0xBE97_037E, // s_mov_b32 s23, exec_lo - 0x7E18_0500, // v_readfirstlane_b32 s12, v0 - 0x7D84_000C, // v_cmp_eq_u32 vcc, s12, v0 - 0xBE95_3C6A, // s_and_saveexec_b32 s21, vcc_lo - 0xBF80_0000, // s_nop 0 - 0x7E02_02FF, - 0x3F80_0000, // v_mov_b32 v1, 1.0f - 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 - 0xBF89_FFF8, // s_cbranch_execnz -> loop - 0xBEFE_0317, // s_mov_b32 exec_lo, s23 - 0xF800_180F, - 0x0101_0101, // exp mrt0, v1, v1, v1, v1 done vm - S_ENDPGM, - ]; - let l = lower_ps(&waterfall).unwrap(); - let has = |name: &str| l.funcs.iter().any(|f| f == name); - assert!(has("dx.op.waveReadLaneFirst.i32"), "{:?}", l.funcs); - assert!(has("dx.op.isHelperLane.i1"), "{:?}", l.funcs); - } - - /// Lowers a compute program of constants that allocates 512 bytes of LDS - /// (`COMPUTE_PGM_RSRC2`'s granule field): whether it translates. - fn lowers_lds(words: &[u32]) -> Result<(), crate::ShaderError> { - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 15, - threads: [32, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); - let io = io::raise(&p, &native).unwrap(); - let st = structure::structure(&p).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - host_wave64: true, - }) - .map(|_| ()) - } - - /// `v_permlanex16_b32` reads a lane of the *other* row of 16 in the - /// lane's 32-lane half, the pick from nibble i of {src2, src1}. Before - /// the rule its write was missing and the LDS store consuming it failed - /// the whole translation. - #[test] - fn permlanex16_reads_a_lane_of_the_other_row() { - let words = [ - // The selector: lane i of a row reads lane i of the other. - 0xBE80_03FF, - 0x7654_3210, // s_mov_b32 s0, 0x76543210 - 0xBE81_03FF, - 0xFEDC_BA98, // s_mov_b32 s1, 0xfedcba98 - // v0 is the thread id; lane i reads the lane its nibble names. - 0xD778_0001, - 0x0004_0100, // v_permlanex16_b32 v1, v0, s0, s1 - 0x7E04_0280, // v_mov_b32 v2, 0 - 0xD834_0000, - 0x0000_0102, // ds_write_b32 v2, v1 - S_ENDPGM, - ]; - lowers_lds(&words).unwrap(); - } - - #[test] - fn a_compressed_export_unpacks_two_f16_channels_per_dword() { - // A compr export: each source dword packs two f16 channels, the - // low half first, so four channels come from two VGPRs. - let words = [ - 0x7E00_0282, // v_mov_b32 v0, 2 - 0x7E02_0282, // v_mov_b32 v1, 2 - 0xF800_0C0F, - 0x0000_0100, // exp mrt0, v0, v0, v1, v1 done compr - S_ENDPGM, - ]; - lowers_ps(&words).unwrap(); - } - - /// A table at s0 holding structured buffers of dwords. - fn dword_buffers() -> (Vec<RootParam>, Vec<UsedResource>) { - let root = RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 0, - slot: 0, - }; - let used = UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }; - (vec![root], vec![used]) - } - - #[test] - fn a_spin_wait_on_a_table_buffer_gets_the_spin_limit() { - // Each lane rereads its flag in a buffer loaded from the table at - // s0 until it is no longer 0, then copies it to LDS. - let spin = [ - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xBE82_0380, // s_mov_b32 s2, 0 - 0xE030_6000, - 0x8002_0100, // 0x14: buffer_load_dword v1, v0, s[8:11], 0 idxen glc - 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 - 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 - 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 - 0xBF89_FFFA, // s_cbranch_execnz -> 0x14 - 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let (layout, used) = dword_buffers(); - let l = lower_with(&spin, layout, used).unwrap(); - assert_eq!(l.spin_loops, 1); - } - - #[test] - fn a_loop_that_writes_lds_keeps_the_loop_limit() { - // The same loop with the LDS write inside it: it has an effect each - // round, so it is no spin wait. - let writes = [ - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xBE82_0380, // s_mov_b32 s2, 0 - 0xE030_6000, - 0x8002_0100, // 0x14: buffer_load_dword v1, v0, s[8:11], 0 idxen glc - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 - 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 - 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 - 0xBF89_FFF8, // s_cbranch_execnz -> 0x14 - 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 - S_ENDPGM, - ]; - let (layout, used) = dword_buffers(); - let l = lower_with(&writes, layout, used).unwrap(); - assert_eq!(l.spin_loops, 0); - } - - /// Lowers a compute program with the root parameters `layout` (in user - /// SGPRs from s0 on) and the used resources `used`. - fn lower_with( - words: &[u32], - layout: Vec<RootParam>, - used: Vec<UsedResource>, - ) -> Result<Lowered, crate::ShaderError> { - lower_wave(words, layout, used, false) - } - - /// [`lower_with`] in wave64 if `wave64`. - fn lower_wave( - words: &[u32], - layout: Vec<RootParam>, - used: Vec<UsedResource>, - wave64: bool, - ) -> Result<Lowered, crate::ShaderError> { - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64, - vgprs: 256, - layout, - used, - io: StageIo::Cs(ComputeIo { - // The layout's user SGPRs (at least two), 512 bytes of LDS. - rsrc2: 1 << 15 | sgprs.max(2) << 1, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, wave64, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - host_wave64: true, - }) - } - - /// A primitive export is bounded by the declared vertex count (the - /// console's 10-bit fields reach 1023), and a group with more lanes - /// than outputs translates with its writes guarded. - #[test] - fn mesh_primitive_indices_are_bounded_by_the_vertex_count() { - let words = [ - 0x7E04_0505u32, // v_readfirstlane_b32 s2, v5 (the group input) - 0xF800_0941, - 0x0000_0009, // exp prim, v9, off, off, off done - S_ENDPGM, - ]; - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Ms, - wave64: true, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Ms(crate::native::MeshIo { - outputs: vec![], - clip_cntl: 0, - threads: 128, - max_vertices: 64, - max_primitives: 96, - topology: 2, - lds_bytes: 0, - }), - code, - }; - let p = ir::build(&native.code, true, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - let l = lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - host_wave64: true, - }) - .unwrap(); - assert_eq!(l.bounded_prims, 1); - } - - /// Root parameter `slot` in user SGPRs from `user_data` on. - fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { - RootParam { - root, - table_offset_dwords: 0, - sgprs: if root == RootType::Descriptor { 2 } else { 1 }, - base_register: 0, - user_data, - slot, - } - } - - #[test] - fn a_scalar_carry_chain_reaches_the_select() { - // The high dword of a 64-bit add or subtract, then a select on the - // carry (borrow) the high half leaves in SCC, and a branch on it - // (only code with an effect needs its operands). - let add = [ - 0xBE80_03C1, // s_mov_b32 s0, -1 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8000_8100, // s_add_u32 s0, s0, 1 - 0x8201_8001, // s_addc_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - let sub = [ - 0xBE80_0380, // s_mov_b32 s0, 0 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8080_8100, // s_sub_u32 s0, s0, 1 - 0x8281_8001, // s_subb_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - - for words in [add, sub] { - lowers(&words).unwrap(); - } - } - - fn perm_features(selector: u32) -> u64 { - // Synthetic compute shader: - // v0 is the thread ID and can supply a dynamic selector. - // Store the result in LDS to keep the permutation live. - let words = [ - 0x7E02_02FFu32, - 0x817F_34AB, - 0x7E04_02FF, - 0xFE01_56CD, - 0xD744_0003, - 257 | (258 << 9) | (selector << 18), - 0x3408_0082, - 0xD834_0000, - 0x0000_0304, - S_ENDPGM, - ]; - - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 15, - threads: [64, 1, 1], - }), - code, - }; - - let p = ir::build(&native.code, false, 256).unwrap(); - - assert!( - p.blocks - .iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_perm_b32") - ); - - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - - let io = io::raise(&p, &native).unwrap(); - - let emitted = lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - host_wave64: true, - }) - .unwrap(); - - let container = crate::Container::parse(&emitted.dxil).unwrap(); - - let features = container.part(crate::FourCC::SFI0).unwrap(); - - u64::from_le_bytes(features.data.try_into().unwrap()) - } - - #[test] - fn perm_constant_selector_needs_no_int64() { - assert_eq!(perm_features(128) & 0x8000, 0); - } - - #[test] - fn perm_dynamic_selector_needs_no_int64() { - assert_eq!( - perm_features(256) & 0x8000, - 0, - "dynamic v_perm_b32 must not require INT64" - ); - } - - #[test] - fn lds_subdword_reads_and_writes_lower() { - // Allocate 128 dwords (512 bytes) of LDS via COMPUTE_PGM_RSRC2[23:15] = 1. - let ds = |op: u32, off: u32, addr: u32, data0: u32, dst: u32| -> [u32; 2] { - [ - 0xD800_0000 | (op << 18) | (off & 0xFFFF), - (dst << 24) | (data0 << 8) | addr, - ] - }; - let mut words = vec![ - 0x7E00_0280, // v_mov_b32 v0, 0 (base address) - 0x7E02_0281, // v_mov_b32 v1, 1 (value) - ]; - // Writes at odd byte and 2-byte offsets, then all sub-dword read forms - // (including _d16 / _d16_hi which preserve the untouched half of vdst). - for inst in [ - ds(0x01e, 1, 0, 1, 0), // ds_write_b8 v0, v1 offset:1 - ds(0x01f, 2, 0, 1, 0), // ds_write_b16 v0, v1 offset:2 - ds(0x0a0, 3, 0, 1, 0), // ds_write_b8_d16_hi v0, v1 offset:3 - ds(0x0a1, 4, 0, 1, 0), // ds_write_b16_d16_hi v0, v1 offset:4 - ds(0x039, 1, 0, 0, 2), // ds_read_i8 v2, v0 offset:1 - ds(0x03a, 1, 0, 0, 2), // ds_read_u8 v2, v0 offset:1 - ds(0x03b, 2, 0, 0, 2), // ds_read_i16 v2, v0 offset:2 - ds(0x03c, 2, 0, 0, 2), // ds_read_u16 v2, v0 offset:2 - ds(0x0a2, 1, 0, 0, 2), // ds_read_u8_d16 v2, v0 offset:1 - ds(0x0a3, 1, 0, 0, 2), // ds_read_u8_d16_hi v2, v0 offset:1 - ds(0x0a4, 1, 0, 0, 2), // ds_read_i8_d16 v2, v0 offset:1 - ds(0x0a5, 1, 0, 0, 2), // ds_read_i8_d16_hi v2, v0 offset:1 - ds(0x0a6, 2, 0, 0, 2), // ds_read_u16_d16 v2, v0 offset:2 - ds(0x0a7, 2, 0, 0, 2), // ds_read_u16_d16_hi v2, v0 offset:2 - ds(0x00d, 8, 0, 2, 0), // ds_write_b32 v0, v2 offset:8 (keep reads live) - ] { - words.extend_from_slice(&inst); - } - words.push(S_ENDPGM); - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 15, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); - let io = io::raise(&p, &native).unwrap(); - let st = structure::structure(&p).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - host_wave64: true, - }) - .unwrap(); - } - - #[test] - fn buffer_formats_by_number() { - // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, - // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. - assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); - assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); - assert_eq!( - buffer_format(50), - Some((&[10, 10, 10, 2][..], Numeric::Unorm)) - ); - assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); - assert_eq!( - buffer_format(77), - Some((&[32, 32, 32, 32][..], Numeric::Float)) - ); - // Invalid, past the table. - assert_eq!(buffer_format(0), None); - assert_eq!(buffer_format(78), None); - } - - #[test] - fn packed_buffer_formats_by_number() { - // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, - // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT - // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. - assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); - assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); - assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); - assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); - assert_eq!( - buffer_format(44), - Some((&[2, 10, 10, 10][..], Numeric::Unorm)) - ); - assert_eq!( - buffer_format(45), - Some((&[2, 10, 10, 10][..], Numeric::Snorm)) - ); - assert_eq!( - buffer_format(46), - Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) - ); - assert_eq!( - buffer_format(47), - Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) - ); - assert_eq!( - buffer_format(48), - Some((&[2, 10, 10, 10][..], Numeric::Uint)) - ); - assert_eq!( - buffer_format(49), - Some((&[2, 10, 10, 10][..], Numeric::Sint)) - ); - } - - /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as - /// `legacyF16ToF32` widens it. - fn half(h: u32) -> f32 { - let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); - let v = match e { - 0 => m as f32 * 2f32.powi(-24), - 31 if m == 0 => f32::INFINITY, - 31 => f32::NAN, - _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), - }; - if s == 1 { -v } else { v } - } - - #[test] - fn small_floats_widen_as_halves() { - // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a - // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. - let f11 = |x: u32| half(x << half_shift(11)); - let f10 = |x: u32| half(x << half_shift(10)); - assert_eq!(f11(0), 0.0); - assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal - assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal - assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal - assert_eq!(f11(0x3C0), 1.0); - assert_eq!(f11(0x3E0), 1.5); - assert_eq!(f11(0x7BF), 65024.0); // largest - assert_eq!(f11(0x7C0), f32::INFINITY); - assert!(f11(0x7C1).is_nan()); - assert_eq!(f10(0x001), 2f32.powi(-19)); - assert_eq!(f10(0x020), 2f32.powi(-14)); - assert_eq!(f10(0x1E0), 1.0); - assert_eq!(f10(0x3DF), 64512.0); - assert_eq!(f10(0x3E0), f32::INFINITY); - assert!(f10(0x3FF).is_nan()); - // A 16-bit float is a half already, sign included. - assert_eq!(half(0xBC00 << half_shift(16)), -1.0); - } - - #[test] - fn sdwa_16bit_reserved_dst_unused_is_refused() { - for dst_sel in [4u32, 5] { - // v_cvt_i16_f16_sdwa v1, v0 dst_sel:{WORD_0,WORD_1} dst_unused:3 (reserved); - // ds_write_b32 v0, v1 to keep v1 live. - let sdwa_ext = (dst_sel << 8) | (3 << 11) | (4 << 16); - let words = [ - 0x7E02_A6F9, // v_cvt_i16_f16 v1, sdwa - sdwa_ext, - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let err = lowers_lds(&words).expect_err("reserved dst_unused must fail"); - assert!( - matches!( - err, - crate::ShaderError::Unsupported { - what: "an SDWA destination of a 16-bit operation", - .. - } - ), - "unexpected error for dst_sel={dst_sel}: {err}" - ); - } - } - - #[test] - fn a_descriptor_selected_by_scc_picks_its_heap_index() { - // Two buffer descriptors loaded from the table at s0, one picked by - // a root constant (s1) with s_cselect_b64 per half, and loaded - // through by index and stored to LDS so the load is needed. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xF408_0302, - 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 - 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] - 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] - 0xE030_2000, - 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - // Both are structured buffers of dwords in the table's range. - let used = || { - vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }] - }; - lower_with(&words, layout(), used()).unwrap(); - } - - #[test] - fn s_buffer_load_descriptor_size_reads_as_data() { - // Buffer descriptor loaded from the table at s0, used by an SMEM - // `s_buffer_load_dword` (Fields::Smem) and also read as data via - // dword 2 (`s10`, num_records), then written to LDS. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xF420_0304, - 0xFA00_0000, // s_buffer_load_dword s12, s[8:11], null - 0x800D_0A0C, // s_add_u32 s13, s12, s10 - 0x7E02_020D, // v_mov_b32 v1, s13 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let used = |kind| { - vec![UsedResource { - kind, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }] - }; - lower_with(&words, vec![root(RootType::Table, 0, 0)], used(ResourceType::Srv)).unwrap(); - let err = lower_with(&words, vec![root(RootType::Table, 0, 0)], used(ResourceType::Cbv)) - .err() - .expect("CBV descriptor read as data must be refused"); - assert!( - err.to_string().contains("constant buffer's descriptor read as data"), - "unexpected error: {err}" - ); - } - - /// Tables of 2D textures at s0 and samplers at s1. - fn texture_tables() -> (Vec<RootParam>, Vec<UsedResource>) { - let range = |kind, user_data, slot| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, - user_data, - slot, - }; - ( - vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], - vec![ - range(ResourceType::Srv, 0, 0), - range(ResourceType::Sampler, 1, 1), - ], - ) - } - - #[test] - fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { - use crate::resource::tests::{ - WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, - }; - for (words, wave64) in [ - (WATERFALL_FETCHED_WAVE32, false), - (WATERFALL_FETCHED_WAVE64, true), - (WATERFALL_PICKED_WAVE32, false), - ] { - let (layout, used) = texture_tables(); - let l = lower_wave(words, layout, used, wave64).unwrap(); - // The loop's reads of the first lane became each lane's own - // dwords: no wave operation is left. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } - } - - #[test] - fn an_image_atomic_after_a_size_query_gets_an_integer_handle() { - // A size query, then an atomic on the same image UAV: the float - // handle of the query must not be reused for the u32 atomic - // (dxil-spirv then declares a float image: OpAtomicUMax %float). - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF40C_0202, - 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], null - 0x7E02_0300, // v_mov_b32 v1, v0 - 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) - 0xF038_0308, - 0x0002_0200, // image_get_resinfo v[2:3], v0, s[8:15] dmask:0x3 dim:2D - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0xF05C_0108, - 0x0002_0200, // image_atomic_umax v2, v[0:1], s[8:15] dmask:0x1 dim:2D - S_ENDPGM, - ]; - let used = vec![UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 8, - user_data: 0, - slot: 0, - }]; - let l = lower_with(&words, vec![root(RootType::Table, 0, 0)], used).unwrap(); - // The query's f32 x4 handle and the atomic's own u32 x1 one. - assert_eq!( - l.heap_props.iter().map(|p| p.1).collect::<Vec<_>>(), - [0x409, 0x105] - ); - } - - /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. - pub(crate) fn texture_and_uav_tables() -> (Vec<RootParam>, Vec<UsedResource>) { - let (layout, mut used) = texture_tables(); - used.push(UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 16, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }); - (layout, used) - } - - #[test] - fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { - use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; - for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { - let (layout, used) = texture_and_uav_tables(); - let l = lower_wave(words, layout, used, false).unwrap(); - // One image handle, from the join's per-lane heap index. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } - } +/// The DXIL interpolation mode of a kind of barycentrics (none for the +/// pull model). +fn interp_mode(kind: Barycentric) -> Option<u8> { + Some(match kind { + Barycentric::PerspectiveCenter => 2, + Barycentric::PerspectiveCentroid => 3, + Barycentric::PerspectiveSample => 6, + Barycentric::LinearCenter => 4, + Barycentric::LinearCentroid => 5, + Barycentric::LinearSample => 7, + Barycentric::PerspectivePullModel => return None, + }) } #[cfg(test)] -mod select_tests { - use super::super::emit; - use crate::native::{ComputeIo, RootParam}; - use crate::{Container, FourCC, HwStage, NativeProgram, ResourceType, RootType, UsedResource}; - - #[test] - fn selects_from_independently_written_mask_words() { - let words = [ - 0xbe81_0380u32, // s1 = 0 (table address high) - 0xf408_0200, - 0xfa00_0000, // load UAV into s[8:11] - 0xbe84_03ff, - 0x8000_0000, // s4 = lane 31 - 0xbe85_0381, // s5 = lane 32 in wave64 - 0x7e02_028b, - 0x7e04_029d, // v1 = 11, v2 = 29 - 0xd501_0003, - 0x0012_0501, // v_cndmask_b32 v3, v1, v2, s[4:5] - 0x3402_0082, // v1 = 4 * v0 - 0xe070_1000, - 0x8002_0301, // store v3 to UAV at v1 - 0xbf81_0000, - ]; - let container = crate::dxbc::build(&[]); - let c = Container::parse(&container).unwrap(); - for (wave64, uses_select) in [(false, true), (true, true), (true, false)] { - let mut words = words; - if !uses_select { - words[12] = 0x8002_0101; // store v1 instead of the select result - } - let native = NativeProgram { - stage: HwStage::Cs, - wave64, - vgprs: 4, - layout: vec![RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 0, - slot: 0, - }], - used: vec![UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }], - io: crate::native::StageIo::Cs(ComputeIo { - rsrc2: 2, - threads: [if wave64 { 64 } else { 32 }, 1, 1], - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let p = crate::ir::build(&native.code, wave64, native.vgprs).unwrap(); - let st = crate::structure::structure(&p).unwrap(); - let io = crate::io::raise(&p, &native).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); - let shader = emit(&c, &native, &p, &st, &io, &res).unwrap(); - let emitted = Container::parse(&shader.dxil).unwrap(); - let features = emitted.part(FourCC::SFI0).unwrap(); - let wave_ops = u64::from_le_bytes(features.data.try_into().unwrap()) & 0x4000 != 0; - assert_eq!(wave_ops, uses_select); - } - } -} +#[path = "lower_tests.rs"] +mod tests; diff --git a/crates/victory-shader/src/emit/lower_tests.rs b/crates/victory-shader/src/emit/lower_tests.rs new file mode 100644 index 0000000000..9b8e180d17 --- /dev/null +++ b/crates/victory-shader/src/emit/lower_tests.rs @@ -0,0 +1,742 @@ +//! Tests of the lowering (`lower.rs`), kept apart for the size limit on files. + +use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +#[test] +fn packed_pixel_inputs_find_their_second_row() { + use super::super::container::SigElement; + use super::half_input_partners; + use crate::native::{PsInput, Usage}; + let entry = |row, row2, pack2| PsInput { + usage: Usage::Generic, + row, + mask: 0xF, + attr: row, + flat: false, + fp16: true, + pack2, + row2, + }; + let element = |row| SigElement { + name: "TEXCOORD".into(), + index: row, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: true, + }; + // Rows 0 and 3 pack and leave their second row out; 5 names its + // own (6). Unnamed 16-bit rows: 1, 4, 6, 7. + let io = StageIo::Ps { + inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }; + let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into(); + let p = half_input_partners(&io, &sig); + assert_eq!(p.get(&0), Some(&1)); + assert_eq!(p.get(&3), Some(&4)); + assert_eq!(p.get(&5), None); +} + +/// The packed pedestrian layouts of the title: an element +/// behind another one in its register follows in the first parameter +/// with a dword left, and is not a half of its register's row. +#[test] +fn packed_elements_behind_another_take_the_first_free_dword() { + use super::super::container::SigElement; + use super::packed_half; + let element = |index, row, col, cols| SigElement { + name: "TEXCOORD".into(), + index, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col, + cols, + usage: 0, + half: true, + }; + // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel + // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4 + // column 3; parameter 3 (rows 6 and 7) carries it in dword 3. + let sig = vec![ + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + element(6, 4, 3, 1), + element(3, 5, 0, 4), + element(5, 6, 0, 4), + element(7, 7, 0, 2), + element(9, 9, 0, 3), + element(11, 10, 0, 3), + element(15, 12, 0, 4), + ]; + let packs = [ + (2, Some(3)), + (4, Some(5)), + (6, Some(7)), + (9, Some(10)), + (12, None), + ]; + let at = |a, h| packed_half(&sig, &packs, a, h); + // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3. + assert_eq!(at(4, 2), Some((4, 2))); + assert_eq!(at(4, 3), None); + assert_eq!(at(4, 4), Some((5, 0))); + assert_eq!(at(4, 7), Some((5, 3))); + // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone. + assert_eq!(at(6, 3), Some((6, 3))); + assert_eq!(at(6, 5), Some((7, 1))); + assert_eq!(at(6, 6), Some((4, 3))); + assert_eq!(at(6, 7), None); + // Parameters without such an element are as before. + assert_eq!(at(9, 3), None); + assert_eq!(at(9, 4), Some((10, 0))); + assert_eq!(at(12, 3), Some((12, 3))); + assert_eq!(at(12, 4), None); + // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at + // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1, + // TEXCOORD7. + let sig = vec![ + element(0, 1, 0, 2), + element(7, 1, 2, 2), + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + ]; + let packs = [(3, Some(4)), (1, Some(2))]; + let at = |a, h| packed_half(&sig, &packs, a, h); + assert_eq!(at(1, 1), Some((1, 1))); + assert_eq!(at(1, 2), Some((2, 0))); + assert_eq!(at(1, 5), Some((2, 3))); + assert_eq!(at(1, 6), Some((1, 2))); + assert_eq!(at(1, 7), Some((1, 3))); + assert_eq!(at(3, 6), Some((4, 2))); + assert_eq!(at(3, 7), None); + // A row no element holds gives nothing, as before. + assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None); +} + +/// Whether a synthetic compute program translates with these input registers. +fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .map(|_| ()) +} + +/// Lowers a compute program with the root parameters `layout` (in user +/// SGPRs from s0 on) and the used resources `used`. +fn lower_with( + words: &[u32], + layout: Vec<RootParam>, + used: Vec<UsedResource>, +) -> Result<Lowered, crate::ShaderError> { + lower_wave(words, layout, used, false) +} + +/// [`lower_with`] in wave64 if `wave64`. +fn lower_wave( + words: &[u32], + layout: Vec<RootParam>, + used: Vec<UsedResource>, + wave64: bool, +) -> Result<Lowered, crate::ShaderError> { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 256, + layout, + used, + io: StageIo::Cs(ComputeIo { + // The layout's user SGPRs (at least two), 512 bytes of LDS. + rsrc2: 1 << 15 | sgprs.max(2) << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, wave64, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) +} + +/// Root parameter `slot` in user SGPRs from `user_data` on. +fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: if root == RootType::Descriptor { 2 } else { 1 }, + base_register: 0, + user_data, + slot, + } +} + +#[test] +fn buffer_cache_invalidations_lower_as_no_ops() { + // MUBUF opcode 0x071/0x072 with no data operand: the title asks the + // host to invalidate its cached view of a buffer. + assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv"); + assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); +} + +#[test] +fn a_scalar_carry_chain_reaches_the_select() { + // The high dword of a 64-bit add or subtract, then a select on the + // carry (borrow) the high half leaves in SCC, and a branch on it + // (only code with an effect needs its operands). + let add = [ + 0xBE80_03C1, // s_mov_b32 s0, -1 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8000_8100, // s_add_u32 s0, s0, 1 + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + let sub = [ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8080_8100, // s_sub_u32 s0, s0, 1 + 0x8281_8001, // s_subb_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + + for words in [add, sub] { + lowers(&words, 0).unwrap(); + } +} + +fn perm_features(selector: u32) -> u64 { + // Synthetic compute shader: + // v0 is the thread ID and can supply a dynamic selector. + // Store the result in LDS to keep the permutation live. + let words = [ + 0x7E02_02FFu32, + 0x817F_34AB, + 0x7E04_02FF, + 0xFE01_56CD, + 0xD744_0003, + 257 | (258 << 9) | (selector << 18), + 0x3408_0082, + 0xD834_0000, + 0x0000_0304, + S_ENDPGM, + ]; + + let code: Vec<u8> = words.iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [64, 1, 1], + }), + code, + }; + + let p = ir::build(&native.code, false, 256).unwrap(); + + assert!(p.blocks.iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32")); + + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + + let io = io::raise(&p, &native).unwrap(); + + let emitted = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }).unwrap(); + + let container = + crate::Container::parse(&emitted.dxil).unwrap(); + + let features = + container.part(crate::FourCC::SFI0).unwrap(); + + u64::from_le_bytes(features.data.try_into().unwrap()) +} + +#[test] +fn perm_constant_selector_needs_no_int64() { + assert_eq!(perm_features(128) & 0x8000, 0); +} + +#[test] +fn perm_dynamic_selector_needs_no_int64() { + assert_eq!( + perm_features(256) & 0x8000, + 0, + "dynamic v_perm_b32 must not require INT64" + ); +} + +#[test] +fn a_descriptor_selected_by_scc_picks_its_heap_index() { + // Two buffer descriptors loaded from the table at s0, one picked by + // a root constant (s1) with s_cselect_b64 per half, and loaded + // through by index and stored to LDS so the load is needed. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408_0302, + 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] + 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] + 0xE030_2000, + 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + // Both are structured buffers of dwords in the table's range. + let used = || { + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + lower_with(&words, layout(), used()).unwrap(); +} + +/// Tables of 2D textures at s0 and samplers at s1. +fn texture_tables() -> (Vec<RootParam>, Vec<UsedResource>) { + let range = |kind, user_data, slot| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, + user_data, + slot, + }; + ( + vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], + vec![ + range(ResourceType::Srv, 0, 0), + range(ResourceType::Sampler, 1, 1), + ], + ) +} + +#[test] +fn a_uniform_branch_can_choose_between_immediate_samplers() { + // A root constant selects wrap or clamp. Keep the sample live with an LDS store. + let words = [ + 0xBE84_0300, 0xBE85_0380, // s[4:5] = texture table + 0xF40C_0302, 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0 + 0xBE89_0380, 0xBE8A_0380, 0xBE8B_0380, // sampler words 1-3 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0002, // branch to clamp + 0xBE88_0380, 0xBF82_0002, // wrap, skip clamp + 0xBE88_03FF, 0x0000_0092, // clamp all axes + 0xF09C_0F08, 0x0043_0C02, // image_sample_lz v[12:15], ..., s[8:11] + 0xD834_0000, 0x0000_0C00, // ds_write_b32 v0, v12 + S_ENDPGM, + ]; + let (mut layout, mut used) = texture_tables(); + layout[1] = root(RootType::Constants, 1, 1); + used.truncate(1); + let shader = lower_with(&words, layout, used).unwrap(); + assert_eq!(shader.samplers.len(), 2); + assert!(shader.samplers.contains(&[0, 0, 0, 0])); + assert!(shader.samplers.contains(&[0x92, 0, 0, 0])); +} + +#[test] +fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { + use crate::resource::tests::{ + WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, + }; + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + (WATERFALL_PICKED_WAVE32, false), + ] { + let (layout, used) = texture_tables(); + let l = lower_wave(words, layout, used, wave64).unwrap(); + // The loop's reads of the first lane became each lane's own + // dwords: no wave operation is left. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } +} + +#[test] +fn an_image_atomic_after_a_size_query_gets_an_integer_handle() { + // A size query, then an atomic on the same image UAV: the float + // handle of the query must not be reused for the u32 atomic + // (dxil-spirv then declares a float image: OpAtomicUMax %float). + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0202, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], null + 0x7E02_0300, // v_mov_b32 v1, v0 + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xF038_0308, + 0x0002_0200, // image_get_resinfo v[2:3], v0, s[8:15] dmask:0x3 dim:2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xF05C_0108, + 0x0002_0200, // image_atomic_umax v2, v[0:1], s[8:15] dmask:0x1 dim:2D + S_ENDPGM, + ]; + let used = vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }]; + let l = lower_with(&words, vec![root(RootType::Table, 0, 0)], used).unwrap(); + // The query's f32 x4 handle and the atomic's own u32 x1 one. + assert_eq!( + l.heap_props.iter().map(|p| p.1).collect::<Vec<_>>(), + [0x409, 0x105] + ); +} + +/// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. +pub(crate) fn texture_and_uav_tables() -> (Vec<RootParam>, Vec<UsedResource>) { + let (layout, mut used) = texture_tables(); + used.push(UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }); + (layout, used) +} + +#[test] +fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { + use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; + for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { + let (layout, used) = texture_and_uav_tables(); + let l = lower_wave(words, layout, used, false).unwrap(); + // One image handle, from the join's per-lane heap index. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } +} + +#[test] +fn scalar_bit_tests_lower() { + // Each tests one bit of a constant into SCC and branches on it (only + // code with an effect needs its operands). + let tail = [ + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let bit_tests: [&[u32]; 4] = [ + &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 + &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 + ], + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 + ], + ]; + for head in bit_tests { + let words: Vec<u32> = head.iter().chain(&tail).copied().collect(); + lowers(&words, 0).unwrap(); + } +} + +#[test] +#[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"] +fn a_missing_value_stays_missing_through_two_live_joins() { + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a direct read so future timestamp support works in both cases. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); +} + +#[test] +fn buffer_formats_by_number() { + // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, + // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. + assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); + assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); + assert_eq!( + buffer_format(50), + Some((&[10, 10, 10, 2][..], Numeric::Unorm)) + ); + assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); + assert_eq!( + buffer_format(77), + Some((&[32, 32, 32, 32][..], Numeric::Float)) + ); + // Invalid, past the table. + assert_eq!(buffer_format(0), None); + assert_eq!(buffer_format(78), None); +} + +#[test] +fn packed_buffer_formats_by_number() { + // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, + // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT + // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. + assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); + assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); + assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); + assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); + assert_eq!( + buffer_format(44), + Some((&[2, 10, 10, 10][..], Numeric::Unorm)) + ); + assert_eq!( + buffer_format(45), + Some((&[2, 10, 10, 10][..], Numeric::Snorm)) + ); + assert_eq!( + buffer_format(46), + Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) + ); + assert_eq!( + buffer_format(47), + Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) + ); + assert_eq!( + buffer_format(48), + Some((&[2, 10, 10, 10][..], Numeric::Uint)) + ); + assert_eq!( + buffer_format(49), + Some((&[2, 10, 10, 10][..], Numeric::Sint)) + ); +} + +/// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as +/// `legacyF16ToF32` widens it. +fn half(h: u32) -> f32 { + let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 if m == 0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), + }; + if s == 1 { -v } else { v } +} + +#[test] +fn small_floats_widen_as_halves() { + // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a + // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. + let f11 = |x: u32| half(x << half_shift(11)); + let f10 = |x: u32| half(x << half_shift(10)); + assert_eq!(f11(0), 0.0); + assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal + assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal + assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal + assert_eq!(f11(0x3C0), 1.0); + assert_eq!(f11(0x3E0), 1.5); + assert_eq!(f11(0x7BF), 65024.0); // largest + assert_eq!(f11(0x7C0), f32::INFINITY); + assert!(f11(0x7C1).is_nan()); + assert_eq!(f10(0x001), 2f32.powi(-19)); + assert_eq!(f10(0x020), 2f32.powi(-14)); + assert_eq!(f10(0x1E0), 1.0); + assert_eq!(f10(0x3DF), 64512.0); + assert_eq!(f10(0x3E0), f32::INFINITY); + assert!(f10(0x3FF).is_nan()); + // A 16-bit float is a half already, sign included. + assert_eq!(half(0xBC00 << half_shift(16)), -1.0); +} + +#[test] +fn first_lane_read_of_uniform_lds_load_lowers_on_wave32() { + // Wave64 compute program lowered for a 32-lane host: inside a divergent + // branch (`v0 < 1`), read LDS at a uniform address (`v1 = s16`), add a + // scalar (`v8 = s17 + v2`), and read the first lane into `s17`. + // When `ds_read_b32` reads from the uniform `v1`, `v8` is wave-uniform + // and `v_readfirstlane_b32` needs no cross-half exchange. When it reads + // from per-lane `v0`, the divergent read must still be refused. + let make = |addr_vgpr: u32| -> Vec<u32> { + vec![ + 0xBE90_0380, // s_mov_b32 s16, 0 + 0xBE91_0380, // s_mov_b32 s17, 0 + 0xD760_0004, // v_readlane_b32 s4, v0, 0 (triggers wave64 exchange) + 0x0001_0100, + 0x7D88_0081, // v_cmp_gt_u32_e32 vcc, 1, v0 + 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBF88_0005, // s_cbranch_execz -> restore exec + 0x7E02_0210, // v_mov_b32 v1, s16 + 0xD8D8_0000, // ds_read_b32 v2, v{addr} + 0x0200_0000 | addr_vgpr, + 0x4A10_0411, // v_add_nc_u32 v8, s17, v2 + 0x7E22_0508, // v_readfirstlane_b32 s17, v8 + 0xBEFE_0406, // s_mov_b64 exec, s[6:7] + 0x8011_0411, // s_add_u32 s17, s17, s4 (keep s17 and s4 live) + 0x7E06_0211, // v_mov_b32 v3, s17 + 0xD834_0000, // ds_write_b32 v0, v3 + 0x0000_0300, + S_ENDPGM, + ] + }; + let run = |words: &[u32]| { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, // 512 bytes LDS + threads: [128, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, true, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let prev = super::TEST_HOST_WAVE.replace(Some(32)); + let out = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }); + super::TEST_HOST_WAVE.set(prev); + out + }; + + if let Err(e) = run(&make(1)) { + panic!("uniform ds_read_b32 + scalar add must be recognised as wave-uniform, got: {e}"); + } + let err = run(&make(0)) + .err() + .expect("per-lane ds_read_b32 must be refused") + .to_string(); + assert!( + err.contains("a first-lane read where not every lane runs"), + "per-lane ds_read_b32 must still require all lanes, got: {err}" + ); +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 8c40ad54d7..8b7a521649 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -29,7 +29,7 @@ //! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter //! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the //! address the title sets is the buffer's. -//! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and +//! * **Vertex fetch** (added 2026-11-23). The title's mesh and //! vertex programs fetch vertices themselves with typed-format loads //! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm, //! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the @@ -73,17 +73,29 @@ //! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are //! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the //! console never exports them). +//! * **Rectangle lists** ([`rect_list_gs`], `gs_6_6`): the console draws a +//! rectangle from three vertices; the host has no such topology. A +//! pipeline the title makes for rectangles (topology type 19) gets a +//! geometry shader of ours between the translated vertex and pixel +//! shaders and draws triangle lists with the title's own vertex counts. +//! It binds nothing. mod bitcode; mod container; #[cfg(all(test, windows))] mod diff_tests; +#[cfg(all(test, windows))] +mod intersect_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; mod lower; +mod own_bits; +mod per_program; +#[cfg(all(test, windows))] +mod permlane_tests; +mod rect; mod sampler; mod shader; -mod spin; mod threading; #[cfg(windows)] pub mod validator; @@ -91,16 +103,24 @@ pub mod validator; mod valu_tests; #[cfg(all(test, windows))] mod waterfall_tests; +#[cfg(all(test, windows))] +mod wave64_tests; mod wave; -#[cfg(test)] -mod wave64_fixtures; use crate::dxbc::{Container, FourCC}; use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; +pub use bitcode::census; pub use sampler::StaticSampler; -pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +pub use lower::{host_uses_wave32, set_host_max_wave}; +pub use per_program::{deep_skips_allowed, for_program}; +pub use rect::rect_list_gs; +pub use shader::{ + MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, + SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, USER_DATA_SPACE, USER_DISPATCH_SPREAD, USER_DISPATCH_THREADS, VIEW_INTEGER, VIEW_SIGNED, + VIEW_STRIDE_BITS, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, set_view_heap_limit, view_heap_limit, +}; /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; @@ -108,8 +128,8 @@ pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; /// The iteration count after which a translated loop is left, per lane and /// per entry into the loop: [`DEFAULT_LOOP_LIMIT`]. /// -/// `VICTORY_SHADER_LOOP_LIMIT` (decimal or `0x` hex, at least 1) sets it -/// instead, in release builds too. A loop that hits the limit in +/// With the `diagnostics` feature, `VICTORY_SHADER_LOOP_LIMIT` (decimal or +/// `0x` hex, at least 1) sets it instead. A loop that hits the limit in /// every lane of a full-screen pass still runs for seconds (2^20 times a /// 4K screen is about 10^13 iterations); a much lower limit shows whether /// such loops are what makes a frame slow. The value is part of the @@ -117,39 +137,105 @@ pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; pub fn loop_limit() -> u32 { static LIMIT: std::sync::OnceLock<u32> = std::sync::OnceLock::new(); *LIMIT.get_or_init(|| { - parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref()) + if cfg!(feature = "diagnostics") { + parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref()) + } else { + lower::LOOP_LIMIT + } }) } -/// The spin-wait limit without an override: 4096. -pub const DEFAULT_SPIN_LIMIT: u32 = 1 << 12; - -/// The iteration count after which a loop that only waits for memory to -/// change (a spin wait, see `spin.rs`) is left: [`DEFAULT_SPIN_LIMIT`], or -/// `VICTORY_SHADER_SPIN_LIMIT` (decimal or `0x` hex, at least 1), never -/// more than [`loop_limit`]. On the console the write such a loop waits -/// for comes within microseconds; on the host, when it never comes (the -/// writer's view is another host resource, null, or the load was hoisted), -/// 2^20 uncached reads per lane cost about a second per wave, which is -/// what world frames spent per host submission. 4096 reads are a few -/// milliseconds. Part of the translation: the shader cache keys on it. -pub fn spin_limit() -> u32 { - static LIMIT: std::sync::OnceLock<u32> = std::sync::OnceLock::new(); - *LIMIT.get_or_init(|| { - let v = std::env::var("VICTORY_SHADER_SPIN_LIMIT").ok(); - parse_limit(v.as_deref(), DEFAULT_SPIN_LIMIT).min(loop_limit()) +/// Which of a translated program's group barriers wait for the whole +/// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory +/// fence and lose the wait. A wait that some thread of the group never +/// reaches is undefined on the host, and NVIDIA's wait is for every +/// thread: the group stands until Windows resets the card. (The console's +/// barrier is the wave's, whatever lanes are live, and a wave that ended +/// is not waited for.) `VICTORY_GROUP_SYNC`: +/// - unset or `2`: every barrier waits, as before. +/// - `1`: the title's `s_barrier` waits only in a block every lane runs, +/// in a program no lane can be cut out of at the iteration limit. +/// - `0`: no barrier waits, neither the title's nor the ones the +/// translation adds (wave64 programs in two host waves exchange through +/// them, so such programs compute wrong values). For one run that tells +/// whether a barrier is what stops the card: with it no run can stand in +/// a barrier. +/// +/// Part of the translation: the shader cache keys on it (`victory-gpu`'s +/// does). +pub fn group_sync() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) { + Some("0") => 0, + Some("1") => 1, + _ => 2, }) } +/// The clean-up passes that run over a translated program before it is +/// written (`bitcode::opt`): a set of that module's pass bits. Every pass +/// is exact, so the switch is for telling a translator fault from a +/// clean-up fault, and for measuring what the clean-up is worth. +/// `VICTORY_SHADER_OPT`: +/// - unset: every pass but the last one below (63). +/// - `0`: none (the module as the lowering made it). +/// - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants +/// and identities, 4 one instruction for one value, 8 what a branch taken +/// says about its condition, 16 one read for one place within a block, +/// 32 a first-lane read of two host waves without the round that asks +/// which half has a lane (where every lane has one). +/// 64 the dwords of one console load read by one call for every four +/// (not on unless asked: `127` is every pass with it). +/// +/// Part of the translation: the shader cache keys on it (`victory-gpu`'s +/// does). +pub fn shader_opt() -> u32 { + static PASSES: std::sync::OnceLock<u32> = std::sync::OnceLock::new(); + *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref())) +} + +/// Everything a translation depends on besides the container: the +/// translator's own source (hashed at build time), the value of every +/// `VICTORY_*` switch it reads, the host facts the device hands it (widest +/// wave, view heap limit) and the settings above. The shader cache keys on +/// this instead of on the whole executable, so a rebuild that leaves the +/// translator alone keeps its translations. Call it after the device is made. +pub fn translation_fingerprint() -> Vec<u8> { + let mut out = Vec::new(); + out.extend_from_slice(env!("VICTORY_SHADER_SOURCE_HASH").as_bytes()); + out.push(u8::from(cfg!(feature = "diagnostics"))); + out.push(u8::from(cfg!(debug_assertions))); + for name in env!("VICTORY_SHADER_SWITCHES").split(',').filter(|n| !n.is_empty()) { + out.extend_from_slice(name.as_bytes()); + out.push(b'='); + if let Some(value) = std::env::var_os(name) { + out.extend_from_slice(value.as_encoded_bytes()); + } + out.push(0); + } + out.push(u8::from(lower::host_uses_wave32())); + out.extend_from_slice(&shader::view_heap_limit().to_le_bytes()); + out.extend_from_slice(&loop_limit().to_le_bytes()); + out.push(group_sync()); + out.extend_from_slice(&shader_opt().to_le_bytes()); + out +} + +/// `VICTORY_SHADER_OPT`'s value; every pass when it is unset or +/// unreadable. Pure, for testing. +fn parse_shader_opt(value: Option<&str>) -> u32 { + let parsed = value + .map(str::trim) + .and_then(|v| match v.strip_prefix("0x") { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => v.parse().ok(), + }); + parsed.map_or(bitcode::opt::DEFAULT, |n| n & bitcode::opt::ALL) +} + /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset, /// unreadable or 0. Pure, for testing. fn parse_loop_limit(value: Option<&str>) -> u32 { - parse_limit(value, lower::LOOP_LIMIT) -} - -/// A limit's value from its variable; `default` when it is unset, -/// unreadable or 0. -fn parse_limit(value: Option<&str>, default: u32) -> u32 { let parsed = value .map(str::trim) .and_then(|v| match v.strip_prefix("0x") { @@ -158,32 +244,10 @@ fn parse_limit(value: Option<&str>, default: u32) -> u32 { }); match parsed { Some(n) if n > 0 => n, - _ => default, + _ => lower::LOOP_LIMIT, } } -/// Whether the host device runs 64-lane waves (`WaveSize(64)`): set once, -/// before the first translation, by whoever creates the host device -/// ([`set_host_wave64`]); true until then. AMD's RDNA GPUs do; NVIDIA's -/// and Intel's have 32 lanes (or fewer) and refuse a pipeline that -/// declares 64. Without them a compute program that needs the console's -/// 64 lanes runs its cross-lane steps through group-shared memory when its -/// group is that one wave, and is refused with a reason otherwise. The -/// value is part of the translation, so the shader cache must key on it -/// (`victory-gpu`'s does). -pub fn host_wave64() -> bool { - HOST_WAVE64.load(std::sync::atomic::Ordering::Relaxed) -} - -/// Sets [`host_wave64`] from the host device's lane counts -/// (`D3D12_FEATURE_DATA_D3D12_OPTIONS1::WaveLaneCountMin/Max`). -pub fn set_host_wave64(min_lanes: u32, max_lanes: u32) { - let yes = (min_lanes..=max_lanes).contains(&64); - HOST_WAVE64.store(yes, std::sync::atomic::Ordering::Relaxed); -} - -static HOST_WAVE64: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); - /// A translated shader and what the host binds for it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HostShader { @@ -203,6 +267,26 @@ pub struct HostShader { /// Root SRVs (raw buffers) the shader reads: `t<index>` in /// [`ROOT_CBV_SPACE`]. pub root_srvs: Vec<u8>, + /// Root UAVs (raw buffers) the shader reads or writes: `u<index>` in + /// [`ROOT_CBV_SPACE`]. + pub root_uavs: Vec<u8>, + /// Heap descriptors that can be selected from root state at bind time. + pub root_indexed_views: Vec<crate::resource::RootIndexedView>, + /// Table descriptors (root parameter, dword offset in the table) whose + /// buffer the shader reads or writes sixteen bits a channel + /// (`buffer_load_format_d16_*`, `buffer_store_format_d16_*`), in + /// order. On the console each channel's 16 bits move as they are + /// through a 16-bit float view and through a 16-bit integer one alike + /// (the title keeps half floats, and indices beside them, in + /// `R16G16B16A16_UINT` and `R16_UINT` buffers). The DXIL moves them as + /// unsigned integers, which an unsigned 16-bit view carries unchanged; + /// the host shows the shader a 16-bit float or signed buffer view at + /// these places as the unsigned format of the same layout. + /// shortcut: a view in a normalised 16-bit format, whose values the + /// console would convert to halves, is read as its integers; a + /// descriptor picked at run time keeps the float path (its slot, and so + /// its format, is known only then). + pub half_views: Vec<(u8, u32)>, } impl HostShader { @@ -219,6 +303,21 @@ impl HostShader { } } +/// A dispatch of `(x, y, z)` groups as the host runs it: `(row, asked x, gx, +/// gy, gz)`. Spread across z when `can_spread`, `x` > 65,535 and `z` == 1 +/// ([`USER_DISPATCH_SPREAD`]); else `row` 0 and the counts as asked (upstream +/// VIctory pull request #2312's `spread_groups`). +pub fn spread_groups(x: u32, y: u32, z: u32, can_spread: bool) -> (u32, u32, u32, u32, u32) { + if can_spread && x > 65_535 && z == 1 { + let rows = x.div_ceil(65_535); + if rows <= 65_535 { + let row = x.div_ceil(rows); + return (row, x, row, y, rows); + } + } + (0, x, x, y, z) +} + /// One dword of user data and the root parameter that fills it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct UserData { @@ -234,7 +333,16 @@ pub struct UserData { /// Translates the vertex, pixel, compute or mesh program of a console /// shader container. +/// +/// A program refused because the first half of an interpolation is read as +/// data is translated once more inside [`translate_plain`]: first with each +/// such first half its own interpolation, then with each evaluated as the +/// pair it starts (`lower::with_approximate_first_halves`). pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> { + translate_plain(container) +} + +fn translate_plain(container: &[u8]) -> Result<HostShader, ShaderError> { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) @@ -251,22 +359,51 @@ pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> { offset: 0, what: "a container without a vertex, pixel, compute or mesh program", })?; - // A compute program whose root arguments all sit past the 16 user SGPRs - // finds them through the spill table `s[0:1]` points to. - let spilled = native.stage == HwStage::Cs - && !native.layout.is_empty() - && native - .layout - .iter() - .all(|r| native.stage.user_sgpr(r.user_data) >= 16); - let p = ir::build_with(&native.patched_code(), native.wave64, native.vgprs, spilled)?; + let p = crate::spill::build(&native)?; // Structurisation first: tracing per-lane descriptors needs it (its // failure is reported after the earlier stages'). let st = structure::structure(&p); let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?; let io = io::raise(&p, &native)?; let st = st?; - emit(&c, &native, &p, &st, &io, &res) + let out = emit(&c, &native, &p, &st, &io, &res); + // A pixel program that also reads a first half of an interpolation + // beside the second half: once more with every first half its own + // interpolation (`VICTORY_KEEP_FIRST_HALVES=0` turns this off). + if matches!(&out, Err(ShaderError::Unsupported { what, .. }) if *what == lower::FIRST_HALF) + && std::env::var_os("VICTORY_KEEP_FIRST_HALVES").is_none_or(|v| v != "0") + && let Ok(io) = io::raise_keeping_first_halves(&p, &native) + && let Ok(shader) = emit(&c, &native, &p, &st, &io, &res) + { + return Ok(shader); + } + // Else (or with that off) each such first half evaluated as its pair, + // approximate for what reads it as data (the fx-prs form). + if matches!(&out, Err(ShaderError::Unsupported { what, .. }) if *what == lower::FIRST_HALF) + && let Ok(shader) = lower::with_approximate_first_halves(|| emit(&c, &native, &p, &st, &io, &res)) + { + return Ok(shader); + } + out +} + +thread_local! { + /// [`with_wave_wide`]'s choice, for this thread's translations. + static WAVE_WIDE_HERE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` (a translation) with the wave-wide form of a wave64 compute +/// program on a host of 32-lane waves allowed, as `VICTORY_WAVE_WIDE=1` +/// allows it for all, for one program chosen by its hash +/// (`victory-gpu`'s `VICTORY_WAVE_WIDE_ONLY`). The form is still tried only +/// after the exact ones. (After commit a416e392 of pull request #823 by +/// Felix2180: the water's transmission volumetrics, particle visibility and +/// the reflection pass's tiling come out of it with 32-lane waves.) +pub fn with_wave_wide<R>(on: bool, f: impl FnOnce() -> R) -> R { + let before = WAVE_WIDE_HERE.replace(on); + let out = f(); + WAVE_WIDE_HERE.set(before); + out } /// Emits a program whose earlier stages already ran. @@ -278,7 +415,291 @@ pub fn emit( io: &io::Io, res: &resource::Resources, ) -> Result<HostShader, ShaderError> { + let out = emit_forms(c, native, p, st, io, res); + // A lane mask holding lanes outside EXEC read as data: once more with it + // read as the ballot of the lanes that reach its block + // ([`lower::with_masks_elsewhere`]; `VICTORY_MASK_ELSEWHERE=0` refuses). + if matches!(&out, Err(ShaderError::Unsupported { what, .. }) if *what == lower::MASK_ELSEWHERE) + && std::env::var_os("VICTORY_MASK_ELSEWHERE").is_none_or(|v| v != "0") + && let Ok(shader) = lower::with_masks_elsewhere(|| emit_forms(c, native, p, st, io, res)) + { + return Ok(shader); + } + out +} + +/// [`emit`] without its last retry. +fn emit_forms( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result<HostShader, ShaderError> { + // (what an earlier program's lowering on this thread left behind) + lower::take_needs(); let original = emit_program(c, native, p, st, io, res); + // A console wave64 compute program on a host of 32-lane waves that + // still needs 64 lanes, or whose cross-lane code sits where not every + // lane runs: once more with its early-outs left out + // ([`ir::without_early_outs`]), which is what usually keeps the whole + // body from being a block every lane runs. + let stuck = match &original { + Ok((_, wave)) => *wave == Some(64), + Err(ShaderError::Unsupported { what, .. }) => lower::needs_every_lane(what), + Err(_) => false, + }; + // (a mask with lanes elsewhere is only helped by the exact forms: not by each half-wave + // on its own) + let exact_only = matches!(&original, Err(ShaderError::Unsupported { what, .. }) if *what == lower::MASK_ELSEWHERE); + if stuck && native.stage == HwStage::Cs && native.wave64 && host_uses_wave32() { + let why = std::env::var_os("VICTORY_WAVE_WHY").is_some(); + let report = |what: &str, r: &Result<(HostShader, Option<u32>), ShaderError>| { + if why { + match r { + Ok((_, wave)) => eprintln!("WAVE64-RETRY {what}: wave {wave:?}"), + Err(e) => eprintln!("WAVE64-RETRY {what}: {e}"), + } + } + }; + let done = |r: &Result<(HostShader, Option<u32>), ShaderError>| matches!(r, Ok((_, wave)) if *wave != Some(64)); + // Each host wave as a wave of its own (`lower::with_local_waves`), + // for programs still stopped where not every lane runs. + let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0"); + // Where the wave operations are the allocation idiom + // ([`lower::wave_local`]) that is exact. Other programs are taken + // the same way last of all, each half-wave giving its own results + // (approximate: a tile-wide result becomes two half-tile ones); + // `VICTORY_WAVE_LOCAL=idiom` refuses those instead. + let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom"); + let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) { + Ok(()) => true, + Err((offset, what)) => { + if why { + eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}"); + } + false + } + }; + // The program in two other forms: without its early-outs, and + // without any branch that only skips code no lane is left for. + // `VICTORY_WAVE_WHY`: why a form is missing (no such branch, or the + // stage that refused the changed program, with its reason). + let form_why = std::env::var_os("VICTORY_WAVE_WHY").is_some(); + let form = |label: &str, p: Option<ir::Program>| { + let say = |what: &dyn std::fmt::Display| { + if form_why { + eprintln!("WAVE64-FORM {label}: {what}"); + } + }; + let Some(p) = p else { + say(&"not made (no such branch in the program, or its blocks could not be made reducible)"); + return None; + }; + let st = match structure::structure(&p) { + Ok(st) => st, + Err(e) => { + say(&format_args!("structure: {e}")); + return None; + } + }; + let io = match io::raise(&p, native) { + Ok(io) => io, + Err(e) => { + say(&format_args!("io: {e}")); + return None; + } + }; + let res = match resource::track(&p, &native.layout, native.stage, Some(&st)) { + Ok(res) => res, + Err(e) => { + say(&format_args!("resources: {e}")); + return None; + } + }; + Some((p, st, io, res)) + }; + let forms = [ + ("without early-outs", form("without early-outs", ir::without_early_outs(p))), + ("without skips", form("without skips", ir::without_skips(p, false))), + ]; + for (name, f) in &forms { + if let Some((p, st, io, res)) = f { + let again = emit_program(c, native, p, st, io, res); + report(name, &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + } + // Off unless asked for (`VICTORY_WAVE_WIDE=1`), for a console wave run as two host + // waves: this form puts group barriers inside branches and loops, and runs 121-124 + // lost the card in a submission of two programs that had just moved to it + // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which + // has no barrier, stays on. + let wide_option = std::env::var_os("VICTORY_WAVE_WIDE"); + // codec_d, cool_fox 8cc31ab: two scene kernels of one console wave a group whose + // 32-lane wave-wide form was validated on RTX; wave-wide by default unless asked + // otherwise. + let scene_kernel = matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64) + && matches!( + c.digest, + [0x58, 0x1d, 0xab, 0x2c, 0xd8, 0xbc, 0xf2, 0x2e, 0x5c, 0x96, 0x4b, 0x98, 0xe9, 0x03, 0x48, 0xd1] + | [0x24, 0x31, 0xbb, 0xe7, 0xdc, 0x15, 0x4a, 0xd7, 0x59, 0xd2, 0x0b, 0xc9, 0x54, 0x82, 0x9c, 0x1c] + ); + let wide_on = wide_option.as_ref().map_or(scene_kernel, |v| v == "1") || WAVE_WIDE_HERE.get(); + // (cool_fox 8cc31ab) A driver-compiled program (ACCC, no DXIL) stopped at a mask + // exchange where not every lane runs: one guest wave can run its active-lane loop + // until both host halves are done; [`widen`] checks the latch. + let driver_loop = wide_option.is_none() + && c.part(FourCC::DXIL).is_none() + && c.part(FourCC::ACCC).is_some() + && matches!(&original, Err(ShaderError::Unsupported { what, .. }) + if *what == lower::DIVERGENT_MASK_EXCHANGE); + // exact first: each host wave on its own where that is exact (the idiom, every + // form; no barriers), then the other exact forms; then approximate + for exact in [true, false] { + if !exact { + // Before anything approximate, the exact forms that cost group barriers. + // Every skip left out that the code after it cannot see + // ([`ir::without_skips`], `deep`): most of the body is then code every + // lane runs, where the two host waves can exchange. + // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off; + // `VICTORY_WAVE_DEEP_SKIPS_NOT` and `_ONLY` the first for some programs, + // the 14 cascade-shadow renderers by default: [`deep_skips_allowed`].) + let program = per_program::current(); + let deep_on = deep_skips_allowed(program.as_deref()); + if why && !deep_on { + eprintln!( + "WAVE64-RETRY #{} without skips, scalars followed: off for this program", + program.as_deref().unwrap_or("?") + ); + } + let deep = if deep_on { form("without skips, scalars followed", ir::without_skips(p, true)) } else { None }; + if let Some((p, st, io, res)) = &deep { + let again = emit_program(c, native, p, st, io, res); + report("without skips, scalars followed", &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + // Still stopped where not every lane runs: the per-lane branches around + // those places taken as the console takes them, by the whole wave at once + // ([`widen`]), at two group barriers per such branch. + if wide_on || driver_loop { + let bases = [ + deep.as_ref().map(|f| &f.0), + forms[1].1.as_ref().map(|f| &f.0), + forms[0].1.as_ref().map(|f| &f.0), + Some(p), + ]; + if let Some(base) = bases.into_iter().flatten().next() { + let again = widen(c, native, base, why, driver_loop); + report("wave-wide branches", &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + } + if strict { + break; + } + } + if !local_on || exact_only { + continue; + } + for (name, f) in &forms { + if let Some((p, st, io, res)) = f + && idiom(p, st) == exact + { + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + if idiom(p, st) == exact { + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + if local_on && !exact_only { + // Last: every mask and lane read per host wave. + if !strict { + for (name, f) in &forms { + if let Some((p, st, io, res)) = f { + let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + report("local waves (APPROXIMATE, any mask)", &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + // The wave-wide form for programs every other form left asking for 64-lane waves, + // which a 32-lane host refuses outright (E_INVALIDARG at pipeline creation: + // 02384a60fda6f2d0, 2cc4c197ee29e291, 2da4beb386509b77, 369cbe906ea72764, + // 5dc3b25986622949, 6f225b641c5b0708 in every run on an RTX 4060, their WaveSize(64) + // tag the only thing the driver objects to; 6b82bc7d22016cb5, victory-gta6 #7). Once + // opt-in (`VICTORY_WAVE_WIDE=last`) because the form's barriers lost the card for two + // other programs, but those took it in place of a form that translates (`=1`); here + // the alternative is a pipeline that is never made. `VICTORY_WAVE_WIDE=0` turns it off. + if !wide_on && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") { + let base = forms + .iter() + .rev() + .filter_map(|(_, f)| f.as_ref().map(|f| &f.0)) + .next() + .unwrap_or(p); + let again = widen(c, native, base, why, false); + report("wave-wide branches (last)", &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + } + // SCC of a mask operation joined with a scalar test behind a per-lane skip (the 32-lane + // trace programs): right once the wave takes that skip together ([`widen`]; the + // lowering has named the skipped blocks). + let original = match original { + Err(ShaderError::Unsupported { what, .. }) + if native.stage == HwStage::Cs + && what == lower::LANE_MASK + && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") => + { + let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some(), false); + match again { + Ok(_) => again, + Err(_) => emit_program(c, native, p, st, io, res), + } + } + other => other, + }; + // A program still asking for 64-lane waves on a host of 32-lane waves: the driver + // refuses its pipeline (E_INVALIDARG), so it is unsupported here and gets the retry + // below (codec_d, cool_fox 8cc31ab). + let supported = |(shader, wave): (HostShader, Option<u32>)| { + if wave == Some(64) && lower::host_uses_wave32() { + Err(ShaderError::Unsupported { + offset: 0, + what: "no wave32 lowering for this wave64 program", + }) + } else { + Ok(shader) + } + }; + let original = original.and_then(supported); // Retry unsupported programs only. Threading can separate an unknown // register value from its apparent use on a mutually exclusive path. if !matches!(original, Err(ShaderError::Unsupported { .. })) { @@ -292,9 +713,97 @@ pub fn emit( let st = structure::structure(&p)?; let io = io::raise(&p, native)?; let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - emit_program(c, native, &p, &st, &io, &res) + emit_program(c, native, &p, &st, &io, &res).and_then(supported) +} + +/// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane +/// branches around its cross-lane code taken wave-wide ([`structure::structure_wide`]): the +/// lowering names the blocks where the two host waves must meet and could not +/// (`lower::take_needs`), the branches whose regions hold them are widened, and so on until +/// it translates or a branch cannot be widened. Only where a thread group is one console +/// wave: with several, the waves of a group would decide differently and a barrier inside +/// such a branch would wait for threads that never come. +fn widen( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + why: bool, + active_loop_only: bool, +) -> Result<(HostShader, Option<u32>), ShaderError> { + const NOT: ShaderError = ShaderError::Unsupported { + offset: 0, + what: "wave-wide branches in a thread group of several console waves", + }; + match native.io { + // (a program whose waves are the host's meets no one: no barrier, any group) + crate::native::StageIo::Cs(_) if !(native.wave64 && host_uses_wave32()) => {} + crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64 => {} + crate::native::StageIo::Cs(cs) => { + if why { + eprintln!("WAVE64-WIDE not tried: thread groups of {:?}", cs.threads); + } + return Err(NOT); + } + _ => return Err(NOT), + } + let mut wide = std::collections::HashSet::new(); + loop { + let st = structure::structure_wide(p, &wide)?; + let io = io::raise(p, native)?; + let res = resource::track(p, &native.layout, native.stage, Some(&st))?; + lower::take_needs(); + let r = emit_program(c, native, p, &st, &io, &res); + let needs = lower::take_needs(); + // (or translated for 64-lane waves still: shared memory read and written where not + // every lane runs, whose blocks the lowering names too) + let stuck = matches!(&r, Err(ShaderError::Unsupported { what, .. }) + if lower::needs_every_lane(what) || *what == lower::LANE_MASK && !needs.is_empty()) + || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty(); + if !stuck { + if why { + eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len()); + } + return r; + } + let more: Vec<usize> = lower::branches_around(&st, &needs) + .unwrap_or_default() + .into_iter() + .filter(|b| !wide.contains(b)) + .collect(); + if more.is_empty() { + if why { + eprintln!("WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", wide.len()); + } + return r; + } + if active_loop_only { + // (cool_fox 8cc31ab) Only a single backward branch on the SCC just set by + // s_andn2_wrexec_b64, which restricts EXEC to the unfinished lanes: the guest + // repeats the loop while either half has work, and each vector write keeps + // its EXEC predicate. + let [latch] = more.as_slice() else { + return r; + }; + let block = &p.blocks[*latch]; + let [.., update, branch] = block.insts.as_slice() else { + return r; + }; + if !wide.is_empty() + || update.name() != "s_andn2_wrexec_b64" + || branch.name() != "s_cbranch_scc1" + || !matches!( + block.exit, + ir::Exit::Branch { taken, not_taken } if taken <= *latch && not_taken > *latch + ) + { + return r; + } + } + wide.extend(more); + } } +/// The translated program, and the wave size it requires of the host. fn emit_program( c: &Container, native: &NativeProgram, @@ -302,7 +811,7 @@ fn emit_program( st: &structure::Structured, io: &io::Io, res: &resource::Resources, -) -> Result<HostShader, ShaderError> { +) -> Result<(HostShader, Option<u32>), ShaderError> { let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> { match c.part(fourcc) { Some(part) => signature(part.data), @@ -321,6 +830,8 @@ fn emit_program( // Constant, as DXC declares it (the AMD compiler crashed on a // front face without a mode). (13, _) => 1, + // Until a read says which mode (`lower`). + (28, _) => 2, (0 | 6 | 7, 9) => 2, (0, _) => 1, _ => 0, @@ -345,7 +856,7 @@ fn emit_program( // primitives) (the code divides by that); the thread count is in PSV0 // from runtime info version 2 on. // shortcut: older containers fall back to the group's lane count, right - // when the HLSL group fills its waves (Grand Theft Auto VI's do). + // when the HLSL group fills its waves (the title's do). let mesh_stride = match &native.io { crate::native::StageIo::Ms(ms) => { let psv = c.part(FourCC::PSV0).map(|p| p.data); @@ -368,9 +879,9 @@ fn emit_program( outputs, prims, mesh_stride, - host_wave64: host_wave64(), })?; - Ok(HostShader { + let wave_size = l.wave_size; + let shader = HostShader { stage: native.stage, dxil: l.dxil, user_data: l.user_data, @@ -389,7 +900,11 @@ fn emit_program( samplers: l.samplers, root_cbvs: l.root_cbvs, root_srvs: l.root_srvs, - }) + root_uavs: l.root_uavs, + root_indexed_views: res.root_indexed_views.clone(), + half_views: l.half_views, + }; + Ok((shader, wave_size)) } /// The rows of an `ISG1`/`OSG1` part. @@ -439,6 +954,7 @@ fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> { 68 => 18, 69 => 20, 70 => 15, + 23 => 28, // barycentrics 25 => 30, // cull primitive _ => { return Err(ShaderError::Unsupported { @@ -485,11 +1001,23 @@ fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> { #[cfg(test)] mod tests { - #[cfg(windows)] use super::bitcode::Attr; use super::lower::LOOP_LIMIT; use super::parse_loop_limit; + #[test] + fn the_clean_up_switch_parses_or_runs_every_pass() { + let (all, usual) = (super::bitcode::opt::ALL, super::bitcode::opt::DEFAULT); + assert_eq!(usual, 63, "the passes of the builds before the wide loads"); + assert_eq!(parse_shader_opt(None), usual); + assert_eq!(parse_shader_opt(Some("0")), 0); + assert_eq!(parse_shader_opt(Some(" 1 ")), 1); + assert_eq!(parse_shader_opt(Some("0x1")), 1); + assert_eq!(parse_shader_opt(Some("127")), all); + assert_eq!(parse_shader_opt(Some("0xffffffff")), all); + assert_eq!(parse_shader_opt(Some("on")), usual); + } + #[test] fn the_loop_limit_switch_parses_or_falls_back() { assert_eq!(parse_loop_limit(None), LOOP_LIMIT); @@ -500,115 +1028,11 @@ mod tests { assert_eq!(parse_loop_limit(Some(bad)), LOOP_LIMIT, "{bad:?}"); } } - - #[test] - fn the_spin_limit_parses_with_its_own_default() { - use super::{DEFAULT_SPIN_LIMIT, parse_limit}; - assert_eq!(parse_limit(None, DEFAULT_SPIN_LIMIT), 4096); - assert_eq!(parse_limit(Some("0x40"), DEFAULT_SPIN_LIMIT), 64); - assert_eq!(parse_limit(Some("0"), DEFAULT_SPIN_LIMIT), 4096); - } - use super::container::SigElement; - #[cfg(windows)] use super::shader::Shader; use super::*; use crate::native::{ComputeIo, StageIo}; - /// Emits a pixel program that writes depth and stencil from `v0` and `v1`. - fn emit_depth_stencil_ps(words: &[u32], wave64: bool) -> Result<(), crate::ShaderError> { - let native = NativeProgram { - stage: HwStage::Ps, - wave64, - vgprs: 2, - layout: vec![], - used: vec![], - io: StageIo::Ps { - inputs: vec![], - input_addr: 0, - db_shader_control: 0, - patches: vec![], - }, - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let el = |name: &str, kind, comp| SigElement { - name: name.into(), - index: 0, - kind, - comp, - interp: 0, - row: None, - col: 0, - cols: 1, - usage: 1, - half: false, - }; - let osg1 = - container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false); - let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); - let c = Container::parse(&bytes).unwrap(); - let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - let _out = emit(&c, &native, &p, &st, &io, &res)?; - #[cfg(windows)] - if let Ok(mut v) = super::validator::Validator::load( - super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut _out.dxil.clone()).unwrap(); - } - Ok(()) - } - - /// A wave64 pixel program whose SGPR holds a lane mask's high dword (a compare result) on one - /// path and a number on the other, then compares it with zero: the - /// join's mask side was a lane mask read as data, which refused the - /// whole program. The ballot stands in for it (wave-size independent for - /// the zero test the console compiler emits). - #[test] - fn a_scalar_joining_a_lane_mask_and_a_number_lowers_in_pixel_programs() { - let words = [ - 0x7E00_02F2u32, // v_mov_b32 v0, 1.0 - 0xD405_000A, // v_cmp_lg_f32_e64 s[10:11], v0, 0 - 0x0001_0100, - 0xBE8C_0383, // s_mov_b32 s12, 3 - 0xBF02_850C, // s_cmp_gt_i32 s12, 5 - 0xBF85_0001, // s_cbranch_scc1 +1 (past the next word) - 0xBE8B_0385, // s_mov_b32 s11, 5 - 0xBF06_800B, // s_cmp_eq_u32 s11, 0 - 0x850D_8081, // s_cselect_b32 s13, 1, 0 - 0x7E02_020D, // v_mov_b32 v1, s13 - 0xF800_1883, // exp mrtz v0, v1, off, off done vm - 0x0000_0100, - 0xBF81_0000, // s_endpgm - ]; - emit_depth_stencil_ps(&words, true).unwrap(); - } - - /// A lane mask spilled into a VGPR lane (`v_writelane_b32`) and restored - /// into another SGPR (`v_readlane_b32`, same constant lane) is the same - /// mask: the select below followed it as an untracked one and refused. - #[test] - fn a_lane_mask_spilled_to_a_vgpr_lane_stays_a_mask() { - let words = [ - 0x7E00_02F2u32, // v_mov_b32 v0, 1.0 - 0xD405_000A, // v_cmp_lg_f32_e64 s10, v0, 0 - 0x0001_0100, - 0xD761_0001, // v_writelane_b32 v1, s10, 0 - 0x0001_000A, - 0xD760_000C, // v_readlane_b32 s12, v1, 0 - 0x0001_0101, - 0xD501_0002, // v_cndmask_b32_e64 v2, 0, 1, s12 - 0x0031_0280, - 0x7E02_0302, // v_mov_b32 v1, v2 - 0xF800_1883, // exp mrtz v0, v1, off, off done vm - 0x0000_0100, - 0xBF81_0000, // s_endpgm - ]; - emit_depth_stencil_ps(&words, false).unwrap(); - } - /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`). /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose /// output signature has SV_StencilRef, and the feature bit @@ -672,11 +1096,12 @@ mod tests { } /// A wave64 compute program that writes only EXEC's high dword - /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is + /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was /// opaque and keyed by the unchanged low dword, so building its lane bit /// needed the mask's own value: lowering recursed until the stack /// overflowed, which takes the whole process down (found by - /// random-input testing). Now the instruction fails like any other that + /// random-input testing). Now that low dword, seen with two high + /// dwords, has no mask, and the instruction fails like any other that /// cannot be expressed: its result is missing, and only a side effect /// that uses it would stop the translation. #[test] @@ -706,6 +1131,149 @@ mod tests { } } + /// A wave64 compute program: `body`, then a store of v1 to a UAV. + fn stores_v1(body: &[u32]) -> Result<(), ShaderError> { + use crate::native::RootParam; + use crate::{ResourceType, RootType, UsedResource}; + // s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0 + let mut words = vec![0xBE81_0380, 0xF408_0200, 0xFA00_0000]; + words.extend_from_slice(body); + // v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen; + // s_endpgm + words.extend_from_slice(&[0x3406_0082, 0xE070_1000, 0x8002_0103, 0xBF81_0000]); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 4, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 2, + threads: [64, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let container = crate::dxbc::build(&[]); + let c = Container::parse(&container).unwrap(); + emit(&c, &native, &p, &st, &io, &res).map(|_| ()) + } + + /// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi` + /// or `exec_hi`): lanes 32-63 took the mask the low dword was first + /// written with (the compare's, EXEC's on entry). Now the store refuses; + /// without the write it translates. + #[test] + fn a_mask_whose_high_dword_is_rewritten_is_refused() { + // v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc + let select = [0x7D84_0080, 0x7E04_028B, 0x0202_0480]; + // The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc. + let carry = [0x7D84_0080, 0x7E04_028B, 0x5002_0480]; + // v_mov_b32 v1, 7 + let mov = [0x7E02_0287]; + for body in [&select[..], &carry, &mov] { + stores_v1(body).unwrap(); + } + // s_mov_b32 vcc_hi, 0 after the compare. + let select_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x0202_0480]; + let carry_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x5002_0480]; + // s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after + // s_mov_b64 s[2:3], exec. + let exec_hi = [0xBEFF_0380, 0x7E02_0287]; + let exec_hi_saved = [0xBE82_047E, 0xBEFF_0380, 0x7E02_0287]; + for body in [&select_hi[..], &carry_hi, &exec_hi, &exec_hi_saved] { + assert!(stores_v1(body).is_err(), "{body:x?}"); + } + } + + /// `ds_bpermute_b32` stores nothing: each lane reads the lane its address + /// names. It stopped as "LDS the program does not allocate" (sticky lips) + /// or "an LDS operation" (the checkerboard shadow masks). + #[test] + fn a_backward_permute_reads_the_lane_its_address_names() { + // v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2 + stores_v1(&[0x7E04_028B, 0xDACC_0000, 0x0100_0200]).unwrap(); + } + + /// A carry-in reading a join of compares after a divergent branch. A + /// lane that skipped the inner compare has VCC clear there (VOPC clears + /// inactive lanes), not the first compare's bit, so the join is no + /// per-lane phi: lowering refuses it. + #[test] + fn a_carry_in_from_a_divergent_join_is_refused() { + let body = [ + 0x7E04_028B, // v_mov_b32 v2, 11 + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE82_376A, // s_andn1_saveexec_b64 s[2:3], vcc + 0xBF88_0001, // s_cbranch_execz 1 + 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0 + 0x88FE_027E, // s_or_b64 exec, exec, s[2:3] + 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc + ]; + let e = stores_v1(&body).unwrap_err().to_string(); + assert!(e.contains("a carry-in from an untracked mask"), "{e}"); + } + + /// A wave64 compute program reading SCC of a mask operation (`scc_some`) + /// inside a divergent per-lane branch on a 32-lane host: exchanging the + /// two halves' answers needs every lane there, so `emit` falls back to + /// `with_local_waves_any` and takes each host wave's `WaveAnyTrue`. + #[test] + fn scc_some_in_a_divergent_branch_lowers_per_host_wave_on_wave32() { + // Direct read (`s_and_b64` -> `s_cselect_b32`) and scalar-skip phi join + // inside a per-lane divergent branch (`s_and_saveexec_b64`). + let direct = [ + 0x7E02_0287, // v_mov_b32 v1, 7 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE82_246A, // s_and_saveexec_b64 s[2:3], vcc + 0xBF88_0004, // s_cbranch_execz 4 + 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0 + 0x8784_6A7E, // s_and_b64 s[4:5], exec, vcc (sets SCC in scc_some) + 0x8506_8789, // s_cselect_b32 s6, 9, 7 + 0x7E02_0206, // v_mov_b32 v1, s6 + 0xBEFE_0402, // s_mov_b64 exec, s[2:3] + ]; + let joined = [ + 0x7E02_0287, // v_mov_b32 v1, 7 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE82_246A, // s_and_saveexec_b64 s[2:3], vcc + 0xBF88_0006, // s_cbranch_execz 6 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF84_0002, // s_cbranch_scc0 2 (uniform skip, SCC = 0) + 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0 + 0x8784_6A7E, // s_and_b64 s[4:5], exec, vcc (sets SCC in scc_some) + 0x8506_8789, // s_cselect_b32 s6, 9, 7 (reads joined SCC phi) + 0x7E02_0206, // v_mov_b32 v1, s6 + 0xBEFE_0402, // s_mov_b64 exec, s[2:3] + ]; + for body in [&direct[..], &joined[..]] { + stores_v1(body).unwrap(); + lower::TEST_HOST_WAVE.set(Some(32)); + let res = stores_v1(body); + lower::TEST_HOST_WAVE.set(None); + res.unwrap(); + } + } + /// A pixel shader writing a constant colour. #[cfg(windows)] fn constant_color() -> Vec<u8> { @@ -751,6 +1319,9 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -761,6 +1332,9 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); @@ -867,7 +1441,8 @@ mod tests { let c = super::Container::parse(&bytes).unwrap(); let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); let st = crate::structure::structure(&p).unwrap(); - let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let res = + crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); let io = crate::io::raise(&p, &native).unwrap(); let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); // dxil.dll, where there is one, checks PSV0 against the module. @@ -942,47 +1517,56 @@ mod tests { let _ = super::emit(&c, &native, &p, &st, &io, &res); } + /// `s_buffer_load_dwordx4`, `x8` and `x16` from a raw SRV read the dwords + /// the console's range-checked load reads, a call a dword or + /// (`VICTORY_SHADER_OPT` with 64) a call for every four: also where a + /// call's four dwords lie across the view's end (the dwords out of it + /// are 0, the others are read). On the software adapter only: run the + /// test once plain and once with `VICTORY_SHADER_OPT=127`. #[test] - fn scalar_bitcmp_and_sext_execute_on_gpu() { - let words: &[u32] = &[ + #[cfg(windows)] + fn scalar_buffer_loads_read_the_same_dwords_one_call_or_four() { + // (first register, dwords) of the three loads, in order. + const LOADS: [(u32, u32); 3] = [(16, 8), (24, 4), (32, 16)]; + let mut words: Vec<u32> = vec![ 0xBE85_0380, // s_mov_b32 s5, 0 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 - 0xBF0C_8000, // s_bitcmp0_b32 s0, 0 - 0x850C_8081, // s_cselect_b32 s12, 1, 0 - 0xBF0D_A100, // s_bitcmp1_b32 s0, 33 - 0x850D_8081, // s_cselect_b32 s13, 1, 0 - 0xBF0E_A200, // s_bitcmp0_b64 s[0:1], 34 - 0x850E_8081, // s_cselect_b32 s14, 1, 0 - 0xBF0F_BF00, // s_bitcmp1_b64 s[0:1], 63 - 0x850F_8081, // s_cselect_b32 s15, 1, 0 - 0xBF0F_BFC1, // s_bitcmp1_b64 -1, 63 - 0x8510_8081, // s_cselect_b32 s16, 1, 0 - 0xBE91_1902, // s_sext_i32_i8 s17, s2 - 0xBE92_1A03, // s_sext_i32_i16 s18, s3 - 0xBF0D_9F00, // s_bitcmp1_b32 s0, 31 - 0xBE94_1903, // s_sext_i32_i8 s20, s3 (must preserve SCC) - 0x8513_8014, // s_cselect_b32 s19, s20, 0 - 0x7E00_020C, // v_mov_b32 v0, s12 - 0x7E02_020D, // v_mov_b32 v1, s13 - 0x7E04_020E, // v_mov_b32 v2, s14 - 0x7E06_020F, // v_mov_b32 v3, s15 - 0x7E08_0280, // v_mov_b32 v4, 0 - 0xE078_1000, - 0x8002_0004, // buffer_store_dwordx4 v[0:3], v4, s[8:11], 0 offen - 0x7E00_0210, // v_mov_b32 v0, s16 - 0x7E02_0211, // v_mov_b32 v1, s17 - 0x7E04_0212, // v_mov_b32 v2, s18 - 0x7E06_0213, // v_mov_b32 v3, s19 - 0x7E08_0290, // v_mov_b32 v4, 16 - 0xE078_1000, - 0x8002_0004, // buffer_store_dwordx4 v[0:3], v4, s[8:11], 0 offen - 0xBF81_0000, // s_endpgm + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 (the SRV) + 0xF408_0302, + 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 (the UAV) + 0xF42C_0404, + 0x0000_0000, // s_buffer_load_dwordx8 s[16:23], s[8:11], s0 + 0xF428_0604, + 0xFA00_0008, // s_buffer_load_dwordx4 s[24:27], s[8:11], 0x8 + 0xF430_0804, + 0x0200_0004, // s_buffer_load_dwordx16 s[32:47], s[8:11], s1, 0x4 ]; - let native = crate::NativeProgram { - stage: crate::HwStage::Cs, + let mut out_dword = 0u32; + for (first, n) in LOADS { + for k in 0..n { + // v_mov_b32 v1, s<first + k> + words.push(0x7E00_0000 | 1 << 17 | 0x001 << 9 | (first + k)); + // buffer_store_dword v1, s[12:15], offset 4 * out_dword + words.push(0x38 << 26 | 0x1C << 18 | (4 * out_dword)); + words.push(0x80 << 24 | (12 >> 2) << 16 | 1 << 8); + out_dword += 1; + } + } + words.push(0xBF81_0000); // s_endpgm + let table = |kind, at| crate::UsedResource { + kind, + root: crate::RootType::Table, + table_offset_dwords: at, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }; + let native = super::NativeProgram { + stage: super::HwStage::Cs, wave64: false, - vgprs: 5, + vgprs: 4, layout: vec![ crate::RootParam { root: crate::RootType::Constants, @@ -1001,16 +1585,7 @@ mod tests { slot: 1, }, ], - used: vec![crate::UsedResource { - kind: crate::ResourceType::Uav, - root: crate::RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 4, - slot: 1, - }], + used: vec![table(crate::ResourceType::Srv, 0), table(crate::ResourceType::Uav, 8)], io: crate::native::StageIo::Cs(crate::native::ComputeIo { rsrc2: 5 << 1, threads: [1, 1, 1], @@ -1031,370 +1606,235 @@ mod tests { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - host_wave64: true, }) .unwrap(); - // Only the validator and the host (Windows) read the DXIL. - #[cfg_attr(not(windows), allow(unused_mut, unused_variables))] + // The calls that read the SRV: 28 a dword, 7 with four a call. + let wide = shader_opt() & super::bitcode::opt::WIDE != 0; let mut dxil = l.dxil; - #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( super::validator::Validator::default_path().as_deref(), ) { v.validate(&mut dxil).unwrap(); } - #[cfg(windows)] - if let Ok(host) = super::host::Host::new(false) { - let cs = super::HostShader { - stage: crate::HwStage::Cs, - dxil, - user_data: l.user_data, - samplers: Vec::new(), - static_samplers: Vec::new(), - root_cbvs: l.root_cbvs, - root_srvs: l.root_srvs, - }; - let (root, pso) = host.compute_pipeline(&cs).unwrap(); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = super::host::Host::new(true) else { + eprintln!("no software adapter; the dispatch is skipped"); + return; + }; + let cs = super::HostShader { + stage: super::HwStage::Cs, + dxil, + user_data: l.user_data, + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + root_indexed_views: Vec::new(), + half_views: l.half_views, + }; + let (root, pso) = host.compute_pipeline(&cs).unwrap(); + // Twelve dwords: the loads below run across the view's end. + let data: Vec<u32> = (0..12u32).map(|i| 0x1111_1111u32.wrapping_mul(i + 1) ^ 0x8000_0000).collect(); + let dword = |byte: u64| -> u32 { + if byte.is_multiple_of(4) && byte + 4 <= 4 * data.len() as u64 { data[(byte / 4) as usize] } else { 0 } + }; + for (s0, s1) in [(0u32, 0u32), (16, 0), (24, 4), (40, 28), (48, 44), (8, 12)] { let out = host .dispatch( &root, &pso, &super::host::Dispatch { - roots: vec![( - 0, - super::host::Root::Constants(vec![ - 0x8000_0002, - 0x8000_0004, - 0x1234_5680, - 0x1234_807F, - 0, - ]), - )], - views: &[super::host::View::RawUav(64)], + roots: vec![(0, super::host::Root::Constants(vec![s0, s1, 0, 0, 0]))], + views: &[ + super::host::View::Buffer { + data: &data, + stride: super::host::Stride::Raw, + }, + super::host::View::RawUav(32), + ], samplers: &[], groups: [1, 1, 1], }, ) .unwrap(); - assert_eq!( - &out[0][..8], - &[1, 1, 0, 1, 1, 0xFFFF_FF80, 0xFFFF_807F, 0x7F] - ); + let starts = [u64::from(s0), 8, u64::from(s1) + 4]; + let mut want = Vec::new(); + for (&(_, n), start) in LOADS.iter().zip(starts) { + want.extend((0..u64::from(n)).map(|k| dword(start + 4 * k))); + } + eprintln!("offsets {s0} and {s1}, four dwords a call: {wide}: {:x?}", &out[0][..28]); + assert_eq!(out[0][..28], want[..], "offsets {s0} and {s1}, four dwords a call: {wide}"); } } - /// Translates a one-lane compute program that copies root constants - /// s0..s3 to v1..v4, runs `body` and stores v0 to a raw UAV (the frame - /// of the GPU tests in `valu_tests`), so a value `body` cannot produce - /// stops the translation. - fn translate_stored(body: &[u32]) -> Result<HostShader, ShaderError> { - translate_stored_with(body, &[]) - } - - /// [`translate_stored`] with more resources of the table declared. - fn translate_stored_with( - body: &[u32], - more: &[crate::native::UsedResource], - ) -> Result<HostShader, ShaderError> { - use crate::native::{ResourceType, RootParam, UsedResource}; - let mut words = vec![ + #[test] + fn valu_div_f32_sequence_executes_on_gpu() { + let words: &[u32] = &[ 0xBE85_0380, // s_mov_b32 s5, 0 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 + 0xF408_0302, + 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 + 0x340E_0083, // v_lshlrev_b32 v7, 3, v0 + 0xE034_1000, + 0x8002_0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen + 0xD56D_6A03, + 0x0406_0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1 + 0xD56D_1008, + 0x0406_0501, // v_div_scale_f32 v8, s16, v1, v2, v1 + 0x7E08_5503, // v_rcp_f32 v4, v3 + 0xD54B_0005, + 0x23CA_0903, // v_fma_f32 v5, -v3, v4, 1.0 + 0xD54B_0004, + 0x0412_0905, // v_fma_f32 v4, v5, v4, v4 + 0x100A_0908, // v_mul_f32 v5, v8, v4 + 0xD54B_0006, + 0x2422_0B03, // v_fma_f32 v6, -v3, v5, v8 + 0xD56F_0004, + 0x0416_0906, // v_div_fmas_f32 v4, v6, v4, v5 + 0xD55F_0001, + 0x0406_0504, // v_div_fixup_f32 v1, v4, v2, v1 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0xE070_1000, + 0x8003_0107, // buffer_store_dword v1, v7, s[12:15], 0 offen + 0xBF81_0000, // s_endpgm ]; - for i in 0..4 { - words.push(0x7E00_0200 | (i + 1) << 17 | i); // v_mov_b32 v(i+1), s(i) - } - words.extend_from_slice(body); - // buffer_store_dword v0, off, s[8:11], 0; s_endpgm - words.extend_from_slice(&[0xE070_0000, 0x8002_0000, 0xBF81_0000]); - let param = |root, sgprs, user_data, slot| RootParam { - root, - table_offset_dwords: 0, - sgprs, - base_register: 0, - user_data, - slot, - }; - let native = NativeProgram { - stage: HwStage::Cs, + let native = super::NativeProgram { + stage: super::HwStage::Cs, wave64: false, - vgprs: 8, + vgprs: 9, layout: vec![ - param(RootType::Constants, 4, 0, 0), - param(RootType::Table, 1, 4, 1), + crate::RootParam { + root: crate::RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + crate::RootParam { + root: crate::RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, ], - used: [UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 4, - slot: 1, - }] - .into_iter() - .chain(more.iter().cloned()) - .collect(), - io: StageIo::Cs(ComputeIo { + used: vec![ + crate::UsedResource { + kind: crate::ResourceType::Srv, + root: crate::RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }, + crate::UsedResource { + kind: crate::ResourceType::Uav, + root: crate::RootType::Table, + table_offset_dwords: 8, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }, + ], + io: crate::native::StageIo::Cs(crate::native::ComputeIo { rsrc2: 5 << 1, - threads: [1, 1, 1], + threads: [7, 1, 1], }), code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), }; - let p = ir::build(&native.code, native.wave64, native.vgprs)?; - let st = structure::structure(&p)?; - let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, &native)?; - let container = crate::dxbc::build(&[]); - let c = Container::parse(&container).unwrap(); - emit(&c, &native, &p, &st, &io, &res) - } - - /// A view the program only measures takes its kind from the table's - /// range: a structured buffer's or a storage image's size, read as - /// data and never used here, translates. - #[test] - fn descriptor_read_only_as_data_takes_its_kind_from_the_range() { - use crate::native::{ResourceType, UsedResource}; - let range = |kind, dwords, stride| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords: 4, - lower_bound: 1, - stride, - dwords, - user_data: 4, - slot: 1, - }; - // s_load_dwordx4 s[12:15], s[4:5], 16; v_mov_b32 v0, s14 (records) - let buffer = [0xF408_0302, 0xFA00_0010, 0x7E00_020E]; - translate_stored_with(&buffer, &[range(ResourceType::Srv, 4, 16)]).unwrap(); - translate_stored_with(&buffer, &[range(ResourceType::Uav, 4, 0)]).unwrap(); - // s_load_dwordx8 s[12:19], s[4:5], 16; v_mov_b32 v0, s14 (height) - let image = [0xF40C_0302, 0xFA00_0010, 0x7E00_020E]; - translate_stored_with(&image, &[range(ResourceType::Uav, 8, 0)]).unwrap(); - } - - /// Selects and carry-ins whose mask `structure` does not follow (a plain - /// SGPR, here a root constant) translate: compute tests this lane's bit - /// of the number. Inline 0 and -1 masks are constants. - #[test] - fn untracked_select_and_carry_masks_translate() { - let vop3 = |op: u32, sdst: u32, s0: u32, s1: u32, s2: u32| { - [0xD400_0000 | op << 16 | sdst << 8, s0 | s1 << 9 | s2 << 18] - }; - let (v1, v2, s3) = (257, 258, 3); - for mask in [s3, 128, 193] { - // v_cndmask_b32_e64 v0, v1, v2, mask - translate_stored(&vop3(0x101, 0, v1, v2, mask)).unwrap(); - // v_add_co_ci_u32_e64 v0, null, v1, v2, mask (and sub, subrev) - for op in [0x128, 0x129, 0x12A] { - translate_stored(&vop3(op, 125, v1, v2, mask)).unwrap(); - } - } - } - - /// The 64-bit multiply-adds of 32-bit operands translate, both halves - /// of the result and the unsigned form's carry; reading the signed - /// form's carry, which is not modelled, is refused with a reason. - #[test] - fn mad_64_of_32_bit_operands_translates() { - for op in [0x176u32, 0x177] { - // v_mad_{u64_u32,i64_i32} v[5:6], vcc_lo, v1, v2, v[3:4] - let mad = [0xD400_6A05 | op << 16, 0x040E_0501]; - for mov in [0x7E00_0305, 0x7E00_0306] { - // v_mov_b32 v0, v5 / v6 - translate_stored(&[mad[0], mad[1], mov]).unwrap(); - } - // v_cndmask_b32 v0, 0, 1, vcc_lo - let carry = translate_stored(&[mad[0], mad[1], 0xD501_0000, 0x01A9_0280]); - if op == 0x176 { - carry.unwrap(); - } else { - assert!( - matches!(carry, Err(ShaderError::Unsupported { .. })), - "{carry:?}" - ); - } - } - } - - /// v_ldexp_f32, v_frexp_mant_f32 and v_frexp_exp_i32_f32 translate. - #[test] - fn ldexp_and_frexp_translate() { - // v_ldexp_f32 v0, v1, v2 - translate_stored(&[0xD762_0000, 0x0002_0501]).unwrap(); - // v_frexp_mant_f32 v0, v1; v_frexp_exp_i32_f32 v0, v1 - translate_stored(&[0x7E00_8101]).unwrap(); - translate_stored(&[0x7E00_7F01]).unwrap(); - // VOP3 forms with |v1| and -v1. - translate_stored(&[0xD5C0_0100, 0x0000_0101]).unwrap(); - translate_stored(&[0xD5BF_0000, 0x2000_0101]).unwrap(); - } - - #[test] - fn a_conditional_pixel_export_is_guarded() { - // Only lanes for which v0 is zero export a colour. This is not the - // final `done` export, so inactive lanes must keep their old output. - let words: [u32; 6] = [ - 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 - 0xBE80_3C6A, // s_and_saveexec_b32 s0, vcc_lo - 0xF800_000F, - 0x0302_0102, // exp mrt0, v2, v1, v2, v3 - 0x887E_007E, // s_or_b32 exec_lo, exec_lo, s0 - 0xBF81_0000, // s_endpgm - ]; - let native = super::NativeProgram { - stage: super::HwStage::Ps, - wave64: false, - vgprs: 4, - layout: vec![], - used: vec![], - io: crate::native::StageIo::Ps { - inputs: vec![], - input_addr: 1 << 8, - db_shader_control: 0, - patches: vec![], - }, - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let position = SigElement { - name: "SV_Position".into(), - index: 0, - kind: 3, - comp: 9, - interp: 4, - row: Some(0), - col: 0, - cols: 4, - usage: 1, - half: false, - }; - let target = SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 15, - half: false, - }; - let isg1 = super::container::signature(&[position], true); - let osg1 = super::container::signature(&[target], false); - let bytes = - crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]); - let c = super::Container::parse(&bytes).unwrap(); - let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); let io = crate::io::raise(&p, &native).unwrap(); let st = crate::structure::structure(&p).unwrap(); - let emitted = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); - + let l = super::lower::lower(&super::lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .unwrap(); + let mut dxil = l.dxil; #[cfg(windows)] if let Ok(mut v) = super::validator::Validator::load( super::validator::Validator::default_path().as_deref(), ) { - v.validate(&mut emitted.dxil.clone()).unwrap(); + v.validate(&mut dxil).unwrap(); } - #[cfg(not(windows))] - drop(emitted); - } - - /// `v_interp_p1ll_f16` writes all 32 bits; it does not preserve the old - /// high half. When a paired p2 represents the interpolation, a following - /// mixed-precision FMA must therefore zero an unavailable preserved half, - /// not resurrect bits from before p1ll. Cover both result halves. - #[test] - fn mixed_precision_fmas_accept_an_unavailable_interpolation_half() { - fn translate(opcode: u32) { - let words = [ - 0x7E10_0280u32, // v_mov_b32 v8, 0 - 0x7E20_0280, // v_mov_b32 v16, 0 - 0x7E16_02FF, - 0xFFFF_0000, // v_mov_b32 v11, 0xffff0000 - 0xD742_000B, - 0x0002_0102, // v_interp_p1ll_f16 v11, v0, attr2.x high - 0xD75A_000F, - 0x042E_0302, // v_interp_p2_f16 v15, v1, attr2.x, v11 high - opcode, - 0x0A02_2108, // v_fma_mix{lo,hi}_f16 v11, sel_lo(v8), v16, 0 - 0xF800_1801, - 0x0000_000B, // exp mrt0, v11, off, off, off done vm - 0xBF81_0000, // s_endpgm - ]; - let native = NativeProgram { - stage: HwStage::Ps, - wave64: false, - vgprs: 17, - layout: vec![], - used: vec![], - io: StageIo::Ps { - inputs: vec![crate::native::PsInput { - usage: crate::native::Usage::Generic, - row: 2, - mask: 3, - attr: 2, - flat: false, - fp16: true, - pack2: true, - row2: 2, - }], - input_addr: 2, - db_shader_control: 0, - patches: vec![], - }, - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let input = SigElement { - name: "TEXCOORD".into(), - index: 0, - kind: 0, - comp: 9, - interp: 0, - row: Some(2), - col: 0, - cols: 2, - usage: 0, - half: false, - }; - let output = SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 1, - usage: 1, - half: false, + #[cfg(windows)] + if let Ok(host) = super::host::Host::new(false) { + let cs = super::HostShader { + stage: super::HwStage::Cs, + dxil, + user_data: l.user_data, + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + root_indexed_views: Vec::new(), + half_views: l.half_views, }; - let isg1 = super::container::signature(&[input], true); - let osg1 = super::container::signature(&[output], false); - let bytes = - crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]); - let c = Container::parse(&bytes).unwrap(); - let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); - let io = io::raise(&p, &native).unwrap(); - let st = structure::structure(&p).unwrap(); - #[cfg_attr(not(windows), allow(unused_mut, unused_variables))] - let mut host = emit(&c, &native, &p, &st, &io, &res).unwrap(); - #[cfg(windows)] - if let Ok(mut v) = super::validator::Validator::load( - super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut host.dxil).unwrap(); - } - } - - for opcode in [0xCC21_000B, 0xCC22_000B] { - translate(opcode); + let (root, pso) = host.compute_pipeline(&cs).unwrap(); + let inputs: Vec<u32> = [ + 7.0f32, 3.0, -1.0, 1e-40, 1.0, 1e35, 1e-35, 1e-36, 0.0, 0.0, -1.0, 0.0, -1e35, 1e35, + ] + .into_iter() + .map(f32::to_bits) + .collect(); + let out = host + .dispatch( + &root, + &pso, + &super::host::Dispatch { + roots: vec![(0, super::host::Root::Constants(vec![0, 0, 0, 0, 0]))], + views: &[ + super::host::View::Buffer { + data: &inputs, + stride: super::host::Stride::Raw, + }, + super::host::View::RawUav(64), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let got: Vec<f32> = out[0][..7].iter().copied().map(f32::from_bits).collect(); + assert!((got[0] - (7.0f32 / 3.0)).abs() < 1e-6, "got {:?}", got); + assert_eq!(out[0][1], (-1.0f32 / 1e-40).to_bits()); + assert!( + (got[2] - 1e-35).abs() <= 1e-40, + "lane 2 got {:?} ({:#x})", + got[2], + out[0][2] + ); + assert!( + (got[3] - 10.0).abs() < 1e-5, + "lane 3 got {:?} ({:#x})", + got[3], + out[0][3] + ); + assert_eq!(out[0][4], 0xFFC0_0000); + assert_eq!(out[0][5], (-1.0f32 / 0.0).to_bits()); + assert!( + (got[6] - (-1.0)).abs() < 1e-6, + "lane 6 got {:?} ({:#x})", + got[6], + out[0][6] + ); } } } @@ -1481,3 +1921,275 @@ mod atomic_tests { } } } + +#[cfg(test)] +mod barycentric_tests { + use super::container::SigElement; + use super::*; + use crate::native::{PsInput, StageIo, Usage}; + + /// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER. + const PERSP_CENTER: u32 = 1 << 1; + const LINEAR_CENTER: u32 = 1 << 5; + + /// `exp mrt0, v<r>, v<r>, v<r>, v<r> done vm`. + fn exp_mrt0(r: u32) -> [u32; 2] { + [0xF800_180F, r * 0x0101_0101] + } + + /// VOP2 `v_add_f32 v<dst>, v<a>, v<b>`. + fn v_add_f32(dst: u32, a: u32, b: u32) -> u32 { + 3 << 25 | dst << 17 | b << 9 | (256 + a) + } + + fn element(name: &str, kind: u8, row: u32) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: 0, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: false, + } + } + + /// Translates a pixel program with the input VGPRs `input_addr` + /// enables and one float4 TEXCOORD0 attribute (attr 0, row 0). + fn pixel(words: &[u32], input_addr: u32) -> Result<HostShader, ShaderError> { + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![PsInput { + usage: Usage::Generic, + row: 0, + mask: 0b1111, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut target = element("SV_Target", 16, 0); + target.usage = 15; + let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true); + let osg1 = container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let res = resource::track(&p, &native.layout, native.stage, None)?; + let io = io::raise(&p, &native)?; + let st = structure::structure(&p)?; + emit(&c, &native, &p, &st, &io, &res) + } + + /// The translation's `SFI0` features and `ISG1` rows. + fn parts(shader: &HostShader) -> (u64, Vec<SigElement>) { + let c = Container::parse(&shader.dxil).unwrap(); + let sfi0 = c.part(FourCC::SFI0).unwrap().data.try_into().unwrap(); + ( + u64::from_le_bytes(sfi0), + signature(c.part(FourCC::ISG1).unwrap().data).unwrap(), + ) + } + + fn validate(shader: &HostShader) { + #[cfg(windows)] + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()).unwrap(); + } + let _ = shader; + } + + /// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as + /// plain floats: they are channels y and z of `SV_Barycentrics`, the + /// weights of vertices 1 and 2. + #[test] + fn barycentrics_read_as_values_are_sv_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + let bary: Vec<_> = inputs.iter().filter(|e| e.kind == 28).collect(); + assert_eq!(bary.len(), 1, "{inputs:?}"); + assert_eq!((bary[0].index, bary[0].col, bary[0].cols), (0, 0, 3)); + // Not packed: the validator wants packing location -1. + assert_eq!(bary[0].row, None); + // Only y and z (I and J) are read. + let isg1 = Container::parse(&shader.dxil).unwrap(); + let isg1 = isg1.part(FourCC::ISG1).unwrap().data; + let rw: Vec<u8> = (0..2).map(|k| isg1[8 + 32 * k + 25]).collect(); + assert!(rw.contains(&0b110), "{rw:?}"); + validate(&shader); + } + + /// Two kinds of barycentrics read directly: one element per mode. + #[test] + fn two_barycentric_modes_get_two_elements() { + // v0-v1 perspective i, j; v2-v3 linear i, j. + let [e0, e1] = exp_mrt0(4); + let words = [v_add_f32(4, 0, 3), e0, e1, 0xBF81_0000]; + let shader = pixel(&words, PERSP_CENTER | LINEAR_CENTER).unwrap(); + let (_, inputs) = parts(&shader); + let mut indices: Vec<u32> = inputs + .iter() + .filter(|e| e.kind == 28) + .map(|e| e.index) + .collect(); + indices.sort(); + assert_eq!(indices, [0, 1], "{inputs:?}"); + validate(&shader); + } + + /// I and J only fed to `v_interp_*` stay host interpolation: no + /// barycentrics are declared. + #[test] + fn interpolation_alone_declares_no_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + e0, + e1, + 0xBF81_0000, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_eq!(features & 0x2_0000, 0); + assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}"); + validate(&shader); + } + + /// Both: the attribute is interpolated and J is used as a value. + #[test] + fn interpolation_and_a_barycentric_value_together() { + let [e0, e1] = exp_mrt0(3); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + v_add_f32(3, 2, 1), // v3 = attribute + j + e0, + e1, + 0xBF81_0000, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + validate(&shader); + } + /// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float). + fn texcoord_mode(shader: &HostShader) -> u8 { + let c = Container::parse(&shader.dxil).unwrap(); + let psv = c.part(FourCC::PSV0).unwrap().data; + let row = [1, 0, 0x44, 0, 3]; + let at = psv.windows(5).position(|w| w == row).unwrap(); + psv[at + 5] + } + + const S_ENDPGM: u32 = 0xBF81_0000; + + /// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads + /// the attribute's vertices: TEXCOORD0 becomes constant, read with + /// `attributeAtVertex`; i and j are `SV_Barycentrics` values. + #[test] + fn computed_barycentrics_read_the_vertices() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0x1006_00F0, // v_mul_f32 v3, 0.5, v0 + 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// Weights from constants alone: the vertices, no `SV_Barycentrics`. + #[test] + fn constant_weights_need_no_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}"); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// The same attribute interpolated with the loaded i and j and with a + /// computed j: both from its vertices, the first weighed with + /// `SV_Barycentrics`. + #[test] + fn computed_and_loaded_barycentrics_on_one_attribute() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC810_0100, // v_interp_p1_f32 v4, v0, attr0.y + 0xC811_0101, // v_interp_p2_f32 v4, v1, attr0.y + 0x1006_02F0, // v_mul_f32 v3, 0.5, v1 + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (_, inputs) = parts(&shader); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// P10 of an attribute the program interpolates is P1 - P0. + #[test] + fn p10_of_an_interpolated_attribute() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xC812_0000, // v_interp_mov_f32 v4, p10, attr0.x + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + // Alone, what the hardware holds is not known. + let [e0, e1] = exp_mrt0(4); + let words = [0xC812_0000, e0, e1, S_ENDPGM]; + assert!(pixel(&words, PERSP_CENTER).is_err()); + } +} diff --git a/crates/victory-shader/src/emit/own_bits.rs b/crates/victory-shader/src/emit/own_bits.rs new file mode 100644 index 0000000000..64aaba8f56 --- /dev/null +++ b/crates/victory-shader/src/emit/own_bits.rs @@ -0,0 +1,914 @@ +//! Wave ORs that only steer a loop over each lane's own bits. +//! +//! The title's light loops are "scalarised": the lanes' light masks are ORed over the wave and +//! the wave walks the set bits of the result together, each lane working only where its own +//! mask has the bit: +//! +//! ```text +//! merged = WaveActiveBitOr(mask); // over the lanes that run +//! while (merged != 0) { +//! bit = firstbitlow(merged); +//! if (mask & (1 << bit)) { ... } // the body +//! merged ^= 1 << bit; +//! } +//! ``` +//! +//! A console wave64 program in two host waves of 32 cannot exchange the halves' ORs where not +//! every lane runs (a group barrier must be reached by every thread). It does not have to: as +//! one thread runs it, the loop visits the bits of `merged` in rising order and does something +//! only at the bits of the thread's own mask, so any `merged` that holds the thread's own bits +//! gives that thread the same run. The host wave's own OR is such a value. +//! +//! That holds only if the OR is used for nothing else, and if a round of the loop at a bit the +//! thread does not have leaves nothing behind. [`find`] proves both for each wave OR, with no +//! instruction sequence taken on trust: +//! +//! - the OR and what derives from it as "the bits still to visit" (copies, the loop's join, the +//! first-lane read of it, the set less the visited bit) are read only by the loop's own +//! steps: the test for an empty set, the lowest set bit, the removal of that bit, the test +//! that ends the loop; +//! - the lane's test is its own bit of the very value that was ORed, and "the body" is what a +//! lane only reaches with that test true in the same round; +//! - outside the body the loop has no side effect and no cross-lane step, writes nothing that +//! is read after the loop or carried into a later round, and is left only by the test for +//! "no bits left"; +//! - no lane mask that depends on the test is used outside the round that made it. +//! +//! Anything else is refused there as before ("a wave reduction where not every lane runs") and +//! left to the forms of the program in which every lane runs that code (`emit`'s retries: the +//! skips left out, the branches around it taken wave-wide), where the halves do exchange. +//! `VICTORY_WAVE_OWN_BITS=0` turns this off. + +use std::collections::{HashMap, HashSet}; + +use super::wave::{self, Op, Shape}; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; +use crate::structure::{Atom, Bool, LaneExit, Structured}; + +type Why = &'static str; + +const USED: Why = "a wave OR used as data"; +const NO_LOOP: Why = "a wave OR that steers no loop over its bits"; +const SHAPE: Why = "a loop over a wave OR's bits of another shape"; +const TEST: Why = "a loop over a wave OR's bits whose lanes do not test their own bit"; +const LEAVES: Why = "a value of a round over a wave OR's bits that outlives the round"; +const EFFECT: Why = "an effect in a loop over a wave OR's bits outside the lanes' own bits"; +const CROSS: Why = "a cross-lane step in a loop over a wave OR's bits outside the lanes' own bits"; +const EXIT: Why = "a loop over a wave OR's bits left another way"; +const STALE: Why = "a lane's own-bit test used outside its round"; +const MASK: Why = "a wave OR over a mask a running lane may be outside"; + +/// What [`find`] proved. +#[derive(Debug, Default)] +pub(super) struct OwnBits { + /// Wave ORs (the values their sections leave) a host wave may take over its own lanes. + pub totals: HashSet<Value>, + /// VGPR values of those loops that every lane of a host wave holds alike (the bits still + /// to visit): a first-lane read of one is the lane's own value. + pub alike: HashSet<Value>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum User { + Inst(usize, usize), + Phi(usize, usize), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Arg { + Val(Value), + K(u32), + Other, +} + +struct Ctx<'a> { + p: &'a Program, + st: &'a Structured, + users: HashMap<Value, Vec<User>>, + /// The instruction writing each value. + def: HashMap<Value, (usize, usize)>, + /// Values an instruction reads, directly or through joins. + live: HashSet<Value>, + idom: Vec<usize>, + sections: Vec<HashMap<usize, wave::Section>>, +} + +/// The values instruction `i` of block `b` uses: what its operands read, without EXEC (lane +/// masks are followed as booleans) and without the old value of a VGPR it writes, which only +/// lanes outside a guard keep. +fn used(p: &Program, st: &Structured, b: usize, i: usize) -> Vec<Value> { + let inst = &p.blocks[b].insts[i]; + let ops = crate::ir::operand_reads(p, inst); + let guarded = st.guards[b][i].is_some(); + inst.reads + .iter() + .filter(|&&(r, _)| match r { + Reg::S(c) if c == EXEC || c == EXEC + 1 => false, + Reg::V(_) => ops.contains(&r) || guarded, + _ => true, + }) + .map(|r| r.1) + .collect() +} + +fn value(inst: &Inst, op: &Operand) -> Option<Value> { + match *op { + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + _ => None, + } +} + +/// The sources of a scalar or unmodified vector operation. +fn args(inst: &Inst) -> Vec<Arg> { + let src: &[Operand] = match &inst.fields { + Fields::Sop { src, .. } => src, + Fields::Valu(v) + if v.dpp.is_none() + && v.sdwa.is_none() + && v.abs == 0 + && v.neg == 0 + && !v.clamp + && v.omod == 0 => + { + &v.src + } + _ => &[], + }; + src.iter() + .map(|o| match (value(inst, o), o) { + (Some(v), _) => Arg::Val(v), + (None, &Operand::Const(c)) => crate::resource::inline(c).map_or(Arg::Other, Arg::K), + (None, &Operand::Literal(x)) => Arg::K(x), + _ => Arg::Other, + }) + .collect() +} + +/// The other source of a two-source operation that reads `a`. +fn other(inst: &Inst, a: Value) -> Option<Arg> { + match args(inst)[..] { + [Arg::Val(x), o] if x == a => Some(o), + [o, Arg::Val(x)] if x == a => Some(o), + _ => None, + } +} + +/// The scalar (not SCC) or vector dword an instruction writes, if it writes one. +fn result(inst: &Inst) -> Option<Value> { + let mut w = inst.writes.iter().filter(|w| w.0 != Reg::Scc); + match (w.next(), w.next()) { + (Some(&(_, v)), None) => Some(v), + _ => None, + } +} + +/// The same test as `wave_local`'s and `Lower::inst`'s `effect`, and the messages a program +/// sends. +fn effect(inst: &Inst) -> bool { + let name = inst.name(); + matches!(inst.fields, Fields::Exp { .. }) + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || name.contains("store") + || name.contains("atomic") + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute")) + || matches!(name, "s_barrier" | "s_sendmsg" | "s_sendmsghalt") +} + +impl Ctx<'_> { + fn new<'a>(p: &'a Program, st: &'a Structured) -> Ctx<'a> { + let mut users: HashMap<Value, Vec<User>> = HashMap::new(); + let mut def = HashMap::new(); + let mut live: HashSet<Value> = HashSet::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (k, phi) in block.phis.iter().enumerate() { + for &a in &phi.args { + users.entry(a).or_default().push(User::Phi(b, k)); + } + } + for (i, inst) in block.insts.iter().enumerate() { + for v in used(p, st, b, i) { + users.entry(v).or_default().push(User::Inst(b, i)); + live.insert(v); + } + for &(_, w) in &inst.writes { + def.insert(w, (b, i)); + } + } + } + // through joins + let mut changed = true; + while changed { + changed = false; + for block in &p.blocks { + for phi in &block.phis { + if live.contains(&phi.value) { + for &a in &phi.args { + changed |= live.insert(a); + } + } + } + } + } + let order = crate::ir::reverse_postorder(&p.blocks); + let mut index = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + index[b] = n; + } + let idom = crate::ir::idoms(&p.blocks, &order, &index); + let sections = (0..p.blocks.len()).map(|b| wave::sections(p, b)).collect(); + Ctx { + p, + st, + users, + def, + live, + idom, + sections, + } + } + + fn inst(&self, u: (usize, usize)) -> &Inst { + &self.p.blocks[u.0].insts[u.1] + } + + fn at(&self, u: (usize, usize)) -> usize { + self.inst(u).machine.offset + } + + /// Whether block `a` dominates block `b`. + fn dominates(&self, a: usize, mut b: usize) -> bool { + loop { + if a == b { + return true; + } + let d = self.idom.get(b).copied().unwrap_or(usize::MAX); + if d == b || d == usize::MAX { + return false; + } + b = d; + } + } + + fn readers(&self, v: Value) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = self + .users + .get(&v) + .into_iter() + .flatten() + .filter_map(|u| match *u { + User::Inst(b, i) => Some((b, i)), + User::Phi(..) => None, + }) + .collect(); + out.sort_unstable(); + out.dedup(); + out + } + + /// The joins reading `v` whose value something reads. + fn joins(&self, v: Value) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = self + .users + .get(&v) + .into_iter() + .flatten() + .filter_map(|u| match *u { + User::Phi(b, k) if self.live.contains(&self.p.blocks[b].phis[k].value) => Some((b, k)), + _ => None, + }) + .collect(); + out.sort_unstable(); + out.dedup(); + out + } + + /// The loop of header `h`: the blocks that reach one of its back edges without passing it. + fn natural_loop(&self, h: usize) -> Vec<bool> { + let mut inside = vec![false; self.p.blocks.len()]; + let mut work: Vec<usize> = self.p.blocks[h] + .preds + .iter() + .copied() + .filter(|&q| self.dominates(h, q)) + .collect(); + if work.is_empty() { + return inside; + } + inside[h] = true; + while let Some(b) = work.pop() { + if inside[b] { + continue; + } + inside[b] = true; + work.extend(self.p.blocks[b].preds.iter().copied()); + } + inside + } + + /// Whether `b` holds only in lanes where `a` does. + fn implied(&self, b: Bool, a: Atom, memo: &mut HashMap<Bool, bool>) -> bool { + if b == Bool::FALSE { + return true; + } + if let Some(&r) = memo.get(&b) { + return r; + } + let r = match self.st.bools.node(b) { + None => false, + Some((x, lo, _)) if x == a => lo == Bool::FALSE, + Some((_, lo, hi)) => self.implied(lo, a, memo) && self.implied(hi, a, memo), + }; + memo.insert(b, r); + r + } + + /// The conditional branch reading `scc`, as (its place, the block it goes to when SCC is + /// set, the other one). + fn branch(&self, scc: Value) -> Option<((usize, usize), usize, usize)> { + let [u] = self.readers(scc)[..] else { + return None; + }; + let Exit::Branch { taken, not_taken } = self.p.blocks[u.0].exit else { + return None; + }; + if u.1 + 1 != self.p.blocks[u.0].insts.len() { + return None; + } + match self.inst(u).name() { + "s_cbranch_scc1" => Some((u, taken, not_taken)), + "s_cbranch_scc0" => Some((u, not_taken, taken)), + _ => None, + } + } + + /// One wave OR `t` of `x` over the lanes of `mask`, left by a section of block `sb`: the + /// VGPR values its loop keeps alike, or where and why it is not such a loop. + fn site(&self, sb: usize, t: Value, x: Value, mask: Value) -> Result<Vec<Value>, (usize, Why)> { + let p = self.p; + let st = self.st; + let n = p.blocks.len(); + let here = p.blocks[sb].offset; + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + // every lane that runs the section is one of the lanes ORed + let &mb = st.masks.get(&mask).ok_or((here, MASK))?; + if st.bools.meet(&[(st.reach[sb], true), (mb, false)]) { + return Err((here, MASK)); + } + // ---- the bits still to visit, and the loop's own steps ---- + let mut rem: HashSet<Value> = HashSet::from([t]); + let mut pattern: HashSet<(usize, usize)> = HashSet::new(); + let mut alike: Vec<Value> = Vec::new(); + // an unguarded copy + let copy = |u: (usize, usize)| -> Option<Value> { + let i = self.inst(u); + (matches!(i.name(), "v_mov_b32" | "s_mov_b32") && args(i).len() == 1 && st.guards[u.0][u.1].is_none()) + .then(|| result(i)) + .flatten() + }; + let mut init = vec![t]; + // (SCC, whether it is set when the OR is empty) + let mut zero: Option<(Value, bool)> = None; + for u in self.readers(t) { + let i = self.inst(u); + let name = i.name(); + if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32") + && other(i, t) == Some(Arg::K(0)) + && zero.is_none() + && let Some(scc) = i.write(Reg::Scc) + { + zero = Some((scc, name.contains("_eq_"))); + rem.insert(scc); + } else if let Some(w) = copy(u) { + init.push(w); + rem.insert(w); + if matches!(i.writes[0].0, Reg::V(_)) { + alike.push(w); + } + } else { + return Err((self.at(u), USED)); + } + pattern.insert(u); + } + // the loop's join of them + let mut join: Option<(usize, usize)> = None; + for &v in &init { + if v != t + && let Some(&u) = self.readers(v).first() + { + return Err((self.at(u), USED)); + } + for j in self.joins(v) { + if join.is_some_and(|q| q != j) { + return Err((p.blocks[j.0].offset, USED)); + } + join = Some(j); + } + } + let (h, k) = join.ok_or((here, NO_LOOP))?; + let phi = &p.blocks[h].phis[k]; + let r = phi.value; + rem.insert(r); + let head = p.blocks[h].offset; + let lp = self.natural_loop(h); + if !lp[h] || lp[sb] { + return Err((head, NO_LOOP)); + } + // the set as a scalar: the first lane's copy of it + let cur = if matches!(phi.reg, Reg::V(_)) { + alike.push(r); + let [u] = self.readers(r)[..] else { + return Err((head, USED)); + }; + let i = self.inst(u); + if i.name() != "v_readfirstlane_b32" || args(i).len() != 1 || !lp[u.0] { + return Err((self.at(u), USED)); + } + pattern.insert(u); + let c = result(i).ok_or((self.at(u), SHAPE))?; + if !self.joins(r).is_empty() { + return Err((head, USED)); + } + c + } else { + r + }; + rem.insert(cur); + // its lowest bit, the set without it, the tests for "that was the last" + let mut idx: Option<Value> = None; + let mut next: Option<(Value, Value)> = None; + // (SCC, whether it is set while bits remain) + let mut more: Vec<(Value, bool)> = Vec::new(); + let mut bits: Vec<Value> = Vec::new(); + for u in self.readers(cur) { + let i = self.inst(u); + let name = i.name(); + if !lp[u.0] { + return Err((self.at(u), USED)); + } + match (name, &args(i)[..]) { + ("s_ff1_i32_b32", [Arg::Val(_)]) if idx.is_none() => idx = result(i), + ("s_xor_b32", _) | ("s_andn2_b32", [Arg::Val(_), Arg::Val(_)]) if next.is_none() => { + let bit = match (name, &args(i)[..]) { + ("s_andn2_b32", [Arg::Val(c), Arg::Val(b)]) if *c == cur && *b != cur => *b, + ("s_xor_b32", _) => match other(i, cur) { + Some(Arg::Val(b)) if b != cur => b, + _ => return Err((self.at(u), USED)), + }, + _ => return Err((self.at(u), USED)), + }; + let w = result(i).ok_or((self.at(u), SHAPE))?; + next = Some((w, bit)); + bits.push(bit); + if let Some(scc) = i.write(Reg::Scc) { + more.push((scc, true)); + rem.insert(scc); + } + } + ("s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32", _) => { + let (Some(Arg::Val(b)), Some(scc)) = (other(i, cur), i.write(Reg::Scc)) else { + return Err((self.at(u), USED)); + }; + bits.push(b); + more.push((scc, name.contains("_lg_"))); + rem.insert(scc); + } + _ => return Err((self.at(u), USED)), + } + pattern.insert(u); + } + if cur != r && !self.joins(cur).is_empty() { + return Err((head, USED)); + } + let (Some(idx), Some((nx, bit))) = (idx, next) else { + return Err((head, SHAPE)); + }; + if bits.iter().any(|&b| b != bit) { + return Err((head, SHAPE)); + } + // the bit: 1 shifted by the lowest set bit's number (a shift takes five bits of it) + let made = |v: Value| self.def.get(&v).map(|&u| (u, self.inst(u))); + let shifted = match made(bit) { + Some((u, i)) if i.name() == "s_lshl_b32" && lp[u.0] => match args(i)[..] { + [Arg::K(1), Arg::Val(sh)] => Some(sh), + _ => None, + }, + _ => None, + }; + let by_idx = shifted.is_some_and(|sh| { + sh == idx + || made(sh).is_some_and(|(_, i)| i.name() == "s_and_b32" && other(i, idx) == Some(Arg::K(31))) + }); + if !by_idx { + return Err((head, SHAPE)); + } + // the set less the bit: back into the join, or tested for empty + rem.insert(nx); + let mut nexts = vec![nx]; + for u in self.readers(nx) { + let i = self.inst(u); + let name = i.name(); + if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32") + && other(i, nx) == Some(Arg::K(0)) + && let Some(scc) = i.write(Reg::Scc) + { + more.push((scc, name.contains("_lg_"))); + rem.insert(scc); + } else if let Some(w) = copy(u) { + nexts.push(w); + rem.insert(w); + if matches!(i.writes[0].0, Reg::V(_)) { + alike.push(w); + } + } else { + return Err((self.at(u), USED)); + } + pattern.insert(u); + } + for &v in &nexts { + if v != nx + && let Some(&u) = self.readers(v).first() + { + return Err((self.at(u), USED)); + } + if self.joins(v).iter().any(|&j| j != (h, k)) { + return Err((head, USED)); + } + } + for (q, a) in p.blocks[h].preds.iter().zip(&phi.args) { + let ok = if lp[*q] { nexts.contains(a) } else { init.contains(a) }; + if !ok { + return Err((head, SHAPE)); + } + } + // the loop goes on while bits remain and is left when none does + let mut leaves: HashSet<usize> = HashSet::new(); + for &(scc, set_while_more) in &more { + if !self.joins(scc).is_empty() { + return Err((head, USED)); + } + if self.readers(scc).is_empty() { + continue; + } + let (u, set, clear) = self.branch(scc).ok_or((head, USED))?; + let (on, out) = if set_while_more { (set, clear) } else { (clear, set) }; + if !lp[u.0] || !lp[on] || lp[out] { + return Err((self.at(u), SHAPE)); + } + leaves.insert(u.0); + pattern.insert(u); + } + if leaves.is_empty() { + return Err((head, SHAPE)); + } + // "no bit at all" skips the loop; what lies between that test and the loop runs only + // when there is one + let mut pre = vec![false; n]; + if let Some((scc, set_when_empty)) = zero { + if !self.joins(scc).is_empty() { + return Err((here, USED)); + } + if !self.readers(scc).is_empty() { + let (u, set, clear) = self.branch(scc).ok_or((here, USED))?; + let (none, some) = if set_when_empty { (set, clear) } else { (clear, set) }; + if none == some || lp[u.0] { + return Err((self.at(u), SHAPE)); + } + if some != h { + if p.blocks[some].preds[..] != [u.0] || !self.dominates(some, h) { + return Err((self.at(u), SHAPE)); + } + for b in 0..n { + pre[b] = self.dominates(some, b) && !self.dominates(h, b); + } + for b in (0..n).filter(|&b| pre[b]) { + let inside = match p.blocks[b].exit { + Exit::End | Exit::Indirect => false, + ref e => e.successors().iter().all(|&s| pre[s] || s == h), + }; + if !inside { + return Err((p.blocks[b].offset, SHAPE)); + } + } + } + pattern.insert(u); + } + } + // ---- the lane's test of its own bit ---- + // (the atom of the compare, its block, its index) + let mut tests: Vec<(Atom, usize, usize)> = Vec::new(); + for u in self.readers(bit) { + let i = self.inst(u); + if i.name() != "v_and_b32" || other(i, bit) != Some(Arg::Val(x)) || st.guards[u.0][u.1].is_some() { + continue; + } + let Some(y) = result(i) else { continue }; + for c in self.readers(y) { + let ci = self.inst(c); + if matches!( + ci.name(), + "v_cmp_ne_u32" | "v_cmpx_ne_u32" | "v_cmp_lg_u32" | "v_cmpx_lg_u32" | "v_cmp_ne_i32" | "v_cmpx_ne_i32" + | "v_cmp_lg_i32" | "v_cmpx_lg_i32" + ) && other(ci, y) == Some(Arg::K(0)) + && lp[c.0] + { + tests.extend(ci.writes.iter().map(|w| (Atom::Lane(w.1), c.0, c.1))); + } + } + } + if tests.is_empty() { + return Err((head, TEST)); + } + let mut memo: Vec<HashMap<Bool, bool>> = vec![HashMap::new(); tests.len()]; + // what a lane only reaches with its own bit set, in the round of that test + let mut body_block = vec![false; n]; + for b in (0..n).filter(|&b| lp[b]) { + body_block[b] = tests.iter().enumerate().any(|(j, &(a, tb, _))| { + b != tb && self.dominates(tb, b) && self.implied(st.reach[b], a, &mut memo[j]) + }); + } + let body_inst = |b: usize, i: usize, memo: &mut Vec<HashMap<Bool, bool>>| { + body_block[b] + || lp[b] + && st.guards[b][i].is_some_and(|g| { + tests.iter().enumerate().any(|(j, &(a, tb, ti))| { + (b == tb && i > ti || b != tb && self.dominates(tb, b)) && self.implied(g, a, &mut memo[j]) + }) + }) + }; + // ---- a round outside the body leaves nothing behind ---- + for b in (0..n).filter(|&b| lp[b] || pre[b]) { + for (i, inst) in p.blocks[b].insts.iter().enumerate() { + if lp[b] && body_inst(b, i, &mut memo) { + continue; + } + let u = (b, i); + for &(reg, w) in &inst.writes { + if rem.contains(&w) || is_mask(w) || matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) { + continue; + } + for user in self.users.get(&w).into_iter().flatten() { + let stays = match *user { + User::Inst(b2, _) => lp[b2] || pre[b2], + User::Phi(b2, k2) => { + body_block[b2] || !self.live.contains(&p.blocks[b2].phis[k2].value) + } + }; + if !stays { + return Err((self.at(u), LEAVES)); + } + } + } + if pattern.contains(&u) { + continue; + } + if effect(inst) { + return Err((self.at(u), EFFECT)); + } + let name = inst.name(); + let cross = name.starts_with("ds_swizzle") + || name.contains("permute") + || name.starts_with("v_mbcnt") + || name.contains("lane") + || matches!(&inst.fields, Fields::Valu(v) if v.dpp.is_some()) + || super::lower::reads_mask_as_data(st, inst) + || self.sections[b].iter().any(|(&s, sec)| i >= s && i <= sec.end); + if cross { + return Err((self.at(u), CROSS)); + } + if used(p, st, b, i).iter().any(|v| rem.contains(v)) { + return Err((self.at(u), USED)); + } + } + // left only by "no bits left"; the body may leave it as it likes + if lp[b] && !body_block[b] { + let ok = match p.blocks[b].exit { + Exit::End | Exit::Indirect => false, + ref e => leaves.contains(&b) || e.successors().iter().all(|&s| lp[s]), + }; + if !ok { + return Err((p.blocks[b].offset, EXIT)); + } + } + } + // ---- no mask that depends on the test outlives its round ---- + let mut dep: HashSet<Atom> = tests.iter().map(|t| t.0).collect(); + let mut changed = true; + while changed { + changed = false; + for (&id, edges) in &st.phi_masks { + if !dep.contains(&Atom::Phi(id)) + && edges.iter().any(|&e| st.bools.support(e).iter().any(|a| dep.contains(a))) + { + dep.insert(Atom::Phi(id)); + changed = true; + } + } + } + let mut seen: HashMap<Bool, bool> = HashMap::new(); + let mut tainted = |b: Bool| -> bool { + *seen + .entry(b) + .or_insert_with(|| st.bools.support(b).iter().any(|a| dep.contains(a))) + }; + for b in 0..n { + if lp[b] && tests.iter().any(|&(_, tb, _)| self.dominates(tb, b)) { + continue; + } + let stale = st.guards[b].iter().flatten().any(|&g| tainted(g)) + || matches!(st.exits[b], LaneExit::Branch { when, .. } if tainted(when)); + if stale { + return Err((p.blocks[b].offset, STALE)); + } + } + for (&v, &m) in &st.masks { + if !tainted(m) { + continue; + } + for user in self.users.get(&v).into_iter().flatten() { + let outside = match *user { + User::Inst(b2, _) => !lp[b2], + User::Phi(b2, k2) => !lp[b2] && self.live.contains(&p.blocks[b2].phis[k2].value), + }; + if outside { + return Err((head, STALE)); + } + } + } + Ok(alike) + } +} + +/// The wave ORs of `p` that only steer a loop over each lane's own bits (see the module +/// notes). `why`: one line on stderr for each wave OR that is not one. +pub(super) fn find(p: &Program, st: &Structured, why: bool) -> OwnBits { + let mut out = OwnBits::default(); + let mut ctx: Option<Ctx> = None; + for b in 0..p.blocks.len() { + let sections = wave::sections(p, b); + let mut starts: Vec<_> = sections.keys().copied().collect(); + starts.sort_unstable(); + for s in starts { + let sec = §ions[&s]; + let mut left: Vec<_> = sec.shapes.iter().collect(); + left.sort_unstable_by_key(|(v, _)| v.0); + for (&t, &shape) in left { + let Shape::Active(Op::Or, x, mask, 0) = shape else { + continue; + }; + let ctx = ctx.get_or_insert_with(|| Ctx::new(p, st)); + // (values only the section itself reads are not results) + let inside = |u: &User| matches!(*u, User::Inst(b2, i) if b2 == b && i > s && i < sec.end); + if ctx.users.get(&t).is_none_or(|us| us.iter().all(inside)) { + continue; + } + match ctx.site(b, t, x, mask) { + Ok(alike) => { + out.totals.insert(t); + out.alike.extend(alike); + } + Err((offset, what)) => { + if why { + eprintln!( + "WAVE64-OWN-BITS the wave OR at {:#x}: not a loop over the lanes' own bits at {offset:#x}: {what}", + p.blocks[b].insts[s].machine.offset + ); + } + } + } + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::emit::wave::WAVE_OR_V7_TO_S7; + + const ADD_BIT_NUMBER: u32 = 0x4A0A_0A0A; // v_add_nc_u32 v5, s10, v5 + + /// The title's scalarised light loop (`indirect_light_probes:CS_IrradianceCache_Shade`, + /// 0x71f8 on), in small: the wave OR of v7 in s7, a loop over its bits with the lowest + /// one's number in s10 and the bit in s11, and `body` for the lanes whose v7 has the bit + /// (`own`) or for every lane; `latch` runs in every lane after the body, `after` after + /// the loop. + fn light_loop(own: bool, body: &[u32], latch: &[u32], after: &[u32]) -> Program { + let mut w = WAVE_OR_V7_TO_S7.to_vec(); + let test: &[u32] = if own { + &[ + 0x3608_0E0B, // v_and_b32 v4, s11, v7 + 0xBE8C_047E, // s_mov_b64 s[12:13], exec + 0x7DAA_0880, // v_cmpx_ne_u32 exec, 0, v4 + ] + } else { + &[0xBE8C_047E] // s_mov_b64 s[12:13], exec + }; + // from the loop's head to its last branch + let head = 3 + test.len() + usize::from(own) + body.len() + 1 + latch.len() + 3; + w.extend_from_slice(&[ + 0xBF06_8007, // s_cmp_eq_u32 s7, 0 + 0xBF85_0000 | (3 + head) as u32, // s_cbranch_scc1 past the loop + 0x7E06_0207, // v_mov_b32 v3, s7 + 0xBF82_0001, // s_branch to the loop's head + 0x7E06_0209, // again: v_mov_b32 v3, s9 + 0x7E10_0503, // head: v_readfirstlane_b32 s8, v3 + 0xBE8A_1308, // s_ff1_i32_b32 s10, s8 + 0x8F0B_0A81, // s_lshl_b32 s11, 1, s10 + ]); + w.extend_from_slice(test); + if own { + w.push(0xBF88_0000 | body.len() as u32); // s_cbranch_execz past the body + } + w.extend_from_slice(body); + w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13] + w.extend_from_slice(latch); + w.extend_from_slice(&[ + 0x8909_080B, // s_xor_b32 s9, s11, s8 + 0xBF06_0B08, // s_cmp_eq_u32 s8, s11 + 0xBF84_0000 | (0x1_0000 - head - 1) as u32, // s_cbranch_scc0 again + ]); + w.extend_from_slice(after); + w.push(0xBF81_0000); // s_endpgm + let code: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect(); + crate::ir::build(&code, true, 256).unwrap() + } + + fn found(p: &Program) -> OwnBits { + let st = crate::structure::structure(p).unwrap(); + find(p, &st, false) + } + + #[test] + fn a_wave_or_that_only_steers_a_loop_over_own_bits_is_found() { + let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[]); + let insts = || p.blocks.iter().flat_map(|b| &b.insts); + let names: Vec<&str> = insts().map(|i| i.name()).collect(); + for n in [ + "s_ff1_i32_b32", + "s_lshl_b32", + "v_and_b32", + "v_cmpx_ne_u32", + "s_xor_b32", + "v_readfirstlane_b32", + "s_cbranch_execz", + ] { + assert!(names.contains(&n), "{n} in {names:?}"); + } + // a loop: its last branch goes back to the copy of the bits still to visit + assert!(p.blocks.iter().enumerate().any(|(b, blk)| blk.exit.successors().iter().any(|&s| s < b))); + let own = found(&p); + // the OR is the section's last lane read, and the bits still to visit (v3) are alike + let total = insts() + .rfind(|i| i.name() == "v_readlane_b32") + .and_then(|i| i.write(Reg::S(7))) + .unwrap(); + assert_eq!(own.totals, HashSet::from([total])); + let first = insts().find(|i| i.name() == "v_readfirstlane_b32").unwrap(); + assert!(own.alike.contains(&first.read(Reg::V(3)).unwrap())); + } + + #[test] + fn a_loop_whose_lanes_all_work_at_every_bit_needs_the_whole_waves_or() { + // (the same title's volume loops, 0xa668 on: no test of the lane's own mask) + let p = light_loop(false, &[ADD_BIT_NUMBER], &[], &[]); + assert!(found(&p).totals.is_empty()); + } + + #[test] + fn a_bit_number_read_after_the_loop_is_not_the_lanes_own() { + // v_mov_b32 v6, s10: the last bit of the OR, which another lane may have set + let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020A]); + assert!(found(&p).totals.is_empty()); + } + + #[test] + fn the_bits_still_to_visit_read_in_the_body_are_not_the_lanes_own() { + // v_add_nc_u32 v5, s8, v5: s8 holds the other lanes' bits too + let p = light_loop(true, &[0x4A0A_0A08], &[], &[]); + assert!(found(&p).totals.is_empty()); + } + + #[test] + fn a_count_of_the_rounds_is_not_the_lanes_own() { + // s_add_i32 s14, s14, 1 where every lane passes, read after the loop + // (v_mov_b32 v6, s14): one round for each bit any lane has + let p = light_loop(true, &[ADD_BIT_NUMBER], &[0x810E_810E], &[0x7E0C_020E]); + assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_add_i32")); + assert!(found(&p).totals.is_empty()); + // (reading s14 there without counting in it is nothing of the loop's) + let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020E]); + assert_eq!(found(&p).totals.len(), 1); + } + + #[test] + fn an_effect_where_every_lane_passes_is_not_the_lanes_own() { + // ds_write_b32 v5, v5 after the body: once for each bit any lane has + let p = light_loop(true, &[ADD_BIT_NUMBER], &[0xD834_0000, 0x0000_0505], &[]); + assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "ds_write_b32")); + assert!(found(&p).totals.is_empty()); + } +} diff --git a/crates/victory-shader/src/emit/per_program.rs b/crates/victory-shader/src/emit/per_program.rs new file mode 100644 index 0000000000..b16a001f11 --- /dev/null +++ b/crates/victory-shader/src/emit/per_program.rs @@ -0,0 +1,176 @@ +//! Switches that pick a translation per program, by the hash a run's log +//! names the shader by: the first 16 hex digits of the BLAKE3 of the +//! container as the title passes it (`hash=` in "shader translated"). +//! +//! The one so far is for the wave64 form "without skips, scalars followed" +//! ([`crate::ir::without_skips`] with `deep`), the exact form tried for a +//! console wave64 compute program on a host of 32-lane waves before the +//! approximate per-half-wave ones. On an RTX 4080 it lost walls, roofs and +//! floors (about 5,000 draws a frame against 6,900 with it off), and the 14 +//! cascade-shadow tiled renderers (`CS_ShadowRenderTiled*`) were the ones +//! wrong in it: with only them kept out, the prison cell had its ceiling, +//! lights, walls' colours and the uniform's print back; keeping all 22 +//! programs that take the form out left the room much darker +//! (Xeltax/VIcky 05ee4e9 and VICKY.md, fxceless/victory-fork#62). +//! - `VICTORY_WAVE_DEEP_SKIPS=0`: off for every program; +//! - `VICTORY_WAVE_DEEP_SKIPS_NOT=<hash>,...`: off for the listed programs +//! ([`SHADOW_PROGRAMS`] when unset; empty: on for every program); +//! - `VICTORY_WAVE_DEEP_SKIPS_ONLY=<hash>,...`: off for every program not +//! listed. +//! +//! The switches are part of the translator's fingerprint (they are +//! `VICTORY_*` switches of this crate), so changing one translates again. + +use std::cell::RefCell; +use std::sync::OnceLock; + +thread_local! { + // The hash of the container being translated on this thread + // ([`for_program`]). + static PROGRAM: RefCell<Option<String>> = const { RefCell::new(None) }; +} + +/// The 14 cascade-shadow tiled renderers kept out of the deep-skips form +/// unless `VICTORY_WAVE_DEEP_SKIPS_NOT` says otherwise. +pub(super) const SHADOW_PROGRAMS: [&str; 14] = [ + // CS_ShadowRenderTiledCascades{AlphaCB,AlphaPPPC,Alpha,CB,} + "922e1d0ee1e19a85", + "d7db57731ada919b", + "ab5455fc6abb804f", + "be6ce5d849d51127", + "191ecaed66eea3b1", + // CS_ShadowRenderTiledMisc{Alpha,CBPPPC,CB,HairAlphaPPPC,HairAlpha,HairPPPC,Hair,PPPC,} + "31d703207b51549a", + "56f3bf2d9388e5a7", + "804b342cb4b9d1e9", + "abd7a22106898c66", + "1d44a723bdebbf27", + "b4b0427232707598", + "240cb516c1af0bc3", + "466ec41d3f9d24c0", + "65de113e23fa4fdd", +]; + +/// Runs `f`, the translation of the container whose hash is `hash` (see the +/// module notes): the per-program switches see it. +pub fn for_program<T>(hash: &str, f: impl FnOnce() -> T) -> T { + struct Restore(Option<String>); + impl Drop for Restore { + fn drop(&mut self) { + PROGRAM.set(self.0.take()); + } + } + let _restore = Restore(PROGRAM.replace(Some(hash.to_owned()))); + f() +} + +/// The hash [`for_program`] set on this thread, if any. +pub(super) fn current() -> Option<String> { + PROGRAM.with_borrow(Clone::clone) +} + +/// Whether the deep-skips form may be tried for the program whose hash is +/// `hash` (`None`: not known, as for a translation outside +/// [`for_program`]), by the switches in the module notes. +pub fn deep_skips_allowed(hash: Option<&str>) -> bool { + struct Switches { + on: bool, + not: Vec<String>, + only: Option<Vec<String>>, + } + static SWITCHES: OnceLock<Switches> = OnceLock::new(); + let s = SWITCHES.get_or_init(|| Switches { + on: std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0"), + not: match std::env::var("VICTORY_WAVE_DEEP_SKIPS_NOT") { + Ok(v) => parse_hash_list(&v), + Err(_) => SHADOW_PROGRAMS.iter().map(|h| (*h).to_owned()).collect(), + }, + only: std::env::var("VICTORY_WAVE_DEEP_SKIPS_ONLY").ok().map(|v| parse_hash_list(&v)), + }); + decide(s.on, &s.not, s.only.as_deref(), hash) +} + +/// The hashes of a list: separated by commas, semicolons or white space, +/// each with or without a `#` before it, in lower case and cut to the 16 +/// digits a hash has. Pure, for testing. +fn parse_hash_list(value: &str) -> Vec<String> { + value + .split(|c: char| c == ',' || c == ';' || c.is_whitespace()) + .map(|h| h.trim_start_matches('#').to_ascii_lowercase()) + .map(|h| h.chars().take(16).collect::<String>()) + .filter(|h| !h.is_empty()) + .collect() +} + +/// Whether `list` names the program `hash`: an entry names every program +/// whose hash begins with it. +fn listed(list: &[String], hash: Option<&str>) -> bool { + hash.is_some_and(|hash| { + let hash = hash.to_ascii_lowercase(); + list.iter().any(|entry| hash.starts_with(entry.as_str())) + }) +} + +/// [`deep_skips_allowed`] on the switches' values. Pure, for testing. +fn decide(on: bool, not: &[String], only: Option<&[String]>, hash: Option<&str>) -> bool { + on && !listed(not, hash) && only.is_none_or(|l| listed(l, hash)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const A: &str = "0123456789abcdef"; + const B: &str = "fedcba9876543210"; + + fn list(v: &str) -> Vec<String> { + parse_hash_list(v) + } + + #[test] + fn lists_split_on_commas_and_space() { + assert_eq!(list(""), Vec::<String>::new()); + assert_eq!(list(" , ;"), Vec::<String>::new()); + assert_eq!(list(&format!(" #{A} ;\t{B} ,")), vec![A, B]); + assert_eq!(list("#0123456789ABCDEF"), vec![A], "upper case"); + assert_eq!(list(&format!("{A}{B}")), vec![A], "cut to 16 digits"); + } + + #[test] + fn not_keeps_the_listed_programs_out() { + let not = list(&format!("#{B}, 01234567")); + assert!(!decide(true, ¬, None, Some(A)), "by its first digits"); + assert!(!decide(true, ¬, None, Some(B))); + assert!(decide(true, ¬, None, Some("1111111111111111"))); + assert!(decide(true, ¬, None, None), "an unknown program is not listed"); + assert!(decide(true, &[], None, Some(A)), "an empty list keeps everything"); + assert!(!decide(false, &[], None, Some(A)), "=0 still wins"); + } + + #[test] + fn only_lets_just_the_listed_programs_in() { + let only = list(A); + assert!(decide(true, &[], Some(&only), Some(A))); + assert!(!decide(true, &[], Some(&only), Some(B))); + assert!(!decide(true, &[], Some(&only), None)); + } + + #[test] + fn the_shadow_programs_are_hashes() { + for h in SHADOW_PROGRAMS { + assert_eq!(h.len(), 16); + assert!(h.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())); + } + } + + #[test] + fn the_program_hash_is_seen_inside_its_translation_only() { + assert_eq!(current(), None); + let inner = for_program(A, || { + let nested = for_program(B, current); + (current(), nested) + }); + assert_eq!(inner, (Some(A.to_owned()), Some(B.to_owned()))); + assert_eq!(current(), None); + } +} diff --git a/crates/victory-shader/src/emit/permlane_tests.rs b/crates/victory-shader/src/emit/permlane_tests.rs new file mode 100644 index 0000000000..d535c4d3bb --- /dev/null +++ b/crates/victory-shader/src/emit/permlane_tests.rs @@ -0,0 +1,255 @@ +//! Synthetic row permutations on hosts supporting waves of at least 32 lanes. + +use super::host::{Dispatch, Host, Root, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{ShaderError, io, ir, resource, structure}; + +const THREADS: u32 = 128; +const OLD: u32 = 42; +const BASE: u32 = 0x1234_0000; + +fn native(cross: bool, fi: bool, bc: bool, alias: bool, wave64: bool) -> NativeProgram { + let mov = |dst: u32, src: u32| 0x7E00_0200 | dst << 17 | src; + let smov = |dst: u32, src: u32| 0xBE80_0300 | dst << 16 | src; + let mut words = vec![ + smov(5, 128), + 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, + 125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 (output byte offset) + 0x4A0A_00FF, + BASE, // v_add_nc_u32 v5, BASE, v0 + mov(6, if alias { 256 + 5 } else { 128 + OLD }), + ]; + words.push(if wave64 { 0xBEFE_0402 } else { smov(126, 2) }); // exec = s[2:3] / s2 + words.extend([ + 0xD400_0006 + | (if cross { 0x378 } else { 0x377 }) << 16 + | u32::from(fi) << 11 + | u32::from(bc) << 12, + (256 + if alias { 6 } else { 5 }) | (1 << 18), + ]); // v_permlane[x]16_b32 v6, v5/v6, s0, s1 + words.push(if wave64 { 0xBEFE_04C1 } else { smov(126, 193) }); // restore EXEC + words.extend([ + 0x38 << 26 | 0x1C << 18 | 1 << 12, + 0x80 << 24 | 2 << 16 | 6 << 8 | 7, // buffer_store_dword v6, v7, s[8:11], 0 offen + 0xBF81_0000, + ]); + NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [THREADS, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +fn lowered(native: &NativeProgram, host_wave: u32) -> Result<HostShader, ShaderError> { + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resources"); + let io = io::raise(&p, native).expect("io"); + let was = lower::TEST_HOST_WAVE.replace(Some(host_wave)); + let result = lower::lower(&lower::Parts { + native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(was); + let result = result?; + let shader = HostShader { + stage: HwStage::Cs, + dxil: result.dxil, + user_data: result.user_data, + samplers: result.samplers, + static_samplers: Vec::new(), + root_cbvs: result.root_cbvs, + root_srvs: result.root_srvs, + root_uavs: result.root_uavs, + root_indexed_views: res.root_indexed_views, + half_views: result.half_views, + }; + match validator::Validator::load(validator::Validator::default_path().as_deref()) { + Ok(mut v) => { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation"); + assert_eq!(copy[4..20], shader.dxil[4..20], "container hash"); + } + Err(e) => eprintln!("DXIL validator unavailable: {e}"), + } + Ok(shader) +} + +#[test] +fn permlane_fetch_inactive_outside_the_host_branch_is_rejected() { + let mut native = native(true, true, false, false, false); + let mut words: Vec<u32> = native + .code + .chunks_exact(4) + .map(|w| u32::from_le_bytes(w.try_into().unwrap())) + .collect(); + // Skip the permutation when EXEC is empty. Structurisation turns this + // into a host lane branch, so FI cannot read lanes that took the skip. + words.insert(8, 0xBF88_0002); // s_cbranch_execz +2 (to the EXEC restore) + native.code = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + assert!(matches!( + lowered(&native, 32), + Err(ShaderError::Unsupported { + what: "a permlane fetch from lanes outside the host branch", + .. + }) + )); +} + +#[test] +fn permlane_rows_and_inactive_sources() { + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (backend, warp) in [("hardware", false), ("WARP", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {backend}; skipped"); + continue; + }; + let mut options = + windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + // SAFETY: options is the correctly sized output for this feature query. + unsafe { + host.device + .CheckFeatureSupport( + windows::Win32::Graphics::Direct3D12::D3D12_FEATURE_D3D12_OPTIONS1, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .expect("wave capabilities"); + } + eprintln!( + "{backend} waves {}..{}", + options.WaveLaneCountMin, options.WaveLaneCountMax + ); + if options.WaveLaneCountMax < 32 { + eprintln!("{backend} cannot hold two 16-lane rows; GPU checks skipped"); + continue; + } + ran += 1; + eprintln!("permlane: testing row and EXEC cases on {backend}"); + for wave64 in [false, true] { + if options.WaveLaneCountMin > if wave64 { 64 } else { 32 } { + eprintln!("{backend} does not support the requested console wave size; skipped"); + continue; + } + for cross in [false, true] { + for fi in [false, true] { + for bc in [false, true] { + for alias in [false, true] { + let shader = lowered( + &native(cross, fi, bc, alias, wave64), + options.WaveLaneCountMax, + ) + .expect("lower permlane"); + let (root, pso) = + host.compute_pipeline(&shader).expect("permlane pipeline"); + for selectors in [ + [0x7654_3210u32, 0xFEDC_BA98], // identity + [0x89AB_CDEF, 0x0123_4567], // reverse + [0, 0], // broadcast lane 0 + [u32::MAX, u32::MAX], // broadcast lane 15 + [0xF10E_2D3C, 0x4B5A_6978], // arbitrary; both selector words + ] { + for mask in [u32::MAX, 0x5555_5555, 0xFFFF_0000, 1, 0] { + let constants = [selectors[0], selectors[1], mask, mask]; + let mut ud = vec![0; shader.user_data_dwords() as usize]; + for u in &shader.user_data { + ud[u.index as usize] = if u.root == RootType::Constants { + constants[u.dword as usize] + } else { + 0 + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(THREADS)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .expect("dispatch permlane"); + for t in 0..THREADS { + let pos = t % 16; + let packed = + u64::from(selectors[0]) | u64::from(selectors[1]) << 32; + let pick = (packed >> (4 * pos)) as u32 & 15; + let src = ((t & !15) ^ if cross { 16 } else { 0 }) | pick; + let old = if alias { BASE + t } else { OLD }; + let want = if mask >> (t % 32) & 1 == 0 { + old + } else if fi || mask >> (src % 32) & 1 != 0 { + BASE + src + } else if bc { + 0 + } else { + old + }; + let got = out[0][t as usize]; + assert_eq!( + got, want, + "{backend} wave64={wave64} cross={cross} fi={fi} bc={bc} alias={alias} selectors={selectors:x?} mask={mask:x} lane={t}" + ); + } + } + } + } + } + } + } + } + eprintln!("permlane: all row and EXEC cases passed on {backend}"); + } + if ran == 0 { + eprintln!("no SM 6.6 device with 32-lane rows; GPU checks skipped"); + } +} diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs new file mode 100644 index 0000000000..ba2f4b9a05 --- /dev/null +++ b/crates/victory-shader/src/emit/rect.rs @@ -0,0 +1,485 @@ +//! The geometry shader that completes the console's rectangle lists (list +//! topology 17, pipeline topology type 19). A rectangle comes as three +//! vertices, three corners of a screen-aligned rectangle; the hardware +//! draws the whole rectangle and continues every vertex shader output +//! linearly into the fourth corner. The host has no such topology: the +//! draw goes out as a triangle list with this shader behind the translated +//! vertex shader, so vertex counts, vertex numbers, indices and indirect +//! arguments stay the title's, and each rectangle arrives here as one +//! triangle. +//! +//! Which vertex is the corner between the other two varies: +//! the title's full-screen rectangles come as top left, bottom left, bottom +//! right (the second), its tiled lighting as top left, bottom left, top +//! right (the first). The corner is the vertex that shares x with one of +//! the others and y with the other; the fourth vertex lies opposite it, +//! `a + b - corner` for the position and every float output. That holds +//! for three vertices with one positive w (then it is the same in clip +//! space and on the screen, whatever the interpolation mode); three that +//! differ in w, or are not such corners, stay the triangle they make. +//! +//! Flat values are the first vertex's: both triangles start with it (the +//! halves on either side of the diagonal through it, turning as the three +//! vertices do), which is the vertex the host takes a flat input from, and +//! the fourth vertex's integer outputs are the first vertex's. +//! +//! shortcut: that the console takes a rectangle's flat values from its +//! first vertex follows from the hardware's provoking-vertex setting for +//! triangles; it is not measured on a rectangle. + +use super::bitcode::{Attr, Bin, Term, V, pred}; +use super::container::SigElement; +use super::shader::{Geometry, Shader}; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC}; + +/// Vertices emitted per rectangle: two triangles. +const VERTICES: u32 = 6; + +/// The scalars a geometry shader may emit per invocation (vertices times +/// output components). +const MAX_SCALARS: u32 = 1024; + +/// The geometry shader (a DXIL container) for rectangle lists drawn with +/// the translated vertex shader `vs` and, if the pipeline has one, the +/// translated pixel shader `ps` (both as [`super::HostShader::dxil`]). Its +/// inputs and outputs are the vertex shader's outputs, register for +/// register, so it links with both. A pixel shader that declares a +/// primitive id gets the rectangle's number, which the host leaves to the +/// geometry stage when there is one. +pub fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> { + let sig = |dxil: &[u8], fourcc| -> Result<Vec<SigElement>, ShaderError> { + let c = Container::parse(dxil)?; + match c.part(fourcc) { + Some(part) => super::signature(part.data), + None => Ok(Vec::new()), + } + }; + let outputs = sig(vs, FourCC::OSG1)?; + let wanted = match ps { + Some(ps) => sig(ps, FourCC::ISG1)?, + None => Vec::new(), + }; + build(outputs, &wanted) +} + +/// [`rect_list_gs`] from the vertex shader's outputs and the pixel +/// shader's inputs. +fn build(mut outputs: Vec<SigElement>, ps_inputs: &[SigElement]) -> Result<Vec<u8>, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + if outputs.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a rectangle list output without a register")); + } + let Some(position) = outputs + .iter() + .position(|e| e.kind == 3 && e.comp == 9 && e.cols == 4) + else { + return Err(unsupported("a rectangle list without a four-component position")); + }; + for e in &mut outputs { + // Interpolation as `emit_program` declares a vertex shader's + // outputs; a geometry shader's inputs carry the same modes. + e.interp = match (e.kind, e.comp) { + (3, _) => 4, + (0 | 6 | 7, 9) => 2, + (0, _) => 1, + _ => 0, + }; + e.usage = (1 << e.cols) - 1; + } + let mut s = Shader::new(false); + s.geometry = Some(Geometry { + max_vertices: VERTICES, + }); + s.inputs = outputs.clone(); + // The primitive id the pixel shader declares, as one more output. + let wanted = ps_inputs + .iter() + .find(|e| e.kind == 10 && e.row.is_some()) + .filter(|_| !outputs.iter().any(|o| o.kind == 10)); + let primitive = match wanted { + Some(e) => { + // Alone in its columns, and in a row of constant elements. + let clash = outputs.iter().any(|o| { + let overlap = o.col < e.col + e.cols && e.col < o.col + o.cols; + o.row == e.row && (o.interp != 1 || overlap) + }); + if clash { + return Err(unsupported( + "a rectangle list whose primitive id shares a register with a vertex output", + )); + } + outputs.push(SigElement { + interp: 1, + usage: (1 << e.cols) - 1, + ..e.clone() + }); + Some(outputs.len() - 1) + } + None => None, + }; + let scalars: u32 = outputs.iter().map(|e| u32::from(e.cols)).sum(); + if scalars * VERTICES > MAX_SCALARS { + return Err(unsupported( + "a rectangle list with more output components than a geometry shader emits", + )); + } + s.outputs = outputs; + let b = s.entry; + + // Every input of the three vertices: [element][column][vertex]. + let mut corners: Vec<Vec<[V; 3]>> = Vec::new(); + for id in 0..s.inputs.len() { + let mut columns = Vec::new(); + for col in 0..s.inputs[id].cols { + columns.push([0, 1, 2].map(|vertex| load(&mut s, id, col, vertex))); + } + corners.push(columns); + } + + // One positive w, and no two vertices in one place. + let (x, y, w) = ( + corners[position][0], + corners[position][1], + corners[position][3], + ); + let zero = s.m.f32(0); + let mut plain = s.m.cmp(b, pred::OGT, w[0], zero); + for &other in &w[1..] { + let one_w = same(&mut s, other, w[0]); + plain = both(&mut s, plain, one_w); + } + for (i, j) in [(0, 1), (0, 2), (1, 2)] { + let (same_x, same_y) = (same(&mut s, x[i], x[j]), same(&mut s, y[i], y[j])); + let together = both(&mut s, same_x, same_y); + let apart = not(&mut s, together); + plain = both(&mut s, plain, apart); + } + // corner[i]: vertex i is the corner between the other two (the first + // that shares x with one of them and y with the other). + let mut corner: Vec<V> = Vec::new(); + for i in 0..3 { + let (a, c) = ((i + 1) % 3, (i + 2) % 3); + let (xa, yc) = (same(&mut s, x[i], x[a]), same(&mut s, y[i], y[c])); + let (xc, ya) = (same(&mut s, x[i], x[c]), same(&mut s, y[i], y[a])); + let (one, other) = (both(&mut s, xa, yc), both(&mut s, xc, ya)); + let shares = either(&mut s, one, other); + let mut here = both(&mut s, shares, plain); + for &found in &corner { + let earlier = not(&mut s, found); + here = both(&mut s, here, earlier); + } + corner.push(here); + } + + // What the six emitted vertices carry: [element][column][vertex]. + let mut emitted: Vec<Vec<[V; 6]>> = Vec::new(); + for (id, columns) in corners.iter().enumerate() { + let float = s.inputs[id].comp == 9; + let mut out = Vec::new(); + for &[p0, p1, p2] in columns { + // The fourth vertex: `a + b - corner`. Integers (flat), and + // three vertices without a corner, keep the first vertex's + // value; the second triangle of the latter is then empty. + let mut fourth = p0; + if float { + for (k, (a, c, at)) in [(p1, p2, p0), (p2, p0, p1), (p0, p1, p2)] + .into_iter() + .enumerate() + { + let sum = s.m.bin(b, Bin::Add, a, c); + let opposite = s.m.bin(b, Bin::Sub, sum, at); + fourth = s.m.select(b, corner[k], opposite, fourth); + } + } + // Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1, + // v2), (v0, v2, v3). Third: (v0, v1, v2), (v0, v3, v1). + let third = s.m.select(b, corner[0], fourth, p2); + let fifth = s.m.select(b, corner[1], p2, fourth); + let sixth = s.m.select(b, corner[0], p2, p1); + let sixth = s.m.select(b, corner[1], fourth, sixth); + out.push([p0, p1, third, p0, fifth, sixth]); + } + emitted.push(out); + } + + // The rectangle's number: the triangle's, three vertices a rectangle. + let mut number = None; + if let Some(id) = primitive { + let n = s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[]); + number = Some((id, n)); + } + let stream = s.m.i8(0); + for vertex in 0..VERTICES as usize { + for (id, columns) in emitted.iter().enumerate() { + let name = if s.outputs[id].comp == 9 { + "storeOutput.f32" + } else { + "storeOutput.i32" + }; + for (col, values) in columns.iter().enumerate() { + let args = [ + s.m.i32(id as u32), + s.m.i32(0), + s.m.i8(col as u8), + values[vertex], + ]; + s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args); + } + } + if let Some((id, n)) = number { + let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(0), n]; + s.op(b, "storeOutput.i32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]); + // The strip ends after the first triangle. + if vertex == 2 { + s.op(b, "cutStream", Attr::NoUnwind, s.t.void, 98, &[stream]); + } + } + s.m.terminate(b, Term::Ret); + Ok(s.finish()) +} + +/// Column `col` of input `id` at vertex `vertex` of the triangle. +fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V { + let (name, ty) = if s.inputs[id].comp == 9 { + ("loadInput.f32", s.t.f32) + } else { + ("loadInput.i32", s.t.i32) + }; + let args = [ + s.m.i32(id as u32), + s.m.i32(0), + s.m.i8(col), + s.m.i32(vertex), + ]; + let entry = s.entry; + s.op(entry, name, Attr::ReadNone, ty, 4, &args) +} + +/// Two floats are equal. +fn same(s: &mut Shader, a: V, b: V) -> V { + let entry = s.entry; + s.m.cmp(entry, pred::OEQ, a, b) +} + +fn both(s: &mut Shader, a: V, b: V) -> V { + let entry = s.entry; + s.m.bin(entry, Bin::And, a, b) +} + +fn either(s: &mut Shader, a: V, b: V) -> V { + let entry = s.entry; + s.m.bin(entry, Bin::Or, a, b) +} + +fn not(s: &mut Shader, a: V) -> V { + let (entry, on) = (s.entry, s.m.bool(true)); + s.m.bin(entry, Bin::Xor, a, on) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn element(name: &str, index: u32, kind: u8, comp: u8, row: u32, cols: u8) -> SigElement { + SigElement { + name: name.into(), + index, + kind, + comp, + interp: 0, + row: Some(row), + col: 0, + cols, + usage: 0, + half: false, + } + } + + /// A position, a float interpolant and an integer one. + fn outputs() -> Vec<SigElement> { + vec![ + element("SV_Position", 0, 3, 9, 0, 4), + element("TEXCOORD", 0, 0, 9, 1, 4), + element("TEXCOORD", 1, 0, 5, 2, 2), + ] + } + + /// The stage is a geometry shader of triangles in and six strip + /// vertices out, with the vertex shader's outputs on both sides and + /// the primitive id the pixel shader declares; the validator, where + /// there is one, accepts it. + #[test] + fn the_rectangle_stage_is_a_geometry_shader() { + let wanted = [element("SV_PrimitiveID", 0, 10, 5, 3, 1)]; + let gs = build(outputs(), &wanted).unwrap(); + let c = Container::parse(&gs).unwrap(); + // Program version: geometry (2), shader model 6.6. + assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0]); + let psv = c.part(FourCC::PSV0).unwrap().data; + // Triangles in, triangle strips out, stream 0, a position. + assert_eq!(psv[4..17], [3, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 1]); + // Geometry stage, six vertices, three inputs, four outputs. + assert_eq!(psv[28..34], [2, 0, 6, 0, 3, 4]); + let sig = |fourcc| super::super::signature(c.part(fourcc).unwrap().data).unwrap(); + let (ins, outs) = (sig(FourCC::ISG1), sig(FourCC::OSG1)); + assert_eq!(ins.len(), 3); + assert_eq!(outs.len(), 4); + for (i, o) in ins.iter().zip(&outs) { + assert_eq!((&i.name, i.index, i.row), (&o.name, o.index, o.row)); + assert_eq!((i.col, i.cols, i.comp), (o.col, o.cols, o.comp)); + } + assert_eq!((outs[3].kind, outs[3].row), (10, Some(3))); + #[cfg(windows)] + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut gs.clone()).unwrap(); + let plain = build(outputs(), &[]).unwrap(); + v.validate(&mut plain.clone()).unwrap(); + } + } + + /// Refused with a reason: no position, a primitive id in a register a + /// vertex output has, more components than six vertices may carry. + #[test] + fn rectangle_stages_that_cannot_be_made_are_refused() { + assert!(build(outputs()[1..].to_vec(), &[]).is_err()); + let taken = [element("SV_PrimitiveID", 0, 10, 5, 1, 1)]; + assert!(build(outputs(), &taken).is_err()); + let mut many = vec![element("SV_Position", 0, 3, 9, 0, 4)]; + many.extend((1..=43).map(|row| element("TEXCOORD", row - 1, 0, 9, row, 4))); + assert!(build(many, &[]).is_err()); + } + + /// A vertex shader that passes a position and a float4 through, and a + /// pixel shader that writes the float4. + #[cfg(windows)] + fn pass_through() -> (super::super::HostShader, super::super::HostShader) { + let position = SigElement { + interp: 4, + usage: 15, + ..element("SV_Position", 0, 3, 9, 0, 4) + }; + let coord = SigElement { + interp: 2, + usage: 15, + ..element("TEXCOORD", 0, 0, 9, 1, 4) + }; + let mut vs = Shader::new(false); + vs.inputs = vec![ + SigElement { + usage: 15, + ..element("POSITION", 0, 0, 9, 0, 4) + }, + SigElement { + interp: 0, + ..coord.clone() + }, + ]; + vs.outputs = vec![position.clone(), coord.clone()]; + let mut ps = Shader::new(true); + ps.inputs = vec![ + SigElement { + usage: 0, + ..position + }, + coord, + ]; + ps.outputs = vec![SigElement { + usage: 15, + ..element("SV_Target", 0, 16, 9, 0, 4) + }]; + // Vertex: output id from input id. Pixel: target 0 from input 1. + for (s, copies) in [(&mut vs, &[(0, 0), (1, 1)][..]), (&mut ps, &[(1, 0)][..])] { + let b = s.entry; + for &(from, to) in copies { + for col in 0..4 { + let args = [s.m.i32(from), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; + let v = s.op(b, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); + let args = [s.m.i32(to), s.m.i32(0), s.m.i8(col), v]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + } + s.m.terminate(b, Term::Ret); + } + let host = |stage, s: Shader| super::super::HostShader { + stage, + dxil: s.finish(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + }; + ( + host(crate::native::HwStage::Vs, vs), + host(crate::native::HwStage::Ps, ps), + ) + } + + /// Three corners of the whole target, the corner between the other two + /// first (as the tiled lighting sends its tiles), second (as + /// full-screen rectangles come) or third: with the stage every texel + /// is drawn and the interpolant continues into the fourth corner's + /// half; without it part of the target is not drawn. + #[test] + #[cfg(windows)] + fn rectangles_are_drawn_whole() { + use super::super::host::{Draw, Host}; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let (vs, ps) = pass_through(); + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut vs.dxil.clone()).unwrap(); + v.validate(&mut ps.dxil.clone()).unwrap(); + } + let gs = rect_list_gs(&vs.dxil, Some(&ps.dxil[..])).unwrap(); + let root = host.root_signature(&vs, &ps).unwrap(); + // Position (z 0.5, w 1) and an interpolant that is the position. + let vertex = |(x, y): (f32, f32)| [x, y, 0.5, 1.0, x, y, 0.0, 1.0]; + for (name, corners) in [ + ("corner first", [(-1.0, 1.0), (-1.0, -1.0), (1.0, 1.0)]), + ("corner second", [(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)]), + ("corner third", [(-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]), + ] { + let vertices = corners.map(vertex).concat(); + let draw = |gs: Option<&[u8]>| { + let pso = host + .pipeline_with_gs(&root, &vs.dxil, gs, &ps.dxil) + .unwrap(); + let d = Draw { + roots: Vec::new(), + textures: &[], + samplers: &[], + vertices: &vertices, + stride: 32, + size: (8, 8), + mesh_groups: 0, + }; + host.draw(&root, &pso, &d).unwrap() + }; + let whole = draw(Some(&gs[..])); + for (i, texel) in whole.iter().enumerate() { + let (x, y) = ((i % 8) as f32, (i / 8) as f32); + let want = [(x + 0.5) / 4.0 - 1.0, 1.0 - (y + 0.5) / 4.0, 0.0, 1.0]; + assert!( + texel.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), + "{name}: texel {i} is {texel:?}, not {want:?}" + ); + } + let half = draw(None); + let missing = half.iter().zip(&whole).filter(|(a, b)| a != b).count(); + assert!(missing >= 24, "{name}: only {missing} texels need the stage"); + } + } +} diff --git a/crates/victory-shader/src/emit/sampler.rs b/crates/victory-shader/src/emit/sampler.rs index e10c0c16e2..ca010e593d 100644 --- a/crates/victory-shader/src/emit/sampler.rs +++ b/crates/victory-shader/src/emit/sampler.rs @@ -34,6 +34,18 @@ pub struct StaticSampler { impl Eq for StaticSampler {} impl StaticSampler { + /// The filter supported by the host device. Anisotropic point-mip + /// filtering is optional (`D3D12_OPTIONS19`); older devices retain the + /// previous linear-mip approximation. Comparison/min/max reduction + /// bits and the sampler's LOD bounds are unchanged. + pub fn filter_for_host(&self, aniso_point_mip_supported: bool) -> u32 { + if !aniso_point_mip_supported && self.filter & !0x180 == 0x54 { + self.filter | 1 + } else { + self.filter + } + } + /// Decodes the four sampler words. pub fn from_words(w: [u32; 4]) -> Self { let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1); @@ -47,7 +59,7 @@ impl StaticSampler { _ => 0, }; let filter = if mag >= 2 || min >= 2 { - 0x55 | reduction << 7 + 0x54 | u32::from(mip == 2) | reduction << 7 } else { (min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7 }; @@ -122,4 +134,54 @@ mod tests { (0x1D5, 16, 15.0) ); } + + #[test] + fn anisotropic_samplers_preserve_mip_point_filtering() { + for (reduction, base) in [(0u32, 0x54u32), (1, 0x154), (2, 0x1D4)] { + let w0 = reduction << 29; + for mip in [0u32, 1] { + let w2 = (mip << 26) | 0x00F0_0000; // mag = 3, min = 3 + let s = StaticSampler::from_words([w0, 0x00FF_F000, w2, 0]); + assert_eq!(s.filter, base, "reduction={reduction} mip={mip}"); + } + let w2 = (2 << 26) | 0x00F0_0000; // mip = 2 (linear) + let s = StaticSampler::from_words([w0, 0x00FF_F000, w2, 0]); + assert_eq!(s.filter, base | 1, "reduction={reduction} mip=2"); + } + // Mixed anisotropic mag (2) with linear min (1) and point mip (1). + let mixed = StaticSampler::from_words([0, 0, (1 << 26) | (1 << 22) | (2 << 20), 0]); + assert_eq!(mixed.filter, 0x54); + } + + #[test] + fn host_filter_falls_back_without_changing_reduction_or_lod() { + for (filter, fallback) in [(0x54, 0x55), (0xD4, 0xD5), (0x154, 0x155), (0x1D4, 0x1D5)] { + for mip in [0u32, 1] { + let s = StaticSampler { + filter, + ..StaticSampler::from_words([0, 0x0054_0100, (mip << 26) | 0x00F0_0000, 0]) + }; + assert_eq!(s.filter_for_host(false), fallback); + assert_eq!(s.filter_for_host(true), filter); + assert_eq!( + (s.min_lod, s.max_lod), + if mip == 0 { (0.0, 0.0) } else { (1.0, 5.25) } + ); + } + } + } + + #[test] + fn host_filter_keeps_other_filters_unchanged() { + for reduction in [0, 0x80, 0x100, 0x180] { + for base in [0, 1, 4, 5, 0x10, 0x11, 0x14, 0x15, 0x55] { + let s = StaticSampler { + filter: base | reduction, + ..StaticSampler::from_words([0; 4]) + }; + assert_eq!(s.filter_for_host(false), s.filter); + assert_eq!(s.filter_for_host(true), s.filter); + } + } + } } diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 3ca41bec05..13a2004d3a 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -13,12 +13,105 @@ pub const SAMPLER_SPACE: u32 = 0; /// `t<root parameter index>` in this space. pub const ROOT_CBV_SPACE: u32 = 1; +/// The root SRV `t<SLOT_STRIDES>` in [`ROOT_CBV_SPACE`] of a shader that +/// reads buffers through descriptors it picks from the view heap at an +/// index it computes (SM 6.6 dynamic resources): a raw buffer of +/// [`SLOT_STRIDES_COUNT`] dwords the host keeps, dword `i` the bytes per +/// element of the buffer view at heap slot `i` (0: none or not a buffer). +/// The console's descriptor holds that stride and its hardware multiplies +/// the element index by it; the program's code does not say it, and the +/// used-resource list only names what tables hold. A shader that has this +/// root SRV also tells the host that the buffer views of the whole heap +/// must be ready when it runs, not only those its tables name. +pub const SLOT_STRIDES: u8 = 255; +/// The same table of strides and format kinds as [`SLOT_STRIDES`], bound for +/// shaders that only look at the views of their descriptor tables +/// (`RootType::Table`): the host binds it without readying the buffer views +/// of the whole heap (codec_d, cool_fox f4b48ad). +pub const SLOT_TABLE_STRIDES: u8 = 252; +/// The bits of a [`SLOT_STRIDES`] dword that hold the stride. +pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1; +/// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format +/// (`UINT` or `SINT`), whose 16-bit typed accesses (`_d16`) pass bits. +/// (After VIctory 4243a96a.) +pub const VIEW_INTEGER: u32 = 1 << 31; +/// With [`VIEW_INTEGER`]: a signed (`SINT`) format. +pub const VIEW_SIGNED: u32 = 1 << 30; +/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it. +pub const SLOT_STRIDES_COUNT: u32 = 1 << 21; + +/// Title memory by address (`resource::MEMORY`): console code reads and +/// writes through raw 40-bit addresses it takes from root constants, +/// descriptors and other memory (the ray-tracing structure builder and the +/// programs that walk its structures). The host keeps copies of the title +/// memory shaders use; a shader with such an access finds the copy by the +/// address: +/// +/// - the root SRV `t<SLOT_MEMORY>` in [`ROOT_CBV_SPACE`] is a directory of +/// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title +/// address space: the number of the host copy holding that page (0: none +/// yet) and the page's byte offset in that copy; +/// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base` +/// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself +/// reads zeros and drops writes; +/// - the root UAV `u<SLOT_FAULTS>` takes the page numbers of accesses that +/// found no copy ([`MEMORY_FAULTS`] dwords, dword 0 a sink), which the +/// host reads afterwards to make those copies for the frames to come. +pub const SLOT_MEMORY: u8 = 254; +/// See [`SLOT_MEMORY`]. +pub const SLOT_FAULTS: u8 = 253; +/// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB. +pub const MEMORY_PAGES: u32 = 1 << 21; +/// Dwords of the [`SLOT_FAULTS`] buffer. +pub const MEMORY_FAULTS: u32 = 4096; +/// `RootType::Other` code of a user-data dword the host computes: the view +/// heap slot of the memory copies' views ([`SLOT_MEMORY`]). +pub const USER_MEMORY_BASE: u32 = 0x100; +/// `RootType::Other` code of a user-data dword the host computes: the low +/// 32 bits of the title address of the buffer view at dword `dword` of the +/// descriptor table of root parameter `slot`; [`USER_VIEW_ADDRESS`] + 1: +/// its bits from 32 up. (Console code reads the address out of a buffer +/// descriptor and uses it as a pointer.) +pub const USER_VIEW_ADDRESS: u32 = 0x101; +/// `RootType::Other` code of a user-data dword the host computes: the +/// bytes (0 to 15) by which the raw view the host binds for the root view +/// of root parameter `slot` begins before the title's address. A raw view +/// begins on 16 bytes of its host buffer; the console's root views begin +/// anywhere (the structure builder's counters sit at addresses ending in +/// 4 and c). The shader adds the dword to every byte offset through that +/// view. Asked for every root UAV, and for the root SRVs of programs with +/// a spilled user-data table. +pub const USER_VIEW_BIAS: u32 = 0x103; +/// `RootType::Other` code of a user-data dword the host computes, for a +/// compute program that reads its group id x: dword 0 the groups per row of +/// a dispatch spread across z (0: not spread), dword 1 the x group count +/// the title asked for. A dispatch of more than 65,535 groups in x (the +/// most Direct3D 12 runs) runs as `(row, y, rows)`; the program takes group +/// `(x + z * row, y, 0)` and leaves at once past the asked count. (After +/// upstream VIctory pull request #2312, Xvania7; run 319 measured indirect +/// compute records asking 115,200 groups, clamped to 65,535 before.) +pub const USER_DISPATCH_SPREAD: u32 = 0x104; +/// `RootType::Other` code of a user-data dword the host computes, for a +/// compute program with a spilled user-data table (the ray-tracing +/// structure builder's stages): dword `n` the thread count along axis `n` +/// of a `DispatchX` with `USE_THREAD_DIMENSIONS` (flags bit 5, 0x20) when +/// it is not a whole number of groups, else 0 (every thread runs). The +/// threads at or past the count do nothing, as the console leaves them out +/// of EXEC. (After fork pull request #646, mynzjerko, which numbers it +/// 0x104; that is [`USER_DISPATCH_SPREAD`] here, and 0x105 is fork #994's +/// `USER_THREAD_LIMIT`.) +pub const USER_DISPATCH_THREADS: u32 = 0x106; + /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; + pub const DOUBLES: u64 = 1 << 2; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; + /// Unordered views in a vertex, geometry or mesh program. + pub const UAVS_EVERY_STAGE: u64 = 1 << 16; pub const WAVE_OPS: u64 = 1 << 19; + pub const BARYCENTRICS: u64 = 1 << 22; pub const INT64: u64 = 1 << 20; pub const ATOMIC_TYPED64: u64 = 1 << 27; pub const ATOMIC_HEAP64: u64 = 1 << 32; @@ -47,6 +140,30 @@ pub(crate) struct Mesh { pub topology: u8, } +/// What a geometry shader declares: triangles in, triangle strips out on +/// stream 0, one instance. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Geometry { + pub max_vertices: u32, +} + +/// The null slot every host view heap keeps at its end (0: no limit). Shaders translated while +/// it is set read that slot for any view index at or past it. A read past a heap's end is +/// undefined: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is +/// larger) hung its GPU (GPU-based validation: "descriptor heap index out of bounds"), and AMD +/// RDNA3 took a page fault and removed the device. +static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null. +pub fn set_view_heap_limit(null_slot: u32) { + VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed); +} + +/// See [`VIEW_LIMIT`]: the null slot shaders translated now clamp view indices to (0: none). +pub fn view_heap_limit() -> u32 { + VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) +} + pub(crate) struct Shader { pub m: Module, pub t: Types, @@ -57,6 +174,8 @@ pub(crate) struct Shader { pub prims: Vec<SigElement>, /// A mesh shader (`threads` is its thread-group size). pub mesh: Option<Mesh>, + /// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false. + pub geometry: Option<Geometry>, /// Dwords of user data the shader reads (0: no user-data buffer). pub user_data: u32, /// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`]. @@ -67,13 +186,11 @@ pub(crate) struct Shader { pub root_cbvs: Vec<(u8, V)>, /// Root SRVs (raw buffers) read, likewise. pub root_srvs: Vec<(u8, V)>, + /// Root UAVs (raw buffers) read or written, likewise. + pub root_uavs: Vec<(u8, V)>, pub flags: u64, /// Heap handles made with a non-uniform index. pub nonuniform_handles: u32, - /// Mesh primitive exports whose indices are checked against the - /// declared vertex count. - #[cfg(test)] - pub bounded_prims: u32, /// Each heap handle's resource properties, in creation order. #[cfg(test)] pub heap_props: Vec<(u32, u32)>, @@ -124,16 +241,16 @@ impl Shader { outputs: Vec::new(), prims: Vec::new(), mesh: None, + geometry: None, user_data: 0, samplers: 0, cmp_samplers: 0, root_cbvs: Vec::new(), root_srvs: Vec::new(), + root_uavs: Vec::new(), flags: 0, nonuniform_handles: 0, #[cfg(test)] - bounded_prims: 0, - #[cfg(test)] heap_props: Vec::new(), threads: None, wave_size: None, @@ -249,6 +366,31 @@ impl Shader { h } + /// The handle of the root UAV (a raw buffer) of root parameter `slot`: + /// `u<slot>` in [`ROOT_CBV_SPACE`]. + pub fn root_uav_handle(&mut self, slot: u8) -> V { + if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) { + return h; + } + let r = self.m.i32(u32::from(slot)); + let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(1)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 11 | 0x1000, 0); + self.flags |= flags::RAW_BUFFERS; + self.root_uavs.push((slot, h)); + h + } + /// The handle of immediate sampler `n` (a comparison sampler when its /// bit in `cmp_samplers` is set). pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { @@ -299,6 +441,29 @@ impl Shader { nonuniform: bool, props: (u32, u32), ) -> V { + // a view index past the host heap (`set_view_heap_limit`) reads its null slot instead + let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed); + // (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid) + let index = if !sampler && limit != 0 { + let null = self.m.i32(limit); + let i32t = self.t.i32; + let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]); + self.m.tag(v, super::bitcode::Tag::Clamp); + v + } else if sampler { + // A sampler heap has at most 2,048 samplers on any host: an + // index past that (a number read from memory the host has not + // got yet) stays inside the largest heap there is. + // shortcut: not the bound heap's own count, which a title + // heap smaller than 2,048 would need. + let last = self.m.i32(2047); + let i32t = self.t.i32; + let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]); + self.m.tag(v, super::bitcode::Tag::Clamp); + v + } else { + index + }; self.flags |= if sampler { flags::SAMPLER_HEAP } else { @@ -323,6 +488,34 @@ impl Shader { pub fn finish(mut self) -> Vec<u8> { let ud_size = (self.user_data * 4).next_multiple_of(16); self.fix_user_data_size(ud_size); + // The clean-up, before anything is declared about the code: a + // feature whose last use it removed must not be declared (the + // validator compares the flags with what the code uses). + let passes = super::shader_opt() & super::bitcode::opt::MODULE; + if passes != 0 { + self.m.optimise(passes); + let used = self.m.usage(); + for (flag, used) in [ + (flags::WAVE_OPS, used.wave_ops), + (flags::INT64, used.int64), + (flags::TYPED_UAV_LOADS, used.typed_uav_loads), + (flags::RESOURCE_HEAP, used.heap_views), + (flags::SAMPLER_HEAP, used.heap_samplers), + (flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64, used.atomic64), + ] { + if !used { + self.flags &= !flag; + } + } + } + // Unordered views outside pixel and compute programs (memory by + // address), as DXC counts them: ranges declared below, not views + // picked from the heap (VIctory a1a2077a, by way of + // avatarmanz/VIctory-7900XTX 9a6c829d). + let compute = self.threads.is_some() && self.mesh.is_none() && self.geometry.is_none(); + if !self.root_uavs.is_empty() && !self.pixel && !compute { + self.flags |= flags::UAVS_EVERY_STAGE; + } let mut resources = None; let mut bindings = Vec::new(); let i32c = |s: &mut Self, v: u32| { @@ -333,6 +526,7 @@ impl Shader { || self.samplers > 0 || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() + || !self.root_uavs.is_empty() { let empty = self.m.md_str(""); let mut cbvs = None; @@ -416,6 +610,43 @@ impl Shader { } srvs = Some(self.m.md_node(list)); } + let mut uavs = None; + if !self.root_uavs.is_empty() { + let ty = self + .m + .named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let no = self.m.bool(false); + let no = self.m.md_value(no); + let mut list = Vec::new(); + for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() { + // Id, variable, name, space, lower bound, range size, + // shape (11: raw buffer), globally coherent, counter, + // rasterizer ordered, no extra properties. + let ops = vec![ + Some(i32c(&mut self, n as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(no), + Some(no), + Some(no), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 7, + space: ROOT_CBV_SPACE, + register: u32::from(slot), + dxil_kind: 11, + }); + } + uavs = Some(self.m.md_node(list)); + } let mut samplers = None; if self.samplers > 0 { let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]); @@ -445,11 +676,12 @@ impl Shader { } samplers = Some(self.m.md_node(list)); } - resources = Some(self.m.md_node(vec![srvs, None, cbvs, samplers])); - // PSV0 lists them as the module does: CBVs, samplers, SRVs. + resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers])); + // PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs. bindings.sort_by_key(|b| match b.kind { 2 => 0, 1 => 1, + 7 => 3, _ => 2, }); } @@ -483,6 +715,11 @@ impl Shader { }); } } + // A geometry shader lists four streams: the other three have + // no outputs. + if self.geometry.is_some() { + view.extend([0, 0, 0]); + } let arr = self.m.array(view.len() as u32, self.t.i32); let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect(); let arr = self.m.aggregate(arr, &elems); @@ -503,8 +740,8 @@ impl Shader { if self.pixel && self.outputs.iter().any(|o| o.kind == 20) { self.flags |= flags::STENCIL_REF; } - // Entry properties: shader flags (tag 0), thread-group size (4), - // wave size (11). + // Entry properties: shader flags (tag 0), geometry state (1), + // thread-group size (4), wave size (11). let mut props = Vec::new(); if self.flags != 0 { props.push(i32c(&mut self, 0)); @@ -512,6 +749,13 @@ impl Shader { let f = self.m.int_const(i64t, self.flags as i64); props.push(self.m.md_value(f)); } + if let Some(g) = self.geometry { + // Input primitive (3: triangles), maximum vertices, stream + // mask, output topology (5: triangle strips), instances. + props.push(i32c(&mut self, 1)); + let state = [3, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n))); + props.push(self.m.md_node(state.to_vec())); + } if let Some(threads) = self.threads { let t = threads.map(|n| Some(i32c(&mut self, n))); let t = self.m.md_node(t.to_vec()); @@ -558,9 +802,10 @@ impl Shader { let version = self.m.md_node(vec![Some(one), Some(six)]); self.m.named_md("dx.version", vec![version]); self.m.named_md("dx.valver", vec![version]); - // Program kinds: 0 pixel, 1 vertex, 5 compute, 13 mesh. + // Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh. let (name, kind) = match (self.threads, self.pixel) { _ if self.mesh.is_some() => ("ms", 13u32), + _ if self.geometry.is_some() => ("gs", 2), (Some(_), _) => ("cs", 5u32), (None, true) => ("ps", 0), (None, false) => ("vs", 1), @@ -571,6 +816,7 @@ impl Shader { self.m.named_md("dx.entryPoints", vec![entry]); let bitcode = self.m.write(); + super::bitcode::census::note(&self.m, &bitcode); let mut dxil = Vec::with_capacity(24 + bitcode.len()); dxil.extend((kind << 16 | 0x66).to_le_bytes()); dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes()); @@ -581,6 +827,12 @@ impl Shader { dxil.extend(&bitcode); let mut features = 0u64; + if self.flags & flags::DOUBLES != 0 { + features |= 0x1; + } + if self.flags & flags::UAVS_EVERY_STAGE != 0 { + features |= 0x4; + } if self.flags & flags::STENCIL_REF != 0 { features |= 0x200; } @@ -593,6 +845,9 @@ impl Shader { if self.flags & flags::INT64 != 0 { features |= 0x8000; } + if self.flags & flags::BARYCENTRICS != 0 { + features |= 0x2_0000; + } if self.flags & flags::RESOURCE_HEAP != 0 { features |= 0x200_0000; } @@ -620,6 +875,7 @@ impl Shader { outputs: &self.outputs, prims: &self.prims, mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)), + geometry: self.geometry.map(|g| g.max_vertices), bindings: &bindings, threads: self.threads.unwrap_or_default(), wave_size: self.wave_size, diff --git a/crates/victory-shader/src/emit/spin.rs b/crates/victory-shader/src/emit/spin.rs deleted file mode 100644 index 63de5bea4a..0000000000 --- a/crates/victory-shader/src/emit/spin.rs +++ /dev/null @@ -1,478 +0,0 @@ -//! Loops that only wait for memory to change (spin waits). -//! -//! A spin wait reads the same address again and again until another -//! workgroup, queue or the command processor writes it: decoupled -//! look-back prefix sums, persistent-thread queues, locks. On the console -//! the write comes within microseconds. On the host it may never come: the -//! writer's view can be another host resource than the reader's, null -//! (reads zeros) or not mirrored yet, and the host compiler may hoist a -//! load out of a loop that writes nothing. Such a loop then runs to the -//! iteration limit in every lane, 2^20 uncached reads: about a second per -//! wave. These loops get a much smaller limit ([`super::spin_limit`]). -//! -//! A loop counts as one only when nothing in it can have an effect the -//! limit would cut short: no stores, exports, LDS writes, barriers or -//! messages; every memory read and atomic at an address the loop does not -//! change; and no loop-carried value made by arithmetic (a counter means -//! the loop does work per iteration). What it carries are lane masks, -//! compare results and what it read. - -use std::collections::{HashMap, HashSet}; - -use crate::gfx10::{Fields, Operand}; -use crate::ir::{EXEC, Program, Reg, Value}; - -/// Headers (IR block indices) of the loops that only wait for memory. -pub(super) fn spin_loops(p: &Program) -> HashSet<usize> { - let order = crate::ir::reverse_postorder(&p.blocks); - let mut rpo = vec![usize::MAX; p.blocks.len()]; - for (n, &b) in order.iter().enumerate() { - rpo[b] = n; - } - let mut found = HashSet::new(); - for &h in &order { - let latches: Vec<usize> = p.blocks[h] - .preds - .iter() - .copied() - .filter(|&q| rpo[q] != usize::MAX && rpo[h] <= rpo[q]) - .collect(); - if latches.is_empty() { - continue; - } - if Loop::new(p, h, &latches, &rpo).waits_only() { - found.insert(h); - } - } - found -} - -#[derive(Clone, Copy)] -enum Def { - Phi(usize, usize), - Inst(usize, usize), -} - -/// What an instruction does to memory, for the spin test. -#[derive(PartialEq)] -enum Access { - /// Reads (or an atomic): fine at an address the loop keeps. - Read, - /// Writes or synchronises: the loop does work. - Effect, - /// Registers only. - None, -} - -struct Loop<'a> { - p: &'a Program, - header: usize, - body: HashSet<usize>, - defs: HashMap<Value, Def>, - /// Phis that merge one value with themselves, by that value. - alias: HashMap<Value, Value>, -} - -impl<'a> Loop<'a> { - fn new(p: &'a Program, header: usize, latches: &[usize], rpo: &[usize]) -> Self { - let mut body = HashSet::from([header]); - let mut work = latches.to_vec(); - while let Some(b) = work.pop() { - if body.insert(b) { - work.extend(p.blocks[b].preds.iter().filter(|&&q| rpo[q] != usize::MAX)); - } - } - let mut defs = HashMap::new(); - for &b in &body { - for (i, phi) in p.blocks[b].phis.iter().enumerate() { - defs.insert(phi.value, Def::Phi(b, i)); - } - for (i, inst) in p.blocks[b].insts.iter().enumerate() { - for &(_, v) in &inst.writes { - defs.insert(v, Def::Inst(b, i)); - } - } - } - let mut l = Loop { - p, - header, - body, - defs, - alias: HashMap::new(), - }; - // Registers the loop does not write still get phis at its header: - // each merges one value with itself. - loop { - let mut changed = false; - for &b in &l.body { - for phi in &p.blocks[b].phis { - if l.alias.contains_key(&phi.value) { - continue; - } - let mut other = None; - let trivial = phi.args.iter().all(|&a| { - let a = l.resolve(a); - a == phi.value || *other.get_or_insert(a) == a - }); - if trivial && let Some(o) = other { - l.alias.insert(phi.value, o); - changed = true; - } - } - } - if !changed { - break; - } - } - l - } - - fn resolve(&self, mut v: Value) -> Value { - // Aliases form no cycle: each points at a value made earlier. - for _ in 0..64 { - match self.alias.get(&v) { - Some(&a) => v = a, - None => break, - } - } - v - } - - fn waits_only(&self) -> bool { - let mut reads = 0; - let mut memo = HashMap::new(); - for &b in &self.body { - for inst in &self.p.blocks[b].insts { - match access(inst) { - Access::Effect => return false, - Access::None => {} - Access::Read => { - reads += 1; - let kept = address(inst) - .into_iter() - .filter_map(|r| inst.read(r)) - .all(|v| self.invariant(v, &mut memo)); - if !kept { - return false; - } - } - } - } - } - if reads == 0 { - return false; - } - // What goes round the loop: no counter. - let mut seen = HashSet::new(); - self.p.blocks[self.header] - .phis - .iter() - .filter(|phi| !self.alias.contains_key(&phi.value)) - .all(|phi| self.carried_ok(phi.value, &mut seen)) - } - - /// Whether `v` is the same in every iteration. - fn invariant(&self, v: Value, memo: &mut HashMap<Value, bool>) -> bool { - let v = self.resolve(v); - let Some(&def) = self.defs.get(&v) else { - return true; - }; - if let Some(&known) = memo.get(&v) { - return known; - } - let r = match def { - Def::Phi(..) => false, - Def::Inst(b, i) => { - let inst = &self.p.blocks[b].insts[i]; - let valu = matches!(inst.fields, Fields::Valu(_)); - let name = inst.name(); - let lane_wise = valu - && !name.starts_with("v_readfirstlane") - && !name.starts_with("v_readlane") - && !name.starts_with("v_cmp"); - matches!(inst.fields, Fields::Sop { .. } | Fields::Valu(_)) - && inst - .reads - .iter() - .filter(|(r, _)| !(lane_wise && is_exec(*r))) - .all(|&(_, x)| self.invariant(x, memo)) - } - }; - memo.insert(v, r); - r - } - - /// Whether loop-carried `v` holds what the loop read, lane masks or - /// compare results, and nothing computed by arithmetic. - fn carried_ok(&self, v: Value, seen: &mut HashSet<Value>) -> bool { - let v = self.resolve(v); - if !seen.insert(v) { - return true; - } - match self.defs.get(&v) { - None => true, - Some(&Def::Phi(b, i)) => self.p.blocks[b].phis[i] - .args - .iter() - .all(|&a| self.carried_ok(a, seen)), - Some(&Def::Inst(b, i)) => { - let inst = &self.p.blocks[b].insts[i]; - let name = inst.name(); - if access(inst) == Access::Read || mask_op(name) { - return true; - } - if copy_op(name) { - let valu = matches!(inst.fields, Fields::Valu(_)); - return inst - .reads - .iter() - .filter(|(r, _)| !(valu && is_exec(*r))) - .all(|&(_, x)| self.carried_ok(x, seen)); - } - false - } - } - } -} - -fn is_exec(r: Reg) -> bool { - matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) -} - -/// Lane-mask bookkeeping and compares: what every divergent loop carries. -fn mask_op(name: &str) -> bool { - [ - "s_and_", "s_or_", "s_xor_", "s_andn2_", "s_orn2_", "s_nand_", "s_nor_", "s_xnor_", - "s_not_", "s_cmp_", "s_cmpk_", "s_bitcmp", "v_cmp_", "v_cmpx_", - ] - .iter() - .any(|p| name.starts_with(p)) -} - -/// Moves and selects: carry what they copy. -fn copy_op(name: &str) -> bool { - name.starts_with("s_mov_") - || name.starts_with("s_cmov_") - || name.starts_with("s_cselect_") - || name.starts_with("v_mov_b32") - || name.starts_with("v_cndmask_b32") - || name.starts_with("v_readfirstlane_b32") - || name.starts_with("v_readlane_b32") -} - -fn access(inst: &crate::ir::Inst) -> Access { - let name = inst.name(); - match &inst.fields { - Fields::Exp { .. } => Access::Effect, - Fields::Sopp { .. } => { - if name == "s_barrier" || name.starts_with("s_sendmsg") || name.starts_with("s_trap") { - Access::Effect - } else { - Access::None - } - } - Fields::Sop { .. } | Fields::Valu(_) | Fields::Vintrp { .. } => Access::None, - Fields::Smem { data, .. } => { - if name.contains("store") || name.contains("atomic") { - Access::Effect - } else if data.is_some() { - Access::Read - } else { - Access::None - } - } - Fields::Buffer { lds, .. } => { - if *lds || name.contains("store") { - Access::Effect - } else if name.contains("load") || name.contains("atomic") { - Access::Read - } else { - // Cache invalidations. - Access::None - } - } - Fields::Image { .. } => { - if name.contains("store") { - Access::Effect - } else { - Access::Read - } - } - Fields::Ds { gds, .. } => { - if *gds { - Access::Effect - } else if name.starts_with("ds_read") { - Access::Read - } else if name.starts_with("ds_swizzle") || name.contains("permute") { - Access::None - } else { - Access::Effect - } - } - Fields::Flat { .. } => { - if name.starts_with("global_load_") { - Access::Read - } else { - Access::Effect - } - } - } -} - -/// The registers that make up a memory access's address. -fn address(inst: &crate::ir::Inst) -> Vec<Reg> { - let mut regs = Vec::new(); - let mut add = |o: &Operand| match *o { - Operand::Scalar { code, dwords } => { - regs.extend((0..dwords).map(|k| Reg::S(code.wrapping_add(k)))); - } - Operand::Vector { reg, dwords } => { - regs.extend((0..dwords).map(|k| Reg::V(reg.wrapping_add(k)))); - } - _ => {} - }; - match &inst.fields { - Fields::Smem { base, soffset, .. } => { - add(base); - add(soffset); - } - Fields::Buffer { - addr, - rsrc, - soffset, - offen, - idxen, - .. - } => { - add(rsrc); - add(soffset); - if *offen || *idxen { - add(addr); - } - } - Fields::Image { - addr, - rsrc, - sampler, - .. - } => { - add(rsrc); - if let Some(s) = sampler { - add(s); - } - addr.iter().for_each(&mut add); - } - Fields::Ds { addr: Some(a), .. } => add(a), - Fields::Flat { addr, saddr, .. } => { - if let Some(a) = addr { - add(a); - } - if let Some(s) = saddr { - add(s); - } - } - _ => {} - } - regs -} - -#[cfg(test)] -mod tests { - use super::spin_loops; - use crate::ir; - - const S_ENDPGM: u32 = 0xBF81_0000; - - fn spins(words: &[u32]) -> Vec<usize> { - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let p = ir::build(&code, false, 256).unwrap(); - let mut h: Vec<usize> = spin_loops(&p).into_iter().collect(); - h.sort_unstable(); - h - } - - #[test] - fn a_loop_rereading_one_flag_is_a_spin_wait() { - // Each lane waits until its flag (at v0 in the buffer at s[8:11]) - // is no longer 0. - let words = [ - 0xBE82_0380, // s_mov_b32 s2, 0 - 0xE030_6000, - 0x8002_0100, // 4: buffer_load_dword v1, v0, s[8:11], 0 idxen glc - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 - 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 - 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 - 0xBF89_FFF9, // s_cbranch_execnz -> 4 - 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 - S_ENDPGM, - ]; - assert_eq!(spins(&words).len(), 1); - } - - #[test] - fn a_loop_that_stores_or_counts_is_not() { - // The same with a store of the flag back: work per iteration. - let stores = [ - 0xBE82_0380, // s_mov_b32 s2, 0 - 0xE030_6000, - 0x8002_0100, // 4: buffer_load_dword v1, v0, s[8:11], 0 idxen glc - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0xE070_2000, - 0x8002_0100, // buffer_store_dword v1, v0, s[8:11], 0 idxen - 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 - 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 - 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 - 0xBF89_FFF7, // s_cbranch_execnz -> 4 - 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 - S_ENDPGM, - ]; - assert_eq!(spins(&stores), Vec::<usize>::new()); - // A loop walking the buffer: the address moves. - let walks = [ - 0xBE82_0380, // s_mov_b32 s2, 0 - 0xE030_6000, - 0x8002_0100, // 4: buffer_load_dword v1, v0, s[8:11], 0 idxen glc - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0x4A00_0081, // v_add_nc_u32 v0, 1, v0 - 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 - 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 - 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 - 0xBF89_FFF8, // s_cbranch_execnz -> 4 - 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 - S_ENDPGM, - ]; - assert_eq!(spins(&walks), Vec::<usize>::new()); - // Rereading one address while counting: a loop with work to do. - let counts = [ - 0xBE82_0380, // s_mov_b32 s2, 0 - 0xE030_6000, - 0x8002_0100, // 4: buffer_load_dword v1, v0, s[8:11], 0 idxen glc - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0x4A04_0481, // v_add_nc_u32 v2, 1, v2 - 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 - 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 - 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 - 0xBF89_FFF8, // s_cbranch_execnz -> 4 - 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 - S_ENDPGM, - ]; - assert_eq!(spins(&counts), Vec::<usize>::new()); - } - - #[test] - fn a_loop_without_memory_reads_is_not() { - // The divergent counting loop of the structure tests (wave32). - let words = [ - 0xBE82_0380, // s_mov_b32 s2, 0 - 0x4A00_0081, // 4: v_add_nc_u32 v0, 1, v0 - 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 - 0x8802_026A, // s_or_b32 s2, vcc_lo, s2 - 0x8A7E_027E, // s_andn2_b32 exec_lo, exec_lo, s2 - 0xBF89_FFFB, // s_cbranch_execnz -> 4 - 0x887E_027E, // s_or_b32 exec_lo, exec_lo, s2 - S_ENDPGM, - ]; - assert_eq!(spins(&words), Vec::<usize>::new()); - } -} diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs index c464d5ea6c..bc212e2ca6 100644 --- a/crates/victory-shader/src/emit/validator.rs +++ b/crates/victory-shader/src/emit/validator.rs @@ -8,7 +8,6 @@ use std::ffi::c_void; use std::path::{Path, PathBuf}; -use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE}; use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; type Hresult = i32; @@ -111,7 +110,6 @@ static BLOB_VTABLE: BlobVtable = BlobVtable { pub struct Validator { object: Object, - module: HMODULE, } pub(super) const SDK_BIN: &str = r"C:\Program Files (x86)\Windows Kits\10\bin"; @@ -126,8 +124,7 @@ pub(super) fn sdk_tool(kits: &Path, name: &str) -> Option<PathBuf> { } // SAFETY: the validator object is free-threaded (DXC's validator has no -// thread affinity) and the module handle is process-wide; calls are -// serialised by `&mut self`. +// thread affinity); calls are serialised by `&mut self`. unsafe impl Send for Validator {} impl Validator { @@ -150,26 +147,18 @@ impl Validator { unsafe { let module = LoadLibraryW(name.as_ptr()); if module.is_null() { - return Err(format!( - "cannot load {}", - String::from_utf16_lossy(&name[..name.len() - 1]) - )); + return Err(format!("cannot load {}", String::from_utf16_lossy(&name))); } - let Some(create) = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast()) else { - FreeLibrary(module); - return Err("dxil.dll lacks DxcCreateInstance".into()); - }; + let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast()) + .ok_or("dxil.dll lacks DxcCreateInstance")?; let create: CreateInstance = std::mem::transmute(create); let mut object = std::ptr::null_mut(); let hr = create(&CLSID_DXC_VALIDATOR, &IID_IDXC_VALIDATOR, &mut object); if hr < 0 || object.is_null() { - release(object.cast()); - FreeLibrary(module); return Err(format!("DxcCreateInstance(validator) failed: {hr:#x}")); } Ok(Validator { object: object.cast(), - module, }) } } @@ -195,19 +184,12 @@ impl Validator { ) -> Hresult = method(self.object, 3); let hr = validate(self.object, &mut blob, IN_PLACE_EDIT, &mut result); if hr < 0 || result.is_null() { - if !result.is_null() { - release(result); - } return Err(format!("Validate failed: {hr:#x}")); } let mut status = 0; let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult = method(result, 3); - let status_hr = get_status(result, &mut status); - if status_hr < 0 { - release(result); - return Err(format!("GetStatus failed: {status_hr:#x}")); - } + get_status(result, &mut status); let mut text = String::new(); if status < 0 { let mut errors: Object = std::ptr::null_mut(); @@ -216,16 +198,13 @@ impl Validator { if get_errors(result, &mut errors) >= 0 && !errors.is_null() { let ptr: unsafe extern "system" fn(Object) -> *const u8 = method(errors, 3); let len: unsafe extern "system" fn(Object) -> usize = method(errors, 4); - let (p, n) = (ptr(errors), len(errors)); - if !p.is_null() && n > 0 { - let bytes = std::slice::from_raw_parts(p, n); - text = String::from_utf8_lossy(bytes) - .trim_end_matches('\0') - .trim() - .into(); - } + let bytes = std::slice::from_raw_parts(ptr(errors), len(errors)); + text = String::from_utf8_lossy(bytes) + .trim_end_matches('\0') + .trim() + .into(); + release(errors); } - release(errors); if text.is_empty() { text = format!("rejected ({status:#x})"); } @@ -238,374 +217,7 @@ impl Validator { impl Drop for Validator { fn drop(&mut self) { - // SAFETY: we own one reference to the validator object and, when loaded - // from a DLL, one module handle; release the object before unloading - // the DLL that implements its vtable. - unsafe { - release(self.object); - if !self.module.is_null() { - FreeLibrary(self.module); - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; - - const E_FAIL: Hresult = 0x8000_4005_u32 as i32; - const E_NOINTERFACE: Hresult = 0x8000_4002_u32 as i32; - - #[repr(C)] - struct ErrorBlobVtable { - qi: unsafe extern "system" fn( - *mut MockErrorBlob, - *const [u8; 16], - *mut *mut c_void, - ) -> Hresult, - add_ref: unsafe extern "system" fn(*mut MockErrorBlob) -> u32, - release: unsafe extern "system" fn(*mut MockErrorBlob) -> u32, - ptr: unsafe extern "system" fn(*mut MockErrorBlob) -> *const u8, - len: unsafe extern "system" fn(*mut MockErrorBlob) -> usize, - } - - #[repr(C)] - struct MockErrorBlob { - vtable: *const ErrorBlobVtable, - ptr: *const u8, - len: usize, - releases: usize, - } - - unsafe extern "system" fn mock_blob_qi( - _: *mut MockErrorBlob, - _: *const [u8; 16], - out: *mut *mut c_void, - ) -> Hresult { - // SAFETY: caller provides a writable output pointer. - unsafe { *out = std::ptr::null_mut() }; - E_NOINTERFACE - } - - unsafe extern "system" fn mock_blob_add_ref(_: *mut MockErrorBlob) -> u32 { - 1 - } - - unsafe extern "system" fn mock_blob_release(this: *mut MockErrorBlob) -> u32 { - // SAFETY: `this` points to a live `MockErrorBlob` on the test stack. - unsafe { - (*this).releases += 1; - } - 0 - } - - unsafe extern "system" fn mock_blob_ptr(this: *mut MockErrorBlob) -> *const u8 { - // SAFETY: `this` points to a live `MockErrorBlob` on the test stack. - unsafe { (*this).ptr } - } - - unsafe extern "system" fn mock_blob_len(this: *mut MockErrorBlob) -> usize { - // SAFETY: `this` points to a live `MockErrorBlob` on the test stack. - unsafe { (*this).len } - } - - static MOCK_ERROR_BLOB_VTABLE: ErrorBlobVtable = ErrorBlobVtable { - qi: mock_blob_qi, - add_ref: mock_blob_add_ref, - release: mock_blob_release, - ptr: mock_blob_ptr, - len: mock_blob_len, - }; - - #[repr(C)] - struct ResultVtable { - qi: unsafe extern "system" fn( - *mut MockResult, - *const [u8; 16], - *mut *mut c_void, - ) -> Hresult, - add_ref: unsafe extern "system" fn(*mut MockResult) -> u32, - release: unsafe extern "system" fn(*mut MockResult) -> u32, - get_status: unsafe extern "system" fn(*mut MockResult, *mut Hresult) -> Hresult, - get_result: unsafe extern "system" fn(*mut MockResult, *mut Object) -> Hresult, - get_errors: unsafe extern "system" fn(*mut MockResult, *mut Object) -> Hresult, - } - - #[repr(C)] - struct MockResult { - vtable: *const ResultVtable, - status_hr: Hresult, - status: Hresult, - error_hr: Hresult, - error_blob: Object, - releases: usize, - } - - unsafe extern "system" fn mock_result_qi( - _: *mut MockResult, - _: *const [u8; 16], - out: *mut *mut c_void, - ) -> Hresult { - // SAFETY: caller provides a writable output pointer. - unsafe { *out = std::ptr::null_mut() }; - E_NOINTERFACE - } - - unsafe extern "system" fn mock_result_add_ref(_: *mut MockResult) -> u32 { - 1 - } - - unsafe extern "system" fn mock_result_release(this: *mut MockResult) -> u32 { - // SAFETY: `this` points to a live `MockResult` on the test stack. - unsafe { - (*this).releases += 1; - } - 0 - } - - unsafe extern "system" fn mock_result_get_status( - this: *mut MockResult, - out: *mut Hresult, - ) -> Hresult { - // SAFETY: `this` and `out` are valid pointers for this mock call. - unsafe { - *out = (*this).status; - (*this).status_hr - } - } - - unsafe extern "system" fn mock_result_get_result( - _: *mut MockResult, - out: *mut Object, - ) -> Hresult { - // SAFETY: caller provides a writable output pointer. - unsafe { *out = std::ptr::null_mut() }; - E_FAIL - } - - unsafe extern "system" fn mock_result_get_errors( - this: *mut MockResult, - out: *mut Object, - ) -> Hresult { - // SAFETY: `this` and `out` are valid pointers for this mock call. - unsafe { - *out = (*this).error_blob; - (*this).error_hr - } - } - - static MOCK_RESULT_VTABLE: ResultVtable = ResultVtable { - qi: mock_result_qi, - add_ref: mock_result_add_ref, - release: mock_result_release, - get_status: mock_result_get_status, - get_result: mock_result_get_result, - get_errors: mock_result_get_errors, - }; - - #[repr(C)] - struct ValidatorVtable { - qi: unsafe extern "system" fn( - *mut MockValidator, - *const [u8; 16], - *mut *mut c_void, - ) -> Hresult, - add_ref: unsafe extern "system" fn(*mut MockValidator) -> u32, - release: unsafe extern "system" fn(*mut MockValidator) -> u32, - validate: - unsafe extern "system" fn(*mut MockValidator, *mut Blob, u32, *mut Object) -> Hresult, - } - - #[repr(C)] - struct MockValidator { - vtable: *const ValidatorVtable, - validate_hr: Hresult, - result: Object, - releases: usize, - } - - unsafe extern "system" fn mock_val_qi( - _: *mut MockValidator, - _: *const [u8; 16], - out: *mut *mut c_void, - ) -> Hresult { - // SAFETY: caller provides a writable output pointer. - unsafe { *out = std::ptr::null_mut() }; - E_NOINTERFACE - } - - unsafe extern "system" fn mock_val_add_ref(_: *mut MockValidator) -> u32 { - 1 - } - - unsafe extern "system" fn mock_val_release(this: *mut MockValidator) -> u32 { - // SAFETY: `this` points to a live `MockValidator` on the test stack. - unsafe { - (*this).releases += 1; - } - 0 - } - - unsafe extern "system" fn mock_val_validate( - this: *mut MockValidator, - _: *mut Blob, - _: u32, - out: *mut Object, - ) -> Hresult { - // SAFETY: `this` and `out` are valid pointers for this mock call. - unsafe { - *out = (*this).result; - (*this).validate_hr - } - } - - static MOCK_VALIDATOR_VTABLE: ValidatorVtable = ValidatorVtable { - qi: mock_val_qi, - add_ref: mock_val_add_ref, - release: mock_val_release, - validate: mock_val_validate, - }; - - #[test] - fn get_status_failure_returns_err_and_releases_result() { - let mut mock_res = MockResult { - vtable: &MOCK_RESULT_VTABLE, - status_hr: E_FAIL, - status: 0, - error_hr: E_FAIL, - error_blob: std::ptr::null_mut(), - releases: 0, - }; - let mut mock_val = MockValidator { - vtable: &MOCK_VALIDATOR_VTABLE, - validate_hr: 0, - result: (&raw mut mock_res).cast(), - releases: 0, - }; - let mut v = Validator { - object: (&raw mut mock_val).cast(), - module: std::ptr::null_mut(), - }; - let mut buf = [0u8; 4]; - let Err(err) = v.validate(&mut buf) else { - panic!("expected GetStatus failure"); - }; - assert_eq!(err, format!("GetStatus failed: {E_FAIL:#x}")); - assert_eq!(mock_res.releases, 1); - drop(v); - assert_eq!(mock_val.releases, 1); - } - - #[test] - fn null_empty_error_blob_falls_back_without_ub() { - let dummy = *b"x"; - let cases = [ - (std::ptr::null(), 0), - (std::ptr::null(), 16), - (dummy.as_ptr(), 0), - ]; - for (ptr, len) in cases { - let mut mock_blob = MockErrorBlob { - vtable: &MOCK_ERROR_BLOB_VTABLE, - ptr, - len, - releases: 0, - }; - let mut mock_res = MockResult { - vtable: &MOCK_RESULT_VTABLE, - status_hr: 0, - status: E_FAIL, - error_hr: 0, - error_blob: (&raw mut mock_blob).cast(), - releases: 0, - }; - let mut mock_val = MockValidator { - vtable: &MOCK_VALIDATOR_VTABLE, - validate_hr: 0, - result: (&raw mut mock_res).cast(), - releases: 0, - }; - let mut v = Validator { - object: (&raw mut mock_val).cast(), - module: std::ptr::null_mut(), - }; - let mut buf = [0u8; 4]; - let Err(err) = v.validate(&mut buf) else { - panic!("expected validation rejection"); - }; - assert_eq!(err, format!("rejected ({E_FAIL:#x})")); - assert_eq!(mock_blob.releases, 1); - assert_eq!(mock_res.releases, 1); - drop(v); - assert_eq!(mock_val.releases, 1); - } - } - - #[test] - fn validate_error_with_non_null_result_releases_result() { - let mut mock_res = MockResult { - vtable: &MOCK_RESULT_VTABLE, - status_hr: 0, - status: 0, - error_hr: 0, - error_blob: std::ptr::null_mut(), - releases: 0, - }; - let mut mock_val = MockValidator { - vtable: &MOCK_VALIDATOR_VTABLE, - validate_hr: E_FAIL, - result: (&raw mut mock_res).cast(), - releases: 0, - }; - let mut v = Validator { - object: (&raw mut mock_val).cast(), - module: std::ptr::null_mut(), - }; - let mut buf = [0u8; 4]; - let Err(err) = v.validate(&mut buf) else { - panic!("expected Validate failure"); - }; - assert_eq!(err, format!("Validate failed: {E_FAIL:#x}")); - assert_eq!(mock_res.releases, 1); - drop(v); - assert_eq!(mock_val.releases, 1); - } - - #[test] - fn load_errors_strip_nul_and_free_module() { - let missing = std::path::Path::new("victory_missing_validator_test.dll"); - let Err(err) = Validator::load(Some(missing)) else { - panic!("loading missing DLL unexpectedly succeeded"); - }; - assert!(!err.contains('\0'), "NUL byte leaked into error: {err:?}"); - assert!( - err.contains("victory_missing_validator_test.dll"), - "unexpected missing-DLL error: {err:?}" - ); - - let candidates = ["cabinet.dll", "msimg32.dll", "lz32.dll", "version.dll"]; - let mut target = None; - for dll in candidates { - let wide: Vec<u16> = dll.encode_utf16().chain([0]).collect(); - // SAFETY: `wide` is a NUL-terminated UTF-16 DLL name. - let handle = unsafe { GetModuleHandleW(wide.as_ptr()) }; - if handle.is_null() { - target = Some((dll, wide)); - break; - } - } - let (dll, wide) = target.expect("all candidate system DLLs are already loaded"); - let Err(err) = Validator::load(Some(std::path::Path::new(dll))) else { - panic!("loading {dll} as a validator unexpectedly succeeded"); - }; - assert!( - err.contains("DxcCreateInstance"), - "expected GetProcAddress failure for {dll}, got: {err:?}" - ); - // SAFETY: `wide` is a NUL-terminated UTF-16 DLL name. - let after = unsafe { GetModuleHandleW(wide.as_ptr()) }; - assert!(after.is_null(), "{dll} remained loaded after failed load"); + // SAFETY: we own one reference. + unsafe { release(self.object) }; } } diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index d8a0e8a71c..264a95ee88 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -3,7 +3,8 @@ //! //! Covers RDNA2 hardware semantics that differ from naive DXIL lowering: //! `v_med3_f32`/`v_med3_f16` with NaN operands, `v_fract_f32`/`v_fract_f16` -//! near `1.0`, and turn-range reduction for `v_sin_*`/`v_cos_*`. +//! near `1.0`, turn-range reduction for `v_sin_*`/`v_cos_*`, and the LDS +//! float atomics `ds_min_f32`/`ds_max_f32`. use super::host::{Dispatch, Host, Root, View}; use super::{HostShader, lower, validator}; @@ -40,49 +41,36 @@ const fn s_load_dwordx4(dst: u8, base: u8) -> [u32; 2] { const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) } -/// VOP1 SDWA `op_sdwa vdst, vsrc0 dst_sel dst_unused src0_sel`. -const fn vop1_sdwa( - op: u16, - vdst: u8, - vsrc0: u8, - dst_sel: u8, - dst_unused: u8, - src0_sel: u8, -) -> [u32; 2] { - [ - vop1(op, vdst, 0xF9), - vsrc0 as u32 - | (dst_sel as u32 & 7) << 8 - | (dst_unused as u32 & 3) << 11 - | (src0_sel as u32 & 7) << 16, - ] + +/// VOP3 `op vdst, src0, src1, src2` (no modifiers). +const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + vop3_mod(op, vdst, src0, src1, src2, 0, 0, 0, false) } -/// VOP2 SDWA `op_sdwa vdst, vsrc0, vsrc1 dst_sel dst_unused src0_sel src1_sel`. -const fn vop2_sdwa( - op: u8, +/// VOP3 `op vdst, src0, src1, src2` with explicit `abs`, `neg`, `omod`, `clamp`. +#[allow(clippy::too_many_arguments)] +const fn vop3_mod( + op: u16, vdst: u8, - vsrc0: u8, - vsrc1: u8, - dst: (u8, u8), - src_sel: [u8; 2], + src0: u16, + src1: u16, + src2: u16, + abs: u8, + neg: u8, + omod: u8, + clamp: bool, ) -> [u32; 2] { [ - (op as u32) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | 0xF9, - vsrc0 as u32 - | (dst.0 as u32 & 7) << 8 - | (dst.1 as u32 & 3) << 11 - | (src_sel[0] as u32 & 7) << 16 - | (src_sel[1] as u32 & 7) << 24, - ] -} - - -/// VOP3 `op vdst, src0, src1, src2` (no modifiers). -const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { - [ - 0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32, - (src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18, + 0x35 << 26 + | (op as u32 & 0x3FF) << 16 + | (clamp as u32) << 15 + | (abs as u32 & 7) << 8 + | vdst as u32, + (neg as u32 & 7) << 29 + | (omod as u32 & 3) << 27 + | (src0 as u32 & 0x1FF) + | (src1 as u32 & 0x1FF) << 9 + | (src2 as u32 & 0x1FF) << 18, ] } @@ -106,6 +94,12 @@ const fn vgpr(n: u8) -> u16 { /// 4 dwords of root constants in `s0..s3`, runs `body` (leaving its result in /// `v0`), and stores `v0` to dword 0 of the raw UAV at heap index 0. fn build_valu_cs(body: &[u32]) -> HostShader { + build_cs(body, 1, 0) +} + +/// [`build_valu_cs`] with `threads` threads in x (thread index in `v0` +/// on entry, before `body`) and `lds_bytes` of LDS (a multiple of 512). +fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { let mut words = Vec::new(); // s[4:5] = descriptor table address (heap index 0 -> byte offset 0). words.push(s_mov_b32(5, 0x80)); // inline constant 0 @@ -153,8 +147,8 @@ fn build_valu_cs(body: &[u32]) -> HostShader { slot: 1, }], io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 - threads: [1, 1, 1], + rsrc2: (5 << 1) | ((lds_bytes / 512) << 15), // 5 user SGPRs: s0..s4 + threads: [threads, 1, 1], }), code, }; @@ -174,7 +168,6 @@ fn build_valu_cs(body: &[u32]) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - host_wave64: true, }) .expect("lower"); @@ -186,6 +179,9 @@ fn build_valu_cs(body: &[u32]) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -210,11 +206,20 @@ pub(super) static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(() fn run_cases( shader: &HostShader, cases: &[[u32; 4]], + check: impl FnMut(&str, usize, [u32; 4], u32), +) { + run_cases_on(shader, cases, &[("hardware", false), ("warp", true)], check); +} + +fn run_cases_on( + shader: &HostShader, + cases: &[[u32; 4]], + devices: &[(&str, bool)], mut check: impl FnMut(&str, usize, [u32; 4], u32), ) { let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut ran = 0; - for (label, warp) in [("hardware", false), ("warp", true)] { + for &(label, warp) in devices { let Ok(host) = Host::new(warp) else { eprintln!("no SM 6.6 {label} device; skipped"); continue; @@ -247,7 +252,12 @@ fn run_cases( } ran += 1; } - assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); + if ran == 0 && devices.iter().all(|&(_, warp)| !warp) { + // A case for the hardware adapter alone, on a machine without one. + eprintln!("no SM 6.6 hardware device; a hardware-only case not run"); + return; + } + assert!(ran > 0, "no SM 6.6 device available ({devices:?})"); } fn is_f16_nan(bits: u16) -> bool { @@ -299,6 +309,110 @@ fn packed_add_selects_halves_of_inline_constants() { } } +/// The float `v_cvt_f32_f64` gives for `x`: Rust's rounding (to nearest +/// even), with results below the smallest normal float flushed to signed +/// zero as the console's default float mode does. +fn cvt_f32_f64_reference(x: f64) -> u32 { + let r = x as f32; + if r.is_subnormal() || (r == 0.0 && x != 0.0) { + r.to_bits() & 0x8000_0000 + } else { + r.to_bits() + } +} + +#[test] +#[ignore = "expects results below the smallest normal float flushed to zero; the IEEE lowering (v_cvt_f32_f64_matches_ieee754) is kept until the console's mode is checked"] +fn v_cvt_f32_f64_rounds_to_nearest_even() { + // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x0f) + let shader = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]); + let tie_even = 1.0f64 + f64::from(f32::EPSILON) / 2.0; // ties to 1.0 + let tie_odd = 1.0f64 + 1.5 * f64::from(f32::EPSILON); // ties up to 1 + 2 ulp + let values = [ + 0.0, + -0.0, + 1.0, + -2.5, + std::f64::consts::PI, + 1.0e-3, + 123_456_789.123, + tie_even, + tie_odd, + 1.0 + f64::from(f32::EPSILON) * 0.75, + f64::from(f32::MAX), + f64::from(f32::MAX) * 1.000_000_1, // rounds to infinity + 1.0e300, + -1.0e300, + 1.0e-40, // a float denormal: flushed + -1.0e-300, + f64::from(f32::MIN_POSITIVE), + f64::INFINITY, + f64::NEG_INFINITY, + f64::NAN, + ]; + let inputs: Vec<[u32; 4]> = values + .iter() + .map(|x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let x = values[i]; + if x.is_nan() { + assert!(f32::from_bits(got).is_nan(), "{backend}: cvt({x}) = {got:#010x}, want NaN"); + return; + } + let want = cvt_f32_f64_reference(x); + assert_eq!(got, want, "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}"); + }); +} + +/// The lane `v_permlane16_b32` (`cross` false) or `v_permlanex16_b32` reads +/// for `lane`, with selector dwords `s1` (lanes 0-7 of a row) and `s2`. +fn permlane_source(lane: u32, s1: u32, s2: u32, cross: bool) -> u32 { + let sel = u64::from(s1) | u64::from(s2) << 32; + let pick = (sel >> (4 * (lane & 15)) & 15) as u32; + let row = if cross { + (lane & !31) | ((lane & 16) ^ 16) + } else { + lane & !15 + }; + row | pick +} + +#[test] +fn v_permlane16_and_x16_read_the_lanes_their_selectors_pick() { + // 32 lanes, each with its lane number in v0; v1 = permute(v0, s0, s1); + // lane `read` of v1 into s12, then into v0 for the store. + let selectors: [(u32, u32); 3] = [ + (0x7654_3210, 0xfedc_ba98), // identity within the row + (0x89ab_cdef, 0x0123_4567), // reversed + (0x1111_1111, 0xf0f0_f0f0), // repeats + ]; + for (op, cross) in [(0x377u16, false), (0x378, true)] { + for read in [0u8, 5, 15, 16, 22, 31] { + let mut body = Vec::new(); + body.extend_from_slice(&vop3(op, 1, vgpr(0), sgpr(0), sgpr(1))); + // v_readlane_b32 s12, v1, read (inline constant 128 + read) + body.extend_from_slice(&vop3(0x360, 12, vgpr(1), 128 + u16::from(read), 0)); + body.push(vop1(0x001, 0, sgpr(12))); // v_mov_b32 v0, s12 + let shader = build_cs(&body, 32, 0); + let inputs: Vec<[u32; 4]> = selectors.iter().map(|&(a, b)| [a, b, 0, 0]).collect(); + // Cross-lane code declares WaveSize(32), which WARP's pipeline + // creation refuses: hardware only. + run_cases_on(&shader, &inputs, &[("hardware", false)], |backend, i, inp, got| { + let want = permlane_source(u32::from(read), inp[0], inp[1], cross); + assert_eq!( + got, want, + "{backend}: op {op:#x} selectors {:08x?}, lane {read}", + selectors[i] + ); + }); + } + } +} + #[test] fn v_med3_f32_matches_rdna2_with_nan() { // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) @@ -414,147 +528,6 @@ fn v_med3_f16_matches_rdna2_with_nan() { }); } -/// The f16 nearest to `x`, ties to even, as the console's conversions -/// round (MODE's default); found by search over the f16 values, so it does -/// not share the lowering's bit arithmetic. -fn f16_nearest_reference(x: f32) -> u16 { - if x.is_nan() { - return 0x7E00; - } - let sign = if x.is_sign_negative() { 0x8000 } else { 0 }; - let a = f64::from(x.abs()); - if a >= 65520.0 { - return sign | 0x7C00; - } - // The largest finite half at or below `a` (halves order as their bits). - let (mut lo, mut hi) = (0u16, 0x7BFF); - while lo < hi { - let mid = (lo + hi).div_ceil(2); - if f64::from(f16_to_f32(mid)) <= a { - lo = mid; - } else { - hi = mid - 1; - } - } - let below = f64::from(f16_to_f32(lo)); - let above = if lo == 0x7BFF { - 65536.0 - } else { - f64::from(f16_to_f32(lo + 1)) - }; - let pick = if a - below < above - a || (a - below == above - a && lo % 2 == 0) { - lo - } else { - lo + 1 - }; - sign | pick -} - -#[test] -fn f32_to_f16_rounds_to_nearest_even() { - // Midpoints between neighbouring halves (ties), the f32 next to them, and - // a spread of f32 values from below the smallest subnormal to past 65504. - let mut inputs: Vec<f32> = Vec::new(); - for h in (0x0000u16..0x7BFF) - .step_by(613) - .chain([0x0000, 0x0001, 0x03FF, 0x0400, 0x3C00, 0x3C01, 0x7BFE]) - { - let mid = ((f64::from(f16_to_f32(h)) + f64::from(f16_to_f32(h + 1))) / 2.0) as f32; - inputs.extend([ - mid, - -mid, - f32::from_bits(mid.to_bits() + 1), - f32::from_bits(mid.to_bits() - 1), - ]); - } - let mut bits = 0x3280_0000u32; // 2^-26 - while bits < 0x4790_0000 { - inputs.push(f32::from_bits(bits)); - bits += 0x0013_3F7D; - } - inputs.extend([ - 65504.0, - 65519.99, - 65520.0, - 1.0e6, - f32::INFINITY, - f32::NEG_INFINITY, - f32::NAN, - -0.0, - 2.0f32.powi(-25), - f32::MIN_POSITIVE, - ]); - // v_mov_b32 v0, 0; v_cvt_f16_f32 v0, v1 (VOP1 0x00a). - let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(0x00A, 0, vgpr(1))]); - let cases: Vec<[u32; 4]> = inputs.iter().map(|x| [x.to_bits(), 0, 0, 0]).collect(); - run_cases(&shader, &cases, |backend, i, _, got| { - let (x, want) = (inputs[i], f16_nearest_reference(inputs[i])); - let got_h = got as u16; - if is_f16_nan(want) { - assert!( - is_f16_nan(got_h), - "{backend}: v_cvt_f16_f32({x:e}) = {got_h:#06x}, want NaN" - ); - } else { - assert_eq!( - got_h, - want, - "{backend}: v_cvt_f16_f32({x:e} = {:#010x}) = {got_h:#06x}, want {want:#06x}", - x.to_bits() - ); - } - }); - // f16 arithmetic narrows the same way: 1 + 2^-10 plus 2^-11 is a tie - // that goes to the even 1 + 2^-9 (toward zero would give 1 + 2^-10). - let mut body = vec![vop1(0x001, 0, 128)]; - body.extend_from_slice(&vop3(0x132, 0, vgpr(1), vgpr(2), 0)); // v_add_f16 v0, v1, v2 - let add = build_valu_cs(&body); - run_cases( - &add, - &[[0x3C01, 0x1000, 0, 0], [0x7BFF, 0x5000, 0, 0]], - |backend, i, _, got| { - let want = [0x3C02u32, 0x7C00][i]; - assert_eq!( - got, want, - "{backend}: v_add_f16 case {i} = {got:#06x}, want {want:#06x}" - ); - }, - ); - // v_cvt_pkrtz_f16_f32 still rounds toward zero: 1 + 3/2048 to 1 + 2^-10, - // 1e6 to the largest finite half, -1e-8 to -0. - let pkrtz = build_valu_cs(&vop3(0x12F, 0, vgpr(1), vgpr(2), 0)); - let (a, b) = ((1.0f32 + 3.0 / 2048.0).to_bits(), 1.0e6f32.to_bits()); - run_cases( - &pkrtz, - &[[a, b, 0, 0], [(-1.0e-8f32).to_bits(), a, 0, 0]], - |backend, i, _, got| { - let want = [0x7BFF_3C01u32, 0x3C01_8000][i]; - assert_eq!( - got, want, - "{backend}: v_cvt_pkrtz_f16_f32 case {i} = {got:#010x}, want {want:#010x}" - ); - }, - ); -} - -#[test] -fn v_fma_legacy_f32_follows_the_d3d9_zero_rule() { - // v_fma_legacy_f32 v0, v1, v2, v3 (VOP3 opcode 0x140 on RDNA2) - let shader = build_valu_cs(&vop3(0x140, 0, vgpr(1), vgpr(2), vgpr(3))); - let f = f32::to_bits; - let cases: &[([u32; 4], u32)] = &[ - ([f(2.0), f(3.0), f(1.0), 0], f(7.0)), - // A zero factor gives a zero product, whatever the other one is. - ([0, f(f32::INFINITY), f(1.5), 0], f(1.5)), - ([f(f32::NAN), 0, f(-2.0), 0], f(-2.0)), - ]; - let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); - run_cases(&shader, &inputs, |backend, i, _, got| { - let want = cases[i].1; - assert_eq!(got, want, "{backend}: case {i}: {got:#x}, want {want:#x}"); - }); -} - /// `v_cmp_lg_*` is "less or greater": ordered and not equal, so false when /// either operand is a NaN (RDNA2 ISA; the same on gfx1036 hardware). #[test] @@ -1013,38 +986,6 @@ fn v_sin_and_v_cos_f16_reduce_large_turns() { }); } -/// A 32-bit literal in a signed 64-bit operand is sign-extended (an -/// unsigned one's is zero-extended): -100 compared with `v[1:2]`, and -/// shifted by `s_ashr_i64`. -#[test] -fn signed_64_bit_operands_sign_extend_their_literal() { - const MINUS_100: u32 = -100_i32 as u32; - let check = |name: &str, body: &[u32], cases: &[([u32; 4], u32)]| { - let shader = build_valu_cs(body); - let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); - run_cases(&shader, &inputs, |backend, i, inp, got| { - let want = cases[i].1; - assert_eq!(got, want, "{backend}: {name} {inp:x?}"); - }); - }; - // v_cmp_*_i64 s6, v[1:2], -100 (VOP3, literal src1), then - // v_cndmask_b32 v0, 0, 1, s6. - let compare = |op: u16| { - let [a, b] = vop3(op, 6, vgpr(1), 255, 0); - let [c, d] = vop3(0x101, 0, 0x80, 0x81, sgpr(6)); - [a, b, MINUS_100, c, d] - }; - // An i64 as the two input dwords of `v[1:2]`. - let pair = |n: i64| [n as u32, (n >> 32) as u32, 0, 0]; - let eq = [(pair(-100), 1), ([MINUS_100, 0, 0, 0], 0), (pair(0), 0)]; - check("v_cmp_eq_i64", &compare(0x0A2), &eq); - let lt = [(pair(-200), 1), (pair(-50), 0), (pair(0), 0)]; - check("v_cmp_lt_i64", &compare(0x0A1), <); - // s_ashr_i64 s[6:7], -100, 4; v_mov_b32 v0, s7: the high dword. - let ashr = [sop2(0x23, 6, 255, 0x84), MINUS_100, vop1(0x001, 0, sgpr(7))]; - check("s_ashr_i64", &ashr, &[([0; 4], u32::MAX)]); -} - #[test] fn bfe_signed_and_unsigned_match_rdna2() { // v_bfe_i32 v0, v1, v2, v3 (VOP3 opcode 0x149) @@ -1119,1019 +1060,526 @@ fn bfe_signed_and_unsigned_match_rdna2() { } #[test] -fn v_cmp_class_f16_matches_rdna2() { - // v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6 - let cmp_lo = build_valu_cs(&[ - vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[0], - vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[1], - vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], - vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], - ]); - // Same with op_sel:[1,0] (high half of v1) + neg on src0 (bit 29 of w1). - let [mut w0, mut w1] = vop3(0x08f, 6, vgpr(1), vgpr(2), 0); - w0 |= 1 << 11; // opsel[0] = 1 (high half) - w1 |= 1 << 29; // neg[0] = 1 - let cmp_hi_neg = build_valu_cs(&[ - w0, - w1, - vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], - vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], - ]); - - // All 10 IEEE-754 binary16 classes: bit k corresponds to class k. - let classes: &[(u32, u32)] = &[ - (0x7C01, 0), // sNaN (+sNaN, quiet bit 0x0200 clear) - (0xFDFF, 0), // -sNaN (sign ignored for NaNs) - (0x7E00, 1), // +qNaN - (0xFE01, 1), // -qNaN - (0xFC00, 2), // -inf - (0xBC00, 3), // -normal (-1.0) - (0x8001, 4), // -denormal - (0x8000, 5), // -0.0 - (0x0000, 6), // +0.0 - (0x0001, 7), // +denormal - (0x3C00, 8), // +normal (+1.0) - (0x7C00, 9), // +inf - ]; - let mut cases = Vec::new(); - for &(bits, cls) in classes { - // Exact class bit -> true; complement of class bit across all 10 bits -> false. - cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); - cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); - } - let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); - run_cases(&cmp_lo, &inputs, |backend, i, inp, got| { - let want = cases[i].1; - assert_eq!( - got, want, - "{backend}: v_cmp_class_f16({:#06x}, {:#05x}) = {got}, want {want}", - inp[0], inp[1], - ); - }); +fn f16_omod_applies_before_clamp() { + // VOP3 v_add_f16 (0x132 = 0x100 + VOP2 0x32): v0 = (v1 + v2) * omod [clamp] + let mul2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 1, false)); + let mul4 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 2, false)); + let div2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, false)); + let div2_clamp = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, true)); - // High half with neg: high half 0x3C00 (+1.0) negated -> -normal (class 3); - // high half 0x7C01 (+sNaN) negated -> still sNaN (class 0, not quieted). - let hi_cases: &[([u32; 4], u32)] = &[ - ([0x3C00_0000, 1 << 3, 0, 0], 1), - ([0x3C00_0000, 1 << 8, 0, 0], 0), - ([0x7C01_FFFF, 1 << 0, 0, 0], 1), - ([0x7C01_FFFF, 1 << 1, 0, 0], 0), + // f16 constants: 0.25=0x3400, 0.5=0x3800, 0.75=0x3A00, 1.0=0x3C00, 1.5=0x3E00, 2.0=0x4000, -0.5=0xB800 + run_cases( + &mul2, + &[[0x3400, 0x3800, 0, 0]], // (0.25 + 0.5) * 2 = 1.5 (0x3E00) + |backend, _, _, got| { + assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 mul:2"); + }, + ); + run_cases( + &mul4, + &[[0x3400, 0x3400, 0, 0]], // (0.25 + 0.25) * 4 = 2.0 (0x4000) + |backend, _, _, got| { + assert_eq!(got as u16, 0x4000, "{backend}: v_add_f16 mul:4"); + }, + ); + run_cases( + &div2, + &[[0x3E00, 0x3E00, 0, 0]], // (1.5 + 1.5) / 2 = 1.5 (0x3E00) + |backend, _, _, got| { + assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 div:2"); + }, + ); + // Ordering check: (0.75 + 0.75) = 1.5; div:2 before clamp gives 0.75 (0x3A00), + // whereas clamp before div:2 would give 0.5 (0x3800). + let clamp_cases: &[(u16, u16, u16)] = &[ + (0x3A00, 0x3A00, 0x3A00), // (0.75 + 0.75) / 2 = 0.75 -> 0.75 + (0x3E00, 0x3E00, 0x3C00), // (1.5 + 1.5) / 2 = 1.5 -> clamped to 1.0 + (0xB800, 0xB800, 0x0000), // (-0.5 + -0.5) / 2 = -0.5 -> clamped to 0.0 ]; - let hi_in: Vec<[u32; 4]> = hi_cases.iter().map(|c| c.0).collect(); - run_cases(&cmp_hi_neg, &hi_in, |backend, i, inp, got| { - let want = hi_cases[i].1; + let inputs: Vec<[u32; 4]> = clamp_cases + .iter() + .map(|&(a, b, _)| [u32::from(a), u32::from(b), 0, 0]) + .collect(); + run_cases(&div2_clamp, &inputs, |backend, i, _, got| { + let want = clamp_cases[i].2; assert_eq!( - got, want, - "{backend}: v_cmp_class_f16(-hi({:#010x}), {:#05x}) = {got}, want {want}", - inp[0], inp[1], + got as u16, want, + "{backend}: v_add_f16 div:2 clamp case {i}: got {:#06x}, want {want:#06x}", + got as u16, ); }); } -/// VOP3B `op vdst, sdst, src0, src1, src2` (no modifiers). -const fn vop3b(op: u16, vdst: u8, sdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { - let [w0, w1] = vop3(op, vdst, src0, src1, src2); - [w0 | (sdst as u32 & 0x7F) << 8, w1] -} - -/// 32 × 32-bit inputs where the product or the 64-bit addend reach their -/// extremes, so both the multiply and the add wrap. -const MAD64_CASES: &[[u32; 4]] = &[ - [0, 0, 0, 0], - [1, 1, 0, 0], - [0xffff_ffff, 0xffff_ffff, 0, 0], - [0xffff_ffff, 0xffff_ffff, 0xffff_ffff, 0xffff_ffff], - [0xffff_ffff, 0xffff_ffff, 0x0000_0002, 0], - [0x8000_0000, 0x8000_0000, 0, 0x8000_0000], - [0x8000_0000, 0x7fff_ffff, 0x1234_5678, 0x9abc_def0], - [0x7fff_ffff, 0x7fff_ffff, 0xffff_ffff, 0x7fff_ffff], - [0xffff_fffe, 3, 1, 0], - [0x0001_0000, 0x0001_0000, 0xffff_ffff, 0xffff_ffff], - [0xdead_beef, 0x1337_c0de, 0x0bad_f00d, 0xfeed_face], -]; - -/// The 64-bit result and the carry out of the addition (unsigned form). -fn mad64(inp: [u32; 4], signed: bool) -> (u64, bool) { - let addend = u64::from(inp[2]) | u64::from(inp[3]) << 32; - let product = if signed { - (i64::from(inp[0] as i32) * i64::from(inp[1] as i32)) as u64 - } else { - u64::from(inp[0]) * u64::from(inp[1]) - }; - product.overflowing_add(addend) -} - #[test] -fn v_mad_u64_u32_and_v_mad_i64_i32_match_rdna2() { - // v_mad_{u64_u32,i64_i32} v[5:6], vcc_lo, v1, v2, v[3:4] (VOP3B 0x176, - // 0x177), then v_mov_b32 v0, v5 (low dword) or v6 (high dword). - for (op, signed, form) in [ - (0x176, false, "v_mad_u64_u32"), - (0x177, true, "v_mad_i64_i32"), - ] { - let mad = vop3b(op, 5, 106, vgpr(1), vgpr(2), vgpr(3)); - for (half, reg) in [("low", 5), ("high", 6)] { - let shader = build_valu_cs(&[mad[0], mad[1], vop1(0x001, 0, vgpr(reg))]); - run_cases(&shader, MAD64_CASES, |backend, _, inp, got| { - let r = mad64(inp, signed).0; - let want = if reg == 5 { r as u32 } else { (r >> 32) as u32 }; - assert_eq!( - got, want, - "{backend}: {form}({:#x}, {:#x}, {:#x}{:08x}) {half} = {got:#010x}, \ - want {want:#010x}", - inp[0], inp[1], inp[3], inp[2], - ); - }); - } - } - // The unsigned form's carry out: v_cndmask_b32 v0, 0, 1, vcc_lo. - let mad = vop3b(0x176, 5, 106, vgpr(1), vgpr(2), vgpr(3)); - let pick = vop3(0x101, 0, 128, 129, 106); - let shader = build_valu_cs(&[mad[0], mad[1], pick[0], pick[1]]); - run_cases(&shader, MAD64_CASES, |backend, _, inp, got| { - let want = u32::from(mad64(inp, false).1); - assert_eq!( - got, want, - "{backend}: v_mad_u64_u32({:#x}, {:#x}, {:#x}{:08x}) carry = {got}, want {want}", - inp[0], inp[1], inp[3], inp[2], - ); - }); -} - -/// f32 bits of values whose significand and exponent RDNA2 returns exactly: -/// zeros, infinities, NaNs, normals at both ends of the range and -/// denormals (normalized: v_frexp works on the bits). -const FREXP_CASES: &[u32] = &[ - 0x0000_0000, // +0 - 0x8000_0000, // -0 - 0x7f80_0000, // +inf - 0xff80_0000, // -inf - 0x7fc0_0000, // NaN - 0xffc0_0001, // NaN with a payload - 0x3f80_0000, // 1.0 - 0xbf80_0000, // -1.0 - 0x3eff_ffff, // just below 0.5 - 0x4049_0fdb, // pi - 0x0080_0000, // smallest normal - 0x7f7f_ffff, // largest finite - 0xff7f_ffff, - 0x0000_0001, // smallest denormal - 0x8000_0001, - 0x007f_ffff, // largest denormal - 0x0040_0000, - 0x0000_ffff, -]; - -/// (significand bits, exponent) as RDNA2's v_frexp_mant_f32 and -/// v_frexp_exp_i32_f32 give them. -fn frexp_ref(x: u32) -> (u32, i32) { - let field = (x >> 23 & 0xFF) as i32; - let frac = x & 0x7F_FFFF; - if x & 0x7FFF_FFFF == 0 || field == 0xFF { - return (x, 0); - } - let (frac, e) = if field == 0 { - let lz = frac.leading_zeros(); - ((frac << (lz - 8)) & 0x7F_FFFF, -117 - lz as i32) - } else { - (frac, field - 126) - }; - (x & 0x8000_0000 | 0x3F00_0000 | frac, e) -} +fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() { + // VOP3 v_cvt_u16_f16 = 0x1D2 (0x180 + VOP1 0x52) + // VOP3 v_cvt_i16_f16 = 0x1D3 (0x180 + VOP1 0x53) + let cvt_u16 = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + let cvt_u16_abs = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 1, 0, 0, false)); + let cvt_i16 = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + let cvt_i16_neg = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 1, 0, false)); -#[test] -fn v_frexp_mant_and_exp_f32_match_rdna2() { - let cases: Vec<[u32; 4]> = FREXP_CASES.iter().map(|&x| [x, 0, 0, 0]).collect(); - // Every case: the significand times 2^exponent gives the input back. - for &x in FREXP_CASES { - let (m, e) = frexp_ref(x); - let back = f64::from(f32::from_bits(m)) * 2f64.powi(e); - let want = f64::from(f32::from_bits(x)); - assert!(back == want || want.is_nan(), "{x:#010x}"); - } - // v_frexp_mant_f32 v0, v1 (VOP1 0x40) - let mant = build_valu_cs(&[vop1(0x040, 0, vgpr(1))]); - run_cases(&mant, &cases, |backend, _, inp, got| { - let want = frexp_ref(inp[0]).0; - assert_eq!( - got, want, - "{backend}: v_frexp_mant_f32({:#010x}) = {got:#010x}, want {want:#010x}", - inp[0], - ); - }); - // v_frexp_exp_i32_f32 v0, v1 (VOP1 0x3f) - let exp = build_valu_cs(&[vop1(0x03f, 0, vgpr(1))]); - run_cases(&exp, &cases, |backend, _, inp, got| { - let want = frexp_ref(inp[0]).1; + let u16_cases: &[(u16, u16)] = &[ + (0xBC00, 0), // -1.0 -> 0 + (0xFC00, 0), // -inf -> 0 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x7BFF, 65504), // 65504.0 (max finite f16) -> 65504 + (0x7C00, 0xFFFF), // +inf -> 65535 (saturated) + ]; + let u16_in: Vec<[u32; 4]> = u16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + run_cases(&cvt_u16, &u16_in, |backend, i, inp, got| { + let want = u16_cases[i].1; assert_eq!( - got as i32, want, - "{backend}: v_frexp_exp_i32_f32({:#010x}) = {}, want {want}", - inp[0], got as i32, + got as u16, want, + "{backend}: v_cvt_u16_f16({:#06x}) = {:#06x}, want {want:#06x}", + inp[0], got as u16, ); }); -} + run_cases( + &cvt_u16_abs, + &[[0xD7BC, 0, 0, 0]], // |-123.75| -> 123 + |backend, _, _, got| { + assert_eq!(got as u16, 123, "{backend}: v_cvt_u16_f16 |src0|"); + }, + ); -#[test] -fn v_ldexp_f32_scales_by_any_exponent() { - // v_ldexp_f32 v0, v1, v2 (VOP3 0x362). Results stay normal (or zero, - // or infinity) so the host's denormal mode cannot change them. - let shader = build_valu_cs(&vop3(0x362, 0, vgpr(1), vgpr(2), 0)); - let inf = f32::INFINITY.to_bits(); - let cases: &[(u32, i32, u32)] = &[ - (1.0f32.to_bits(), 0, 1.0f32.to_bits()), - (1.0f32.to_bits(), 127, 0x7f00_0000), - (1.0f32.to_bits(), 128, inf), - (1.0f32.to_bits(), -126, 0x0080_0000), - (1.5f32.to_bits(), -1, 0.75f32.to_bits()), - ((-3.0f32).to_bits(), 4, (-48.0f32).to_bits()), - // Exponents past what one power-of-two factor holds. - (0x0080_0000, 253, 0x7f00_0000), - (0x7f00_0000, -253, 0x0080_0000), - (0x0080_0000, 254, inf), - (0x7f7f_ffff, -253, 0x00ff_ffff), - // Overflow and underflow from any finite nonzero input. - (0x0080_0000, i32::MAX, inf), - ((-1.0e-30f32).to_bits(), 1000, 0xff80_0000), - (0x7f7f_ffff, i32::MIN, 0), - ((-0.5f32).to_bits(), -400, 0x8000_0000), - // Zeros, infinities and NaN keep their value. - (0x8000_0000, 1000, 0x8000_0000), - (inf, -1000, inf), - (0xff80_0000, 0, 0xff80_0000), + let i16_cases: &[(u16, u16)] = &[ + (0xFC00, 0x8000), // -inf -> -32768 + (0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped) + (0xD7BC, (-123i16) as u16), // -123.75 -> -123 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped) + (0x7C00, 0x7FFF), // +inf -> 32767 ]; - let inputs: Vec<[u32; 4]> = cases.iter().map(|&(x, e, _)| [x, e as u32, 0, 0]).collect(); - run_cases(&shader, &inputs, |backend, i, inp, got| { - let want = cases[i].2; + let i16_in: Vec<[u32; 4]> = i16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + run_cases(&cvt_i16, &i16_in, |backend, i, inp, got| { + let want = i16_cases[i].1; assert_eq!( - got, want, - "{backend}: v_ldexp_f32({:#010x}, {}) = {got:#010x}, want {want:#010x}", - inp[0], inp[1] as i32, + got as u16, want, + "{backend}: v_cvt_i16_f16({:#06x}) = {:#06x}, want {want:#06x}", + inp[0], got as u16, ); }); - run_cases(&shader, &[[0x7fc0_0000, 10, 0, 0]], |backend, _, _, got| { - assert!(f32::from_bits(got).is_nan(), "{backend}: {got:#010x}"); - }); + run_cases( + &cvt_i16_neg, + &[[0x57BC, 0, 0, 0], [0x78E2, 0, 0, 0]], // -(123.75) -> -123; -(40000.0) -> -32768 + |backend, i, _, got| { + let want = [(-123i16) as u16, 0x8000][i]; + assert_eq!(got as u16, want, "{backend}: v_cvt_i16_f16 -src0 case {i}"); + }, + ); } -/// Translates a 64-thread wave64 program from `wave64_fixtures` for a host -/// without 64-lane waves (lane exchanges through group-shared memory) and -/// checks what its group stores on every available SM 6.6 host. The -/// translation declares no wave size, so it runs on any GPU: on NVIDIA's -/// 32-lane waves this is the only way these programs run at all. -fn run_wave64_group(body: &[u32], lds_bytes: u32, expected: &[u32]) { - use super::wave64_fixtures::{lower_for, program}; - let lowered = lower_for(&program(body, 64, lds_bytes), false).expect("lower"); - let shader = HostShader { - stage: HwStage::Cs, - dxil: lowered.dxil, - user_data: lowered.user_data, - samplers: lowered.samplers, - static_samplers: Vec::new(), - root_cbvs: lowered.root_cbvs, - root_srvs: lowered.root_srvs, - }; - if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - let mut copy = shader.dxil.clone(); - v.validate(&mut copy).expect("DXIL validation failed"); - } - let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); - let mut ran = 0; - for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; - }; - let (root, pso) = host - .compute_pipeline(&shader) - .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); - let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; - for u in &shader.user_data { - ud[u.index as usize] = match (u.root, u.slot) { - (RootType::Constants, 0) | (RootType::Table, 1) => 0, - other => panic!("unexpected user data {other:?}"), - }; - } - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(ud))], - views: &[View::RawUav(256)], - samplers: &[], - groups: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - for (n, (&got, &want)) in out[0].iter().zip(expected).enumerate() { - assert_eq!( - got, - want, - "{label}: dword {n} (lane {}, result {}) = {got:#x}, want {want:#x}", - n % 64, - n / 64, - ); - } - ran += 1; - } - assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); -} +const S_BARRIER: u32 = 0xBF8A_0000; -#[test] -fn wave64_lane_reads_ballots_and_lds_run_without_64_lane_waves() { - use super::wave64_fixtures::{CROSS_LANE, cross_lane_expected}; - run_wave64_group(CROSS_LANE, 512, &cross_lane_expected()); +/// VOP2 `op vdst, src0, vsrc1`. +const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) } -#[test] -fn wave64_dpp_first_lane_and_swizzle_run_without_64_lane_waves() { - use super::wave64_fixtures::{DPP_FIRST_SWIZZLE, dpp_first_swizzle_expected}; - run_wave64_group(DPP_FIRST_SWIZZLE, 0, &dpp_first_swizzle_expected()); +/// DS `op vdst, addr, data0` at offset 0. +const fn ds(op: u8, vdst: u8, addr: u8, data0: u8) -> [u32; 2] { + [ + 0x36 << 26 | (op as u32) << 18, + (vdst as u32) << 24 | (data0 as u32) << 8 | addr as u32, + ] } -#[test] -fn v_cmp_class_f32_matches_rdna2() { - let build = |abs0: bool, neg0: bool| { - let [mut w0, mut w1] = vop3(0x088, 6, vgpr(1), vgpr(2), 0); - if abs0 { - w0 |= 1 << 8; // abs[0] = 1 - } - if neg0 { - w1 |= 1 << 29; // neg[0] = 1 - } - let sel = vop3(0x101, 0, 0x80, 0x81, sgpr(6)); - build_valu_cs(&[w0, w1, sel[0], sel[1]]) +const DS_WRITE_B32: u8 = 0x0D; +const DS_MIN_F32: u8 = 0x12; +const DS_MAX_F32: u8 = 0x13; +const DS_MIN_RTN_F32: u8 = 0x32; +const DS_MAX_RTN_F32: u8 = 0x33; +const DS_READ_B32: u8 = 0x36; + +/// What RDNA2 writes for `ds_max_f32` / `ds_min_f32` over a dword holding +/// `old` with `data` (bits), as measured on gfx1036 with f32 denormals kept: +/// an sNaN, data first, then memory, is written quieted; otherwise a NaN +/// loses to a number (two quiet NaNs give the data); numbers compare as +/// floats with -0 below +0. +fn lds_min_max_ref(old: u32, data: u32, max: bool) -> u32 { + let nan = |x: u32| x & 0x7FFF_FFFF > 0x7F80_0000; + let snan = |x: u32| nan(x) && x & 0x40_0000 == 0; + let key = |x: u32| { + let b = x as i32; + if b < 0 { b ^ 0x7FFF_FFFF } else { b } }; - - // All 10 IEEE-754 binary32 classes: bit k corresponds to class k. - let classes: &[(u32, u32)] = &[ - (0x7F80_0001, 0), // +sNaN (quiet bit 0x40_0000 clear) - (0xFF80_0001, 0), // -sNaN - (0x7FC0_0000, 1), // +qNaN (quiet bit set) - (0xFFC0_0001, 1), // -qNaN - (0xFF80_0000, 2), // -inf - (0xBF80_0000, 3), // -normal (-1.0) - (0x8000_0001, 4), // -denormal - (0x8000_0000, 5), // -0.0 - (0x0000_0000, 6), // +0.0 - (0x0000_0001, 7), // +denormal - (0x3F80_0000, 8), // +normal (+1.0) - (0x7F80_0000, 9), // +inf - ]; - let mut plain_cases = Vec::new(); - for &(bits, cls) in classes { - plain_cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); - plain_cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); + if snan(data) { + return data | 0x40_0000; } - let cmp_plain = build(false, false); - let plain_in: Vec<[u32; 4]> = plain_cases.iter().map(|c| c.0).collect(); - run_cases(&cmp_plain, &plain_in, |backend, i, inp, got| { - let want = plain_cases[i].1; - assert_eq!( - got, want, - "{backend}: v_cmp_class_f32({:#010x}, {:#05x}) = {got}, want {want}", - inp[0], inp[1], - ); - }); - - // RDNA2 input modifiers on v_cmp_class_f32 manipulate the sign bit bitwise: - // they must not quiet sNaNs or flush denormals to zero. - struct ModCases { - label: &'static str, - abs: bool, - neg: bool, - items: &'static [(u32, u32)], + if snan(old) { + return old | 0x40_0000; } - let mod_sets = [ - ModCases { - label: "neg", - abs: false, - neg: true, - items: &[ - (0x3F80_0000, 3), // -(+1.0) -> -normal - (0x0000_0000, 5), // -(+0.0) -> -0.0 - (0x8000_0000, 6), // -(-0.0) -> +0.0 - (0x0000_0001, 4), // -(+denormal) -> -denormal (not flushed to -0.0) - (0x8000_0001, 7), // -(-denormal) -> +denormal (not flushed to +0.0) - (0x7F80_0001, 0), // -(+sNaN) -> sNaN (not quieted to qNaN) - (0xFF80_0001, 0), // -(-sNaN) -> sNaN (not quieted to qNaN) - ], - }, - ModCases { - label: "abs", - abs: true, - neg: false, - items: &[ - (0xBF80_0000, 8), // |-1.0| -> +normal - (0x8000_0000, 6), // |-0.0| -> +0.0 - (0xFF80_0000, 9), // |-inf| -> +inf - (0x8000_0001, 7), // |-denormal| -> +denormal - (0xFF80_0001, 0), // |-sNaN| -> sNaN - ], - }, - ModCases { - label: "abs+neg", - abs: true, - neg: true, - items: &[ - (0x3F80_0000, 3), // -|+1.0| -> -normal - (0xBF80_0000, 3), // -|-1.0| -> -normal - (0x0000_0001, 4), // -|+denormal| -> -denormal - (0x8000_0001, 4), // -|-denormal| -> -denormal - (0x7F80_0001, 0), // -|+sNaN| -> sNaN - ], - }, - ]; - for set in mod_sets { - let shader = build(set.abs, set.neg); - let mut cases = Vec::new(); - for &(bits, cls) in set.items { - cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); - cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); - } - let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); - run_cases(&shader, &inputs, |backend, i, inp, got| { - let want = cases[i].1; - assert_eq!( - got, want, - "{backend}: v_cmp_class_f32[{}]({:#010x}, {:#05x}) = {got}, want {want}", - set.label, inp[0], inp[1], - ); - }); + match (nan(data), nan(old)) { + (true, true) | (false, true) => return data, + (true, false) => return old, + (false, false) => {} } + let take = if max { + key(data) > key(old) + } else { + key(data) < key(old) + }; + if take { data } else { old } } #[test] -fn sdwa_16bit_dst_unused_sext_sign_extends_word0() { - // SDWA dst_sel: 4 = WORD_0, 5 = WORD_1. - // SDWA dst_unused: 0 = UNUSED_PAD, 1 = UNUSED_SEXT, 2 = UNUSED_PRESERVE. - // Pre-seed v0 from v4 (0xABCD_1234) so UNUSED_SEXT/UNUSED_PAD/UNUSED_PRESERVE - // are distinguishable from each other. - let seed = 0xABCD_1234u32; - - // v_cvt_i16_f16_sdwa v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0 - let mut body = vec![vop1(0x001, 0, vgpr(4))]; - body.extend_from_slice(&vop1_sdwa(0x053, 0, 1, 4, 1, 4)); - let cvt_sext = build_valu_cs(&body); - let cvt_cases: &[(u32, u32)] = &[ - (0xBC00, 0xFFFF_FFFF), // -1.0 -> -1i16 sign-extended to -1i32 - (0xF800, 0xFFFF_8000), // -32768.0 -> -32768i16 sign-extended - (0x3C00, 0x0000_0001), // +1.0 -> +1i16 zero-extended (old v0 upper bits cleared) - (0x7BFF, 0x0000_7FFF), // +65504.0 -> saturated +32767i16 - (0x0000, 0x0000_0000), // 0.0 -> 0 - ]; - let cvt_in: Vec<[u32; 4]> = cvt_cases.iter().map(|&(x, _)| [x, 0, 0, seed]).collect(); - run_cases(&cvt_sext, &cvt_in, |backend, i, inp, got| { - let want = cvt_cases[i].1; - assert_eq!( - got, want, - "{backend}: v_cvt_i16_f16_sdwa({:#06x}, WORD_0, UNUSED_SEXT) = {got:#010x}, want {want:#010x}", - inp[0], - ); - }); - - // v_cvt_norm_i16_f16_sdwa v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_1 - let mut body = vec![vop1(0x001, 0, vgpr(4))]; - body.extend_from_slice(&vop1_sdwa(0x063, 0, 1, 4, 1, 5)); - let norm_sext = build_valu_cs(&body); - let norm_cases: &[(u32, u32)] = &[ - (0xBC00_3C00, 0xFFFF_8001), // high half -1.0 -> -32767i16 sign-extended - (0x3C00_BC00, 0x0000_7FFF), // high half +1.0 -> +32767i16 - ]; - let norm_in: Vec<[u32; 4]> = norm_cases.iter().map(|&(x, _)| [x, 0, 0, seed]).collect(); - run_cases(&norm_sext, &norm_in, |backend, i, inp, got| { - let want = norm_cases[i].1; - assert_eq!( - got, want, - "{backend}: v_cvt_norm_i16_f16_sdwa({:#010x}, WORD_0, UNUSED_SEXT) = {got:#010x}, want {want:#010x}", - inp[0], - ); - }); - - // v_add_f16_sdwa v0, v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0 src1_sel:WORD_0 - let mut body = vec![vop1(0x001, 0, vgpr(4))]; - body.extend_from_slice(&vop2_sdwa(0x32, 0, 1, 2, (4, 1), [4, 4])); - let add_sext = build_valu_cs(&body); - let add_cases: &[(u32, u32, u32)] = &[ - (0xBC00, 0xC000, 0xFFFF_C200), // -1.0 + -2.0 = -3.0 (0xC200, bit 15 set -> sign-extended) - (0x3C00, 0x4000, 0x0000_4200), // +1.0 + +2.0 = +3.0 (0x4200, bit 15 clear) +fn ds_min_max_f32_order_floats_and_return_the_old_value() { + let values = [ + 0.0f32, + -0.0, + 1.0, + -1.0, + 2.5, + -2.5, + 1e-30, + -1e-30, + f32::from_bits(1), // denormal + f32::from_bits(0x8000_0001), + f32::INFINITY, + f32::NEG_INFINITY, + f32::MAX, + f32::MIN, ]; - let add_in: Vec<[u32; 4]> = add_cases.iter().map(|&(a, b, _)| [a, b, 0, seed]).collect(); - run_cases(&add_sext, &add_in, |backend, i, inp, got| { - let want = add_cases[i].2; - assert_eq!( - got, want, - "{backend}: v_add_f16_sdwa({:#06x}, {:#06x}, WORD_0, UNUSED_SEXT) = {got:#010x}, want {want:#010x}", - inp[0], inp[1], - ); - }); - - // Regression check for the other dst_sel / dst_unused modes on v_cvt_i16_f16_sdwa(-1.0): - // WORD_0 + UNUSED_PAD -> 0x0000_FFFF, WORD_0 + UNUSED_PRESERVE -> 0xABCD_FFFF, - // WORD_1 + UNUSED_PAD / UNUSED_SEXT -> 0xFFFF_0000 (bits below WORD_1 pad with 0), - // WORD_1 + UNUSED_PRESERVE -> 0xFFFF_1234, DWORD -> 0x0000_FFFF. - let modes: &[(u8, u8, u32)] = &[ - (4, 0, 0x0000_FFFF), - (4, 2, 0xABCD_FFFF), - (5, 0, 0xFFFF_0000), - (5, 1, 0xFFFF_0000), - (5, 2, 0xFFFF_1234), - (6, 0, 0x0000_FFFF), + // Quiet and signalling NaNs of both signs, in memory and as data. + let nans = [ + 0x7FC0_0000u32, + 0xFFC0_0000, + 0x7F80_0001, + 0xFFA0_0000, + 0x7FBF_FFFF, ]; - for &(dst_sel, dst_unused, want) in modes { - let mut body = vec![vop1(0x001, 0, vgpr(4))]; - body.extend_from_slice(&vop1_sdwa(0x053, 0, 1, dst_sel, dst_unused, 4)); - let shader = build_valu_cs(&body); - run_cases(&shader, &[[0xBC00, 0, 0, seed]], |backend, _, _, got| { - assert_eq!( - got, want, - "{backend}: v_cvt_i16_f16_sdwa(-1.0, dst_sel={dst_sel}, dst_unused={dst_unused}) = {got:#010x}, want {want:#010x}", - ); - }); - } -} - -/// [`build_valu_cs`], with the lowering's refusal as an error. -fn try_build_valu_cs(body: &[u32]) -> Result<HostShader, String> { - let mut words = Vec::new(); - // s[4:5] = descriptor table address (heap index 0 -> byte offset 0). - words.push(s_mov_b32(5, 0x80)); // inline constant 0 - words.extend_from_slice(&s_load_dwordx4(8, 4)); - // Copy root constants s0..s3 into v1..v4 so VALU instructions operate on - // VGPRs just as they do in real shaders. - for i in 0..4u8 { - words.push(vop1(0x001, i + 1, sgpr(i))); // v_mov_b32 - } - words.extend_from_slice(body); - words.extend_from_slice(&buffer_store_dword(0, 8, 0)); - words.push(S_ENDPGM); - - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 8, - layout: vec![ - RootParam { - root: RootType::Constants, - table_offset_dwords: 0, - sgprs: 4, - base_register: 0, - user_data: 0, - slot: 0, - }, - RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 1, - }, - ], - used: vec![UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 4, - slot: 1, - }], - io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 - threads: [1, 1, 1], - }), - code, - }; - - let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - let st = structure::structure(&p).expect("structure"); - let res = - resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); - let io = io::raise(&p, &native).expect("io::raise"); - let lowered = lower::lower(&lower::Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, - host_wave64: true, - }) - .map_err(|e| format!("{e:?}"))?; - - let shader = HostShader { - stage: HwStage::Cs, - dxil: lowered.dxil, - user_data: lowered.user_data, - samplers: lowered.samplers, - static_samplers: Vec::new(), - root_cbvs: lowered.root_cbvs, - root_srvs: lowered.root_srvs, - }; - - if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - let mut copy = shader.dxil.clone(); - let ours = copy[4..20].to_vec(); - v.validate(&mut copy).expect("DXIL validation failed"); - assert_eq!(copy[4..20], ours[..], "container hash mismatch"); - } - - Ok(shader) -} - -/// MTBUF `op vdata, v5, s[8:11], 0 format:fmt offset:16` (no offen/idxen; -/// `op` 4..7 stores x..xyzw, 12..15 their d16 forms). -const fn mtbuf_store(op: u8, fmt: u8, vdata: u8) -> [u32; 2] { - [ - 0x3A << 26 | (fmt as u32) << 19 | (op as u32 & 7) << 16 | 16, - 0x80 << 24 | (op as u32 >> 3 & 1) << 21 | (8 >> 2) << 16 | (vdata as u32) << 8 | 5, - ] -} - -/// Runs `shader` once with root constants `inputs` on every available -/// SM 6.6 host and returns the first `dwords` of its raw UAV, per device. -fn run_dwords(shader: &HostShader, inputs: [u32; 4], dwords: u32) -> Vec<(&'static str, Vec<u32>)> { - let mut out = Vec::new(); - for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; - }; - let (root, pso) = host - .compute_pipeline(shader) - .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); - let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; - for u in &shader.user_data { - ud[u.index as usize] = match (u.root, u.slot) { - (RootType::Constants, 0) => inputs[u.dword as usize], - (RootType::Table, 1) => 0, - other => panic!("unexpected user data {other:?}"), - }; + let bits: Vec<u32> = values.iter().map(|v| v.to_bits()).chain(nans).collect(); + let mut cases: Vec<[u32; 4]> = Vec::new(); + for &old in &bits { + for &data in &bits { + cases.push([old, data, 0, 0]); } - let r = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(ud))], - views: &[View::RawUav(dwords)], - samplers: &[], - groups: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - out.push((label, r[0].clone())); } - assert!( - !out.is_empty(), - "neither hardware nor WARP SM 6.6 device available" - ); - out -} - -#[test] -fn tbuffer_store_format_writes_the_formats_layout() { - let f = |x: f32| x.to_bits(); - // (what, op, format, data in v1..v4, dwords 4..8 afterwards) - type Case = (&'static str, u8, u8, [u32; 4], [u32; 4]); - let cases: &[Case] = &[ - ( - "32_32_32_32 float xyzw", - 7, - 77, - [f(1.5), f(-0.0), 0x7FC0_1234, 0x0000_0001], - [f(1.5), f(-0.0), 0x7FC0_1234, 0x0000_0001], - ), - ( - "32_32_32_32 sint xyzw", - 7, - 76, - [u32::MAX, 0x8000_0000, 7, 0x1234_5678], - [u32::MAX, 0x8000_0000, 7, 0x1234_5678], - ), - ( - "32_32_32 float xyz", - 6, - 74, - [f(2.0), f(3.0), f(4.0), 0xDEAD_BEEF], - [f(2.0), f(3.0), f(4.0), 0], - ), - ( - "32_32 uint xy", - 5, - 63, - [0xAABB_CCDD, 9, 0xDEAD_BEEF, 0xDEAD_BEEF], - [0xAABB_CCDD, 9, 0, 0], - ), - ( - "32 float x", - 4, - 22, - [f(-7.25), 1, 2, 3], - [f(-7.25), 0, 0, 0], - ), - ( - // d16: the halves are stored as they are. - "16_16 float d16_xy", - 13, - 29, - [0xBC00_3555, 0xDEAD_BEEF, 0, 0], - [0xBC00_3555, 0, 0, 0], - ), - ( - "16_16_16_16 float d16_xyzw", - 15, - 71, - [0x1234_5678, 0x7C00_FC00, 0, 0], - [0x1234_5678, 0x7C00_FC00, 0, 0], - ), - ]; - for &(what, op, fmt, inputs, want) in cases { - let mut body = vec![vop1(0x001, 5, 0x80)]; // v_mov_b32 v5, 0 - body.extend(mtbuf_store(op, fmt, 1)); - let shader = build_valu_cs(&body); - for (backend, out) in run_dwords(&shader, inputs, 8) { - assert_eq!( - out[4..8], - want, - "{backend}: tbuffer_store {what}: wrote {:#010x?}, want {want:#010x?}", - &out[4..8], + for (rtn, plain, max, what) in [ + (DS_MAX_RTN_F32, DS_MAX_F32, true, "ds_max"), + (DS_MIN_RTN_F32, DS_MIN_F32, false, "ds_min"), + ] { + // v5 = 0; LDS[v5] = v1; the atomic with v2; v0 = the old value + // (rtn) or the dword afterwards (read back). + let mut returns_old = vec![vop1(0x001, 5, 0x80)]; + returns_old.extend(ds(DS_WRITE_B32, 0, 5, 1)); + returns_old.extend(ds(rtn, 0, 5, 2)); + let mut returns_new = vec![vop1(0x001, 5, 0x80)]; + returns_new.extend(ds(DS_WRITE_B32, 0, 5, 1)); + returns_new.extend(ds(plain, 0, 5, 2)); + returns_new.extend(ds(DS_READ_B32, 0, 5, 0)); + for (body, old_result) in [(returns_old, true), (returns_new, false)] { + // One thread with LDS declares WaveSize(32), which WARP's + // pipeline creation refuses: hardware only (the 64-thread test + // below runs on WARP too). + let shader = build_cs(&body, 1, 512); + run_cases_on( + &shader, + &cases, + &[("hardware", false)], + |backend, _, inp, got| { + let (old, data) = (f32::from_bits(inp[0]), f32::from_bits(inp[1])); + let want = if old_result { + inp[0] + } else { + lds_min_max_ref(inp[0], inp[1], max) + }; + assert_eq!( + got, + want, + "{backend}: {what}_f32 on {old:e} [{:#010x}] with {data:e} [{:#010x}] gave {got:#010x}, want {want:#010x} ({})", + inp[0], + inp[1], + if old_result { + "old value" + } else { + "dword after" + }, + ); + }, ); } } } #[test] -fn tbuffer_store_format_refuses_what_it_does_not_convert() { - for (what, op, fmt, reason) in [ - ("8_8_8_8 unorm", 7, 56, "a converted or narrow format"), - ("16_16 uint", 5, 27, "a converted or narrow format"), - ("16 float", 4, 13, "an element under a dword"), - ( - "32_32_32_32 float, xy only", - 5, - 77, - "some of its format's channels", - ), - ("32 float d16_x", 12, 22, "a converted or narrow format"), - // f32 to f16 waits for nearest-even narrowing (#422). - ("16_16 float xy", 5, 29, "a converted or narrow format"), - ( - "16_16_16_16 float xyzw", - 7, - 71, - "a converted or narrow format", - ), +fn ds_min_max_f32_are_atomic_across_waves() { + // 64 threads (two host waves of 32 or one of 64): LDS[0] = v1, then + // every thread applies (thread - 32) as a float; v0 = LDS[0]. + for (op, max, init, want) in [ + (DS_MAX_F32, true, f32::NEG_INFINITY, 31.0f32), + (DS_MAX_F32, true, 100.0, 100.0), + (DS_MIN_F32, false, f32::INFINITY, -32.0), + (DS_MIN_F32, false, -0.0, -32.0), ] { let mut body = vec![vop1(0x001, 5, 0x80)]; - body.extend(mtbuf_store(op, fmt, 1)); - match try_build_valu_cs(&body) { - Ok(_) => panic!("tbuffer_store {what} lowered; it should be refused"), - Err(e) => assert!(e.contains(reason), "tbuffer_store {what}: refused with {e}"), - } - } -} - -#[test] -fn v_mul_legacy_f32_treats_denormals_as_zero() { - // v_mul_legacy_f32 v0, v1, v2 (VOP2 opcode 0x007 in its VOP3 encoding) - let shader = build_valu_cs(&vop3(0x107, 0, vgpr(1), vgpr(2), vgpr(0))); - let f = f32::to_bits; - let (denorm, neg_denorm, min_normal) = (0x0000_0001u32, 0x8040_0000u32, 0x0080_0000u32); - - let cases: &[(u32, u32, u32)] = &[ - // Zero or denormal times anything, non-finite included, is +0. - (f(0.0), f(f32::INFINITY), f(0.0)), - (f(-0.0), f(f32::NAN), f(0.0)), - (f(f32::NAN), f(0.0), f(0.0)), - (denorm, f(f32::INFINITY), f(0.0)), - (f(f32::NAN), neg_denorm, f(0.0)), - (denorm, f(2.0f32.powi(100)), f(0.0)), - // The smallest normal is not zero. - (min_normal, f(2.0), f(f32::MIN_POSITIVE * 2.0)), - // Ordinary products. - (f(1.5), f(-4.0), f(-6.0)), - (f(3.0), f(0.5), f(1.5)), - ]; - - let inputs: Vec<[u32; 4]> = cases.iter().map(|&(a, b, _)| [a, b, 0, 0]).collect(); - run_cases(&shader, &inputs, |backend, i, inp, got| { - let want = cases[i].2; - assert_eq!( - got, want, - "{backend}: v_mul_legacy_f32({:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", - inp[0], inp[1], + body.extend(ds(DS_WRITE_B32, 0, 5, 1)); + body.push(S_BARRIER); + body.push(vop2(0x26, 6, vgpr(0), 3)); // v_sub_nc_u32 v6, v0, v3 + body.push(vop1(0x005, 6, vgpr(6))); // v_cvt_f32_i32 + body.extend(ds(op, 0, 5, 6)); + body.push(S_BARRIER); + body.extend(ds(DS_READ_B32, 0, 5, 0)); + let shader = build_cs(&body, 64, 512); + run_cases( + &shader, + &[[init.to_bits(), 0, 32, 0]], + |backend, _, _, got| { + assert_eq!( + f32::from_bits(got), + want, + "{backend}: {} from {init} over 64 threads", + if max { "max" } else { "min" }, + ); + }, ); - }); -} - -/// VOP3 `op vdst, src0, src1, src2` with explicit `abs`, `neg`, `omod`, `clamp`. -#[allow(clippy::too_many_arguments)] -const fn vop3_mod( - op: u16, - vdst: u8, - src0: u16, - src1: u16, - src2: u16, - abs: u8, - neg: u8, - omod: u8, - clamp: bool, -) -> [u32; 2] { - [ - 0x35 << 26 - | (op as u32 & 0x3FF) << 16 - | (clamp as u32) << 15 - | (abs as u32 & 7) << 8 - | vdst as u32, - (neg as u32 & 7) << 29 - | (omod as u32 & 3) << 27 - | (src0 as u32 & 0x1FF) - | (src1 as u32 & 0x1FF) << 9 - | (src2 as u32 & 0x1FF) << 18, - ] + } } #[test] -fn f16_omod_applies_before_clamp() { - // VOP3 v_add_f16 (0x132 = 0x100 + VOP2 0x32): v0 = (v1 + v2) * omod [clamp] - let mul2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 1, false)); - let mul4 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 2, false)); - let div2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, false)); - let div2_clamp = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, true)); +fn v_cmp_class_f16_matches_rdna2() { + // v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6 + let cmp_lo = build_valu_cs(&[ + vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[0], + vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[1], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + // Same with op_sel:[1,0] (high half of v1) + neg on src0 (bit 29 of w1). + let [mut w0, mut w1] = vop3(0x08f, 6, vgpr(1), vgpr(2), 0); + w0 |= 1 << 11; // opsel[0] = 1 (high half) + w1 |= 1 << 29; // neg[0] = 1 + let cmp_hi_neg = build_valu_cs(&[ + w0, + w1, + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); - // f16 constants: 0.25=0x3400, 0.5=0x3800, 0.75=0x3A00, 1.0=0x3C00, 1.5=0x3E00, 2.0=0x4000, -0.5=0xB800 - run_cases( - &mul2, - &[[0x3400, 0x3800, 0, 0]], // (0.25 + 0.5) * 2 = 1.5 (0x3E00) - |backend, _, _, got| { - assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 mul:2"); - }, - ); - run_cases( - &mul4, - &[[0x3400, 0x3400, 0, 0]], // (0.25 + 0.25) * 4 = 2.0 (0x4000) - |backend, _, _, got| { - assert_eq!(got as u16, 0x4000, "{backend}: v_add_f16 mul:4"); - }, - ); - run_cases( - &div2, - &[[0x3E00, 0x3E00, 0, 0]], // (1.5 + 1.5) / 2 = 1.5 (0x3E00) - |backend, _, _, got| { - assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 div:2"); - }, - ); - // Ordering check: (0.75 + 0.75) = 1.5; div:2 before clamp gives 0.75 (0x3A00), - // whereas clamp before div:2 would give 0.5 (0x3800). - let clamp_cases: &[(u16, u16, u16)] = &[ - (0x3A00, 0x3A00, 0x3A00), // (0.75 + 0.75) / 2 = 0.75 -> 0.75 - (0x3E00, 0x3E00, 0x3C00), // (1.5 + 1.5) / 2 = 1.5 -> clamped to 1.0 - (0xB800, 0xB800, 0x0000), // (-0.5 + -0.5) / 2 = -0.5 -> clamped to 0.0 + // All 10 IEEE-754 binary16 classes: bit k corresponds to class k. + let classes: &[(u32, u32)] = &[ + (0x7C01, 0), // sNaN (+sNaN, quiet bit 0x0200 clear) + (0xFDFF, 0), // -sNaN (sign ignored for NaNs) + (0x7E00, 1), // +qNaN + (0xFE01, 1), // -qNaN + (0xFC00, 2), // -inf + (0xBC00, 3), // -normal (-1.0) + (0x8001, 4), // -denormal + (0x8000, 5), // -0.0 + (0x0000, 6), // +0.0 + (0x0001, 7), // +denormal + (0x3C00, 8), // +normal (+1.0) + (0x7C00, 9), // +inf ]; - let inputs: Vec<[u32; 4]> = clamp_cases - .iter() - .map(|&(a, b, _)| [u32::from(a), u32::from(b), 0, 0]) - .collect(); - run_cases(&div2_clamp, &inputs, |backend, i, _, got| { - let want = clamp_cases[i].2; + let mut cases = Vec::new(); + for &(bits, cls) in classes { + // Exact class bit -> true; complement of class bit across all 10 bits -> false. + cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); + cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); + } + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&cmp_lo, &inputs, |backend, i, inp, got| { + let want = cases[i].1; assert_eq!( - got as u16, want, - "{backend}: v_add_f16 div:2 clamp case {i}: got {:#06x}, want {want:#06x}", - got as u16, + got, want, + "{backend}: v_cmp_class_f16({:#06x}, {:#05x}) = {got}, want {want}", + inp[0], inp[1], ); }); -} - -#[test] -fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() { - // VOP3 v_cvt_u16_f16 = 0x1D2 (0x180 + VOP1 0x52) - // VOP3 v_cvt_i16_f16 = 0x1D3 (0x180 + VOP1 0x53) - let cvt_u16 = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 0, 0, 0, false)); - let cvt_u16_abs = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 1, 0, 0, false)); - let cvt_i16 = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 0, 0, false)); - let cvt_i16_neg = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 1, 0, false)); - let u16_cases: &[(u16, u16)] = &[ - (0xBC00, 0), // -1.0 -> 0 - (0xFC00, 0), // -inf -> 0 - (0x7E00, 0), // NaN -> 0 - (0x57BC, 123), // 123.75 -> 123 - (0x7BFF, 65504), // 65504.0 (max finite f16) -> 65504 - (0x7C00, 0xFFFF), // +inf -> 65535 (saturated) + // High half with neg: high half 0x3C00 (+1.0) negated -> -normal (class 3); + // high half 0x7C01 (+sNaN) negated -> still sNaN (class 0, not quieted). + let hi_cases: &[([u32; 4], u32)] = &[ + ([0x3C00_0000, 1 << 3, 0, 0], 1), + ([0x3C00_0000, 1 << 8, 0, 0], 0), + ([0x7C01_FFFF, 1 << 0, 0, 0], 1), + ([0x7C01_FFFF, 1 << 1, 0, 0], 0), ]; - let u16_in: Vec<[u32; 4]> = u16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); - run_cases(&cvt_u16, &u16_in, |backend, i, inp, got| { - let want = u16_cases[i].1; + let hi_in: Vec<[u32; 4]> = hi_cases.iter().map(|c| c.0).collect(); + run_cases(&cmp_hi_neg, &hi_in, |backend, i, inp, got| { + let want = hi_cases[i].1; assert_eq!( - got as u16, want, - "{backend}: v_cvt_u16_f16({:#06x}) = {:#06x}, want {want:#06x}", - inp[0], got as u16, + got, want, + "{backend}: v_cmp_class_f16(-hi({:#010x}), {:#05x}) = {got}, want {want}", + inp[0], inp[1], ); }); - run_cases( - &cvt_u16_abs, - &[[0xD7BC, 0, 0, 0]], // |-123.75| -> 123 - |backend, _, _, got| { - assert_eq!(got as u16, 123, "{backend}: v_cvt_u16_f16 |src0|"); - }, - ); +} - let i16_cases: &[(u16, u16)] = &[ - (0xFC00, 0x8000), // -inf -> -32768 - (0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped) - (0xD7BC, (-123i16) as u16), // -123.75 -> -123 - (0x7E00, 0), // NaN -> 0 - (0x57BC, 123), // 123.75 -> 123 - (0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped) - (0x7C00, 0x7FFF), // +inf -> 32767 +#[test] +fn v_cvt_f32_f64_matches_ieee754() { + // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x00f -> VOP3 opcode 0x18f). + let plain = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]); + // Same with abs + neg on src0 (VOP3: abs[0] = bit 8 of w0, neg[0] = bit 29 of w1). + let [mut w0, mut w1] = vop3(0x18f, 0, vgpr(1), 0, 0); + w0 |= 1 << 8; + w1 |= 1 << 29; + let neg_abs = build_valu_cs(&[w0, w1]); + + let values: &[f64] = &[ + 0.0, + -0.0, + 1.0, + -1.0, + 3.5, + -123456.75, + // Tie-to-even: even mantissa stays, odd mantissa rounds up. + f64::from_bits(0x3FF0_0000_1000_0000), // 1.0 + 0.5 ulp(f32) -> 1.0 + f64::from_bits(0x3FF0_0000_3000_0000), // (1.0 + 1 ulp) + 0.5 ulp -> 1.0 + 2 ulp + f64::from_bits(0x3FF0_0000_1000_0001), // > 0.5 ulp -> rounds up + // Largest finite f32 and overflow to +Inf / -Inf. + f64::from(f32::MAX), + f64::from(f32::MAX) * 1.000_001, + -f64::from(f32::MAX) * 1.000_001, + 1e300, + // Subnormal range (exp64 in [874, 896]), including carry into smallest normal. + f64::from(f32::MIN_POSITIVE), + f64::from(f32::MIN_POSITIVE) * 0.5, + f64::from(f32::MIN_POSITIVE) * 0.75, + f64::from(f32::from_bits(0x007F_FFFF)), + f64::from_bits(0x380F_FFFF_F000_0000), // max subnormal + 0.5 ulp -> min normal + // exp64 == 873: exact 2^-150 ties to 0; strictly greater rounds to min subnormal (1). + f64::from_bits(0x3690_0000_0000_0000), + f64::from_bits(0x3690_0000_0000_0001), + f64::from_bits(0xB690_0000_0000_0001), + // Deep underflow -> +/-0.0. + 1e-200, + -1e-200, + // Infinities and NaNs. + f64::INFINITY, + f64::NEG_INFINITY, + f64::from_bits(0x7FF8_0000_0000_0000), // +qNaN + f64::from_bits(0x7FF0_0000_0000_0001), // +sNaN -> quieted ]; - let i16_in: Vec<[u32; 4]> = i16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); - run_cases(&cvt_i16, &i16_in, |backend, i, inp, got| { - let want = i16_cases[i].1; + let inputs: Vec<[u32; 4]> = values + .iter() + .map(|&x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&plain, &inputs, |backend, i, _, got| { + let x = values[i]; + let want = (x as f32).to_bits(); + if x.is_nan() { + assert!( + f32::from_bits(got).is_nan() && (got & 0x0040_0000) != 0, + "{backend}: v_cvt_f32_f64({:#018x}) = {got:#010x}, expected qNaN", + x.to_bits(), + ); + } else { + assert_eq!( + got, want, + "{backend}: v_cvt_f32_f64({x} / {:#018x}) = {got:#010x}, want {want:#010x}", + x.to_bits(), + ); + } + }); + + // -|x| via VOP3 abs + neg modifiers. + let mod_values: &[f64] = &[2.5, -2.5, 0.0, f64::INFINITY]; + let mod_in: Vec<[u32; 4]> = mod_values + .iter() + .map(|&x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&neg_abs, &mod_in, |backend, i, _, got| { + let x = mod_values[i]; + let want = (-(x.abs()) as f32).to_bits(); assert_eq!( - got as u16, want, - "{backend}: v_cvt_i16_f16({:#06x}) = {:#06x}, want {want:#06x}", - inp[0], got as u16, + got, want, + "{backend}: v_cvt_f32_f64(-|{x}|) = {got:#010x}, want {want:#010x}", ); }); - run_cases( - &cvt_i16_neg, - &[[0x57BC, 0, 0, 0], [0x78E2, 0, 0, 0]], // -(123.75) -> -123; -(40000.0) -> -32768 - |backend, i, _, got| { - let want = [(-123i16) as u16, 0x8000][i]; - assert_eq!(got as u16, want, "{backend}: v_cvt_i16_f16 -src0 case {i}"); - }, - ); -} - -/// MUBUF `buffer_load_dword vdata, vaddr, s[srsrc:srsrc+3], 0 offen`. -const fn buffer_load_dword_offen(vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { - [ - 0x38 << 26 | 0x0C << 18 | 1 << 12, - 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, - ] } -/// A root SRV has no bounds on the host: a read past what the host bound -/// reads 0, as a console buffer view past its records does, instead of -/// memory after it (or an unmapped page, which some GPUs stall on). #[test] -fn root_view_reads_stop_at_the_bound_size() { - // s0..s3 root constants, s4 the UAV table, s[8:9] the root SRV's address. - let mut words = vec![s_mov_b32(5, 0x80)]; - words.extend_from_slice(&s_load_dwordx4(12, 4)); - // The buffer descriptor built around the root address: all records. - words.push(s_mov_b32(10, 0xC1)); - words.push(s_mov_b32(11, 0x80)); - words.push(vop1(0x001, 1, sgpr(0))); // v_mov_b32 v1, s0: the byte offset - words.extend_from_slice(&buffer_load_dword_offen(0, 1, 8)); - words.extend_from_slice(&buffer_store_dword(0, 12, 0)); +fn whole_wave_f64_sum_and_cvt_f32_f64() { + let s_or_saveexec_b32 = + |sdst: u8, src0: u8| 0xBE80_0000 | (sdst as u32) << 16 | 0x3D << 8 | src0 as u32; + let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)]; + let v_mov_row_mirror = |vdst: u8, vsrc: u8| { + [ + vop1(0x001, vdst, 0xFA), + vsrc as u32 | (0x140 << 8) | (1 << 19) | (0xF << 24) | (0xF << 28), + ] + }; + + let mut words = Vec::new(); + words.push(s_mov_b32(5, 0x80)); + words.extend_from_slice(&s_load_dwordx4(8, 4)); + // Per-lane f64 input in v[6:7] = (s0, s1). + words.push(vop1(0x001, 6, sgpr(0))); + words.push(vop1(0x001, 7, sgpr(1))); + // Whole-wave f64 sum over Wave32 with s_mov_b32 copy before EXEC restore. + words.push(s_or_saveexec_b32(12, 0xC1)); + words.extend_from_slice(&vop3(0x101, 2, 0x80, vgpr(6), sgpr(12))); + words.extend_from_slice(&vop3(0x101, 3, 0x80, vgpr(7), sgpr(12))); + for sel in [14570689u32, 9658386, 2340] { + words.extend_from_slice(&v_mov_dpp8(4, 2, sel)); + words.extend_from_slice(&v_mov_dpp8(5, 3, sel)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); // v_add_f64 + } + words.extend_from_slice(&v_mov_row_mirror(4, 2)); + words.extend_from_slice(&v_mov_row_mirror(5, 3)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + words.extend_from_slice(&vop3(0x378, 4, vgpr(2), 0x80, 0x80)); // v_permlanex16_b32 + words.extend_from_slice(&vop3(0x378, 5, vgpr(3), 0x80, 0x80)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + words.extend_from_slice(&vop3(0x360, 14, vgpr(2), 0x80, 0)); // v_readlane_b32 s14, v2, 0 + words.extend_from_slice(&vop3(0x360, 15, vgpr(3), 0x80, 0)); // v_readlane_b32 s15, v3, 0 + words.push(s_mov_b32(16, 14)); + words.push(s_mov_b32(17, 15)); + words.push(s_mov_b32(126, 12)); // restore exec_lo + words.push(vop1(0x00f, 0, sgpr(16))); // v_cvt_f32_f64 v0, s[16:17] + words.extend_from_slice(&buffer_store_dword(0, 8, 0)); words.push(S_ENDPGM); + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let root = |root, sgprs, user_data, slot| RootParam { - root, - table_offset_dwords: 0, - sgprs, - base_register: 0, - user_data, - slot, - }; - let used = |kind, root, user_data, slot| UsedResource { - kind, - root, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data, - slot, - }; let native = NativeProgram { stage: HwStage::Cs, wave64: false, - vgprs: 8, + vgprs: 12, layout: vec![ - root(RootType::Constants, 4, 0, 0), - root(RootType::Table, 1, 4, 1), - root(RootType::Descriptor, 2, 8, 2), - ], - used: vec![ - used(ResourceType::Uav, RootType::Table, 4, 1), - used(ResourceType::Srv, RootType::Descriptor, 8, 2), + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], io: StageIo::Cs(ComputeIo { - rsrc2: 10 << 1, // 10 user SGPRs: s0..s9 - threads: [1, 1, 1], + rsrc2: 5 << 1, + threads: [4, 1, 1], }), code, }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); let st = structure::structure(&p).expect("structure"); let res = @@ -2147,9 +1595,9 @@ fn root_view_reads_stop_at_the_bound_size() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - host_wave64: true, }) .expect("lower"); + let shader = HostShader { stage: HwStage::Cs, dxil: lowered.dxil, @@ -2158,42 +1606,39 @@ fn root_view_reads_stop_at_the_bound_size() { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), + half_views: lowered.half_views, }; - assert_eq!(shader.root_srvs, [2]); - assert!( - shader - .user_data - .iter() - .any(|u| u.root == RootType::Descriptor && u.slot == 2 && u.index == 8), - "the root view's size is user data: {:?}", - shader.user_data - ); if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - v.validate(&mut shader.dxil.clone()) - .expect("DXIL validation failed"); + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); } - // 64 dwords bound, of which the host says 16 (64 bytes) are the view's. - let data: Vec<u32> = (0..64).map(|i| 0x100 + i).collect(); - let mut ran = 0; + + let cases: &[(f64, f32)] = &[(1.25, 5.0), (-0.75, -3.0)]; + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); for (label, warp) in [("hardware", false), ("warp", true)] { let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); continue; }; - let (root, pso) = host.compute_pipeline(&shader).expect("pipeline"); - for (offset, want) in [ - (0, 0x100), - (60, 0x10F), - (64, 0), - (128, 0), - (u32::MAX - 3, 0), - ] { + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(p) => p, + // WARP does not support fixed WaveSize(32) on SM 6.6. + Err(e) if warp => { + eprintln!("{label}: compute_pipeline skipped ({e})"); + continue; + } + Err(e) => panic!("{label}: compute_pipeline failed: {e}"), + }; + for &(x, want) in cases { + let b = x.to_bits(); + let inputs = [b as u32, (b >> 32) as u32, 0, 0]; let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; for u in &shader.user_data { - ud[u.index as usize] = match u.root { - RootType::Constants => offset, - RootType::Descriptor => 64, - _ => 0, + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) => inputs[u.dword as usize], + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), }; } let out = host @@ -2201,27 +1646,134 @@ fn root_view_reads_stop_at_the_bound_size() { &root, &pso, &Dispatch { - roots: vec![ - (0, Root::Constants(ud)), - ( - 1, - Root::View { - srv: true, - data: data.clone(), - }, - ), - ], + roots: vec![(0, Root::Constants(ud))], views: &[View::RawUav(1)], samplers: &[], groups: [1, 1, 1], }, ) - .unwrap_or_else(|e| panic!("{label}: {e}")); - assert_eq!(out[0][0], want, "{label}: offset {offset:#x}"); + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!( + out[0][0], + want.to_bits(), + "{label}: wave f64 sum({x}) = {:#010x}, want {:#010x}", + out[0][0], + want.to_bits(), + ); + } + } +} + +#[test] +fn v_cmp_class_f32_matches_rdna2() { + let build = |abs0: bool, neg0: bool| { + let [mut w0, mut w1] = vop3(0x088, 6, vgpr(1), vgpr(2), 0); + if abs0 { + w0 |= 1 << 8; // abs[0] = 1 + } + if neg0 { + w1 |= 1 << 29; // neg[0] = 1 + } + let sel = vop3(0x101, 0, 0x80, 0x81, sgpr(6)); + build_valu_cs(&[w0, w1, sel[0], sel[1]]) + }; + + // All 10 IEEE-754 binary32 classes: bit k corresponds to class k. + let classes: &[(u32, u32)] = &[ + (0x7F80_0001, 0), // +sNaN (quiet bit 0x40_0000 clear) + (0xFF80_0001, 0), // -sNaN + (0x7FC0_0000, 1), // +qNaN (quiet bit set) + (0xFFC0_0001, 1), // -qNaN + (0xFF80_0000, 2), // -inf + (0xBF80_0000, 3), // -normal (-1.0) + (0x8000_0001, 4), // -denormal + (0x8000_0000, 5), // -0.0 + (0x0000_0000, 6), // +0.0 + (0x0000_0001, 7), // +denormal + (0x3F80_0000, 8), // +normal (+1.0) + (0x7F80_0000, 9), // +inf + ]; + let mut plain_cases = Vec::new(); + for &(bits, cls) in classes { + plain_cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); + plain_cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); + } + let cmp_plain = build(false, false); + let plain_in: Vec<[u32; 4]> = plain_cases.iter().map(|c| c.0).collect(); + run_cases(&cmp_plain, &plain_in, |backend, i, inp, got| { + let want = plain_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmp_class_f32({:#010x}, {:#05x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + + // RDNA2 input modifiers on v_cmp_class_f32 manipulate the sign bit bitwise: + // they must not quiet sNaNs or flush denormals to zero. + struct ModCases { + label: &'static str, + abs: bool, + neg: bool, + items: &'static [(u32, u32)], + } + let mod_sets = [ + ModCases { + label: "neg", + abs: false, + neg: true, + items: &[ + (0x3F80_0000, 3), // -(+1.0) -> -normal + (0x0000_0000, 5), // -(+0.0) -> -0.0 + (0x8000_0000, 6), // -(-0.0) -> +0.0 + (0x0000_0001, 4), // -(+denormal) -> -denormal (not flushed to -0.0) + (0x8000_0001, 7), // -(-denormal) -> +denormal (not flushed to +0.0) + (0x7F80_0001, 0), // -(+sNaN) -> sNaN (not quieted to qNaN) + (0xFF80_0001, 0), // -(-sNaN) -> sNaN (not quieted to qNaN) + ], + }, + ModCases { + label: "abs", + abs: true, + neg: false, + items: &[ + (0xBF80_0000, 8), // |-1.0| -> +normal + (0x8000_0000, 6), // |-0.0| -> +0.0 + (0xFF80_0000, 9), // |-inf| -> +inf + (0x8000_0001, 7), // |-denormal| -> +denormal + (0xFF80_0001, 0), // |-sNaN| -> sNaN + ], + }, + ModCases { + label: "abs+neg", + abs: true, + neg: true, + items: &[ + (0x3F80_0000, 3), // -|+1.0| -> -normal + (0xBF80_0000, 3), // -|-1.0| -> -normal + (0x0000_0001, 4), // -|+denormal| -> -denormal + (0x8000_0001, 4), // -|-denormal| -> -denormal + (0x7F80_0001, 0), // -|+sNaN| -> sNaN + ], + }, + ]; + for set in mod_sets { + let shader = build(set.abs, set.neg); + let mut cases = Vec::new(); + for &(bits, cls) in set.items { + cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); + cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); } - ran += 1; + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmp_class_f32[{}]({:#010x}, {:#05x}) = {got}, want {want}", + set.label, inp[0], inp[1], + ); + }); } - assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); } /// RDNA2 ignores VOP3 `op_sel` on 16-bit compares (reading the low halves @@ -2337,3 +1889,644 @@ fn cmp16_sdwa_preserves_word_selects() { } } } + +/// `v_mad_legacy_f32` as RDNA 2 runs it: fused (`v_fma_legacy_f32`), with +/// flushed subnormal sources and the legacy zero-factor rule. +#[test] +fn legacy_mad_fuses_its_product_and_flushes_its_sources() { + let mad = build_valu_cs(&vop3(0x140, 0, vgpr(1), vgpr(2), vgpr(3))); + let cases = [ + // (1 + 2^-23) * (1 - 2^-23) - 1 is -2^-46 exactly: kept by one + // rounding, lost when the product is rounded before the add. + [0x3f80_0001, 0x3f7f_fffe, 0xbf80_0000, 0], + // A subnormal source flushes to zero: subnormal * 1.0 + 0.0 == 0.0. + [0x0000_0001, 0x3f80_0000, 0x0000_0000, 0], + // A flushed subnormal factor triggers the legacy zero-factor rule with +inf. + [0x0000_0001, 0x7f80_0000, 0x3f80_0000, 0], + // A zero factor gives a +0 product even with an infinite factor. + [0, 0x7f80_0000, 0x3f80_0000, 0], + ]; + let want = [0xa880_0000u32, 0x0000_0000, 0x3f80_0000, 0x3f80_0000]; + if Host::new(false).is_err() && Host::new(true).is_err() { + eprintln!("no SM 6.6 host or WARP device; skipped"); + return; + } + run_cases(&mad, &cases, |backend, i, _, got| { + if backend == "warp" && i == 0 { + // WARP rounds the product before the add; hardware's single + // rounding is the reference for the fused form. + eprintln!("{backend}: fused rounding differs on WARP; skipped"); + return; + } + assert_eq!(got, want[i], "{backend}: case {i}"); + }); +} + +/// A dispatch spread across z past 65,535 groups in x +/// (`USER_DISPATCH_SPREAD`): the program sees the group id the title asked +/// for, `(x + z * row)`, and the groups past the asked count do nothing. +/// One thread a group stores 1 at dword `group id x` of a raw UAV. Run +/// unspread (10 groups), spread with surplus (10 asked as 4 x 1 x 3) and +/// spread exactly (10 asked as 5 x 1 x 2), on the hardware adapter and +/// WARP. (After upstream VIctory pull request #2312.) +#[test] +fn a_spread_dispatch_runs_each_asked_group_once() { + use crate::native::{ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource}; + let words: Vec<u32> = [ + vec![s_mov_b32(5, 0x80)], // s5 = 0: the table address's high half + s_load_dwordx4(8, 4).to_vec(), // s[8:11] = table entry 0 (raw UAV) + vec![ + vop1(0x001, 1, sgpr(6)), // v_mov_b32 v1, s6 (group id x) + 0x3404_0282, // v_lshlrev_b32 v2, 2, v1 + vop1(0x001, 3, 129), // v_mov_b32 v3, 1 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x38 << 26 | 0x1C << 18 | 1 << 12, // buffer_store_dword v3, v2, s[8:11], 0 offen + 0x80 << 24 | (8 >> 2) << 16 | 3 << 8 | 2, + S_ENDPGM, + ], + ] + .concat(); + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 0, + }], + // 6 user SGPRs (s0..s5), then the group id x in s6 (TGID_X_EN). + io: StageIo::Cs(ComputeIo { rsrc2: (6 << 1) | (1 << 7), threads: [1, 1, 1] }), + code, + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + half_views: lowered.half_views, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let spread = RootType::Other(super::USER_DISPATCH_SPREAD); + let row_at = shader.user_data.iter().find(|u| u.root == spread && u.dword == 0).expect("the row word").index; + let asked_at = shader.user_data.iter().find(|u| u.root == spread && u.dword == 1).expect("the asked word").index; + assert_eq!(asked_at, row_at + 1, "the two words are adjacent (one root-constant argument sets both)"); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut ran = Vec::new(); + for (backend, warp) in [("hardware", false), ("warp", true)] { + let host = match Host::new(warp) { + Ok(host) => host, + Err(e) => { + eprintln!("no SM 6.6 {backend} device ({e}); skipped"); + continue; + } + }; + ran.push(backend); + let (root, pso) = host.compute_pipeline(&shader).unwrap_or_else(|e| panic!("{backend}: {e}")); + // (row, asked, groups): unspread, spread with surplus, spread exactly. + for (row, asked, groups) in [(0u32, 10u32, [10u32, 1, 1]), (4, 10, [4, 1, 3]), (5, 10, [5, 1, 2])] { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + ud[row_at as usize] = row; + ud[asked_at as usize] = if row == 0 { 0 } else { asked }; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(16)], + samplers: &[], + groups, + }, + ) + .unwrap_or_else(|e| panic!("{backend} row {row}: {e}")); + let want: Vec<u32> = (0..16).map(|i| u32::from(i < asked)).collect(); + assert_eq!(out[0], want, "{backend}: row {row}, groups {groups:?}"); + } + } + eprintln!("ran on {ran:?}"); + assert!(!ran.is_empty(), "no device ran the test"); +} + +/// A program that moves a typed buffer's 16-bit channels +/// (`buffer_load_format_d16_xyzw` from the table's first view, +/// `buffer_store_format_d16_xyzw` to its second) names both places for the +/// host (`HostShader::half_views`) and moves every pattern as it is through +/// unsigned views: half floats, the not-a-number ones among them, and +/// plain 16-bit integers (the title keeps both in such buffers; the +/// network that moves its faces reads indices this way). A program that +/// moves no halves names nothing. +#[test] +fn halves_go_through_a_table_as_they_are_and_name_their_views() { + use super::host::Stride; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_UINT; + /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. + const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | op << 18 | 1 << 13, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] + } + const LOAD_D16_XYZW: u32 = 0x83; + const STORE_D16_XYZW: u32 = 0x87; + const THREADS: u32 = 32; + // The table's second descriptor, 0x20 bytes on. + let mut second = s_load_dwordx4(12, 4); + second[1] |= 0x20; + let mut words = vec![s_mov_b32(5, 0x80)]; + words.extend_from_slice(&s_load_dwordx4(8, 4)); + words.extend_from_slice(&second); + // v[1:2] = first[thread] (four halves), second[thread] = v[1:2]. + words.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); + words.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); + words.push(S_ENDPGM); + let view = |kind: ResourceType, table_offset_dwords: u32| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: table_offset_dwords / 8, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![view(ResourceType::Srv, 0), view(ResourceType::Uav, 8)], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [THREADS, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = + resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + assert_eq!(lowered.half_views, [(1, 0), (1, 8)]); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + half_views: lowered.half_views, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut dxil = shader.dxil.clone(); + v.validate(&mut dxil).expect("DXIL validation failed"); + } + // A raw store through the same table: no halves, nothing named. + assert!(build_valu_cs(&[]).half_views.is_empty()); + + // Four halves a thread: numbers, both zeros, subnormals, infinities, + // not-a-numbers of both signs, and integers past the largest number's + // pattern, as indices are. + const SPECIAL: [u16; 16] = [ + 0x0000, 0x0001, 0x03ff, 0x0400, 0x3c00, 0x7bff, 0x7c00, 0x7c01, 0x7e00, 0x7fff, 0x8000, + 0x8001, 0xbc00, 0xfc00, 0xfc01, 0xffff, + ]; + let halves: Vec<u16> = (0..4 * THREADS as usize) + .map(|i| match i { + 0..16 => SPECIAL[i], + _ => (i as u16).wrapping_mul(0x0203).wrapping_add(0x7b00), + }) + .collect(); + let data: Vec<u32> = halves + .chunks(2) + .map(|pair| u32::from(pair[0]) | u32::from(pair[1]) << 16) + .collect(); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[ + View::Buffer { + data: &data, + stride: Stride::Format(DXGI_FORMAT_R16G16B16A16_UINT, 8), + }, + View::HalfUintUav(THREADS), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!( + out[0], data, + "{label}: the halves stored are the halves loaded" + ); + ran += 1; + } + assert!(ran > 0, "no SM 6.6 device available"); +} + +/// The places a program that moves halves names are the descriptors it +/// loads, not the start of the range their used-resource entry describes: +/// with one entry for a range from dword 0, a load at byte 0x20 names +/// dword 8 (a host view there in a 16-bit float format is the one shown +/// as its unsigned twin). A descriptor picked at run time (the load's +/// offset in an SGPR) names nothing and keeps the float path: which slot +/// it reads, and in which format, is known only then. +#[test] +fn half_places_are_the_descriptors_the_program_loads() { + /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. + const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | op << 18 | 1 << 13, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] + } + const LOAD_D16_XYZW: u32 = 0x83; + const STORE_D16_XYZW: u32 = 0x87; + let lowered = |words: &[u32]| { + let range = |kind: ResourceType, table_offset_dwords: u32| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: table_offset_dwords / 8, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + // One entry for a range of views from dword 0, one at 16. + used: vec![range(ResourceType::Srv, 0), range(ResourceType::Uav, 16)], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [32, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = + resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower") + }; + // `s_load_dwordx4 s[dst:dst+3], s[4:5], offset` (soffset null), or with + // the offset in `soffset` instead. + let at = |dst: u8, offset: u32| { + let mut w = s_load_dwordx4(dst, 4); + w[1] |= offset; + w + }; + let picked = |dst: u8, soffset: u8| { + let mut w = s_load_dwordx4(dst, 4); + w[1] = u32::from(soffset) << 25; + w + }; + let mut fixed = vec![s_mov_b32(5, 0x80)]; + fixed.extend_from_slice(&at(8, 0x20)); + fixed.extend_from_slice(&at(12, 0x40)); + fixed.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); + fixed.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); + fixed.push(S_ENDPGM); + assert_eq!(lowered(&fixed).half_views, [(1, 8), (1, 16)]); + // The load's offset in s20, from the first lane's thread index + // (`v_readfirstlane_b32 s20, v0`): picked at run time. The pick may land + // on the store's place too, so no place of that table is named: the d16 + // accesses there take the float path, as before half views. + let mut runtime = vec![s_mov_b32(5, 0x80), vop1(0x02, 20, vgpr(0))]; + runtime.extend_from_slice(&picked(8, 20)); + runtime.extend_from_slice(&at(12, 0x40)); + runtime.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); + runtime.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); + runtime.push(S_ENDPGM); + assert!(lowered(&runtime).half_views.is_empty()); +} + +/// A format load of whole dwords (`buffer_load_format_x`, not d16) whose +/// result the program only reads one half of as a half float +/// (`v_cvt_f32_f16`) is moving 16-bit integers: the head program reads the +/// face network's output so, from an `R16_UINT` view. It names its view for +/// the host and loads the integer: 0x3c00 comes through as 1.0. Used as a +/// whole float instead (`v_add_f32`), the load stays a float load and names +/// nothing; so does a load of halves beside a load of the same view read as +/// a whole float (a view of numbers the program also picks one half float +/// out of, as hundreds of the title's pixel programs do). +#[test] +fn a_format_load_read_as_halves_loads_the_integer() { + use super::host::Stride; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT; + /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. + const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | op << 18 | 1 << 13, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] + } + const LOAD_FORMAT_X: u32 = 0x00; + const V_CVT_F32_F16: u16 = 0x0B; + const V_ADD_F32: u8 = 0x03; + let lowered = |body: &[u32]| { + let view = |kind: ResourceType, table_offset_dwords: u32, stride: u32| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: table_offset_dwords / 8, + stride, + dwords: 4, + user_data: 4, + slot: 1, + }; + let mut second = s_load_dwordx4(12, 4); + second[1] |= 0x20; + let mut words = vec![s_mov_b32(5, 0x80)]; + words.extend_from_slice(&s_load_dwordx4(8, 4)); + words.extend_from_slice(&second); + // `body` leaves v2, stored raw. + words.extend_from_slice(body); + words.extend_from_slice(&buffer_store_dword(2, 12, 0)); + words.push(S_ENDPGM); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![view(ResourceType::Srv, 0, 4), view(ResourceType::Uav, 8, 0)], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = + resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let l = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + HostShader { + stage: HwStage::Cs, + dxil: l.dxil, + user_data: l.user_data, + samplers: l.samplers, + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + root_indexed_views: res.root_indexed_views, + half_views: l.half_views, + } + }; + // v1 = first[v0] (one channel). + let load = mubuf_idxen(LOAD_FORMAT_X, 1, 0, 8); + let half = vop1(V_CVT_F32_F16, 2, vgpr(1)); + let as_halves = lowered(&[&load[..], &[half]].concat()); + assert_eq!(as_halves.half_views, [(1, 0)]); + let as_float = lowered(&[&load[..], &[vop2(V_ADD_F32, 2, vgpr(1), 1)]].concat()); + assert!(as_float.half_views.is_empty()); + // v3 = first[v0] too, read as a whole float: v2 = half(v1) + v3. + let mut beside = load.to_vec(); + beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8)); + beside.push(half); + beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2)); + assert!(lowered(&beside).half_views.is_empty()); + // Behind a branch, as the head program has it: where the lanes meet + // again the loaded value goes on through a phi, and a later write of + // v1 under EXEC reads it only to keep it in the lanes it leaves alone. + const SAVE_EXEC: u32 = 0xBE90_037E; // s_mov_b32 s16, exec_lo + const ONLY_LANE_0: u32 = 0x7DA4_0080; // v_cmpx_eq_u32 exec_lo, 0, v0 + const SKIP_3: u32 = 0xBF88_0003; // s_cbranch_execz over the next 3 words + const RESTORE_EXEC: u32 = 0xBEFE_0310; // s_mov_b32 exec_lo, s16 + let zero = vop1(0x01, 2, 128); // v_mov_b32 v2, 0 + let rewrite = vop1(0x01, 1, 128); // v_mov_b32 v1, 0 + let branched = lowered( + &[ + &[zero, SAVE_EXEC, ONLY_LANE_0, SKIP_3][..], + &load, + &[ + half, + RESTORE_EXEC, + SAVE_EXEC, + ONLY_LANE_0, + rewrite, + RESTORE_EXEC, + ], + ] + .concat(), + ); + assert_eq!(branched.half_views, [(1, 0)]); + // A d16 load names its place where it is the only access there... + const LOAD_FORMAT_D16_X: u32 = 0x80; + let d16 = mubuf_idxen(LOAD_FORMAT_D16_X, 1, 0, 8); + let d16_alone = lowered(&[&d16[..], &[half]].concat()); + assert_eq!(d16_alone.half_views, [(1, 0)]); + // ...and not beside a whole float read through the same place, which + // would see the unsigned twin: v2 = half(d16 v1) + v3. + let mut d16_beside = d16.to_vec(); + d16_beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8)); + d16_beside.push(half); + d16_beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2)); + assert!(lowered(&d16_beside).half_views.is_empty()); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + for shader in [&as_halves, &branched, &d16_alone] { + let mut dxil = shader.dxil.clone(); + v.validate(&mut dxil).expect("DXIL validation failed"); + } + } + // Element 0 of an R16_UINT buffer holds the half 1.0 (0x3c00). + let data = [0x0000_3c00u32, 0]; + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + for (name, shader) in [("straight", &as_halves), ("branched", &branched)] { + let (root, pso) = host + .compute_pipeline(shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Table, 1) => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[ + View::Buffer { + data: &data, + stride: Stride::Format(DXGI_FORMAT_R16_UINT, 2), + }, + View::RawUav(1), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!( + out[0][0], + 1.0f32.to_bits(), + "{label}, {name}: the half read as an integer's bits" + ); + } + ran += 1; + } + assert!(ran > 0, "no SM 6.6 device available"); +} diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index fa2d38cb40..2ea23dc367 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -16,6 +16,11 @@ use crate::{io, ir, resource, structure}; /// s0 (textures, or with `buffers` structured buffers of dwords, at entries /// 0 and 1, a raw UAV at entry 2) and the table of samplers at s1. fn build(words: &[u32], buffers: bool) -> HostShader { + build_with(words, buffers, 1) +} + +/// [`build`] for a program with `nonuniform` per-lane handles. +fn build_with(words: &[u32], buffers: bool, nonuniform: u32) -> HostShader { let table = |user_data: u8| RootParam { root: RootType::Table, table_offset_dwords: 0, @@ -69,12 +74,12 @@ fn build(words: &[u32], buffers: bool) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, - host_wave64: true, }) .expect("lower"); // One access with each lane's own heap index, no wave operation. - assert_eq!(lowered.nonuniform_handles, 1); - assert!(!lowered.wave_ops); + assert_eq!(lowered.nonuniform_handles, nonuniform); + // (Without an access to prove the loop a waterfall, its first-lane read is a wave operation.) + assert_eq!(lowered.wave_ops, nonuniform == 0); let shader = HostShader { stage: HwStage::Cs, dxil: lowered.dxil, @@ -83,6 +88,9 @@ fn build(words: &[u32], buffers: bool) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), + half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) @@ -248,3 +256,239 @@ fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() { } } } + +#[test] +fn immediate_sampler_chosen_by_control_flow() { + let s_mov_lit = |dst: u8, lit: u32| [0xBE80_03FF | (dst as u32) << 16, lit]; + let s_mov_zero = |dst: u8| 0xBE80_0380 | (dst as u32) << 16; + let s_load_x8 = |dst: u8, base: u8| [0x3D << 26 | 0x03 << 18 | (dst as u32) << 6 | (base as u32 >> 1), 125 << 25]; + let s_load_x4_off = |dst: u8, base: u8, off: u32| [0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), 125 << 25 | off]; + // image_sample_lz v4, v[2:3], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D + let image_sample_lz: [u32; 2] = [ + 0x3C << 26 | 0x21 << 18 | 1 << 8 | 1 << 3, // dmask=1, dim=2D(1) + (16u32 >> 2) << 21 | (8u32 >> 2) << 16 | 4 << 8 | 2, + ]; + // buffer_store_dword v4, off, s[20:23], 0 + let buf_store: [u32; 2] = [0x38 << 26 | 0x1C << 18, 0x80 << 24 | (20u32 >> 2) << 16 | 4 << 8]; + + // Two distinct valid immediate sampler descriptors (different wrap/filter bits). + let samp_a: [u32; 4] = [0x0000_0092, 0x00C0_0000, 0x1850_0000, 0]; + let samp_b: [u32; 4] = [0x0000_0092, 0x00C0_0000, 0x1850_0001, 0]; + + for (case_name, alt) in [("same_sampler", samp_a), ("different_samplers", samp_b)] { + let mut words = Vec::new(); + // s[2:3] = view table base (s0, 0). + words.push(0xBE80_0300 | (2 << 16)); // s_mov_b32 s2, s0 + words.push(s_mov_zero(3)); + words.extend_from_slice(&s_load_x8(8, 2)); // s[8:15] = texture SRV (offset 0) + words.extend_from_slice(&s_load_x4_off(20, 2, 64)); // s[20:23] = raw UAV (offset 16 dwords = 64B) + // v2 = 0.5, v3 = 0.5 (sample coordinates). + words.push(0x7E00_02F0 | (2 << 17)); // v_mov_b32 v2, 0.5 + words.push(0x7E00_02F0 | (3 << 17)); // v_mov_b32 v3, 0.5 + // s_cmp_eq_u32 s1, 0; s_cbranch_scc0 else_arm + words.push(0xBF00_8001); // s_cmp_eq_u32 s1, 0 (const 128) + let br_else = words.len(); + words.push(0); // placeholder s_cbranch_scc0 + // then arm: load samp_a into s[16:19] + for (i, &w) in samp_a.iter().enumerate() { + words.extend_from_slice(&s_mov_lit(16 + i as u8, w)); + } + let br_join = words.len(); + words.push(0); // placeholder s_branch + let else_pc = words.len(); + // else arm: load alt into s[16:19] + for (i, &w) in alt.iter().enumerate() { + words.extend_from_slice(&s_mov_lit(16 + i as u8, w)); + } + let join_pc = words.len(); + words[br_else] = 0xBF84_0000 | ((else_pc - br_else - 1) as u32 & 0xFFFF); + words[br_join] = 0xBF82_0000 | ((join_pc - br_join - 1) as u32 & 0xFFFF); + words.extend_from_slice(&image_sample_lz); + words.extend_from_slice(&buf_store); + words.push(0xBF81_0000); // s_endpgm + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 1, + slot: 1, + }, + ], + used: vec![ + UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }, + UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }, + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + + let p = ir::build(&native.code, false, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .unwrap_or_else(|e| panic!("{case_name}: lower failed: {e}")); + + let static_samplers = lowered + .samplers + .iter() + .map(|&w| super::StaticSampler::from_words(w)) + .collect(); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers, + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), + half_views: lowered.half_views, + }; + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + continue; + }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{case_name}/{label}: compute_pipeline failed: {e}")); + for branch in [0u32, 1u32] { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.slot) { + (RootType::Table, 0) => 0, + (RootType::Constants, 1) => branch, + other => panic!("unexpected user data {other:?}"), + }; + } + let texels = [[1.0f32, 0.0, 0.0, 1.0]]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[ + View::Texture(1, 1, &texels), + View::Texture(1, 1, &texels), + View::RawUav(1), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{case_name}/{label}: dispatch failed: {e}")); + let got = f32::from_bits(out[0][0]); + assert_eq!(got, 1.0, "{case_name}/{label} branch={branch}"); + } + } + } +} + +/// The console waterfall of [`resource::tests::WATERFALL_INDEXED_WAVE32`] +/// whose loaded descriptor is only read as numbers, never sampled (the +/// ray-tracing resolve reads an image's size that way): the loop ends in +/// `v_alignbit_b32 v1, s14, s13, 30`, which is the width - 1 and, from bit +/// 16, the height - 1 of the image descriptor's dwords 1 and 2. +const WATERFALL_SIZE_ONLY_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x360E_0081, // v_and_b32 v7, 1, v0 + 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBE95_037E, // s_mov_b32 s21, exec_lo + 0x7E28_0507, // 0x20: v_readfirstlane_b32 s20, v7 + 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 + 0xF40C_0302, + 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xD54E_0001, + 0x0278_1A0E, // v_alignbit_b32 v1, s14, s13, 30 + 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 + 0xBF89_FFF7, // s_cbranch_execnz -> 0x20 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0110, // buffer_store_dword v1, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm +]; + +#[test] +fn a_descriptor_only_read_as_data_gives_its_views_size() { + // Without a use no instruction names the view's kind; the table's range + // does (an image: taken for 2D). The lowering used to refuse. + let shader = build_with(WATERFALL_SIZE_ONLY_WAVE32, false, 0); + let (a, b) = ([[0.0f32; 4]; 8 * 4], [[0.0f32; 4]; 4 * 2]); + let views = [ + View::Texture(8, 4, &a), + View::Texture(4, 2, &b), + View::RawUav(32), + ]; + for (label, got) in run(&shader, &views) { + // Even lanes hold entry 0's offset (8 x 4), odd lanes entry 1's (4 x 2). + let want: Vec<u32> = (0..32) + .map(|l| if l & 1 == 0 { 7 | 3 << 16 } else { 3 | 1 << 16 }) + .collect(); + assert_eq!(got, want, "{label}"); + } +} diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index ca9b6e3489..1d7a91b7f4 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -2,7 +2,7 @@ //! (or `s_nand_saveexec 0`) and the restore of the saved mask runs in every lane of the console's //! wave, the inactive ones included, which is how the compiler expands //! HLSL wave reductions and prefix sums (an identity put into the inactive -//! lanes with `v_cndmask`, then DPP, `v_permlane16`, `v_permlanex16` and `v_readlane` +//! lanes with `v_cndmask`, then DPP, `v_permlanex16` and `v_readlane` //! steps). A host lane that is elsewhere cannot run that code, so each //! section is simulated on the console's lanes with symbolic values, and a //! value it leaves is lowered by what it turned out to be: the reduction or @@ -21,6 +21,10 @@ use crate::ir::{EXEC, Inst, Program, Reg, Value}; pub(crate) enum Op { AddU, AddF, + /// A sum of 16-bit floats in the low halves (`v_add_f16`), each addition rounded to 16 + /// bits: not associative, so only the balanced tree over the lanes in their order is + /// followed (see [`buddies`]), which is how the compiler sums a wave. + AddH, MinU, MaxU, MinI, @@ -35,8 +39,11 @@ pub(crate) enum Op { impl Op { fn of(name: &str) -> Option<Op> { Some(match name { - "v_add_nc_u32" => Op::AddU, + // the low dword of a 64-bit sum (`v_add_co_ci_u32` carries into + // the high one) is the 32-bit sum of the low dwords + "v_add_nc_u32" | "v_add_co_u32" => Op::AddU, "v_add_f32" => Op::AddF, + "v_add_f16" => Op::AddH, "v_min_u32" => Op::MinU, "v_max_u32" => Op::MaxU, "v_min_i32" => Op::MinI, @@ -53,7 +60,7 @@ impl Op { /// Whether `k` leaves the other operand unchanged. fn identity(self, k: u32) -> bool { match self { - Op::AddU | Op::Or | Op::Xor | Op::MaxU => k == 0, + Op::AddU | Op::AddH | Op::Or | Op::Xor | Op::MaxU => k == 0, Op::AddF => k == 0 || k == 0x8000_0000, Op::MinU | Op::And => k == u32::MAX, Op::MinI => k == 0x7FFF_FFFF, @@ -65,7 +72,26 @@ impl Op { /// Counting a lane twice changes the result. fn counts(self) -> bool { - matches!(self, Op::AddU | Op::AddF | Op::Xor) + matches!(self, Op::AddU | Op::AddF | Op::AddH | Op::Xor) + } +} + +/// Whether the lane sets `a` and `b` are the two halves of one aligned run of lanes: lanes +/// 2k and 2k+1, then two such pairs side by side, and so on up to the two halves of the +/// wave. Sums joined only that way form the balanced tree over the lanes in their order, +/// whichever of the two a lane adds to the other (the addition is commutative). +fn buddies(a: u64, b: u64) -> bool { + let n = a.count_ones(); + if n != b.count_ones() || !n.is_power_of_two() || n == 64 { + return false; + } + let run = |s: u64| { + let first = s.trailing_zeros(); + (first.is_multiple_of(n) && s >> first == (1u64 << n) - 1).then_some(first) + }; + match (run(a), run(b)) { + (Some(x), Some(y)) => x.min(y) % (2 * n) == 0 && x.abs_diff(y) == n, + _ => false, } } @@ -86,6 +112,15 @@ pub(crate) enum Sym { ident: u32, lanes: u64, }, + /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over + /// `lanes` of `mask ? f64(lo, hi) : 0.0`. + Red64F { + lo: Value, + hi: Value, + mask: Value, + lanes: u64, + high: bool, + }, } /// What a value a section leaves holds in every lane. @@ -97,6 +132,8 @@ pub(crate) enum Shape { Masked(Value, Value, u32), /// `op` over every lane. Active(Op, Value, Value, u32), + /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over every lane. + ActiveF64(Value, Value, Value, bool), /// `op` over the lanes below (`inclusive`: and including) each lane. Prefix(Op, Value, Value, u32, bool), } @@ -216,7 +253,8 @@ fn combine(op: Op, a: Sym, b: Sym) -> Sym { && op.identity(ident) && oa.is_none_or(|o| o == op) && ob.is_none_or(|o| o == op) - && (!op.counts() || la & lb == 0) => + && (!op.counts() || la & lb == 0) + && (op != Op::AddH || buddies(la, lb)) => { Sym::Red { op: Some(op), @@ -271,13 +309,28 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> { exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all; continue; } - if let Fields::Sop { src, .. } = &inst.fields { + if let Fields::Sop { dst, src, .. } = &inst.fields { if name.starts_with("s_and_b") && src.iter().any(|o| matches!(*o, Operand::Scalar { code, .. } if inst.read(Reg::S(code)).is_some_and(|v| masked.contains(&v)))) && let Some(&(_, w)) = inst.writes.iter().find(|w| matches!(w.0, Reg::S(_))) { masked.push(w); } + if name == "s_mov_b32" + && let (Some(Operand::Scalar { code: dc, .. }), Some(s0)) = (dst, src.first()) + && *dc != NULL + && let Some(w) = inst.write(Reg::S(*dc)) + { + let sym = match *s0 { + Operand::Scalar { code, .. } if code != NULL => inst + .read(Reg::S(code)) + .map_or(Sym::Unknown, |x| uni.get(&x).copied().unwrap_or(Sym::Uni(x))), + Operand::Const(c) => crate::resource::inline(c).map_or(Sym::Unknown, Sym::K), + Operand::Literal(x) => Sym::K(x), + _ => Sym::Unknown, + }; + uni.insert(w, sym); + } for &(_, w) in &inst.writes { uni.entry(w).or_insert(Sym::Unknown); } @@ -332,6 +385,130 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> { } continue; } + if name == "v_add_f64" + && !modifiers + && v.dpp.is_none() + && let Some(Operand::Vector { reg: dreg, .. }) = v.dst + && let (Some(dst_lo), Some(dst_hi)) = + (inst.write(Reg::V(dreg)), inst.write(Reg::V(dreg + 1))) + { + let pair_lanes = |op: Option<&Operand>| -> Option<(Vec<Sym>, Vec<Sym>)> { + match *op? { + Operand::Vector { reg, .. } => Some(( + lanes(&Operand::Vector { reg, dwords: 1 }, &vec, &uni), + lanes( + &Operand::Vector { + reg: reg + 1, + dwords: 1, + }, + &vec, + &uni, + ), + )), + Operand::Scalar { code, .. } if code != NULL => Some(( + lanes(&Operand::Scalar { code, dwords: 1 }, &vec, &uni), + lanes( + &Operand::Scalar { + code: code + 1, + dwords: 1, + }, + &vec, + &uni, + ), + )), + _ => None, + } + }; + let old_lo = lanes( + &Operand::Vector { + reg: dreg, + dwords: 1, + }, + &vec, + &uni, + ); + let old_hi = lanes( + &Operand::Vector { + reg: dreg + 1, + dwords: 1, + }, + &vec, + &uni, + ); + let f64_term = |lo_s: Sym, hi_s: Sym| -> Option<(Value, Value, Value, u64)> { + match (lo_s, hi_s) { + ( + Sym::Red { + op: None, + src: lo, + mask: ml, + ident: 0, + lanes: ll, + }, + Sym::Red { + op: None, + src: hi, + mask: mh, + ident: 0, + lanes: lh, + }, + ) if ml == mh && ll == lh => Some((lo, hi, ml, ll)), + ( + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: l1, + high: false, + }, + Sym::Red64F { + lo: lo2, + hi: hi2, + mask: m2, + lanes: l2, + high: true, + }, + ) if (lo1, hi1, m1, l1) == (lo2, hi2, m2, l2) => Some((lo1, hi1, m1, l1)), + _ => None, + } + }; + let mut out_lo = vec![Sym::Unknown; wave as usize]; + let mut out_hi = vec![Sym::Unknown; wave as usize]; + if let (Some((alo, ahi)), Some((blo, bhi))) = + (pair_lanes(v.src.first()), pair_lanes(v.src.get(1))) + { + for l in 0..wave as usize { + let (rl, rh) = match (f64_term(alo[l], ahi[l]), f64_term(blo[l], bhi[l])) { + (Some((lo1, hi1, m1, la)), Some((lo2, hi2, m2, lb))) + if (lo1, hi1, m1) == (lo2, hi2, m2) && la & lb == 0 => + { + ( + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: la | lb, + high: false, + }, + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: la | lb, + high: true, + }, + ) + } + _ => (Sym::Unknown, Sym::Unknown), + }; + out_lo[l] = if exec >> l & 1 != 0 { rl } else { old_lo[l] }; + out_hi[l] = if exec >> l & 1 != 0 { rh } else { old_hi[l] }; + } + } + vec.insert(dst_lo, out_lo); + vec.insert(dst_hi, out_hi); + continue; + } let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { for &(_, w) in &inst.writes { uni.insert(w, Sym::Unknown); @@ -408,29 +585,22 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> { }) .collect() } - (n @ ("v_permlane16_b32" | "v_permlanex16_b32"), Some(a)) => { - // Lane i of a row picks nibble i of {src2, src1}: from its - // own row (permlane16) or from the other row of its half of - // 32 lanes (permlanex16). Only with every lane active: the - // opsel bits (fi, bound_ctrl) decide what an inactive lane - // reads. + ("v_permlanex16_b32", Some(a)) => { + // Lanes of each row read the other row of their half; lane + // i's pick is nibble i of {src2, src1}. let sel = |k: usize| match v.src.get(k) { Some(&Operand::Const(c)) => crate::resource::inline(c), Some(&Operand::Literal(x)) => Some(x), _ => None, }; match (sel(1), sel(2)) { - (Some(s1), Some(s2)) if exec == all => { + (Some(s1), Some(s2)) => { let s = u64::from(s1) | u64::from(s2) << 32; (0..wave) .map(|l| { - let row = if n == "v_permlane16_b32" { - l & !15 - } else { - (l & !31) | ((l & 16) ^ 16) - }; + let other = (l & !31) | ((l & 16) ^ 16); let pick = (s >> (4 * (l & 15)) & 15) as u32; - a[(row | pick) as usize] + a[(other | pick) as usize] }) .collect() } @@ -540,6 +710,13 @@ fn shapes( ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + Sym::Red64F { + lo, + hi, + mask, + lanes, + high, + } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), _ => None, }; for (v, s) in uni { @@ -583,6 +760,13 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> { ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + Sym::Red64F { + lo, + hi, + mask, + lanes, + high, + } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), _ => None, }; } @@ -640,6 +824,32 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> { Some(Shape::Prefix(op, src, mask, ident, inclusive)) } +/// `WaveActiveBitOr(v7)` into s7 as the console compiler expands it: every lane takes part, +/// those outside the saved EXEC (s[4:5]) with 0. +#[cfg(test)] +pub(super) const WAVE_OR_V7_TO_S7: [u32; 20] = [ + 0xBE84_25C1, // s_or_saveexec_b64 s[4:5], -1 + 0xD501_0001, + 0x0012_0E80, // v_cndmask_b32 v1, 0, v7, s[4:5] + 0x3802_02E9, + 0xDE54_C101, // v_or_b32 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + 0x3802_02E9, + 0x9360_1201, // v_or_b32 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + 0x3802_02E9, + 0x0009_2401, // v_or_b32 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x3802_02FA, + 0xFF09_4001, // v_or_b32 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778_0002, + 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x3802_0302, // v_or_b32 v1, v2, v1 + 0xD760_0007, + 0x0001_4101, // v_readlane_b32 s7, v1, 32 + 0x3802_0207, // v_or_b32 v1, s7, v1 + 0xD760_0007, + 0x0001_0101, // v_readlane_b32 s7, v1, 0 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] +]; + #[cfg(test)] mod tests { use super::*; @@ -739,50 +949,6 @@ mod tests { ); } - /// Assembled with llvm-mc (gfx1030, wave32): a sum over all 32 lanes as - /// the console expands it, a DPP reduction of each row of 16, then each - /// row total read from lane 15 of its own row and of the other row. - const ROW_SUM_WORDS: [u32; 15] = [ - 0xBE80_3DC1, // s_or_saveexec_b32 s0, -1 - 0xD501_0001, - 0x0002_0080, // v_cndmask_b32_e64 v1, 0, v0, s0 - 0x4A02_02FA, - 0xFF01_6101, // v_add_nc_u32_dpp v1, v1, v1 row_xmask:1 - 0x4A02_02FA, - 0xFF01_6201, // v_add_nc_u32_dpp v1, v1, v1 row_xmask:2 - 0x4A02_02FA, - 0xFF01_6401, // v_add_nc_u32_dpp v1, v1, v1 row_xmask:4 - 0x4A02_02FA, - 0xFF01_6801, // v_add_nc_u32_dpp v1, v1, v1 row_xmask:8 - 0xD777_0002, - 0x0305_8301, // v_permlane16_b32 v2, v1, -1, -1 - 0xD778_0003, - 0x0305_8302, // v_permlanex16_b32 v3, v2, -1, -1 - ]; - - #[test] - fn permlane16_reads_the_lanes_own_row() { - let mut words = ROW_SUM_WORDS.to_vec(); - words.extend([ - 0x4A08_0702, // v_add_nc_u32_e32 v4, v2, v3 - 0xBEFE_0300, // s_mov_b32 exec_lo, s0 - 0xBF81_0000, // s_endpgm - ]); - let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let p = crate::ir::build(&code, false, 8).unwrap(); - let insts = &p.blocks[0].insts; - let (saved, x) = ( - insts[0].write(Reg::S(0)).unwrap(), - insts[1].read(Reg::V(0)).unwrap(), - ); - let total = insts[8].write(Reg::V(4)).unwrap(); - let found = sections(&p, 0); - assert_eq!( - found[&0].shapes.get(&total), - Some(&Shape::Active(Op::AddU, x, saved, 0)) - ); - } - #[test] fn constant_decodes_width_and_inline_kinds() { let b64 = 0x04; @@ -908,6 +1074,67 @@ mod tests { } } + /// `WaveActiveSum` of 16-bit floats, as compiled in + /// `compute_graph_ops:CS_TransposeVecMatMulAlignedOperation` (0x19c on): the tree the + /// lowering reproduces. A tree in another order is not followed. + #[test] + fn a_sum_of_halves_over_the_wave_is_followed_in_the_order_of_its_tree() { + let words = |first: [u32; 2], second: [u32; 2]| { + [ + 0xBE84_25C1, // s_or_saveexec_b64 s[4:5], -1 + 0xD501_0001, + 0x0012_0E80, // v_cndmask_b32 v1, 0, v7, s[4:5] + first[0], + first[1], + second[0], + second[1], + 0x6402_02E9, + 0x0009_2401, // v_add_f16 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x6402_02FA, + 0xFF09_4001, // v_add_f16 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778_0002, + 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x6402_0302, // v_add_f16 v1, v2, v1 + 0xD760_0007, + 0x0001_4101, // v_readlane_b32 s7, v1, 32 + 0x6402_0207, // v_add_f16 v1, s7, v1 + 0xD760_0007, + 0x0001_0101, // v_readlane_b32 s7, v1, 0 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] + ] + }; + let pairs = [0x6402_02E9, 0xDE54_C101]; // v_add_f16 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + let quads = [0x6402_02E9, 0x9360_1201]; // v_add_f16 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + let shape = |w: &[u32]| { + let p = build(w, true); + let insts = &p.blocks[0].insts; + let saved = insts[0].write(Reg::S(4)).unwrap(); + let v7 = p.inputs.iter().find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)).unwrap(); + // ..., v_readlane_b32 s7, v1, 0; s_mov_b64 exec, s[4:5]; s_endpgm + let total = insts[insts.len() - 3].write(Reg::S(7)).unwrap(); + (sections(&p, 0)[&0].shapes.get(&total).copied(), Shape::Active(Op::AddH, v7, saved, 0)) + }; + let (found, want) = shape(&words(pairs, quads)); + assert_eq!(found, Some(want)); + // lanes two apart first, neighbours second: every lane counted once, but + // (x0 + x2) + (x1 + x3) rounds differently from (x0 + x1) + (x2 + x3) + let (found, _) = shape(&words(quads, pairs)); + assert_eq!(found, None); + } + + #[test] + fn buddies_are_the_two_halves_of_an_aligned_run() { + assert!(buddies(0b01, 0b10)); + assert!(buddies(0b1100, 0b0011)); + assert!(buddies(0xF0, 0x0F)); + assert!(buddies(u64::from(u32::MAX), u64::from(u32::MAX) << 32)); + assert!(!buddies(0b010, 0b100)); // lanes 1 and 2: not one pair + assert!(!buddies(0b0011, 0b110000)); // pairs 0 and 2 + assert!(!buddies(0b0101, 0b1010)); // not runs + assert!(!buddies(0b01, 0b1100)); // unequal + assert!(!buddies(0b11, 0b11)); + } + #[test] fn wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp() { let w = [ diff --git a/crates/victory-shader/src/emit/wave64_fixtures.rs b/crates/victory-shader/src/emit/wave64_fixtures.rs deleted file mode 100644 index cebba3b869..0000000000 --- a/crates/victory-shader/src/emit/wave64_fixtures.rs +++ /dev/null @@ -1,199 +0,0 @@ -//! Synthetic wave64 compute programs (assembled with LLVM's `llvm-mc -//! -mcpu=gfx1010 -mattr=+wavefrontsize64`) for the emulation of 64-lane -//! waves on hosts without them ([`super::host_wave64`]). -//! -//! Each runs as one group of 64 threads (one console wave). The frame puts a -//! raw buffer UAV descriptor in `s[8:11]`; thread n stores its results at -//! dwords n, 64 + n, 128 + n and 192 + n. - -use super::lower::{Lowered, Parts, lower}; -use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, -}; -use crate::{ShaderError, io, ir, resource, structure}; - -/// Lane reads, a ballot and LDS shared within the wave without a barrier. -/// Per lane n: lane 37's v0 (37), the count of lanes below 40 (40), the -/// lane's own index from `v_mbcnt` (n), and lane (n + 1) % 64's v0 through -/// LDS (written by every lane just before). -pub(super) const CROSS_LANE: &[u32] = &[ - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0x340E_0082, // v_lshlrev_b32_e32 v7, 2, v0 - 0xD760_000C, - 0x0001_4B00, // v_readlane_b32 s12, v0, 37 - 0x7E02_020C, // v_mov_b32_e32 v1, s12 - 0xE070_1000, - 0x8002_0107, // buffer_store_dword v1, v7, s[8:11], 0 offen - 0x7D88_00A8, // v_cmp_gt_u32_e32 vcc, 40, v0 - 0xBE8D_106A, // s_bcnt1_i32_b64 s13, vcc - 0x7E04_020D, // v_mov_b32_e32 v2, s13 - 0xE070_1100, - 0x8002_0207, // buffer_store_dword v2, v7, s[8:11], 0 offen offset:256 - 0xD765_0003, - 0x0001_00C1, // v_mbcnt_lo_u32_b32 v3, -1, 0 - 0xD766_0003, - 0x0002_06C1, // v_mbcnt_hi_u32_b32 v3, -1, v3 - 0xE070_1200, - 0x8002_0307, // buffer_store_dword v3, v7, s[8:11], 0 offen offset:512 - 0x4A0C_0081, // v_add_nc_u32_e32 v6, 1, v0 - 0x360C_0CBF, // v_and_b32_e32 v6, 63, v6 - 0x340C_0C82, // v_lshlrev_b32_e32 v6, 2, v6 - 0xD834_0000, - 0x0000_0007, // ds_write_b32 v7, v0 - 0xD8D8_0000, - 0x0500_0006, // ds_read_b32 v5, v6 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xE070_1300, - 0x8002_0507, // buffer_store_dword v5, v7, s[8:11], 0 offen offset:768 -]; - -/// What [`CROSS_LANE`] stores, by dword. -#[cfg_attr(not(windows), allow(dead_code))] -pub(super) fn cross_lane_expected() -> Vec<u32> { - let mut out = vec![37; 64]; - out.extend([40; 64]); - out.extend(0..64); - out.extend((0..64).map(|n| (n + 1) % 64)); - out -} - -/// DPP, `v_readfirstlane` and `ds_swizzle`. Per lane n: lane n - 1's v0 -/// within its row of 16 (0 for a row's first lane, `bound_ctrl`), lane 0's -/// v0 + 100 (100), and lane n ^ 1's v0 (`ds_swizzle` SWAP 1). -pub(super) const DPP_FIRST_SWIZZLE: &[u32] = &[ - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0x340E_0082, // v_lshlrev_b32_e32 v7, 2, v0 - 0x7E10_02FA, - 0xFF09_1100, // v_mov_b32_dpp v8, v0 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1 - 0xE070_1000, - 0x8002_0807, // buffer_store_dword v8, v7, s[8:11], 0 offen - 0x4A12_00FF, - 0x0000_0064, // v_add_nc_u32_e32 v9, 0x64, v0 - 0x7E1C_0509, // v_readfirstlane_b32 s14, v9 - 0x7E14_020E, // v_mov_b32_e32 v10, s14 - 0xE070_1100, - 0x8002_0A07, // buffer_store_dword v10, v7, s[8:11], 0 offen offset:256 - 0xD8D4_041F, - 0x0B00_0000, // ds_swizzle_b32 v11, v0 offset:swizzle(SWAP,1) - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xE070_1200, - 0x8002_0B07, // buffer_store_dword v11, v7, s[8:11], 0 offen offset:512 -]; - -/// What [`DPP_FIRST_SWIZZLE`] stores, by dword (192 dwords). -#[cfg_attr(not(windows), allow(dead_code))] -pub(super) fn dpp_first_swizzle_expected() -> Vec<u32> { - let mut out: Vec<u32> = (0..64) - .map(|n| if n % 16 == 0 { 0 } else { n - 1 }) - .collect(); - out.extend([100; 64]); - out.extend((0..64).map(|n| n ^ 1)); - out -} - -/// A lane read inside `if (lane < 10)`: only those lanes reach it, so a -/// group barrier there could never complete. -pub(super) const DIVERGENT_READLANE: &[u32] = &[ - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0x340E_0082, // v_lshlrev_b32_e32 v7, 2, v0 - 0x7E02_0280, // v_mov_b32_e32 v1, 0 - 0x7D88_008A, // v_cmp_gt_u32_e32 vcc, 10, v0 - 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc - 0xBF88_0003, // s_cbranch_execz 3 - 0xD760_000C, - 0x0001_0B00, // v_readlane_b32 s12, v0, 5 - 0x7E02_020C, // v_mov_b32_e32 v1, s12 - 0x88FE_147E, // s_or_b64 exec, exec, s[20:21] - 0xE070_1000, - 0x8002_0107, // buffer_store_dword v1, v7, s[8:11], 0 offen -]; - -/// `body` as a wave64 compute program of `threads` threads with -/// `lds_bytes` of LDS, root constants in s0-s3 and a UAV table in s4. -pub(super) fn program(body: &[u32], threads: u32, lds_bytes: u32) -> NativeProgram { - // s_mov_b32 s5, 0; s_load_dwordx4 s[8:11], s[4:5], null - let mut words = vec![0xBE85_0380, 0xF408_0202, 0xFA00_0000]; - words.extend_from_slice(body); - words.push(0xBF81_0000); // s_endpgm - let param = |root, sgprs, user_data, slot| RootParam { - root, - table_offset_dwords: 0, - sgprs, - base_register: 0, - user_data, - slot, - }; - NativeProgram { - stage: HwStage::Cs, - wave64: true, - vgprs: 32, - layout: vec![ - param(RootType::Constants, 4, 0, 0), - param(RootType::Table, 1, 4, 1), - ], - used: vec![UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 4, - slot: 1, - }], - io: StageIo::Cs(ComputeIo { - // 5 user SGPRs; LDS in 512-byte units. - rsrc2: 5 << 1 | lds_bytes.div_ceil(512) << 15, - threads: [threads, 1, 1], - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - } -} - -/// Lowers `native` for a host with (or without) 64-lane waves. -pub(super) fn lower_for(native: &NativeProgram, host_wave64: bool) -> Result<Lowered, ShaderError> { - let p = ir::build(&native.code, native.wave64, native.vgprs)?; - let st = structure::structure(&p)?; - let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, native)?; - lower(&Parts { - native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, - host_wave64, - }) -} - -#[test] -fn one_wave_groups_translate_without_64_lane_waves() { - for body in [CROSS_LANE, DPP_FIRST_SWIZZLE] { - let native = program(body, 64, 512); - lower_for(&native, true).unwrap(); - lower_for(&native, false).unwrap(); - } -} - -#[test] -fn what_cannot_be_emulated_is_refused_with_a_reason() { - // Several console waves in one group: their lanes cannot be exchanged - // through one group's barriers. - let several = program(CROSS_LANE, 128, 512); - lower_for(&several, true).unwrap(); - let Err(e) = lower_for(&several, false) else { - panic!("translated"); - }; - assert!(e.to_string().contains("several 64-lane waves"), "{e}"); - // A lane read only some lanes reach. - let divergent = program(DIVERGENT_READLANE, 64, 0); - lower_for(&divergent, true).unwrap(); - let Err(e) = lower_for(&divergent, false) else { - panic!("translated"); - }; - assert!(e.to_string().contains("lane-dependent code"), "{e}"); -} diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs new file mode 100644 index 0000000000..ad3e4418c1 --- /dev/null +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -0,0 +1,907 @@ +//! A console wave64 compute program on a host of 32-lane waves: a wave reduction inside a +//! per-lane branch, with that branch taken wave-wide ([`crate::structure::structure_wide`]) +//! so that the two host waves can exchange their halves inside it. Lowered, validated by +//! `dxil.dll` when present, and run on the host GPU when it takes waves of 32. + +use std::collections::HashSet; + +use super::host::{Dispatch, Host, Root, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{ShaderError, io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// 64 threads in one console wave. Each thread t holds the bit `1 << (t >> 1)`; the threads +/// below s0 (a root constant) OR theirs over the wave inside `if (t < s0) { ... }` and store +/// the result to dword 0 of the raw UAV. +/// `skip`: the branch past the body when no thread is below s0: `s_cbranch_execz`, or +/// `s_cbranch_scc0` on the SCC `s_and_saveexec` sets ("some lane is left"). +fn program(skip: u32) -> NativeProgram { + let mut words = vec![ + 0x7E0A_0281, // v_mov_b32 v5, 1 + 0x2C0C_0081, // v_lshrrev_b32 v6, 1, v0 + 0x340E_0B06, // v_lshlrev_b32 v7, v6, v5 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + skip | 23, // the branch to the restore of EXEC + ]; + words.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + ]); + native(&words) +} + +/// A wave64 compute program of 64 threads (one console wave; the thread index in v0) with 4 +/// root constants in s0..s3 and a raw UAV's descriptor in s[8:11], then `body`. +fn native(body: &[u32]) -> NativeProgram { + native_of(body, true, 64) +} + +/// The same for a console of 32-lane waves when `wave64` is not set, with `threads` threads. +fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, + 125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0 + ]; + words.extend_from_slice(body); + words.push(S_ENDPGM); + NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 16, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + threads: [threads, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide. +fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet<usize>) -> Result<HostShader, ShaderError> { + lowered_on(native, p, wide, 32) +} + +/// [`lowered`] for a host whose waves have at most `host_wave` lanes. +fn lowered_on( + native: &NativeProgram, + p: &ir::Program, + wide: &HashSet<usize>, + host_wave: u32, +) -> Result<HostShader, ShaderError> { + let st = structure::structure_wide(p, wide).expect("structure"); + let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(p, native).expect("io::raise"); + let was = lower::TEST_HOST_WAVE.replace(Some(host_wave)); + let lowered = lower::lower(&lower::Parts { + native, + p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(was); + let lowered = lowered?; + Ok(HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + half_views: lowered.half_views, + }) +} + +#[test] +fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { + // thread t holds the 16-bit float with bits 0x3C00 + 37 t (1.0 and up, with odd + // mantissas, so that additions round); all of them store the wave's sum + let mut words = vec![ + 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E_0EFF, + 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 + ]; + // (the wave OR's words with v_add_f16 for v_or_b32: opcode 50 for 28) + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6); + let shader = lowered(&native, &p, &HashSet::new()).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + // the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits + // (to nearest, ties to even); values here are normal numbers + let wide = |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13); + let narrow = |f: f32| { + let b = f.to_bits(); + let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); + let rest = b & 0x1FFF; + (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 + }; + let add = |a: u16, b: u16| narrow(wide(a) + wide(b)); + let terms: Vec<u16> = (0..64u16).map(|t| 0x3C00 + 37 * t).collect(); + let mut tree = terms.clone(); + while tree.len() > 1 { + tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect(); + } + let in_a_row = terms.iter().copied().reduce(add).unwrap(); + assert_ne!(tree[0], in_a_row, "these terms tell the tree from another order"); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(x) => x, + Err(e) => { + eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run"); + return; + } + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + // (the high half is lane 0's term's: zero) + assert_eq!(out[0][0], u32::from(tree[0]), "tree {:#x}, in a row {in_a_row:#x}", tree[0]); + eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); +} + +/// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a +/// thread past the end of the data): on the console they add +0, and after each step of the +/// tree they hold their run's partial sum all the same. On a host of 64-lane waves (AMD) the +/// lanes that are here read each partner run's sum from a lane of it that is here. +#[test] +fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() { + let mut words = vec![ + 0x7DA8_0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay + 0, // s_cbranch_execz to the end (filled in below) + 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E_0EFF, + 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 + ]; + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + // past every word after it, to the program's end + words[1] = 0xBF88_0000 | (words.len() as u32 - 2); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let wide = |h: u16| { + if h == 0 { + 0.0 + } else { + f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13) + } + }; + let narrow = |f: f32| { + if f == 0.0 { + return 0; + } + let b = f.to_bits(); + let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); + let rest = b & 0x1FFF; + (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 + }; + let add = |a: u16, b: u16| narrow(wide(a) + wide(b)); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut ran = false; + for stay in [64u32, 63, 40, 33, 32, 17, 5, 1] { + let terms: Vec<u16> = (0..64u32) + .map(|t| if t < stay { (0x3C00 + 37 * t) as u16 } else { 0 }) + .collect(); + let mut tree = terms.clone(); + while tree.len() > 1 { + tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect(); + } + let Some(got) = on_the_card(&shader, [stay, 0]) else { + return; + }; + ran = true; + // (the high half is lane 0's term's: zero) + assert_eq!(got, u32::from(tree[0]), "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", tree[0]); + } + if ran { + eprintln!("ran on the hardware device: the console's tree with lanes gone, in every case"); + } +} + +/// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 +/// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The +/// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the +/// translation gives the console's whatever the host does. +#[test] +fn a_16_bit_sum_rounds_to_nearest_when_asked_to() { + let words = [ + 0x7E0E_02FF, + 0x0000_3C03, // v_mov_b32 v7, 0x3c03 + 0x7E0C_02FF, + 0x0000_4000, // v_mov_b32 v6, 0x4000 + 0x6400_0D07, // v_add_f16 v0, v7, v6 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]; + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "v_add_f16")); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for nearest in [false, true] { + let was = lower::TEST_F16_NEAREST.replace(Some(nearest)); + let shader = lowered(&native, &p, &HashSet::new()); + lower::TEST_F16_NEAREST.set(was); + let shader = shader.expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + eprintln!("the hardware device does not take this program; not run"); + return; + }; + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + let got = out[0][0] & 0xFFFF; + eprintln!("v_add_f16 0x3c03 + 0x4000 on the hardware device, nearest {nearest}: {got:#x}"); + if nearest { + assert_eq!(got, 0x4202); + } else { + assert!(got == 0x4201 || got == 0x4202, "{got:#x}"); + } + } +} + +#[test] +fn a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide() { + for (skip, name) in [(0xBF88_0000, "s_cbranch_execz"), (0xBF84_0000, "s_cbranch_scc0")] { + a_wave_or_inside(skip, name); + } +} + +fn a_wave_or_inside(skip: u32, name: &str) { + let native = program(skip); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let branch = (0..p.blocks.len()) + .find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == name)) + .expect("the branch"); + // per lane, the two host waves cannot meet inside the branch + lower::take_needs(); + let per_lane = lowered(&native, &p, &HashSet::new()); + assert!( + matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a wave reduction where not every lane runs"), + "{:?}", + per_lane.err() + ); + // ... and the lowering names the block, around which that branch is the one to widen + let needs = lower::take_needs(); + let st = structure::structure(&p).expect("structure"); + assert_eq!(lower::branches_around(&st, &needs), Some(vec![branch])); + // (taken, past the body, when every lane's bit is clear) + assert_eq!(st.wave_any[branch], Some(false)); + // wave-wide, every lane runs the reduction (EXEC stays a guard on what it does there) + let wide = HashSet::from([branch]); + let st = structure::structure_wide(&p, &wide).expect("structure"); + let inside = match p.blocks[branch].exit { + ir::Exit::Branch { not_taken, .. } => not_taken, + _ => unreachable!(), + }; + assert!(st.guards[inside].iter().any(Option::is_some)); + let shader = lowered(&native, &p, &wide).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + // On a GPU that takes waves of 32 (two host waves for the console's one): the OR is of + // both halves, whichever half's lanes take the branch. + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(x) => x, + Err(e) => { + eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run"); + return; + } + }; + // (threads below s0 take the branch; thread t gives bit t >> 1) + for (below, expected) in [(64u32, u32::MAX), (40, 0x000F_FFFF), (33, 0x0001_FFFF), (10, 0x1F), (1, 1)] { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if let (RootType::Constants, 0, 0) = (u.root, u.slot, u.dword) { + ud[u.index as usize] = below; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + assert_eq!(out[0][0], expected, "{name}: {below} threads in the branch"); + } + eprintln!("ran on the hardware device ({name}): the OR of both halves in every case"); +} + +/// Runs `shader` on the hardware device with the root constants `s0`, `s1` and gives dword 0 +/// of the UAV; None (and a line) without a device that takes it. +fn on_the_card(shader: &HostShader, constants: [u32; 2]) -> Option<u32> { + whole_uav(shader, constants, 1).map(|out| out[0]) +} + +/// As [`on_the_card`], and gives the first `dwords` dwords of the UAV. +fn whole_uav(shader: &HostShader, constants: [u32; 2], dwords: u32) -> Option<Vec<u32>> { + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return None; + }; + let Ok((root, pso)) = host.compute_pipeline(shader) else { + eprintln!("the hardware device does not take this program; not run"); + return None; + }; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if let (RootType::Constants, 0, d @ 0..=1) = (u.root, u.slot, u.dword) { + ud[u.index as usize] = constants[d as usize]; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(dwords)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + Some(out[0].clone()) +} + +/// A 32-lane console wave. A register holds a lane mask on one path (the lanes below s0) +/// and a number on the other, and is read as a number after the join, as the trace programs +/// keep their lanes' masks and their node numbers on one stack +/// (`deferred_tiled:CS_LaserLightShadowRaytracing`, s46 at 0x104, 0x75c and 0x188). The +/// mask arrives as the ballot of its lanes. +#[test] +fn a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is() { + let words = [ + 0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0 + 0xBE94_036A, // s_mov_b32 s20, vcc_lo + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0001, // s_cbranch_scc1 over the next + 0xBE94_0385, // s_mov_b32 s20, 5 + 0x7E00_0214, // v_mov_b32 v0, s20 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]; + let native = native_of(&words, false, 32); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = lowered(&native, &p, &HashSet::new()).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (below, other, expected) in [(32u32, 0u32, u32::MAX), (10, 0, 0x3FF), (0, 0, 0), (10, 1, 5)] { + let Some(got) = on_the_card(&shader, [below, other]) else { return }; + assert_eq!(got, expected, "{below} lanes in the mask, s1 = {other}"); + } + eprintln!("ran on the hardware device: the mask's bits, or the number"); +} + +/// A 32-lane console wave. `if (t < s0) { ... SCC = (s1 == 7) }` and a branch on SCC after +/// the join: the skip brings the SCC of `s_and_saveexec` ("some lane is left") along +/// (`rtdirectionalshadows:CS_RTShadowTrace32HQ_TiledFarOnly`, 0x360-0x39c). On the console +/// the skip is taken by the wave, so with some lane inside every lane sees the inner test. +/// A lane that skipped on its own would see "some lane is left" instead: refused per lane, +/// right with the branch taken wave-wide. Lane 31 stores what it saw. +#[test] +fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() { + let words = [ + 0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0 + 0xBE8D_3C6A, // s_and_saveexec_b32 s13, vcc_lo + 0xBF88_0001, // s_cbranch_execz over the next + 0xBF06_8701, // s_cmp_eq_u32 s1, 7 + 0xBEFE_030D, // s_mov_b32 exec_lo, s13 + 0xBF85_0002, // s_cbranch_scc1 to "seven" + 0x7E0A_0281, // v_mov_b32 v5, 1 + 0xBF82_0001, // s_branch over the next + 0x7E0A_0282, // seven: v_mov_b32 v5, 2 + 0x7DA4_009F, // v_cmpx_eq_u32 exec_lo, 31, v0 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16 | 5 << 8, // buffer_store_dword v5, off, s[8:11], 0 + ]; + let native = native_of(&words, false, 32); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let branch = (0..p.blocks.len()) + .find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz")) + .expect("the skip"); + lower::take_needs(); + let per_lane = lowered(&native, &p, &HashSet::new()); + assert!( + matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a lane mask read as data"), + "{:?}", + per_lane.err() + ); + let st = structure::structure(&p).expect("structure"); + assert_eq!(lower::branches_around(&st, &lower::take_needs()), Some(vec![branch])); + let shader = lowered(&native, &p, &HashSet::from([branch])).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + // (lanes below s0 inside, s1) -> what lane 31 stores: 2 if SCC was set at the branch + for (below, s1, expected) in [(0u32, 7u32, 1u32), (10, 7, 2), (10, 3, 1), (32, 3, 1), (32, 7, 2)] { + let Some(got) = on_the_card(&shader, [below, s1]) else { return }; + assert_eq!(got, expected, "{below} lanes inside, s1 = {s1}"); + } + eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside"); +} + +/// Fork pull request #646 (mynzjerko): a spilled 64-thread wave64 compute program, as the +/// structure builder's, dispatched by a `DispatchX` that counts threads +/// (`USER_DISPATCH_THREADS`). It stores `(bit count of EXEC on entry, wave OR of +/// 1 << (lane >> 1))` at `uav[lane * 2..]` from every lane. The threads at or past the count +/// must store nothing and count in neither; 0 is no count (all 64). On a host of 64-lane +/// waves they leave at entry; on one of 32 (both halves exchange) they stay, left out of the +/// ballot, the reduction and the store, and no barrier hangs with an empty upper half. +#[test] +fn threads_past_a_dispatch_x_count_do_nothing() { + let mut words = vec![ + // The spilled table's descriptor-table offset (user data 16) from s[0:1] + 0. + 0x8703_FF01, + 0x0000_00FF, // s_and_b32 s3, s1, 0xff + 0xBE82_0300, // s_mov_b32 s2, s0 + 0x3D << 26 | 4 << 6 | 1, + 125 << 25, // s_load_dword s4, s[2:3], 0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, + 125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xBE86_107E, // s_bcnt1_i32_b64 s6, exec + 0x7E0A_0281, // v_mov_b32 v5, 1 + 0x2C0C_0081, // v_lshrrev_b32 v6, 1, v0 + 0x340E_0B06, // v_lshlrev_b32 v7, v6, v5 + ]; + words.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7); + words.extend_from_slice(&[ + 0x3402_0083, // v_lshlrev_b32 v1, 3, v0 (8 bytes a lane) + 0x7E04_0206, // v_mov_b32 v2, s6 + 0x7E06_0207, // v_mov_b32 v3, s7 + 0x38 << 26 | 0x1D << 18 | 1 << 12, + 0x80 << 24 | 2 << 16 | 2 << 8 | 1, // buffer_store_dwordx2 v[2:3], v1, s[8:11], 0 offen + S_ENDPGM, + ]); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 16, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 16, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 16, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, // s[0:1]: the spilled table's pointer + threads: [64, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + assert!(crate::spill::is_spilled(&native)); + let p = crate::spill::build(&native).expect("spill::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let host = Host::new(false).ok(); + let counts = RootType::Other(super::USER_DISPATCH_THREADS); + for host_wave in [64u32, 32] { + let was = lower::TEST_HOST_WAVE.replace(Some(host_wave)); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(was); + let lowered = lowered.unwrap_or_else(|e| panic!("lower (waves of {host_wave}): {e}")); + assert!( + lowered.user_data.iter().any(|u| u.root == counts && u.dword == 0), + "waves of {host_wave}: the program does not take the thread count of x" + ); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views.clone(), + half_views: lowered.half_views, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).unwrap_or_else(|e| panic!("DXIL validation failed (waves of {host_wave}): {e}")); + } + let Some(host) = host.as_ref() else { continue }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + eprintln!("the hardware device does not take the waves-of-{host_wave} form; not run"); + continue; + }; + // (count, threads that run, their wave OR: bits 0..ceil(n / 2)) + for (count, active, or) in [(45u32, 45usize, 0x007F_FFFFu32), (1, 1, 1), (0, 64, u32::MAX)] { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in shader.user_data.iter().filter(|u| u.root == counts && u.dword == 0) { + ud[u.index as usize] = count; + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(128)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed (waves of {host_wave}, count {count}): {e}")); + for lane in 0..64 { + let got = (out[0][lane * 2], out[0][lane * 2 + 1]); + let expected = if lane < active { (active as u32, or) } else { (0, 0) }; + assert_eq!(got, expected, "waves of {host_wave}, count {count}, lane {lane}"); + } + } + eprintln!("ran on the hardware device (waves of {host_wave}): counts 45, 1 and none exact"); + } +} + +/// A wave64 program of 128 threads (two console waves) that leaves early when no lane of its +/// wave is below s0, as the console's compiler does when the end of the program is too far for +/// a branch: `s_cbranch_execnz` over a far jump to the end. `extra` are words that go into the +/// far jump's block before it, and `work_at_end` puts an instruction between the jump's target +/// and the end of the program. Then the gate: every thread stores 1, or 2 when some lane of its +/// console wave that is still running has the thread number s1 (the lanes that fail a test). +fn far_early_out(extra: &[u32], work_at_end: bool) -> NativeProgram { + let gate = [ + 0x7D84_0001, // v_cmp_eq_u32 vcc, s1, v0 + 0xBE90_106A, // s_bcnt1_i32_b64 s16, vcc + 0xBF06_8010, // s_cmp_eq_u32 s16, 0 + 0x8511_8281, // s_cselect_b32 s17, 1, 2 + 0x7E02_0211, // v_mov_b32 v1, s17 + 0x3404_0082, // v_lshlrev_b32 v2, 2, v0 + 0x38 << 26 | 0x1C << 18 | 1 << 12, + 0x80 << 24 | 2 << 16 | 1 << 8 | 2, // buffer_store_dword v1, v2, s[8:11], 0 offen + ]; + let jump = [ + 0xBE8E_1F00, // s_getpc_b64 s[14:15] + 0x800E_FF0E, + 4 * (4 + gate.len() as u32), // s_add_u32 s14, s14, the way to the end + 0x820F_800F, // s_addc_u32 s15, s15, 0 + 0xBE80_200E, // s_setpc_b64 s[14:15] + ]; + let mut words = vec![ + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF89_0000 | (extra.len() + jump.len()) as u32, // s_cbranch_execnz over the jump + ]; + words.extend_from_slice(extra); + words.extend_from_slice(&jump); + words.extend_from_slice(&gate); + if work_at_end { + words.push(0x7E06_0281); // v_mov_b32 v3, 1 + } + native_of(&words, true, 128) +} + +fn branches_named(p: &ir::Program, name: &str) -> usize { + p.blocks.iter().filter(|b| b.insts.last().is_some_and(|i| i.name() == name)).count() +} + +/// What the gate of [`far_early_out`] stores in each of 128 threads. +fn gate_expected(below: u32, failing: u32) -> Vec<u32> { + (0..128u32) + .map(|t| { + let some_fail = failing < below && failing / 64 == t / 64; + match (t < below, some_fail) { + (false, _) => 0, + (true, false) => 1, + (true, true) => 2, + } + }) + .collect() +} + +#[test] +fn a_far_early_out_is_left_out_and_the_gate_counts_the_lanes_of_both_halves() { + let native = far_early_out(&[], false); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + assert_eq!(branches_named(&p, "s_cbranch_execnz"), 1); + lower::take_needs(); + let kept = lowered(&native, &p, &HashSet::new()); + assert!( + matches!(&kept, Err(ShaderError::Unsupported { what, .. }) if what.ends_with("where not every lane runs")), + "{:?}", + kept.err() + ); + for (name, form) in [("early-outs", ir::without_early_outs(&p)), ("skips", ir::without_skips(&p, false))] { + let form = form.unwrap_or_else(|| panic!("without {name}: the far early-out stays")); + assert_eq!(branches_named(&form, "s_cbranch_execnz"), 0, "without {name}"); + } + let form = ir::without_early_outs(&p).expect("left out"); + let shader = lowered(&native, &form, &HashSet::new()).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + // (threads below s0 are in bounds; the one thread s1 fails the test) A failing thread of the + // upper half gives 2 to the lower half's threads as well, and a failing thread out of + // bounds counts for nothing + for (below, failing) in [(128u32, 40u32), (128, 100), (128, 63), (40, 50), (40, 10), (33, 32), (1, 0), (0, 5)] { + let Some(got) = whole_uav(&shader, [below, failing], 128) else { return }; + assert_eq!(got, gate_expected(below, failing), "{below} threads in bounds, thread {failing} fails"); + } + eprintln!("ran on the hardware device: the gate's count over both halves of each console wave"); +} + +#[test] +fn a_far_jump_that_does_work_is_not_an_early_out() { + // work in the jump's block, and work between the jump's target and the end + for (name, native) in [ + ("work in the jump", far_early_out(&[0xBE94_0385], false)), // s_mov_b32 s20, 5 + ("work at the target", far_early_out(&[], true)), + ] { + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + assert_eq!(branches_named(&p, "s_cbranch_execnz"), 1, "{name}"); + assert!(ir::without_early_outs(&p).is_none(), "{name}"); + assert!(ir::without_skips(&p, false).is_none(), "{name}"); + assert!(ir::without_skips(&p, true).is_none(), "{name}"); + } +} + +/// `if (t < s0) { park s[20:21]; if (s1 == 0) {..} else {..}; take it back }` and a read of +/// s[20:21] after the join, as the console's compiler leaves a parked scalar across an inner +/// branch. `then` is the inner branch's first arm; the second one leaves the parked scalar alone. +fn parked_across_an_inner_branch(then: u32) -> ir::Program { + let body = [ + 0xBE96_0414, // s_mov_b64 s[22:23], s[20:21] + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0002, // s_cbranch_scc1 to the second arm + then, + 0xBF82_0001, // s_branch to the join + 0xBE98_0382, // s_mov_b32 s24, 2 + 0xBE94_0416, // s_mov_b64 s[20:21], s[22:23] + ]; + let mut words = vec![ + 0xBE94_0406, // s_mov_b64 s[20:21], s[6:7] + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0000 | body.len() as u32, // s_cbranch_execz past the body + ]; + words.extend_from_slice(&body); + words.extend_from_slice(&[ + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0x7E02_0214, // v_mov_b32 v1, s20 + ]); + let native = native(&words); + ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build") +} + +#[test] +fn a_skip_whose_parked_scalars_pass_an_inner_branch_unchanged_is_left_out() { + let p = parked_across_an_inner_branch(0xBE96_0314); // s_mov_b32 s22, s20 + assert_eq!(branches_named(&p, "s_cbranch_execz"), 1); + // (s22 comes back through a phi of the inner join whose two arguments are copies of one + // value: only `deep` follows it) + assert!(ir::without_skips(&p, false).is_none()); + let deep = ir::without_skips(&p, true).expect("left out"); + assert_eq!(branches_named(&deep, "s_cbranch_execz"), 0); +} + +#[test] +fn a_skip_whose_parked_scalar_an_inner_branch_changes_is_kept() { + let p = parked_across_an_inner_branch(0xBE96_0387); // s_mov_b32 s22, 7 + assert_eq!(branches_named(&p, "s_cbranch_execz"), 1); + assert!(ir::without_skips(&p, false).is_none()); + assert!(ir::without_skips(&p, true).is_none()); +} + +/// `v_writelane_b32 vN, sX, K`. +fn writelane(n: u32, x: u32, lane: u32) -> Vec<u32> { + vec![0xD761_0000 | n, (128 + lane) << 9 | x] +} + +/// `v_readlane_b32 sX, vN, K`. +fn readlane(x: u32, n: u32, lane: u32) -> Vec<u32> { + vec![0xD760_0000 | x, (128 + lane) << 9 | (256 + n)] +} + +fn parked(words: &[Vec<u32>]) -> ir::Program { + let native = native(&words.concat()); + ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build") +} + +fn instructions<'a>(p: &'a ir::Program, name: &str) -> Vec<&'a ir::Inst> { + p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == name).collect() +} + +fn regs<T>(of: &[(ir::Reg, T)]) -> Vec<ir::Reg> { + of.iter().map(|r| r.0).collect() +} + +#[test] +fn a_pair_parked_in_lanes_that_hold_other_scalars_elsewhere_moves_as_a_pair() { + // s[20:21] goes into lanes 4 and 5 of v10 and comes back into s[22:23]; later lane 4 + // holds s30 for a while: no lane of the two is the pair's alone + let p = parked(&[ + writelane(10, 20, 4), + writelane(10, 21, 5), + vec![0x7E04_0281], // v_mov_b32 v2, 1 + readlane(22, 10, 4), + readlane(23, 10, 5), + writelane(10, 30, 4), + readlane(31, 10, 4), + ]); + let wide = instructions(&p, "s_mov_b64"); + let [save, restore] = wide[..] else { panic!("one pair save and one pair restore: {} moves", wide.len()) }; + assert_eq!(regs(&save.reads), [ir::Reg::S(20), ir::Reg::S(21)]); + assert_eq!(regs(&restore.writes), [ir::Reg::S(22), ir::Reg::S(23)]); + assert_eq!(regs(&restore.reads), regs(&save.writes)); + // the single scalar has its own lane register, not the pair's + let narrow = instructions(&p, "s_mov_b32"); + let lone_save = narrow.iter().find(|i| regs(&i.reads) == [ir::Reg::S(30)]).expect("the save of s30"); + let lone_restore = narrow.iter().find(|i| regs(&i.writes) == [ir::Reg::S(31)]).expect("the restore into s31"); + assert_eq!(regs(&lone_restore.reads), regs(&lone_save.writes)); + assert!(regs(&lone_save.writes).iter().all(|r| !regs(&save.writes).contains(r))); +} + +#[test] +fn a_parked_pair_another_save_or_restore_shares_stays_two_scalars() { + let cases = [ + ( + "a lone restore of the lane", + vec![ + writelane(10, 20, 4), + writelane(10, 21, 5), + readlane(22, 10, 4), + readlane(23, 10, 5), + readlane(24, 10, 4), + ], + ), + ( + "another save of the lane on one path to the restore", + vec![ + writelane(10, 20, 4), + writelane(10, 21, 5), + vec![0xBF06_8001, 0xBF85_0002], // s_cmp_eq_u32 s1, 0 and s_cbranch_scc1 over the save + writelane(10, 30, 4), + readlane(22, 10, 4), + readlane(23, 10, 5), + ], + ), + ]; + for (name, words) in cases { + let p = parked(&words); + assert!(instructions(&p, "s_mov_b64").is_empty(), "{name}"); + assert!(!instructions(&p, "s_mov_b32").is_empty(), "{name}"); + } +} diff --git a/crates/victory-shader/src/gfx10/fields.rs b/crates/victory-shader/src/gfx10/fields.rs index 723dae736b..2773b3c846 100644 --- a/crates/victory-shader/src/gfx10/fields.rs +++ b/crates/victory-shader/src/gfx10/fields.rs @@ -11,7 +11,9 @@ use super::{Encoding, Instruction}; pub enum Operand { /// Scalar registers by operand code: 0-105 `s0`-`s105`, 106/107 /// `vcc_lo`/`vcc_hi`, 108-123 `ttmp0`-`ttmp15`, 124 `m0`, 125 `null`, - /// 126/127 `exec_lo`/`exec_hi`. + /// 126/127 `exec_lo`/`exec_hi`. The decoder gives no code above 127; the + /// IR names scalars parked in VGPR lanes by the codes from 128 up + /// (`crate::ir::PARKED`). Scalar { code: u8, dwords: u8, @@ -805,15 +807,9 @@ fn image_addr_dwords(name: &str, dim: u8, a16: bool) -> u8 { } else if name.contains("_mip") { packed += 1; } - // On GFX10.3, `a16` packs coordinates/LOD/clamp into 16-bit pairs (and - // bias stays in its own VGPR as an f16 in the low half), while derivatives - // remain 32-bit unless the opcode is a `_g16` form. - let g16 = name.ends_with("_g16"); - let deriv_dwords = if g16 { - 2 * derivs.div_ceil(2) + if a16 { + whole + 2 * derivs.div_ceil(2) + packed.div_ceil(2) } else { - 2 * derivs - }; - let coord_dwords = if a16 { packed.div_ceil(2) } else { packed }; - whole + deriv_dwords + coord_dwords + whole + 2 * derivs + packed + } } diff --git a/crates/victory-shader/src/gfx10/mod.rs b/crates/victory-shader/src/gfx10/mod.rs index bd89534c33..ee38642a11 100644 --- a/crates/victory-shader/src/gfx10/mod.rs +++ b/crates/victory-shader/src/gfx10/mod.rs @@ -334,6 +334,27 @@ fn isa(offset: usize, reason: &'static str) -> ShaderError { mod tests { use super::*; + /// `VICTORY_DECODE=<file>` (+ `VICTORY_DECODE_WAVE64=1`): the GFX10 + /// instructions of a raw code file (device methods 0x1c8 / 0x218 dumps). + /// `cargo test -p victory-shader --lib -- --ignored decode_raw_file --nocapture` + #[test] + #[ignore] + fn decode_raw_file() { + let Some(path) = std::env::var_os("VICTORY_DECODE") else { + return; + }; + let code = std::fs::read(path).unwrap_or_default(); + let wave64 = std::env::var_os("VICTORY_DECODE_WAVE64").is_some(); + match decode(&code) { + Ok(list) => { + for i in list { + println!("{:06x}: {}", i.offset, i.text(wave64)); + } + } + Err(e) => println!("not decodable: {e}"), + } + } + const S_ENDPGM: u32 = 0xBF81_0000; /// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction. const fn sopp(op: u32, simm16: i16) -> u32 { @@ -475,18 +496,6 @@ mod tests { ); } - /// RDNA2 (GFX10.3) has the fused legacy multiply-adds at these - /// opcodes: LLVM's gfx1030 assembler tests encode - /// `v_fma_legacy_f32 v0, v1, v2, v3` and `v_fmac_legacy_f32_e32 v0, - /// v1, v2` as these words. - #[test] - fn legacy_multiply_adds_are_the_fused_ones() { - let fma = summary(&[0xD540_0000, 0x040E_0501, S_ENDPGM]); - assert_eq!(fma[0].2, "v_fma_legacy_f32"); - let fmac = summary(&[0x0C00_0501, S_ENDPGM]); - assert_eq!(fmac[0].2, "v_fmac_legacy_f32"); - } - #[test] fn rejects_bad_code() { assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4"); diff --git a/crates/victory-shader/src/gfx10/opcodes.rs b/crates/victory-shader/src/gfx10/opcodes.rs index 0ab9fa76cb..d1ba275aac 100644 --- a/crates/victory-shader/src/gfx10/opcodes.rs +++ b/crates/victory-shader/src/gfx10/opcodes.rs @@ -332,9 +332,7 @@ pub(super) const VOP2: &[(u16, &str)] = &[ (0x003, "v_add_f32"), (0x004, "v_sub_f32"), (0x005, "v_subrev_f32"), - // GFX10.3 fuses the legacy multiply-adds of GFX10.1 (Mesa's GFX10 - // column has the older names): AMD's RDNA2 ISA, LLVM's gfx1030 tables. - (0x006, "v_fmac_legacy_f32"), + (0x006, "v_mac_legacy_f32"), (0x007, "v_mul_legacy_f32"), (0x008, "v_mul_f32"), (0x009, "v_mul_i32_i24"), @@ -659,7 +657,7 @@ pub(super) const VOPC: &[(u16, &str)] = &[ ]; pub(super) const VOP3: &[(u16, &str)] = &[ - (0x140, "v_fma_legacy_f32"), + (0x140, "v_mad_legacy_f32"), (0x141, "v_mad_f32"), (0x142, "v_mad_i32_i24"), (0x143, "v_mad_u32_u24"), diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs index 9ed00ce969..9c7117e93b 100644 --- a/crates/victory-shader/src/io.rs +++ b/crates/victory-shader/src/io.rs @@ -31,8 +31,6 @@ //! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | //! primitives << 12). -use std::collections::HashMap; - use crate::ShaderError; use crate::gfx10::{Fields, Operand}; use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads}; @@ -140,6 +138,11 @@ pub enum Interp { /// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10, /// 1 for P20, 2 for P0 (the provoking vertex). Vertex { attribute: Attribute, vertex: u8 }, + /// A half of an interpolation whose i or j is computed rather than + /// loaded: each half evaluates as the hardware does, from the + /// attribute's vertex values (`v_interp_p1*`: P0 + i P10, with P10 = + /// P1 - P0; `v_interp_p2*`: its old dst + j P20, with P20 = P2 - P0). + Weighted { attribute: Attribute }, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -192,6 +195,22 @@ pub struct Io { /// Raises the I/O of `p`, built from `native`'s patched code. Fails for /// stages whose stage data is not read and on constructs not covered yet. pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { + raise_with(p, native, false) +} + +/// [`raise`], keeping every first half of an interpolation as an +/// interpolation of its own ([`Interp::Weighted`]: P0 + i P10, what the +/// hardware writes), also those a second half completes. For a pixel +/// program whose lowering stopped at "the first half of an +/// interpolation": one that also reads a first half's result for its own +/// sake (three world pixel shaders in a run on an RTX 4060, their draws +/// lost). Its rows are then read per vertex, weighed with `SV_Barycentrics` +/// (as for P10 and P20), which gives the same values. +pub fn raise_keeping_first_halves(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { + raise_with(p, native, true) +} + +fn raise_with(p: &Program, native: &NativeProgram, keep_firsts: bool) -> Result<Io, ShaderError> { let unsupported = |offset, what| ShaderError::Unsupported { offset, what }; let (loaded, ps_inputs, params) = match (&native.io, native.stage) { ( @@ -337,28 +356,63 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { }, ..Io::default() }; - // Only a second interpolation half needs to trace SSA definitions. - let mut halves = None; + let defs: std::collections::HashMap<Value, Site> = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + block + .insts + .iter() + .enumerate() + .flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i)))) + }) + .collect(); + let phis: std::collections::HashMap<Value, (usize, usize)> = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + block + .phis + .iter() + .enumerate() + .map(move |(i, phi)| (phi.value, (b, i))) + }) + .collect(); + let halves = Halves { + p, + defs: &defs, + phis: &phis, + }; for (b, block) in p.blocks.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); let at = inst.machine.offset; + let name = inst.name(); match &inst.fields { Fields::Vintrp { dst, src, attr } => { let attribute = attribute(inst, attr)?; - match (inst.name(), *src) { + match (name, *src) { ("v_interp_mov_f32", Operand::Const(vertex)) => { io.interps .push((site, Interp::Vertex { attribute, vertex })); } - ("v_interp_p1_f32", _) => {} + // A first half stands on its own when no second half + // consumes it (its result read as data): register it + // as a weighted interpolation, exactly what + // `push_pair` records for a consumed one (`push_pair` + // then finds it already there and adds nothing). + ("v_interp_p1_f32", _) => { + io.interps + .push((site, Interp::Weighted { attribute })); + } ("v_interp_p2_f32", Operand::Vector { reg, .. }) => { let Operand::Vector { reg: d, .. } = *dst else { return Err(unsupported(at, "an interpolation operand")); }; // The first half's result is this one's old dst. let interp = halves - .get_or_insert_with(|| Halves::new(p)) .pair( attr, inst.read(Reg::V(d)), @@ -366,30 +420,31 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { &barycentric, ) .map_err(|what| unsupported(at, what))?; - io.interps.push((site, interp.with(attribute))); + push_pair(&mut io, site, interp, attribute); } _ => return Err(unsupported(at, "an interpolation form")), } } - // Only interpolation has an attribute as a VALU source. - Fields::Valu(v) if matches!(v.src.first(), Some(Operand::Attr { .. })) => { - match inst.name() { - "v_interp_p1ll_f16" => {} - "v_interp_p2_f16" => { + Fields::Valu(v) if name.starts_with("v_interp_") => match name { + "v_interp_p1ll_f16" => { + if keep_firsts { let attribute = attribute(inst, &v.src[0])?; - let read = |k: usize| match v.src.get(k) { - Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)), - _ => None, - }; - let interp = halves - .get_or_insert_with(|| Halves::new(p)) - .pair(&v.src[0], read(2), read(1), &barycentric) - .map_err(|what| unsupported(at, what))?; - io.interps.push((site, interp.with(attribute))); + io.interps.push((site, Interp::Weighted { attribute })); } - _ => return Err(unsupported(at, "an interpolation form")), } - } + "v_interp_p2_f16" => { + let attribute = attribute(inst, &v.src[0])?; + let read = |k: usize| match v.src.get(k) { + Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)), + _ => None, + }; + let interp = halves + .pair(&v.src[0], read(2), read(1), &barycentric) + .map_err(|what| unsupported(at, what))?; + push_pair(&mut io, site, interp, attribute); + } + _ => return Err(unsupported(at, "an interpolation form")), + }, Fields::Exp { target, src, @@ -434,6 +489,23 @@ pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { } } } + // A first half registered for its own sake that a second half later + // paired with goes back to being the pair's business alone: the pair's + // `first` sites name it, and a standalone weighted entry here would make + // the lower emit the interpolation twice. + let paired: Vec<Site> = io + .interps + .iter() + .filter_map(|(_, interp)| match interp { + Interp::Interpolated { first, .. } => Some(first.iter().copied()), + _ => None, + }) + .flatten() + .collect(); + io.interps.retain(|(site, interp)| match interp { + Interp::Weighted { .. } => keep_firsts || !paired.contains(site), + _ => true, + }); Ok(io) } @@ -457,61 +529,52 @@ fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> { out } -/// An interpolation before its attribute is known. +/// An interpolation before its attribute is known: `barycentric` none +/// when i or j is computed. struct Pair { - barycentric: Barycentric, + barycentric: Option<Barycentric>, first: Vec<Site>, } impl Pair { fn with(self, attribute: Attribute) -> Interp { - Interp::Interpolated { - attribute, - barycentric: self.barycentric, - first: self.first, + match self.barycentric { + Some(barycentric) => Interp::Interpolated { + attribute, + barycentric, + first: self.first, + }, + None => Interp::Weighted { attribute }, } } } +/// Records interpolation `pair` at `site`, and its first halves too when +/// they evaluate on their own (computed barycentrics). +fn push_pair(io: &mut Io, site: Site, pair: Pair, attribute: Attribute) { + if pair.barycentric.is_none() { + for &f in &pair.first { + if !io.interps.iter().any(|(s, _)| *s == f) { + io.interps.push((f, Interp::Weighted { attribute })); + } + } + } + io.interps.push((site, pair.with(attribute))); +} + /// Finds the first halves of interpolations. struct Halves<'a> { p: &'a Program, - defs: HashMap<Value, Site>, - phis: HashMap<Value, (usize, usize)>, + defs: &'a std::collections::HashMap<Value, Site>, + phis: &'a std::collections::HashMap<Value, (usize, usize)>, } -impl<'a> Halves<'a> { - fn new(p: &'a Program) -> Self { - let defs = p - .blocks - .iter() - .enumerate() - .flat_map(|(b, block)| { - block - .insts - .iter() - .enumerate() - .flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i)))) - }) - .collect(); - let phis = p - .blocks - .iter() - .enumerate() - .flat_map(|(b, block)| { - block - .phis - .iter() - .enumerate() - .map(move |(i, phi)| (phi.value, (b, i))) - }) - .collect(); - Self { p, defs, phis } - } - +impl Halves<'_> { /// The interpolation whose second half reads the first half's result /// `acc`, the barycentric `j`, and attribute `attr`: every first half - /// must read the same attribute channel and the same kind's i. + /// must read the same attribute channel. With j and every first half's + /// i loaded as one kind's, the pair interpolates with that kind; + /// otherwise each half evaluates on its own (`Interp::Weighted`). fn pair( &self, attr: &Operand, @@ -525,8 +588,9 @@ impl<'a> Halves<'a> { &mut Vec::new(), &mut first, )?; - let Some((kind, 1)) = barycentric(j) else { - return Err("an interpolation with computed barycentrics"); + let mut kind = match barycentric(j) { + Some((kind, 1)) => Some(kind), + _ => None, }; for &(b, i) in &first { let inst = &self.p.blocks[b].insts[i]; @@ -545,8 +609,8 @@ impl<'a> Halves<'a> { if a != *attr { return Err("interpolation halves of different attributes"); } - if barycentric(i) != Some((kind, 0)) { - return Err("an interpolation with computed barycentrics"); + if kind.is_some_and(|k| barycentric(i) != Some((k, 0))) { + kind = None; } } Ok(Pair { @@ -681,85 +745,66 @@ mod tests { } #[test] - fn interpolation_can_take_its_first_half_from_either_branch() { + fn computed_barycentrics_evaluate_each_half() { + // i scaled before the first half: both halves stand on their own. let p = program(&[ - 0xBF84_0003, // s_cbranch_scc0 to the second branch - 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x - 0xC80C_0000, // v_interp_p1_f32 v3, v0, attr0.x - 0xBF82_0002, // s_branch to the paired p2 instructions - 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x - 0xC80C_0000, // v_interp_p1_f32 v3, v0, attr0.x + 0x1006_00F0, // v_mul_f32 v3, 0.5, v0 + 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x - 0xC80D_0001, // v_interp_p2_f32 v3, v1, attr0.x S_ENDPGM, ]); let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap(); - assert_eq!(io.interps.len(), 2); - for (i, (site, interp)) in io.interps.iter().enumerate() { - assert_eq!(*site, (3, i)); - let Interp::Interpolated { first, .. } = interp else { - panic!("{interp:?}"); - }; - assert_eq!(first, &[(1, i), (2, i)]); - } - } - - #[test] - fn vertex_sample_needs_no_second_half() { - let p = program(&[0xC80A_0002, S_ENDPGM]); // v_interp_mov_f32 v2, p0, attr0.x - let io = raise(&p, &pixel(vec![TEXCOORD], 0)).unwrap(); + let attribute = Attribute { + usage: Usage::Generic, + row: 1, + channel: 0, + high: false, + }; + let mut interps = io.interps.clone(); + interps.sort_by_key(|i| i.0); assert_eq!( - io.interps, - [( - (0, 0), - Interp::Vertex { - attribute: Attribute { - usage: Usage::Generic, - row: 1, - channel: 0, - high: false, - }, - vertex: 2, - }, - )] + interps, + [ + ((0, 1), Interp::Weighted { attribute }), + ((0, 2), Interp::Weighted { attribute }), + ] ); } #[test] - fn packed_interpolation_and_unsupported_form() { + fn kept_first_halves_stand_beside_their_pair() { + // The blit pair: with first halves kept, the first half is an + // interpolation of its own as well as the pair's. let p = program(&[ - 0xD742_0002, - 0x0002_0100, // v_interp_p1ll_f16 v2, attr0.x high, v0 - 0xD75A_0002, - 0x040A_0300, // v_interp_p2_f16 v2, attr0.x high, v1, v2 + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x S_ENDPGM, ]); let native = pixel(vec![TEXCOORD], 2); - let io = raise(&p, &native).unwrap(); - assert_eq!( - io.interps, - [( - (0, 1), - Interp::Interpolated { - attribute: Attribute { - usage: Usage::Generic, - row: 1, - channel: 0, - high: true, - }, - barycentric: Barycentric::PerspectiveCenter, - first: vec![(0, 0)], - }, - )] - ); - - let p = program(&[0xD743_0002, 0x0402_0000, S_ENDPGM]); // v_interp_p1lv_f16 + let attribute = Attribute { + usage: Usage::Generic, + row: 1, + channel: 0, + high: false, + }; + let plain = raise(&p, &native).unwrap(); + assert!(!plain.interps.iter().any(|i| i.0 == (0, 0))); + let kept = raise_keeping_first_halves(&p, &native).unwrap(); + let mut interps = kept.interps.clone(); + interps.sort_by_key(|i| i.0); assert_eq!( - raise(&p, &native), - Err(ShaderError::Unsupported { - offset: 0, - what: "an interpolation form", - }) + interps, + [ + ((0, 0), Interp::Weighted { attribute }), + ( + (0, 1), + Interp::Interpolated { + attribute, + barycentric: Barycentric::PerspectiveCenter, + first: vec![(0, 0)], + } + ), + ] ); } @@ -861,61 +906,4 @@ mod tests { ] ); } - - #[test] - #[ignore = "benchmark"] - fn bench_raise_io() { - use std::hint::black_box; - use std::time::Instant; - - let compute = NativeProgram { - stage: HwStage::Cs, - io: StageIo::Cs(crate::native::ComputeIo { - rsrc2: 0, - threads: [32, 1, 1], - }), - ..pixel(vec![], 0) - }; - let pixel = pixel(vec![TEXCOORD], 2); - for (label, native, prefix, suffix) in [ - ("compute", &compute, &[][..], &[][..]), - ( - "pixel vertex sample", - &pixel, - &[0xC80A_0002][..], - &[0xF800_0801, 2][..], - ), - ( - "pixel interpolation pair", - &pixel, - &[0xC808_0000, 0xC809_0001][..], - &[0xF800_0801, 2][..], - ), - ] { - for instructions in [64, 512, 4096] { - let mut words = prefix.to_vec(); - // Mix vector and scalar ALU writes without disturbing v0-v2. - words.extend( - [0x0606_0703, 0x0608_0904, 0x8000_8100, 0x060A_0B05].repeat(instructions / 4), - ); - words.extend_from_slice(suffix); - words.push(S_ENDPGM); - let p = program(&words); - let iterations = 2_000_000 / instructions; - let mut samples = [0.; 7]; - for sample in &mut samples { - let start = Instant::now(); - for _ in 0..iterations { - black_box(raise(black_box(&p), black_box(native)).unwrap()); - } - *sample = start.elapsed().as_secs_f64() * 1e9 / iterations as f64; - } - samples.sort_by(f64::total_cmp); - println!( - "{label:24} {instructions:4} ALU instructions: {:>10.1} ns/raise", - samples[3] - ); - } - } - } } diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 8f17c81528..29a24be4bc 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -19,7 +19,9 @@ use crate::ShaderError; use crate::gfx10::{self, Fields, Flow, Instruction, Operand}; /// One register dword. Scalar codes as in [`Operand::Scalar`]: 0-105 SGPRs, -/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. +/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. Codes from +/// [`PARKED`] up are scalars the compiler parked in VGPR lanes (`unspill`): +/// no machine instruction names them. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Reg { S(u8), @@ -30,6 +32,8 @@ pub enum Reg { pub const VCC: u8 = 106; pub const M0: u8 = 124; pub const EXEC: u8 = 126; +/// The first scalar code past the machine's (0-127): see [`Reg`]. +pub const PARKED: u8 = 128; /// An SSA value: the content of one register dword (SCC: one bit). #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -40,8 +44,8 @@ pub struct Program { pub wave64: bool, /// VGPRs v0 up to this exist; bounds M0-relative access. pub vgprs: u16, - /// In code order, then copies made to give every loop one entry. Block 0 - /// is the entry, which can be an empty block before the code. + /// In code order, then copies made to give every loop one entry; block 0 + /// is the entry. pub blocks: Vec<Block>, /// Registers read before any write, with their value on entry: what the /// hardware or a called fetch routine set up (user SGPRs, system values, @@ -52,7 +56,7 @@ pub struct Program { #[derive(Debug, Clone, PartialEq, Eq)] pub struct Block { /// Byte offset of the block's first machine instruction (shared by a - /// block and its copies). Zero for an empty entry block. + /// block and its copies). pub offset: usize, pub preds: Vec<usize>, pub phis: Vec<Phi>, @@ -76,18 +80,6 @@ pub enum Exit { } impl Exit { - fn successor_at(&self, index: usize) -> Option<usize> { - match (*self, index) { - (Exit::Jump(b), 0) | (Exit::Branch { taken: b, .. }, 0) => Some(b), - (Exit::Branch { not_taken, .. }, 1) => Some(not_taken), - _ => None, - } - } - - fn successor_iter(&self) -> impl Iterator<Item = usize> { - self.successor_at(0).into_iter().chain(self.successor_at(1)) - } - pub fn successors(&self) -> Vec<usize> { match *self { Exit::Jump(b) => vec![b], @@ -131,148 +123,11 @@ impl Inst { } } -/// The first user SGPR that the spill table of root arguments stands for. -const SPILL_FIRST: u8 = 16; - -/// Rewrites loads from the spill table (`s[0:1]`, the high dword masked to a -/// 40-bit address, usually through copies in `s2`/`s3`) into `s_mov_b32` from -/// the user SGPRs the table's dwords stand for. Only loads with a constant -/// offset, in code no branch joins after the pointer is set up, are rewritten. -fn spill_loads( - list: Vec<Instruction>, - wave64: bool, - code_len: usize, -) -> Result<Vec<Instruction>, ShaderError> { - use gfx10::Fields::{Smem, Sop, Valu}; - let mut targets = std::collections::BTreeSet::new(); - for inst in list.iter() { - let flow = gfx10::control(inst, code_len, |at| { - list[..list.partition_point(|i| i.offset < at)].last() - })?; - if let Flow::Jump(t) | Flow::Branch(t) = flow { - targets.insert(t); - } - } - // 1: a copy of s0, 2: a copy of s1 (masked to the address's high bits). - let mut tag = [0u8; 128]; - tag[0] = 1; - tag[1] = 2; - let mut out = Vec::with_capacity(list.len()); - let scalar = |o: &Operand| match *o { - Operand::Scalar { code, dwords } if code < 106 => Some((code, dwords.max(1))), - _ => None, - }; - for inst in list { - if targets.contains(&inst.offset) { - tag = [0; 128]; - } - let f = inst.fields(wave64); - let name = inst.name().unwrap_or(""); - // The load of the table. - if let Smem { - data: Some(ref d), - ref base, - offset, - ref soffset, - .. - } = f - && name.starts_with("s_load_dword") - && let Some((a, 2)) = scalar(base) - && tag[a as usize] == 1 - && tag[a as usize + 1] == 2 - && offset >= 0 - && offset % 4 == 0 - && matches!(*soffset, Operand::Scalar { code: 125, .. }) - && let Some((dst, n)) = scalar(d) - { - let first = u32::from(SPILL_FIRST) + (offset as u32) / 4; - if first + u32::from(n) <= 105 { - for k in 0..n { - let mov = - 0xBE80_0000 | u32::from(dst + k) << 16 | 3 << 8 | (first + u32::from(k)); - let mut bytes = mov.to_le_bytes().to_vec(); - bytes.extend(0xBF81_0000u32.to_le_bytes()); // s_endpgm - let mut one = gfx10::decode(&bytes)?.remove(0); - one.offset = inst.offset; - out.push(one); - } - for k in 0..n { - tag[(dst + k) as usize] = 0; - } - continue; - } - } - // What this instruction does to the tracked registers. - let mut written: Vec<(u8, u8)> = Vec::new(); - match &f { - Sop { - dst: Some(d), src, .. - } => { - if let Some((dc, dn)) = scalar(d) { - let new = match (name, src.as_slice()) { - ("s_mov_b32", [x]) => match scalar(x) { - Some((c, _)) if tag[c as usize] != 0 => tag[c as usize], - _ => 0, - }, - ("s_and_b32", [x, y]) => { - // `s1 & mask` with a small mask, either way round. - let masked = |reg: &Operand, mask: &Operand| match (scalar(reg), mask) { - (Some((c, _)), Operand::Literal(m)) => { - tag[c as usize] == 2 && *m <= 0xFFFF - } - (Some((c, _)), Operand::Const(k)) => { - tag[c as usize] == 2 && (129..=192).contains(k) - } - _ => false, - }; - if masked(x, y) || masked(y, x) { 2 } else { 0 } - } - _ => 0, - }; - if dn == 1 { - tag[dc as usize] = new; - } else { - written.push((dc, dn)); - } - } - } - Smem { data: Some(d), .. } => written.extend(scalar(d)), - Valu(v) => { - written.extend(v.dst.as_ref().and_then(scalar)); - written.extend(v.carry.as_ref().and_then(scalar)); - } - _ => {} - } - for (c, n) in written { - for k in c..c.saturating_add(n).min(128) { - tag[k as usize] = 0; - } - } - out.push(inst); - } - Ok(out) -} - /// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR /// count. Fails on instructions the IR cannot express yet /// ([`ShaderError::Unsupported`]). pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderError> { - build_with(code, wave64, vgprs, false) -} - -/// [`build`]; with `spilled`, loads from the root-argument spill table that -/// `s[0:1]` points to read the user SGPRs the table stands for (table dword -/// `k` is user SGPR `16 + k`), as plain register copies. -pub fn build_with( - code: &[u8], - wave64: bool, - vgprs: u16, - spilled: bool, -) -> Result<Program, ShaderError> { let mut list = gfx10::decode(code)?; - if spilled { - list = spill_loads(list, wave64, code.len())?; - } let lanes = 1 + u8::from(wave64); let isa = |offset, reason| ShaderError::Isa { offset, reason }; @@ -294,17 +149,10 @@ pub fn build_with( } leaders.sort_unstable(); leaders.dedup(); - // When the first instruction is a loop header, give SSA a separate - // entry edge to carry the initial register values into its phis. - let preheader = usize::from( - flows - .iter() - .any(|flow| matches!(flow, Flow::Jump(0) | Flow::Branch(0))), - ); + let parked = unspill(&mut list, &leaders, &flows, wave64, lanes, vgprs); let block_at = |offset: usize| { leaders .binary_search(&offset) - .map(|b| b + preheader) .map_err(|_| isa(offset, "jump into a block")) }; @@ -318,28 +166,24 @@ pub fn build_with( exit: Exit::End, }) .collect(); - if preheader != 0 { - blocks.insert( - 0, - Block { - offset: 0, - preds: Vec::new(), - phis: Vec::new(), - insts: Vec::new(), - exit: Exit::Jump(1), - }, - ); - } let next_offsets: Vec<Option<usize>> = (0..list.len()) .map(|i| list.get(i + 1).map(|n| n.offset)) .collect(); - for ((machine, flow), next) in list.into_iter().zip(flows).zip(next_offsets) { - let b = leaders.partition_point(|&l| l <= machine.offset) - 1 + preheader; + for (n, ((machine, flow), next)) in list.into_iter().zip(flows).zip(next_offsets).enumerate() { + let b = leaders.partition_point(|&l| l <= machine.offset) - 1; let name = machine.name().ok_or(ShaderError::Unsupported { offset: machine.offset, what: "unknown opcode", })?; - let fields = machine.fields(wave64); + let mut fields = machine.fields(wave64); + // A move to or from a scalar parked in a VGPR lane (`unspill`): its register + // codes may be ones the machine word cannot hold. + if let Ok(k) = parked.binary_search_by_key(&n, |m| m.0) + && let Fields::Sop { dst: Some(Operand::Scalar { code: to, .. }), src, .. } = &mut fields + && let Some(Operand::Scalar { code: from, .. }) = src.first_mut() + { + (*to, *from) = (parked[k].1, parked[k].2); + } let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?); let ends = flow != Flow::Next || next.is_none_or(|n| leaders.binary_search(&n).is_ok()); if ends { @@ -371,11 +215,504 @@ pub fn build_with( } } link(&mut blocks); + if !blocks[0].preds.is_empty() { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a branch to the program entry", + }); + } split_irreducible(&mut blocks)?; Ok(rename(blocks, wave64, vgprs)) } +/// Scalar registers the compiler parked in lanes of a VGPR, as scalar moves. +/// +/// When it runs out of SGPRs the console compiler saves one in a lane of a +/// spare VGPR (`v_writelane_b32 vN, sX, K`) and takes it back later +/// (`v_readlane_b32 sX, vN, K`). A VGPR whose every use in the program is one +/// of those two forms with a constant lane is such a store: lane K of it is a +/// scalar register by another name. Each (VGPR, lane) gets a register code +/// the program does not use (the trap temporaries first, then SGPRs it never +/// names, then codes from [`PARKED`] up, which no machine word can hold), and +/// the save and the restore become `s_mov_b32` to and from it. Returns those +/// moves (index in `list`, destination code, source code) in order, for +/// `build` to put the codes into the decoded fields. They are then copies for +/// every later stage: a parked descriptor is traced to its load, and nothing +/// is left of a cross-lane operation, which a console wave run as two host +/// waves could not do where not every lane runs (the lane may be in the other +/// wave, or not running). +/// A register pair parked in two neighbouring lanes (a lane mask, a 64-bit +/// address) moves as a pair (`s_mov_b64`) when every save and every restore +/// of the two lanes come together, so a parked lane mask comes back as the +/// mask it is; otherwise its halves come back as two scalars. A lane that holds other +/// scalars elsewhere (the compiler reuses lanes) has such pairs all the same, one by one: a +/// save of a pair into two lanes and the restores that read exactly that save, with no write +/// to the lanes on the way ([`site_pairs`]). +fn unspill( + list: &mut [gfx10::Instruction], + leaders: &[usize], + flows: &[Flow], + wave64: bool, + lanes: u8, + vgprs: u16, +) -> Vec<(usize, u8, u8)> { + /// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`: (save, N, X, K). + fn parked(inst: &gfx10::Instruction, fields: &Fields) -> Option<(bool, u8, u8, u32)> { + let Fields::Valu(v) = fields else { return None }; + if v.abs != 0 || v.neg != 0 || v.opsel != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some() || v.dpp.is_some() { + return None; + } + let lane = |op: &Operand| match *op { + Operand::Const(c @ 128..=191) => Some(u32::from(c) - 128), + _ => None, + }; + match (inst.name()?, v.dst?, v.src.as_slice()) { + ("v_writelane_b32", Operand::Vector { reg, .. }, [Operand::Scalar { code, .. }, k]) if *code < 105 => { + Some((true, reg, *code, lane(k)?)) + } + ("v_readlane_b32", Operand::Scalar { code, .. }, [Operand::Vector { reg, .. }, k]) if code < 105 => { + Some((false, *reg, code, lane(k)?)) + } + _ => None, + } + } + // VGPRs used by parking alone, the scalar codes the program uses, and + // per instruction the scalar codes it writes. + let mut stores = [false; 256]; + let mut other = [false; 256]; + let mut used = [false; 256]; + let mut parks: Vec<Option<Park>> = Vec::with_capacity(list.len()); + let mut written: Vec<Vec<u8>> = Vec::with_capacity(list.len()); + for inst in list.iter() { + let Some(name) = inst.name() else { return Vec::new() }; + let fields = inst.fields(wave64); + let park = parked(inst, &fields); + let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else { + return Vec::new(); + }; + let mut codes = Vec::new(); + if let Some((reads, writes)) = effects { + for ® in &writes { + if let Reg::S(c) = reg { + codes.push(c); + } + } + for reg in reads.into_iter().chain(writes) { + match reg { + Reg::S(c) => used[usize::from(c)] = true, + Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true, + Reg::V(r) => other[usize::from(r)] = true, + Reg::Scc => {} + } + } + } + parks.push(park); + written.push(codes); + } + for (i, park) in parks.iter_mut().enumerate() { + if park.is_some_and(|p| other[usize::from(p.1)]) { + *park = None; + } + let _ = i; + } + if parks.iter().all(Option::is_none) { + return Vec::new(); + } + let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); + // Lane pairs (register, lower lane) that always move together: each + // save of the lower lane is followed, in the same block and before its + // register changes, by the save of the next register into the next + // lane; each restore of the lower lane is followed at once by the + // restore of the next lane into the next register. + // The second save may come any number of instructions after the first (the + // compiler puts loads and constants between the two: five instructions later + // in the ped mesh programs). Only wave64 programs have pairs: a wave32 mask + // is one dword, and a pair move of it with its neighbour would hide it. + let mut slots: Vec<(u8, u32)> = parks.iter().flatten().map(|p| (p.1, p.3)).collect(); + slots.sort_unstable(); + slots.dedup(); + // instruction -> the instruction that completes its pair + let partner = |i: usize| -> Option<usize> { + let (save, reg, code, lane) = parks[i]?; + if save { + let mut j = i + 1; + while j < list.len() && !leader(j) { + if parks[j] == Some((true, reg, code + 1, lane + 1)) { + return Some(j); + } + if parks[j].is_some_and(|p| p.1 == reg && (p.3 == lane || p.3 == lane + 1)) + || written[j].contains(&code) + || written[j].contains(&(code + 1)) + { + return None; + } + j += 1; + } + None + } else { + let j = i + 1; + (j < list.len() && !leader(j) && parks[j] == Some((false, reg, code + 1, lane + 1))).then_some(j) + } + }; + let mut pairs: Vec<(u8, u32)> = Vec::new(); + for &(reg, lane) in &slots { + if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) { + continue; + } + let lower: Vec<usize> = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect(); + let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count(); + let partners: Vec<Option<usize>> = lower.iter().map(|&i| partner(i)).collect(); + let mut distinct: Vec<usize> = partners.iter().flatten().copied().collect(); + distinct.sort_unstable(); + distinct.dedup(); + if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() { + pairs.push((reg, lane)); + } + } + // Codes for the parked scalars: the trap temporaries (108..=123), then + // user SGPRs the program never names, from the top, then the codes past + // the machine's (`PARKED`..=254; 255 stays unused so that the code after a + // parked one always exists). A material resolve program parks up to 63 + // scalars and leaves about 20 machine codes unused. + let past = usize::from(PARKED); + let mut free = [false; 256]; + for c in (0..105).chain(108..=123) { + free[c] = !used[c]; + } + free[past..255].fill(true); + let take_pair = |free: &mut [bool; 256]| { + let c = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1])?; + (free[c], free[c + 1]) = (false, false); + Some(c as u8) + }; + let mut codes: Vec<((u8, u32), u8)> = Vec::new(); + for &(reg, lane) in &pairs { + // Not enough spare codes: leave the program as it is. + let Some(c) = take_pair(&mut free) else { return Vec::new() }; + codes.push(((reg, lane), c)); + codes.push(((reg, lane + 1), c + 1)); + } + let graph = BlockGraph::new(list, leaders, flows); + let candidates: Vec<(u8, u32)> = slots + .iter() + .copied() + .filter(|&(reg, lane)| { + let near = [lane.wrapping_sub(1), lane, lane + 1].map(|l| pairs.contains(&(reg, l))); + wave64 && !near.contains(&true) && slots.contains(&(reg, lane + 1)) + }) + .collect(); + let mut webs = site_webs(&candidates, &parks, &partner, &graph); + for web in &mut webs { + let Some(c) = take_pair(&mut free) else { return Vec::new() }; + web.code = c; + } + let in_web: Vec<usize> = webs.iter().flat_map(WebPair::sites).collect(); + for &slot in &slots { + if codes.iter().any(|c| c.0 == slot) { + continue; + } + let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else { + return Vec::new(); + }; + free[c] = false; + codes.push((slot, c as u8)); + } + let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1); + let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| { + list[i] = gfx10::Instruction { + offset: list[i].offset, + encoding, + opcode, + words: vec![word], + }; + }; + // `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code + // from `PARKED` up does not fit the word: s0 stands in for it there. + let field = |code: u8| if code < PARKED { u32::from(code) } else { 0 }; + let mov = |wide: bool, dst: u8, src: u8| 0xBE80_0000 | field(dst) << 16 | (3 + u32::from(wide)) << 8 | field(src); + const NOP: u32 = 0xBF80_0000; + let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = webs.iter().flat_map(|w| w.edits(&parks)).collect(); + for i in 0..list.len() { + let Some((save, reg, code, lane)) = parks[i] else { + continue; + }; + if in_web.contains(&i) { + continue; + } + let Some(slot) = code_of(reg, lane) else { return Vec::new() }; + if pairs.contains(&(reg, lane)) { + let Some(j) = partner(i) else { return Vec::new() }; + // A save moves the pair where its second half is saved; a + // restore where its first half is restored. + let (at, gone) = if save { (j, i) } else { (i, j) }; + let (dst, src) = if save { (slot, code) } else { (code, slot) }; + edits.push((at, Some((true, dst, src)))); + edits.push((gone, None)); + } else if lane > 0 && pairs.contains(&(reg, lane - 1)) { + // the upper half of a pair: moved with the lower + } else { + let (dst, src) = if save { (slot, code) } else { (code, slot) }; + edits.push((i, Some((false, dst, src)))); + } + } + let mut moves = Vec::new(); + for (i, edit) in edits { + match edit { + Some((wide, dst, src)) => { + put(list, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src)); + moves.push((i, dst, src)); + } + None => put(list, i, gfx10::Encoding::Sopp, 0, NOP), + } + } + moves.sort_unstable(); + moves +} + +/// `v_writelane_b32` / `v_readlane_b32` of a parked scalar, as [`unspill`] reads it: +/// (save, VGPR, scalar code, lane). +type Park = (bool, u8, u8, u32); + +/// A pair of scalars saved into two lanes at some sites and restored from them at others, +/// and nothing else of those lanes' content touches (see [`site_pairs`]). Its sites, as +/// instruction indices: each save or restore of the first lane with the one of the second. +#[derive(Debug)] +struct WebPair { + saves: Vec<(usize, usize)>, + restores: Vec<(usize, usize)>, + /// The scalar code the pair is parked in, with the one after it. + code: u8, +} + +impl WebPair { + fn sites(&self) -> impl Iterator<Item = usize> + '_ { + self.saves.iter().chain(&self.restores).flat_map(|&(a, b)| [a, b]) + } + + /// The pair moves that stand for its sites, and the no-ops that take the other halves' + /// places: a save moves the pair where its second half is saved, a restore where its + /// first half is restored. + fn edits(&self, parks: &[Option<Park>]) -> Vec<(usize, Option<(bool, u8, u8)>)> { + let code_of = |i: usize| parks[i].map_or(0, |p| p.2); + let mut edits = Vec::new(); + for &(first, second) in &self.saves { + edits.push((second, Some((true, self.code, code_of(first))))); + edits.push((first, None)); + } + for &(first, second) in &self.restores { + edits.push((first, Some((true, code_of(first), self.code)))); + edits.push((second, None)); + } + edits + } +} + +/// The blocks of the decoded code, as `build` cuts it: each instruction's block (an index into +/// the leaders) and each block's successors. +struct BlockGraph { + block_of: Vec<usize>, + succ: Vec<Vec<usize>>, +} + +impl BlockGraph { + fn new(list: &[gfx10::Instruction], leaders: &[usize], flows: &[Flow]) -> Self { + let block_of: Vec<usize> = list.iter().map(|i| leaders.partition_point(|&l| l <= i.offset) - 1).collect(); + let mut succ = vec![Vec::new(); leaders.len()]; + let block_at = |offset: usize| leaders.binary_search(&offset).ok(); + for (i, flow) in flows.iter().enumerate() { + let b = block_of[i]; + let fall = block_of.get(i + 1).copied(); + if fall == Some(b) { + continue; + } + match *flow { + Flow::Next => succ[b].extend(fall), + Flow::Jump(t) => succ[b].extend(block_at(t)), + Flow::Branch(t) => { + succ[b].extend(block_at(t)); + succ[b].extend(fall); + } + Flow::Stop => {} + } + } + Self { block_of, succ } + } +} + +/// The saves (bit k for the k-th, `entry` for none) that can reach the start of each block, +/// when the block `b` leaves only `last_save[b]` if it saves at all. +fn reach_blocks(graph: &BlockGraph, last_save: &[Option<u64>], entry: u64) -> Vec<u64> { + let mut reach = vec![0u64; graph.succ.len()]; + reach[0] = entry; + let mut changed = true; + while changed { + changed = false; + for (b, succ) in graph.succ.iter().enumerate() { + let out = last_save[b].unwrap_or(reach[b]); + for &s in succ { + let seen = reach[s]; + reach[s] |= out; + changed |= reach[s] != seen; + } + } + } + reach +} + +/// For each restore of the parked `slot` (VGPR, lane), the saves that can reach it: `None` +/// for the program's entry, where the lane holds nothing. Gives up (`None`) on a lane saved +/// too often for the sets to be bit masks. +fn reaching_saves(parks: &[Option<Park>], graph: &BlockGraph, slot: (u8, u32)) -> Option<Vec<(usize, Vec<Option<usize>>)>> { + let here = |i: usize| parks[i].filter(|p| (p.1, p.3) == slot); + let saves: Vec<usize> = (0..parks.len()).filter(|&i| here(i).is_some_and(|p| p.0)).collect(); + if saves.len() >= 63 { + return None; + } + let mut last_save: Vec<Option<u64>> = vec![None; graph.succ.len()]; + for (k, &i) in saves.iter().enumerate() { + last_save[graph.block_of[i]] = Some(1 << k); + } + let reach = reach_blocks(graph, &last_save, 1 << saves.len()); + let restores = (0..parks.len()).filter(|&i| here(i).is_some_and(|p| !p.0)); + Some( + restores + .map(|r| { + let b = graph.block_of[r]; + let mut before = saves.iter().enumerate().filter(|&(_, &i)| graph.block_of[i] == b && i < r); + let bits = before.next_back().map_or(reach[b], |(k, _)| 1 << k); + let defs = (0..=saves.len()).filter(|k| bits >> k & 1 != 0); + (r, defs.map(|k| saves.get(k).copied()).collect()) + }) + .collect(), + ) +} + +fn root_of(parent: &mut [usize], mut x: usize) -> usize { + while parent[x] != x { + parent[x] = parent[parent[x]]; + x = parent[x]; + } + x +} + +/// The pairs of every candidate lane pair (VGPR, lower lane), none sharing a site with an +/// earlier one. +fn site_webs( + candidates: &[(u8, u32)], + parks: &[Option<Park>], + partner: &dyn Fn(usize) -> Option<usize>, + graph: &BlockGraph, +) -> Vec<WebPair> { + let mut webs: Vec<WebPair> = Vec::new(); + for &candidate in candidates { + let claimed: Vec<usize> = webs.iter().flat_map(WebPair::sites).collect(); + let fresh = site_pairs(parks, partner, graph, candidate) + .into_iter() + .filter(|web| !web.sites().any(|i| claimed.contains(&i))); + webs.extend(fresh); + } + webs +} + +/// Whether each restore pair (first, second) reads exactly the saves that go with the saves +/// its first restore reads: `reaching` gives the saves each restore can see. +fn restores_read_their_pair( + restores: &[(usize, usize)], + reaching: &[(usize, Vec<Option<usize>>)], + partner: &dyn Fn(usize) -> Option<usize>, +) -> bool { + let reads = |i: usize| -> Vec<Option<usize>> { + let mut saves = reaching.iter().find(|r| r.0 == i).map_or_else(Vec::new, |r| r.1.clone()); + saves.sort_unstable(); + saves + }; + restores.iter().all(|&(first, second)| { + let mut want: Vec<Option<usize>> = reads(first).iter().map(|d| d.and_then(partner)).collect(); + want.sort_unstable(); + want == reads(second) + }) +} + +/// The pairs (see [`WebPair`]) parked in the lanes `lane` and `lane + 1` of a VGPR that +/// `unspill` can move as one 64-bit register though the lanes hold other scalars at other +/// places. Sites are joined into webs: a save with the save of the next lane that goes with it +/// (`partner`), a restore likewise, and a save with every restore it can reach. A web is a +/// pair when every one of its sites has its partner in it, the saves match the restores one +/// to one, each restore pair reads exactly the saves of one save pair, and no path reaches a +/// restore without a save. Then nothing else reads what the web saves and the web reads +/// nothing else's, so it can have registers of its own. +fn site_pairs( + parks: &[Option<Park>], + partner: &dyn Fn(usize) -> Option<usize>, + graph: &BlockGraph, + (reg, lane): (u8, u32), +) -> Vec<WebPair> { + let in_lane = |i: usize, l: u32| parks[i].is_some_and(|p| p.1 == reg && p.3 == l); + let sites: Vec<usize> = (0..parks.len()).filter(|&i| in_lane(i, lane) || in_lane(i, lane + 1)).collect(); + let at = |i: usize| sites.binary_search(&i).expect("a site of the lanes"); + let is_save = |i: usize| parks[i].is_some_and(|p| p.0); + let mut parent: Vec<usize> = (0..sites.len()).collect(); + let mut broken = vec![false; sites.len()]; + let join = |parent: &mut [usize], a: usize, b: usize| { + let (a, b) = (root_of(parent, at(a)), root_of(parent, at(b))); + parent[a] = b; + }; + let mut partners = Vec::new(); + for &i in sites.iter().filter(|&&i| in_lane(i, lane)) { + match partner(i) { + Some(j) => { + join(&mut parent, i, j); + partners.push(j); + } + None => broken[at(i)] = true, + } + } + for &j in sites.iter().filter(|&&j| in_lane(j, lane + 1) && !partners.contains(&j)) { + broken[at(j)] = true; + } + let mut reaching: Vec<(usize, Vec<Option<usize>>)> = Vec::new(); + for l in [lane, lane + 1] { + let Some(found) = reaching_saves(parks, graph, (reg, l)) else { return Vec::new() }; + reaching.extend(found); + } + for (r, defs) in &reaching { + for def in defs { + match def { + Some(d) => join(&mut parent, *r, *d), + None => broken[at(*r)] = true, + } + } + } + let mut components: Vec<usize> = (0..sites.len()).map(|k| root_of(&mut parent, k)).collect(); + components.sort_unstable(); + components.dedup(); + let mut webs = Vec::new(); + for component in components { + let members: Vec<usize> = sites.iter().copied().filter(|&i| root_of(&mut parent, at(i)) == component).collect(); + if members.iter().any(|&i| broken[at(i)]) { + continue; + } + let (saves, restores): (Vec<usize>, Vec<usize>) = + members.iter().copied().filter(|&i| in_lane(i, lane)).partition(|&i| is_save(i)); + let (upper_saves, upper_restores): (Vec<usize>, Vec<usize>) = + members.iter().copied().filter(|&i| in_lane(i, lane + 1)).partition(|&i| is_save(i)); + if saves.is_empty() + || restores.is_empty() + || saves.len() != upper_saves.len() + || restores.len() != upper_restores.len() + { + continue; + } + let pairs = |sites: &[usize]| -> Vec<(usize, usize)> { sites.iter().filter_map(|&i| Some((i, partner(i)?))).collect() }; + let restores = pairs(&restores); + if restores_read_their_pair(&restores, &reaching, partner) { + webs.push(WebPair { saves: pairs(&saves), restores, code: 0 }); + } + } + webs +} + /// Rename register reads and writes after changing edges in a reducible graph. fn rename(mut blocks: Vec<Block>, wave64: bool, vgprs: u16) -> Program { let order = reverse_postorder(&blocks); @@ -486,25 +823,282 @@ pub(crate) fn thread_edges( Ok(rename(blocks, p.wave64, p.vgprs)) } +/// The program without its early-outs: an `s_cbranch_execz` to a block that +/// only ends the program (`if (!inBounds) return;`, the outermost branch of +/// most compute programs) is left out, so the lanes that would have left +/// walk the body with EXEC clear. Vector instructions and every effect are +/// masked by EXEC already, as on the console, where the branch is taken +/// only when no lane of the wave is left; scalar code has no effects. The +/// body is then code every lane runs, which a console wave run as two host +/// waves needs for the barriers of its exchanges and LDS accesses. +/// A program too long for the branch to reach its end has the other form of the same +/// early-out: `s_cbranch_execnz` over a far jump to that end, which is left out as well. +/// `None` if the program has no such branch. +pub(crate) fn without_early_outs(p: &Program) -> Option<Program> { + let mut blocks = p.blocks.clone(); + let mut any = false; + for (b, block) in blocks.iter_mut().enumerate() { + if let Some(next) = early_out_continuation(p, b) { + block.insts.pop(); + block.exit = Exit::Jump(next); + any = true; + } + } + if !any { + return None; + } + for block in &mut blocks { + block.phis.clear(); + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + +/// Whether block `b` only ends the program. +fn ends_program(p: &Program, b: usize) -> bool { + p.blocks[b].exit == Exit::End + && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) +} + +/// Whether block `b` is the far jump of a console branch whose target is too far for the +/// branch's 16-bit offset (`s_getpc_b64`, an address added to it, `s_setpc_b64`) to a block +/// that only ends the program. Code that does any work on the way stays what it is. +fn far_jump_to_end(p: &Program, b: usize) -> bool { + let block = &p.blocks[b]; + matches!(block.exit, Exit::Jump(target) if ends_program(p, target)) + && block + .insts + .iter() + .all(|i| matches!(i.name(), "s_getpc_b64" | "s_add_u32" | "s_addc_u32" | "s_setpc_b64")) +} + +/// Where the lanes that stay go when block `b` ends in an early-out: `s_cbranch_execz` to a +/// block that only ends the program, or `s_cbranch_execnz` whose other way is a far jump to +/// such a block (a program too long for the branch to reach its end). The branch is then +/// left out and the code goes on there. +fn early_out_continuation(p: &Program, b: usize) -> Option<usize> { + let Exit::Branch { taken, not_taken } = p.blocks[b].exit else { + return None; + }; + match p.blocks[b].insts.last()?.name() { + "s_cbranch_execz" if ends_program(p, taken) => Some(not_taken), + "s_cbranch_execnz" if far_jump_to_end(p, not_taken) => Some(taken), + _ => None, + } +} + +/// As [`without_early_outs`], and also without the branches that only skip a +/// region when no lane is left for it: an `s_cbranch_execz` whose target is +/// where the skipped code ends up anyway (`if (c) { ... }` with nothing +/// else leaving the region). Every lane then walks the region with EXEC +/// clear for those that would have skipped it, and LDS accesses and +/// exchanges inside it are in code every lane runs. +/// The console takes such a branch only when no lane of the wave is left, +/// and then its scalar code does not run: a branch is kept if the code +/// after it could see that (a scalar register or SCC that the region +/// changes and the join merges with the value from before; EXEC aside, +/// which is empty either way). `None` if nothing changes. +/// +/// `deep` looks closer at what the code after the branch can see. A scalar the region moves +/// away and back (the compiler parks scalars in VGPR lanes around a branch and takes them +/// back before the join, `unspill`) is the value it copies, and so is a scalar phi whose +/// arguments all come to one value (a join of branches that left it alone); a join nothing +/// reads shows no one the difference (a restore of EXEC that the next one overwrites reads +/// nothing); and the join may have other ways in (an inner branch that ends together with an +/// outer one). +/// That leaves out most of the skips of the title's large lighting programs, whose bodies +/// are then code every lane runs. +pub(crate) fn without_skips(p: &Program, deep: bool) -> Option<Program> { + let n = p.blocks.len(); + // Scalars moved from register to register (a scalar the compiler parked in a VGPR lane + // comes back by such a move, `unspill`) are the value they copy. + let mut copy: std::collections::HashMap<Value, Value> = Default::default(); + // Values something reads, directly or through joins. A scalar operation none of whose + // results is read reads nothing either (the compiler restores EXEC from a saved mask + // and overwrites it at once where two branches end together). + let mut live: std::collections::HashSet<Value> = Default::default(); + let idle = |inst: &Inst, live: &std::collections::HashSet<Value>| { + let name = inst.name(); + matches!(inst.fields, crate::gfx10::Fields::Sop { .. }) + && !(name.starts_with("s_setpc") + || name.starts_with("s_swappc") + || name.starts_with("s_call") + || name.starts_with("s_rfe") + || name.starts_with("s_movrel") + || name.starts_with("s_subvector")) + && inst.writes.iter().all(|w| !live.contains(&w.1)) + }; + for block in &p.blocks { + for inst in &block.insts { + if matches!(inst.name(), "s_mov_b32" | "s_mov_b64") + && inst.reads.len() == inst.writes.len() + && inst.reads.iter().chain(&inst.writes).all(|r| matches!(r.0, Reg::S(_))) + { + copy.extend(inst.writes.iter().zip(&inst.reads).map(|(w, r)| (w.1, r.1))); + } + } + } + let mut changed = true; + while changed { + changed = false; + for block in &p.blocks { + for inst in &block.insts { + if !idle(inst, &live) { + for r in &inst.reads { + changed |= live.insert(r.1); + } + } + } + for phi in &block.phis { + if live.contains(&phi.value) { + for &a in &phi.args { + changed |= live.insert(a); + } + } + } + } + } + if deep { + copy_through_phis(p, &mut copy); + } + let root = |v: Value| if deep { follow(©, v) } else { v }; + // The region a skip of `b` to `target` leaves out, if it is a pure skip. + let skipped = |b: usize, target: usize, first: usize| -> Option<Vec<bool>> { + let mut inside = vec![false; n]; + let mut stack = vec![first]; + while let Some(x) = stack.pop() { + if x == target || inside[x] { + continue; + } + if x == b { + return None; // a loop back to the branch + } + inside[x] = true; + match p.blocks[x].exit { + Exit::End | Exit::Indirect => return None, + exit => stack.extend(exit.successors()), + } + } + // entered only through the branch + for x in (0..n).filter(|&x| inside[x]) { + if p.blocks[x].preds.iter().any(|&q| q != b && !inside[q]) { + return None; + } + } + // the join sees no scalar the region changed + let join = &p.blocks[target]; + for phi in &join.phis { + let scalar = match phi.reg { + Reg::S(c) => c != 126 && c != 127, + Reg::Scc => true, + Reg::V(_) => false, + }; + // (a join nothing reads shows no one the difference) + if !scalar || deep && !live.contains(&phi.value) { + continue; + } + let before: Vec<Value> = + join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| root(*a)).collect(); + let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| root(*a)); + if within.into_iter().any(|a| !before.contains(&a)) { + return None; + } + } + // Other ways into the join than the branch and the region (an inner branch that ends + // together with an outer one) change nothing in that: the lanes that would have + // skipped arrive from the region instead, with the same scalars. + if !deep && join.preds.iter().any(|&q| q != b && !inside[q]) { + return None; + } + Some(inside) + }; + let mut blocks = p.blocks.clone(); + let mut any = false; + for b in 0..n { + let Exit::Branch { taken, not_taken } = p.blocks[b].exit else { + continue; + }; + let next = early_out_continuation(p, b).or_else(|| { + let skip = p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz"); + (skip && skipped(b, taken, not_taken).is_some()).then_some(not_taken) + }); + if let Some(next) = next { + blocks[b].insts.pop(); + blocks[b].exit = Exit::Jump(next); + any = true; + } + } + if !any { + return None; + } + for block in &mut blocks { + block.phis.clear(); + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + +/// The value `v` is a copy of, followed to the end of `copy`'s chains. +fn follow(copy: &std::collections::HashMap<Value, Value>, mut v: Value) -> Value { + while let Some(&c) = copy.get(&v) { + v = c; + } + v +} + +/// The one value every argument of the scalar `phi` comes to (the phi's own value left +/// aside, as a loop's back edge brings it), if there is one. +fn single_source(copy: &std::collections::HashMap<Value, Value>, phi: &Phi) -> Option<Value> { + let mut one = None; + for x in phi.args.iter().map(|&a| follow(copy, a)).filter(|&x| x != phi.value) { + if *one.get_or_insert(x) != x { + return None; + } + } + one +} + +/// Adds to `copy` the scalar phis that pass one value through (a join of branches none of +/// which changed it, one after the other, as the console's compiler leaves them): such a phi +/// is a copy of that value. A phi that merges a real change is not. Repeats until no phi is +/// added, for a phi may pass through the ones before it. +fn copy_through_phis(p: &Program, copy: &mut std::collections::HashMap<Value, Value>) { + let mut added = true; + while added { + added = false; + for phi in p.blocks.iter().flat_map(|b| &b.phis) { + if copy.contains_key(&phi.value) || !matches!(phi.reg, Reg::S(_) | Reg::Scc) { + continue; + } + if let Some(one) = single_source(copy, phi) { + copy.insert(phi.value, one); + added = true; + } + } + } +} + /// Placeholder before renaming. const NONE: Value = Value(u32::MAX); -/// SGPR codes 0-127, SCC, VGPRs 0-255. -const REGS: usize = 128 + 1 + 256; +/// Scalar codes 0-255 (from [`PARKED`] up: parked scalars), SCC, VGPRs 0-255. +const REGS: usize = 256 + 1 + 256; type RegSet = [u64; REGS.div_ceil(64)]; fn index(reg: Reg) -> usize { match reg { Reg::S(c) => usize::from(c), - Reg::Scc => 128, - Reg::V(r) => 129 + usize::from(r), + Reg::Scc => 256, + Reg::V(r) => 257 + usize::from(r), } } fn reg_at(i: usize) -> Reg { match i { - 0..128 => Reg::S(i as u8), - 128 => Reg::Scc, - _ => Reg::V((i - 129) as u8), + 0..256 => Reg::S(i as u8), + 256 => Reg::Scc, + _ => Reg::V((i - 257) as u8), } } @@ -539,8 +1133,8 @@ pub(crate) fn reverse_postorder(blocks: &[Block]) -> Vec<usize> { while let Some(top) = stack.last_mut() { let (b, i) = *top; top.1 += 1; - match blocks[b].exit.successor_at(i) { - Some(s) if !seen[s] => { + match blocks[b].exit.successors().get(i) { + Some(&s) if !seen[s] => { seen[s] = true; stack.push((s, 0)); } @@ -561,7 +1155,7 @@ fn link(blocks: &mut [Block]) { block.preds.clear(); } for b in 0..blocks.len() { - for s in blocks[b].exit.successor_iter() { + for s in blocks[b].exit.successors() { blocks[s].preds.push(b); } } @@ -578,7 +1172,7 @@ pub(crate) fn irreducible_edge( let &entry = order.first()?; let idom = idoms(blocks, order, index); for &b in order { - for s in blocks[b].exit.successor_iter() { + for s in blocks[b].exit.successors() { if index[s] > index[b] { continue; } @@ -672,7 +1266,7 @@ fn split_irreducible(blocks: &mut Vec<Block>) -> Result<(), ShaderError> { } copy[b] = blocks.len() + copied.len(); copied.push(b); - for s in blocks[b].exit.successor_iter() { + for s in blocks[b].exit.successors() { if region[s] && s != header { stack.push(s); } @@ -716,16 +1310,16 @@ fn multi_entry_loop(blocks: &[Block], inside: &[bool]) -> Option<(Vec<bool>, Vec let mut seen = vec![false; blocks.len()]; let mut stack = vec![from]; while let Some(b) = stack.pop() { - let mut visit = |n: usize| { + let next = if forward { + blocks[b].exit.successors() + } else { + blocks[b].preds.clone() + }; + for n in next { if inside[n] && !seen[n] { seen[n] = true; stack.push(n); } - }; - if forward { - blocks[b].exit.successor_iter().for_each(&mut visit); - } else { - blocks[b].preds.iter().copied().for_each(&mut visit); } } seen @@ -787,7 +1381,7 @@ fn liveness(blocks: &[Block], order: &[usize]) -> (Vec<RegSet>, Vec<RegSet>) { changed = false; for &b in order.iter().rev() { let mut out = empty; - for s in blocks[b].exit.successor_iter() { + for s in blocks[b].exit.successors() { for (o, i) in out.iter_mut().zip(&live_in[s]) { *o |= i; } @@ -1044,6 +1638,7 @@ fn effects( indexed(d, &mut r)?; } } + "v_div_fmas_f32" | "v_div_fmas_f64" => r.extend(mask(VCC)), _ => {} } if name.starts_with("v_interp_") || src_indexed || dst_indexed { @@ -1232,10 +1827,13 @@ fn add_regs(op: &Operand, lanes: u8, out: &mut Vec<Reg>) -> Result<(), ()> { Operand::Scalar { code, .. } if code == gfx10::NULL => {} Operand::Scalar { code, dwords } => { let end = u16::from(code) + u16::from(dwords); - if end > 128 { + // A machine operand ends within the machine's codes, a parked + // scalar (`unspill`) within those past them. + let limit = if code < PARKED { 128 } else { 256 }; + if end > limit { return Err(()); } - out.extend((code..end as u8).map(Reg::S)); + out.extend((u16::from(code)..end).map(|c| Reg::S(c as u8))); } Operand::Vector { reg, dwords } => { if u16::from(reg) + u16::from(dwords) > 256 { @@ -1449,166 +2047,6 @@ mod tests { assert!(built > 500, "only {built} programs built"); } - fn reference_postorder(blocks: &[Block]) -> Vec<usize> { - let mut seen = vec![false; blocks.len()]; - let mut post = Vec::with_capacity(blocks.len()); - let mut stack = vec![(0, 0)]; - seen[0] = true; - while let Some(top) = stack.last_mut() { - let (b, i) = *top; - top.1 += 1; - match blocks[b].exit.successors().get(i) { - Some(&s) if !seen[s] => { - seen[s] = true; - stack.push((s, 0)); - } - Some(_) => {} - None => { - post.push(b); - stack.pop(); - } - } - } - post.reverse(); - post - } - - #[test] - fn cfg_successors_preserve_order() { - for exit in [ - Exit::End, - Exit::Indirect, - Exit::Jump(3), - Exit::Branch { - taken: 7, - not_taken: 2, - }, - Exit::Branch { - taken: 4, - not_taken: 4, - }, - ] { - assert_eq!(exit.successor_iter().collect::<Vec<_>>(), exit.successors()); - } - } - - fn synthetic_cfg(diamonds: usize) -> Vec<Block> { - let block = |exit| Block { - offset: 0, - preds: Vec::new(), - phis: Vec::new(), - insts: Vec::new(), - exit, - }; - - let mut blocks = Vec::new(); - - for i in 0..diamonds { - let base = i * 3; - - blocks.push(block(Exit::Branch { - taken: base + 1, - not_taken: base + 2, - })); - - blocks.push(block(Exit::Jump(base + 3))); - - let exit = if i % 5 == 0 { - Exit::Branch { - taken: base, - not_taken: base + 3, - } - } else { - Exit::Jump(base + 3) - }; - - blocks.push(block(exit)); - } - - blocks.push(block(Exit::End)); - - // Unreachable block. - blocks.push(block(Exit::Jump(diamonds * 3 + 1))); - - blocks - } - - #[test] - fn cfg_postorder_matches_reference() { - for count in [0, 1, 2, 16, 128, 2048] { - let blocks = synthetic_cfg(count); - - let expected = reference_postorder(&blocks); - let actual = reverse_postorder(&blocks); - - assert_eq!(actual, expected); - assert_eq!(actual.len(), count * 3 + 1); - } - } - - #[test] - #[ignore = "synthetic release microbenchmark"] - fn cfg_postorder_benchmark() { - use std::hint::black_box; - use std::time::Instant; - - fn measure(blocks: &[Block], run: impl Fn(&[Block]) -> Vec<usize>) -> f64 { - let start = Instant::now(); - - for _ in 0..128 { - black_box(run(black_box(blocks))); - } - - start.elapsed().as_secs_f64() * 1000.0 - } - - for count in [256, 2048, 8192] { - let blocks = synthetic_cfg(count); - - assert_eq!(reference_postorder(&blocks), reverse_postorder(&blocks)); - - black_box(measure(&blocks, reference_postorder)); - black_box(measure(&blocks, reverse_postorder)); - - let mut original = Vec::new(); - let mut candidate = Vec::new(); - - for round in 0..5 { - let (a, b) = if round % 2 == 0 { - let a = measure(&blocks, reference_postorder); - let b = measure(&blocks, reverse_postorder); - (a, b) - } else { - let b = measure(&blocks, reverse_postorder); - let a = measure(&blocks, reference_postorder); - (a, b) - }; - - original.push(a); - candidate.push(b); - - println!( - "blocks={} round={round}: \ - original={a:.3}ms candidate={b:.3}ms", - blocks.len() - ); - } - - original.sort_by(f64::total_cmp); - candidate.sort_by(f64::total_cmp); - - println!( - "MEDIAN blocks={}: \ - original={:.3}ms candidate={:.3}ms \ - speedup={:.3}x", - blocks.len(), - original[2], - candidate[2], - original[2] / candidate[2] - ); - } - } - const S_ENDPGM: u32 = 0xBF81_0000; fn build_words(words: &[u32], wave64: bool) -> Program { @@ -1620,71 +2058,54 @@ mod tests { p.inputs.iter().find(|i| i.0 == reg).expect("input").1 } - /// A compute program whose root arguments are in the spill table `s[0:1]` - /// points to: the loads become copies of the user SGPRs the dwords stand for. - #[test] - fn spill_table_loads_read_user_sgprs() { - let code: Vec<u8> = [ - 0xBE82_0300u32, // s_mov_b32 s2, s0 - 0x8703_FF01, // s_and_b32 s3, s1, lit - 0x0000_00FF, // 0xff - 0xF408_0201, // s_load_dwordx4 s[8:11], s[2:3], 0x10 - 0xFA00_0010, - 0xBE86_0308, // s_mov_b32 s6, s8 - S_ENDPGM, - ] - .iter() - .flat_map(|w| w.to_le_bytes()) - .collect(); - let plain = build_with(&code, false, 256, false).unwrap(); - assert!( - plain - .blocks - .iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "s_load_dwordx4") - ); - let p = build_with(&code, false, 256, true).unwrap(); - let insts: Vec<_> = p.blocks.iter().flat_map(|b| &b.insts).collect(); - assert!(!insts.iter().any(|i| i.name().starts_with("s_load"))); - // Table dwords 4..8 are user SGPRs 20..24. - for k in 0..4 { - assert!( - p.inputs.iter().any(|i| i.0 == Reg::S(20 + k)), - "s{} read", - 20 + k - ); - } - assert_eq!( - insts.iter().filter(|i| i.name() == "s_mov_b32").count(), - 1 + 4 + 1 - ); + /// `if (v0 < s0) { ... }` whose body changes s6: `body` are its words, `after` what + /// follows the join. + fn skip(body: &[u32], after: &[u32]) -> Program { + let mut w = vec![ + 0xBE94_0306, // s_mov_b32 s20, s6 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0000 | body.len() as u32, // s_cbranch_execz past the body + ]; + w.extend_from_slice(body); + w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13] + w.extend_from_slice(after); + w.push(S_ENDPGM); + build_words(&w, true) } - /// Loads from a pointer that is not the spill table stay loads. - #[test] - fn spill_table_leaves_other_loads() { - let code: Vec<u8> = [ - 0xF408_0A00u32, // s_load_dwordx4 s[8:11], s[0:1], 0 (s0:1 not yet copied: tagged) - 0xFA00_0000, - 0xBE82_0380, // s_mov_b32 s2, 0 - 0xF408_0201, // s_load_dwordx4 s[8:11], s[2:3], 0 (s2 overwritten) - 0xFA00_0000, - S_ENDPGM, - ] - .iter() - .flat_map(|w| w.to_le_bytes()) - .collect(); - let p = build_with(&code, false, 256, true).unwrap(); - let loads = p - .blocks + fn skips(p: &Program) -> usize { + p.blocks .iter() - .flat_map(|b| &b.insts) - .filter(|i| i.name().starts_with("s_load")) - .count(); - // The first load is from s[0:1] itself, so it is rewritten; the second - // reads a pointer the program overwrote, so it stays. - assert_eq!(loads, 1); + .filter(|b| b.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz")) + .count() + } + + #[test] + fn a_skip_is_left_out_when_the_scalars_it_changes_come_back_or_are_not_read() { + const SET: u32 = 0xBE86_0385; // s_mov_b32 s6, 5 + const USE: u32 = 0x7E02_0206; // v_mov_b32 v1, s6 + const BACK: u32 = 0xBE86_0314; // s_mov_b32 s6, s20 + const READ: u32 = 0x7E04_0206; // v_mov_b32 v2, s6 + // s6 is changed in the body and read after the join: the branch stays + let kept = skip(&[SET, USE], &[READ]); + assert_eq!(skips(&kept), 1); + assert!(without_skips(&kept, false).is_none()); + assert!(without_skips(&kept, true).is_none()); + // ... put back by a copy of what it held (as a scalar parked in a VGPR lane comes + // back): every lane may walk the body + let back = skip(&[SET, USE, BACK], &[READ]); + assert!(without_skips(&back, false).is_none()); + assert_eq!(skips(&without_skips(&back, true).expect("left out")), 0); + // ... or not read after the join at all + let unread = skip(&[SET, USE], &[]); + assert_eq!(skips(&without_skips(&unread, false).expect("left out")), 0); + assert_eq!(skips(&without_skips(&unread, true).expect("left out")), 0); + // ... or read only by a restore of EXEC that nothing uses before the next one + // (s_mov_b64 exec, s[6:7]; s_mov_b64 exec, s[12:13]; v_mov_b32 v2, s0) + let idle = skip(&[SET, USE], &[0xBEFE_0406, 0xBEFE_040C, 0x7E04_0200]); + assert!(without_skips(&idle, false).is_none()); + assert_eq!(skips(&without_skips(&idle, true).expect("left out")), 0); } #[test] @@ -1795,46 +2216,6 @@ mod tests { assert_eq!(b2.insts[0].name(), "s_endpgm"); } - #[test] - fn loops_can_branch_to_offset_zero() { - let p = build_words( - &[ - 0x8000_8100, // 0: s_add_u32 s0, s0, 1 - 0xBF07_8400, // s_cmp_lg_u32 s0, 4 - 0xBF85_FFFD, // s_cbranch_scc1 -> 0 - S_ENDPGM, - ], - false, - ); - let [entry, header, end] = &p.blocks[..] else { - panic!("{:?}", p.blocks); - }; - assert!(entry.preds.is_empty()); - assert!(entry.insts.is_empty()); - assert_eq!(entry.exit, Exit::Jump(1)); - assert_eq!(header.offset, 0); - assert_eq!(header.preds, [0, 1]); - assert_eq!( - header.exit, - Exit::Branch { - taken: 1, - not_taken: 2, - } - ); - assert_eq!(end.exit, Exit::End); - let [phi] = &header.phis[..] else { - panic!("{:?}", header.phis); - }; - let add = &header.insts[0]; - assert_eq!(phi.reg, Reg::S(0)); - assert_eq!( - phi.args, - [input(&p, Reg::S(0)), add.write(Reg::S(0)).unwrap()] - ); - assert_eq!(add.read(Reg::S(0)), Some(phi.value)); - assert!(crate::structure::structure(&p).is_ok()); - } - #[test] fn drops_scheduling_and_follows_far_jumps() { let p = build_words( diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs index beb6a67cc0..30b195262e 100644 --- a/crates/victory-shader/src/lib.rs +++ b/crates/victory-shader/src/lib.rs @@ -6,11 +6,7 @@ //! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use //! console-only intrinsics, so the GFX10 code is translated in general. -// Test-only: the symbols must be exported by whatever module hosts the device, and the -// application defines its own copy in `apps/victory`. Two definitions in one binary would -// collide at link time. -#[cfg(test)] -pub mod agility; +pub mod bvh; pub mod dxbc; pub mod dxil; pub mod emit; @@ -19,6 +15,7 @@ pub mod io; pub mod ir; pub mod native; pub mod resource; +pub mod spill; pub mod structure; pub use dxbc::{Container, FourCC, Part}; diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 036cb768e0..bea8fe698e 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -63,6 +63,7 @@ //! Rows are registers of the container's signature parts (`ISG1`, `OSG1`). //! Merged stages keep their stage data in another layout (not read). //! +//! Kind 0x0c holds the same `FSSM` blob unpacked. //! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped), //! 0x0a `xbop` (compiler options), 0x0e a table not decoded yet, 0x10 and //! 0x12 16-byte blobs (0x10 is the shader hash). @@ -74,6 +75,9 @@ use crate::dxbc::{u32_at, u64_at}; const XDAT_OFFSET: usize = 0x18; const MAX_XDAT_ENTRIES: usize = 64; const KIND_NATIVE: u32 = 0x0d; +/// The same `FSSM` blob stored as is, without the `XBCH` wrapper (the +/// executable's own debug-text shaders carry it so). +const KIND_NATIVE_RAW: u32 = 0x0c; const XBCH_VERSION: u32 = 3; const XBCH_HEADER: usize = 0x18; const FSSM_VERSION: u32 = 0x101; @@ -99,8 +103,6 @@ const RECORD_LAYOUT: usize = 0x28; const RECORD_USED: usize = 0x30; const RECORD_COUNTS: usize = 0x38; const ENTRY_SIZE: u64 = 20; -/// `s0`-`s105`: the SGPRs a program can address (106 on is VCC). -const SGPRS: u32 = 106; const MAX_SEMANTICS: u32 = 32; const PS_INPUTS: usize = 0x24; const PS_INPUT_COUNT: usize = 0x124; @@ -119,19 +121,21 @@ const VS_OUTPUTS: usize = 0xc8; const VS_OUTPUT_COUNT: usize = 0x188; const CS_RSRC2: usize = 0x24; const CS_THREADS: usize = 0x28; -/// D3D12's `numthreads` limits: x and y up to 1024, z up to 64, and at -/// most 1024 threads in the group. -const MAX_GROUP: [u32; 3] = [1024, 1024, 64]; -const MAX_GROUP_THREADS: u64 = 1024; const RECORD_LDS: usize = 0x4c; const MS_CLIP_CNTL: usize = 0x194; const MS_INFO: usize = 0x448; -/// The LDS a GFX10 thread group can address. -const MAX_LDS_BYTES: u32 = 64 << 10; -/// D3D12's mesh limits: at most 128 threads in the group, and at most 256 -/// vertices and 256 primitives out. -const MAX_MESH_THREADS: u32 = 128; -const MAX_MESH_OUTPUTS: u32 = 256; +const FSPX_VERSION: u32 = 1; +const FSPX_HEADER: usize = 0x10; +const FSPX_PACKET: u32 = 0; +const FSPX_CODE: u32 = 6; +const FSPX_METADATA: u32 = 7; +const PACKET_THREADS: usize = 0x0c; +const PACKET_FLAGS: usize = 0x12; +const PACKET_WAVE32: u16 = 1 << 4; +const PACKET_RSRC1: usize = 0x14; +const PACKET_RSRC2: usize = 0x18; +const FSPX_RECORDS: usize = 0x18; +const FSPX_RECORD: usize = 32; /// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes. const MAX_UNPACKED: u64 = 16 << 20; @@ -340,11 +344,9 @@ impl ComputeIo { end.unwrap_or(0).max(self.user_sgprs()) + (self.rsrc2 & 1) as u8 } - /// Thread id components in v0, v1, v2 (1 to 3). `TIDIG_COMP_CNT` is a - /// 2-bit field, but a group id has only three components: 3 loads x, y - /// and z like 2 does. + /// Thread id components in v0, v1, v2 (1 to 3). pub fn thread_id_vgprs(&self) -> u8 { - (self.rsrc2 >> 11 & 3).min(2) as u8 + 1 + (self.rsrc2 >> 11 & 3) as u8 + 1 } /// LDS bytes per thread group (512-byte granules). @@ -423,8 +425,12 @@ pub struct UsedResource { pub slot: u8, } -/// The native programs in a `DXIL` part's data; empty for the PC layout. +/// The native programs in a `DXIL` part's data, or in an `ACCC` part's +/// ([`fspx_program`]); empty for the PC layout. pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> { + if part.starts_with(b"FSPX") { + return Ok(vec![fspx_program(part)?]); + } if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") { return Ok(Vec::new()); } @@ -435,17 +441,145 @@ pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> { let mut out = Vec::new(); for i in 0..count { let at = XDAT_OFFSET + 12 + 12 * i; - if u32_at(part, at)? != KIND_NATIVE { + let kind = u32_at(part, at)?; + if kind != KIND_NATIVE && kind != KIND_NATIVE_RAW { continue; } let offset = u32_at(part, at + 4)?.into(); let size = u32_at(part, at + 8)?.into(); let blob = bytes(part, offset, size).ok_or(Malformed("XDAT entry out of bounds"))?; - out.extend(programs(&unpack(blob)?)?); + if kind == KIND_NATIVE_RAW { + out.extend(programs(blob)?); + } else { + out.extend(programs(&unpack(blob)?)?); + } } Ok(out) } +/// The compute program of an `ACCC` part, which a container carries in place +/// of `DXIL` when another compiler made the native code (the AMD +/// FidelityFX upscaler's shaders). Layout as observed (offsets from "FSPX"): +/// +/// ```text +/// +0x00 "FSPX" u32 version (1), u32 entry count, u32 size; entries of 16 B +/// from +0x10: u32 kind, u32 offset, u32 size, u32 0 +/// kind 0 pipeline registers, 0x1c B: +0x0c u16 x3 thread-group size, +/// +0x12 u16 flags (bit 4 wave32), +0x14 COMPUTE_PGM_RSRC1, +/// +0x18 COMPUTE_PGM_RSRC2 +/// kind 1 pipeline metadata (a hash); kind 6 the GFX10 code +/// kind 7 program metadata: u32 0x403, u32 size - 0x14, u32 code dwords, +/// u64 0, u8 0x40, u8 first user-data dword, u8 count of 0x41 +/// records, u8 0; then 32-byte records from +0x18, each a u32 tag: +/// 0x41 a resource the code reads: u8 resource type (as FSSM's used +/// entries), u8 root type, u16 0, u32 table offset (dwords), u32 +/// register, u32 view dimension (1 buffer, 4 2D, 0 root view), +/// u8 descriptor dwords, u8 user-data dword, u8 root slot, u8 0, +/// u32 -1, u32 0 +/// 0x42 a view declaration: u32 0, u8 1, u8 class (0 SRV, 1 UAV), +/// u8 resource kind (DXIL's), u8 0, u32 register +/// 0x43 the shader hash (16 B); the last record +/// ``` +pub fn fspx_program(part: &[u8]) -> Result<NativeProgram, ShaderError> { + if u32_at(part, 4)? != FSPX_VERSION { + return Err(Malformed("unknown FSPX version")); + } + let count = u32_at(part, 8)? as usize; + if count > MAX_XDAT_ENTRIES { + return Err(Malformed("implausible FSPX entry count")); + } + let entry = |kind: u32| -> Result<&[u8], ShaderError> { + for i in 0..count { + let at = FSPX_HEADER + 16 * i; + if u32_at(part, at)? == kind { + let (offset, size) = (u32_at(part, at + 4)?, u32_at(part, at + 8)?); + return bytes(part, offset.into(), size.into()) + .ok_or(Malformed("FSPX entry out of bounds")); + } + } + Err(Malformed("FSPX entry missing")) + }; + let packet = entry(FSPX_PACKET)?; + let code = entry(FSPX_CODE)?; + let meta = entry(FSPX_METADATA)?; + if u32_at(meta, 8)? as usize * 4 != code.len() { + return Err(Malformed("FSPX code size disagrees")); + } + let wave64 = u16_at(packet, PACKET_FLAGS)? & PACKET_WAVE32 == 0; + // VGPRs in granules of 4 (wave64) or 8 (wave32). + let granules = (u32_at(packet, PACKET_RSRC1)? & 0x3F) + 1; + let vgprs = (granules * if wave64 { 4 } else { 8 }).min(256) as u16; + let threads = |i: usize| u16_at(packet, PACKET_THREADS + 2 * i).map(u32::from); + let mut layout: Vec<RootParam> = Vec::new(); + let mut used = Vec::new(); + for e in meta + .get(FSPX_RECORDS..) + .unwrap_or(&[]) + .as_chunks::<FSPX_RECORD>() + .0 + { + match e[0] { + 0x41 => {} + 0x42 => continue, + 0x43 => break, + _ => return Err(Malformed("unknown FSPX metadata record")), + } + let root = RootType::from_raw(e[5].into()); + let u = UsedResource { + kind: match e[4] { + 0 => ResourceType::Srv, + 1 => ResourceType::Sampler, + 2 => ResourceType::Cbv, + 3 => ResourceType::Uav, + n => ResourceType::Other(n), + }, + root, + table_offset_dwords: le32(e, 8), + lower_bound: le32(e, 12), + stride: 0, + dwords: e[20], + user_data: e[21], + slot: e[22], + }; + let sgprs = match root { + RootType::Table => 1, + RootType::Descriptor => 2, + // The code holds its words; no user data. + RootType::ImmediateSampler => 0, + _ => return Err(Malformed("an FSPX resource of an unknown root type")), + }; + if sgprs > 0 && !layout.iter().any(|p| p.slot == u.slot) { + layout.push(RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: u.lower_bound, + user_data: u.user_data, + slot: u.slot, + }); + } + used.push(u); + } + Ok(NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs, + layout, + used, + io: StageIo::Cs(ComputeIo { + rsrc2: u32_at(packet, PACKET_RSRC2)?, + threads: [threads(0)?, threads(1)?, threads(2)?], + }), + code: code.to_vec(), + }) +} + +fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> { + data.get(at..at + 2) + .map(|b| u16::from_le_bytes([b[0], b[1]])) + .ok_or(Malformed("FSPX data out of bounds")) +} + fn unpack(blob: &[u8]) -> Result<Vec<u8>, ShaderError> { if blob.get(0..4) != Some(b"XBCH") { return Err(Malformed("native blob lacks XBCH magic")); @@ -460,14 +594,63 @@ fn unpack(blob: &[u8]) -> Result<Vec<u8>, ShaderError> { } let stream = bytes(blob, XBCH_HEADER as u64, packed).ok_or(Malformed("XBCH stream out of bounds"))?; - let out = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(stream, unpacked as usize) - .map_err(|_| Malformed("XBCH stream does not inflate to its stated size"))?; - if out.len() as u64 != unpacked { - return Err(Malformed("XBCH stream does not inflate to its stated size")); - } + let out = inflate_zlib_exact(stream, unpacked as usize) + .ok_or(Malformed("XBCH stream does not inflate to its stated size"))?; Ok(out) } +/// Inflates a zlib stream incrementally up to `expected` bytes, rejecting +/// truncated, corrupt, under-filled, or oversized streams without eagerly +/// allocating the full declared size up front. +fn inflate_zlib_exact(source: &[u8], expected: usize) -> Option<Vec<u8>> { + let mut state = zlib_rs::Inflate::new(true, 15); + let mut out = Vec::new(); + let (mut in_pos, mut out_pos) = (0usize, 0usize); + loop { + if out_pos == expected { + let mut extra = [0u8; 1]; + let status = state + .decompress( + &source[in_pos..], + &mut extra, + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + return (status == zlib_rs::Status::StreamEnd + && state.total_out() as usize == expected) + .then_some(out); + } + if out_pos == out.len() { + let next_len = if out.is_empty() { + expected.min(source.len().saturating_mul(4).max(4096)) + } else { + out.len().saturating_mul(2).min(expected) + }; + out.resize(next_len, 0); + } + let status = state + .decompress( + &source[in_pos..], + &mut out[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + match status { + zlib_rs::Status::StreamEnd => { + out.truncate(next_out); + return (next_out == expected).then_some(out); + } + zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => { + in_pos = next_in; + out_pos = next_out; + } + zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None, + } + } +} + fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> { if fssm.get(0..4) != Some(b"FSSM") { return Err(Malformed("native blob lacks FSSM magic")); @@ -516,36 +699,7 @@ fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> { user_data: e[16], slot: e[17], }) - .collect::<Vec<RootParam>>(); - // A parameter's SGPRs must exist: `user_sgpr` and the high half of a - // root descriptor are computed from these bytes ([`sgpr_span`]). - if layout.iter().any(|p| { - let (first, span) = sgpr_span(stage, p); - u64::from(first) + u64::from(span) > u64::from(SGPRS) - }) { - return Err(Malformed("root parameter outside the SGPRs")); - } - // A table or heap parameter is one 32-bit address. Resource tracking - // maps each SGPR it states to the parameter (`resource::param_of`), - // and the host fills every dword of a table with that address - // (`draw::user_value`; lowering reads a heap's as 0), so an SGPR past - // the first would silently read the address too. - if layout.iter().any(|p| { - matches!( - p.root, - RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap - ) && p.sgprs > 1 - }) { - return Err(Malformed("root address wider than one SGPR")); - } - // Resource tracking maps an SGPR to the first parameter covering it - // (`resource::param_of`), so a second parameter over the same SGPR - // would have its reads attributed to the first. The ranges of one - // table share its SGPR (and its address), so only different slots - // are refused. - if !params_apart(stage, &layout) { - return Err(Malformed("root parameters share an SGPR")); - } + .collect(); let used = table(RECORD_USED, RECORD_COUNTS + 4)? .as_chunks::<{ ENTRY_SIZE as usize }>() .0 @@ -566,40 +720,20 @@ fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> { user_data: e[17], slot: e[18], }) - .collect::<Vec<UsedResource>>(); - // The host binds a table read by its root slot (`draw::tables`), - // while lowering finds what a read is by the table address's SGPR - // (`used_kind`). A read naming no table parameter with both would be - // classified from one table and its descriptors bound from another, - // or from none. A root descriptor's read is likewise found by its - // SGPR (`handle`, which picks CBV or SRV from it) and bound by the - // parameter's slot, so it must name that parameter with both too. - let named = |u: &UsedResource| { - layout - .iter() - .any(|p| p.root == u.root && p.slot == u.slot && p.user_data == u.user_data) - }; - if used.iter().any(|u| u.root == RootType::Table && !named(u)) { - return Err(Malformed("used descriptor names no root table")); - } - if used - .iter() - .any(|u| u.root == RootType::Descriptor && !named(u)) - { - return Err(Malformed("used descriptor names no root descriptor")); - } - if !used_one_way(&used) { - return Err(Malformed("used descriptors read one descriptor two ways")); - } - if !tables_one_heap(&used) { - return Err(Malformed("root table mixes samplers and views")); - } + .collect(); // The record is in bounds, so its end is too. let stage_data = &payload[(start + RECORD_SIZE) as usize..]; let io = match stage { HwStage::Ps => ps_io(stage_data, code.len())?, - HwStage::Vs => vs_outputs_per_vertex(vs_inputs_fit(vs_io(stage_data)?)?)?, - HwStage::Cs => StageIo::Cs(compute_io(stage_data, &layout)?), + HwStage::Vs => vs_io(stage_data)?, + HwStage::Cs => StageIo::Cs(ComputeIo { + rsrc2: u32_at(stage_data, CS_RSRC2)?, + threads: [ + u32_at(stage_data, CS_THREADS)?, + u32_at(stage_data, CS_THREADS + 4)?, + u32_at(stage_data, CS_THREADS + 8)?, + ], + }), HwStage::Ms => ms_io(stage_data, u32_at(record, RECORD_LDS)?)?, _ => StageIo::None, }; @@ -616,130 +750,6 @@ fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> { Ok(out) } -/// A compute program's dispatch settings. `COMPUTE_PGM_RSRC2.LDS_SIZE` is a -/// 9-bit count of 512-byte granules, so it can state up to 255.5 KiB, which -/// lowering would declare as the group's shared memory; like a mesh group's, -/// a compute group's LDS can't exceed 64 KiB. -/// -/// The group ids and group info arrive in the SGPRs after the user SGPRs -/// (`ComputeIo::system_sgprs`), and raising labels them there. A root -/// parameter covering one of those SGPRs would make the same register both a -/// root parameter and a group id, so such a layout is refused. -fn compute_io(data: &[u8], layout: &[RootParam]) -> Result<ComputeIo, ShaderError> { - let cs = ComputeIo { - rsrc2: u32_at(data, CS_RSRC2)?, - threads: group_size(data)?, - }; - if cs.lds_bytes() > MAX_LDS_BYTES { - return Err(Malformed("implausible LDS size")); - } - let (ids, info) = cs.system_sgprs(); - // The layout was checked first, so `first + span` stays below `SGPRS`. - let mut system = ids.into_iter().chain([info]).flatten().map(u32::from); - if system.any(|s| { - layout.iter().any(|p| { - let (first, span) = sgpr_span(HwStage::Cs, p); - (first..first + span).contains(&s) - }) - }) { - return Err(Malformed("root parameter over a system SGPR")); - } - Ok(cs) -} - -/// The first SGPR of a root parameter and how many it takes. Resource -/// tracking reads a root descriptor's high half from the SGPR after its -/// first whatever the stated count, so a descriptor spans at least two. -fn sgpr_span(stage: HwStage, p: &RootParam) -> (u32, u32) { - let first = u32::from(p.user_data) + u32::from(stage.user_sgpr(0)); - let span = match p.root { - RootType::Descriptor => p.sgprs.max(2), - _ => p.sgprs.max(1), - }; - (first, span) -} - -/// Whether no SGPR holds two root parameters: each covers its stated -/// SGPRs (none for, say, a fixed sampler), a root descriptor also the high -/// half resource tracking reads after its first. Only the ranges of one -/// table (one slot, one table address SGPR) may share; a slot number alone -/// does not make two entries one parameter, as a table range and constants -/// stating the same slot would still be read as whichever comes first. -fn params_apart(stage: HwStage, layout: &[RootParam]) -> bool { - // The layout was checked first, so every covered SGPR is below `SGPRS`. - let mut owner = [None; SGPRS as usize]; - layout.iter().all(|p| { - let (first, _) = sgpr_span(stage, p); - let span = match p.root { - RootType::Descriptor => p.sgprs.max(2), - _ => p.sgprs, - }; - let key = (p.slot, p.root, first); - (first..first + span).all(|s| match owner[s as usize].replace(key) { - None => true, - Some(held) => held == key && p.root == RootType::Table, - }) - }) -} - -/// The descriptor a table or root-descriptor read names: its parameter and, -/// in a table, its offset. A root descriptor is one view, so all its reads -/// name the same one. -fn read_of(u: &UsedResource) -> Option<(RootType, u8, u8, u32)> { - match u.root { - RootType::Table => Some((u.root, u.slot, u.user_data, u.table_offset_dwords)), - RootType::Descriptor => Some((u.root, u.slot, u.user_data, 0)), - _ => None, - } -} - -/// Whether no descriptor is read as two kinds. Lowering classifies a read -/// by one entry (`used_kind`: a root descriptor's first, a table's last at -/// or below the offset) and picks CBV, SRV or UAV access from its kind, -/// while the host binds each entry by its own kind (`draw::readable`): a -/// second entry of another kind would bind the view one way and read it -/// another. -fn used_one_way(used: &[UsedResource]) -> bool { - used.iter().enumerate().all(|(k, a)| { - used[..k] - .iter() - .all(|b| read_of(a).is_none() || read_of(b) != read_of(a) || b.kind == a.kind) - }) -} - -/// Whether each root table holds samplers only or views only. D3D12 puts -/// samplers in their own heap, so one table can't hold both, and the host -/// makes a table with a constant buffer afresh in its view heap -/// (`draw::tables`), where a sampler has no place. -fn tables_one_heap(used: &[UsedResource]) -> bool { - let tables = || used.iter().filter(|u| u.root == RootType::Table); - let sampler = |u: &UsedResource| u.kind == ResourceType::Sampler; - tables().all(|a| { - tables().all(|b| (a.slot, a.user_data) != (b.slot, b.user_data) || sampler(a) == sampler(b)) - }) -} - -/// A compute program's thread-group size. Lowering multiplies the -/// components and writes them as the DXIL `numthreads`, so each must be one -/// that HLSL allows: a zero or oversized group is refused here rather than -/// overflowing that product (a debug panic) or emitting an invalid shader. -fn group_size(data: &[u8]) -> Result<[u32; 3], ShaderError> { - let mut threads = [0; 3]; - for (k, n) in threads.iter_mut().enumerate() { - *n = u32_at(data, CS_THREADS + 4 * k)?; - } - // Each component is checked first, so the product fits a u64. - if threads - .iter() - .zip(MAX_GROUP) - .any(|(&n, max)| n == 0 || n > max) - || threads.iter().map(|&n| u64::from(n)).product::<u64>() > MAX_GROUP_THREADS - { - return Err(Malformed("implausible thread-group size")); - } - Ok(threads) -} - /// The entries of `size` bytes from `at`, with their count at `count_at`. fn semantics(data: &[u8], at: usize, size: usize, count_at: usize) -> Result<&[u8], ShaderError> { let count = u32_at(data, count_at)?; @@ -765,38 +775,7 @@ fn ps_io(data: &[u8], code_len: usize) -> Result<StageIo, ShaderError> { pack2: e[7] & 0x10 != 0, row2: e[5], }) - .collect::<Vec<_>>(); - // Raising resolves `v_interp` of attribute n to the first input naming - // n, so a second input with the same attribute would be dropped. - if !distinct(inputs.iter().map(|i| i.attr)) { - return Err(Malformed("pixel inputs share an attribute")); - } - // Inputs packed into one signature row (disjoint channels) are fine, but - // lowering finds a row's 16-bit layout as the first fp16 input naming - // it: a second input on that row read as 32-bit, or packed differently, - // would be decoded with the first's layout. - let packing = |i: &PsInput| i.fp16.then_some((i.pack2, i.row2)); - if inputs.iter().enumerate().any(|(k, a)| { - inputs[..k] - .iter() - .any(|b| b.row == a.row && packing(b) != packing(a)) - }) { - return Err(Malformed("pixel inputs read a row two ways")); - } - // A packed input's halves past its own row's come from its second row - // (`row2`), which lowering reads as that row's signature element - // (`packed_half`). Another input naming that row, or a packed input of - // another row claiming it too, would read one element as two inputs. - let second = |i: &PsInput| (i.fp16 && i.pack2 && i.row2 != i.row).then_some(i.row2); - if inputs.iter().any(|a| { - second(a).is_some_and(|r2| { - inputs - .iter() - .any(|b| b.row == r2 || (b.row != a.row && second(b) == Some(r2))) - }) - }) { - return Err(Malformed("pixel inputs claim a packed row")); - } + .collect(); let size = u32_at(data, PS_PATCH_SIZE)? as usize; if size > PATCH_SLOT_DWORDS { return Err(Malformed("implausible export patch size")); @@ -811,15 +790,6 @@ fn ps_io(data: &[u8], code_len: usize) -> Result<StageIo, ShaderError> { if (offset as usize + size) * 4 > code_len { return Err(Malformed("export patch outside the code")); } - // `patched_code` writes the patches in MRT order: a later one over an - // earlier one's dwords would clobber that export with no error. - let (start, end) = (offset as usize, offset as usize + size); - if patches - .iter() - .any(|p: &ExportPatch| start < p.offset as usize + size && (p.offset as usize) < end) - { - return Err(Malformed("export patches overlap")); - } let full = at + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; let code = (0..size) .map(|i| u32_at(data, full + 4 * i)) @@ -838,19 +808,8 @@ fn ps_io(data: &[u8], code_len: usize) -> Result<StageIo, ShaderError> { }) } -fn vs_io(data: &[u8]) -> Result<StageIo, ShaderError> { - let inputs = semantics(data, VS_INPUTS, 5, VS_INPUT_COUNT)? - .as_chunks::<5>() - .0 - .iter() - .map(|e| VsInput { - usage: Usage::from_raw(e[0]), - row: e[1], - mask: e[2] & 0xf, - vgpr: e[3], - }) - .collect(); - let outputs = semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT)? +fn vs_outputs(data: &[u8]) -> Result<Vec<VsOutput>, ShaderError> { + Ok(semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT)? .as_chunks::<6>() .0 .iter() @@ -861,139 +820,38 @@ fn vs_io(data: &[u8]) -> Result<StageIo, ShaderError> { fp16: e[5] & 1 != 0, pack2: e[5] & 2 != 0, }) - .collect::<Vec<_>>(); - // Raising resolves `exp param<n>` to the first output whose parameter - // (bit 7, a mesh program's per-primitive flag, aside) is n, so a second - // output with the same parameter would be dropped. - if !distinct(outputs.iter().map(|o| o.param & 0x7F)) { - return Err(Malformed("vertex outputs share a parameter")); - } - // Raising turns each `exp param<n>` into a write of its output's - // signature row, and lowering keys 16-bit outputs by that row - // (`half_outputs`): two outputs naming one row would write the same - // element, the later export silently replacing the earlier. Per-vertex - // rows (`OSG1`) and per-primitive rows (`PSG1`) are separate signatures. - let rows = |primitive: bool| { - outputs - .iter() - .filter(move |o| (o.param & 0x80 != 0) == primitive) - .map(|o| o.row) - }; - if !distinct(rows(false)) || !distinct(rows(true)) { - return Err(Malformed("vertex outputs share a row")); - } - Ok(StageIo::Vs { inputs, outputs }) + .collect()) } -/// Whether no byte appears twice. -fn distinct(bytes: impl IntoIterator<Item = u8>) -> bool { - let mut seen = [false; 256]; - bytes - .into_iter() - .all(|b| !std::mem::replace(&mut seen[usize::from(b)], true)) -} - -/// The VGPRs a vertex program receives its vertex, primitive and instance -/// id in. -const VS_SYSTEM_VGPRS: [u32; 3] = [0, 2, 3]; - -/// Raising loads a vertex input's channel `c` from `v[vgpr + c]`, an 8-bit -/// register number: every enabled channel must land on a VGPR. -fn vs_inputs_fit(io: StageIo) -> Result<StageIo, ShaderError> { - if let StageIo::Vs { inputs, .. } = &io - && inputs.iter().any(|i| { - i.mask - .checked_ilog2() - .is_some_and(|last| u32::from(i.vgpr) + last > u32::from(u8::MAX)) - }) - { - return Err(Malformed("vertex input outside the VGPRs")); - } - // Raising also labels v0, v2 and v3 as the vertex, primitive and - // instance id (`io::raise`) and takes the first label a register has, so - // a channel loaded into one of them would silently read as that id. - if let StageIo::Vs { inputs, .. } = &io - && inputs.iter().any(|i| { - (0..4) - .filter(|c| i.mask >> c & 1 != 0) - .any(|c| VS_SYSTEM_VGPRS.contains(&(u32::from(i.vgpr) + c))) +fn vs_io(data: &[u8]) -> Result<StageIo, ShaderError> { + let inputs = semantics(data, VS_INPUTS, 5, VS_INPUT_COUNT)? + .as_chunks::<5>() + .0 + .iter() + .map(|e| VsInput { + usage: Usage::from_raw(e[0]), + row: e[1], + mask: e[2] & 0xf, + vgpr: e[3], }) - { - return Err(Malformed("vertex input over a system VGPR")); - } - // Two inputs loading one VGPR would leave it labeled as the first; the - // fetch would have overwritten it with the second, which raising drops. - if let StageIo::Vs { inputs, .. } = &io { - let mut taken = [false; 256]; - for i in inputs { - for c in (0..4).filter(|c| i.mask >> c & 1 != 0) { - // The first check keeps `vgpr + c` within v255. - let r = usize::from(i.vgpr) + c; - if std::mem::replace(&mut taken[r], true) { - return Err(Malformed("vertex inputs overlap")); - } - } - } - } - Ok(io) -} - -/// Bit 7 of an output's parameter marks a mesh program's per-primitive -/// output (a `PSG1` row). A vertex program has no primitive signature: such -/// an output's exports would be written to an element that doesn't exist -/// and silently dropped, and its row would escape the shared-row check. -fn vs_outputs_per_vertex(io: StageIo) -> Result<StageIo, ShaderError> { - if let StageIo::Vs { outputs, .. } = &io - && outputs.iter().any(|o| o.param & 0x80 != 0) - { - return Err(Malformed("vertex output marked per-primitive")); - } - Ok(io) + .collect(); + let outputs = vs_outputs(data)?; + Ok(StageIo::Vs { inputs, outputs }) } fn ms_io(data: &[u8], lds_bytes: u32) -> Result<StageIo, ShaderError> { - let StageIo::Vs { outputs, .. } = vs_io(data)? else { - unreachable!() - }; + let outputs = vs_outputs(data)?; let info = data .get(MS_INFO..MS_INFO + 8) .ok_or(Malformed("stage data out of bounds"))?; let half = |at: usize| u32::from(u16::from_le_bytes([info[at], info[at + 1]])); - // The group's lanes become the DXIL `numthreads` x and, for containers - // without the HLSL count, the stride of the group id: an empty group - // would emit `numthreads(0, 1, 1)` and give every group id 0. - // A group past 128 lanes is one no mesh shader can declare (the lanes - // are the HLSL group rounded up to waves, and 128 is a whole number of - // either), so it would emit a `numthreads` the validator rejects. - let threads = half(0); - if threads == 0 || threads > MAX_MESH_THREADS { - return Err(Malformed("implausible thread-group size")); - } - // Lowering writes the vertex and primitive limits and the topology as - // the DXIL mesh state and the PSV mesh info as they are (the limits as - // 16-bit values): past 256 outputs, or a topology neither lines (1) nor - // triangles (2), the emitted shader is one D3D12 refuses to create. - let (max_vertices, max_primitives) = (half(2), half(4)); - if max_vertices > MAX_MESH_OUTPUTS || max_primitives > MAX_MESH_OUTPUTS { - return Err(Malformed("implausible mesh output count")); - } - let topology = info[7]; - if !matches!(topology, 1 | 2) { - return Err(Malformed("unknown mesh topology")); - } - // Lowering declares the LDS as `lds_bytes.div_ceil(4)` dwords and states - // it again in bytes (`lds_dwords * 4`), a u32 product that overflows for - // sizes near `u32::MAX`; a group's LDS can't exceed 64 KiB anyway. - if lds_bytes > MAX_LDS_BYTES { - return Err(Malformed("implausible LDS size")); - } Ok(StageIo::Ms(MeshIo { outputs, clip_cntl: u32_at(data, MS_CLIP_CNTL)?, - threads, - max_vertices, - max_primitives, - topology, + threads: half(0), + max_vertices: half(2), + max_primitives: half(4), + topology: info[7], lds_bytes, })) } @@ -1059,20 +917,7 @@ mod tests { payload.extend_from_slice(&flags.to_le_bytes()); payload.resize(record as usize + RECORD_REGS, 0); payload.extend_from_slice(&(VGPRS | 31 << 20).to_le_bytes()); - let mut data = empty_stage_data(); - // numthreads(1, 1, 1): a compute or mesh group is never empty. - if stage == HwStage::Cs { - for k in 0..3 { - data[CS_THREADS + 4 * k..][..4].copy_from_slice(&1u32.to_le_bytes()); - } - } - // One lane drawing triangles: a mesh group is never empty and - // always names a topology. - if stage == HwStage::Ms { - data[MS_INFO..][..2].copy_from_slice(&1u16.to_le_bytes()); - data[MS_INFO + 7] = 2; - } - payload.extend_from_slice(&data); + payload.extend_from_slice(&empty_stage_data()); payload.extend_from_slice(code); } let mut out = b"FSSM".to_vec(); @@ -1083,12 +928,15 @@ mod tests { } fn xbch(unpacked: &[u8]) -> Vec<u8> { - let stream = miniz_oxide::deflate::compress_to_vec_zlib(unpacked, 6); + let mut buf = vec![0u8; zlib_rs::compress_bound(unpacked.len())]; + let (stream, rc) = + zlib_rs::compress_slice(&mut buf, unpacked, zlib_rs::DeflateConfig::new(6)); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); let mut out = b"XBCH".to_vec(); out.extend_from_slice(&XBCH_VERSION.to_le_bytes()); out.extend_from_slice(&(stream.len() as u64).to_le_bytes()); out.extend_from_slice(&(unpacked.len() as u64).to_le_bytes()); - out.extend_from_slice(&stream); + out.extend_from_slice(stream); out } @@ -1149,6 +997,17 @@ mod tests { ); } + #[test] + fn finds_programs_stored_without_xbch() { + let blob = fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)]); + let raw = native_programs(&part(&[(0x12, &[0; 16]), (KIND_NATIVE_RAW, &blob)])).unwrap(); + let packed = native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap(); + assert_eq!(raw.len(), 2); + assert_eq!(raw, packed); + // A damaged raw blob is an error, not an empty container. + assert!(native_programs(&part(&[(KIND_NATIVE_RAW, &blob[..blob.len() - 1])])).is_err()); + } + #[test] fn reads_root_tables() { let mut blob = fssm(&[(HwStage::Ps, &PS_CODE)]); @@ -1195,110 +1054,6 @@ mod tests { }] ); - // Parameters must sit in SGPRs the program can address: s9 plus 97 - // dwords ends at s105, one more is past it, and so is a user-data - // byte past the SGPR file. (Constants: a table takes one SGPR, and - // the read is then not a table's.) - let entry = FSSM_HEADER + tables as usize; - let layout = |blob: &[u8]| native_programs(&part(&[(KIND_NATIVE, &xbch(blob))])); - let mut wide = blob.clone(); - wide[entry..entry + 4].copy_from_slice(&0u32.to_le_bytes()); - wide[entry + ENTRY_SIZE as usize + 1] = 0; - wide[entry + 8..entry + 12].copy_from_slice(&97u32.to_le_bytes()); - assert_eq!(layout(&wide).unwrap()[0].layout[0].sgprs, 97); - wide[entry + 8..entry + 12].copy_from_slice(&98u32.to_le_bytes()); - assert_eq!( - refused_blob(&xbch(&wide)), - "root parameter outside the SGPRs" - ); - let mut far = blob.clone(); - far[entry + 16] = 0xFF; - assert_eq!( - refused_blob(&xbch(&far)), - "root parameter outside the SGPRs" - ); - - // A root descriptor's high half is the SGPR after its first, even - // when the record states fewer than two: one in s104 fits (s104, - // s105), one in s105 would take VCC_LO as its high half. - for sgprs in [0u32, 1, 2] { - let mut desc = blob.clone(); - desc[entry..entry + 4].copy_from_slice(&1u32.to_le_bytes()); - // The SRV read through it is then a root descriptor's. - desc[entry + ENTRY_SIZE as usize + 1] = 1; - desc[entry + 8..entry + 12].copy_from_slice(&sgprs.to_le_bytes()); - desc[entry + 16] = 104; - desc[entry + ENTRY_SIZE as usize + 17] = 104; - assert_eq!( - layout(&desc).unwrap()[0].layout[0].root, - RootType::Descriptor - ); - desc[entry + 16] = 105; - desc[entry + ENTRY_SIZE as usize + 17] = 105; - assert_eq!( - refused_blob(&xbch(&desc)), - "root parameter outside the SGPRs" - ); - // Other kinds of parameter still take one SGPR there. - desc[entry..entry + 4].copy_from_slice(&3u32.to_le_bytes()); - desc[entry + ENTRY_SIZE as usize + 1] = 3; - if sgprs <= 1 { - assert!(layout(&desc).is_ok()); - } - } - - // The SRV is read through the table in s9, root slot 1: a read - // naming another slot or SGPR names no table the layout has. - let used = entry + ENTRY_SIZE as usize; - for (at, byte) in [(17, 8u8), (17, 10), (18, 0), (18, 2)] { - let mut stray = blob.clone(); - stray[used + at] = byte; - assert_eq!( - refused_blob(&xbch(&stray)), - "used descriptor names no root table", - "byte {at} = {byte}" - ); - } - // Nor may it name a parameter of another kind there. - let mut constants = blob.clone(); - constants[entry..entry + 4].copy_from_slice(&0u32.to_le_bytes()); - assert_eq!( - refused_blob(&xbch(&constants)), - "used descriptor names no root table" - ); - // A read of another kind of root is not a table read. - let mut desc = constants.clone(); - desc[used + 1] = 0; - assert!(layout(&desc).is_ok()); - - // A root descriptor read must name the root descriptor in its SGPR - // and slot: not another SGPR or slot, nor a table or constants there. - let mut root = blob.clone(); - root[entry..entry + 4].copy_from_slice(&1u32.to_le_bytes()); - root[entry + 8..entry + 12].copy_from_slice(&2u32.to_le_bytes()); - root[used + 1] = 1; - assert!(layout(&root).is_ok()); - for (at, byte) in [(17, 8u8), (17, 10), (18, 0), (18, 2)] { - let mut stray = root.clone(); - stray[used + at] = byte; - assert_eq!( - refused_blob(&xbch(&stray)), - "used descriptor names no root descriptor", - "byte {at} = {byte}" - ); - } - for kind in [0u32, 3] { - let mut other = root.clone(); - other[entry..entry + 4].copy_from_slice(&kind.to_le_bytes()); - // A table takes one SGPR. - other[entry + 8..entry + 12].copy_from_slice(&1u32.to_le_bytes()); - assert_eq!( - refused_blob(&xbch(&other)), - "used descriptor names no root descriptor", - "parameter kind {kind}" - ); - } - blob[record + RECORD_COUNTS] = 9; assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err()); } @@ -1396,6 +1151,16 @@ mod tests { ); } + #[test] + fn mesh_stage_io_ignores_unused_vs_input_count() { + let mut blob = fssm(&[(HwStage::Ms, &VS_CODE)]); + let e = stage_data_at(&blob, HwStage::Ms); + // Mesh stage data has no vertex inputs; E+0xc4 is unused by MS. + blob[e + VS_INPUT_COUNT..][..4].copy_from_slice(&u32::MAX.to_le_bytes()); + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + assert!(matches!(p.io, StageIo::Ms(_))); + } + #[test] fn compute_dispatch_settings() { // 5 user SGPRs, group id x and y, thread ids in v0-v1, 1 KiB LDS. @@ -1415,64 +1180,6 @@ mod tests { assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (3, 0)); } - #[test] - fn compute_root_params_stay_off_system_sgprs() { - // 4 user SGPRs, then group id x in s4, y in s5 and the group info - // in s6. - let rsrc2: u32 = 4 << 1 | 1 << 7 | 1 << 8 | 1 << 10; - let program = |rsrc2: u32, root: u32, sgprs: u32, user_data: u8| { - let mut blob = fssm(&[(HwStage::Cs, &VS_CODE)]); - let record = - FSSM_HEADER + u64_at(&blob, FSSM_HEADER + slot(HwStage::Cs)).unwrap() as usize; - let e = record + RECORD_SIZE as usize; - blob[e + CS_RSRC2..][..4].copy_from_slice(&rsrc2.to_le_bytes()); - let table = (blob.len() - FSSM_HEADER) as u64; - for v in [root, 0, sgprs, 0] { - blob.extend_from_slice(&v.to_le_bytes()); - } - blob.extend_from_slice(&[user_data, 0, 0, 0]); - let payload = (blob.len() - FSSM_HEADER) as u64; - blob[8..16].copy_from_slice(&payload.to_le_bytes()); - blob[record + RECORD_LAYOUT..][..8].copy_from_slice(&table.to_le_bytes()); - blob[record + RECORD_COUNTS..][..8].copy_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0]); - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - let (constants, descriptor, table) = (0, 1, 3); - // s0-s3 are the user SGPRs; a table in s3 takes one of them. - let p = program(rsrc2, constants, 4, 0).unwrap(); - assert_eq!(p[0].layout[0].sgprs, 4); - assert!(program(rsrc2, table, 1, 3).is_ok()); - // Past the system SGPRs nothing collides. - assert!(program(rsrc2, constants, 1, 7).is_ok()); - // With no group ids or info enabled, s4 is free. - assert!(program(4 << 1, constants, 1, 4).is_ok()); - for (root, sgprs, user_data, what) in [ - (constants, 5, 0, "five dwords from s0 reach group id x"), - (descriptor, 1, 3, "a descriptor's high half in s4"), - (constants, 1, 5, "group id y"), - (table, 1, 6, "the group info"), - ] { - assert!( - matches!( - program(rsrc2, root, sgprs, user_data), - Err(Malformed("root parameter over a system SGPR")) - ), - "{what}" - ); - } - } - - #[test] - fn thread_id_count_three_is_still_three_components() { - // TIDIG_COMP_CNT (bits 11-12) of 3: still x, y and z in v0-v2, - // never a fourth component in v3. - let cs = ComputeIo { - rsrc2: 3 << 11, - threads: [4, 4, 4], - }; - assert_eq!(cs.thread_id_vgprs(), 3); - } - #[test] fn initialized_sgprs_covers_user_system_and_scratch() { // 5 user SGPRs, group ids x and y (s5, s6), no scratch: s0..=s6. @@ -1537,725 +1244,31 @@ mod tests { assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&bad_record))])).is_err()); } - /// Why `data` (a `DXIL` part) is refused. - fn refused(data: &[u8]) -> &'static str { - match native_programs(data) { - Err(Malformed(why)) => why, - other => panic!("expected a malformed blob, got {other:?}"), - } - } - - /// Why a part holding `blob` as its only native entry is refused. - fn refused_blob(blob: &[u8]) -> &'static str { - refused(&part(&[(KIND_NATIVE, blob)])) - } - - #[test] - fn names_each_xdat_refusal() { - let native = xbch(&fssm(&[(HwStage::Vs, &VS_CODE)])); - let mut data = part(&[(KIND_NATIVE, &native)]); - data[XDAT_OFFSET + 4..][..4].copy_from_slice(&(MAX_XDAT_ENTRIES as u32 + 1).to_le_bytes()); - assert_eq!(refused(&data), "implausible XDAT entry count"); - - // A native entry whose size runs past the part. - let mut data = part(&[(KIND_NATIVE, &native)]); - let size = XDAT_OFFSET + 12 + 8; - data[size..][..4].copy_from_slice(&u32::MAX.to_le_bytes()); - assert_eq!(refused(&data), "XDAT entry out of bounds"); - - // Entries of other kinds are never read, so their bounds do not matter. - let mut data = part(&[(0x0e, b"tbl."), (KIND_NATIVE, &native)]); - data[size..][..4].copy_from_slice(&u32::MAX.to_le_bytes()); - assert_eq!(native_programs(&data).unwrap().len(), 1); - } - - #[test] - fn names_each_xbch_refusal() { - let good = xbch(&fssm(&[(HwStage::Vs, &VS_CODE)])); - let with = |at: usize, value: &[u8]| { - let mut blob = good.clone(); - blob[at..at + value.len()].copy_from_slice(value); - blob - }; - assert_eq!( - refused_blob(&with(0, b"XBCX")), - "native blob lacks XBCH magic" - ); - assert_eq!( - refused_blob(&with(4, &(XBCH_VERSION + 1).to_le_bytes())), - "unknown XBCH version" - ); - assert_eq!( - refused_blob(&with(16, &(MAX_UNPACKED + 1).to_le_bytes())), - "implausible XBCH unpacked size" - ); - let packed = u64_at(&good, 8).unwrap(); - assert_eq!( - refused_blob(&with(8, &(packed + 1).to_le_bytes())), - "XBCH stream out of bounds" - ); - // A stated size either side of what the stream holds. - let unpacked = u64_at(&good, 16).unwrap(); - for stated in [unpacked - 1, unpacked + 1] { - assert_eq!( - refused_blob(&with(16, &stated.to_le_bytes())), - "XBCH stream does not inflate to its stated size" - ); - } - // A header with no stream after it. - assert_eq!(refused_blob(&good[..20]), "truncated"); - } - - #[test] - fn names_each_fssm_header_refusal() { - let good = fssm(&[(HwStage::Vs, &VS_CODE)]); - let with = |at: usize, value: &[u8]| { - let mut blob = good.clone(); - blob[at..at + value.len()].copy_from_slice(value); - xbch(&blob) - }; - assert_eq!( - refused_blob(&with(0, b"FSSX")), - "native blob lacks FSSM magic" - ); - assert_eq!( - refused_blob(&with(4, &(FSSM_VERSION + 1).to_le_bytes())), - "unknown FSSM version" - ); - let payload = (good.len() - FSSM_HEADER) as u64; - assert_eq!( - refused_blob(&with(8, &(payload - 1).to_le_bytes())), - "FSSM payload size disagrees" - ); - assert_eq!( - refused_blob(&with(FSSM_HEADER, &(GRAPHICS_SLOT_COUNT + 1).to_le_bytes())), - "unexpected FSSM slot count" - ); - assert_eq!( - refused_blob(&with( - FSSM_HEADER + slot(HwStage::Vs), - &payload.to_le_bytes() - )), - "FSSM record out of bounds" - ); - } - - #[test] - fn names_each_record_refusal() { - let good = fssm(&[(HwStage::Vs, &VS_CODE)]); - let record = stage_data_at(&good, HwStage::Vs) - RECORD_SIZE as usize; - let with = |at: usize, value: &[u8]| { - let mut blob = good.clone(); - blob[at..at + value.len()].copy_from_slice(value); - xbch(&blob) - }; - // One byte more code than the payload holds. - assert_eq!( - refused_blob(&with(record + 8, &(VS_CODE.len() as u64 + 1).to_le_bytes())), - "native code out of bounds" - ); - assert_eq!( - refused_blob(&with(record + RECORD_REGS, &257u32.to_le_bytes())), - "implausible VGPR count" - ); - // 256 is the most a program can have. - let blob = with(record + RECORD_REGS, &256u32.to_le_bytes()); - assert_eq!( - native_programs(&part(&[(KIND_NATIVE, &blob)])).unwrap()[0].vgprs, - 256 - ); - // One root parameter, at an offset past the payload. - let mut blob = good.clone(); - blob[record + RECORD_LAYOUT..][..8].copy_from_slice(&u64::MAX.to_le_bytes()); - blob[record + RECORD_COUNTS..][..4].copy_from_slice(&1u32.to_le_bytes()); - assert_eq!(refused_blob(&xbch(&blob)), "FSSM root table out of bounds"); - } - #[test] - fn names_each_stage_data_refusal() { - let vs = fssm(&[(HwStage::Vs, &VS_CODE)]); - let e = stage_data_at(&vs, HwStage::Vs); - for count_at in [VS_INPUT_COUNT, VS_OUTPUT_COUNT] { - let mut blob = vs.clone(); - blob[e + count_at..][..4].copy_from_slice(&(MAX_SEMANTICS + 1).to_le_bytes()); - assert_eq!(refused_blob(&xbch(&blob)), "implausible semantic count"); - } - // One input in v252 or v253: x-w of v252 end at v255 and fit; from - // v253, w would be v256. - let input = |vgpr: u8, mask: u8| { - let mut blob = vs.clone(); - blob[e + VS_INPUT_COUNT..][..4].copy_from_slice(&1u32.to_le_bytes()); - blob[e + VS_INPUTS..][..5].copy_from_slice(&[0, 0, mask, vgpr, 0]); - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - assert!(input(252, 0xf).is_ok()); - assert!(input(255, 0x1).is_ok()); - assert!(input(255, 0).is_ok(), "no channel is loaded"); - for (vgpr, mask) in [(253, 0xf), (255, 0x2)] { - assert!( - matches!( - input(vgpr, mask), - Err(Malformed("vertex input outside the VGPRs")) - ), - "v{vgpr} mask {mask:#x}" - ); - } - // v1 and v4 up hold no id: x in v1 and x-w from v4 load. Any channel - // on v0, v2 or v3 is refused, including y and z of an input in v1. - assert!(input(1, 0x1).is_ok()); - assert!(input(4, 0xf).is_ok()); - assert!(input(0, 0).is_ok(), "no channel is loaded"); - for (vgpr, mask) in [(0, 0x1), (1, 0x2), (2, 0x1), (3, 0x1), (1, 0x4)] { - assert!( - matches!( - input(vgpr, mask), - Err(Malformed("vertex input over a system VGPR")) - ), - "v{vgpr} mask {mask:#x}" - ); - } - // Two inputs: x-w in v4 and the second at `vgpr` with `mask`. - let inputs = |vgpr: u8, mask: u8| { - let mut blob = vs.clone(); - blob[e + VS_INPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes()); - blob[e + VS_INPUTS..][..10].copy_from_slice(&[0, 0, 0xf, 4, 0, 0, 1, mask, vgpr, 0]); - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - assert!(inputs(8, 0xf).is_ok()); - assert!(inputs(5, 0).is_ok(), "no channel is loaded"); - // x in v1 sits below the first input; any channel on v4-v7 overlaps - // it, including w of an input in v1. - assert!(inputs(1, 0x1).is_ok()); - for (vgpr, mask) in [(4, 0xf), (7, 0x1), (6, 0x2), (1, 0x8), (5, 0x4)] { - assert!( - matches!(inputs(vgpr, mask), Err(Malformed("vertex inputs overlap"))), - "v{vgpr} mask {mask:#x}" - ); - } - - let ps = fssm(&[(HwStage::Ps, &PS_CODE)]); - let e = stage_data_at(&ps, HwStage::Ps); - let mut blob = ps.clone(); - blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&(MAX_SEMANTICS + 1).to_le_bytes()); - assert_eq!(refused_blob(&xbch(&blob)), "implausible semantic count"); - let mut blob = ps.clone(); - let size = PATCH_SLOT_DWORDS as u32 + 1; - blob[e + PS_PATCH_SIZE..][..4].copy_from_slice(&size.to_le_bytes()); - assert_eq!(refused_blob(&xbch(&blob)), "implausible export patch size"); - // A one-dword patch at the code's last dword fits; one past it does not. - let mut blob = ps.clone(); - blob[e + PS_PATCH_SIZE..][..4].copy_from_slice(&1u32.to_le_bytes()); - let last = (PS_CODE.len() / 4) as u32; - blob[e + PS_PATCHES..][..4].copy_from_slice(&(last - 1).to_le_bytes()); - assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_ok()); - blob[e + PS_PATCHES..][..4].copy_from_slice(&last.to_le_bytes()); - assert_eq!(refused_blob(&xbch(&blob)), "export patch outside the code"); - // Two-dword patches for MRT0 and MRT1: adjacent fits, sharing a - // dword does not; with no dwords to patch, nothing can overlap. - let code: Vec<u8> = [0xBF80_0000u32; 4] // s_nop - .iter() - .flat_map(|w| w.to_le_bytes()) - .collect(); - let ps4 = fssm(&[(HwStage::Ps, &code)]); - let patches = |size: u32, offsets: [u32; 2]| { - let mut blob = ps4.clone(); - blob[e + PS_PATCH_SIZE..][..4].copy_from_slice(&size.to_le_bytes()); - for (mrt, offset) in offsets.into_iter().enumerate() { - let at = e + PS_PATCHES + mrt * PATCH_BYTES; - blob[at..][..4].copy_from_slice(&offset.to_le_bytes()); - } - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - assert!(patches(2, [0, 2]).is_ok()); - assert!(patches(2, [2, 0]).is_ok()); - assert!(patches(0, [1, 1]).is_ok()); - for offsets in [[0, 1], [1, 0], [1, 1]] { - assert!( - matches!( - patches(2, offsets), - Err(Malformed("export patches overlap")) - ), - "{offsets:?}" - ); - } - - // numthreads at each limit fits; past one, or a zero component, does - // not. 65536 x 65536 would overflow lowering's u32 thread count. - let cs = fssm(&[(HwStage::Cs, &VS_CODE)]); - let e = stage_data_at(&cs, HwStage::Cs); - let group = |threads: [u32; 3]| { - let mut blob = cs.clone(); - for (k, n) in threads.into_iter().enumerate() { - blob[e + CS_THREADS + 4 * k..][..4].copy_from_slice(&n.to_le_bytes()); - } - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - for fits in [[1024, 1, 1], [1, 1024, 1], [1, 16, 64], [32, 32, 1]] { - let p = group(fits).unwrap(); - assert!( - matches!(p[0].io, StageIo::Cs(ComputeIo { threads, .. }) if threads == fits), - "{fits:?}" - ); - } - for bad in [ - [0, 1, 1], - [1, 1, 0], - [1025, 1, 1], - [1, 1, 65], - [64, 32, 1], - [65536, 65536, 1], - [u32::MAX, u32::MAX, u32::MAX], - ] { - assert!( - matches!(group(bad), Err(Malformed("implausible thread-group size"))), - "{bad:?}" - ); - } - - // A compute group's LDS (512-byte granules in RSRC2 bits 15-23): - // 128 granules is 64 KiB and fits; one more, or the field's maximum - // of 511, does not. - let cs_lds = |granules: u32| { - let mut blob = cs.clone(); - blob[e + CS_RSRC2..][..4].copy_from_slice(&(granules << 15).to_le_bytes()); - xbch(&blob) - }; - let p = native_programs(&part(&[(KIND_NATIVE, &cs_lds(128))])).unwrap(); - assert!(matches!(p[0].io, StageIo::Cs(c) if c.lds_bytes() == MAX_LDS_BYTES)); - for bad in [129, 0x1FF] { - assert_eq!(refused_blob(&cs_lds(bad)), "implausible LDS size", "{bad}"); - } - - // A mesh group of one lane fits; an empty one does not. - let ms = fssm(&[(HwStage::Ms, &VS_CODE)]); - let e = stage_data_at(&ms, HwStage::Ms); - let p = native_programs(&part(&[(KIND_NATIVE, &xbch(&ms))])).unwrap(); - assert!(matches!(&p[0].io, StageIo::Ms(m) if m.threads == 1)); - let mut blob = ms.clone(); - blob[e + MS_INFO..][..2].copy_from_slice(&0u16.to_le_bytes()); - assert_eq!(refused_blob(&xbch(&blob)), "implausible thread-group size"); - - // Mesh limits: 128 lanes and 256 vertices and primitives fit, with - // lines or triangles; a lane, an output past them, or another - // topology does not. - let info = |bytes: [u8; 8]| { - let mut blob = ms.clone(); - blob[e + MS_INFO..][..8].copy_from_slice(&bytes); - xbch(&blob) - }; - for topology in [1, 2] { - let p = native_programs(&part(&[( - KIND_NATIVE, - &info([128, 0, 0, 1, 0, 1, 0, topology]), - )])) - .unwrap(); - assert!(matches!( - &p[0].io, - StageIo::Ms(m) if (m.threads, m.max_vertices, m.max_primitives, m.topology) - == (128, 256, 256, topology) - )); - } - assert_eq!( - refused_blob(&info([129, 0, 1, 0, 1, 0, 0, 2])), - "implausible thread-group size" - ); - assert_eq!( - refused_blob(&info([0xff, 0xff, 1, 0, 1, 0, 0, 2])), - "implausible thread-group size" - ); - for bad in [ - [1, 0, 1, 1, 1, 0, 0, 2], - [1, 0, 1, 0, 1, 1, 0, 2], - [1, 0, 0xff, 0xff, 1, 0, 0, 2], - ] { - assert_eq!( - refused_blob(&info(bad)), - "implausible mesh output count", - "{bad:?}" - ); - } - for topology in [0, 3, 0xff] { - assert_eq!( - refused_blob(&info([1, 0, 1, 0, 1, 0, 0, topology])), - "unknown mesh topology", - "{topology}" - ); - } - - // A mesh group's LDS: 64 KiB fits; a byte more, or u32::MAX, does not. - let lds = |bytes: u32| { - let mut blob = ms.clone(); - let record = e - RECORD_SIZE as usize; - blob[record + RECORD_LDS..][..4].copy_from_slice(&bytes.to_le_bytes()); - xbch(&blob) - }; - let p = native_programs(&part(&[(KIND_NATIVE, &lds(MAX_LDS_BYTES))])).unwrap(); - assert!(matches!(&p[0].io, StageIo::Ms(m) if m.lds_bytes == 64 << 10)); - for bad in [MAX_LDS_BYTES + 1, u32::MAX] { - assert_eq!(refused_blob(&lds(bad)), "implausible LDS size", "{bad}"); - } - } - - #[test] - fn refuses_outputs_sharing_a_parameter_and_inputs_sharing_an_attribute() { - // Two outputs: param0 and `param`. Bit 7 (per-primitive) does not - // make a separate index: `exp param<n>` matches n either way. - for stage in [HwStage::Vs, HwStage::Ms] { - let base = fssm(&[(stage, &VS_CODE)]); - let e = stage_data_at(&base, stage); - let outputs = |param: u8| { - let mut blob = base.clone(); - blob[e + VS_OUTPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes()); - blob[e + VS_OUTPUTS..][..12] - .copy_from_slice(&[6, 0, 0, 0, 0, 0, 6, 1, param, 1, 0, 0]); - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - assert!(outputs(1).is_ok(), "{stage:?}"); - assert!(outputs(31).is_ok(), "{stage:?}"); - for param in [0, 0x80] { - assert!( - matches!( - outputs(param), - Err(Malformed("vertex outputs share a parameter")) - ), - "{stage:?} param {param:#x}" - ); - } - } - - // Two inputs: attr0 and `attr`. - let ps = fssm(&[(HwStage::Ps, &PS_CODE)]); - let e = stage_data_at(&ps, HwStage::Ps); - let inputs = |attr: u8| { - let mut blob = ps.clone(); - blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes()); - blob[e + PS_INPUTS..][..16] - .copy_from_slice(&[6, 0, 0xf, 0, 0, 0, 0, 0, 6, 1, 0xf, attr, 0, 0, 1, 0]); - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - assert!(inputs(1).is_ok()); - assert!(matches!( - inputs(0), - Err(Malformed("pixel inputs share an attribute")) - )); - } - - #[test] - fn refuses_pixel_inputs_reading_a_row_two_ways() { - // Two inputs, attr0 and attr1, with these (row, row2, flags): flag - // bit 3 is fp16, bit 4 two values per dword. - let ps = fssm(&[(HwStage::Ps, &PS_CODE)]); - let e = stage_data_at(&ps, HwStage::Ps); - let inputs = |a: (u8, u8, u8), b: (u8, u8, u8)| { - let mut blob = ps.clone(); - blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes()); - blob[e + PS_INPUTS..][..16].copy_from_slice(&[ - 6, a.0, 0x3, 0, 0, a.1, 0, a.2, 6, b.0, 0xc, 1, 0, b.1, 1, b.2, - ]); - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - let (fp16, pack2) = (0x8, 0x18); - // Different rows may differ; one row packed the same way (or 32-bit - // in both, or a 32-bit input's unused row2 differing) is fine. - for (a, b) in [ - ((0, 0, 0), (1, 1, fp16)), - ((0, 0, 0), (0, 0, 0)), - ((0, 0, 0), (0, 5, 0)), - ((2, 2, fp16), (2, 2, fp16)), - ((2, 3, pack2), (2, 3, pack2)), - ((0, 0, 0x1), (0, 0, 0x1)), - ] { - assert!(inputs(a, b).is_ok(), "{a:?} {b:?}"); - } - for (a, b, what) in [ - ((0, 0, 0), (0, 0, fp16), "32-bit then fp16"), - ((0, 0, fp16), (0, 0, 0), "fp16 then 32-bit"), - ((2, 2, fp16), (2, 2, pack2), "one packed, one not"), - ((2, 3, pack2), (2, 4, pack2), "different second rows"), - ] { - assert!( - matches!( - inputs(a, b), - Err(Malformed("pixel inputs read a row two ways")) - ), - "{what}" - ); - } - } - - #[test] - fn refuses_pixel_inputs_claiming_a_packed_row() { - // Two inputs, attr0 and attr1, with these (row, row2, flags), as in - // `refuses_pixel_inputs_reading_a_row_two_ways`. - let ps = fssm(&[(HwStage::Ps, &PS_CODE)]); - let e = stage_data_at(&ps, HwStage::Ps); - let inputs = |a: (u8, u8, u8), b: (u8, u8, u8)| { - let mut blob = ps.clone(); - blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes()); - blob[e + PS_INPUTS..][..16].copy_from_slice(&[ - 6, a.0, 0x3, 0, 0, a.1, 0, a.2, 6, b.0, 0xc, 1, 0, b.1, 1, b.2, - ]); - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - let (fp16, pack2) = (0x8, 0x18); - // A second row no input names; one row's inputs sharing theirs; a - // packed input with no second row; an unpacked input's unused row2. - for (a, b) in [ - ((2, 3, pack2), (4, 5, pack2)), - ((2, 3, pack2), (2, 3, pack2)), - ((2, 2, pack2), (3, 3, fp16)), - ((2, 3, fp16), (3, 3, fp16)), - ((2, 3, 0), (3, 3, 0)), - ] { - assert!(inputs(a, b).is_ok(), "{a:?} {b:?}"); - } - for (a, b, what) in [ - ((2, 3, pack2), (3, 3, 0), "32-bit input on the second row"), - ((2, 3, pack2), (3, 3, fp16), "fp16 input on the second row"), - ((3, 3, fp16), (2, 3, pack2), "named before it is claimed"), - ((2, 4, pack2), (3, 4, pack2), "two rows claiming one"), - ((2, 3, pack2), (3, 2, pack2), "each claiming the other"), - ] { - assert!( - matches!( - inputs(a, b), - Err(Malformed("pixel inputs claim a packed row")) - ), - "{what}" - ); - } - } - - #[test] - fn refuses_outputs_sharing_a_row() { - // Two outputs: param0 in row 0, param1 (or per-primitive param1) in - // `row`. - for stage in [HwStage::Vs, HwStage::Ms] { - let base = fssm(&[(stage, &VS_CODE)]); - let e = stage_data_at(&base, stage); - let outputs = |param: u8, row: u8| { - let mut blob = base.clone(); - blob[e + VS_OUTPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes()); - blob[e + VS_OUTPUTS..][..12] - .copy_from_slice(&[6, 0, 0, 0, 0, 0, 6, row, param, row, 0, 0]); - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - assert!(outputs(1, 1).is_ok(), "{stage:?}"); - // A per-primitive output's row is in the primitive signature, so - // row 0 there is not the vertex output's row 0. Only a mesh - // program has that signature. - if stage == HwStage::Ms { - assert!(outputs(0x81, 0).is_ok()); - } else { - for (param, row) in [(0x81, 0), (0x81, 1), (0xFF, 7)] { - assert!( - matches!( - outputs(param, row), - Err(Malformed("vertex output marked per-primitive")) - ), - "{param:#x} in row {row}" - ); - } - } - assert!( - matches!(outputs(1, 0), Err(Malformed("vertex outputs share a row"))), - "{stage:?}" - ); - } - // Two per-primitive outputs in one row clash too. - let base = fssm(&[(HwStage::Ms, &VS_CODE)]); - let e = stage_data_at(&base, HwStage::Ms); - let mut blob = base.clone(); - blob[e + VS_OUTPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes()); - blob[e + VS_OUTPUTS..][..12].copy_from_slice(&[6, 2, 0x80, 2, 0, 0, 6, 2, 0x81, 2, 0, 0]); - assert!(matches!( - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])), - Err(Malformed("vertex outputs share a row")) - )); - } - - #[test] - fn refuses_root_parameters_sharing_an_sgpr() { - // A pixel program with these (root type, SGPRs, user data, slot) - // parameters. - let program = |params: &[(u32, u32, u8, u8)]| { - let mut blob = fssm(&[(HwStage::Ps, &PS_CODE)]); - let record = - FSSM_HEADER + u64_at(&blob, FSSM_HEADER + slot(HwStage::Ps)).unwrap() as usize; - let table = (blob.len() - FSSM_HEADER) as u64; - for &(root, sgprs, user_data, slot) in params { - for v in [root, 0, sgprs, 0] { - blob.extend_from_slice(&v.to_le_bytes()); - } - blob.extend_from_slice(&[user_data, slot, 0, 0]); - } - let payload = (blob.len() - FSSM_HEADER) as u64; - blob[8..16].copy_from_slice(&payload.to_le_bytes()); - blob[record + RECORD_LAYOUT..][..8].copy_from_slice(&table.to_le_bytes()); - let count = params.len() as u64; - blob[record + RECORD_COUNTS..][..8].copy_from_slice(&count.to_le_bytes()); - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - }; - let (constants, descriptor, table, sampler) = (0, 1, 3, 4); - // Side by side, two ranges of one table, and a fixed sampler (no - // SGPRs) at a taken user-data dword are all fine. - assert!(program(&[(constants, 2, 0, 0), (descriptor, 2, 2, 1)]).is_ok()); - assert!(program(&[(table, 1, 4, 2), (table, 1, 4, 2)]).is_ok()); - assert!(program(&[(table, 1, 4, 2), (table, 1, 4, 2), (table, 1, 4, 2)]).is_ok()); - assert!(program(&[(constants, 2, 0, 0), (sampler, 0, 0, 3)]).is_ok()); - for (params, what) in [ - ( - [(constants, 2, 0, 0), (table, 1, 1, 1)], - "a table in the constants' second dword", - ), - ( - [(table, 1, 3, 0), (table, 1, 3, 1)], - "two tables in one SGPR", - ), - ( - [(descriptor, 1, 0, 0), (constants, 1, 1, 1)], - "constants in a descriptor's high half", - ), - ( - [(table, 1, 3, 2), (constants, 1, 3, 2)], - "constants in a table's SGPR stating its slot", - ), - ( - [(constants, 2, 0, 0), (constants, 2, 1, 0)], - "one slot's constants overlapping themselves", - ), - ( - [(constants, 1, 5, 4), (constants, 1, 5, 4)], - "constants listed twice", - ), - ( - [(descriptor, 2, 0, 1), (descriptor, 2, 0, 1)], - "a root descriptor listed twice", - ), - ] { - assert_eq!( - match program(¶ms) { - Err(Malformed(why)) => why, - other => panic!("{what}: expected a refusal, got {other:?}"), - }, - "root parameters share an SGPR", - "{what}" - ); - } - - // A table or heap is one 32-bit address: it may state one SGPR (or - // none, as a further range of a table), never two. - let (resource_heap, sampler_heap) = (5, 6); - for root in [table, resource_heap, sampler_heap] { - for sgprs in [0, 1] { - assert!(program(&[(root, sgprs, 4, 2)]).is_ok(), "{root}/{sgprs}"); - } - for sgprs in [2, 8] { - assert_eq!( - match program(&[(root, sgprs, 4, 2)]) { - Err(Malformed(why)) => why, - other => panic!("{root}/{sgprs}: expected a refusal, got {other:?}"), - }, - "root address wider than one SGPR", - "{root}/{sgprs}" - ); - } - } - // Constants and a root descriptor still take what they state. - assert!(program(&[(constants, 8, 0, 0), (descriptor, 2, 8, 1)]).is_ok()); - } - - /// A pixel program with a table in s4 (slot 2), a root descriptor in - /// s6-s7 (slot 3), and these (kind, root type, table offset) reads. - fn reading(reads: &[(u8, u8, u32)]) -> Result<Vec<NativeProgram>, ShaderError> { - let mut blob = fssm(&[(HwStage::Ps, &PS_CODE)]); - let record = FSSM_HEADER + u64_at(&blob, FSSM_HEADER + slot(HwStage::Ps)).unwrap() as usize; - let tables = (blob.len() - FSSM_HEADER) as u64; - for (root, sgprs, user_data, slot) in [(3u32, 1u32, 4u8, 2u8), (1, 2, 6, 3)] { - for v in [root, 0, sgprs, 0] { - blob.extend_from_slice(&v.to_le_bytes()); - } - blob.extend_from_slice(&[user_data, slot, 0, 0]); - } - for &(kind, root, offset) in reads { - let (user_data, slot) = if root == 3 { (4, 2) } else { (6, 3) }; - blob.extend_from_slice(&[kind, root, 0, 0]); - for v in [offset, 0, 0] { - blob.extend_from_slice(&v.to_le_bytes()); - } - blob.extend_from_slice(&[8, user_data, slot, 0]); - } - let payload = (blob.len() - FSSM_HEADER) as u64; - blob[8..16].copy_from_slice(&payload.to_le_bytes()); - blob[record + RECORD_LAYOUT..][..8].copy_from_slice(&tables.to_le_bytes()); - let used = tables + 2 * ENTRY_SIZE; - blob[record + RECORD_USED..][..8].copy_from_slice(&used.to_le_bytes()); - blob[record + RECORD_COUNTS..][..4].copy_from_slice(&2u32.to_le_bytes()); - blob[record + RECORD_COUNTS + 4..][..4] - .copy_from_slice(&(reads.len() as u32).to_le_bytes()); - native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])) - } - - #[test] - fn refuses_a_descriptor_read_two_ways() { - let (srv, cbv, uav) = (0u8, 2u8, 3u8); - let (descriptor, table) = (1u8, 3u8); - // Distinct table entries, the same entry listed twice as one kind, - // and a root descriptor read twice as one kind are fine. - assert!(reading(&[(srv, table, 0), (uav, table, 8), (cbv, table, 16)]).is_ok()); - assert!(reading(&[(srv, table, 8), (srv, table, 8)]).is_ok()); - assert!(reading(&[(cbv, descriptor, 0), (cbv, descriptor, 0)]).is_ok()); - for (reads, what) in [ - ( - [(srv, table, 8), (uav, table, 8)], - "an SRV and a UAV at one offset", - ), - ( - [(cbv, table, 0), (srv, table, 0)], - "a CBV and an SRV at one offset", - ), - ( - [(cbv, descriptor, 0), (srv, descriptor, 0)], - "a root descriptor as a CBV and an SRV", - ), - ( - [(srv, descriptor, 0), (uav, descriptor, 4)], - "a root descriptor at two offsets", - ), - ] { - assert_eq!( - why_refused(reading(&reads)), - "used descriptors read one descriptor two ways", - "{what}" - ); - } - // A table and a root descriptor are different descriptors even at - // the same stated offset. - assert!(reading(&[(srv, table, 0), (cbv, descriptor, 0)]).is_ok()); - } - - #[test] - fn refuses_a_table_mixing_samplers_and_views() { - let (srv, sampler, cbv) = (0u8, 1u8, 2u8); - let table = 3u8; - assert!(reading(&[(sampler, table, 0), (sampler, table, 4)]).is_ok()); - assert!(reading(&[(srv, table, 0), (cbv, table, 8)]).is_ok()); - for reads in [ - [(sampler, table, 0), (srv, table, 8)], - [(cbv, table, 0), (sampler, table, 8)], - ] { - assert_eq!( - why_refused(reading(&reads)), - "root table mixes samplers and views", - "{reads:?}" - ); - } - } - - fn why_refused(r: Result<Vec<NativeProgram>, ShaderError>) -> &'static str { - match r { - Err(Malformed(why)) => why, - other => panic!("expected a refusal, got {other:?}"), - } + fn rejects_truncated_oversized_and_bad_checksum_xbch_streams() { + let plain = fssm(&[(HwStage::Vs, &VS_CODE)]); + let good = xbch(&plain); + assert_eq!(unpack(&good).unwrap(), plain); + + // Truncated zlib stream (drop last byte, update packed length). + let mut truncated = good[..good.len() - 1].to_vec(); + let new_packed = (truncated.len() - XBCH_HEADER) as u64; + truncated[8..16].copy_from_slice(&new_packed.to_le_bytes()); + assert!(unpack(&truncated).is_err()); + + // Stated unpacked size smaller than the inflated output. + let mut oversized = good.clone(); + oversized[16..24].copy_from_slice(&((plain.len() - 1) as u64).to_le_bytes()); + assert!(unpack(&oversized).is_err()); + + // Stated unpacked size larger than the inflated output. + let mut underfilled = good.clone(); + underfilled[16..24].copy_from_slice(&((plain.len() + 1) as u64).to_le_bytes()); + assert!(unpack(&underfilled).is_err()); + + // Corrupt Adler-32 trailer. + let mut bad_adler = good.clone(); + *bad_adler.last_mut().unwrap() ^= 1; + assert!(unpack(&bad_adler).is_err()); } } diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index c496a0602e..79cff790a4 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -16,7 +16,7 @@ use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; use crate::native::{HwStage, RootParam, RootType}; -use crate::structure::{Bool, LaneExit, Structured}; +use crate::structure::{Bool, LaneExit, Meets, Structured}; /// An instruction: block and index in [`crate::ir::Block::insts`]. pub type Site = (usize, usize); @@ -38,6 +38,24 @@ pub struct Address { /// offset is then the byte offset in the code. pub const CODE: usize = usize::MAX; +/// [`Address::param`] of title memory at an address no root parameter +/// gives: one the code computes from root constants, reads out of a +/// descriptor or loads from other memory (compute programs only: the +/// ray-tracing structure builder and the programs that walk its +/// structures). Offset and computed term are not used: lowering takes the +/// 64-bit address from the instruction's operands. +pub const MEMORY: usize = usize::MAX - 1; + +/// The reasons an address traces to no root parameter for which the +/// address is then taken as it stands ([`MEMORY`]). +const RAW: [&str; 5] = [ + "an address not from a root parameter", + "an address from a root parameter that is no address", + "an address in an SGPR that is no root parameter", + "an address loaded from memory", + "an address from a phi", +]; + #[derive(Debug, Clone, PartialEq, Eq)] pub enum Source { /// Dwords `first..` of what the scalar load at `load` reads (see @@ -107,16 +125,57 @@ pub struct Descriptor { pub source: Source, } +/// A view-heap descriptor whose byte address can be evaluated when binding +/// the draw, using a table base and a root constant. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RootIndexedView { + pub table_slot: u8, + pub constant_slot: u8, + pub constant_dword: u32, + pub byte_offset: u32, + pub shift: u8, +} + #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Resources { + /// Scalar values saved to a constant VGPR lane and restored within one + /// block, even where that VGPR is also used in ordinary vector operations + /// (codec_d, cool_fox 8cc31ab: a reduction scratch whose other lanes + /// hold unknown values). + pub(crate) restored_lanes: std::collections::HashMap<Site, Moved>, /// Every scalar memory access by address (`s_load_*`, `s_store_*`), and /// every global memory access (`global_*`, the dynamic term per lane). pub scalar: Vec<(Site, Address)>, pub descriptors: Vec<Descriptor>, + /// Direct descriptor sources with a draw-evaluable index. + pub root_indexed_views: Vec<RootIndexedView>, /// User SGPRs holding root parameters: value on entry, layout index, /// dword within the parameter. pub params: Vec<(Value, usize, u32)>, + /// Scalar loads of one descriptor the code keeps per lane in VGPRs + /// ([`Tracer::lane_copies`]): they read one address, so their dwords + /// stand in for each other. + pub lane_copied: Vec<Site>, pub waterfall: Waterfall, + /// Every `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`: where + /// its nodes are. + pub bvh: Vec<(Site, BvhNodes)>, +} + +/// Where a ray-tracing node test ([`crate::bvh`]) reads its nodes. Its +/// descriptor operand names a range of memory, not a texture. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BvhNodes { + /// A buffer of the host: the descriptor is loaded from a table (it is + /// among [`Resources::descriptors`]), and node pointers count from the + /// buffer's start. Its flags are not known to the shader: boxes are + /// sorted and triangles return barycentrics, as every descriptor + /// the title builds asks. + Resource, + /// Title memory by address: the code makes the descriptor from numbers + /// (the title: the whole address space, or one structure's address in + /// dword 0). Dwords 1 and 3, which hold its flags. + Memory { word1: u32, word3: u32 }, } /// Waterfall loops over descriptors that differ between lanes: each pass @@ -172,6 +231,10 @@ pub fn track( for (b, block) in p.blocks.iter().enumerate() { for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); + t.at.set(Some(site)); + if let Some(value) = t.restored(inst, Some(b)) { + out.restored_lanes.insert(site, value); + } let fail = |what| ShaderError::Unsupported { offset: inst.machine.offset, what, @@ -179,12 +242,16 @@ pub fn track( let mut first_lane = Vec::new(); let mut offset = Vec::new(); let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { - let source = t.descriptor(inst, op, b).map_err(fail)?; - first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); + let source = t.descriptor(inst, op, site).map_err(fail)?; + // A descriptor the code keeps per lane ([`Tracer::lane_copies`]) + // is the same in every lane: its loop is lowered as it stands + // and needs no proof. + if !t.kept_per_lane(inst, op) { + first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); + } if let Source::Loaded { load, .. } = source - && let Some((_, a)) = out.scalar.iter().find(|s| s.0 == load) - && let Some(Term::Value(v)) = a.dynamic.map(|d| t.origin(d)) - && t.first_lane_source(v).is_some() + && out.scalar.iter().any(|s| s.0 == load) + && let Some(v) = t.first_lane_offset(load) { offset.push((v, load)); } @@ -192,16 +259,40 @@ pub fn track( Ok(()) }; match &inst.fields { + Fields::Image { rsrc, .. } if inst.name().starts_with("image_bvh") => { + // The ray and node test names no texture. A descriptor + // whose flag dwords the code sets as numbers and whose + // type is a ray-tracing structure is a range of title + // memory (the title: all of it, or from one structure's + // address on), and the node's address is among the + // operands; any other descriptor must be a resource of + // the host. + let word = |k: u8| match *rsrc { + Operand::Scalar { code, dwords } if k < dwords => { + inst.read(Reg::S(code + k)).map(|v| t.origin(v)) + } + _ => None, + }; + match (word(1), word(3)) { + (Some(Term::Const(word1)), Some(Term::Const(word3))) + if word3 >> 28 == crate::bvh::DESCRIPTOR_TYPE => + { + out.bvh.push((site, BvhNodes::Memory { word1, word3 })); + } + _ => { + descriptor(rsrc, Role::Resource)?; + out.bvh.push((site, BvhNodes::Resource)); + } + } + } Fields::Image { rsrc, sampler, .. } => { descriptor(rsrc, Role::Resource)?; if let Some(s) = sampler { descriptor(s, Role::Sampler)?; } } - // A cache invalidation names a buffer only to scope the - // address range it flushes; it reads no data through the - // descriptor. Lowering one is a no-op on the host, so there - // is no descriptor to keep alive for it. + // Cache invalidations name a buffer's address space but do + // not read its descriptor; the host has no cache to drop. Fields::Buffer { rsrc, .. } if !inst.name().ends_with("_inv") => { descriptor(rsrc, Role::Resource)? } @@ -215,7 +306,10 @@ pub fn track( soffset, .. } if inst.name().contains("_load_") || inst.name().contains("_store_") => { - let address = t.smem_address(inst, base, *offset, soffset).map_err(fail)?; + let address = t + .smem_address(inst, base, *offset, soffset) + .or_else(|why| t.by_address(why)) + .map_err(fail)?; out.scalar.push((site, address)); } Fields::Flat { @@ -226,6 +320,7 @@ pub fn track( } if inst.name().starts_with("global_") => { let address = t .flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset) + .or_else(|why| t.by_address(why)) .map_err(fail)?; out.scalar.push((site, address)); } @@ -246,6 +341,8 @@ pub fn track( } } } + // What follows traces no access of one block. + t.at.set(None); // The proof needs the per-lane form. Without it nothing is emitted, and // its failure is the one to report, so the reads stay unproven here. if t.lanes.is_none() { @@ -254,12 +351,12 @@ pub fn track( for (block, (accesses, mut reads)) in first_lane_at { reads.sort_unstable(); reads.dedup(); - let proof = - t.waterfall(block, &accesses, &reads) - .map_err(|what| ShaderError::Unsupported { - offset: t.inst((block, accesses[0])).machine.offset, - what, - })?; + let proof = t + .waterfall(block, &accesses, &reads) + .map_err(|what| ShaderError::Unsupported { + offset: t.inst((block, accesses[0])).machine.offset, + what, + })?; out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); } @@ -274,6 +371,14 @@ pub fn track( out.waterfall.loads.extend(loads); } } + out.lane_copied = t.lane_copied.take(); + out.lane_copied.sort_unstable(); + out.lane_copied.dedup(); + out.root_indexed_views = out + .descriptors + .iter() + .filter_map(|d| t.root_indexed_view(d, &out.scalar)) + .collect(); Ok(out) } @@ -286,7 +391,6 @@ enum Term { /// A 32-bit sum: optional root parameter (as its first dword), constant, /// optional computed term. -#[derive(Clone, Copy)] struct Sum { base: Option<Value>, offset: u32, @@ -304,11 +408,19 @@ struct Tracer<'a> { /// Register per input value. inputs: Vec<Option<Reg>>, origin: Vec<Term>, - /// Address sums already traced, indexed by SSA value. - sums: std::cell::RefCell<Vec<Option<Sum>>>, + /// See [`Resources::lane_copied`]. + lane_copied: std::cell::RefCell<Vec<Site>>, lanes: Option<&'a Structured>, + /// While set, [`Self::sum`] keeps the first-lane read of an index as + /// the computed term instead of what the lanes hold. + read_first_lane: std::cell::Cell<bool>, + /// What the conditions asked of `lanes` so far came down to: the proofs + /// of one program ask about the same blocks and masks again and again. + meets: std::cell::RefCell<Meets>, /// Reverse-postorder index per block. rpo: Vec<usize>, + /// The instruction site of the access being traced ([`Self::live`]). + at: std::cell::Cell<Option<Site>>, } /// What lanes are known to satisfy: each [`Bool`] where its flag is set, @@ -317,6 +429,8 @@ type Known = Vec<(Bool, bool)>; const MAX_ROUNDS: usize = 64; const MAX_JOINS: usize = 8; +/// VGPR values followed for one dword of a descriptor kept per lane. +const MAX_COPIES: usize = 64; impl<'a> Tracer<'a> { fn new( @@ -368,9 +482,12 @@ impl<'a> Tracer<'a> { phis, inputs, origin: Vec::new(), - sums: Default::default(), + lane_copied: Default::default(), lanes, + read_first_lane: Default::default(), + meets: Default::default(), rpo, + at: Default::default(), }; t.origin = t.propagate_copies(n)?; Ok(t) @@ -405,7 +522,7 @@ impl<'a> Tracer<'a> { } for inst in &block.insts { for (k, &(_, v)) in inst.writes.iter().enumerate() { - let new = match copy_source(inst, k).or_else(|| self.restored(inst)) { + let new = match copy_source(inst, k).or_else(|| self.restored(inst, None)) { Some(Moved::Const(c)) => Some(Term::Const(c)), Some(Moved::Value(s)) => o[s.0 as usize], None => Some(Term::Value(v)), @@ -431,6 +548,15 @@ impl<'a> Tracer<'a> { }) } + /// Whether some lane can satisfy all of `conditions` ([`Bools::meet`]). + /// + /// [`Bools::meet`]: crate::structure::Bools::meet + fn meet(&self, lanes: &Structured, conditions: &[(Bool, bool)]) -> bool { + lanes + .bools + .meet_seen(conditions, &mut self.meets.borrow_mut()) + } + fn inst(&self, (b, i): Site) -> &'a Inst { &self.p.blocks[b].insts[i] } @@ -464,7 +590,7 @@ impl<'a> Tracer<'a> { }) } - /// The SOP2 operands of `v` if an `s_add` with one of `names` wrote it. + /// The SOP2 operands of `v` if an instruction with one of `names` wrote it. fn sop2(&self, v: Value, names: &[&str]) -> Option<(&'a Inst, [Term; 2])> { let inst = self.def(v)?; if !names.contains(&inst.name()) || inst.writes.first()?.1 != v { @@ -482,6 +608,42 @@ impl<'a> Tracer<'a> { )) } + fn root_indexed_view( + &self, + descriptor: &Descriptor, + scalar: &[(Site, Address)], + ) -> Option<RootIndexedView> { + if descriptor.role != Role::Resource { + return None; + } + let Source::Loaded { load, first } = descriptor.source else { + return None; + }; + let i = scalar.binary_search_by_key(&load, |(site, _)| *site).ok()?; + let address = scalar[i].1; + let base = self.layout.get(address.param)?; + if base.root != RootType::Table { + return None; + } + let dynamic = address.dynamic?; + let (input, shift) = match self.sop2(dynamic, &["s_lshl_b32"]) { + Some((_, [Term::Value(input), Term::Const(shift)])) => (input, (shift & 31) as u8), + _ => (dynamic, 0), + }; + let (param, constant_dword) = self.param_of(self.inputs[input.0 as usize]?)?; + let constant = self.layout.get(param)?; + if constant.root != RootType::Constants { + return None; + } + Some(RootIndexedView { + table_slot: base.slot, + constant_slot: constant.slot, + constant_dword, + byte_offset: address.offset.wrapping_add(u32::from(first) * 4), + shift, + }) + } + fn sum(&self, t: Term) -> Sum { let v = match t { Term::Const(c) => { @@ -493,16 +655,12 @@ impl<'a> Tracer<'a> { } Term::Value(v) => v, }; - let index = v.0 as usize; - if let Some(&Some(sum)) = self.sums.borrow().get(index) { - return sum; - } let dynamic = Sum { base: None, offset: 0, dynamic: Some(v), }; - if let Some(reg) = self.inputs[index] { + if let Some(reg) = self.inputs[v.0 as usize] { return match self.param_of(reg) { Some((_, 0)) => Sum { base: Some(v), @@ -519,6 +677,34 @@ impl<'a> Tracer<'a> { dynamic: None, }; } + // Paths that each add an index to a table in the code and meet before one + // load: the join itself is the computed term. Lowering gives every + // `s_getpc_b64` its own offset in the code as its value, so the join is the + // byte in the code whichever table a path took ([`Self::address`] adds no + // base to it). + if let Some(pc) = self.code_join(v) { + return Sum { + base: Some(pc), + offset: 0, + dynamic: Some(v), + }; + } + // An address computed in VGPRs and taken from the first lane (a + // table in the code indexed by a value held per lane, or a table + // offset held per lane, the console's waterfall): the sum of what + // the lanes hold. Loads at one offset in different loops (each with + // its own `v_readfirstlane_b32`) then have one address, which is + // what tells lowering that they read one descriptor. With + // `read_first_lane` a first-lane read of an index alone stays the + // computed term ([`Self::first_lane_offset`]). + if let Some(lane) = self.first_lane(v) { + let per_lane = self.sum(self.vorigin(lane)); + return if per_lane.base.is_some() || !self.read_first_lane.get() { + per_lane + } else { + dynamic + }; + } let Some([a, b]) = self .sop2(v, &["s_add_u32", "s_add_i32"]) .map(|(_, t)| t) @@ -527,24 +713,114 @@ impl<'a> Tracer<'a> { return dynamic; }; let (x, y) = (self.sum(a), self.sum(b)); - let sum = - if x.base.is_some() && y.base.is_some() || x.dynamic.is_some() && y.dynamic.is_some() { - dynamic - } else { - Sum { - base: x.base.or(y.base), - offset: x.offset.wrapping_add(y.offset), - dynamic: x.dynamic.or(y.dynamic), - } + if x.base.is_some() && y.base.is_some() || x.dynamic.is_some() && y.dynamic.is_some() { + return dynamic; + } + Sum { + base: x.base.or(y.base), + offset: x.offset.wrapping_add(y.offset), + dynamic: x.dynamic.or(y.dynamic), + } + } + + /// For a join `v` whose every incoming value adds to an `s_getpc_b64` low + /// dword: the first of those (one level of joins only). The paths may add + /// to different ones: two tables in the code, one picked by control flow + /// (the title's fog reconstruction reads its sample offsets from + /// one of two tables, by the sample's number; refused, the lit frame was + /// multiplied by a fog transmittance nothing had written). + fn code_join(&self, v: Value) -> Option<Value> { + let (b, i) = self.phis[v.0 as usize]?; + let mut base = None; + for &a in &self.p.blocks[b].phis[i].args { + let Term::Value(x) = self.vorigin(a) else { + return None; }; - // The operands' origins are settled before tracing starts. Every - // use of this value can reuse its sum, including an opaque result. - let mut sums = self.sums.borrow_mut(); - if index >= sums.len() { - sums.resize(index + 1, None); + if x == v { + continue; + } + let pc = self.code_base(x, 4)?; + base = base.or(Some(pc)); + } + base + } + + /// `t` is the high dword of an `s_getpc_b64`, or `s_addc_u32`s of one: + /// the carry may be added in steps (the counter's high dword plus 0 + /// where the table's offset is added, then plus the index's high dword). + fn code_high(&self, t: Term) -> bool { + self.code_high_in(t, 4) + } + + /// [`Self::code_high`], at most `depth` additions deep. + fn code_high_in(&self, t: Term, depth: u32) -> bool { + let Term::Value(x) = t else { return false }; + if self.def(x).is_some_and(|i| { + i.name() == "s_getpc_b64" && i.writes.get(1).is_some_and(|w| w.1 == x) + }) { + return true; + } + depth > 0 + && self.sop2(x, &["s_addc_u32"]).is_some_and(|(_, [p, q])| { + self.code_high_in(p, depth - 1) || self.code_high_in(q, depth - 1) + }) + } + + /// The `s_getpc_b64` low dword among the terms `v` adds up (`depth` + /// additions deep; joins are not followed). + fn code_base(&self, v: Value, depth: u32) -> Option<Value> { + if self.getpc(v).is_some() { + return Some(v); + } + // Computed in VGPRs and taken from the first lane. + if let Some(lane) = self.first_lane(v) { + return match self.vorigin(lane) { + Term::Value(x) => self.code_base(x, depth), + Term::Const(_) => None, + }; + } + if depth == 0 || self.phis[v.0 as usize].is_some() { + return None; + } + let terms = self + .sop2(v, &["s_add_u32", "s_add_i32"]) + .map(|(_, t)| t) + .or_else(|| self.vadd(v))?; + terms.into_iter().find_map(|t| match t { + Term::Value(x) => self.code_base(x, depth - 1), + Term::Const(_) => None, + }) + } + + /// `t` is `high` or an `s_addc_u32` of it. + fn is_high(&self, t: Term, high: Value) -> bool { + match t { + Term::Value(x) => { + x == high + || self + .sop2(x, &["s_addc_u32"]) + .is_some_and(|(_, [p, q])| p == Term::Value(high) || q == Term::Value(high)) + } + Term::Const(_) => false, + } + } + + /// The VGPR value `v_readfirstlane_b32` reads to write the scalar `v`. + fn first_lane(&self, v: Value) -> Option<Value> { + let inst = self.def(v)?; + if inst.name() != "v_readfirstlane_b32" || inst.writes.first()?.1 != v { + return None; + } + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + return None; + } + match *f.src.first()? { + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + _ => None, } - sums[index] = Some(sum); - sum } /// The `s_getpc_b64` writing `lo` as its low dword. @@ -604,6 +880,21 @@ impl<'a> Tracer<'a> { self.origin(v) } + /// The address of an access that traces to no root parameter (`why` + /// says how it failed): title memory at the address as it stands, in a + /// compute program. + fn by_address(&self, why: &'static str) -> Result<Address, &'static str> { + if self.stage == HwStage::Cs && RAW.contains(&why) { + Ok(Address { + param: MEMORY, + offset: 0, + dynamic: None, + }) + } else { + Err(why) + } + } + /// A global memory address: an SGPR pair plus a VGPR offset, or a VGPR /// pair. fn flat_address( @@ -652,6 +943,15 @@ impl<'a> Tracer<'a> { /// The address `lo` and `hi` hold, plus `extra` (an instruction's /// immediate and offset register). fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result<Address, &'static str> { + // The high half as the lanes that read through the address hold + // it, where that is a constant or what a register held on entry + // (the code clears a table address's high half inside a branch + // and uses the address after the join). + let hi = match self.live(hi) { + t @ Term::Const(_) => t, + Term::Value(v) if self.inputs[v.0 as usize].is_some() => Term::Value(v), + _ => hi, + }; let s = self.sum(lo); if s.dynamic.is_some() && extra.dynamic.is_some() { return Err("an address with two computed terms"); @@ -663,11 +963,13 @@ impl<'a> Tracer<'a> { if !self.high_half(hi, high) && !high.is_some_and(|h| self.carried(hi, h)) { return Err("an address with an untracked high half"); } + // A join of paths into tables in the code is the byte in the code + // already: each path's `s_getpc_b64` counts as its own offset. + let joined = s.dynamic.is_some_and(|d| self.code_join(d).is_some()); + let first = if joined { 0 } else { pc.machine.offset as u32 + 4 }; return Ok(Address { param: CODE, - offset: (pc.machine.offset as u32 + 4) - .wrapping_add(s.offset) - .wrapping_add(extra.offset), + offset: first.wrapping_add(s.offset).wrapping_add(extra.offset), dynamic: s.dynamic.or(extra.dynamic), }); } @@ -715,6 +1017,39 @@ impl<'a> Tracer<'a> { if v == high { return true; } + // A join ([`Self::code_join`]): every path carries into the table's high half. + if let Some((b, i)) = self.phis[v.0 as usize] { + // A path may carry into another table's high half ([`Self::code_join`]). + let high_of = |t: Term| self.is_high(t, high) || self.code_high(t); + return self.p.blocks[b].phis[i].args.iter().all(|&a| { + let t = self.vorigin(a); + if t == Term::Value(v) || high_of(t) { + return true; + } + let Term::Value(x) = t else { + return false; + }; + // Computed in VGPRs and taken from the first lane. + let x = match self.first_lane(x).map(|lane| self.vorigin(lane)) { + Some(Term::Value(y)) => y, + Some(Term::Const(_)) => return false, + None => x, + }; + let Some(inst) = self.def(x) else { + return false; + }; + let Fields::Valu(f) = &inst.fields else { + return false; + }; + inst.name() == "v_add_co_ci_u32" + && f.src[..2.min(f.src.len())] + .iter() + .any(|o| self.vterm(inst, o).is_some_and(high_of)) + }); + } + if let Some(lane) = self.first_lane(v) { + return self.carried(self.vorigin(lane), high); + } if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { return self.carried(a, high) || self.carried(b, high); } @@ -786,8 +1121,8 @@ impl<'a> Tracer<'a> { self.address(lo, hi, extra) } - /// The source of the descriptor operand `op` of `inst`, in block `at`. - fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result<Source, &'static str> { + /// The source of the descriptor operand `op` of `inst`, at `at`. + fn descriptor(&self, inst: &Inst, op: &Operand, at: Site) -> Result<Source, &'static str> { let Operand::Scalar { code, dwords } = *op else { return Err("a descriptor not in SGPRs"); }; @@ -795,8 +1130,17 @@ impl<'a> Tracer<'a> { .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) .collect::<Option<Vec<_>>>() .ok_or("a descriptor not in SGPRs")?; - // Only the lanes that reach the access read the descriptor. - let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); + // Only the lanes that reach and run the access read the descriptor + // (codec_d, cool_fox f4b48ad: its EXEC guard too; without it a join + // edge only lanes outside EXEC take kept 2da4beb386509b77, + // CS_AlphTransmissionPrefilterMip, from translating for 32-lane waves). + let mut known = Vec::new(); + if let Some(l) = self.lanes { + known.push((l.reach[at.0], true)); + if let Some(guard) = l.guards[at.0][at.1] { + known.push((guard, true)); + } + } self.classify(&words, &mut Vec::new(), &mut known) } @@ -819,6 +1163,10 @@ impl<'a> Tracer<'a> { Term::Const(_) => None, }; if let Some(sources) = words.iter().map(read).collect::<Option<Vec<_>>>() { + // One descriptor the code keeps per lane: the lanes agree. + if let Some(source) = self.lane_copies(words) { + return Ok(source); + } // Read from the first active lane, as a waterfall loop does: the // dwords each lane holds. let lanes: Vec<Term> = sources.into_iter().map(Term::Value).collect(); @@ -873,6 +1221,94 @@ impl<'a> Tracer<'a> { }) } + /// The one edge into the join `block` that lanes satisfying `known` + /// can have taken, if the lanes' paths ([`Structured`]) rule out every + /// other: the console compiler loads a descriptor (or clears an + /// address's high half) inside a branch that skips code when no lane + /// is left for it, and uses it after the join, where only lanes that + /// ran the branch are left (the title's + /// `CS_Alpha_Schedule`: the registers' values from before the branch, + /// which the join also sees, are what a wave with no such lane holds). + /// None at loop headers and without the lanes' paths. + fn only_edge(&self, block: usize, known: &mut Known) -> Option<usize> { + let lanes = self.lanes?; + let preds = &self.p.blocks[block].preds; + if preds.len() < 2 || preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) { + return None; + } + let mut only = None; + for (j, &q) in preds.iter().enumerate() { + let n = known.len(); + known.push((lanes.reach[q], true)); + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + known.push((when, taken == block)); + } + let possible = self.meet(lanes, known); + known.truncate(n); + if possible { + if only.is_some() { + return None; + } + only = Some(j); + } + } + only + } + + /// Whether lowering can make a handle for `source` in any block: its + /// heap index comes from root parameters and constants alone (a table + /// offset the code computes exists only where the load is). + fn anywhere(&self, source: &Source) -> bool { + match source { + Source::Constant(_) => true, + Source::Built { address, .. } => address.dynamic.is_none(), + Source::Loaded { load, .. } => { + let inst = self.inst(*load); + match &inst.fields { + Fields::Smem { + base, + offset, + soffset, + .. + } => self + .smem_address(inst, base, *offset, soffset) + .is_ok_and(|a| a.dynamic.is_none()), + _ => false, + } + } + _ => false, + } + } + + /// `t` as the lanes that reach the access being traced hold it: through + /// joins they can have entered by one edge only ([`Self::only_edge`]). + fn live(&self, mut t: Term) -> Term { + let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else { + return t; + }; + let mut known = vec![(lanes.reach[at.0], true)]; + if let Some(guard) = lanes.guards[at.0][at.1] { + known.push((guard, true)); + } + for _ in 0..MAX_JOINS { + let Term::Value(v) = t else { break }; + let Some((block, i)) = self.phis[v.0 as usize] else { + break; + }; + let Some(j) = self.only_edge(block, &mut known) else { + break; + }; + t = self.origin(self.p.blocks[block].phis[i].args[j]); + } + t + } + /// Words that phis of one block join, traced per predecessor (words /// defined before the join hold on every edge). fn phi( @@ -900,20 +1336,35 @@ impl<'a> Tracer<'a> { } joins.push(block); let phis = &self.p.blocks[block].phis; + let edge = |j: usize| -> Vec<Term> { + words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => self.origin(phis[i].args[j]), + None => *w, + }) + .collect() + }; let args = (0..self.p.blocks[block].preds.len()) - .map(|j| { - let edge: Vec<Term> = words - .iter() - .map(|w| match phi_of(w) { - Some((_, i)) => self.origin(phis[i].args[j]), - None => *w, - }) - .collect(); - self.classify(&edge, joins, known) - }) + .map(|j| self.classify(&edge(j), joins, known)) .collect::<Result<_, _>>(); + let source = match args { + Ok(args) => Ok(Source::Phi { block, args }), + // An edge holds no descriptor. With only one edge the lanes + // that read the descriptor can have come by, it is what the + // registers hold on that one (a wave that took another edge + // has no lane left that reads it), if that can be named where + // it is read. + Err(e) => match self.only_edge(block, known) { + Some(j) => match self.classify(&edge(j), joins, known) { + Ok(source) if self.anywhere(&source) => Ok(source), + _ => Err(e), + }, + None => Err(e), + }, + }; joins.pop(); - Ok(Some(Source::Phi { block, args: args? })) + source.map(Some) } /// Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced @@ -1046,6 +1497,42 @@ impl<'a> Tracer<'a> { inst.read(Reg::V(reg)) } + /// The `v_readfirstlane_b32` result the scalar load at `load` adds to + /// its address as a table offset (the console's waterfall, + /// `s_load_dwordx8 .., s[4:5], s20`): `track` proves the waterfall from + /// it, and lowering reads it per lane there. + fn first_lane_offset(&self, load: Site) -> Option<Value> { + let inst = self.inst(load); + let Fields::Smem { + base, + offset, + soffset, + .. + } = &inst.fields + else { + return None; + }; + self.read_first_lane.set(true); + let address = self.smem_address(inst, base, *offset, soffset); + self.read_first_lane.set(false); + match self.origin(address.ok()?.dynamic?) { + Term::Value(v) if self.first_lane_source(v).is_some() => Some(v), + _ => None, + } + } + + /// Whether the descriptor operand `op` of `inst` is one the code keeps + /// per lane ([`Self::lane_copies`]). + fn kept_per_lane(&self, inst: &Inst, op: &Operand) -> bool { + let Operand::Scalar { code, dwords } = *op else { + return false; + }; + (0..dwords) + .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) + .collect::<Option<Vec<_>>>() + .is_some_and(|words| self.lane_copies(&words).is_some()) + } + /// The `v_readfirstlane_b32` results the descriptor operand `op` of /// `inst` is, when every dword is one. fn first_lane_words(&self, inst: &Inst, op: &Operand) -> Option<Vec<Value>> { @@ -1144,7 +1631,7 @@ impl<'a> Tracer<'a> { }; let mut skips = known.clone(); skips.extend([(lanes.reach[site.0], true), (guard, false)]); - if lanes.bools.meet(&skips) { + if self.meet(lanes, &skips) { return Err("a per-lane descriptor written where some lanes may keep the old one"); } Ok(()) @@ -1407,7 +1894,7 @@ impl<'a> Tracer<'a> { { known.push((when, taken == block)); } - let arg = if lanes.bools.meet(known) { + let arg = if self.meet(lanes, known) { let edge: Vec<Term> = words .iter() .map(|w| match phi_of(w) { @@ -1508,7 +1995,7 @@ impl<'a> Tracer<'a> { return Err(SELECT); } let reach = (lanes.reach[b], true); - let meet = |conditions: &[(Bool, bool)]| lanes.bools.meet(conditions); + let meet = |conditions: &[(Bool, bool)]| self.meet(lanes, conditions); let mut out = Waterfall::default(); let mut required = vec![(remaining, true)]; for (i, inst) in block.insts[..access].iter().enumerate() { @@ -1563,8 +2050,7 @@ impl<'a> Tracer<'a> { } else { continue; }; - let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) - else { + let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) else { continue; }; if meet(&[reach, (selected, true), (matched, false)]) { @@ -1621,43 +2107,218 @@ impl<'a> Tracer<'a> { first: first as u8, }) } + + /// A descriptor the code keeps per lane: every dword of `words` is the + /// first lane (`v_readfirstlane_b32`) of a VGPR that `v_mov_b32` filled + /// from SGPRs. The console compiler does this to a descriptor loaded on + /// both sides of a per-lane branch: the join is per lane, so it lives in + /// VGPRs, and the instruction that needs it in SGPRs runs in a loop over + /// the distinct values (the first lane's, the lanes holding the same, + /// then the rest). When every scalar those moves copy is the same dword + /// of loads from one constant address, the lanes agree and the + /// descriptor is any of those loads. + // shortcut: what else the VGPRs held (numbers, on paths or in lanes that + // never read them as a descriptor) is ignored, and a move is taken to + // leave either its source or what a move before it wrote; a descriptor + // read per lane from memory (`global_load_*`) refuses. + fn lane_copies(&self, words: &[Term]) -> Option<Source> { + let mut loads: Vec<Site> = Vec::new(); + let mut first = None; + for (k, w) in words.iter().enumerate() { + let Term::Value(v) = *w else { return None }; + let mut copies = Vec::new(); + if !self.scalar_copies(self.first_lane(v)?, &mut copies) { + return None; + } + let mut found = false; + for c in copies { + let Term::Value(c) = c else { continue }; + let Some(site) = self.defs[c.0 as usize] else { + continue; + }; + let load = self.inst(site); + if !load.name().starts_with("s_load_") { + continue; + } + // Dword k of the operand is dword `first + k` of each load. + let dword = load.writes.iter().position(|x| x.1 == c)?; + let f = dword.checked_sub(k)?; + if *first.get_or_insert(f) != f { + return None; + } + if !loads.contains(&site) { + loads.push(site); + } + found = true; + } + if !found { + return None; + } + } + let address = |site: Site| { + let inst = self.inst(site); + match &inst.fields { + Fields::Smem { + base, + offset, + soffset, + .. + } => self.smem_address(inst, base, *offset, soffset).ok(), + _ => None, + } + }; + let a = address(*loads.first()?)?; + if a.dynamic.is_some() || loads.iter().any(|&l| address(l) != Some(a)) { + return None; + } + // The handle is made where the descriptor is used, from the load's + // operands: take a load whose base is the root parameter's own SGPR. + loads.sort_unstable(); + let load = *loads.iter().find(|&&l| self.base_from_entry(l))?; + self.lane_copied.borrow_mut().extend(&loads); + Some(Source::Loaded { + load, + first: first? as u8, + }) + } + + /// The scalars (as origins) that `v_mov_b32` copies put in VGPR value + /// `v`, through joins, moves between VGPRs and per-lane selects; a move + /// keeps what it wrote over in the lanes it does not run. False if the + /// VGPR may hold something read per lane from memory. + fn scalar_copies(&self, v: Value, out: &mut Vec<Term>) -> bool { + let (mut seen, mut work) = (Vec::new(), vec![v]); + while let Some(v) = work.pop() { + if seen.contains(&v) { + continue; + } + if seen.len() == MAX_COPIES { + return false; + } + seen.push(v); + if let Some((b, i)) = self.phis[v.0 as usize] { + work.extend(&self.p.blocks[b].phis[i].args); + continue; + } + // An entry value, or a number some instruction computed. + let Some(inst) = self.def(v) else { continue }; + if inst.name().starts_with("global_load_") { + return false; + } + let Fields::Valu(f) = &inst.fields else { + continue; + }; + let sources = match inst.name() { + "v_mov_b32" => 1, + "v_cndmask_b32" => 2, + _ => continue, + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + continue; + } + for op in f.src.iter().take(sources) { + match *op { + Operand::Vector { reg, .. } => work.extend(inst.read(Reg::V(reg))), + Operand::Scalar { code, .. } if code != NULL => { + out.extend(inst.read(Reg::S(code)).map(|s| self.origin(s))); + } + _ => {} + } + } + // Lanes outside EXEC keep the old value. + if let Some(Operand::Vector { reg, .. }) = f.dst { + work.extend(inst.read(Reg::V(reg))); + } + } + true + } + + /// The load at `site` has a constant offset and takes its base from a + /// root parameter's SGPR through moves alone: a value that exists + /// wherever the descriptor is used. + fn base_from_entry(&self, site: Site) -> bool { + let inst = self.inst(site); + let Fields::Smem { + base: Operand::Scalar { code, .. }, + soffset: Operand::Scalar { code: NULL, .. }, + .. + } = &inst.fields + else { + return false; + }; + let Some(mut v) = inst.read(Reg::S(*code)) else { + return false; + }; + loop { + if self.inputs[v.0 as usize].is_some() { + return true; + } + let Some(def) = self.def(v) else { return false }; + let Some(k) = def.writes.iter().position(|w| w.1 == v) else { + return false; + }; + match copy_source(def, k) { + Some(Moved::Value(s)) => v = s, + _ => return false, + } + } + } } -#[derive(Clone, Copy, PartialEq, Eq)] -enum Moved { +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Moved { Const(u32), Value(Value), } +/// A lane read or write with no modifier (the lane holds the value as is). +fn plain_lane(v: &crate::gfx10::Valu) -> bool { + v.abs == 0 && v.neg == 0 && v.opsel == 0 && !v.clamp && v.omod == 0 && v.sdwa.is_none() && v.dpp.is_none() +} + impl Tracer<'_> { /// For `v_readlane_b32` of a constant lane: the SGPR spilled to that /// lane, found by following the VGPR's `v_writelane_b32` writes. - fn restored(&self, inst: &Inst) -> Option<Moved> { + /// With `block`: only a spill written in that block, through no phi. + fn restored(&self, inst: &Inst, block: Option<usize>) -> Option<Moved> { let Fields::Valu(v) = &inst.fields else { return None; }; - if inst.name() != "v_readlane_b32" { + if inst.name() != "v_readlane_b32" || !plain_lane(v) { return None; } let [Operand::Vector { reg, .. }, lane] = v.src[..] else { return None; }; - self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new()) + let lane = lane_of(lane)?; + if lane >= if self.p.wave64 { 64 } else { 32 } { + return None; + } + self.spilled(inst.read(Reg::V(reg))?, lane, block, &mut Vec::new()) .ok() .flatten() } /// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in /// `seen` (already being resolved), `Err` if not a spilled SGPR. - fn spilled(&self, v: Value, lane: u32, seen: &mut Vec<Value>) -> Result<Option<Moved>, ()> { + fn spilled( + &self, + v: Value, + lane: u32, + block: Option<usize>, + seen: &mut Vec<Value>, + ) -> Result<Option<Moved>, ()> { if let Some((b, i)) = self.phis[v.0 as usize] { + if block.is_some() { + return Err(()); + } if seen.contains(&v) { return Ok(None); } seen.push(v); let mut found = None; for &a in &self.p.blocks[b].phis[i].args { - if let Some(m) = self.spilled(a, lane, seen)? { + if let Some(m) = self.spilled(a, lane, block, seen)? { if found.is_some_and(|f| f != m) { return Err(()); } @@ -1666,18 +2327,26 @@ impl Tracer<'_> { } return Ok(found); } - let inst = self.def(v).ok_or(())?; + let site = self.defs[v.0 as usize].ok_or(())?; + if block.is_some_and(|b| site.0 != b) { + return Err(()); + } + let inst = self.inst(site); let Fields::Valu(w) = &inst.fields else { return Err(()); }; let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else { return Err(()); }; - if inst.name() != "v_writelane_b32" { + if inst.name() != "v_writelane_b32" || !plain_lane(w) { + return Err(()); + } + let written = lane_of(*at).ok_or(())?; + if written >= if self.p.wave64 { 64 } else { 32 } { return Err(()); } - if lane_of(*at).ok_or(())? != lane { - return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen); + if written != lane { + return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, block, seen); } match *value { Operand::Scalar { code, .. } if code != NULL => { @@ -1866,16 +2535,17 @@ pub(crate) mod tests { fn heap_indices_from_root_constants_in_a_merged_stage() { // User data starts at s8: the constant (index 6) is s14, the heap // (index 10) s18. + let code = [ + 0x8F08_850E, // s_lshl_b32 s8, s14, 5 + 0xBE93_0380, // s_mov_b32 s19, 0 + 0xF408_0209, + 0x1000_0000, // s_load_dwordx4 s[8:11], s[18:19], s8 + 0xE000_2000, + 0x8002_0400, // buffer_load_format_x v4, v0, s[8:11], 0 idxen + S_ENDPGM, + ]; let r = track_words( - &[ - 0x8F08_850E, // s_lshl_b32 s8, s14, 5 - 0xBE93_0380, // s_mov_b32 s19, 0 - 0xF408_0209, - 0x1000_0000, // s_load_dwordx4 s[8:11], s[18:19], s8 - 0xE000_2000, - 0x8002_0400, // buffer_load_format_x v4, v0, s[8:11], 0 idxen - S_ENDPGM, - ], + &code, &[param(Constants, 6, 1), param(ResourceHeap, 10, 1)], HwStage::Ms, ); @@ -1891,6 +2561,24 @@ pub(crate) mod tests { first: 0 } ); + assert!(r.root_indexed_views.is_empty()); + let table = RootParam { + slot: 7, + ..param(Table, 10, 1) + }; + let indexed = track_words(&code, &[param(Constants, 6, 1), table], HwStage::Ms); + assert_eq!( + indexed.root_indexed_views, + [RootIndexedView { + table_slot: 7, + constant_slot: 0, + constant_dword: 0, + byte_offset: 0, + shift: 5, + }] + ); + let nonconstant = track_words(&code, &[param(Table, 6, 1), table], HwStage::Ms); + assert!(nonconstant.root_indexed_views.is_empty()); } #[test] @@ -1951,6 +2639,134 @@ pub(crate) mod tests { ); } + /// Two paths add an index to one table in the code and meet before one load + /// (hair `CS_InterpolateStrands`): the join is the computed term, counted + /// from the `s_getpc_b64`. + #[test] + fn two_paths_into_one_code_table_load() { + let r = track_words( + &[ + 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3] + 0x8002_FF02, + 0x0000_0040, // s_add_u32 s2, s2, 0x40 + 0x8203_8003, // s_addc_u32 s3, s3, 0 + 0xBF06_8001, // 0x10: s_cmp_eq_u32 s1, 0 + 0xBF85_0005, // 0x14: s_cbranch_scc1 -> 0x2c + 0xD70F_0457, + 0x0000_054A, // 0x18: v_add_co_u32 v87, s4, v74, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0xBF82_0004, // 0x28: s_branch -> 0x3c + 0xD70F_0457, + 0x0000_054B, // 0x2c: v_add_co_u32 v87, s4, v75, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0xDC34_8000, + 0x577D_0057, // 0x3c: global_load_dwordx2 v[87:88], v[87:88], null + S_ENDPGM, + ], + &[], + HwStage::Cs, + ); + assert_eq!(r.scalar.len(), 1); + let a = r.scalar[0].1; + assert_eq!((a.param, a.offset), (CODE, 0)); + assert!(a.dynamic.is_some(), "the join is the computed term, the byte in the code"); + } + + /// An address into a table in the code computed per lane and taken from + /// the first lane (`avgLuminanceCompute` `ColorDownsample`): the per-lane + /// sum carries the `s_getpc_b64` base, so the first-lane read is looked + /// through and the lane's index is the computed term. (A first-lane read + /// of an index alone stays the computed term itself; see + /// `the_console_waterfall_over_a_first_lane_offset_is_one`.) + #[test] + fn a_code_table_address_taken_from_the_first_lane() { + let r = track_words( + &[ + 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3] + 0xD70F_0457, + 0x0000_054A, // v_add_co_u32 v87, s4, v74, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0x7E0C_0557, // v_readfirstlane_b32 s6, v87 + 0x7E0E_0558, // v_readfirstlane_b32 s7, v88 + 0xF400_0203, + 0xFA00_0000, // s_load_dword s8, s[6:7], 0x0 + S_ENDPGM, + ], + &[], + HwStage::Cs, + ); + assert_eq!(r.scalar.len(), 1); + let a = r.scalar[0].1; + assert_eq!((a.param, a.offset), (CODE, 4)); + assert!(a.dynamic.is_some(), "the lane's index is the computed term"); + } + + #[test] + fn a_descriptor_kept_per_lane_is_its_load_and_needs_no_waterfall() { + // The console compiler's way with a descriptor it joins per lane: + // the dwords go to VGPRs and come back from the first lane. Every + // lane holds the one load's dwords, so the descriptor is that load + // (`lane_copied`), and no waterfall is asked for. + let mut words = vec![ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + ]; + // v_mov_b32 v10.., s0..; v_readfirstlane_b32 s16.., v10.. + words.extend((0..8).map(|k| 0x7E00_0200 | (10 + k) << 17 | k)); + words.extend((0..8).map(|k| 0x7E00_0400 | (16 + k) << 17 | (0x100 + 10 + k))); + words.extend([ + 0xF000_1700, + 0x0004_0D06, // image_load v[13:15], v6, s[16:23] + S_ENDPGM, + ]); + let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps); + let load = (0, 2); + assert_eq!(r.scalar, [(load, at(0, 0))]); + let sources: Vec<_> = r.descriptors.iter().map(|d| &d.source).collect(); + assert_eq!(sources, [&Source::Loaded { load, first: 0 }]); + assert_eq!(r.lane_copied, [load]); + assert_eq!(r.waterfall, Waterfall::default()); + } + + #[test] + fn loads_at_one_first_lane_offset_have_one_address() { + // Two loads of the table entry at the offset v4 holds, each with + // its own first-lane read, as the console compiler loads a + // descriptor again wherever it needs it: one address, by which + // lowering knows them for the same descriptor. + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0x7E08_0504, // v_readfirstlane_b32 s4, v4 + 0xF40C_0201, + 0x0800_0000, // s_load_dwordx8 s[8:15], s[2:3], s4 + 0x7E0A_0504, // v_readfirstlane_b32 s5, v4 + 0xF40C_0401, + 0x0A00_0000, // s_load_dwordx8 s[16:23], s[2:3], s5 + 0xF000_1700, + 0x0004_0D06, // image_load v[13:15], v6, s[16:23] + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let [(_, a), (_, b)] = r.scalar[..] else { + panic!("{:?}", r.scalar) + }; + assert_eq!(a, b); + assert_eq!((a.param, a.offset), (0, 0)); + assert!( + a.dynamic.is_some(), + "the lane's offset is the computed term" + ); + } + #[test] fn descriptors_selected_by_scc_are_traced_per_outcome() { // Two buffer descriptors loaded from the table at s9 and one @@ -2293,7 +3109,7 @@ pub(crate) mod tests { 0xBF81_0000, // s_endpgm ]; - /// The console compiler's waterfall (Grand Theft Auto VI's ray-tracing + /// The console compiler's waterfall (the title's ray-tracing /// resolve and others): each lane holds its entry's byte offset in the /// table at s0 (v7 = (lane & 1) * 32); the loop reads the first active /// lane's offset, narrows EXEC to the lanes with the same one @@ -3076,4 +3892,46 @@ pub(crate) mod tests { assert_eq!(r.waterfall.compares.len(), 2); assert_eq!(r.waterfall.reads.len(), 4); } + + /// codec_d, cool_fox f4b48ad (2da4beb386509b77). + #[test] + fn a_guarded_access_excludes_dead_lane_edges_at_a_join() { + // Lanes failing `v_cmp_gt_u32` clear EXEC and take `s_cbranch_execz` + // directly to the join block without initializing the immediate + // sampler `s[8:11]`. The join's `image_sample_lz` is guarded by EXEC, + // so only the arm where `s[8:11]` was built can execute it. + let code: Vec<u8> = [ + 0xBE84_0300u32, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x877E_6A7E, // s_and_b32 exec_lo, exec_lo, vcc_lo + 0xBF88_0004, // s_cbranch_execz -> join (skips 4 dwords) + 0xBE88_0380, // s_mov_b32 s8, 0 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let structured = lanes(&p).expect("structured form"); + assert!(structured.guards[2][0].is_some(), "join access must carry an EXEC guard"); + let r = track(&p, &[param(Table, 0, 1)], HwStage::Cs, Some(&structured)).unwrap(); + assert!( + r.descriptors + .iter() + .any(|d| d.role == Role::Sampler && d.source == Source::Constant(vec![0; 4])), + "guarded join should resolve the immediate sampler from the live arm: {:?}", + r.descriptors + ); + } } diff --git a/crates/victory-shader/src/spill.rs b/crates/victory-shader/src/spill.rs new file mode 100644 index 0000000000..a0feb6aeb3 --- /dev/null +++ b/crates/victory-shader/src/spill.rs @@ -0,0 +1,380 @@ +//! The spilled user-data table of a compute program. +//! +//! A compute program has as many user SGPRs as `COMPUTE_PGM_RSRC2` says. A +//! root signature that needs more dwords than that keeps none of its +//! parameters in registers: user-data dwords 0 and 1 then hold the 40-bit +//! address of a table in memory (`s0`, and `s1 & 0xff` as bits 32-39), and +//! the parameter the layout declares at user-data index N (16 or above) is +//! at byte `4 * (N - 16)` of that table. The code reads it with +//! `s_load_dword*` through that pointer. (Every compute program of the +//! console's ray-tracing structure builder, `XboxBvhBuilder.dll`, is of this +//! kind; measured there: 118 of 118 such loads land on a declared parameter.) +//! +//! [`user_data`] rewrites those loads away: each dword they read becomes the +//! entry value of the SGPR its user-data index names, as if the parameter +//! had arrived in a register. Resource tracking and lowering then treat a +//! spilled parameter like any other (the host binds user data by root slot +//! and dword, not by register). + +use crate::ShaderError; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{self, Program, Reg, Value}; +use crate::native::{HwStage, NativeProgram, StageIo}; + +/// The user-data index of the table's first dword. +const FIRST: u32 = 16; + +/// [`ir::build`] of `native`'s code as the hardware runs it, with the loads +/// of a spilled user-data table rewritten ([`user_data`]). +pub fn build(native: &NativeProgram) -> Result<Program, ShaderError> { + let mut p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + user_data(&mut p, native); + Ok(p) +} + +/// Whether `native` is a compute program that keeps its root parameters in +/// a spilled user-data table (see the module): the entries no register +/// holds, as (first user-data index, dwords), if the table starts at index +/// 16 and the program has the two registers of its address. +fn spilled(native: &NativeProgram) -> Option<Vec<(u32, u32)>> { + let StageIo::Cs(cs) = &native.io else { + return None; + }; + if native.stage != HwStage::Cs { + return None; + } + let registers = u32::from(cs.user_sgprs()); + let spilled: Vec<(u32, u32)> = native + .layout + .iter() + .filter(|e| e.sgprs > 0 && u32::from(e.user_data) >= registers) + .map(|e| (u32::from(e.user_data), e.sgprs)) + .collect(); + // Only the one arrangement seen: the table starts at index 16. + (spilled.iter().map(|e| e.0).min() == Some(FIRST) && registers >= 2).then_some(spilled) +} + +/// Whether `native` reads its root parameters from a spilled user-data +/// table. (In the title exactly the compute programs of the +/// console's ray-tracing structure builder do.) +pub fn is_spilled(native: &NativeProgram) -> bool { + spilled(native).is_some() +} + +/// Rewrites the loads of `native`'s spilled user-data table in `p`; returns +/// how many loads it replaced. Nothing changes unless the program is a +/// compute program whose layout has entries past its user SGPRs, the first +/// at index 16. A load is left alone (and resource tracking then refuses it +/// as before) when its offset is not a constant on a dword, or when a dword +/// it reads and the program uses is in no layout entry. +pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize { + let Some(spilled) = spilled(native) else { + return 0; + }; + let entry = |reg: Reg, p: &Program| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1); + let (Some(low), Some(high)) = (entry(Reg::S(0), p), entry(Reg::S(1), p)) else { + return 0; + }; + + // The pointer's halves: `s0` and its copies, `s1 & 0xff` and its copies. + let mut lows = vec![low]; + let mut highs: Vec<Value> = Vec::new(); + let mut raw_highs = vec![high]; + // Instructions that only form the pointer: dropped when nothing reads + // them any more. + let mut forming: Vec<(usize, usize)> = Vec::new(); + loop { + let mut changed = false; + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + let Fields::Sop { dst, src, .. } = &inst.fields else { + continue; + }; + let Some(Operand::Scalar { code: d, .. }) = *dst else { + continue; + }; + let Some(out) = inst.write(Reg::S(d)) else { + continue; + }; + let read = |op: &Operand| match *op { + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + _ => None, + }; + let found = match (inst.name(), &src[..]) { + ("s_mov_b32", [s]) => match read(s) { + Some(v) if lows.contains(&v) => Some(&mut lows), + Some(v) if highs.contains(&v) => Some(&mut highs), + Some(v) if raw_highs.contains(&v) => Some(&mut raw_highs), + _ => None, + }, + ("s_and_b32", [x, y]) => { + let masked = |a: &Operand, m: &Operand| { + matches!(*m, Operand::Literal(0xff)) + && read(a).is_some_and(|v| raw_highs.contains(&v)) + }; + (masked(x, y) || masked(y, x)).then_some(&mut highs) + } + _ => None, + }; + if let Some(set) = found + && !set.contains(&out) + { + set.push(out); + forming.push((b, i)); + changed = true; + } + } + } + if !changed { + break; + } + } + if highs.is_empty() { + return 0; + } + + // Values some instruction or phi reads. + let mut read_somewhere = std::collections::HashSet::new(); + for block in &p.blocks { + read_somewhere.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied())); + read_somewhere.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1))); + } + let mut next = p + .inputs + .iter() + .map(|i| i.1) + .chain(p.blocks.iter().flat_map(|b| { + b.phis + .iter() + .map(|phi| phi.value) + .chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1))) + })) + .map(|v| v.0 + 1) + .max() + .unwrap_or(0); + + // Each load through the pointer: its dwords become entry values. + let mut replaced: std::collections::HashMap<Value, Value> = Default::default(); + let mut gone: Vec<(usize, usize)> = Vec::new(); + let mut inputs = p.inputs.clone(); + for (b, block) in p.blocks.iter().enumerate() { + 'insts: for (i, inst) in block.insts.iter().enumerate() { + let Fields::Smem { + data: Some(Operand::Scalar { code: first, .. }), + base: Operand::Scalar { code: base, .. }, + offset, + soffset, + .. + } = inst.fields + else { + continue; + }; + if !inst.name().starts_with("s_load_dword") + || !matches!(soffset, Operand::Scalar { code: NULL, .. } | Operand::Const(128)) + || offset < 0 + || offset % 4 != 0 + || !inst.read(Reg::S(base)).is_some_and(|v| lows.contains(&v)) + || !inst.read(Reg::S(base + 1)).is_some_and(|v| highs.contains(&v)) + { + continue; + } + let mut dwords = Vec::new(); + for &(reg, v) in &inst.writes { + let Reg::S(code) = reg else { + continue 'insts; + }; + let Some(k) = code.checked_sub(first) else { + continue 'insts; + }; + let index = FIRST + offset as u32 / 4 + u32::from(k); + let declared = spilled.iter().any(|&(at, n)| index >= at && index < at + n); + if !declared { + if read_somewhere.contains(&v) { + continue 'insts; + } + continue; + } + // SGPR codes end at 105; no root signature reaches there. + let Ok(code) = u8::try_from(index) else { + continue 'insts; + }; + if code > 105 { + continue 'insts; + } + dwords.push((Reg::S(code), v)); + } + for (reg, v) in dwords { + let value = match inputs.iter().find(|e| e.0 == reg) { + Some(e) => e.1, + None => { + let value = Value(next); + next += 1; + inputs.push((reg, value)); + value + } + }; + replaced.insert(v, value); + } + gone.push((b, i)); + } + } + if gone.is_empty() { + return 0; + } + p.inputs = inputs; + let renamed = |v: &mut Value| { + if let Some(&to) = replaced.get(v) { + *v = to; + } + }; + for block in &mut p.blocks { + for phi in &mut block.phis { + phi.args.iter_mut().for_each(renamed); + } + for inst in &mut block.insts { + inst.reads.iter_mut().for_each(|r| renamed(&mut r.1)); + } + } + // The loads go, then what only formed the pointer (last first, so a + // copy goes before what it copied). + let mut drop = gone.clone(); + loop { + let read_somewhere = { + let mut used = std::collections::HashSet::new(); + for (b, block) in p.blocks.iter().enumerate() { + used.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied())); + for (i, inst) in block.insts.iter().enumerate() { + if !drop.contains(&(b, i)) { + used.extend(inst.reads.iter().map(|r| r.1)); + } + } + } + used + }; + let before = drop.len(); + for &site in &forming { + let inst = &p.blocks[site.0].insts[site.1]; + if !drop.contains(&site) && inst.writes.iter().all(|w| !read_somewhere.contains(&w.1)) { + drop.push(site); + } + } + if drop.len() == before { + break; + } + } + for (b, block) in p.blocks.iter_mut().enumerate() { + let mut i = 0; + block.insts.retain(|_| { + i += 1; + !drop.contains(&(b, i - 1)) + }); + } + // The pointer's registers are no inputs once nothing reads them. + let mut read = std::collections::HashSet::new(); + for block in &p.blocks { + read.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied())); + read.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1))); + } + p.inputs + .retain(|&(reg, v)| !matches!(reg, Reg::S(0 | 1)) || read.contains(&v)); + gone.len() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::native::{ComputeIo, RootParam, RootType}; + + fn param(root: RootType, user_data: u8, sgprs: u32, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + } + } + + /// A compute program with `registers` user SGPRs and the group id after + /// them. + fn native(words: &[u32], registers: u32, layout: Vec<RootParam>) -> NativeProgram { + NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout, + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: registers << 1 | 1 << 7, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } + } + + // s_and_b32 s3, s1, 0xff; s_mov_b32 s2, s0; s_load_dword s5, s[2:3], + // 0x10; s_load_dwordx2 s[0:1], s[2:3], 0; s_endpgm. + const TABLE: [u32; 8] = [ + 0x8703_FF01, + 0x0000_00FF, + 0xBE82_0300, + 0xF400_0141, + 0xFA00_0010, + 0xF404_0001, + 0xFA00_0000, + 0xBF81_0000, + ]; + + #[test] + fn loads_of_the_spilled_table_become_entry_registers() { + let n = native( + &TABLE, + 4, + vec![ + param(RootType::Descriptor, 16, 2, 0), + param(RootType::Descriptor, 18, 2, 1), + param(RootType::Constants, 20, 16, 2), + ], + ); + let mut p = ir::build(&n.code, false, 256).unwrap(); + assert_eq!(user_data(&mut p, &n), 2); + let names: Vec<&str> = p.blocks.iter().flat_map(|b| &b.insts).map(|i| i.name()).collect(); + assert!(!names.iter().any(|n| n.starts_with("s_load_")), "{names:?}"); + // The pointer is gone with the loads; byte 0x10 is index 20, the + // first root constant, and bytes 0-7 are the first root view. + let mut regs: Vec<Reg> = p.inputs.iter().map(|i| i.0).collect(); + regs.sort(); + assert_eq!(regs, [Reg::S(16), Reg::S(17), Reg::S(20)]); + } + + #[test] + fn parameters_in_registers_are_left_alone() { + // The same code where s0 and s1 are a root view the layout declares. + let n = native(&TABLE, 6, vec![param(RootType::Descriptor, 0, 2, 0)]); + let mut p = ir::build(&n.code, false, 256).unwrap(); + let before = p.clone(); + assert_eq!(user_data(&mut p, &n), 0); + assert_eq!(p, before); + } + + #[test] + fn a_used_dword_no_parameter_declares_keeps_its_load() { + // As above with `s_mov_b32 s6, s5` before the end: the dword at + // byte 0x10 (index 20) is read, and here nothing declares it. + let mut words = TABLE.to_vec(); + words.insert(7, 0xBE86_0305); + let n = native(&words, 4, vec![param(RootType::Descriptor, 16, 2, 0)]); + let mut p = ir::build(&n.code, false, 256).unwrap(); + assert_eq!(user_data(&mut p, &n), 1); + let loads = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| i.name().starts_with("s_load_")) + .count(); + assert_eq!(loads, 1); + // The pointer is still read, by the load that stays. + assert!(p.inputs.iter().any(|i| i.0 == Reg::S(0))); + } +} diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index 0f7b016425..afeec826a9 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -68,42 +68,6 @@ pub struct Bools { /// The tables below have small integer keys; SipHash dominated run time. type Map<K, V> = HashMap<K, V, BuildHasherDefault<Fx>>; -type Set<K> = HashSet<K, BuildHasherDefault<Fx>>; - -/// A set of what a walk has met: a list scan while it is small (most lane -/// masks are a handful of nodes), a hash set once it grows. -struct Seen<T> { - list: Vec<T>, - set: Set<T>, -} - -impl<T> Default for Seen<T> { - fn default() -> Self { - Seen { - list: Vec::new(), - set: Set::default(), - } - } -} - -impl<T: Copy + Eq + std::hash::Hash> Seen<T> { - const SCAN: usize = 32; - - /// Adds `x`; false if it was already in. - fn insert(&mut self, x: T) -> bool { - if self.set.is_empty() { - if self.list.contains(&x) { - return false; - } - if self.list.len() < Self::SCAN { - self.list.push(x); - return true; - } - self.set.extend(self.list.drain(..)); - } - self.set.insert(x) - } -} /// FxHash's multiply-rotate step. #[derive(Default)] @@ -135,11 +99,18 @@ impl Hasher for Fx { const TERMINAL: u32 = u32::MAX; const MAX_NODES: usize = 1 << 21; -/// Cap the `ite` memo table so complex shaders cannot trigger multi-tens-of-MB -/// HashMap resizes (e.g. 35 MB at 2^21 buckets) under concurrent compilation. -const MAX_MEMO: usize = 1 << 18; /// Case splits [`Bools::meet`] makes before it gives up. const MAX_MEET: usize = 1 << 16; +/// Conditions [`Meets`] keeps; past that, they are searched anew. +const MAX_MEETS: usize = 1 << 18; + +/// What [`Bools::meet`] found out about one [`Bools`], for its later calls: +/// the conditions no lane satisfies, and the case splits it took to find +/// that out of each. +#[derive(Debug, Default)] +pub struct Meets { + none: Map<Box<[u32]>, usize>, +} impl Bools { fn new() -> Self { @@ -171,18 +142,15 @@ impl Bools { vars.into_iter().map(|v| self.atoms[v as usize]).collect() } - /// The variables `b` tests, in the order a depth-first walk meets them. - /// Each node is visited once: scanning lists of every node and variable - /// seen made this quadratic in the size of `b`. fn vars(&self, b: Bool) -> Vec<u32> { - let (mut seen, mut found) = (Seen::default(), Seen::default()); - let (mut vars, mut stack) = (Vec::new(), vec![b]); + let (mut seen, mut vars, mut stack) = (Vec::new(), Vec::new(), vec![b]); while let Some(b) = stack.pop() { let (v, lo, hi) = self.nodes[b.0 as usize]; - if v == TERMINAL || !seen.insert(b) { + if v == TERMINAL || seen.contains(&b) { continue; } - if found.insert(v) { + seen.push(b); + if !vars.contains(&v) { vars.push(v); } stack.extend([lo, hi]); @@ -226,9 +194,6 @@ impl Bools { } fn ite(&mut self, f: Bool, g: Bool, h: Bool) -> Bool { - if self.overflow { - return Bool::FALSE; - } if f == Bool::TRUE || g == h { return g; } @@ -247,12 +212,7 @@ impl Bools { let lo = self.ite(f0, g0, h0); let hi = self.ite(f1, g1, h1); let r = self.mk(v, lo, hi); - if !self.overflow { - if self.memo.len() >= MAX_MEMO { - self.memo.clear(); - } - self.memo.insert((f, g, h), r); - } + self.memo.insert((f, g, h), r); r } @@ -277,7 +237,99 @@ impl Bools { /// `b` where `holds`, its negation where not. Yes when the search grows /// too large to finish. pub fn meet(&self, all: &[(Bool, bool)]) -> bool { - Meet::new(self).solve(all.to_vec()) + self.meet_seen(all, &mut Meets::default()) + } + + /// [`Self::meet`], which looks up in `seen` what earlier calls on these + /// `Bools` found out and adds what it finds. The answer is the one + /// `meet` gives. + pub fn meet_seen(&self, all: &[(Bool, bool)], seen: &mut Meets) -> bool { + self.meet_within(all, MAX_MEET, seen) + } + + /// [`Self::meet_seen`] with `budget` case splits. + fn meet_within(&self, all: &[(Bool, bool)], mut budget: usize, seen: &mut Meets) -> bool { + let mut work = all + .iter() + .map(|&(b, holds)| b.0 << 1 | u32::from(holds)) + .collect(); + self.meet_in(0, &mut work, &mut budget, seen) + } + + /// The search of [`Self::meet`] for the conditions `work[at..]` (a node + /// doubled, plus one where it must hold), which it takes off `work`. + /// + /// The search is a case split on the top variable, and the cofactors of + /// a few large functions come down to the same conditions over and over + /// (a block's reach under a mask and under its negation share most of + /// their nodes), so splitting each anew is exponential where the + /// distinct conditions are few. `seen` keeps the conditions that no lane + /// satisfies with the case splits it took to find that out: meeting + /// them again takes those splits off the budget at once. A search + /// therefore gives up exactly where one that split everything anew + /// would (nothing below such conditions ends it early, so it either + /// makes all those splits or runs out among them), and gives the same + /// answer. + fn meet_in( + &self, + at: usize, + work: &mut Vec<u32>, + budget: &mut usize, + seen: &mut Meets, + ) -> bool { + // Constants either fail or say nothing. + let mut kept = at; + for i in at..work.len() { + let (b, holds) = (work[i] >> 1, work[i] & 1 != 0); + if b > Bool::TRUE.0 { + work[kept] = work[i]; + kept += 1; + } else if (b == Bool::TRUE.0) != holds { + work.truncate(at); + return false; + } + } + work.truncate(kept); + if kept == at || *budget == 0 { + work.truncate(at); + return true; + } + // As a set: neither order nor repeats change the search. + work[at..].sort_unstable(); + let mut end = at + 1; + for i in at + 1..kept { + if work[i] != work[end - 1] { + work[end] = work[i]; + end += 1; + } + } + work.truncate(end); + if let Some(&splits) = seen.none.get(&work[at..]) { + let within = splits <= *budget; + *budget = budget.saturating_sub(splits); + work.truncate(at); + return !within; + } + let before = *budget; + *budget -= 1; + let top = |code: u32| self.nodes[(code >> 1) as usize].0; + let v = work[at..].iter().map(|&c| top(c)).min().expect("not empty"); + let mut found = false; + for value in [false, true] { + for i in at..end { + let (lo, hi) = self.split(Bool(work[i] >> 1), v); + work.push((if value { hi } else { lo }).0 << 1 | work[i] & 1); + } + if self.meet_in(end, work, budget, seen) { + found = true; + break; + } + } + if !found && seen.none.len() < MAX_MEETS { + seen.none.insert(work[at..end].into(), before - *budget); + } + work.truncate(at); + found } fn implies(&mut self, a: Bool, b: Bool) -> bool { @@ -288,9 +340,6 @@ impl Bools { /// `b` with every atom born at reverse-postorder index `from` or later /// existentially quantified: what still holds once those are redefined. fn forget(&mut self, b: Bool, from: usize, memo: &mut Map<Bool, Bool>) -> Bool { - if self.overflow { - return Bool::FALSE; - } let (v, lo, hi) = self.nodes[b.0 as usize]; if v == TERMINAL { return b; @@ -309,271 +358,37 @@ impl Bools { r } - /// `b` with every variable in `values` (sorted by variable) replaced by - /// its value. Nothing below a node testing a later variable than the - /// last of them changes. - fn restrict(&mut self, b: Bool, values: &[(u32, bool)], memo: &mut Map<Bool, Bool>) -> Bool { - let (v, lo, hi) = self.nodes[b.0 as usize]; - if v == TERMINAL || values.last().is_none_or(|&(last, _)| v > last) { + fn restrict(&mut self, b: Bool, v: u32, value: bool, memo: &mut Map<Bool, Bool>) -> Bool { + let (bv, lo, hi) = self.nodes[b.0 as usize]; + if bv == TERMINAL || bv > v { return b; } + if bv == v { + return if value { hi } else { lo }; + } if let Some(&r) = memo.get(&b) { return r; } - let decided = values.binary_search_by_key(&v, |&(v, _)| v).ok(); - let r = match decided { - Some(i) => self.restrict(if values[i].1 { hi } else { lo }, values, memo), - None => { - let l = self.restrict(lo, values, memo); - let h = self.restrict(hi, values, memo); - self.mk(v, l, h) - } - }; - // While only decided nodes were walked the walk is one path, which - // meets no node twice: the table (and its allocation) can wait. - if decided.is_none() || !memo.is_empty() { - memo.insert(b, r); - } + let l = self.restrict(lo, v, value, memo); + let h = self.restrict(hi, v, value, memo); + let r = self.mk(bv, l, h); + memo.insert(b, r); r } - /// `b` with each atom that `known` decides replaced by its value. The - /// atoms are replaced together, in one walk of `b`: cofactors for - /// different variables commute, and a walk per atom made this cost the - /// size of `b` times the number of atoms. - fn given(&mut self, b: Bool, known: Bool) -> Bool { - let mut values = Vec::new(); + /// `b` with each atom that `known` decides replaced by its value. + fn given(&mut self, mut b: Bool, known: Bool) -> Bool { for v in self.vars(b) { let x = self.mk(v, Bool::FALSE, Bool::TRUE); let nx = self.not(x); if self.implies(known, x) { - values.push((v, true)); + b = self.restrict(b, v, true, &mut Map::default()); } else if self.implies(known, nx) { - values.push((v, false)); + b = self.restrict(b, v, false, &mut Map::default()); } } - if values.is_empty() { - return b; - } - values.sort_unstable(); - self.restrict(b, &values, &mut Map::default()) - } -} - -/// Ephemeral SAT solver for [`Bools::meet`] over immutable BDD nodes. -struct Meet<'a> { - bools: &'a Bools, - extra: Vec<(u32, Bool, Bool)>, - extra_unique: Map<(u32, Bool, Bool), Bool>, - restrict_memo: Map<Bool, Bool>, - forced: Map<u32, bool>, - failed: HashSet<Vec<(Bool, bool)>, BuildHasherDefault<Fx>>, - budget: usize, - overflow: bool, -} - -impl<'a> Meet<'a> { - fn new(bools: &'a Bools) -> Self { - Self { - bools, - extra: Vec::new(), - extra_unique: Map::default(), - restrict_memo: Map::default(), - forced: Map::default(), - failed: HashSet::with_hasher(BuildHasherDefault::default()), - budget: MAX_MEET, - overflow: false, - } - } - - fn node(&self, b: Bool) -> (u32, Bool, Bool) { - let idx = b.0 as usize; - if idx < self.bools.nodes.len() { - self.bools.nodes[idx] - } else { - self.extra[idx - self.bools.nodes.len()] - } - } - - fn split(&self, b: Bool, v: u32) -> (Bool, Bool) { - match self.node(b) { - (bv, lo, hi) if bv == v => (lo, hi), - _ => (b, b), - } - } - - fn mk(&mut self, v: u32, lo: Bool, hi: Bool) -> Bool { - if lo == hi { - return lo; - } - if let Some(&b) = self.bools.unique.get(&(v, lo, hi)) { - return b; - } - if let Some(&b) = self.extra_unique.get(&(v, lo, hi)) { - return b; - } - if self.extra.len() >= MAX_NODES - || self.bools.nodes.len() + self.extra.len() >= u32::MAX as usize - { - self.overflow = true; - return Bool::FALSE; - } - let b = Bool((self.bools.nodes.len() + self.extra.len()) as u32); - self.extra.push((v, lo, hi)); - self.extra_unique.insert((v, lo, hi), b); b } - - fn restrict(&mut self, b: Bool, forced: &Map<u32, bool>, max_v: u32) -> Bool { - let (bv, lo, hi) = self.node(b); - if bv == TERMINAL || bv > max_v || self.overflow { - return b; - } - if let Some(&r) = self.restrict_memo.get(&b) { - return r; - } - let r = if let Some(&value) = forced.get(&bv) { - self.restrict(if value { hi } else { lo }, forced, max_v) - } else { - let l = self.restrict(lo, forced, max_v); - let h = self.restrict(hi, forced, max_v); - if self.overflow { - return Bool::FALSE; - } - if l == lo && h == hi { - b - } else { - self.mk(bv, l, h) - } - }; - self.restrict_memo.insert(b, r); - r - } - - /// Canonicalizes constraints and propagates forced top-variable assignments to - /// a fixed point before branching into larger BDDs. - fn propagate(&mut self, all: &mut Vec<(Bool, bool)>) -> Option<bool> { - loop { - let mut i = 0; - while i < all.len() { - let (b, holds) = all[i]; - if b == if holds { Bool::FALSE } else { Bool::TRUE } { - return Some(false); - } - if b == Bool::FALSE || b == Bool::TRUE { - all.swap_remove(i); - } else { - i += 1; - } - } - all.sort_unstable(); - all.dedup(); - if all.windows(2).any(|w| w[0].0 == w[1].0 && w[0].1 != w[1].1) { - return Some(false); - } - if all.len() <= 1 { - // Any single non-constant reduced ROBDD node attains both `false` and `true`. - return Some(true); - } - - let mut forced = std::mem::take(&mut self.forced); - forced.clear(); - let mut max_v = 0u32; - let mut conflict = false; - for &(b, holds) in all.iter() { - let (v, lo, hi) = self.node(b); - debug_assert_ne!(v, TERMINAL); - let bad = if holds { Bool::FALSE } else { Bool::TRUE }; - let req = if lo == bad { - Some(true) - } else if hi == bad { - Some(false) - } else { - None - }; - if let Some(val) = req { - if let Some(prev) = forced.insert(v, val) { - if prev != val { - conflict = true; - break; - } - } else { - max_v = max_v.max(v); - } - } - } - if conflict { - self.forced = forced; - return Some(false); - } - if forced.is_empty() { - self.forced = forced; - return None; - } - self.restrict_memo.clear(); - for (b, _) in all.iter_mut() { - *b = self.restrict(*b, &forced, max_v); - } - self.forced = forced; - if self.overflow { - return Some(true); - } - } - } - - fn solve(&mut self, mut all: Vec<(Bool, bool)>) -> bool { - if self.bools.overflow { - return true; - } - if let Some(res) = self.propagate(&mut all) { - return res; - } - if self.failed.contains(&all) { - return false; - } - if self.budget == 0 { - return true; - } - self.budget -= 1; - let v = all - .iter() - .map(|&(b, _)| self.node(b).0) - .min() - .expect("not empty"); - let mut score = [0usize; 2]; - for &(b, holds) in &all { - let (bv, lo, hi) = self.node(b); - if bv == v { - let good = if holds { Bool::TRUE } else { Bool::FALSE }; - if lo == good { - score[0] += 1; - } - if hi == good { - score[1] += 1; - } - } - } - let order = if score[1] > score[0] { - [true, false] - } else { - [false, true] - }; - for value in order { - let next = all - .iter() - .map(|&(b, holds)| { - let (lo, hi) = self.split(b, v); - (if value { hi } else { lo }, holds) - }) - .collect(); - if self.solve(next) { - return true; - } - } - // Both branches returned false cleanly, so `all` is genuinely UNSAT. - self.failed.insert(all); - false - } } /// How a lane leaves a block. @@ -607,17 +422,27 @@ pub struct Structured { pub reach: Vec<Bool>, /// The lane's bit of each lane-mask value, by its low dword's value. pub masks: HashMap<Value, Bool>, - /// Symbolic select conditions, keyed by the destination SSA value. - /// A wave64 condition belongs to the exact pair read by the select. - pub(crate) select_masks: HashMap<Value, Bool>, /// Exact Wave64 pairs for checking masks at their uses. paired_masks: Map<Key, Bool>, /// Wave64 masks: low dword's value by the high dword's. pub highs: HashMap<Value, Value>, /// Masks (low dwords) set only in lanes whose EXEC bit is set where /// they are written: every such lane reaches the writing block, so a - /// ballot there gives the mask as data. + /// ballot there gives the mask as data. No split low dword, as in + /// `masks`. pub active: HashSet<Value>, + /// Incoming lane boolean per predecessor edge (in block predecessor order) + /// for each [`Atom::Phi`] id. + pub phi_masks: HashMap<Value, Vec<Bool>>, + /// Blocks whose closing branch the whole wave takes together ([`structure_wide`]): its + /// `when` is still the lane's own bit; the wave goes by all of them. + pub wide: HashSet<usize>, + /// Per block closed by a branch on a lane mask: whether the console takes it when some + /// lane's `when` holds (`true`) or when every lane's does (`false`). + pub wave_any: Vec<Option<bool>>, + /// SCC values a mask operation sets when some lane's bit of its result is set, with that + /// lane bit: as data such an SCC is "some lane of the wave has it". + pub scc_some: HashMap<Value, Bool>, } impl Structured { @@ -632,15 +457,32 @@ impl Structured { /// Builds the per-lane form of `program`. pub fn structure(program: &Program) -> Result<Structured, ShaderError> { + structure_wide(program, &HashSet::new()) +} + +/// [`structure`], with the branches that close the blocks of `wide` kept as the console has +/// them: one decision for the whole wave (`s_cbranch_execz` and `vccz`: taken when no lane's +/// bit is set; `execnz` and `vccnz`: when some lane's is; SCC of a mask operation likewise, +/// [`Structured::wave_any`]), which every lane follows. A lane +/// then learns nothing about its own bit from the way it went, so past such a branch EXEC +/// stays a guard on every vector instruction, as it is on the console. For a console wave +/// run as two host waves, which exchange that decision and can then meet (a group barrier) +/// inside the branch. +pub fn structure_wide(program: &Program, wide: &HashSet<usize>) -> Result<Structured, ShaderError> { let mut l = Lanes::new(program)?; + l.wide = wide.clone(); loop { let execs = l.masks_in_order(); let cond = l.paths()?; - let wrong = l.wrong_joins(&cond); - if wrong.is_empty() { + let (wrong, new_derived) = l.check_joins(&cond); + if l.b.overflow { + return Err(TOO_LARGE); + } + if wrong.is_empty() && new_derived.is_empty() { return l.finish(&execs, &cond); } l.unresolved.extend(wrong); + l.derived_phis.extend(new_derived); l.reset(); } } @@ -662,23 +504,39 @@ struct Lanes<'a> { phis: Map<Value, (usize, usize)>, /// Mask joins found wrong when resolved to a constant: atoms instead. unresolved: HashSet<Value>, + /// Phi ids whose joins depend on EXEC or VALU results (including along + /// back edges), carried across resets so their joins stay in `masks`. + derived_phis: HashSet<Value>, b: Bools, /// Masks derived from EXEC and VALU results. masks: Map<Key, Bool>, /// Other values read as masks: constants, uniform selects, opaque ones. other: Map<Key, Bool>, - select_masks: HashMap<Value, Bool>, + /// Pairs read as masks that `mask` does not see: carry-ins, and pairs + /// joins take over back edges. + seen: Vec<Key>, /// For branches: SCC of a mask operation ("some lane is set") as the /// lane's own bit. scc_lane: Map<Value, Bool>, /// Joins resolved to a constant, to check once all edges are known. joins: Vec<Join>, + /// [`Atom::Phi`] joins created in the current pass, resolved in + /// `check_joins` and exported in `finish`. + phi_joins: Vec<PhiJoin>, + phi_join_ids: HashSet<Value>, /// Per block: what a lane knows on entry, over forward edges only. first: Vec<Bool>, /// Per block ending in a branch: when a lane takes it. when: Vec<Option<Bool>>, /// See [`Structured::active`]. active: HashSet<Value>, + /// See [`Structured::wide`]. + wide: HashSet<usize>, + /// SCC values of [`Self::scc_lane`] that are set when EVERY lane's bit is (`s_cmp_eq` of + /// two masks: "no lane differs"); the others are set when some lane's is. + scc_every: HashSet<Value>, + /// See [`Structured::wave_any`]. + wave_any: Vec<Option<bool>>, } /// A mask join taken as `value` in every lane that reaches `block`: each @@ -688,6 +546,16 @@ struct Join { /// The phi value naming the join. id: Value, value: bool, + derived: bool, + args: Vec<Key>, +} + +/// A mask join represented as [`Atom::Phi`], whose incoming edge masks are +/// resolved once every block (including loop back edges) has been visited. +struct PhiJoin { + block: usize, + id: Value, + derived: bool, args: Vec<Key>, } @@ -734,15 +602,21 @@ impl<'a> Lanes<'a> { defs, phis, unresolved: HashSet::new(), + derived_phis: HashSet::new(), b: Bools::new(), masks: Map::default(), other: Map::default(), - select_masks: HashMap::new(), + seen: Vec::new(), scc_lane: Map::default(), joins: Vec::new(), + phi_joins: Vec::new(), + phi_join_ids: HashSet::new(), first: vec![Bool::FALSE; blocks.len()], when: vec![None; blocks.len()], active: HashSet::new(), + wide: HashSet::new(), + scc_every: HashSet::new(), + wave_any: vec![None; blocks.len()], }) } @@ -750,9 +624,13 @@ impl<'a> Lanes<'a> { self.b = Bools::new(); self.masks.clear(); self.other.clear(); - self.select_masks.clear(); + self.seen.clear(); self.scc_lane.clear(); + self.scc_every.clear(); + self.wave_any.fill(None); self.joins.clear(); + self.phi_joins.clear(); + self.phi_join_ids.clear(); self.first.fill(Bool::FALSE); self.when.fill(None); self.active.clear(); @@ -808,6 +686,7 @@ impl<'a> Lanes<'a> { && let Some(last) = p.blocks[b].insts.last() { self.when[b] = Some(self.branch(last)); + self.wave_any[b] = self.wave_kind(last); } } execs @@ -815,6 +694,10 @@ impl<'a> Lanes<'a> { /// `c` narrowed by the branch at the end of `q` towards one successor. fn edge(&mut self, c: Bool, q: usize, taken: bool) -> Bool { + if self.wide.contains(&q) { + // the wave's decision: it says nothing about this lane's own bit + return c; + } match self.when[q] { Some(w) if taken => self.b.and(c, w), Some(w) => { @@ -825,28 +708,61 @@ impl<'a> Lanes<'a> { } } - /// Joins whose constant fails on some edge, given what lanes know. - fn wrong_joins(&mut self, cond: &[Bool]) -> Vec<Value> { + /// Joins whose constant fails on some edge, and joins that need another + /// pass because a later edge turned out to derive from EXEC or VALU. + fn check_joins(&mut self, cond: &[Bool]) -> (Vec<Value>, Vec<Value>) { let mut wrong = Vec::new(); + let mut new_derived = Vec::new(); + let mut seen_derived = HashSet::new(); let mut j = 0; + let mut p = 0; // Checking an argument can resolve another join; it is checked too. - while j < self.joins.len() { - let (block, id, value) = (self.joins[j].block, self.joins[j].id, self.joins[j].value); - for (n, a) in self.joins[j].args.clone().into_iter().enumerate() { - let (q, taken) = self.incoming[block][n]; - let e = self.edge(cond[q], q, taken); - let mut m = self.mask(a).0; - if !value { - m = self.b.not(m); + while j < self.joins.len() || p < self.phi_joins.len() { + while j < self.joins.len() { + let (block, id, value, was_derived) = ( + self.joins[j].block, + self.joins[j].id, + self.joins[j].value, + self.joins[j].derived, + ); + let mut failed = false; + for (n, a) in self.joins[j].args.clone().into_iter().enumerate() { + let (q, taken) = self.incoming[block][n]; + let e = self.edge(cond[q], q, taken); + let (mut m, d) = self.mask(a); + if !was_derived + && d + && !self.derived_phis.contains(&id) + && seen_derived.insert(id) + { + new_derived.push(id); + } + if !value { + m = self.b.not(m); + } + if !failed && !self.b.implies(e, m) { + wrong.push(id); + failed = true; + } } - if !self.b.implies(e, m) { - wrong.push(id); - break; + j += 1; + } + while p < self.phi_joins.len() { + let (id, was_derived) = (self.phi_joins[p].id, self.phi_joins[p].derived); + for a in self.phi_joins[p].args.clone() { + let (_, d) = self.mask(a); + if !was_derived + && d + && !self.derived_phis.contains(&id) + && seen_derived.insert(id) + { + new_derived.push(id); + } } + p += 1; } - j += 1; } - wrong + (wrong, new_derived) } fn finish( @@ -854,6 +770,22 @@ impl<'a> Lanes<'a> { execs: &[Vec<Option<Bool>>], cond: &[Bool], ) -> Result<Structured, ShaderError> { + let phi_joins = std::mem::take(&mut self.phi_joins); + let mut phi_masks = HashMap::with_capacity(phi_joins.len()); + for pj in phi_joins { + let incoming: Vec<Bool> = pj + .args + .into_iter() + .enumerate() + .map(|(n, a)| { + let (q, taken) = self.incoming[pj.block][n]; + let e = self.edge(cond[q], q, taken); + let m = self.mask(a).0; + self.b.given(m, e) + }) + .collect(); + phi_masks.insert(pj.id, incoming); + } let blocks = &self.p.blocks; let b = &mut self.b; let guards = blocks @@ -892,6 +824,20 @@ impl<'a> Lanes<'a> { if self.b.overflow { return Err(TOO_LARGE); } + // Exports go by low dword. A low dword read with two high dwords + // (one rewritten alone) names no one mask: it is left out, so + // lowering refuses what reads it instead of taking the other + // pair's lanes 32-63. Not where the low dword holds a number: see + // the shortcut in `mask`. + let (mut high, mut split) = (Map::default(), HashSet::new()); + let keys = self.masks.keys().chain(self.other.keys()); + for &(lo, hi) in keys.chain(&self.seen) { + if *high.entry(lo).or_insert(hi) != hi { + split.insert(lo); + } + } + self.masks.retain(|k, _| !split.contains(&k.0)); + self.active.retain(|lo| !split.contains(lo)); Ok(Structured { masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), highs: self @@ -900,13 +846,17 @@ impl<'a> Lanes<'a> { .filter(|(lo, hi)| lo != hi) .map(|&(lo, hi)| (hi, lo)) .collect(), - select_masks: self.select_masks, - paired_masks: if self.p.wave64 { - self.masks - } else { - Map::default() - }, + paired_masks: if self.p.wave64 { self.masks } else { Map::default() }, active: self.active, + wide: self.wide, + wave_any: self.wave_any, + scc_some: self + .scc_lane + .iter() + .filter(|(scc, _)| !self.scc_every.contains(scc)) + .map(|(&scc, &m)| (scc, m)) + .collect(), + phi_masks, bools: self.b, exits, guards, @@ -931,56 +881,41 @@ impl<'a> Lanes<'a> { } } - fn exec(&mut self, inst: &Inst) -> Bool { - match self.key(|r| inst.read(r), EXEC) { - Some(k) => self.mask(k).0, - None => Bool::TRUE, - } - } - - /// The scalar a `v_readlane_b32` of a constant lane gives back: the one - /// a `v_writelane_b32` of the same lane put into that VGPR (the console - /// compiler spills scalars, lane masks among them, into VGPR lanes). - fn spilled(&self, v: Value) -> Option<Value> { - let at = |v: Value| { + /// The source pair of two adjacent dword moves in one block. + fn moved_pair(&self, k: Key) -> Option<Key> { + let moved = |v| { let &(b, i) = self.defs.get(&v)?; - Some(&self.p.blocks[b].insts[i]) - }; - let lane = |op: Option<&Operand>| match op { - Some(&Operand::Const(c @ 128..=192)) => Some(c - 128), - _ => None, - }; - let read = at(v)?; - let Fields::Valu(r) = &read.fields else { - return None; - }; - let k = lane(r.src.get(1)).filter(|_| read.name() == "v_readlane_b32")?; - let Some(&Operand::Vector { reg, .. }) = r.src.first() else { - return None; - }; - let mut vgpr = read.read(Reg::V(reg))?; - // shortcut: only a straight chain of lane writes; a phi or any other - // write of the VGPR ends the search (the mask stays opaque). - for _ in 0..64 { - let w = at(vgpr)?; - let Fields::Valu(w) = &w.fields else { - return None; - }; - if at(vgpr)?.name() != "v_writelane_b32" { + let inst = &self.p.blocks[b].insts[i]; + if inst.name() != "s_mov_b32" { return None; } - let (Some(&Operand::Scalar { code, .. }), Some(&Operand::Vector { reg, .. })) = - (w.src.first(), w.dst.as_ref()) + let Fields::Sop { + dst: Some(Operand::Scalar { code: dst, .. }), + src, + .. + } = &inst.fields else { return None; }; - let inst = at(vgpr)?; - if lane(w.src.get(1))? == k { - return inst.read(Reg::S(code)); + let [Operand::Scalar { code: src, .. }] = src.as_slice() else { + return None; + }; + if inst.write(Reg::S(*dst)) != Some(v) { + return None; } - vgpr = inst.read(Reg::V(reg))?; + Some((b, *dst, *src, inst.read(Reg::S(*src))?)) + }; + let (lb, ld, ls, lv) = moved(k.0)?; + let (hb, hd, hs, hv) = moved(k.1)?; + (lb == hb && ld.checked_add(1) == Some(hd) && ls.checked_add(1) == Some(hs)) + .then_some((lv, hv)) + } + + fn exec(&mut self, inst: &Inst) -> Bool { + match self.key(|r| inst.read(r), EXEC) { + Some(k) => self.mask(k).0, + None => Bool::TRUE, } - None } /// The mask a value pair holds, and whether it derives from EXEC or a @@ -992,30 +927,54 @@ impl<'a> Lanes<'a> { if let Some(&m) = self.other.get(&k) { return (m, false); } + // A scalar pair can be parked in two VGPR lanes and restored one + // dword at a time. The spill pass turns these into scalar moves. + // Recover the original lane predicate only when the two words + // still come from the same known mask, in their original order. + if self.p.wave64 { + let source = (self.move_source(k.0), self.move_source(k.1)); + if source != k && let Some(&m) = self.masks.get(&source) { + self.masks.insert(k, m); + return (m, true); + } + } let p = self.p; - let spilled = self - .spilled(k.0) - .zip(self.spilled(k.1)) - .filter(|&(a, b)| (a, b) != k); - let (m, derived) = match spilled.map(|s| self.mask(s)).or_else(|| self.join(k)) { + let (m, derived) = match self.join(k) { Some(join) => join, None => { let (lo, hi) = (self.defs.get(&k.0).copied(), self.defs.get(&k.1).copied()); let def = |d: Option<(usize, usize)>| d.map(|(b, i)| &p.blocks[b].insts[i]); - let m = match (lo, hi) { - (Some(at), Some(hi)) if at == hi => def(lo) - .and_then(|i| self.sop(i)) - .and_then(|r| r.dst) - .map(|d| d.1), - _ => None, - }; // What an EXEC write the pass does not follow leaves there. let exec_write = |d: Option<(usize, usize)>, v: Value| { def(d).is_some_and(|i| { i.write(Reg::S(EXEC)) == Some(v) || i.write(Reg::S(EXEC + 1)) == Some(v) }) }; - let derived = exec_write(lo, k.0) || exec_write(hi, k.1); + let (m, derived) = match (lo, hi) { + (Some(at), Some(hi)) if at == hi => { + let m = def(lo) + .and_then(|i| self.sop(i)) + .and_then(|r| r.dst) + .map(|d| d.1); + (m, exec_write(lo, k.0) || exec_write(Some(hi), k.1)) + } + _ => { + let copied = self.moved_pair(k).and_then(|source| { + let (m, derived) = self.mask(source); + self.b + .support(m) + .iter() + .all(|a| !matches!(a, Atom::Opaque(_))) + .then_some((m, derived)) + }); + copied.map_or_else( + || (None, exec_write(lo, k.0) || exec_write(hi, k.1)), + |(m, derived)| (Some(m), derived), + ) + } + }; + // shortcut: the atom names the pair by its low dword, and + // lowering takes the high dword written beside it. let m = m.unwrap_or_else(|| { let born = self.born(k.0); self.b.atom(Atom::Opaque(k.0), born) @@ -1032,6 +991,20 @@ impl<'a> Lanes<'a> { (m, derived) } + fn move_source(&self, mut value: Value) -> Value { + while let Some(&(b, i)) = self.defs.get(&value) { + let inst = &self.p.blocks[b].insts[i]; + let [(Reg::S(_), source)] = inst.reads.as_slice() else { + break; + }; + if inst.name() != "s_mov_b32" { + break; + } + value = *source; + } + value + } + /// A mask joined by phis at a block entry, and whether a mask coming in /// on a forward edge derives from EXEC or a VALU result. Where every /// lane arriving so far has the incoming mask set (or clear), the join @@ -1052,7 +1025,7 @@ impl<'a> Lanes<'a> { .map(|n| (arg(lo, k.0, n), arg(hi, k.1, n))) .collect(); let id = lo.map_or(k.1, |_| k.0); - let mut derived = false; + let mut derived = self.derived_phis.contains(&id); // (edge condition, mask) per forward edge; back edges come later. let mut forward = Vec::new(); for (n, &a) in args.iter().enumerate() { @@ -1062,6 +1035,8 @@ impl<'a> Lanes<'a> { derived |= d; let e = self.edge(self.first[q], q, taken); forward.push((e, m)); + } else { + self.seen.push(a); } } if forward.len() == args.len() @@ -1082,6 +1057,7 @@ impl<'a> Lanes<'a> { block, id, value, + derived, args, }); let m = if value { Bool::TRUE } else { Bool::FALSE }; @@ -1089,6 +1065,14 @@ impl<'a> Lanes<'a> { } } } + if self.phi_join_ids.insert(id) { + self.phi_joins.push(PhiJoin { + block, + id, + derived, + args, + }); + } let born = self.index[block]; Some((self.b.atom(Atom::Phi(id), born), derived)) } @@ -1176,9 +1160,13 @@ impl<'a> Lanes<'a> { "cselect" => { let (a, c) = (arg(0, self)?, arg(1, self)?); let scc = inst.read(Reg::Scc)?; - let born = self.born(scc); - let u = self.b.atom(Atom::Uniform(scc), born); - (self.b.ite(u, a, c), None) + if self.clear_after_loop(scc) { + (c, None) + } else { + let born = self.born(scc); + let u = self.b.atom(Atom::Uniform(scc), born); + (self.b.ite(u, a, c), None) + } } _ => { let (a, c) = (arg(0, self)?, arg(1, self)?); @@ -1194,6 +1182,31 @@ impl<'a> Lanes<'a> { }) } + /// Whether SCC value `scc` is clear wherever it is read: the instruction before an + /// `s_cbranch_execnz` that closes a loop wrote it as "the EXEC it leaves is not + /// empty" (`s_andn2_wrexec`, say), and the wave leaves `do { .. } while (EXEC)` + /// with EXEC empty. A read inside the loop or behind another way out of it sees a + /// join of this value, not the value itself. + fn clear_after_loop(&self, scc: Value) -> bool { + let Some(&(b, i)) = self.defs.get(&scc) else { + return false; + }; + let block = &self.p.blocks[b]; + let (Some(writer), Some(last)) = (block.insts.get(i), block.insts.last()) else { + return false; + }; + let exec = writer.write(Reg::S(EXEC)); + let back = match block.exit { + Exit::Branch { taken, .. } => self.index[taken] <= self.index[b], + _ => false, + }; + back && i + 2 == block.insts.len() + && exec.is_some() + && last.name() == "s_cbranch_execnz" + && last.read(Reg::S(EXEC)) == exec + && (!self.p.wave64 || last.read(Reg::S(EXEC + 1)) == writer.write(Reg::S(EXEC + 1))) + } + fn combine(&mut self, f: &str, a: Bool, c: Bool) -> Option<Bool> { let b = &mut self.b; Some(match f { @@ -1284,6 +1297,26 @@ impl<'a> Lanes<'a> { ne }; self.scc_lane.insert(scc, m); + if rest.starts_with("eq") { + self.scc_every.insert(scc); + } + } + // `s_bcnt1` of a mask every running lane sees alike (EXEC under a scalar + // condition, or EXEC itself): its SCC, "some lane is set", is each lane's own + // bit. A branch on it then reads no ballot. + if takes_mask + && name.starts_with("s_bcnt1_i32_b") + && let Some(scc) = inst.write(Reg::Scc) + && let [a] = &src[..] + && let Some((m, true)) = self.operand(inst, a) + { + let e = exec.unwrap_or(Bool::TRUE); + let own = self.b.given(m, e); + if self.b.implies(m, e) + && self.b.support(own).iter().all(|a| matches!(a, Atom::Uniform(_))) + { + self.scc_lane.insert(scc, own); + } } } Fields::Valu(v) => { @@ -1296,18 +1329,25 @@ impl<'a> Lanes<'a> { l.active.insert(k.0); }; // A select reads a mask nothing else may: a join of compare - // results is resolved here, as for EXEC. - if name == "v_cndmask_b32" + // results is resolved here, as for EXEC. A carry-in is only + // recorded for `finish`: resolving its join would turn a + // refusal into a per-lane phi, wrong after a divergent branch. + if (name == "v_cndmask_b32" || name.contains("_co_ci_")) && let Some(&Operand::Scalar { code, .. }) = v.src.get(2) && code != NULL && let Some(k) = self.key(|r| inst.read(r), code) - && let Some(&(_, dst)) = inst.writes.first() { - let (mask, derived) = self.mask(k); - if derived { - self.select_masks.insert(dst, mask); + if name == "v_cndmask_b32" { + self.mask(k); + } else { + self.seen.push(k); } } + if matches!(name, "v_div_fmas_f32" | "v_div_fmas_f64") + && let Some(k) = self.key(|r| inst.read(r), VCC) + { + self.mask(k); + } if name.starts_with("v_cmpx") { if let Some(k) = self.key(|r| inst.write(r), EXEC) { lane(self, k); @@ -1328,6 +1368,27 @@ impl<'a> Lanes<'a> { } /// The per-lane condition under which a block's closing branch is taken. + /// How the console decides the branch `inst` on a lane mask, in terms of the lanes' own + /// `when` ([`Self::branch`]): taken when some lane's holds (`true`) or when every lane's + /// does (`false`). `execnz`/`vccnz` ask for some set bit, `execz`/`vccz` for none; SCC + /// of a mask operation is "some lane's bit is set", SCC of `s_cmp_eq` of two masks is + /// "every lane's is" ([`Self::scc_every`]), and `scc0` branches on the opposite. None + /// for a branch on a scalar condition. + fn wave_kind(&self, inst: &Inst) -> Option<bool> { + match inst.name() { + "s_cbranch_execnz" | "s_cbranch_vccnz" => Some(true), + "s_cbranch_execz" | "s_cbranch_vccz" => Some(false), + n @ ("s_cbranch_scc0" | "s_cbranch_scc1") => { + let scc = inst.read(Reg::Scc)?; + self.scc_lane.get(&scc)?; + // set: SCC is 1 when some lane's bit is set (every lane's, for a compare) + let every = self.scc_every.contains(&scc); + Some((n == "s_cbranch_scc1") != every) + } + _ => None, + } + } + fn branch(&mut self, inst: &Inst) -> Bool { let exec = self.exec(inst); match inst.name() { @@ -1438,6 +1499,102 @@ mod tests { s.guards.iter().flatten().filter(|g| g.is_some()).count() } + /// The search of [`Bools::meet`] with every case split made anew, as it + /// was before [`Meets`]. + fn meet_anew(b: &Bools, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool { + let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE }; + if all.iter().any(fails) { + return false; + } + all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE); + if all.is_empty() || *budget == 0 { + return true; + } + *budget -= 1; + let top = |x: Bool| b.nodes[x.0 as usize].0; + let v = all.iter().map(|&(x, _)| top(x)).min().expect("not empty"); + [false, true].into_iter().any(|value| { + let next = all + .iter() + .map(|&(x, holds)| { + let (lo, hi) = b.split(x, v); + (if value { hi } else { lo }, holds) + }) + .collect(); + meet_anew(b, next, budget) + }) + } + + #[test] + fn a_search_that_remembers_answers_as_one_made_anew() { + // Functions of 12 variables put together at random, and conditions + // of two to five of them (repeats and constants among them), under + // budgets that run out early, late and never: the answer, and where + // no lane is found the budget left, are those of the search that + // remembers nothing; with what one `Meets` gathered over all of + // them, and with an empty one. + let mut b = Bools::new(); + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut random = move |n: usize| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % n as u64) as usize + }; + let mut f: Vec<Bool> = (0..12).map(|i| b.atom(Atom::Constant(i + 2), 0)).collect(); + f.extend([Bool::FALSE, Bool::TRUE]); + for _ in 0..120 { + let (x, y) = (f[random(f.len())], f[random(f.len())]); + let made = match random(4) { + 0 => b.and(x, y), + 1 => b.or(x, y), + 2 => b.xor(x, y), + _ => b.not(x), + }; + f.push(made); + } + let mut seen = Meets::default(); + let (mut none, mut some, mut gave_up) = (0, 0, 0); + for _ in 0..1500 { + let all: Vec<(Bool, bool)> = (0..2 + random(4)) + .map(|_| (f[random(f.len())], random(2) == 0)) + .collect(); + for budget in [0, 1, 2, 3, 5, 9, 20, 60, 250, 1000, MAX_MEET] { + let mut left = budget; + let anew = meet_anew(&b, all.clone(), &mut left); + for fresh in [false, true] { + let mut empty = Meets::default(); + let seen = if fresh { &mut empty } else { &mut seen }; + let mut work = all + .iter() + .map(|&(x, holds)| x.0 << 1 | u32::from(holds)) + .collect(); + let mut mine = budget; + let found = b.meet_in(0, &mut work, &mut mine, seen); + assert_eq!(found, anew, "{all:?} within {budget}"); + assert!(work.is_empty()); + if !found { + assert_eq!(mine, left, "{all:?} within {budget}"); + } + } + assert_eq!(b.meet_within(&all, budget, &mut seen), anew); + if !anew { + none += 1; + } else if meet_anew(&b, all.clone(), &mut usize::MAX.clone()) { + some += 1; + } else { + gave_up += 1; + } + } + } + // All three outcomes came up, and searches were remembered. + assert!( + none > 100 && some > 100 && gave_up > 100, + "{none} {some} {gave_up}" + ); + assert!(seen.none.len() > 100); + } + #[test] fn divergent_if_becomes_a_lane_branch() { let p = build( @@ -1519,6 +1676,39 @@ mod tests { )); } + /// `s_cselect` on the SCC a lane loop ended with (the blend-shape skinning + /// programs): the loop is left when no lane remains, so the select takes + /// its second operand; it was a uniform atom whose value no lane has. + #[test] + fn a_select_on_the_condition_a_lane_loop_ended_with_takes_its_second_operand() { + let cnd = 256 | (256 << 9) | (3 << 18); + let p = build( + &[ + 0xBE83_037E, // 0: s_mov_b32 s3, exec_lo + 0xBE9C_037E, // s_mov_b32 s28, exec_lo + 0x7E3A_0507, // 8: v_readfirstlane_b32 s29, v7 + 0x7DA4_0E1D, // v_cmpx_eq_u32 exec_lo, s29, v7 + 0xBE9C_471C, // s_andn2_wrexec_b32 s28, s28 + 0xBF89_FFFC, // s_cbranch_execnz -> 8 + 0xBEFE_0303, // s_mov_b32 exec_lo, s3 + 0x8503_807E, // s_cselect_b32 s3, exec_lo, 0 + 0xD501_0001, + cnd, // v_cndmask_b32 v1, v0, v0, s3 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let select = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| i.name() == "s_cselect_b32") + .expect("the select"); + let mask = select.write(Reg::S(3)).unwrap(); + assert_eq!(s.masks.get(&mask), Some(&Bool::FALSE)); + } + #[test] fn scalar_branches_stay_uniform() { let p = build( @@ -1539,404 +1729,253 @@ mod tests { } #[test] - fn irreducible_loops_are_split() { + fn a_mask_whose_high_dword_is_rewritten_is_not_the_compare() { + for reader in [ + 0x0202_0480, // v_cndmask_b32 v1, 0, v2, vcc + 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc + ] { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBEEB_0380, // s_mov_b32 vcc_hi, 0 + reader, + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let lo = p.blocks[0].insts[2].read(Reg::S(VCC)).unwrap(); + assert_eq!(p.blocks[0].insts[0].write(Reg::S(VCC)), Some(lo)); + // The reader sees (compare low dword, 0): lanes 32-63 are clear. + // The mask exported for that low dword must not be the compare. + assert_ne!( + s.masks.get(&lo).and_then(|&m| s.bools.node(m)), + Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)), + "{reader:#x}: vcc_hi was zeroed after the compare" + ); + } + } + + #[test] + fn paired_dword_moves_keep_exec_mask_provenance() { let p = build( &[ - 0xBF06_0100, // s_cmp_eq_u32 s0, s1 - 0xBF85_0001, // s_cbranch_scc1 -> 12, into the loop's middle - 0x8002_8102, // 8: s_add_u32 s2, s2, 1 - 0xBF84_FFFE, // 12: s_cbranch_scc0 -> 8 + 0xBE82_047E, // s_mov_b64 s[2:3], exec + 0xBE84_0302, // s_mov_b32 s4, s2 + 0xBE85_0303, // s_mov_b32 s5, s3 + 0xBE86_0304, // s_mov_b32 s6, s4 + 0xBE87_0305, // s_mov_b32 s7, s5 + 0xBEFE_0406, // s_mov_b64 exec, s[6:7] + 0x7E02_0280, // v_mov_b32 v1, 0 S_ENDPGM, ], - false, + true, ); - // The loop keeps 12 as its header; the entry into 8 gets a copy of it. - let copy = &p.blocks[4]; - assert_eq!((copy.offset, copy.exit), (8, ir::Exit::Jump(2))); - assert_eq!(p.blocks[0].exit.successors(), [2, 4]); - assert_eq!(p.blocks[1].preds, [2]); - assert!(structure(&p).is_ok()); - } - - /// [`Bools::vars`] as it was: lists of the nodes and variables seen. - fn vars_by_scan(b: &Bools, root: Bool) -> Vec<u32> { - let (mut seen, mut vars, mut stack) = (Vec::new(), Vec::new(), vec![root]); - while let Some(n) = stack.pop() { - let (v, lo, hi) = b.nodes[n.0 as usize]; - if v == TERMINAL || seen.contains(&n) { - continue; - } - seen.push(n); - if !vars.contains(&v) { - vars.push(v); - } - stack.extend([lo, hi]); - } - vars - } - - /// One variable's cofactor, as `restrict` did before it took several. - fn restrict_one( - b: &mut Bools, - f: Bool, - v: u32, - value: bool, - memo: &mut Map<Bool, Bool>, - ) -> Bool { - let (bv, lo, hi) = b.nodes[f.0 as usize]; - if bv == TERMINAL || bv > v { - return f; - } - if bv == v { - return if value { hi } else { lo }; - } - if let Some(&r) = memo.get(&f) { - return r; - } - let l = restrict_one(b, lo, v, value, memo); - let h = restrict_one(b, hi, v, value, memo); - let r = b.mk(bv, l, h); - memo.insert(f, r); - r - } - - /// [`Bools::given`] as it was: a walk of `f` per decided variable. - fn given_by_walks(b: &mut Bools, mut f: Bool, known: Bool) -> Bool { - for v in vars_by_scan(b, f) { - let x = b.mk(v, Bool::FALSE, Bool::TRUE); - let nx = b.not(x); - if b.implies(known, x) { - f = restrict_one(b, f, v, true, &mut Map::default()); - } else if b.implies(known, nx) { - f = restrict_one(b, f, v, false, &mut Map::default()); - } - } - f - } - - /// Atoms `0..n` of a fresh [`Bools`], in variable order. - fn atoms(n: u64) -> (Bools, Vec<Bool>) { - let mut b = Bools::new(); - let xs = (0..n).map(|i| b.atom(Atom::Constant(i), 0)).collect(); - (b, xs) - } - - /// `x[i] == y[i]` for every `i`, with every `x` ordered before every - /// `y`: the classic order that makes the diagram exponential in `n`. - fn pairs_equal(b: &mut Bools, xs: &[Bool], n: usize) -> Bool { - let mut f = Bool::TRUE; - for i in 0..n { - let ne = b.xor(xs[i], xs[n + i]); - let eq = b.not(ne); - f = b.and(f, eq); - } - f - } - - /// A deterministic mix of ands, ors and xors over `xs`. - fn mixed(b: &mut Bools, xs: &[Bool], seed: u64, steps: usize) -> Bool { - let mut s = seed; - let mut next = || { - s = s - .wrapping_mul(6_364_136_223_846_793_005) - .wrapping_add(1_442_695_040_888_963_407); - (s >> 33) as usize - }; - let mut f = xs[next() % xs.len()]; - for _ in 0..steps { - let x = xs[next() % xs.len()]; - let x = if next() % 2 == 0 { b.not(x) } else { x }; - f = match next() % 3 { - 0 => b.and(f, x), - 1 => b.or(f, x), - _ => b.xor(f, x), - }; - } - f - } - - /// The function of `f` on the assignment `bits` (bit `v`: variable `v`). - fn value_at(b: &Bools, mut f: Bool, bits: u64) -> bool { - loop { - match f { - Bool::FALSE => return false, - Bool::TRUE => return true, - _ => { - let (v, lo, hi) = b.nodes[f.0 as usize]; - f = if bits >> v & 1 == 1 { hi } else { lo }; - } - } - } - } - - #[test] - fn vars_match_the_scan() { - let (mut b, xs) = atoms(16); - let mut fs = vec![Bool::FALSE, Bool::TRUE, xs[3], pairs_equal(&mut b, &xs, 8)]; - for seed in 0..40 { - fs.push(mixed(&mut b, &xs, seed, 30)); - } - for f in fs { - assert_eq!(b.vars(f), vars_by_scan(&b, f)); - } + let s = structure(&p).unwrap(); + assert_eq!(guarded(&s), 0, "{:?}", s.guards); } #[test] - fn given_matches_a_walk_per_variable() { - let (mut b, xs) = atoms(12); - for seed in 0..60 { - let f = mixed(&mut b, &xs, seed, 24); - let known = mixed(&mut b, &xs, seed ^ 0x9e37, 3); - let fast = b.given(f, known); - // Equal functions are equal nodes, so the ids match too. - assert_eq!(fast, given_by_walks(&mut b, f, known), "seed {seed}"); - // Where `known` holds, the result agrees with `f`. - for bits in 0..1u64 << 12 { - if value_at(&b, known, bits) { - assert_eq!(value_at(&b, fast, bits), value_at(&b, f, bits)); - } - } - } + fn paired_dword_moves_do_not_make_unknown_values_into_masks() { + let p = build( + &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0301, // s_mov_b32 s5, s1 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let guard = s.guards[0][3].expect("unknown mask still guards the vector op"); + assert!( + s.bools + .support(guard) + .iter() + .any(|a| matches!(a, Atom::Opaque(_))) + ); } #[test] - fn given_replaces_every_decided_atom() { - let (mut b, xs) = atoms(12); - let f = pairs_equal(&mut b, &xs, 6); - // x0..x5 all true: f becomes y0 && .. && y5. - let mut known = Bool::TRUE; - let mut ys = Bool::TRUE; - for i in 0..6 { - known = b.and(known, xs[i]); - ys = b.and(ys, xs[6 + i]); + fn split_scalar_copies_across_a_branch_preserve_both_words_of_a_wave64_mask() { + for (high, intact) in [(0xBE83_036B, true), (0xBE83_036A, false)] { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE84_046A, // s_mov_b64 s[4:5], vcc + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0004, // s_cbranch_scc1 -> join at 32 + 0xBE82_036A, // s_mov_b32 s2, vcc_lo + high, // s_mov_b32 s3, vcc_hi (or vcc_lo) + 0xBE84_0302, // s_mov_b32 s4, s2 + 0xBE85_0303, // s_mov_b32 s5, s3 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let compare = p.blocks[0].insts[0].write(Reg::S(VCC)).unwrap(); + let restored = p.blocks[2].insts[0].write(Reg::S(EXEC)).unwrap(); + assert_eq!(s.masks[&restored] == s.masks[&compare], intact); } - assert_eq!(b.given(f, known), ys); - // Nothing decided: unchanged; a contradiction decides nothing useful - // but must not panic. - assert_eq!(b.given(f, Bool::TRUE), f); - let _ = b.given(f, Bool::FALSE); - assert_eq!(b.given(Bool::TRUE, known), Bool::TRUE); } #[test] - #[ignore = "benchmark: cargo test --release -p victory-shader bench_bools -- --ignored --nocapture"] - fn bench_bools() { - // Microseconds per call, over at least 3 calls and 50 ms. - let time = |f: &mut dyn FnMut()| { - let (t, mut calls) = (std::time::Instant::now(), 0); - while calls < 3 || t.elapsed().as_millis() < 50 { - f(); - calls += 1; - } - t.elapsed().as_secs_f64() * 1e6 / f64::from(calls) - }; - for n in [2, 4, 8, 10, 12, 13] { - let (mut b, xs) = atoms(2 * n as u64); - let f = pairs_equal(&mut b, &xs, n); - let count = vars_by_scan(&b, f).len(); - let size = { - let (mut seen, mut stack) = (Set::default(), vec![f]); - while let Some(g) = stack.pop() { - let (v, lo, hi) = b.nodes[g.0 as usize]; - if v != TERMINAL && seen.insert(g) { - stack.extend([lo, hi]); - } - } - seen.len() - }; - // Half the x's known true. - let mut known = Bool::TRUE; - for x in &xs[..n / 2] { - known = b.and(known, *x); - } - let (expect, mut got) = (given_by_walks(&mut b, f, known), Bool::FALSE); - let vars_old = time(&mut || assert_eq!(vars_by_scan(&b, f).len(), count)); - let vars_new = time(&mut || assert_eq!(b.vars(f).len(), count)); - let given_old = time(&mut || got = given_by_walks(&mut b, f, known)); - assert_eq!(got, expect); - let given_new = time(&mut || got = b.given(f, known)); - assert_eq!(got, expect); - println!( - "n={n} nodes={size}: vars {vars_old:.2} -> {vars_new:.2} us ({:.1}x), \ - given {given_old:.2} -> {given_new:.2} us ({:.1}x)", - vars_old / vars_new, - given_old / given_new - ); - } + fn a_mask_joined_over_a_back_edge_with_a_rewritten_high_dword_is_not_the_compare() { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0x0202_0480, // 4: v_cndmask_b32 v1, 0, v2, vcc + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0xBEEB_0380, // s_mov_b32 vcc_hi, 0 + 0xBF85_FFFC, // s_cbranch_scc1 -> 4 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + // The select reads the loop header's join; over the back edge it + // takes (compare low dword, 0), which only the join sees. + let lo = p.blocks[1].insts[1].write(Reg::S(VCC)).unwrap(); + assert_ne!( + s.masks.get(&lo).and_then(|&m| s.bools.node(m)), + Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)) + ); } #[test] - fn meet_pins_forced_variables_across_deep_diamond_chain() { - let mut b = Bools::new(); - let val = Value; - let mut reach = Bool::TRUE; - for i in 0..24u32 { - let x = b.atom(Atom::Lane(val(2 * i + 1)), i as usize); - let y = b.atom(Atom::Lane(val(2 * i + 2)), i as usize); - let clause = b.or(x, y); - reach = b.and(reach, clause); - } - let tail = b.atom(Atom::Lane(val(100)), 30); - let not_tail = b.not(tail); - let guarded = b.and(reach, not_tail); - // Without bottom-up forced-var restriction, branching on the 24 (x | y) diamonds - // explores 3^24 paths and hits MAX_MEET, falsely returning `true`. - assert!(!b.meet(&[(guarded, true), (tail, true)])); - assert!(b.meet(&[(guarded, true), (tail, false)])); - - // Cascading unit propagation through a forced chain at the bottom. - let gate = b.atom(Atom::Uniform(val(101)), 31); - let cascade = b.ite(tail, gate, Bool::FALSE); - assert!(!b.meet(&[(guarded, true), (cascade, true)])); - assert!(b.meet(&[(reach, true), (cascade, true)])); + fn irreducible_loops_are_split() { + let p = build( + &[ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0001, // s_cbranch_scc1 -> 12, into the loop's middle + 0x8002_8102, // 8: s_add_u32 s2, s2, 1 + 0xBF84_FFFE, // 12: s_cbranch_scc0 -> 8 + S_ENDPGM, + ], + false, + ); + // The loop keeps 12 as its header; the entry into 8 gets a copy of it. + let copy = &p.blocks[4]; + assert_eq!((copy.offset, copy.exit), (8, ir::Exit::Jump(2))); + assert_eq!(p.blocks[0].exit.successors(), [2, 4]); + assert_eq!(p.blocks[1].preds, [2]); + assert!(structure(&p).is_ok()); } #[test] - fn meet_memoizes_diamonds_without_forced_root_vars() { - let mut b = Bools::new(); - let val = Value; - let mut reach = Bool::TRUE; - for i in 0..22u32 { - let x = b.atom(Atom::Lane(val(2 * i + 1)), i as usize); - let y = b.atom(Atom::Lane(val(2 * i + 2)), i as usize); - let clause = b.or(x, y); - reach = b.and(reach, clause); - } - // Keep the conflict (z0 & !z0) below all 22 diamonds so no variable is - // forced at the root; failed-state memoization collapses the DAG. - let z0 = b.atom(Atom::Lane(val(200)), 30); - let z1 = b.atom(Atom::Lane(val(201)), 30); - let eq = b.xor(z0, z1); - let c1 = b.and(reach, z0); - let nz0 = b.not(z0); - let c2 = b.and(reach, nz0); - assert!(!b.meet(&[(c1, true), (c2, true)])); - - let same_side = b.and(reach, eq); - assert!(b.meet(&[(c1, true), (same_side, true)])); - assert!(!b.meet(&[(c1, true), (c1, false)])); + fn mask_phi_joining_constant_and_compare_records_edge_bools() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xBF06_8000, // 0: s_cmp_eq_u32 s0, 0 + 0xBF85_0002, // 4: s_cbranch_scc1 -> 16 + 0xBE82_0380, // 8: s_mov_b32 s2, 0 + 0xBF82_0002, // 12: s_branch -> 24 + 0xD4C2_0002, + 0x0002_0080, // 16: v_cmp_eq_u32 s2, 0, v0 + 0xD501_0001, + cnd, // 24: v_cndmask_b32 v1, v2, v3, s2 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("mask phi for s2"); + assert_eq!( + s.masks.get(&phi.value).and_then(|&m| s.bools.node(m)), + Some((Atom::Phi(phi.value), Bool::FALSE, Bool::TRUE)) + ); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!( + edges + .iter() + .any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])), + "{edges:?}" + ); } #[test] - fn meet_handles_canonical_dedup_and_trivial_constraints() { - let mut b = Bools::new(); - let x = b.atom(Atom::Lane(Value(1)), 0); - let nx = b.not(x); - assert!(b.meet(&[])); - assert!(b.meet(&[(Bool::TRUE, true), (Bool::FALSE, false)])); - assert!(!b.meet(&[(Bool::FALSE, true)])); - assert!(!b.meet(&[(Bool::TRUE, false)])); - assert!(b.meet(&[(x, true), (x, true)])); - assert!(!b.meet(&[(x, true), (x, false)])); - assert!(!b.meet(&[(x, false), (nx, false)])); + fn loop_mask_accumulator_from_zero_tracks_phi_and_edges() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xBE82_0480, // 0: s_mov_b64 s[2:3], 0 + 0xBE84_0380, // 4: s_mov_b32 s4, 0 + 0xD501_0001, + cnd, // 8: v_cndmask_b32 v1, v2, v3, s[2:3] + 0x7D84_0080, // 16: v_cmp_eq_u32 vcc, 0, v0 + 0x8882_026A, // 20: s_or_b64 s[2:3], vcc, s[2:3] + 0x8004_8104, // 24: s_add_u32 s4, s4, 1 + 0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4 + 0xBF85_FFF9, // 32: s_cbranch_scc1 -> 8 + 0xD501_0004, + cnd, // 36: v_cndmask_b32 v4, v2, v3, s[2:3] + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("loop mask phi for s[2:3]"); + assert!(s.masks.contains_key(&phi.value)); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!(edges.iter().any(|&e| { + let sup = s.bools.support(e); + sup.contains(&Atom::Phi(phi.value)) && sup.iter().any(|a| matches!(a, Atom::Lane(_))) + })); } #[test] - fn resource_lane_phi_prunes_dead_arm_behind_diamond_chain() { - use crate::native::{HwStage, RootParam, RootType::Table}; - - let mut words = vec![ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0602, - 0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0 - 0xF408_0802, - 0xFA00_0020, // s_load_dwordx4 s[32:35], s[4:5], 0x20 - 0xF408_0A02, - 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 - 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - ]; - // Prepend 20 (a_i | b_i) early-cull diamonds so `reach` carries 3^20 paths into - // the `lane_phi` + waterfall below; each cbranch targets the shared final s_endpgm. - const DIAMONDS: usize = 20; - let mut cbranch_sites = Vec::with_capacity(DIAMONDS); - for _ in 0..DIAMONDS { - words.extend_from_slice(&[ - 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 - 0xBE8A_036A, // s_mov_b32 s10, vcc_lo - 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0 - 0x886A_6A0A, // s_or_b32 vcc_lo, s10, vcc_lo - 0xBE8A_3C6A, // s_and_saveexec_b32 s10, vcc_lo - 0xBF88_0000, // s_cbranch_execz -> patched to final s_endpgm - ]); - cbranch_sites.push(words.len() - 1); - } - // Waterfall descriptor join guarded by `s30` (`24 > v0`); the `!s30` arm never runs - // inside the waterfall loop and must be proven dead despite the 20 diamonds above. - words.extend_from_slice(&[ - 0xD4C4_001E, - 0x0002_0098, // v_cmp_gt_u32_e64 s30, 24, v0 - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 - 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo - 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 - 0xBF88_0004, // s_cbranch_execz -> +4 - 0x7E08_0218, // v_mov_b32 v4, s24 - 0x7E0A_0219, // v_mov_b32 v5, s25 - 0x7E0C_021A, // v_mov_b32 v6, s26 - 0x7E0E_021B, // v_mov_b32 v7, s27 - 0xBE94_3D14, // s_or_saveexec_b32 s20, s20 - 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 - 0xBF88_0007, // s_cbranch_execz -> +7 - 0xBE9F_3C1E, // s_and_saveexec_b32 s31, s30 - 0xBF88_0004, // s_cbranch_execz -> +4 - 0x7E08_0220, // v_mov_b32 v4, s32 - 0x7E0A_0221, // v_mov_b32 v5, s33 - 0x7E0C_0222, // v_mov_b32 v6, s34 - 0x7E0E_0223, // v_mov_b32 v7, s35 - 0x887E_1F7E, // s_or_b32 exec_lo, exec_lo, s31 - 0x887E_147E, // s_or_b32 exec_lo, exec_lo, s20 - 0xBE97_3C1E, // s_and_saveexec_b32 s23, s30 - 0xBF88_0013, // s_cbranch_execz -> +19 - 0xBE9D_037E, // s_mov_b32 s29, exec_lo - 0x7E18_0504, // v_readfirstlane_b32 s12, v4 - 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 - 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 - 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 - 0xD4E2_0015, - 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] - 0xD4E2_0016, - 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] - 0x8715_1615, // s_and_b32 s21, s21, s22 - 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 - 0xE030_1000, - 0x8003_0C10, // buffer_load_dword v12, v16, s[12:15], 0 offen - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 - 0xBF89_FFF1, // s_cbranch_execnz -> loop - 0xBEFE_031D, // s_mov_b32 exec_lo, s29 - 0xE070_1000, - 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen - 0x887E_177E, // s_or_b32 exec_lo, exec_lo, s23 - S_ENDPGM, - ]); - let end_idx = words.len() - 1; - for site in cbranch_sites { - let rel = (end_idx - site - 1) as u16; - words[site] = 0xBF88_0000 | u32::from(rel); - } - let p = build(&words, false); + fn loop_mask_phi_reset_to_constant_on_back_edge() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xD4C2_0002, + 0x0002_0080, // 0: v_cmp_eq_u32 s2, 0, v0 + 0xBE84_0380, // 8: s_mov_b32 s4, 0 + 0xD501_0001, + cnd, // 12: v_cndmask_b32 v1, v2, v3, s2 + 0xBE82_0380, // 20: s_mov_b32 s2, 0 + 0x8004_8104, // 24: s_add_u32 s4, s4, 1 + 0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4 + 0xBF85_FFFA, // 32: s_cbranch_scc1 -> 12 + S_ENDPGM, + ], + false, + ); let s = structure(&p).unwrap(); - let layout = [ - RootParam { - root: Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 0, - slot: 0, - }, - RootParam { - root: Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 1, - slot: 0, - }, - ]; - let r = crate::resource::track(&p, &layout, HwStage::Cs, Some(&s)).unwrap(); - assert_eq!(r.waterfall.reads.len(), 4, "{r:?}"); - assert!(!r.descriptors.is_empty(), "{r:?}"); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("loop mask phi for s2"); + assert!(s.masks.contains_key(&phi.value)); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!( + edges + .iter() + .any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])), + "{edges:?}" + ); } } diff --git a/crates/victory-shader/tests/resource_tracking.rs b/crates/victory-shader/tests/resource_tracking.rs deleted file mode 100644 index ddf9e2ce60..0000000000 --- a/crates/victory-shader/tests/resource_tracking.rs +++ /dev/null @@ -1,177 +0,0 @@ -use std::hint::black_box; -use std::time::Instant; - -use victory_shader::ir::{self, Program, Reg}; -use victory_shader::resource::{Address, track}; -use victory_shader::{HwStage, RootParam, RootType, ShaderError}; - -const TABLE: RootParam = RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 8, - slot: 0, -}; -const ZERO_HIGH: u32 = 0xBE83_0380; // s_mov_b32 s3, 0 -const COPY_BASE: u32 = 0xBE82_0308; // s_mov_b32 s2, s8 -const ADD_16: u32 = 0x8002_9002; // s_add_u32 s2, s2, 16 -const LOAD: u32 = 0xF408_0401; // s_load_dwordx4 s[16:19], s[2:3], imm -const END: u32 = 0xBF81_0000; // s_endpgm - -fn build(words: &[u32]) -> Program { - let code: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect(); - ir::build(&code, false, 256).unwrap() -} - -// Each unrolled step advances the same base and reads several fields. -fn unrolled_loads(steps: u32, loads_per_step: u32) -> Program { - let mut step = vec![ADD_16]; - for field in 0..loads_per_step { - step.extend([LOAD, 0xFA00_0000 | (4 * field)]); - } - let mut words = vec![ZERO_HIGH, COPY_BASE]; - for _ in 0..steps { - words.extend_from_slice(&step); - } - words.push(END); - build(&words) -} - -#[test] -fn tracks_every_offset_in_a_shared_address_chain() { - let program = unrolled_loads(32, 4); - let tracked = track(&program, &[TABLE], HwStage::Ps, None).unwrap(); - let expected: Vec<_> = (1..=32) - .flat_map(|step| (0..4).map(move |field| (16 * step + 4 * field, None))) - .collect(); - assert_eq!( - tracked - .scalar - .iter() - .map(|(_, a)| (a.offset, a.dynamic)) - .collect::<Vec<_>>(), - expected - ); - assert!(tracked.scalar.iter().all(|(_, a)| a.param == 0)); -} - -#[test] -fn shared_address_keeps_its_dynamic_term_and_wraps_offsets() { - let program = build(&[ - ZERO_HIGH, - 0x8002_0908, // s_add_u32 s2, s8, s9 - 0x8002_FF02, // s_add_u32 s2, s2, 0xfffffff0 - 0xFFFF_FFF0, - LOAD, - 0xFA00_0004, - LOAD, - 0xFA00_0014, - END, - ]); - let dynamic = program - .inputs - .iter() - .find(|(r, _)| *r == Reg::S(9)) - .unwrap() - .1; - let tracked = track(&program, &[TABLE], HwStage::Ps, None).unwrap(); - assert_eq!( - tracked.scalar, - [ - ( - (0, 3), - Address { - param: 0, - offset: 0xFFFF_FFF4, - dynamic: Some(dynamic) - } - ), - ( - (0, 4), - Address { - param: 0, - offset: 4, - dynamic: Some(dynamic) - } - ), - ] - ); -} - -#[test] -fn shared_sum_with_two_dynamic_terms_stays_opaque() { - let program = build(&[ - ZERO_HIGH, - 0x8004_0A09, // s_add_u32 s4, s9, s10 - 0x8002_0408, // s_add_u32 s2, s8, s4 - LOAD, - 0xFA00_0000, - LOAD, - 0xFA00_0004, - END, - ]); - let dynamic = program.blocks[0].insts[1].write(Reg::S(4)).unwrap(); - let tracked = track(&program, &[TABLE], HwStage::Ps, None).unwrap(); - assert_eq!( - tracked.scalar, - [ - ( - (0, 3), - Address { - param: 0, - offset: 0, - dynamic: Some(dynamic) - } - ), - ( - (0, 4), - Address { - param: 0, - offset: 4, - dynamic: Some(dynamic) - } - ), - ] - ); - assert_eq!( - track(&program, &[], HwStage::Ps, None).unwrap_err(), - ShaderError::Unsupported { - offset: 12, - what: "an address not from a root parameter", - } - ); -} - -// cargo test -p victory-shader --release --test resource_tracking \ -// bench_unrolled_loads -- --ignored --nocapture -#[test] -#[ignore = "benchmark"] -fn bench_unrolled_loads() { - for (steps, loads, iterations) in [(16, 4, 1_000), (128, 4, 50), (384, 4, 20)] { - let program = unrolled_loads(steps, loads); - let layout = [TABLE]; - assert_eq!( - track(&program, &layout, HwStage::Ps, None) - .unwrap() - .scalar - .len(), - (steps * loads) as usize - ); - let mut samples = [0.0; 7]; - for sample in &mut samples { - let start = Instant::now(); - for _ in 0..iterations { - let tracked = - track(black_box(&program), black_box(&layout), HwStage::Ps, None).unwrap(); - black_box(tracked); - } - *sample = start.elapsed().as_secs_f64() * 1e6 / f64::from(iterations); - } - samples.sort_by(f64::total_cmp); - println!( - "{steps:>3} steps x {loads} loads: {:>9.2} us/track (median)", - samples[3] - ); - } -} diff --git a/docs/agents/domain.md b/docs/agents/domain.md deleted file mode 100644 index 4032de016c..0000000000 --- a/docs/agents/domain.md +++ /dev/null @@ -1,51 +0,0 @@ -# Domain Docs - -How the engineering skills should consume this repo's domain documentation when exploring the codebase. - -## Before exploring, read these - -- **`GLOSSARY.md`** at the repo root, or -- **`GLOSSARY-MAP.md`** at the repo root if it exists: it points at one `GLOSSARY.md` per context. Read each one relevant to the topic. -- **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions. - -If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved. - -## File structure - -Single-context repo (most repos): - -``` -/ -├── GLOSSARY.md -├── docs/adr/ -│ ├── 0001-event-sourced-orders.md -│ └── 0002-postgres-for-write-model.md -└── src/ -``` - -Multi-context repo (presence of `GLOSSARY-MAP.md` at the root): - -``` -/ -├── GLOSSARY-MAP.md -├── docs/adr/ ← system-wide decisions -└── src/ - ├── ordering/ - │ ├── GLOSSARY.md - │ └── docs/adr/ ← context-specific decisions - └── billing/ - ├── GLOSSARY.md - └── docs/adr/ -``` - -## Use the glossary's vocabulary - -When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `GLOSSARY.md`. Don't drift to synonyms the glossary explicitly avoids. - -If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`). - -## Flag ADR conflicts - -If your output contradicts an existing ADR, surface it explicitly rather than silently overriding: - -> _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_ diff --git a/docs/agents/issue-tracker.md b/docs/agents/issue-tracker.md deleted file mode 100644 index a63510f740..0000000000 --- a/docs/agents/issue-tracker.md +++ /dev/null @@ -1,46 +0,0 @@ -# Issue tracker: GitHub - -Issues and specs for this repo live as GitHub issues. Use the `gh` CLI for all operations. - -## Conventions - -- **Create an issue**: `gh issue create --title "..." --body "..."`. Use a heredoc for multi-line bodies. -- **Read an issue**: `gh issue view <number> --json number,title,body,labels,comments`. -- **List issues**: `gh issue list --state open --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'` with appropriate `--label` and `--state` filters. -- **Make an issue a sub-issue of a parent**: `gh issue create --parent <parent> ...`, or `gh issue edit <parent> --add-sub-issue <child>` afterwards (`gh` 2.94+). Older `gh`: `gh api --method POST repos/<owner>/<repo>/issues/<parent>/sub_issues -F sub_issue_id=<child-db-id>` (database id, as in **Blocking** below). Without sub-issues, put `Part of #<parent>` at the top of the child body. -- **Comment on an issue**: `gh issue comment <number> --body "..."` -- **Apply / remove labels**: `gh issue edit <number> --add-label "..."` / `--remove-label "..."` -- **Close**: `gh issue close <number> --comment "..."` - -Infer the repo from `git remote -v`; `gh` does this automatically when run inside a clone. - -## Pull requests as a triage surface - -**PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_ - -When set to `yes`, PRs run through the same labels and states as issues, using the `gh pr` equivalents: - -- **Read a PR**: `gh pr view <number> --comments` and `gh pr diff <number>` for the diff. -- **List external PRs for triage**: `gh api --paginate 'repos/{owner}/{repo}/pulls?state=open' --jq '.[] | select(.author_association | IN("OWNER","MEMBER","COLLABORATOR") | not) | {number, title, author: .user.login, author_association, labels: [.labels[].name]}'`. -- **Comment / label / close**: `gh pr comment`, `gh pr edit --add-label`/`--remove-label`, `gh pr close`. - -GitHub shares one number space across issues and PRs, so a bare `#42` may be either: resolve with `gh pr view 42` and fall back to `gh issue view 42`. - -## When a skill says "publish to the issue tracker" - -Create a GitHub issue. - -## When a skill says "fetch the relevant ticket" - -Read it as in **Read an issue** above. - -## Wayfinding operations - -Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets. - -- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `gh issue create --label wayfinder:map`. -- **Child ticket**: an issue linked to the map as a GitHub sub-issue (see **Make an issue a sub-issue of a parent**). Where sub-issues aren't enabled, add the child to a task list in the map body and put `Part of #<map>` at the top of the child body. Labels: `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev. -- **Blocking**: GitHub's **native issue dependencies**, the canonical, UI-visible representation. Add an edge with `gh api --method POST repos/<owner>/<repo>/issues/<child>/dependencies/blocked_by -F issue_id=<blocker-db-id>`, where `<blocker-db-id>` is the blocker's numeric **database id** (`gh api repos/<owner>/<repo>/issues/<n> --jq .id`, _not_ the `#number` or `node_id`). GitHub reports `issue_dependencies_summary.blocked_by` (open blockers only, the live gate). Where dependencies aren't available, fall back to a `Blocked by: #<n>, #<n>` line at the top of the child body. A ticket is unblocked when every blocker is closed. -- **Frontier query**: list the map's open children (`gh issue list --state open`, scoped to the map's sub-issues / task list), drop any with an open blocker (`issue_dependencies_summary.blocked_by > 0`, or an open issue in the `Blocked by` line) or an assignee; first in map order wins. -- **Claim**: `gh issue edit <n> --add-assignee @me`, the session's first write. -- **Resolve**: `gh issue comment <n> --body "<answer>"`, then `gh issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far. diff --git a/docs/agents/triage-labels.md b/docs/agents/triage-labels.md deleted file mode 100644 index 5276464244..0000000000 --- a/docs/agents/triage-labels.md +++ /dev/null @@ -1,15 +0,0 @@ -# Triage Labels - -The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker. - -| Label in mattpocock/skills | Label in our tracker | Meaning | -| -------------------------- | -------------------- | ---------------------------------------- | -| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue | -| `needs-info` | `needs-info` | Waiting on reporter for more information | -| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent | -| `ready-for-human` | `ready-for-human` | Requires human implementation | -| `wontfix` | `wontfix` | Will not be actioned | - -When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table. - -Edit the "Label in our tracker" column to match whatever vocabulary you actually use. diff --git a/docs/arch-proton-rendering.md b/docs/arch-proton-rendering.md deleted file mode 100644 index 3051f554b4..0000000000 --- a/docs/arch-proton-rendering.md +++ /dev/null @@ -1,127 +0,0 @@ -# Cross-building on Arch Linux and checking rendering under Proton - -On CachyOS x86-64, VIctory at `d2a4bae` built for Windows MSVC and rendered -through loading on a GeForce RTX 4080 (NVIDIA 620.70.06). Entering the world -triggered a GPU fault. This is one compatibility report. See the -[world-rendering status and GPU hang warning](../README.md#status-2026-11-23) -before running a title. - -## Build the launcher - -The host had AVX2, Clang/LLVM/LLD, CMake, Ninja, Wine and `file`. Check -`df -h .` and the filesystem holding your SDK cache. This release build used -365 MiB for `target/` and 642 MiB for the x64 SDK/CRT cache, measured -separately. Allow extra space for Rust, Cargo downloads and temporary files. - -Use the compiler and target standard library from the **same Rust distribution**. -Combining Arch's Rust 1.98.1 with the official 1.98.1 Windows standard library -failed with `E0514` on `compiler_builtins`, even with matching version numbers. -The official 1.98.1 compiler, host standard library and Windows standard -library worked together. With rustup, run these commands from the checkout -in Bash. Check the [Microsoft license notice](https://github.com/rust-cross/cargo-xwin#cargo-xwin) -before installing or using cargo-xwin. - -```bash -repo="$PWD" -target=x86_64-pc-windows-msvc -rustup toolchain install 1.98.1 --profile minimal --target "$target" -cargo +1.98.1 fetch --locked --target "$target" -cargo +1.98.1 install --locked --version 0.24.1 cargo-xwin -export XWIN_ARCH=x86_64 -export XWIN_CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/victory-xwin-x64" -cargo +1.98.1 xwin build --release --locked --target "$target" -p victory -exe="$repo/target/$target/release/victory.exe" -file "$exe" -du -sh "$repo/target" "$XWIN_CACHE_DIR" -``` - -`file` should report a PE32+ x86-64 console executable. If Cargo fails to -resolve crates.io, run `curl -fsS https://index.crates.io/config.json` in the -build shell and your normal terminal. In this test the terminal had network -access and could fetch the locked dependencies. - -## Check the CLI and game path - -System Wine 11.21 ran `--help` and `config` successfully in a dedicated -prefix. It later opened the title's archives and displayed a white window. -`D3D12CreateDevice` at feature level 12.0 returned `0x80070057`, and VIctory -logged `drawn=0` as the frame counter advanced. - -The working graphics configuration used Steam's Proton Experimental with -vkd3d-proton and DXVK. First check that `vulkaninfo --summary` lists your -GPU. The example continues in the same Bash shell and uses a separate prefix. -Adjust the Steam library path if needed. This Proton build used -`SteamLinuxRuntime_4`; its `toolmanifest.vdf` identifies the runtime app ID. - -```bash -game='/absolute/path/to/your/game' -work="${XDG_DATA_HOME:-$HOME/.local/share}/victory-proton-test" -steam="$HOME/.local/share/Steam" -common="$steam/steamapps/common" -runtime="$common/SteamLinuxRuntime_4/_v2-entry-point" -proton="$common/Proton - Experimental/proton" -unset WINEPREFIX VICTORY_GAME_DIR VICTORY_CACHE_DIR VICTORY_DATA_DIR VICTORY_TEST_TITLES -export STEAM_COMPAT_CLIENT_INSTALL_PATH="$steam" -export STEAM_COMPAT_DATA_PATH="$work/compatdata" -export STEAM_COMPAT_INSTALL_PATH="$repo" -export STEAM_COMPAT_MOUNTS="$repo:$game:$work${STEAM_COMPAT_MOUNTS:+:$STEAM_COMPAT_MOUNTS}" -mkdir -p "$STEAM_COMPAT_DATA_PATH" -cd "$work" -slr() { "$runtime" --verb=run -- "$proton" "$@"; } -slr run cmd.exe /d /c ver -export WINEDLLOVERRIDES='d3d12,d3d12core,dxgi=n' -slr runinprefix "$exe" --help -slr getcompatpath "$game" -``` - -For a fresh prefix, copy `"$repo/victory.example.toml"` to -`"$STEAM_COMPAT_DATA_PATH/pfx/drive_c/victory.toml"`. Set `[paths].game_dir` -to the Windows path printed by `getcompatpath` (Proton's `winepath -w`). -Use a single-quoted TOML string to preserve backslashes. Keep the game files -outside the checkout and run the following check before launching. - -```bash -export VICTORY_CONFIG='C:\victory.toml' -slr runinprefix "$exe" config -``` - -Check the printed config filename and game directory. If Proton returns zero -with no console output, redirect inside the prefix and read the file on the -host. This example only reads configuration. - -```bash -exe_win=$(slr getcompatpath "$exe" | tr -d '\r') -printf '@echo off\r\n"%s" config > C:\\victory-config.txt 2>&1\r\n' "$exe_win" \ - > "$STEAM_COMPAT_DATA_PATH/pfx/drive_c/victory-config.cmd" -slr runinprefix cmd.exe /d /c 'C:\victory-config.cmd' -cat "$STEAM_COMPAT_DATA_PATH/pfx/drive_c/victory-config.txt" -``` - -## Distinguish a white window from a world-loading crash - -With `runinprefix`, specifying the native DLL overrides above made the -difference in the device probe. The loader trace showed native `d3d12.dll`, -`d3d12core.dll` and `dxgi.dll`. A standalone probe then created the feature -level 12.0 device, direct queue, fence, event and both descriptor heaps. -`--help` and `config` alone do not exercise these calls. - -For an intentional title run, read the executable name from the game's -manifest (such as `MicrosoftGame.config`). Keep the same shell, prefix and -overrides. Substitute the manifest's relative executable path below. - -```bash -title_win=$(slr getcompatpath "$game/relative/path/from/manifest.exe" | tr -d '\r') -slr runinprefix "$exe" run "$title_win" --execute -``` - -In the Proton run, `drawn` and `dispatched` rose with the submitted work. -At frame 4096 all 56,069 draws and 2,884 dispatches in the reporting interval -had executed. During the transition to the world, two compute pipelines -were refused. The Linux kernel then logged NVIDIA Xid 13 (GPU MMU fault) for -the title process, and VIctory recorded a null write (`0xc0000005`) in -`crashes.log`. The logs do not identify the GPU command that faulted. - -To compare a run, match its timestamps against -`journalctl -k --utc -g 'NVRM: Xid'` and the title's `crashes.log` under -`%LOCALAPPDATA%\victory\data` in the same prefix. For this build, successful -menu and loading-screen rendering is the last verified milestone. diff --git a/docs/architecture.md b/docs/architecture.md index 56acf4cfd5..5e3e6b6b4d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -35,9 +35,9 @@ Converting them ahead of time from files is only a warm-up. | `victory-hle` | console API implementations, host pass-through policy | | `victory-gpu` | D3D12.X objects, command lists and GPU memory → host D3D12 | | `victory-shader` | Xbox shader containers → host shaders | -| `victory-formats` | the GPU's texture layouts (sizes, tiling, detiling), BCPack decoding, audio codecs | +| `victory-formats` | the GPU's texture layouts (sizes, tiling, detiling), audio codecs; planned: BCPack | | `victory-pipeline` | converter trait, content-addressed cache | -| `victory-game` | Grand Theft Auto VI-specific formats, build identities, hooks | +| `victory-game` | the title-specific formats, build identities, hooks | | `apps/victory` | command-line front end | | `xtask` | asset-policy check, git hooks | | `tests/fixtures/hle-probe` | a stand-in "title" (our own code) for loader tests | diff --git a/docs/asset-policy.md b/docs/asset-policy.md index 8ceff74888..f66a340778 100644 --- a/docs/asset-policy.md +++ b/docs/asset-policy.md @@ -34,18 +34,16 @@ by the project owner's decision (2026-11-23), entered as an exception in repository's licence does not cover them. Nothing else of this kind is accepted. +Not game data, so outside the rule but listed as the binary file it is: +`docs/media/catez.gif`, the fork's README picture (owner's decision, +2026-11-24). + ## Where data lives Outside the repository, configured in `victory.toml`: `game_dir` (the user's dump), `test_titles`, and `cache_dir` for everything derived (default `%LOCALAPPDATA%\victory\cache`). -Under Wine/Proton, vkd3d-proton and DXVK write shader caches -(`vkd3d-proton.cache`, `*.dxvk-cache`) into the current directory. They are -derived data and `.gitignore` covers them; to keep them out of the checkout -entirely, run from elsewhere or point `VKD3D_SHADER_CACHE_PATH` / -`DXVK_STATE_CACHE_PATH` at a directory outside the repository. - ## Enforcement 1. `.gitignore` keeps common data types out of `git status`. diff --git a/docs/debugging-notes-from-a-gta-v-port.md b/docs/debugging-notes-from-a-gta-v-port.md deleted file mode 100644 index f739f6327b..0000000000 --- a/docs/debugging-notes-from-a-gta-v-port.md +++ /dev/null @@ -1,155 +0,0 @@ -# Debugging notes from a GTA V port - -Lessons from bringing GTA V (RAGE, D3D11 path) up natively on an Android -phone (ARM64, D3D11 over DXVK and Vulkan on an Adreno 740). That port went -through the stage VIctory is at now: the title loads the world and then -does not move on into the game. What got it past that is written down here -as things to try. None of it has been checked against GTA VI. - -Nothing from either game is in this note: no code, names from it or data. - -## The world loads, but the game does not start - -In the port, the title got through boot, menus and the loading screen, -loaded the map, and then sat there: the loading screen (or a dark frame) -stayed up, memory stopped growing, nothing crashed. It was never one cause. -Each fix moved it a little further, to the next wait. The order below is -the order they turned up in. - -### First, find out what it is waiting for - -A hang with no crash only shows itself through state. These dumps, taken -while it sat there, are what named each cause: - -* **Every script thread with its state and program counter.** Taken - every few seconds during loading. A script that never leaves its first - instructions, or one that has faulted, stops the game flow even though - the engine keeps rendering. -* **The streaming queue.** When the head request stops moving: its file, - its state, whether the read completed, whether it was placed in memory, - and how many requests are pending against the loader's limit (30 in that - engine; past it, nothing new is issued). -* **All threads' stacks** (`VICTORY_STACKS`), to see who waits on what: a - sleeping thread waiting for a service that never answers looks idle, not - stuck. -* **Any warning or prompt the title opens**, with its text, logged from the - title's own call. See the next section on why. - -### The title is waiting for something the platform should give it - -These were the actual causes, each with what it looked like. - -**A prompt nobody can see or answer.** Twice the game was not stuck but -waiting for input. Once a "sign in" warning came up during autoload, and -the screen showed no text because fonts were not drawing yet. Once it was -the first-boot brightness calibration, which waits for a button press, and -input was not wired up. With a dark scene, the title may be showing a -dialog. Logging every warning or prompt with its text (and the button it -waits for) answers that in one run. - -**The signed-in user.** The save system asked whether a user was signed -in, and the replacement for the online platform answered no. Autoload then -stopped at the sign-in warning above. Answering "signed in" as a local -offline user fixed it; with no saves, autoload then starts a new game. In -VIctory that is the runtime-services layer: every user, licence and -package query the title makes while loading should get a definite "yes, -offline" answer. - -**A background service that never answers.** One thread slept forever -waiting for the online platform's entitlement check. That one was harmless, -but it is the same shape as a real stall: a title thread blocked on a -platform callback, event or async result that is never signalled. Check -that every async operation the HLE layer accepts completes, including the -ones that fail. - -**Data it waits on without reporting a missing file.** The loading screen -waited for sound banks that were not there yet: no error, just a wait. -After the banks were added, it moved on. - -**Data in a form it did not expect.** Script files were still encrypted -(they used the container's key, unlike the other resources). The script -system loaded them and failed silently. Every converted file should be -verified by a read in the title's own format, not by size. - -**The startup script faulting.** The first script faulted with "call -through a null function pointer" in its first instructions, and the game -never left the loading flow. The script VM was not translating the older -bytecode it was given. Natives were not the problem, although they looked -like it. If the title runs scripts, a VM fault log (script, program counter, -reason) is worth having before anything else. - -**Budgets and pools from the platform config.** The world's streaming -stalled because a memory budget was 0 MB: it was inherited from another -platform's config and cut down by a heap size that did not match. Later, -crossing from the first area to the main city aborted because a pool of -loaded objects was sized for a smaller data set. In VIctory the title reads -its config for the Xbox. If a memory figure the title asks the platform for -comes back smaller or 0, the title sizes its budgets from it and stalls -when they fill up. - -**A platform function returning garbage.** A "how many worker threads" -query had no branch for the new platform and returned garbage. It was used -as an index, and the physics crashed on the first frame of gameplay. In -VIctory the equivalents are system queries with an out of range answer -(processor count, core masks, memory sizes, GPU properties) that the title -uses to size arrays. - -**The render thread deadlocking with the main thread.** One fix took the -graphics context for a whole list of commands. The main thread then waited -for the context while the render thread held it waiting for the next list, -and the picture froze. Look at both threads' stacks when the frame freezes -and the process does not crash. - -**Streaming reads that never complete.** Sometimes one read request never -finished. The streamer was idle, the loader's queue filled up behind it, -and loading stopped. It was intermittent. In VIctory this is file I/O and -async completion in the HLE layer: a read, or a completion port or event, -that never gets signalled. It looks exactly like this. - -### Slow frames make "running" look like "stuck" - -Game flow in these engines advances per frame. At 0.5 to 1.8 s per frame, a -cutscene or scripted transition that takes 300 frames needs several minutes. -Before treating the game as stuck, check the script program counters and -the streaming queue over time: if they move, it is running, just slowly. - -## A dark scene after loading - -**Find the pass where the image goes empty.** In the port the world was -black and characters were flat grey shapes. A dump of every bound render -target before each change of targets (141 passes in one frame) showed that -the G-buffer and lighting were correct. The frame went black in the copy -that feeds post-processing: the title took a branch that skips that copy -on some platforms. More generally, anything the console does implicitly -(render-target metadata, fast clears, resolves) has to be done by the host -layer, or a later pass reads an empty target. - -**Auto-exposure turns one bad value into a dark frame.** A luminance -reduction that yields 0 or NaN darkens the whole scene. A missing compute -dispatch in that chain would look the same. Forcing a fixed exposure tells -the two apart. - -**A constant that arrives as 0 makes a pass sample texel (0,0).** That gives -one flat colour, exactly that pixel's. Check the constant buffer for zeros. - -## GPU hangs - -* A half-drawn frame left on screen by a GPU hang looked like a shading bug. - Separate the two first (WARP or full synchronisation). -* Waiting for the GPU before each present stopped the hangs. So did one - submission per draw. Both showed the fault depended on CPU/GPU overlap. -* Early fences (the title reusing memory because a fence said the GPU was - done) were tested and ruled out. In VIctory, title fences map onto host - fences, so the same check is worth one run. -* The cause there was the phone vendor's driver; switching to Mesa's Turnip - fixed it. - -## What does not carry over - -That port recompiled the title for another CPU; VIctory runs its x86-64 code -unchanged. These problems from the port do not apply: - -* memory ordering on ARM (empty barriers, counters seen before data); -* compiler differences (signed `char`, null checks after `new`, references - assumed non-null); -* the data formats and encryption of GTA V's PC release. diff --git a/docs/dependency-diagnostics.md b/docs/dependency-diagnostics.md deleted file mode 100644 index 7f9bfc8da8..0000000000 --- a/docs/dependency-diagnostics.md +++ /dev/null @@ -1,45 +0,0 @@ -# Dependency diagnostics - -`victory --diagnostic-jsonl FILE` writes structured events to a new file outside -the source tree. The parent directory must exist. Ordinary command output and -the `VICTORY_LOG` console filter continue to work. A diagnostic file failure is -reported on stderr and leaves the command result intact. - -This first implementation covers image reads in `inspect` and `run`, creating -the image cache directory, and the Win32 loader call. A missing synthetic file -exercises the CLI without running guest code: - -```powershell -$capture = Join-Path $env:TEMP ("victory-" + [guid]::NewGuid() + ".jsonl") -$absent = Join-Path $env:TEMP ("victory-" + [guid]::NewGuid() + ".exe") -cargo run --locked -p victory -- --diagnostic-jsonl $capture inspect $absent -cargo xtask diagnostics $capture -``` - -The inspect command is expected to return an error. The report shows the first -observed operation failure, distinct incidents and occurrence counts, and -whether the session ended cleanly enough to write its summary. A completed -session can still have a failed command. Test counts are based on explicit test -events in the input. An ordinary CLI session does not produce test events. - -## Event format - -Each complete line is a JSON event for schema version `1.0`. The timestamp is -UTC milliseconds since the Unix epoch. The sequence orders events written -within the session. Each observed operation failure starts a correlation group. -The current instrumentation reports one event per operation failure. A -correlation ID alone does not establish a causal link across operations. - -The diagnostic definition describes the returned code. The root cause stays -`undetermined` unless evidence establishes it. The loader's Windows binding -version is read from the checked-in lockfile and identified as a locked version. -For builds that provide it, `VICTORY_BUILD_COMMIT` is read at compile time and -included only if it has the form of a Git hash. - -Only fields allowlisted by the emitter are written. The JSONL excludes path -names, native messages that can contain user or guest data, and guest data from -the existing crash and capture facilities. The Rust error still carries its -original source for ordinary error handling. Limits are fixed at 4 MiB per -session for this implementation. A normal close reports any events omitted to -stay within that limit. A failed write or process termination can leave an -incomplete capture. diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md new file mode 100644 index 0000000000..dee02815c7 --- /dev/null +++ b/docs/fork-ray-tracing.md @@ -0,0 +1,85 @@ +# Ray tracing in this fork: what the title does and what has been built + +Status, 2026-11-25: **nothing is lit by ray tracing yet.** Most of the +machinery translates and is unit-tested; it has not yet run end to end in the +game. Everything here is off by default. + +## What the title does + +The title's indirect light (probes, bounce, reflections) and the +shadows of its lamps and sun are ray traced. Without them, anything the sun +does not hit directly is black: interiors, the shadowed side of a face, rooms +lit only by lamps. + +The title does not use a ray-tracing API: + +- Traversal is ordinary compute-shader code: a per-thread stack in shared + memory, and loads through raw 40-bit addresses of title memory. +- The static world's acceleration structures ship pre-built in the title's + data, in the console GPU's native node format (64-byte nodes: box nodes with + four children and 16-bit float bounds, 128-byte box nodes with 32-bit float + bounds, triangle nodes, instance nodes). They are unpacked on the GPU. +- A set of builder programs (from the title's `XboxBvhBuilder.dll`, 52 compute + programs) builds and refits the dynamic structures on the GPU every frame. +- Only the per-node test is hardware: the instructions + `image_bvh64_intersect_ray` and `image_bvh_intersect_ray`. One call tests a + ray against a box node's four children (returning the hit children, nearest + first) or against a triangle node (returning the intersection's numerator, + denominator and barycentric numerators). + +So mapping this onto the host's own ray tracing (DXR) is not practical: the +layer would have to know the geometry behind structures the title never +describes to it, and the traversal loops live in 64 of the title's own +programs. This fork runs the title's builder and traversal as translated +shaders and emulates the one instruction. + +## What this fork adds + +1. **The builder programs translate** (49 of 52; all that the title creates in + the scenes tested). They pass buffer addresses in a spilled parameter table + rather than in descriptors. Added: the spilled user-data table, root + unordered-access views (translator and host binding), byte and 16-bit buffer + accesses, and several control-flow shapes. +2. **Title memory by raw address from shaders.** A directory with one entry per + 64 KiB of title address space leads a shader to the layer's host copy of + that memory; loads, stores, atomic add/sub and float min/max go through it. + Before a dispatch the host makes ready the memory its root views and root + constants name. +3. **The ray test, emulated in DXIL.** Four slab tests and a sorting network + for box nodes; a watertight ray/triangle test for triangle nodes; both forms + of the instruction. A plain Rust reference lives in + `crates/victory-shader/src/bvh.rs`; tests run the emitted DXIL on the GPU + over 311 ray/node cases and compare with the reference bit for bit. +4. **The trace and shading programs translate** (59 of 64 trace programs, and + the irradiance-cache shading program). This needed lane masks treated as + plain numbers on some paths, and exact forms for programs written for + 64-lane waves running on a GPU with 32-lane waves. +5. **A safety rule on the host side.** The builder's stages run only while + every builder pipeline the title has created has a host pipeline; otherwise + none run (`VICTORY_BVH_BUILDER=1` asks for it; `VICTORY_BVH_QUARANTINE=1` + also keeps the builder's stores out of title memory, for a first test). A + partly working builder wrote garbage bounds into title memory and crashed + the title. + +## Known gaps + +- With `VICTORY_BVH_BUILDER=1` the builder still stays off in a real run: a few + of its pipelines are refused by the host (they still ask for 64-lane waves on + a 32-lane GPU) or do not translate. +- Five shadow-mask trace programs do not translate yet. +- An access to a title page that has no host copy is lost (a read gives zero, a + store is dropped). +- Not publicly documented, and assumed: the instruction's rounding, the order + of two boxes entered at the same distance, and the result for a ray exactly + through an edge. +- Cost on the GPU is unmeasured. + +## Where to look + +- `crates/victory-shader/src/bvh.rs`: the reference for the node test. +- `crates/victory-shader/src/emit/lower.rs`: the lowering of the two + instructions and of memory by address (`Lower::memory`). +- `crates/victory-shader/src/resource.rs`: address tracking for descriptors + and raw addresses. +- `crates/victory-gpu/src/pipeline.rs`, `draw.rs`: the builder rule and the + host side of root views and title memory. diff --git a/docs/linux-proton.md b/docs/linux-proton.md deleted file mode 100644 index 3d91d50042..0000000000 --- a/docs/linux-proton.md +++ /dev/null @@ -1,234 +0,0 @@ -# Linux and Proton - -VIctory is a Windows program. On Linux you can run the host tests, cross-build -`victory.exe`, and run that exe under Wine/Proton, where D3D12 goes through -vkd3d-proton. None of this is official support, and the title is **not -playable** on Linux any more than on Windows (see the status in the README). - -You supply your own files. Keep them, and everything built or derived from -them, outside the repository: see [asset-policy.md](asset-policy.md). Never -commit game data, built binaries or logs that contain title bytes. - -Tests use synthetic data generated by the repository's own code (for -example `tests/fixtures/hle-probe`); they need no game files, and none are -accepted on GitHub. - -## Where Linux support stands - -These links go stale as PRs land; check their state before relying on them. - -- [#90](https://github.com/Marvisak/VIctory/issues/90): `main` does not - build the whole workspace on Linux (`victory-gpu` stops at E0425). -- [#235](https://github.com/Marvisak/VIctory/pull/235) (open): `cfg(windows)` - gates so the workspace checks, builds and tests on - `x86_64-unknown-linux-gnu`. Closes #90. Windows behaviour is unchanged and - `victory run` on Linux still refuses to run titles. -- [#232](https://github.com/Marvisak/VIctory/pull/232) (open): an interim - Linux CI job for the crates that already build on `main`, and a fix that - lets `load_probe` run under Wine/Proton. -- [#112](https://github.com/Marvisak/VIctory/pull/112) (open, conflicts - with `main`): the larger Linux workspace, contributor setup and CI effort. - It can rebase onto #235. -- [#191](https://github.com/Marvisak/VIctory/pull/191) (open): a Linux - launcher and smoke test for Proton. It replaced #195. -- [#241](https://github.com/Marvisak/VIctory/pull/241) (open): where - `victory-core` keeps files on a non-Windows host (cache in - `$XDG_CACHE_HOME/victory`, data in `$XDG_DATA_HOME/victory`), config-file - paths relative to the file, `~` expansion, and a warning for a - `VICTORY_LOG` that does not parse. See - [Native tools and #241](#native-tools-and-241). - -## Host tests - -On current `main`, these crates build, test and are clippy-clean natively on -Linux. These are the commands #232's CI job runs: - -```sh -cargo xtask policy -L="-p victory-core -p victory-pe -p victory-formats -p victory-pipeline \ - -p victory-game -p victory-loader -p xtask" -cargo clippy --all-targets --locked $L -- -D warnings -cargo clippy --lib --locked -p victory-shader -- -D warnings -cargo test --locked $L -p victory-shader -- --exact \ - --skip image::tests::parses_own_test_binary \ - --skip image::tests::rva_to_file_offset_maps_entry_point \ - --skip image::tests::rva_to_file_offset_rejects_offsets_past_4_gib \ - --skip image::tests::rejects_iat_outside_image \ - --skip prepare::tests::patches_own_test_binary \ - --skip prepare::tests::keeps_iat_slots_when_import_size_excludes_the_terminator \ - --skip prepare::tests::file_name_is_stable_per_build -cargo xtask install-hooks # asset-policy check on every commit -``` - -The skipped `victory-pe` and `victory-loader` tests parse the test -executable itself as a PE image, which is an ELF on Linux; they still run -on Windows. `victory-shader`'s test target has a helper only the Windows -tests use, so only its library is linted. - -Keep `TMPDIR` outside the checkout. `victory-core`'s policy tests make -temporary folders and expect them to be outside the repository, so with -`TMPDIR` under the checkout `policy::tests::accepts_unrelated_directories` -fails with `InsideRepo`. - -`victory-gpu`, `victory-hle` and `apps/victory` need #235's gates. Until it -is merged, run `gh pr checkout 235` and then `cargo test --workspace`. #235 -also gates the PE self-parsing tests to Windows, so the `--skip` flags -above become no-ops there. - -To run the Windows test binaries under Wine/Proton, cross-build them with -`cargo xwin test --target x86_64-pc-windows-msvc --no-run` (or the -environment from the next section) and run the `.exe` files under -`target/x86_64-pc-windows-msvc/debug/deps/` with `wine`. Known Wine/vkd3d -gaps make a few of them fail; see #232 and #235 for the current counts and -the `load_probe` workaround (`VICTORY_HLE_PROBE_DLL`). - -## Tools on Linux vs running the title - -With #235, the `victory` subcommands that only read files (`inspect`, -`census`, `lib-exports`, `shader-info`, `translate`, `config`) build as a -native Linux ELF. `translate` reports the validator and pipeline checks as -unavailable off Windows. - -`victory run` is different: running the title needs D3D12 and the rest of -the Windows runtime, so it stays the cross-built `victory.exe` under -Proton, as described below. - -## Native tools and #241 - -On `main`, without `LOCALAPPDATA` (a native Linux build of the tools), the -default data folder ends up under the cache base (`~/.cache/victory/data`), -and an empty or relative `XDG_CACHE_HOME` makes the cache relative to the -working directory, which the asset policy then refuses. Set -`VICTORY_CACHE_DIR` and `VICTORY_DATA_DIR` to absolute paths outside the -checkout, or use #241, which changes that to: - -- cache: `$XDG_CACHE_HOME/victory`, else `~/.cache/victory`; - data: `$XDG_DATA_HOME/victory`, else `~/.local/share/victory`. Empty or - relative base variables are skipped. A data folder inside the cache is - refused. -- relative `[paths]` values in `victory.toml` are relative to the file, and - a leading `~` in them or in the `VICTORY_*` path variables is the home - directory. A Windows drive path such as the example file's - `D:\victory-data\game` is refused on Linux instead of being anchored - next to the file. -- `victory config` prints each path and where it came from (variable, - file or default). - -None of this changes `victory.exe` under Proton: there it is a Windows -program, `LOCALAPPDATA` is the prefix's, and the `Z:` paths below still -apply. - -## Cross-building victory.exe - -Needs the pinned toolchain with the `x86_64-pc-windows-msvc` target, LLVM -(`lld-link`, `clang-cl`, `llvm-lib`) and the Windows CRT and SDK from -[xwin](https://github.com/Jake-Shadle/xwin). - -```sh -rustup target add x86_64-pc-windows-msvc -xwin --accept-license splat --output ~/.cache/xwin - -X=$HOME/.cache/xwin -export CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER=lld-link -export CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS="-Lnative=$X/crt/lib/x86_64 -Lnative=$X/sdk/lib/um/x86_64 -Lnative=$X/sdk/lib/ucrt/x86_64" -export CC_x86_64_pc_windows_msvc=clang-cl -export CXX_x86_64_pc_windows_msvc=clang-cl -export AR_x86_64_pc_windows_msvc=llvm-lib -export CFLAGS_x86_64_pc_windows_msvc="--target=x86_64-pc-windows-msvc -Wno-unused-command-line-argument -fuse-ld=lld-link /imsvc$X/crt/include /imsvc$X/sdk/include/ucrt /imsvc$X/sdk/include/um /imsvc$X/sdk/include/shared" -export CXXFLAGS_x86_64_pc_windows_msvc="$CFLAGS_x86_64_pc_windows_msvc" - -cargo build --release -p victory --target x86_64-pc-windows-msvc -# target/x86_64-pc-windows-msvc/release/victory.exe - -cargo build --profile diag -p victory --features diagnostics --target x86_64-pc-windows-msvc -# target/x86_64-pc-windows-msvc/diag/victory.exe -``` - -The exe imports `VCRUNTIME140.dll`, the UCRT, `d3d12.dll`, `dxgi.dll`, -`d3dcompiler_47.dll` and `xinput1_4.dll`. Proton provides all of them; on a -plain Wine prefix without vcruntime140, run `winetricks vcrun2022`. - -## Running under Proton - -Tried with UMU-Proton (11.0) via [umu-run](https://github.com/Open-Wine-Components/umu-launcher). -Paths given to `victory.exe` are Windows paths, so use `Z:` plus the Linux -path. The `VICTORY_*` variables override `victory.toml`, as on Windows. - -```sh -export WINEPREFIX=$HOME/.local/share/victory/pfx -export GAMEID=umu-victory STORE=none -# PROTONPATH=<Proton dir> # optional; umu-run uses UMU-Proton when unset - -z() { printf 'Z:%s' "${1//\//\\}"; } -export VICTORY_GAME_DIR=$(z "$HOME/victory-data/game") -export VICTORY_DATA_DIR=$(z "$HOME/victory-data/data") -export VICTORY_CACHE_DIR=$(z "$HOME/victory-data/cache") -export VICTORY_LOG=info -# vkd3d-proton writes vkd3d-proton.cache into the working directory by -# default; keep it outside the checkout or `cargo xtask policy` flags it. -export VKD3D_SHADER_CACHE_PATH=$HOME/.local/share/victory/vkd3d-cache -mkdir -p "$VKD3D_SHADER_CACHE_PATH" - -# From the repository root: the cargo output from the build step above -# (use .../diag/victory.exe for the diagnostics build). -VICTORY_BIN=$PWD/target/x86_64-pc-windows-msvc/release/victory.exe -# Host logs go outside the checkout, one folder per run. -LOGS=$HOME/.local/share/victory/logs/$(date +%Y%m%d-%H%M%S) -mkdir -p "$LOGS" - -umu-run cmd.exe /c "$(z "$VICTORY_BIN") run $VICTORY_GAME_DIR\<the title's exe> --execute > $(z "$LOGS/host.out.log") 2> $(z "$LOGS/host.err.log")" -``` - -Proton does not pass the Windows console through, hence `cmd.exe /c` with -redirections to keep the log. Those logs can contain title-derived data, so -they live under `$LOGS`, not in the repository. If you copy `victory.exe` -somewhere else, point `VICTORY_BIN` at that copy, also outside the -repository. `crashes.log` is in the data folder as usual. - -`VKD3D_SHADER_CACHE_PATH` must be a directory outside the repository. If a -`vkd3d-proton.cache` file ever lands in the checkout, delete it rather than -committing it; `cargo xtask policy` rejects it. - -Seen on one machine (NVIDIA RTX 2060 SUPER, UMU-Proton 11.0, release build): -imports bind, the D3D12 device comes up on vkd3d-proton, the first-boot -screens and intro video run at 30 fps, and the title starts loading the -world. Some compute pipelines are refused with `E_INVALIDARG` (NVIDIA has -32-lane waves; see the README's shader row), and the title's view heap is -larger than vkd3d-proton allows on that GPU, so it is capped. - -### Indirect draws under Wine - -Wine's `D3DCompile` can refuse the shader that clamps indirect-draw -arguments, so indirect execution is dropped -([#170](https://github.com/Marvisak/VIctory/issues/170)). Two open fixes -take different routes: [#178](https://github.com/Marvisak/VIctory/pull/178) -falls back to DXC, and [#190](https://github.com/Marvisak/VIctory/pull/190) -builds the clamp as hand-written DXIL with no compiler at run time. They -conflict, so only one of them should be merged; measurements under Proton -are in the comments on both PRs. - -### Open Wine/Proton fixes - -Still open: - -- [#76](https://github.com/Marvisak/VIctory/pull/76): xmem maps a run of - physical pages over several placeholders. It merges cleanly onto - current `main`, so you can stack it with `gh pr checkout 76`. - -Already on `main`: [#41](https://github.com/Marvisak/VIctory/pull/41) -(reject non-software WARP adapters under Proton) and -[#53](https://github.com/Marvisak/VIctory/pull/53) (commit physical-page -sections whole under Wine). - -These lists go stale as PRs land. If you keep a fork, sync its `main` from -upstream `main` (taking upstream's side on any conflict) before you rebase -your own branches onto it. - -## Diagnostics - -`VICTORY_D3D12_WARP`, `VICTORY_KEYS`, `VICTORY_STACKS` and the other -variables in the README's Debugging table only work in the `diag` build -above; a release build ignores them. Under Proton, `VICTORY_D3D12_WARP=1` -asks for the WARP adapter, and #41 refuses an adapter that is not a software -one instead of using the real GPU. Add `WINEDEBUG=+seh,+loaddll` for Wine's -view of faults and DLL loads. diff --git a/docs/media/catez.gif b/docs/media/catez.gif new file mode 100644 index 0000000000..fe4786c6dd Binary files /dev/null and b/docs/media/catez.gif differ diff --git a/docs/proton-launcher.md b/docs/proton-launcher.md deleted file mode 100644 index 0237a80929..0000000000 --- a/docs/proton-launcher.md +++ /dev/null @@ -1,61 +0,0 @@ -# Running VIctory with the Proton launcher - -Install `umu-run` on x86-64 Linux. The game requires an AVX2 CPU and a Vulkan -driver that exposes Shader Model 6.6 through vkd3d-proton. -[UMU installation](https://github.com/Open-Wine-Components/umu-launcher#installation) - -Use a Windows x64 build of VIctory. The launcher supports MSVC builds, -including those produced by `cargo xwin`, and LLVM-MinGW builds. Both Rust -targets use native Windows thread-local storage (TLS). A loader test with -the GCC-based `x86_64-pc-windows-gnu` target aborted when a title DLL called -into Rust during thread startup. - -```sh -./scripts/victory-proton.sh "/path/to/game/title.exe" --execute -``` - -Omit `--execute` to check mapping and import binding first. The launcher -forwards other `victory run` options and arguments after `--`. To select a -specific build, set `VICTORY_EXE` to its Linux path. By default the launcher -looks beside itself for `victory.exe`, then under `${CARGO_TARGET_DIR:-target}` -for the gnullvm and MSVC release builds, in that order. - -On first launch UMU fetches Proton and the Steam Linux Runtime. The default -prefix is `${XDG_DATA_HOME:-$HOME/.local/share}/victory/proton`, and the -default `GAMEID` is `umu-victory`. Set `WINEPREFIX`, `GAMEID` or `PROTONPATH` -to override them. Use Windows paths in `victory.toml`. - -## Building with LLVM-MinGW - -Install Rust with rustup and put the x86-64 Linux UCRT distribution of -LLVM-MinGW first on `PATH` (its `bin` directory). -[LLVM-MinGW releases](https://github.com/mstorsjo/llvm-mingw/releases) - -```sh -rustup target add x86_64-pc-windows-gnullvm -cargo build --locked --release -p victory --target x86_64-pc-windows-gnullvm -``` - -## Testing without game files - -`./tests/proton-smoke.sh` compiles its synthetic title with the LLVM-MinGW -toolchain and gnullvm Rust target above, even when `VICTORY_EXE` points to -an MSVC build. The test checks the launcher's exit status and the return -value from the title. It uses a separate `victory/proton-smoke` prefix under -the XDG data directory. Set `VICTORY_SMOKE_PREFIX` to choose another test prefix. - -To reproduce the loader integration tests after the smoke test, build the -DLL fixture on Linux and set `VICTORY_HLE_PROBE` to the Windows path of the -built DLL. This lets the test load it without starting Cargo inside Proton. -Run these commands from the checkout in Bash. - -```sh -target=x86_64-pc-windows-gnullvm -fixture_dir=$(realpath -m "${CARGO_TARGET_DIR:-target}/proton-fixture") -cargo build --locked --manifest-path tests/fixtures/hle-probe/Cargo.toml \ - --target "$target" --target-dir "$fixture_dir" -export VICTORY_HLE_PROBE="Z:$fixture_dir/$target/debug/hle_probe.dll" -export WINEPREFIX=${VICTORY_SMOKE_PREFIX:-${XDG_DATA_HOME:-$HOME/.local/share}/victory/proton-smoke} -PROTON_VERB=runinprefix GAMEID=umu-victory CARGO_TARGET_X86_64_PC_WINDOWS_GNULLVM_RUNNER=umu-run \ - cargo test --locked --target "$target" -p victory-loader --test load_probe -- --test-threads=1 -``` diff --git a/docs/pt-BR/architecture.md b/docs/pt-BR/architecture.md deleted file mode 100644 index 42800542ac..0000000000 --- a/docs/pt-BR/architecture.md +++ /dev/null @@ -1,102 +0,0 @@ -# Arquitetura - -> Tradução de [docs/architecture.md](../architecture.md), feita em 2026-11-23. -> Em caso de divergência, vale a versão em inglês. - -``` - arquivos do usuário (fora do repo) VIctory - ────────────────────────────────── ───────────────────────────────────────── - assets do jogo ───────────────────────► victory-pipeline + victory-game - (victory-formats, victory-shader) - │ - ▼ - cache_dir: dados convertidos - │ - executável do jogo ─► victory-loader ─► código do jogo (x86-64 nativo) - prepara, mapeia, │ imports - vincula ▼ - victory-hle ── Windows do host (APIs compartilhadas) - │ D3D12.X - ▼ - victory-gpu ─► D3D12 do host - │ shaders na criação do pipeline - ▼ - victory-shader ◄─► cache_dir -``` - -Os shaders são traduzidos quando o jogo cria um pipeline, a partir dos bytes -que ele passa, de onde quer que os tenha carregado (executável, arquivo -compactado, memória). Convertê-los antecipadamente a partir de arquivos serve -só como aquecimento. - -## Crates - -| Crate | Função | -|-------|--------| -| `victory-core` | configuração, proteção da política de assets, logs | -| `victory-pe` | análise somente leitura de PE32+ e de bibliotecas de importação | -| `victory-loader` | prepara, mapeia, vincula e inicia a imagem do jogo | -| `victory-hle` | implementações das APIs do console, política de repasse ao host | -| `victory-gpu` | objetos D3D12.X, command lists e memória de GPU → D3D12 do host | -| `victory-shader` | containers de shader do Xbox → shaders do host | -| `victory-formats` | layouts de textura da GPU (tamanhos, tiling, detiling), decodificação BCPack, codecs de áudio | -| `victory-pipeline` | trait de conversor, cache endereçado por conteúdo | -| `victory-game` | formatos, identidades de build e hooks específicos de Grand Theft Auto VI | -| `apps/victory` | interface de linha de comando | -| `xtask` | verificação da política de assets, git hooks | -| `tests/fixtures/hle-probe` | um "jogo" substituto (código nosso) para testes do loader | - -Tudo, exceto `victory-game`, é de nível de plataforma e pode ser testado com -qualquer jogo de Xbox Series. - -## Resolução de imports - -Para cada `dll!função` que o jogo importa, nesta ordem: - -1. a nossa implementação em `victory-hle::modules` (sempre tem prioridade); -2. a própria função do host, se `HostPolicy` permitir aquela DLL; -3. um export de uma DLL que o jogo traz junto ao executável, mapeada como o - executável (só DLLs que nenhuma das opções acima atende); -4. um stub gerado que informa o nome do import quando chamado - (`--unimplemented trap` entra no depurador e aborta; `zero` registra uma - vez e retorna 0). - -`LoadLibrary*` de uma DLL exclusiva do console que implementamos (ex.: -`xgameruntime.dll`) retorna um pseudo-handle; `GetProcAddress` nele encontra -as nossas funções. `LoadLibrary*` de uma DLL do jogo retorna a imagem mapeada, -mapeando-a antes se nada a importar. Por nome, assim como por import, o jogo -só recebe DLLs do host que `HostPolicy` repassa, e `GetProcAddress` em uma -delas retorna a nossa substituição onde a vinculação de imports retornaria. -`QueryApiImpl` entrega os nossos objetos de runtime por id de provedor e de -interface (`victory-hle::modules::xgameruntime` lista as áreas); áreas online -respondem como um console offline. Os saves do jogo são arquivos dentro de -`VICTORY_DATA_DIR`. - -O armazenamento do jogo é uma unidade no console, e os jogos montam caminhos -a partir dela. `victory-hle::modules::files` vincula todo import do jogo que -recebe caminhos (kernel32 e o runtime C/C++) e reescreve caminhos de uma -unidade virtual para a pasta do host por trás dela; o armazenamento local -persistente é uma dessas unidades, sobre uma pasta dentro de -`VICTORY_DATA_DIR`. Outros caminhos chegam ao host sem alteração. - -O código de um exe acessa seu TLS estático como slot 0; mapeado como DLL ele -recebe outro slot, então o loader redireciona esses acessos -(`victory-loader::tls`). `victory run --execute` instala um relator de crashes -que identifica falhas como `módulo+rva` e desenrola a pilha da thread que -falhou (`victory-loader::crash`). - -`victory census` mostra essa classificação sem executar nada (ele não mapeia -DLLs do jogo; `victory run` sem `--execute` mapeia). - -## Shaders - -`victory_shader::ir::build` transforma um programa nativo em SSA, uma -instrução por instrução de máquina. `victory_shader::structure` então remove o -EXEC: máscaras de lanes viram booleanos por lane, testes de máscara de toda a -wave viram desvios por lane, e instruções vetoriais mantêm uma guarda só onde -uma lane pode alcançá-las com seu bit EXEC desligado. -`victory_shader::resource` rastreia cada descritor e endereço de memória -escalar até o parâmetro raiz de onde vem (tabela, heap, root descriptor ou -constante). `victory translate` passa todos os shaders que encontra -(containers, arquivos SGD5) por essas etapas e lista o que eles ainda não -conseguem tratar. diff --git a/docs/pt-BR/asset-policy.md b/docs/pt-BR/asset-policy.md deleted file mode 100644 index b580afb8a3..0000000000 --- a/docs/pt-BR/asset-policy.md +++ /dev/null @@ -1,70 +0,0 @@ -# Política de assets (regra nº 1) - -> Tradução de [docs/asset-policy.md](../asset-policy.md), feita em 2026-11-23. -> Em caso de divergência, vale a versão em inglês. - -**Nada do jogo é armazenado neste repositório, nunca.** Tudo é gerado na -máquina do usuário a partir de arquivos fornecidos por ele. O mesmo vale para -outros jogos usados em testes e para qualquer outro material proprietário. - -## Não é permitido - -Em nenhuma forma (arquivos, literais de string, fixtures, snapshots, -documentação): - -* assets: modelos, texturas, shaders, áudio, vídeo, textos, arquivos - compactados; -* o executável ou qualquer parte dele: seções de dados, strings, tabelas, - recursos, código além das assinaturas descritas abaixo; -* qualquer coisa derivada deles: assets convertidos, código descompilado ou - desmontado, dumps de shaders, tabelas extraídas, capturas de tela. - -## É permitido - -* código nosso que entende formatos; -* identidades de build: BLAKE3 de um executável, GUID/age do CodeView; -* offsets, por build, das funções em que fazemos hook, com nomes escolhidos - por nós; -* assinaturas de padrões de bytes que localizam funções ou dados no - executável; -* pequenas constantes de interoperabilidade (números mágicos, valores de enum) - escritas por nós; -* dados de teste sintéticos gerados pelo nosso próprio código. - -## A única exceção - -`crates/victory-formats/src/bcpack-tables.bin` (cerca de 78 KB): as tabelas -constantes do formato BCPack (modelos de entropia, tabelas de ranking de -índices, códigos de controle, dicionários por formato). Um stream BCPack não -pode ser decodificado sem exatamente essas tabelas, e elas não podem ser -derivadas; por isso são distribuídas com o VIctory por decisão do dono do -projeto (2026-11-23), registradas como exceção em `xtask/src/policy.rs`. Elas -fazem parte do formato, não são trabalho nosso, e a licença do repositório não -as cobre. Nada mais desse tipo é aceito. - -## Onde ficam os dados - -Fora do repositório, configurados em `victory.toml`: `game_dir` (o dump do -usuário), `test_titles` e `cache_dir` para tudo que é derivado (padrão -`%LOCALAPPDATA%\victory\cache`). - -## Como é garantido - -1. O `.gitignore` mantém tipos comuns de dados fora do `git status`. -2. `cargo xtask policy` (executado pelo hook de pre-commit; instale com - `cargo xtask install-hooks`) é uma lista de permissões: os arquivos precisam - ter um tipo permitido, ter menos de 512 KiB, não conter dados binários nem - assinaturas binárias conhecidas, e não ter sequências longas de hex/base64. - Exceções precisam de uma entrada com justificativa em - `xtask/src/policy.rs`. -3. Em tempo de execução, tudo que grava dados derivados chama - `victory_core::ensure_outside_repo`. -4. Testes que precisam de arquivos reais recebem os caminhos por variáveis de - ambiente e são pulados quando elas não estão definidas. Eles verificam - propriedades, nunca snapshots. - -## Se algo escapar - -Um commit de correção não basta. Reescreva o histórico -(`git filter-repo --path <arquivo> --invert-paths`), faça force-push e peça -para todos clonarem de novo. diff --git a/docs/pt-BR/instalacao.md b/docs/pt-BR/instalacao.md deleted file mode 100644 index ce39da0fb6..0000000000 --- a/docs/pt-BR/instalacao.md +++ /dev/null @@ -1,191 +0,0 @@ -# Guia de instalação para iniciantes - -Este guia é para quem nunca compilou um programa. Ele leva você do zero até o -VIctory compilado e testado no seu PC. Os comandos são os mesmos do -[README](../../README.pt-BR.md), só que explicados passo a passo. - -> **Antes de começar.** O VIctory **ainda não é jogável** (veja a seção -> "Situação" do README). Ele também **não traz nenhum arquivo do jogo** e este -> guia não explica como obtê-los. Para rodar o jogo você precisa dos arquivos -> da sua própria cópia; para compilar e rodar os testes, não precisa de nada -> do jogo. - -## 1. Confira se o seu PC atende aos requisitos - -| Requisito | Como conferir | -|-----------|---------------| -| Windows 10 ou 11, 64 bits | **Configurações → Sistema → Sobre**: "Tipo de sistema" deve dizer 64 bits | -| Processador com AVX2 | Praticamente todo Intel Core de 4ª geração (2013) em diante e todo AMD Ryzen têm | -| Placa de vídeo com DirectX 12, shader model 6.6 e mesh shaders | Na prática, placas "DirectX 12 Ultimate": NVIDIA RTX 20 ou mais nova, AMD Radeon RX 6000 ou mais nova, Intel Arc. Mantenha o driver de vídeo atualizado | -| Memória suficiente para rodar o jogo | Não há um mínimo oficial, mas hoje o jogo renderiza em 4K, e com 16 GB de RAM e 8 GB na placa de vídeo pode faltar memória (issue [#203](https://github.com/Marvisak/VIctory/issues/203)). Para compilar e rodar os testes, isso não importa | -| Alguns GB livres em disco | A compilação e o cache ocupam bastante espaço | - -Os menus funcionam sem mesh shaders; o mundo do jogo precisa deles. - -## 2. Instale as ferramentas - -Você vai instalar três coisas. Depois de cada instalação, **feche e abra de -novo** o PowerShell, senão ele não encontra os programas novos. - -### 2.1 Git - -O Git baixa o código do projeto e mantém ele atualizado. - -1. Acesse <https://git-scm.com/download/win> e baixe o instalador para Windows. -2. Instale com as opções padrão (é só ir clicando em **Next**). - -### 2.2 Rust e as ferramentas de C++ da Microsoft - -O Rust é a linguagem do VIctory. No Windows ele precisa também das -ferramentas de compilação de C++ da Microsoft, e o instalador do Rust oferece -instalá-las para você (pelo Visual Studio Community, que é gratuito). - -1. Acesse <https://rustup.rs> e baixe o **rustup-init.exe** (64 bits). -2. Execute. Se aparecer a mensagem de que faltam os pré-requisitos do Visual - Studio, escolha a opção **1** (instalação rápida pelo Visual Studio) e - aguarde o instalador da Microsoft terminar. Ele pode demorar e pedir para - reiniciar. -3. De volta à janela do Rust, escolha a opção **1** (instalação padrão). - -Se preferir instalar as ferramentas de C++ à mão: baixe o **Build Tools para -Visual Studio** no site da Microsoft e marque a carga de trabalho -**Desenvolvimento para desktop com C++**. - -> Não se preocupe com a versão do Rust. O projeto fixa a versão certa no -> arquivo `rust-toolchain.toml`, e o Rust baixa essa versão sozinho na -> primeira vez que você compilar. - -### 2.3 Confira se deu certo - -Abra um PowerShell novo e rode: - -```powershell -git --version -cargo --version -``` - -Os dois devem mostrar um número de versão. Se aparecer "não é reconhecido como -nome de cmdlet", feche e abra o PowerShell; se continuar, reinstale a -ferramenta que falhou. - -## 3. Baixe o código - -Escolha uma pasta para o projeto (por exemplo, a sua pasta de usuário) e rode: - -```powershell -cd $HOME -git clone https://github.com/Marvisak/VIctory.git -cd VIctory -``` - -A partir daqui, todos os comandos são rodados **dentro da pasta `VIctory`**. - -## 4. Compile e rode os testes - -```powershell -cargo test --workspace -``` - -Na primeira vez isso demora bastante: o Rust baixa a versão certa do -compilador, baixa as bibliotecas usadas pelo projeto e compila tudo. As -próximas vezes são bem mais rápidas. - -No final deve aparecer `test result: ok` para cada parte do projeto. Testes -que precisam de arquivos que você não configurou são pulados, e isso é normal. - -> **No Windows 10**, o teste `only_loopback_is_reachable` falha com a -> mensagem `winhttp.dll lacks WinHttpGetProxySettingsEx`. É um problema -> conhecido do próprio teste (issue -> [#118](https://github.com/Marvisak/VIctory/issues/118)), não da sua -> instalação: pode seguir em frente. - -Agora compile o programa em si: - -```powershell -cargo build --release -p victory -``` - -O resultado fica em `target\release\victory.exe`. - -> **Só quer ajudar testando?** Se você parou aqui e os testes passaram, isso -> já é uma informação útil para o projeto, porque até agora ele foi testado em -> pouquíssimas máquinas. Se algo falhar, abra uma issue com a mensagem de erro, -> o seu processador, a sua placa de vídeo e a versão do Windows. - -## 5. Configure os caminhos - -Esta etapa só é necessária para rodar o jogo. - -1. Crie uma pasta **fora** da pasta `VIctory` para os seus arquivos, por - exemplo `D:\victory-data\game`. O VIctory se recusa a usar caminhos dentro - do repositório, para que nenhum arquivo do jogo acabe enviado por engano. -2. Crie o seu arquivo de configuração a partir do exemplo: - - ```powershell - copy victory.example.toml victory.toml - notepad victory.toml - ``` - -3. No Bloco de Notas, troque o valor de `game_dir` pelo caminho da sua pasta e - salve. As outras linhas podem ficar como estão. -4. Confira se o VIctory entendeu os caminhos: - - ```powershell - cargo run -p victory -- config - ``` - -O `victory.toml` fica fora do controle do Git, então ele nunca é enviado para -o GitHub. - -## 6. Rode - -```powershell -target\release\victory.exe run D:\victory-data\game\<exe do jogo> --execute -``` - -Troque o caminho pelo da sua pasta e pelo nome do executável do jogo. A barra -de título da janela mostra o framerate. Sem controle conectado, o teclado -funciona como controle (a tabela de teclas está no README). - -> **Atenção.** Hoje, ao entrar no mundo do jogo com uma placa de vídeo de -> verdade, ela pode travar, e o Windows reinicia o driver de vídeo: todos os -> monitores ficam pretos por um instante. Isso é esperado no estado atual do -> projeto e não estraga nada, mas salve o que estiver fazendo em outros -> programas antes. - -## 7. Atualize - -O projeto muda quase todo dia. Para pegar a versão mais nova: - -```powershell -git pull -cargo build --release -p victory -``` - -## Problemas comuns - -| Problema | O que fazer | -|----------|-------------| -| `git` ou `cargo` "não é reconhecido" | Feche e abra o PowerShell. Se continuar, reinstale a ferramenta | -| Erro falando de `link.exe` ou do linker | Faltam as ferramentas de C++: instale o Build Tools com **Desenvolvimento para desktop com C++** (passo 2.2) | -| A compilação parece travada | A primeira compilação demora mesmo. Espere enquanto o processador estiver em uso | -| Só o teste `only_loopback_is_reachable` falha, no Windows 10 | Problema conhecido do teste, não da instalação (issue [#118](https://github.com/Marvisak/VIctory/issues/118)) | -| O jogo fecha logo no início com `0xc000001d` (instrução ilegal) | Acontecia em processadores sem a instrução CLWB (Intel até a geração Broadwell e alguns AMD) e já foi corrigido. Atualize (passo 7) e compile de novo | -| `crashes.log` mostra o erro 1455 do Windows | Falta memória confirmada. Feche outros programas ou aumente o arquivo de paginação do Windows e tente de novo. Veja em **Gerenciador de Tarefas → Desempenho → Memória → Confirmada** | -| Os monitores piscam pretos ao entrar no mundo | É o travamento de GPU descrito no passo 6. Para investigar sem travar, há um modo de diagnóstico que usa o processador no lugar da placa de vídeo; veja "Depuração" no README | -| Onde ficam saves, configurações e o `crashes.log` | Em `%LOCALAPPDATA%\victory\data`. Cole esse caminho na barra de endereço do Explorador de Arquivos | - -## Como relatar um problema - -Abra uma issue em <https://github.com/Marvisak/VIctory/issues> e inclua: - -- o que você fez e o que aconteceu; -- processador, placa de vídeo, versão do driver e versão do Windows; -- o trecho do `crashes.log`, se houver; -- o comando que você rodou. - -Nunca anexe arquivos do jogo nem trechos do executável. O projeto não aceita -nenhum material do jogo (veja a [política de assets](asset-policy.md)). - -Pode escrever em português se preferir, mas em inglês mais gente consegue -ajudar. diff --git a/languages/README.id.md b/languages/README.id.md deleted file mode 100644 index 38fa434d0c..0000000000 --- a/languages/README.id.md +++ /dev/null @@ -1,120 +0,0 @@ -# VIctory - -*Read this in: [English](../README.md)* - -Menjalankan Grand Theft Auto VI (Xbox Series X|S) secara native di Windows, dari file yang disediakan oleh pengguna. - -Kode x86-64 milik game berjalan tanpa perubahan di dalam proses kita; VIctory menyediakan platform di bawahnya dan mengonversi data game — di muka jika memungkinkan, dan saat pertama dipakai jika tidak (shader). Lihat [docs/architecture.md](../docs/architecture.md). - -## Status (2026-11-23) - -**Belum bisa dimainkan.** Game berhasil boot, menjalankan menu-menunya di 30 fps, dan memuat dunia — namun rendering-nya gagal. - -| Tahap | Status | -|-------|--------| -| Boot, layar pertama kali (aksesibilitas, bahasa, pengaturan, hukum) | berjalan, 30 fps | -| Video intro dengan suara | berjalan | -| Layar start, profil dan save | berjalan | -| Loading ke dalam dunia (sekitar 50 detik) | berjalan | -| Dunia (intro misi pertama) | tercapai dan berjalan dengan indirect draws; title card-nya merender, scene setelahnya masih gelap; 0,5–1,8 detik per frame | - -Diuji pada satu mesin: Windows 11, AMD RX 6700 XT. - -> **Peringatan.** Memasuki dunia di GPU nyata saat ini dapat membuatnya hang, lalu Windows akan mereset driver display (semua monitor menjadi hitam sesaat). Untuk investigasi lebih lanjut, gunakan diagnostics build dengan `VICTORY_D3D12_WARP=1`, yang merender di atas software adapter. - -Apa yang dikerjakan setiap bagian saat ini dan apa yang masih dibutuhkan: - -| Subsistem | Saat Ini | Yang Dibutuhkan | -|-----------|----------|-----------------| -| Loader | Menjalankan executable dan DLL-nya di dalam proses kita; laporan crash menyebut kode yang bermasalah dan disimpan di `crashes.log` | – | -| Runtime services | Satu pengguna offline yang sudah login, lisensi, paket, save yang bertahan walau dimatikan di langkah mana pun, dialog input teks | Speech masih bisu; dialog dan relaunch belum diuji secara live | -| Network | Offline by design: game tidak bisa mengakses jaringan | – | -| File dan streaming | Arsip dan data streaming terbaca, zlib dan BCPack didekode secara paralel | Loading dibatasi oleh penulisan ke memori game | -| Input | XInput pad, keyboard, keyboard sebagai pengganti pad | Trigger rumble | -| Audio | Suara menu, video, dan loading; XMA voices dan Opus stream terdekode | Reverb masih bisu; hasil Opus belum diverifikasi terhadap game | -| GPU: menu | Draw, compute, dan presentasi di host D3D12; hanya memori game yang berubah yang disalin | Frame pacing drift di satu layar pada release build | -| GPU: dunia | Mesh pipeline, shader-written buffer, descriptor lifetime, indirect execution (argumen di-clamp), pipeline yang dibuat oleh worker thread dan disimpan ke disk | Sebagian besar scene masih hilang (shader yang belum diterjemahkan menggugurkan draw); frame memakan waktu detik-an; real query, depth bounds, HDR, dan scaling belum ada | -| Shader | Kode GPU konsol dikompilasi ulang ke DXIL saat pertama dipakai, disimpan di cache disk. Menu: semua. Dunia: mesh 8.191 dari 8.506, vertex/pixel 10.617 dari 12.346, compute 1.643 dari 2.539 | 64-bit image atomic, merged geometry stage, shader untuk ray-tracing builder; beberapa program compute memerlukan GPU dengan 64-lane wave | -| Tekstur | Tiled layout konsol dan detiling untuk mode yang dipakai game | Render-target metadata plane | -| Mode Series S | Berjalan melewati menu hingga layar loading | Dunia, sama seperti di atas | - -## Memulai - -Persyaratan: Windows 10/11 x64, CPU dengan AVX2, GPU Direct3D 12 dengan shader model 6.6 (dan mesh shader untuk dunia), Rust (versi dikunci di `rust-toolchain.toml`). - -Game juga membutuhkan beberapa GiB Windows commit yang tersedia saat startup. Periksa **Committed** di **Task Manager → Performance → Memory**. Jika `crashes.log` melaporkan Windows error 1455, tutup aplikasi lain atau perbesar ukuran paging file Windows, lalu coba lagi. - -```powershell -cargo xtask install-hooks # cek kebijakan aset di setiap commit -copy victory.example.toml victory.toml # lalu atur path kamu (di luar repo) -cargo test --workspace # tidak membutuhkan data game -cargo run -p victory -- config # periksa path kamu -``` - -Jalankan game: - -```powershell -cargo build --release -p victory -target\release\victory.exe run <direktori game>\<executable game> --execute -``` - -Caption jendela menampilkan framerate. Save, pengaturan, dan `crashes.log` disimpan di folder data (default `%LOCALAPPDATA%\victory\data`), data turunan di folder cache. - -Input: XInput pad. Jika tidak ada yang terhubung, keyboard berfungsi sebagai pad selama jendela game dalam fokus: - -| Tombol | Pad | -|--------|-----| -| W A S D / I J K L | stick kiri / kanan | -| arrow keys | D-pad | -| Enter, Backspace, X, Y | A, B, X, Y | -| Q / E, Z / C | shoulder button, trigger | -| F / H | klik stick | -| Esc, Tab | Menu, View | - -## Perintah - -``` -victory inspect <exe|dll> [--imports] [--exports] -victory census [paths...] [--missing] [--strict] -victory lib-exports <import.lib> [--list] -victory shader-info [paths...] [--verbose] [--disasm] -victory translate [paths...] [--validate] [--pipelines] [--list] [--jobs N] -victory run <exe> [--execute] [--unimplemented trap|zero] [--strict] - [--console series-x|series-s] [-- <argumen game>] -victory config -``` - -Logging: `VICTORY_LOG=victory_loader=trace,info` (release build mencatat info ke atas). - -## Debugging - -Release build tidak memiliki alat bantu debugging. Aktifkan dengan: - -```powershell -cargo build --profile diag -p victory --features diagnostics # target\diag\victory.exe -``` - -| Variabel | Efek | -|----------|------| -| `VICTORY_LOG=<target>=debug,...` | output debug dan trace | -| `VICTORY_STACKS=20,60` | stack setiap thread pada detik-detik tersebut | -| `VICTORY_WATCH=<rva>,...` | mencatat u32 milik game saat nilainya berubah | -| `VICTORY_KEYS=30:Enter,35:X` | menekan tombol pada detik-detik tersebut, dengan atau tanpa fokus | -| `VICTORY_CRASH_SAVE=<rva>:<len>,...` | menyimpan memori game ke folder cache saat crash | -| `VICTORY_CAPTURE=<dir>` | menyimpan frame yang dipresentasikan (pangkat dua, atau `VICTORY_CAPTURE_FRAMES=<list>`) | -| `VICTORY_DUMP_TARGETS=1` | bersama dua di atas, menyimpan setiap render target dari frame tersebut | -| `VICTORY_D3D12_DEBUG=1` | host debug layer | -| `VICTORY_D3D12_GBV=1` | bersama di atas, GPU-based validation (penggunaan descriptor buruk dilaporkan, bukan di-fault; lambat) | -| `VICTORY_D3D12_DRED=1` | saat terjadi kegagalan GPU, alokasi yang terkena dampak dan perintah yang sedang berjalan | -| `VICTORY_SKIP_PIPELINES=<hash>,...` | lewati draw dan dispatch, termasuk yang indirect, yang pipeline-nya mengandung hash shader 16-digit yang dicantumkan | -| `VICTORY_GPU_TIMING=1` | bersama di atas, setiap daftar submission dijalankan dan diukur waktunya sendiri; daftar yang lambat dicatat bersama perintah-perintah paling lambatnya | -| `VICTORY_D3D12_WARP=1` | perangkat host di software adapter (lambat; tidak bisa mereset driver) | -| `VICTORY_SHADER_LOOP_LIMIT=<n>` | loop shader yang sudah diterjemahkan berhenti setelah `n` iterasi per lane, bukan 2^20 (entri cache shader tersendiri); jika `n` yang lebih kecil membuat frame dunia jauh lebih cepat, berarti loop yang mencapai batas tersebut yang membuatnya lambat | -| `VICTORY_AUDIO_CAPTURE=<file.wav>` | merekam audio yang diputar game (proses kita saja) | -| `VICTORY_XMA_DUMP=<dir>` | menyimpan konteks dan input dari 32 XMA voice pertama | - -Setiap build menambahkan crash dan kegagalan GPU host ke `crashes.log` di folder data game. - -## Lisensi - -GPL-3.0-or-later. Lihat [LICENSE](../LICENSE). diff --git a/rustfmt.toml b/rustfmt.toml index 632b8e2ab3..8d1691c59e 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,5 +1,2 @@ -# VIctory Rust formatting configuration -edition = "2024" -newline_style = "Unix" +max_width = 100 use_field_init_shorthand = true -use_try_shorthand = true diff --git a/scripts/pilot/README.md b/scripts/pilot/README.md deleted file mode 100644 index 86de1a70bf..0000000000 --- a/scripts/pilot/README.md +++ /dev/null @@ -1,84 +0,0 @@ -# VIctory Pilot - -Pilot turns a Windows PC into a test machine that works with the developer -by itself. You start it once and leave it running. It then keeps doing four -things: - -1. **Builds and tests every new commit** on the branch, including the - Windows-only crates (`victory-gpu`, `victory-hle`, `victory-loader`) that - cannot be compiled where the fixes are written. -2. **Runs the game**, once you have chosen it, and watches for crashes, hangs - (no output for a few minutes) and GPU device removal. -3. **Reports what breaks** as issues on - [MfDev0/victory](https://github.com/MfDev0/victory/issues), titled - `[Pilot] ...`. Each report has the machine, the commit, the new - `crashes.log` entries, the most frequent warnings and the end of the - output. It also keeps a `[Pilot] status` issue up to date. -4. **Picks up fixes**: when a new commit lands on the branch, Pilot updates, - rebuilds, retests and reruns the game. If a crash does not come back, - Pilot closes its report with a note. - -A dashboard at `http://localhost:8765/` shows all of it live: what Pilot is -doing, the game's output, the reports, and buttons to choose the game, run, -stop, rebuild, test, or send a note ("the screen went black after the -logo"). - -## Start - -1. Download [`VIctoryPilot.cmd`](https://github.com/MfDev0/victory/raw/refs/heads/arena/59fabb00-victory/scripts/pilot/VIctoryPilot.cmd) - (right-click, *Save link as...*). -2. Double-click it. If Windows SmartScreen warns about it, choose - *More info*, then *Run anyway*. -3. The first start installs what is missing with `winget`: Git, Rust, the - GitHub CLI and the Visual Studio C++ build tools. Windows asks for - permission. The build tools are a large download. -4. Sign in to GitHub when asked. Press Enter, then paste the code shown in - the window into the browser page. Reports are sent from your account. -5. The dashboard opens. Keep the Pilot window open; closing it stops Pilot. - -You do not need the game for the first part: Pilot builds and tests on its -own. When you have the game, click **Choose game...** and pick the title's -executable. Testing the game starts then. - -The game must be your own copy. Keep it outside Pilot's folder. - -## What it runs, and what the developer can change - -Pilot only runs `git`, `cargo build` and `cargo test` for this repository, -`gh` (for issues on the fork) and the built `victory.exe`. Building runs the -repository's code, so only run Pilot on a branch you trust. - -The branch's [`remote.json`](remote.json) sets the next run. The developer -uses it to switch on more logging or another setting without asking you. -Pilot checks every value against an allowlist and ignores anything else: - -| Key | Allowed | -|---|---| -| `pause` | `true` stops Pilot from building and running until it is `false` again | -| `profile` | `release`, or `diag` (the diagnostics build) | -| `env` | variables named `VICTORY_*`, and `RUST_BACKTRACE` | -| `args` | `--console series-s` or `series-x`, `--unimplemented trap` or `zero`, `--strict` | -| `test_crates` | crates of this workspace | -| `test_filter` | a test name filter (letters, digits, `_`, `:`) | -| `hang_minutes` | minutes without output before a run counts as hung (2-120) | -| `survive_minutes` | minutes a run must last before an old crash report is closed (2-120) | - -When the branch has a newer `pilot.ps1`, Pilot replaces itself and restarts. -It waits until nothing is running. - -## Privacy - -Reports contain logs only: no game files, shaders, screenshots or memory, -per [docs/asset-policy.md](../../docs/asset-policy.md). Pilot replaces your -user name, your profile folder and the game's folder with placeholders -before sending anything. The issues are public. - -Pilot keeps its files under `%LOCALAPPDATA%\VIctoryPilot`: the source, -build output, `logs\` (every build, test and game run) and its settings. To -remove Pilot, delete that folder. - -## The developer's side - -`scripts/pilot/watch.sh [seconds]` waits until a `[Pilot]` report is new or -updated, prints it with its comments, and exits. A fix is pushed to the -branch, which Pilot picks up by itself. diff --git a/scripts/pilot/VIctoryPilot.cmd b/scripts/pilot/VIctoryPilot.cmd deleted file mode 100644 index ccbfe165f5..0000000000 --- a/scripts/pilot/VIctoryPilot.cmd +++ /dev/null @@ -1,19 +0,0 @@ -@echo off -rem VIctory Pilot: double-click to start. Gets the latest Pilot from the -rem branch and runs it; the first start installs what is missing. -setlocal -set "PILOT_HOME=%LOCALAPPDATA%\VIctoryPilot" -set "PILOT_URL=https://raw.githubusercontent.com/MfDev0/victory/refs/heads/arena/59fabb00-victory/scripts/pilot/pilot.ps1" -if not exist "%PILOT_HOME%" mkdir "%PILOT_HOME%" -title VIctory Pilot -echo Getting the latest VIctory Pilot... -powershell -NoProfile -ExecutionPolicy Bypass -Command "try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $new = Join-Path $env:PILOT_HOME 'pilot.new.ps1'; Invoke-WebRequest -UseBasicParsing -Uri $env:PILOT_URL -OutFile $new; Move-Item -Force $new (Join-Path $env:PILOT_HOME 'pilot.ps1') } catch { Write-Host ('Download failed, using the last copy: ' + $_) }" -if not exist "%PILOT_HOME%\pilot.ps1" ( - echo Could not download Pilot. Check the internet connection and try again. - pause - exit /b 1 -) -powershell -NoProfile -ExecutionPolicy Bypass -Command "do { & powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $env:PILOT_HOME 'pilot.ps1'); $code = $LASTEXITCODE } while ($code -eq 3); exit $code" -echo. -echo VIctory Pilot stopped. Start it again with this file. -pause diff --git a/scripts/pilot/pilot.ps1 b/scripts/pilot/pilot.ps1 deleted file mode 100644 index 86fe077bd2..0000000000 --- a/scripts/pilot/pilot.ps1 +++ /dev/null @@ -1,1061 +0,0 @@ -# VIctory Pilot: builds, tests and runs VIctory on this PC, sends what -# breaks to GitHub as issues, and picks up fixes from the branch by itself. -# Started by VIctoryPilot.cmd; see scripts/pilot/README.md. -# -# Pilot only runs git, cargo (build and test of this repository), gh (issues -# on the fork) and victory.exe. The branch's scripts/pilot/remote.json can -# change the next run's settings, but only through the allowlists below: no -# command from the branch is run as such. -# -# ASCII only: Windows PowerShell 5.1 reads a script without a BOM as ANSI. - -$ErrorActionPreference = 'Continue' -$PilotVersion = '1.0' -$Repo = 'MfDev0/victory' -$Branch = 'arena/59fabb00-victory' -$PilotHome = Join-Path $env:LOCALAPPDATA 'VIctoryPilot' -$RepoDir = Join-Path $PilotHome 'victory' -$LogDir = Join-Path $PilotHome 'logs' -$ConfigPath = Join-Path $PilotHome 'config.json' -$StatePath = Join-Path $PilotHome 'state.json' -New-Item -ItemType Directory -Force -Path $PilotHome, $LogDir | Out-Null -try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch {} -try { $Host.UI.RawUI.WindowTitle = 'VIctory Pilot' } catch {} - -# ---------------------------------------------------------------- basics - -$script:Activity = New-Object System.Collections.Generic.List[string] -function Say([string]$msg) { - $line = (Get-Date -Format 'HH:mm:ss') + ' ' + $msg - Write-Host $line - $script:Activity.Add($line) - while ($script:Activity.Count -gt 300) { $script:Activity.RemoveAt(0) } - try { Add-Content -Path (Join-Path $LogDir 'pilot.log') -Value $line -Encoding UTF8 } catch {} -} - -function ConvertTo-Hash($obj) { - if ($null -eq $obj) { return $null } - if ($obj -is [System.Collections.IDictionary]) { return $obj } - if ($obj -is [System.Management.Automation.PSCustomObject]) { - $h = @{} - foreach ($p in $obj.PSObject.Properties) { $h[$p.Name] = ConvertTo-Hash $p.Value } - return $h - } - if (($obj -is [System.Collections.IEnumerable]) -and ($obj -isnot [string])) { - $list = New-Object System.Collections.ArrayList - foreach ($item in $obj) { [void]$list.Add((ConvertTo-Hash $item)) } - return , $list.ToArray() - } - return $obj -} - -function Load-Json([string]$path) { - if (Test-Path $path) { - try { return ConvertTo-Hash (Get-Content -Path $path -Raw -Encoding UTF8 | ConvertFrom-Json) } - catch { Say "could not read $path, starting fresh" } - } - return @{} -} - -function Save-Json([string]$path, $obj) { - try { ($obj | ConvertTo-Json -Depth 10) | Set-Content -Path $path -Encoding UTF8 } catch { Say "could not save $path" } -} - -function Find-Exe([string]$name) { - $c = Get-Command $name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($c) { return $c.Source } - return $null -} - -function Refresh-Path { - $machine = [Environment]::GetEnvironmentVariable('Path', 'Machine') - $user = [Environment]::GetEnvironmentVariable('Path', 'User') - $env:Path = "$machine;$user" - $cargoBin = Join-Path $env:USERPROFILE '.cargo\bin' - if ((Test-Path $cargoBin) -and ($env:Path -notlike "*$cargoBin*")) { $env:Path += ";$cargoBin" } - $ghDir = Join-Path $env:ProgramFiles 'GitHub CLI' - if ((Test-Path $ghDir) -and ($env:Path -notlike "*$ghDir*")) { $env:Path += ";$ghDir" } -} - -function Quote-Arg([string]$a) { - if ($a -eq '') { return '""' } - if ($a -notmatch '[\s"]') { return $a } - $escaped = ($a -replace '(\\*)"', '$1$1\"') -replace '(\\+)$', '$1$1' - return '"' + $escaped + '"' -} - -function Join-Args([string[]]$argv) { return (($argv | ForEach-Object { Quote-Arg $_ }) -join ' ') } - -# Runs a program to the end and returns its exit code and output. -function Run-Sync([string]$exe, [string[]]$argv, [string]$cwd = $PilotHome, [int]$timeout = 600) { - $path = $exe - if (-not [IO.Path]::IsPathRooted($exe)) { $path = Find-Exe $exe } - if (-not $path) { return @{ Code = -1; Out = "$exe is not installed" } } - $psi = New-Object System.Diagnostics.ProcessStartInfo - $psi.FileName = $path - $psi.Arguments = Join-Args $argv - $psi.WorkingDirectory = $cwd - $psi.UseShellExecute = $false - $psi.CreateNoWindow = $true - $psi.RedirectStandardOutput = $true - $psi.RedirectStandardError = $true - try { $p = [System.Diagnostics.Process]::Start($psi) } - catch { return @{ Code = -1; Out = "$exe could not start: $_" } } - $errTask = $p.StandardError.ReadToEndAsync() - $outTask = $p.StandardOutput.ReadToEndAsync() - if (-not $p.WaitForExit($timeout * 1000)) { - Kill-Tree $p.Id - return @{ Code = -2; Out = "$exe timed out after $timeout s" } - } - $p.WaitForExit() - return @{ Code = $p.ExitCode; Out = ($outTask.Result + "`n" + $errTask.Result).Trim() } -} - -function Kill-Tree([int]$id) { - try { & taskkill.exe /PID $id /T /F 2>&1 | Out-Null } catch {} -} - -function File-Size([string]$path) { - try { return (Get-Item -LiteralPath $path -ErrorAction Stop).Length } catch { return 0 } -} - -# The last lines of a file another process may still be writing. -function Read-Tail([string]$path, [int]$maxBytes = 262144, [long]$from = -1) { - if (-not (Test-Path -LiteralPath $path)) { return } - try { - $fs = [System.IO.File]::Open($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]'ReadWrite, Delete') - try { - $len = $fs.Length - $start = [Math]::Max([long]0, $len - $maxBytes) - if ($from -ge 0) { $start = [Math]::Max($from, $start) } - [void]$fs.Seek($start, [System.IO.SeekOrigin]::Begin) - $buf = New-Object byte[] ([int]($len - $start)) - $n = $fs.Read($buf, 0, $buf.Length) - $text = [System.Text.Encoding]::UTF8.GetString($buf, 0, $n) - } finally { $fs.Close() } - $text = $text -replace "\x1b\[[0-9;?]*[A-Za-z]", '' - return ($text -split "`r?`n") - } catch { return } -} - -# Hides this PC's user name and game folder in anything sent out. -function Scrub([string]$text) { - if (-not $text) { return '' } - $out = $text - if ($script:Config -and $script:Config.game_exe) { - $gameDir = Split-Path -Parent $script:Config.game_exe - if ($gameDir) { $out = $out.Replace($gameDir, '<game folder>') } - } - if ($env:USERPROFILE) { $out = $out.Replace($env:USERPROFILE, '%USERPROFILE%') } - if ($env:USERNAME -and $env:USERNAME.Length -ge 3) { $out = $out.Replace($env:USERNAME, '<user>') } - return $out -} - -function Short([string]$sha) { if ($sha -and $sha.Length -ge 7) { return $sha.Substring(0, 7) }; return '?' } - -# ---------------------------------------------------------------- state - -$script:Config = Load-Json $ConfigPath -foreach ($pair in @(@('game_exe', ''), @('auto_run', $true), @('run_tests', $true), @('extra_args', ''))) { - if (-not $script:Config.ContainsKey($pair[0])) { $script:Config[$pair[0]] = $pair[1] } -} -$script:State = Load-Json $StatePath -if (-not $script:State.ContainsKey('issues') -or $null -eq $script:State.issues) { $script:State.issues = @() } -$script:State.issues = @($script:State.issues | Where-Object { $_ -is [System.Collections.IDictionary] }) -foreach ($k in @('built', 'tested', 'ran')) { if (-not $script:State.ContainsKey($k)) { $script:State[$k] = '' } } - -function Save-State { Save-Json $StatePath $script:State } -function Save-Config { Save-Json $ConfigPath $script:Config } - -$script:Phase = 'starting' -$script:Detail = '' -$script:LocalSha = '' -$script:Subject = '' -$script:RemoteSha = '' -$script:Job = $null -$script:LastJob = $null -$script:PendingUpdate = $false -$script:SelfUpdate = $null -$script:Login = '' -$script:CanReport = $false -$script:IssuesOn = $false -$script:LastRemoteCheck = [DateTime]::MinValue -$script:LastHeartbeat = [DateTime]::MinValue -$script:Machine = @{} -$script:Remote = @{} - -# ---------------------------------------------------------------- setup - -function Has-MsvcTools { - $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' - if (-not (Test-Path $vswhere)) { return $false } - $found = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2>$null - return [bool]$found -} - -function Winget-Install([string]$id, [string]$override = '') { - Say "installing $id (Windows may ask for permission; this can take a while)" - $wargs = @('install', '--id', $id, '-e', '--source', 'winget', '--accept-source-agreements', '--accept-package-agreements') - if ($override) { $wargs += @('--override', $override) } else { $wargs += '--silent' } - & winget @wargs - Refresh-Path -} - -function Ensure-Tools { - $script:Phase = 'setting up' - Refresh-Path - $need = @() - if (-not (Find-Exe 'git')) { $need += 'Git.Git' } - if (-not (Find-Exe 'cargo')) { $need += 'Rustlang.Rustup' } - if (-not (Find-Exe 'gh')) { $need += 'GitHub.cli' } - $msvc = Has-MsvcTools - if (($need.Count -eq 0) -and $msvc) { Say 'tools: git, Rust, GitHub CLI and the C++ build tools are installed'; return $true } - if (-not (Find-Exe 'winget')) { - Say 'winget is missing. Install "App Installer" from the Microsoft Store (opening it now), then start Pilot again.' - Start-Process 'ms-windows-store://pdp/?ProductId=9NBLGGH4NNS1' - return $false - } - $listed = @($need) - if (-not $msvc) { $listed += 'C++ build tools' } - Say ('first start: installing what is missing: ' + ($listed -join ', ')) - foreach ($id in $need) { Winget-Install $id } - if (-not $msvc) { - Winget-Install 'Microsoft.VisualStudio.2022.BuildTools' '--passive --wait --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended' - } - Refresh-Path - $missing = @() - if (-not (Find-Exe 'git')) { $missing += 'git' } - if (-not (Find-Exe 'cargo')) { $missing += 'Rust (cargo)' } - if (-not (Find-Exe 'gh')) { $missing += 'GitHub CLI' } - if (-not (Has-MsvcTools)) { $missing += 'C++ build tools' } - if ($missing.Count -gt 0) { - Say ('still missing: ' + ($missing -join ', ') + '. Close this window and start Pilot again (a restart of Windows may be needed).') - return $false - } - return $true -} - -function Ensure-GitHub { - $r = Run-Sync 'gh' @('auth', 'status', '--hostname', 'github.com') - if ($r.Code -ne 0) { - Say 'Sign in to GitHub so Pilot can send reports: press Enter below, then paste the code in the browser page.' - & gh auth login --hostname github.com --git-protocol https --web - $r = Run-Sync 'gh' @('auth', 'status', '--hostname', 'github.com') - } - if ($r.Code -ne 0) { Say 'not signed in to GitHub: Pilot keeps working but cannot send reports'; return $false } - $who = Run-Sync 'gh' @('api', 'user', '--jq', '.login') - if ($who.Code -eq 0) { $script:Login = $who.Out.Trim() } - Say "GitHub: signed in as $($script:Login), reports go to $Repo" - return $true -} - -# Reports need issues on the fork (forks start with them off) and labels. -function Ensure-Issues { - $r = Run-Sync 'gh' @('api', "repos/$Repo", '--jq', '.has_issues') - if (($r.Code -eq 0) -and ($r.Out.Trim() -eq 'false')) { - Say "issues are off on ${Repo}: switching them on" - [void](Run-Sync 'gh' @('api', '-X', 'PATCH', "repos/$Repo", '-F', 'has_issues=true')) - $r = Run-Sync 'gh' @('api', "repos/$Repo", '--jq', '.has_issues') - } - if (($r.Code -ne 0) -or ($r.Out.Trim() -ne 'true')) { - Say "issues are off on $Repo and Pilot cannot switch them on: the owner can, under Settings > General > Features > Issues" - return $false - } - $labels = @( - @('crash-report', 'b60205', 'Pilot: a crash, hang or player report'), - @('build-failure', 'd93f0b', 'Pilot: the branch does not build on Windows'), - @('test-failure', 'fbca04', 'Pilot: Windows tests fail'), - @('pilot-status', '0e8a16', 'Pilot: the status of a Pilot PC') - ) - foreach ($l in $labels) { [void](Run-Sync 'gh' @('label', 'create', $l[0], '-R', $Repo, '--color', $l[1], '--description', $l[2], '--force')) } - return $true -} - -function Read-Machine { - $m = @{ gpu = '?'; driver = '?'; windows = '?'; cpu = '?'; ram_gb = '?' } - try { - $gpus = @(Get-CimInstance Win32_VideoController | Where-Object { $_.Name -notmatch 'Basic Display|Remote' }) - if ($gpus.Count -gt 0) { - $m.gpu = ($gpus | ForEach-Object { $_.Name }) -join ' / ' - $m.driver = ($gpus | ForEach-Object { $_.DriverVersion }) -join ' / ' - } - $os = Get-CimInstance Win32_OperatingSystem - $m.windows = "$($os.Caption) build $($os.BuildNumber)" - $m.ram_gb = [Math]::Round($os.TotalVisibleMemorySize / 1MB, 1) - $m.cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name.Trim() - } catch {} - try { - $smi = Find-Exe 'nvidia-smi' - if ($smi) { - $v = (& $smi --query-gpu=driver_version --format=csv,noheader 2>$null | Select-Object -First 1) - if ($v) { $m.driver = "$($m.driver) (GeForce $($v.Trim()))" } - } - } catch {} - return $m -} - -# ---------------------------------------------------------------- the branch - -function Remote-Sha { - $r = Run-Sync 'git' @('ls-remote', "https://github.com/$Repo.git", "refs/heads/$Branch") $PilotHome 60 - if (($r.Code -eq 0) -and ($r.Out -match '([0-9a-f]{40})')) { return $Matches[1] } - return $null -} - -function Update-Repo { - $script:Phase = 'updating' - if (-not (Test-Path (Join-Path $RepoDir '.git'))) { - Say 'downloading the VIctory source (first time only)' - $r = Run-Sync 'git' @('clone', '--branch', $Branch, "https://github.com/$Repo.git", $RepoDir) $PilotHome 3600 - if ($r.Code -ne 0) { Say ('download failed: ' + $r.Out); return $false } - } - $r = Run-Sync 'git' @('fetch', '--quiet', 'origin', $Branch) $RepoDir 900 - if ($r.Code -ne 0) { Say ('update failed: ' + $r.Out); return $false } - $r = Run-Sync 'git' @('reset', '--hard', '--quiet', 'FETCH_HEAD') $RepoDir 300 - if ($r.Code -ne 0) { Say ('update failed: ' + $r.Out); return $false } - $old = $script:LocalSha - $script:LocalSha = (Run-Sync 'git' @('rev-parse', 'HEAD') $RepoDir).Out.Trim() - $script:Subject = (Run-Sync 'git' @('log', '-1', '--format=%s') $RepoDir).Out.Trim() - $script:RemoteSha = $script:LocalSha - $script:PendingUpdate = $false - if ($old -ne $script:LocalSha) { Say "source at $(Short $script:LocalSha): $($script:Subject)" } - Load-Remote - Check-SelfUpdate - return $true -} - -function Check-SelfUpdate { - $new = Join-Path $RepoDir 'scripts\pilot\pilot.ps1' - if (-not $PSCommandPath -or -not (Test-Path $new)) { return } - if ((Get-FileHash $new).Hash -ne (Get-FileHash $PSCommandPath).Hash) { - $script:SelfUpdate = $new - Say 'a newer Pilot is on the branch: it takes over once nothing is running' - } -} - -# The branch's run settings, every value checked. -function Load-Remote { - $r = @{ pause = $false; profile = 'release'; env = @{}; args = @(); test_crates = @('victory-gpu', 'victory-hle', 'victory-loader'); test_filter = ''; hang_minutes = 5; survive_minutes = 10 } - $path = Join-Path $RepoDir 'scripts\pilot\remote.json' - $raw = Load-Json $path - if ($raw.ContainsKey('pause')) { $r.pause = [bool]$raw.pause } - if ($raw.profile -in @('release', 'diag')) { $r.profile = $raw.profile } - if ($raw.env -is [System.Collections.IDictionary]) { - foreach ($k in $raw.env.Keys) { - $v = [string]$raw.env[$k] - if ((($k -match '^VICTORY_[A-Z0-9_]{1,40}$') -or ($k -in @('RUST_BACKTRACE'))) -and ($v.Length -le 300) -and ($v -notmatch '[\r\n]')) { $r.env[$k] = $v } - else { Say "remote.json: env $k ignored" } - } - } - $allowedArgs = @('--console', 'series-s', 'series-x', '--unimplemented', 'trap', 'zero', '--strict') - foreach ($a in @($raw.args)) { - if ($null -eq $a) { continue } - if ($a -in $allowedArgs) { $r.args += $a } else { Say "remote.json: argument $a ignored" } - } - $allowedCrates = @('victory', 'victory-gpu', 'victory-hle', 'victory-loader', 'victory-shader', 'victory-formats', 'victory-core', 'victory-game', 'xmem') - if ($raw.ContainsKey('test_crates')) { $r.test_crates = @(@($raw.test_crates) | Where-Object { $_ -in $allowedCrates }) } - if (($raw.test_filter -is [string]) -and ($raw.test_filter -match '^[A-Za-z0-9_:]{0,120}$')) { $r.test_filter = $raw.test_filter } - foreach ($k in @('hang_minutes', 'survive_minutes')) { - if ($raw.ContainsKey($k)) { $n = 0; if ([int]::TryParse([string]$raw[$k], [ref]$n) -and $n -ge 2 -and $n -le 120) { $r[$k] = $n } } - } - $script:Remote = $r -} - -function Victory-Exe { - $dir = 'release'; if ($script:Remote.profile -eq 'diag') { $dir = 'diag' } - return Join-Path $RepoDir "target\$dir\victory.exe" -} - -# ---------------------------------------------------------------- jobs - -function Start-LongJob([string]$kind, [string]$exe, [string[]]$argv, [hashtable]$envVars) { - $stamp = Get-Date -Format 'yyyyMMdd-HHmmss' - $out = Join-Path $LogDir "$kind-$stamp.out.txt" - $err = Join-Path $LogDir "$kind-$stamp.err.txt" - $saved = @{} - $envVars['CARGO_TERM_COLOR'] = 'never' - foreach ($k in $envVars.Keys) { $saved[$k] = [Environment]::GetEnvironmentVariable($k); [Environment]::SetEnvironmentVariable($k, $envVars[$k]) } - $p = $null - try { - $p = Start-Process -FilePath $exe -ArgumentList (Join-Args $argv) -WorkingDirectory $RepoDir -RedirectStandardOutput $out -RedirectStandardError $err -NoNewWindow -PassThru - $null = $p.Handle - } catch { Say "$kind could not start: $_" } - finally { foreach ($k in $saved.Keys) { [Environment]::SetEnvironmentVariable($k, $saved[$k]) } } - if (-not $p) { return $false } - $script:Job = @{ - Kind = $kind; Proc = $p; Out = $out; Err = $err; Started = Get-Date; LastActivity = Get-Date; LastSize = 0 - Sha = $script:LocalSha; Hung = $false; UserStopped = $false; Env = $envVars; Args = $argv; CrashBefore = @{} - } - return $true -} - -function Start-Build { - $cargo = Find-Exe 'cargo' - $script:Phase = 'building' - $script:Detail = 'compiling VIctory (the first build takes a long time)' - Say "building $(Short $script:LocalSha) ($($script:Remote.profile))" - $bargs = @('build', '--locked', '-p', 'victory') - if ($script:Remote.profile -eq 'diag') { $bargs += @('--profile', 'diag', '--features', 'diagnostics') } else { $bargs += '--release' } - return Start-LongJob 'build' $cargo $bargs @{} -} - -function Start-Tests { - $crates = @($script:Remote.test_crates) - if ($crates.Count -eq 0) { return $false } - $cargo = Find-Exe 'cargo' - $script:Phase = 'testing' - $script:Detail = 'running the Windows-only tests: ' + ($crates -join ', ') - Say "testing $(Short $script:LocalSha): $($crates -join ', ')" - $targs = @('test', '--locked') - foreach ($c in $crates) { $targs += @('-p', $c) } - $targs += '--no-fail-fast' - if ($script:Remote.test_filter) { $targs += @('--', $script:Remote.test_filter) } - return Start-LongJob 'test' $cargo $targs @{} -} - -function Crash-Logs { - $h = @{} - foreach ($root in @((Join-Path $env:LOCALAPPDATA 'victory'))) { - if ($root -and (Test-Path $root)) { - Get-ChildItem -Path $root -Recurse -Filter 'crashes.log' -ErrorAction SilentlyContinue -Depth 4 | ForEach-Object { $h[$_.FullName] = $_.Length } - } - } - return $h -} - -function Start-Game { - $exe = Victory-Exe - if (-not (Test-Path $exe)) { Say 'no build to run yet'; return $false } - if (-not $script:Config.game_exe -or -not (Test-Path -LiteralPath $script:Config.game_exe)) { Say 'choose the game first (Choose game on the dashboard)'; return $false } - $script:Phase = 'running the game' - $script:Detail = 'watching for crashes, hangs and device removal' - $gargs = @('run', $script:Config.game_exe, '--execute') + @($script:Remote.args) - $envVars = @{ RUST_BACKTRACE = '1' } - foreach ($k in $script:Remote.env.Keys) { $envVars[$k] = $script:Remote.env[$k] } - $before = Crash-Logs - Say "starting the game on $(Short $script:LocalSha)" - if (-not (Start-LongJob 'game' $exe $gargs $envVars)) { return $false } - $script:Job.CrashBefore = $before - return $true -} - -function Stop-Job([string]$why) { - if ($script:Job) { - $script:Job.UserStopped = $true - Say "stopping $($script:Job.Kind): $why" - Kill-Tree $script:Job.Proc.Id - } -} - -function Job-Lines($j, [int]$maxBytes = 262144) { - $a = @(Read-Tail $j.Out $maxBytes) - $b = @(Read-Tail $j.Err $maxBytes) - return (($a + $b) | Where-Object { $_ -ne '' }) -} - -function Tick-Job { - $j = $script:Job - if (-not $j) { return } - $size = (File-Size $j.Out) + (File-Size $j.Err) - if ($size -ne $j.LastSize) { $j.LastSize = $size; $j.LastActivity = Get-Date } - if (($j.Kind -eq 'game') -and -not $j.Proc.HasExited) { - $quiet = ((Get-Date) - $j.LastActivity).TotalMinutes - if ($quiet -ge $script:Remote.hang_minutes) { - Say "no output for $([int]$quiet) minutes: treating it as a hang" - $j.Hung = $true - Kill-Tree $j.Proc.Id - } - } - if ($j.Proc.HasExited) { - $script:Job = $null - $script:LastJob = $j - $code = 0 - try { $code = $j.Proc.ExitCode } catch {} - $j.Code = $code - $j.Minutes = [Math]::Round(((Get-Date) - $j.Started).TotalMinutes, 1) - switch ($j.Kind) { - 'build' { Finish-Build $j } - 'test' { Finish-Tests $j } - 'game' { Finish-Game $j } - } - } -} - -# ---------------------------------------------------------------- reports - -function Issue-Url([int]$n) { return "https://github.com/$Repo/issues/$n" } - -function Gh-Body([string]$text) { - $text = Scrub $text - if ($text.Length -gt 60000) { $text = $text.Substring(0, 60000) + "`n... (cut)" } - $file = Join-Path $LogDir 'issue-body.md' - [IO.File]::WriteAllText($file, $text, (New-Object System.Text.UTF8Encoding $false)) - return $file -} - -function New-Issue([string]$kind, [string]$title, [string]$body, [string]$label) { - if (-not $script:CanReport) { Say "not reported (not signed in): $title"; return 0 } - $file = Gh-Body $body - $r = Run-Sync 'gh' @('issue', 'create', '-R', $Repo, '--title', $title, '--body-file', $file, '--label', $label) - if ($r.Code -ne 0) { $r = Run-Sync 'gh' @('issue', 'create', '-R', $Repo, '--title', $title, '--body-file', $file) } - if (($r.Code -eq 0) -and ($r.Out -match '/issues/(\d+)')) { - $n = [int]$Matches[1] - Say "reported: $title -> $(Issue-Url $n)" - return $n - } - Say ('could not send the report: ' + $r.Out) - return 0 -} - -function Comment-Issue([int]$n, [string]$body) { - if (-not $script:CanReport -or $n -le 0) { return } - $file = Gh-Body $body - $r = Run-Sync 'gh' @('issue', 'comment', "$n", '-R', $Repo, '--body-file', $file) - if ($r.Code -ne 0) { Say ('could not comment: ' + $r.Out) } -} - -function Close-Issue($issue, [string]$why) { - Comment-Issue $issue.number $why - if ($script:CanReport) { [void](Run-Sync 'gh' @('issue', 'close', "$($issue.number)", '-R', $Repo)) } - $issue.closed = $true - Save-State - Say "closed #$($issue.number): $why" -} - -function Open-Issues([string]$kind) { $script:State.issues | Where-Object { $_.kind -eq $kind -and -not $_.closed } } - -function Add-Issue([int]$n, [string]$kind, [string]$title, [string]$signature, [double]$atMinutes) { - if ($n -le 0) { return } - $script:State.issues = @($script:State.issues) + @(@{ number = $n; kind = $kind; title = $title; signature = $signature; sha = $script:LocalSha; at_minutes = $atMinutes; closed = $false; seen = @($script:LocalSha) }) - Save-State -} - -function Machine-Table { - $m = $script:Machine - $lines = @( - '| | |', '|---|---|', - "| Commit | ``$($script:LocalSha)`` $($script:Subject) |", - "| GPU | $($m.gpu) |", - "| Driver | $($m.driver) |", - "| Windows | $($m.windows) |", - "| CPU / RAM | $($m.cpu) / $($m.ram_gb) GB |", - "| Profile | $($script:Remote.profile) |", - "| Pilot | $PilotVersion |" - ) - return ($lines -join "`n") -} - -function Fence([string[]]$lines, [int]$max) { - $l = @($lines) - if ($l.Count -gt $max) { $l = $l[($l.Count - $max)..($l.Count - 1)] } - return "``````text`n" + (($l -join "`n") -replace '```', "'''") + "`n``````" -} - -# ---------------------------------------------------------------- results - -function Finish-Build($j) { - $lines = @(Job-Lines $j) - if ($j.UserStopped) { $script:Phase = 'idle'; $script:Detail = 'build stopped'; return } - if ($j.Code -eq 0) { - Say "build OK in $($j.Minutes) min" - $script:State.built = $j.Sha - Save-State - foreach ($i in @(Open-Issues 'build')) { Close-Issue $i "Builds on ``$($j.Sha)`` (Pilot on $($script:Machine.gpu))." } - Next-Step - return - } - $errors = New-Object System.Collections.Generic.List[string] - $take = 0 - foreach ($l in $lines) { - if ($l -match '^(error|warning: unused)') { $take = 18 } - if ($take -gt 0) { $errors.Add($l); $take-- } - if ($errors.Count -gt 400) { break } - } - if ($errors.Count -eq 0) { $errors.AddRange([string[]]@($lines | Select-Object -Last 80)) } - $first = ($errors | Where-Object { $_ -match '^error' } | Select-Object -First 1) - if (-not $first) { $first = "exit code $($j.Code)" } - Say "build FAILED: $first" - $body = "Pilot could not build ``victory`` on Windows.`n`n" + (Machine-Table) + "`n`n### Errors`n" + (Fence $errors.ToArray() 400) - $open = @(Open-Issues 'build') - if ($open.Count -gt 0) { - if ($open[0].seen -notcontains $j.Sha) { - Comment-Issue $open[0].number ("Still fails on ``$($j.Sha)``.`n`n" + (Fence $errors.ToArray() 300)) - $open[0].seen = @($open[0].seen) + @($j.Sha); Save-State - } - } else { - $n = New-Issue 'build' "[Pilot] build fails on Windows: $first" $body 'build-failure' - Add-Issue $n 'build' $first $first 0 - } - $script:Phase = 'waiting for a fix' - $script:Detail = 'the build failed; reported, waiting for a new commit' -} - -function Finish-Tests($j) { - if ($j.UserStopped) { $script:Phase = 'idle'; return } - $lines = @(Job-Lines $j 4194304) - $failed = @($lines | Where-Object { $_ -match '^test (\S+) \.\.\. FAILED' } | ForEach-Object { ($_ -split ' ')[1] } | Select-Object -Unique) - $results = @($lines | Where-Object { $_ -match '^test result:' }) - $script:State.tested = $j.Sha - Save-State - $open = @(Open-Issues 'test') - if (($j.Code -eq 0) -or (($failed.Count -eq 0) -and ($results.Count -gt 0) -and -not ($results -match 'FAILED'))) { - Say "tests OK in $($j.Minutes) min ($($results.Count) suites)" - foreach ($i in $open) { Close-Issue $i "All tests pass on ``$($j.Sha)`` (Pilot on $($script:Machine.gpu))." } - Next-Step - return - } - if ($failed.Count -eq 0) { - # The tests did not run: a compile error in a test target. - Finish-Build $j - return - } - $details = New-Object System.Collections.Generic.List[string] - $inside = $false - foreach ($l in $lines) { - if ($l -match '^---- .* stdout ----') { $inside = $true } - elseif ($l -match '^(failures:|test result:)') { $inside = $false } - if ($inside) { $details.Add($l) } - if ($details.Count -gt 600) { break } - } - Say ("tests FAILED: " + ($failed -join ', ')) - $sig = ($failed | Sort-Object) -join ',' - $body = "Windows-only tests fail under Pilot.`n`n" + (Machine-Table) + "`n`n### Failed`n" + (($failed | ForEach-Object { "- ``$_``" }) -join "`n") + "`n`n### Output`n" + (Fence $details.ToArray() 600) + "`n`n### Summary`n" + (Fence $results 40) - if ($open.Count -gt 0) { - if (($open[0].signature -ne $sig) -or ($open[0].seen -notcontains $j.Sha)) { - Comment-Issue $open[0].number ("On ``$($j.Sha)`` these fail:`n" + (($failed | ForEach-Object { "- ``$_``" }) -join "`n") + "`n`n" + (Fence $details.ToArray() 400)) - $open[0].signature = $sig; $open[0].seen = @($open[0].seen) + @($j.Sha); Save-State - } - } else { - $n = New-Issue 'test' "[Pilot] $($failed.Count) Windows test(s) fail: $($failed[0])" $body 'test-failure' - Add-Issue $n 'test' $failed[0] $sig 0 - } - Next-Step -} - -function Crash-Signature([string[]]$crashLines, [string[]]$outLines, $j) { - $first = $crashLines | Where-Object { $_ -match '^VIctory: ' } | Select-Object -First 1 - if (-not $first) { - $first = @($outLines | Where-Object { $_ -match 'panicked at|DEVICE_REMOVED|DEVICE_HUNG|device removed|device hung|DXGI_ERROR|unhandled exception|access violation' }) | Select-Object -Last 1 - } - if (-not $first) { - if ($j.Hung) { return "hang: no output for $($script:Remote.hang_minutes) minutes" } - return ('exit code 0x{0:x8}' -f $j.Code) - } - $s = $first -replace '^\S*\s*\d{4}-\d\d-\d\d\S*\s*', '' - $s = $s -replace '\s\(.*$', '' - $s = $s -replace '0x[0-9a-fA-F]{9,}', '0x...' - $s = $s -replace 'thread \S+', 'thread' - if ($s.Length -gt 140) { $s = $s.Substring(0, 140) } - return $s.Trim() -} - -function Warning-Summary([string[]]$lines) { - $counts = @{} - foreach ($l in $lines) { - if ($l -match '\b(WARN|ERROR)\b') { - $k = $l -replace '^\S+\s+', '' -replace '0x[0-9a-fA-F]+', '0x_' -replace '\b\d+\b', 'N' - if ($k.Length -gt 160) { $k = $k.Substring(0, 160) } - if ($counts.ContainsKey($k)) { $counts[$k]++ } else { $counts[$k] = 1 } - } - } - $top = $counts.GetEnumerator() | Sort-Object Value -Descending | Select-Object -First 25 | ForEach-Object { '{0,6}x {1}' -f $_.Value, $_.Key } - return $top -} - -function Finish-Game($j) { - $outLines = @(Job-Lines $j 1048576) - $after = Crash-Logs - $crashLines = @() - foreach ($f in $after.Keys) { - $was = 0; if ($j.CrashBefore.ContainsKey($f)) { $was = $j.CrashBefore[$f] } - if ($after[$f] -gt $was) { $crashLines += @(Read-Tail $f 262144 $was) } - } - $crashLines = @($crashLines | Where-Object { $_ -ne '' }) - $script:State.ran = $j.Sha - Save-State - $crashed = $j.Hung -or ($crashLines.Count -gt 0) -or (($j.Code -ne 0) -and -not $j.UserStopped) - # Fixes that held: open crash reports from older commits this run got past. - foreach ($i in @(Open-Issues 'crash')) { - if ($i.sha -eq $j.Sha) { continue } - $need = [Math]::Max([double]$script:Remote.survive_minutes, 1.5 * [double]$i.at_minutes + 2) - $sig = '' - if ($crashed) { $sig = Crash-Signature $crashLines $outLines $j } - if (($sig -ne $i.signature) -and ($j.Minutes -ge $need)) { - Close-Issue $i "Not seen on ``$($j.Sha)``: the run lasted $($j.Minutes) min (this crash came at $($i.at_minutes) min). Closing; Pilot reopens a new report if it comes back." - } - } - if (-not $crashed) { - Say "the game ended normally after $($j.Minutes) min" - $script:Phase = 'idle' - $script:Detail = 'last run ended without a crash' - return - } - $sig = Crash-Signature $crashLines $outLines $j - $kind = 'crash'; if ($j.Hung) { $kind = 'hang' } - Say "$kind after $($j.Minutes) min: $sig" - $runArgs = (@($j.Args) | Select-Object -Skip 2) -join ' ' - $runEnv = @() - foreach ($k in $j.Env.Keys) { if ($k -ne 'CARGO_TERM_COLOR') { $runEnv += "$k=$($j.Env[$k])" } } - $settings = 'args: `' + $runArgs + '`, env: `' + ($runEnv -join ' ') + '`' - $existing = @(Open-Issues 'crash') | Where-Object { $_.signature -eq $sig } | Select-Object -First 1 - if ($existing) { - if ($existing.seen -notcontains $j.Sha) { - Comment-Issue $existing.number ("Happened again on ``$($j.Sha)`` after $($j.Minutes) min.`n`n" + (Fence $crashLines 120) + "`n`n<details><summary>Output tail</summary>`n`n" + (Fence $outLines 150) + "`n</details>") - $existing.seen = @($existing.seen) + @($j.Sha); Save-State - } else { Say "same crash as #$($existing.number) on the same commit: not reported again" } - } else { - $body = @( - "Pilot saw a **$kind** after **$($j.Minutes) min** (exit code ``$('0x{0:x8}' -f $j.Code)``).", - '', (Machine-Table), '', "Run: $settings", '', - '### New crashes.log entries', (Fence $crashLines 200), '', - '### Most frequent warnings', (Fence @(Warning-Summary $outLines) 25), '', - '<details><summary>Output tail (last 250 lines)</summary>', '', (Fence $outLines 250), '</details>', - '', '_Sent by VIctory Pilot. Logs only: no game data._' - ) -join "`n" - $n = New-Issue 'crash' "[Pilot] $($kind): $sig" $body 'crash-report' - Add-Issue $n 'crash' $sig $sig $j.Minutes - } - $script:Phase = 'waiting for a fix' - $script:Detail = "$kind reported; the next commit is built, tested and run by itself" -} - -# What to do next for the current commit. -function Next-Step { - if ($script:Job) { return } - if ($script:Remote.pause) { $script:Phase = 'paused'; $script:Detail = 'paused by remote.json on the branch'; return } - if ($script:State.built -ne $script:LocalSha) { [void](Start-Build); return } - if ($script:Config.run_tests -and ($script:State.tested -ne $script:LocalSha) -and (@($script:Remote.test_crates).Count -gt 0)) { if (Start-Tests) { return } } - if ($script:Config.auto_run -and ($script:State.ran -ne $script:LocalSha) -and $script:Config.game_exe) { if (Start-Game) { return } } - if (-not $script:Config.game_exe) { $script:Phase = 'idle'; $script:Detail = 'built and tested; choose the game when you have it' } - elseif ($script:Phase -ne 'waiting for a fix') { $script:Phase = 'idle'; $script:Detail = 'up to date' } -} - -function Check-Remote([bool]$force = $false) { - $script:LastRemoteCheck = Get-Date - $sha = Remote-Sha - if (-not $sha) { return } - $script:RemoteSha = $sha - if ($sha -eq $script:LocalSha) { return } - if ($script:Job) { - if (-not $script:PendingUpdate) { Say "new commit $(Short $sha) on the branch: applied when the current $($script:Job.Kind) ends" } - $script:PendingUpdate = $true - if ($script:Job.Kind -ne 'game') { Stop-Job 'a newer commit arrived' } - return - } - Say "new commit $(Short $sha): updating" - if (Update-Repo) { Next-Step } -} - -# A status issue the developer can read at a glance, edited in place. -function Heartbeat { - $script:LastHeartbeat = Get-Date - if (-not $script:CanReport) { return } - $job = 'none' - if ($script:Job) { $job = "$($script:Job.Kind), $([Math]::Round(((Get-Date) - $script:Job.Started).TotalMinutes, 1)) min" } - $open = @($script:State.issues | Where-Object { -not $_.closed } | ForEach-Object { "- #$($_.number) ($($_.kind)) $($_.title)" }) - $body = @( - "Pilot status, updated $(Get-Date -Format 'yyyy-MM-dd HH:mm') (local time).", '', - (Machine-Table), '', - "| Phase | $($script:Phase): $($script:Detail) |", '|---|---|', - "| Job | $job |", - "| Game chosen | $([bool]$script:Config.game_exe) |", - "| Built / tested / ran | $(Short $script:State.built) / $(Short $script:State.tested) / $(Short $script:State.ran) |", '', - '### Open reports', $(if ($open.Count) { $open -join "`n" } else { 'none' }), '', - '### Recent activity', (Fence ($script:Activity | Select-Object -Last 30) 30) - ) -join "`n" - $n = 0 - if ($script:State.ContainsKey('status_issue')) { $n = [int]$script:State.status_issue } - if ($n -gt 0) { - $file = Gh-Body $body - $r = Run-Sync 'gh' @('issue', 'edit', "$n", '-R', $Repo, '--body-file', $file) - if ($r.Code -eq 0) { return } - } - $n = New-Issue 'status' "[Pilot] status of $($script:Login)'s PC" $body 'pilot-status' - if ($n -gt 0) { $script:State.status_issue = $n; Save-State } -} - -# ---------------------------------------------------------------- dashboard - -function Choose-Game { - try { - Add-Type -AssemblyName System.Windows.Forms - $d = New-Object System.Windows.Forms.OpenFileDialog - $d.Title = "Choose the game's executable" - $d.Filter = 'Game executable (*.exe)|*.exe' - $owner = New-Object System.Windows.Forms.Form - $owner.TopMost = $true - if ($d.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { return $d.FileName } - } catch { Say "file dialog failed: $_" } - return $null -} - -function Set-Game([string]$path) { - $path = $path.Trim().Trim('"') - if (-not $path) { return 'no path given' } - if (-not (Test-Path -LiteralPath $path)) { return "not found: $path" } - if ($path.StartsWith($RepoDir, [StringComparison]::OrdinalIgnoreCase)) { return 'the game must not be inside the source folder' } - $script:Config.game_exe = $path - Save-Config - Say "game set: $path" - $script:State.ran = '' - Save-State - Next-Step - return 'game set' -} - -function Do-Action([string]$name, [string]$body) { - switch ($name) { - 'run' { if ($script:Job) { return "busy: $($script:Job.Kind)" }; $script:State.ran = ''; if (Start-Game) { return 'game started' } else { return 'could not start the game (see activity)' } } - 'stop' { Stop-Job 'stopped from the dashboard'; return 'stopping' } - 'rebuild' { if ($script:Job) { return "busy: $($script:Job.Kind)" }; $script:State.built = ''; $script:State.tested = ''; Save-State; Next-Step; return 'rebuilding' } - 'test' { if ($script:Job) { return "busy: $($script:Job.Kind)" }; if (Start-Tests) { return 'testing' } else { return 'no tests configured' } } - 'check' { Check-Remote $true; return "checked: branch at $(Short $script:RemoteSha)" } - 'browse' { $p = Choose-Game; if ($p) { return (Set-Game $p) } else { return 'nothing chosen' } } - 'setgame' { return (Set-Game $body) } - 'toggle_run' { $script:Config.auto_run = -not $script:Config.auto_run; Save-Config; return "auto-run: $($script:Config.auto_run)" } - 'toggle_tests' { $script:Config.run_tests = -not $script:Config.run_tests; Save-Config; return "tests: $($script:Config.run_tests)" } - 'report' { - $note = $body.Trim(); if (-not $note) { $note = 'Something looked wrong.' } - if ($note.Length -gt 2000) { $note = $note.Substring(0, 2000) } - $lines = @(); if ($script:Job) { $lines = @(Job-Lines $script:Job) } elseif ($script:LastJob) { $lines = @(Job-Lines $script:LastJob) } - $text = "Report from the player: $note`n`n" + (Machine-Table) + "`n`n### Output tail`n" + (Fence $lines 250) - $n = New-Issue 'note' "[Pilot] player report: $($note.Split("`n")[0])" $text 'crash-report' - Add-Issue $n 'note' $note $note 0 - if ($n -gt 0) { return "sent as #$n" } else { return 'could not send' } - } - 'logs' { Start-Process explorer.exe $LogDir; return 'opened' } - default { return "unknown action $name" } - } -} - -function Status-Json { - $tail = @() - $j = $script:Job; if (-not $j) { $j = $script:LastJob } - if ($j) { $tail = @(@(Job-Lines $j 65536) | Select-Object -Last 120) } - $job = $null - if ($script:Job) { - $job = @{ kind = $script:Job.Kind; minutes = [Math]::Round(((Get-Date) - $script:Job.Started).TotalMinutes, 1); quiet = [Math]::Round(((Get-Date) - $script:Job.LastActivity).TotalMinutes, 1) } - } - $issues = @($script:State.issues | Select-Object -Last 30 | ForEach-Object { @{ number = $_.number; kind = $_.kind; title = $_.title; closed = $_.closed; url = (Issue-Url $_.number) } }) - [array]::Reverse($issues) - $s = @{ - version = $PilotVersion; phase = $script:Phase; detail = $script:Detail - local = $script:LocalSha; subject = $script:Subject; remote = $script:RemoteSha; pending = $script:PendingUpdate - game = $script:Config.game_exe; auto_run = $script:Config.auto_run; run_tests = $script:Config.run_tests - login = $script:Login; can_report = $script:CanReport; repo = $Repo; branch = $Branch - machine = $script:Machine; job = $job; tail = $tail; activity = @($script:Activity | Select-Object -Last 80) - issues = $issues; paused = $script:Remote.pause; profile = $script:Remote.profile - status_issue = $script:State.status_issue; issues_on = $script:IssuesOn - } - return ($s | ConvertTo-Json -Depth 6 -Compress) -} - -function Send-Text($ctx, [string]$text, [string]$type, [int]$code = 200) { - $bytes = [Text.Encoding]::UTF8.GetBytes($text) - $ctx.Response.StatusCode = $code - $ctx.Response.ContentType = $type - $ctx.Response.Headers['Cache-Control'] = 'no-store' - $ctx.Response.OutputStream.Write($bytes, 0, $bytes.Length) -} - -function Serve($ctx) { - $req = $ctx.Request - if ($req.Headers['Host'] -notmatch '^(localhost|127\.0\.0\.1)(:\d+)?$') { Send-Text $ctx 'forbidden' 'text/plain' 403; return } - $path = $req.Url.AbsolutePath - if (($req.HttpMethod -eq 'GET') -and ($path -eq '/')) { Send-Text $ctx $DashboardHtml 'text/html; charset=utf-8'; return } - if (($req.HttpMethod -eq 'GET') -and ($path -eq '/api/status')) { Send-Text $ctx (Status-Json) 'application/json'; return } - if (($req.HttpMethod -eq 'POST') -and $path.StartsWith('/api/')) { - # A custom header: other web pages cannot send it without asking first. - if ($req.Headers['X-Pilot'] -ne '1') { Send-Text $ctx 'forbidden' 'text/plain' 403; return } - $reader = New-Object IO.StreamReader($req.InputStream, [Text.Encoding]::UTF8) - $body = $reader.ReadToEnd() - $msg = Do-Action $path.Substring(5) $body - Send-Text $ctx (@{ message = "$msg" } | ConvertTo-Json -Compress) 'application/json' - return - } - Send-Text $ctx 'not found' 'text/plain' 404 -} - -function Handle-Http { - while ($script:CtxTask -and $script:CtxTask.IsCompleted) { - $ctx = $null - try { $ctx = $script:CtxTask.Result } catch {} - $script:CtxTask = $script:Listener.GetContextAsync() - if (-not $ctx) { continue } - try { Serve $ctx } catch { Say "dashboard error: $_" } - finally { try { $ctx.Response.Close() } catch {} } - } -} - -$DashboardHtml = @' -<!doctype html> -<html><head><meta charset="utf-8"><title>VIctory Pilot - - - -

VIctory Pilot

...
-
-
-

Connection

-
GitHub
-
Reports go to
-
Status issue
-
Branch
-
Running commit
-
Latest on branch
-
-

This PC

-
GPU
-
Driver
-
Windows
-
CPU / RAM
-
-

Game

-
Executable
- - - -
-
-

Controls

- - - -
- - -
-
-

Something looked wrong?

- - -
-
-
- -

Output

-

Reports

none yet
-

Pilot activity

-
-
- - -'@ - -# ---------------------------------------------------------------- main - -Say "VIctory Pilot $PilotVersion" -if (-not (Ensure-Tools)) { Read-Host 'Press Enter to close'; exit 1 } -$script:CanReport = Ensure-GitHub -$script:IssuesOn = $false -if ($script:CanReport) { $script:IssuesOn = Ensure-Issues; $script:CanReport = $script:IssuesOn } -$script:Machine = Read-Machine -Say "this PC: $($script:Machine.gpu), driver $($script:Machine.driver), $($script:Machine.windows)" - -$script:Listener = $null -$Port = 0 -foreach ($p in 8765..8775) { - try { - $l = New-Object System.Net.HttpListener - $l.Prefixes.Add("http://localhost:$p/") - $l.Start() - $script:Listener = $l - $Port = $p - break - } catch {} -} -if ($script:Listener) { - $script:CtxTask = $script:Listener.GetContextAsync() - Say "dashboard: http://localhost:$Port/ (keep this window open)" - Start-Process "http://localhost:$Port/" -} else { Say 'could not open the dashboard port: Pilot keeps working in this window' } - -if (Update-Repo) { Next-Step } -Heartbeat - -while ($true) { - Handle-Http - Tick-Job - $now = Get-Date - if (-not $script:Job -and $script:SelfUpdate) { - Say 'restarting into the newer Pilot' - try { Copy-Item -LiteralPath $script:SelfUpdate -Destination $PSCommandPath -Force } catch { Say "could not update Pilot: $_" } - if ($script:Listener) { $script:Listener.Stop() } - exit 3 - } - if (-not $script:Job -and $script:PendingUpdate) { if (Update-Repo) { Next-Step } } - if (($now - $script:LastRemoteCheck).TotalSeconds -ge 60) { Check-Remote } - if (($now - $script:LastHeartbeat).TotalMinutes -ge 10) { Heartbeat } - Start-Sleep -Milliseconds 250 -} diff --git a/scripts/pilot/remote.json b/scripts/pilot/remote.json deleted file mode 100644 index 8dfc4d95c5..0000000000 --- a/scripts/pilot/remote.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "note": "Settings for the next Pilot run, set by the developer on the branch. Pilot checks every value against an allowlist and ignores anything else.", - "pause": false, - "profile": "release", - "env": {}, - "args": [], - "test_crates": ["victory-gpu", "victory-hle", "victory-loader"], - "test_filter": "", - "hang_minutes": 5, - "survive_minutes": 10 -} diff --git a/scripts/pilot/watch.sh b/scripts/pilot/watch.sh deleted file mode 100755 index b75398dd60..0000000000 --- a/scripts/pilot/watch.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env bash -# The developer's side of Pilot: waits until a [Pilot] report on the fork is -# new or updated, prints it, and exits 0; exits 2 when none came in time. -# Usage: scripts/pilot/watch.sh [seconds, default 1500] -# PILOT_STATUS=1 also wakes on the status issue (it is edited every 10 min). -set -euo pipefail -repo=${PILOT_REPO:-MfDev0/victory} -seen=${PILOT_SEEN:-${TMPDIR:-/tmp}/pilot-seen.txt} -limit=${1:-1500} -touch "$seen" -filter='.[] | select((.title | startswith("[Pilot] status")) | not)' -if [ "${PILOT_STATUS:-0}" = 1 ]; then filter='.[]'; fi -list() { - gh issue list -R "$repo" --state all --limit 100 --search '"[Pilot]" in:title' \ - --json number,updatedAt,title --jq "$filter"' | "\(.number) \(.updatedAt) \(.title)"' -} -end=$((SECONDS + limit)) -while :; do - now=$(list) - changed=$(grep -vxF -f "$seen" <<<"$now" || true) - if [ -n "$changed" ]; then - echo "== changed Pilot reports" - echo "$changed" - while read -r n _; do - echo - echo "================ #$n" - gh issue view "$n" -R "$repo" --comments | head -c 30000 - done <<<"$changed" - printf '%s\n' "$now" >"$seen" - exit 0 - fi - if [ "$SECONDS" -ge "$end" ]; then - echo "no new Pilot reports in ${limit}s" - exit 2 - fi - sleep 30 -done diff --git a/scripts/try/PLAN.md b/scripts/try/PLAN.md new file mode 100644 index 0000000000..b04c47d9c4 --- /dev/null +++ b/scripts/try/PLAN.md @@ -0,0 +1,398 @@ +# VIctory Try: plan and to-do (6.10, updated for 6.17) + +Goal: the whole picture rendered, **20+ fps** on the reporter's PC: RTX 4050 +Laptop (5921 MB, budget about 5153 MB), 12 threads, about 16 GB of RAM, +Series S profile, game 1.0.2.1. + +**Base: this fork's own engine, always.** (6.9 made AvatarManz's engine the +default; the owner turned that down: the base never changes again.) The +other forks' most important fixes are ported into our engine one at a time, +each with its author named, each with the log line that shows it working. +avm/8GB stay selectable with N for comparing only. + +How the loop works: a version ships, the user runs it and sends the report +zip, we read it, fix, ship the next. Every round PortWatch and the forks +below are checked again. + +## Where everyone stands (2026-11-26, PortWatch + their READMEs) + +| Fork | Card | fps | What gets them there | +|---|---|---|---| +| Belobug (`a-publier`) | RX 9070 XT | ~22 | avm c9c932c + prelude uploads (flicker), VRAM-aware texture cap, **PC FSR via the host DLL** | +| avatarmanz/VIctory-7900XTX | RX 7900 XTX | 16 (45 ms Series S) | renderer ports 1-7 (CBV -4.7 ms, guard -2, journal -1..-3), THIN list calls on 8 threads, copy-queue textures + show-after, shaders/pipelines made ahead (`warm`) | +| DexNom/VIctory | RX 7900 XTX | 3-4 | best picture: ray tracing, cube gradients, the PC FSR bridge (ab34a8b2) | +| kelvaroq (stellarr-studio) | RTX 5080 | ~10 (11 on a 4090 for 36 min) | patches 0001-0064 on fork f85101b (an ancestor of ours): wide card hashes + mesh launch (0041, 198 -> 120 ms), async submit + async present + copy queues by default (0040/0048), translate-once descriptors (0055), unified memory layer (0063, `VICTORY_UMA`, not in a build yet) | +| DoubleGhosty/cool_fox | - | - | community continuation (codec_d): renderer ports 1/5/6/7 by default, coalesced card compares (Xyzstk f2dd4508), frame-rate and render-scale switches | +| this fork | RTX 4050L / RTX 4060 | 1.6-3.3 (6.7) / 4.2-4.7 (6.12, MAX) | 6.12: relay waits 130 ms a frame for fetches queued behind the flights (copy-engine fetch off since an old lost card), GPU ~150 ms with no barrier trimmed | + +## Done in 6.10 + +- [x] Own engine is the default again (one-time switch back; N: own -> avm -> 8GB). +- [x] **PC FidelityFX upscaler** (Belobug cd8dfc06 from DexNom ab34a8b2): + `victory-hle/modules/fidelityfx.rs` serves the title's + `amd_fidelityfx_loader_xbox.dll` with AMD's signed + `amd_fidelityfx_upscaler_dx12.dll` on the host GPU. Changed for us: + any profile (Series S 1280x720 -> 1920x1080 too, not only their 4K + patch), provider chosen FSR 4.1.2 -> newest other (FSR 3.1 on NVIDIA), + the next provider tried if the card refuses one, and a dispatch the PC + DLL cannot record falls back to our temporal resolve (never black). + `victory-gpu/external.rs` records it on our plain host list. Try + downloads the DLL once (57 MB, AMD's GitHub, signature checked). + Expected: no blocky lit/reflecting surfaces, sharp hair, real jitter + accumulation. T: FSR / own / off. +- [x] Own temporal resolve (fallback, T=own): Catmull-Rom colour sample, + sharpening against a smooth tent blur (the old 3x3 mean of the nearest + rendered texel drew the 720p grid into bright surfaces), sharpen 10 %. +- [x] avm's native shader reader: shaders stored without XBCH (kind 0x0c, + avm e70e031c) and the FSPX/ACCC layout (AMD-compiled shaders, avm + 66afb2b4; parser only so far). +- [x] Logs: `upscaler PC FidelityFX ...` line at start, providers offered + and chosen, every 600 upscales how many were jittered (both paths). + +## Done in 6.17 ("no wasted processor") + +From the 6.15 log again: `console_insn` emulated=67,108,864 patched=1 +unpatched=65,974,989; monitorx 403k-442k exceptions a second, mwaitx 0 (it +was patched); so the hot monitorx could not be: its first two bytes across a +word (neither the whole-word store nor the 2-byte jump fits). Descriptor heap +pass 22-39 ms a frame ("making the host slots" 15-31 ms, 24-30k records) +on the submitting thread; the card idle 68-112 ms behind it. + +- [x] `plan`: `0F xx yy` -> `0F 1F C0` when `xx yy` share a word; failed places + remembered (16), first 4 reasons logged. +- [x] Try: `VICTORY_SYNC_BESIDE=1` (config `beside`). +- [x] Mirror `MfDev0/ctz` (a standalone repository, not a fork) tried first. +- Next: the heap-buffers pass (47 ms a frame, about 50,000 slots a pass on the + title's thread, F mode); Kelvaroq 0055's snapshot compare of record keys + (their decoder differs: port by idea); the 6.16 card meter's table. + +## Done in 6.16 ("room for windows") + +Found in the 6.15 report (RTX 4050 Laptop, MAX, low preset, 2.4-3.4 fps in +the world, 30-36 in the menu): VRAM 5,048-5,102 of 5,153 MB all through the +world (`TEXTURE_ROOM_PERCENT=99`), windows: BAR 117 (436 MB), card 0 (768 +turned down for room), so most windows were read across the bus; card 58-72 % +busy. Texture rush toggled 209 times (111,497 uploads, 51,988 MB, 75,957 +placeholders shown, BC4 white / BC5 128,128,255 = the face flicker). Disk: a +new shader translation set per build (~1 GB), target never collected, other +engines' trees, logs never pruned. + +- [x] `shadow::windows_room_kept` counted in `resource::room`; `window_line` + 96 % (80 off); `windows_line` in the stats (BAR / card / PC MB). +- [x] Rush: `rush_next` with a gap (`VICTORY_TEXTURE_RUSH_GAP_S`, 30); + `descriptor::host::unrushing`: an unrushed texture's detile leaves out + no level. +- [x] Shader cache per build folder, `prune` (`VICTORY_SHADER_CACHE_KEEP`). +- [x] Card meter without the frame log; kinds line; table at least every + 60 s. Try sets `VICTORY_CARD_METER=1` (config `meter=off`). +- [x] Try: `Tidy-Disk` / `Tidy-Target` / `TIDY`; MAX on small cards 94 %. +- Next, from the next report: the submit thread's 55-169 ms a frame + (descriptor slots, heap-buffers 47-78 ms, heap worker 88-94 ms, monitorx + 450k exceptions/s); keep the last real view instead of the placeholder. + +## Done in 6.15 ("new things fast") + +Found in the 6.12 report: the library saves (1.1 GB each, ten in eighteen +minutes, every 20-40 s with memory Normal) line up with the worst frames: +20:27:55 397 ms + 19 draws/frame dropped "being made", 20:28:41 523 ms + 24.3 +dropped, then the 5196 ms frame at 20:28:50. `StorePipeline` waited for the +save's write lock, so every pipeline finished during a save waited too. And +`VICTORY_STAND_IN=0` (new38 off) dropped every draw of a pipeline being made. + +- [x] Library: store later (cool_fox 4a028f31, Esteban Viera; on here, + `VICTORY_LIBRARY_STORE_LATER=0` goes back); one save at a time; saves on + a thread of their own (`save_soon`, `VICTORY_LIBRARY_SAVE_THREAD=0`); + in the world every `VICTORY_LIBRARY_SAVE_S` (300) whatever the memory. + Save line: `handed_out_during_saves`. +- [x] Stand-ins on their own Try switch (config `standin`), and + `VICTORY_STAND_IN_FIRST` (engine, on): a same-shape stand-in before any + wait (Kelvaroq 0050). Try: `VICTORY_PIPELINE_WAIT_MS=250`. Log: the + stand-in counts line now has "at once, before any wait". +- [x] A panicking pipeline build is refused (cool_fox 744c09ba). +- [x] `alias_of` holds the aliased texture (cool_fox 94f35b7f). +- Looked at, not taken: cool_fox 6ad1eff1 (sparse mips on address-backed + textures: our tiles path differs, `tiles::by_quality`), f4164f86 (skips all + hair strand passes), c9f654e0 (already here), f2dd4508/8eb4f320 (their tree). + +## Why 3-4 fps (6.12 report, RTX 4060 8 GB, 32 GB, MAX on) and 6.14 + +Steady state 20:36-20:42: 4.2-4.7 fps, 215-240 ms a frame, ~3,500 draws. + +| part of a frame | ms | cause | +|---|---|---| +| relay thread waiting for fetches of card copies' pieces | **129-133** | `VICTORY_COPY_FETCH=0`: the fetch went on the direct queue behind every flight sent since; an old lost card had set config `new38=off`, which also turned off copy fetch and barrier trimming for good | +| card busy (our count 66-68 %, Task Manager 3D 87-88 %) | ~150 | `VICTORY_TRIM_BARRIERS=0` (0 trimmed), 105 hash passes + 58 compares a frame, one thread a piece | +| preparing on the title's thread (copies 24, refreshes 24, descriptor mirror 21-24) | 50-55 | the title's thread prepares every submission itself, then waits in the present | +| title waits for the copy-back to hear a fence | (inside the above) | `VICTORY_LAZY_BACK=0` (an old access-violation crash) | +| windows outside buffers | 0 MB | so the 6.13 BAR windows could not help this PC | + +MAX lifted caps; none of these is a cap. The Series S has one memory: the +GPU's writes are simply there for the CPU (no fetch, no compare, no +copy-back), and the game records frame N+1 while the GPU draws frame N +(the present returns at once). 6.14 moves us toward that: + +- [x] Copy fetch and barrier trimming on their own switches (config + `copyfetch`, `trim`), on; a one-time migration (`mig613`) undoes the + old lock-out. Last in the lost-card chain. +- [x] Lazy copy-back on again once (migration); an AV crash turns it off. +- [x] `VICTORY_ASYNC_SUBMIT=1` + `VICTORY_ASYNC_PRESENT=1` (config `ahead`): + one frame ahead (Kelvaroq 0040/0048 defaults). Second in the lost-card + chain after wide hashes. +- [x] `VICTORY_CARD_HASH_WIDE=1` (config `widehash`; fork #1014 martindevbr, + Kelvaroq 0041 default). First in the lost-card chain after BAR windows. +- [x] Joined relay fetch copies (Kelvaroq 0032; `VICTORY_RELAY_COPY_RUNS=0` + goes back), engine default. + +Expected in the 6.14 report: relay `waited ... for fetches` a few ms (not +130), `what shaders wrote ... fetched on the card's copy engine` at start, +`barriers and full waits left out so far` > 0, `submissions are prepared and +sent by a thread of ours`, `presents go behind the queue's line`, the lazy +line. Frame then bounded by the card (~100 ms?) -> about 8-10 fps; the next +step is the card's own time (our passes, indirect clamps, 354 spread +dispatches a frame) and the descriptor mirror. + +Not ported (yet): Kelvaroq 0041 mesh launch stage (1,389 lines), 0055 +translate-once descriptors (1,012), 0063 UMA (1,988, not in their build); +cool_fox f2dd4508 coalesced compares (on their tree's `CardRange`), 8a31b96e +journal (1,503 lines). + +## Done in 6.13 ("NVIDIA fixes"; deep search of the NVIDIA forks) + +Searched: trustno1-coder/VIctory-NVIDIA (`nv/main` 6a31e431), edsuuu/VI-BR-PORT +(`br/main` 2aa1895d), Itsbatt/victory-unified, TaynanGT/Vice-Tay. Ported: + +- [x] **Memory windows through Resizable BAR** (nv cda4987a + 85a529b6, + Indy2l): `VICTORY_WINDOWS_BAR_MB` in `shadow.rs` (`window_bar_most`, + `window_bar_for`): windows outside buffers are one buffer in a GPU + upload heap, no copy in the PC's memory, no list of changes; own + counter, not tied to `VICTORY_CARD_WINDOWS_MB`; off with + `VICTORY_GPU_UPLOAD=0`; refused past 80% of the card's budget. + Measured there: 16 GB RTX 3060 PC, `0x8007000E` and the driver fault + gone, shared memory 4.4 GB instead of 7.5, 1.6-3 -> 10-12 fps. Try sets + it on PCs under 24 GB of RAM: 20% of the card under 8 GB (about + 1184 MB on the 4050), 30% above, at most 3072; MAX 35%. A lost card + (with the BAR line in the log) turns it off next (config `barwin`). + Log: `windows outside buffers in the card's memory through a resizable + BAR` (supported=true?) and `windows through the BAR (...)`. +- [x] **Texture read-backs on their own thread** (nv 2d1dc382, Indy2l): + `texback::land` only copies the texels out; the lock wait, tiling and + write go to the `texture read-backs` thread, newest copy only. There: + 124-416 ms landing stalls while the world streamed on 16 GB. + `VICTORY_TEXBACK_ASYNC=0` goes back. Log: `texture readback landed` + now carries waited_ms / worked_ms / replaced. +- [x] **A slow pipeline is waited for in one frame only** + (`VICTORY_PIPELINE_WAIT_ONCE`, on; br dc3fa30b, nv 77e13a97): no more + half-second freezes every frame while a driver compile runs. +- [x] **Compute pipelines start at creation** (br b9d4f96c; + `VICTORY_PIPELINE_EARLY_COMPUTE=0` goes back), only with workers. +- [x] **Decoration bake found by name** (br 10ac68f9): `PS_DecorationBlend_*` + and `PS_BakeDecorations_*` get their sources uploaded first (cutscene + faces came out black). +- [x] **Texture change lists compacted, not cleared** (br 87dc3075 + + 47fa23c9, myokex): 2^18 ranges, a full list joins neighbours instead + of forgetting streamed textures. +- [x] **Card compare submitted on its own** (nv d1fe0bd0, Jeremy Goldberg): + D3D12 error 538 (buffers decay to COMMON between ExecuteCommandLists). +- [x] (6.12 open question) `$Src` is defined in try.ps1 (line 53), so the + rt-off list path resolves. + +Looked at and left (and why): +- br a46bbdc6 + 689be4d2 (wave64 programs take the wave-wide form on + 32-lane hosts): our wide form lost the card in runs 121-124; needs the + 295-line barrier fix ported and tested first. Next round. +- br fd36f4a4 (movie planes per-list upload): intro video steps back only; + later. +- br 44ead3c5 SHOW_AFTER default: our descriptor host has no show-after yet. +- br 389b9747 (1 MiB / 1 GiB card buffers on 8-12 GB): our 6 GB card was at + 4822/5153 MB; MAX already raises it. Try after the 6.13 report. +- br 5c17c8c8 (#1241 alias source): already in our tree. +- br 72903b29 (64 MB pipeline worker stack): already in our tree. +- nv c05b44b3 (ambient depth SRV): our ambient pass differs; check if the + debug layer shows error 646. +- nv 12b1d16d (HLE mouse): if the user wants mouse camera. + +## Done in 6.12 ("all-out") + +The user: "still bad"; asked for a mode with no caps that reads the PC and +gives the game all but ~1%, and a deep search of git.gtahub.st/explore/repos. + +- [x] **All-out mode** (MAX, `VICTORY_TRY_ALL_OUT=1`; try.ps1 `Set-AllOut`), + from `Win32_OperatingSystem` memory, `ProcessorCount`, the card's + memory: threads-1 for `VICTORY_WIDE_THREADS`, `VICTORY_DETILE_THREADS` + and the new `VICTORY_PIPELINE_WORKERS`; `VICTORY_PRIORITY=high` and + `VICTORY_WORKING_SET_PERCENT=90` (new, `victory-hle/src/runtime.rs`); + `VICTORY_TEXTURE_ROOM_PERCENT=99` (clamp raised 97 -> 99), no + `TEXTURE_BUDGET_MB`, `TEXTURE_STAGE_MB=512`, `STAGING_POOL_MB=256`, + `DSTORAGE_STAGING_MB=256` (cool_fox via CGBJ), `CARD_BUFFERS_MB` a fifth + of the card (1 GB at least), `MERGE_UNWATCHED_MB=256`; the pressure + guard's limits from the new `VICTORY_PRESSURE_RAM_MB`, + `VICTORY_PRESSURE_COMMIT_MB`, `VICTORY_PRESSURE_CARD_PERCENT` (each + `mild,critical`; `pressure.rs` `Limits`) at 2%/1% of memory and + 98/99% of the card. First thing turned off after a lost card. + Left as they are on purpose: `SHADER_LOOP_LIMIT` (1024 lost the card), + `CARD_ROOM_FOR_TARGETS_MB` (room the render targets need), + `LATE_WAIT_LISTS` (the 6.7 report never waited on it), + `PIPELINE_HEAVY` (more than 3 heavy compiles ran the driver out of + memory). Honest limit: in the 6.7 report the PC had 368-740 MB free + and 1.2-1.6 GB left to commit, the card 4.8 of its 5.15 GB budget; + there is no spare memory to give, only the guard to move. Log: + `memory pressure starts later`, `the whole machine for the title ... + high=true`, `pipeline workers workers=11`. +- [x] **Ray-only passes** (edsuuu/VI-BR-PORT ab4571df, 1556de82, f1e5e454, + 24f8d2ed): `pipeline.rs` `for_rays` by entry-point name + (`CSComputeSkinning*`, `CSGenerateHairVB`, `CS_RaytracingResolve*`, + `CS_ScreenProbes_ActivateRays*`, `..._TraceRays*_BVH*`, + `CS_RaytraceVBuffer*` but not Voxels/Fallback); with + `VICTORY_SKIP_RT=1` and the builder off their dispatches are left out + (`draw.rs`) and, ours on top, they are never built (`make.rs`, + `recipe.rs` prepare). There: 6.8 -> 10.2 fps (skinning), +8 % (traces). + Switches `VICTORY_RT_SKIN/RESOLVE/TRACE`, `VICTORY_ACTIVATE_RAYS`. + Log: `passes that only serve rays are left out`, `... not built`. +- [x] **rt-off list** (trustno1-coder/VIctory-NVIDIA 77e13a97): + `scripts/try/rt-off-hashes.txt` (1,000 resolve + 34 traced shadows) + as `VICTORY_DENY_PIPELINES` with B (our release build has no + `VICTORY_SKIP_PIPELINES`; deny works in release). Denied pipelines are + skipped by prepare too; the log says the first 8, then powers of two. +- [x] **NaN scrub** (same commit): `emit/lower.rs` `scrub_nan` on pixel + colour exports, `VICTORY_NAN_SCRUB=1` on in Try (not in plain mode). +- [x] Searched (2026-11-26): gtahub explore, `q=victory` by stars. Fetched + `nv` (trustno1-coder/VIctory-NVIDIA), `bat` (Itsbatt/victory-unified), + `br` (edsuuu/VI-BR-PORT), `tay` (TaynanGT/Vice-Tay). cesarzxk's CGBJ, + N137S and codec-d/cool_fox are not on GitHub (gtahub only). + +Next candidates (not in 6.12): +- nv a9632bc8 `VICTORY_DYNAMIC_SLOTS` on a capped heap: the 6.7 report + refused no tables (no "no free dynamic descriptor slots"), so not needed + yet; needed if lists in the air go past 384. +- nv `VICTORY_PIPELINE_WAIT_ONCE` with `PIPELINE_WAIT_MS=10000` (no dropped + draws for pipelines being made, one wait each). +- nv `VICTORY_AMBIENT_AIR`/`AMBIENT_MOST` (their ambient is the estimate + kind; ours is the constant: br 557d2f03 makes the air bound work with + the constant too). +- br a06da66f (tiled cascade shadows exact on wave32), 5c17c8c8 (fork PR + #1241, card-written texture views), 389b9747/ab9ae781 (card copies of + buffers from 64 KB on 8-12 GB cards). +- bat 2a95f8b5 (RTX 3070 paired bitcode, descriptor/shadow hardening). + +## Done in 6.11 + +- [x] **Shader stutter, disk side**: `pipeline/library.rs` `prefetch()` + wanted the library + 4 GB free; the 6.7 report had 4295 MB free for a + 773 MB library, so nothing was read ahead and each pipeline loaded in + play paged in from disk (2.6-4.5 s each in the 6.2 report). Now 1 GB + room (`VICTORY_LIBRARY_PREFETCH_ROOM_MB`), partial read of the front + when the whole does not fit. Log: `host pipeline library read ahead` + (and `... in part`). +- [x] **Shader stutter, translation side**: Try runs `victory prepare + ` once per build: every shader container translated into + the shader cache (avm's `victory shaders` idea, with our cache keys). + Log: `translating N shaders ...`, `translated ... from the files`. +- [x] `VICTORY_JOIN_PARTS=1` in the Y set (viktoschi, leonida launcher). +- [x] leonida c6c9da9f, first part: `WIDE_JOB` 256 KiB. +- [x] avm 011735ff: anisotropic point-mip samplers (static, console and + host-layout samplers, through `sampler::enhance`). +- [x] CI is green for the first time on this branch. The xtask policy test + had failed on every run: CI checks the pull request merged onto + `main`, where the owner's `VIctory-report-*.zip` uploads sit (now let + through, top level only), and on `host.rs` (587 KB) / `lower.rs` + (545 KB) over 512 KiB (Rust sources may be 1 MiB). CI's step outputs + moved out of the checkout; policy violations show in the annotations. +- [x] try.ps1: the 8 GB engine's fallback wrote `engine = 'ours'` (no such + name): `own`. + +Looked at and **not** ported this round (why): +- leonida 8f1e9032 (dark-scene ambient) and avm 9576c45/b4ba4bb (ambient + settle): our `ambient.rs` is a different implementation that already + follows the scene's brightness (6.6 `VICTORY_AMBIENT_FOLLOW`). +- Belobug e9428969: its pipeline part is a guard for AMD's compiler + crashing (RX 9070 XT); not needed on NVIDIA. +- mandy-port 9d581cb5 (DirectStorage handle per worker): sits on ffc80295, + which conflicts with our `dstorage.rs`; start-up time only (~5 s). +- leonida `INPLACE=0`: ours is already off unless H is on. + `TEXTURE_NO_WAIT`: already the default here. +- avm CBV/guard/journal (`0dec5dc`, `cc761bf`, `3406192`): 500-2000 lines in + `watch.rs`/`host.rs`/the translator each, off by default even in avm, + and they conflict everywhere with ours. They save 2-5 ms of a 45 ms + frame there; our 6.7 frames were 520-820 ms, spent elsewhere (below). + Waiting for the 6.11 report's numbers before taking that risk. + +## Where the time goes (6.7 report, last world minutes) + +| part of a frame | ms | +|---|---| +| preparing (copies 47-229 ms, textures 10-40 ms) | 160-330 | +| heap pass, textures picked by index | 64-138 | +| refreshes, all threads (write watch asks 30-65) | 58-169 | +| copying back | 54-102 | +| on the GPU | 12-317 | + +Draws dropped: ~2000 a frame are the ray-tracing structure builder (off with +B), about 10 a frame "being made". So in the world, pipelines were *not* the +frame-rate limit; the CPU's copies are. The 6.8+ fx set (heap thread, +parallel refresh) targets rows 2-3; the 6.11 report will show how much. + +## To do, in order + +### 0. Read the 6.14 report (needs the user's zip) +- [ ] The expected lines above; relay fetch wait; card busy %; fps. +- [ ] Any crash (lazy copy-back) or lost card (which step went off). +- [ ] If the card is now the limit: time our passes (`VICTORY_CARD_HASH_WIDE` + line), port Kelvaroq 0055 descriptors / 0041 mesh launch next. + +### 1. Read the 6.13 report (needs the user's zip) +- [ ] `through a resizable BAR` supported=true? `windows through the BAR` + counts and MB; memory pressure and `shared with the card` against 6.7 + (368 MB free, Critical); any 0x8007000E or device removed. +- [ ] `texture readback landed` waited_ms against worked_ms; landing line. +- [ ] Pipeline waits per frame (one frame per slow pipeline now). + +### 1b. Read the 6.11 report (needs the user's zip) +- [ ] `upscaler` line: PC FidelityFX used? `FidelityFX: upscalers the PC + build offers` (expect 3.1.x on the 4050), `upscaler context on the host`, + `recorded the title's temporal dispatch` with jitter not 0. +- [ ] If `did not record ... our temporal resolve instead`: which resource + or state failed (the `index`/`state` warning) and fix `host_state` / + `legal_state` for it. +- [ ] fps lines, `memory pressure`, pipelines "being made" over time. +- [ ] `host pipeline library read ahead` present (ok=true, how many ms)? +- [ ] `prepare.log`: how many shaders the game's files had, how long. +- [ ] The five frame parts above, against 6.7, with the heap thread on. + +### 2. Picture +- [ ] "PS3 characters": the 6.7 card held only 263 MB of title textures + (1.1 of 5.1 GB used): not a VRAM cap. Suspects: the title's streamer + starved by 2-3 fps (fixes itself with speed), LEVELS_ON_DEMAND leaving + top levels without tiles (check `uploads that left a held level + without tiles` in the stats), TEXTURE_BUDGET_MB=1536 of the low preset. + Log to add: per-minute count of textures shown below their top level. +- [ ] "Wrong light reflections": SKIP_RT=1 (boost B) has no ray-traced + reflections. Measure B off once on the 4050; port avm's light settle + (`9576c45`) and lightprobe/texlate (`b4ba4bb`). +- [ ] Belobug flicker fix (prelude uploads, 5d6bd841) if the 6.11 report + or the user shows flicker. +- [ ] Rest of the ACCC port (avm 66afb2b4: dot4, pk_fmac, src_scc, raw + buffer descriptors, s_bfm samplers) so the title's own console FSR + translates when the PC DLL is missing. + +### 3. Speed to 20+ (largest first) +- [ ] avm renderer ports into our engine: CBV `0dec5dc` (-4.7 ms), guard + `cc761bf` (-2 ms), journal `3406192` (-1..-3 ms), descriptors `f249fe0`. +- [ ] avm `5a2f8c60` `VICTORY_PIPELINE_LOW_MEMORY` (16 GB PCs). +- [ ] leonida c6c9da9f rest: the fused AVX2 compare-and-copy in + `merge_under_writes`, dynamic slots on capped heaps, pooled uploads. +- [ ] Belobug `over_cap`/`TEXTURE_MAX`, `release_tables`, by_address fix. +- [ ] Copy-queue texture uploads + show-after (avm; device-loss fix too). + +### 4. No shader/pipeline building while playing +- [ ] 6.7: ~2800 host pipelines made during the run (stand-ins meanwhile), + shader misses 0. Compare our `prepare` (recipes) with avm's pipeline + book + `warm --used`; log how many pipelines were made in game that + prepare had not made. + +### 5. Forks to check each round +- https://portwatch-vi.xyz/ (chunks 3-5 not read yet) +- avatarmanz/VIctory-7900XTX (main + claude/* branches), Belobug a-publier, + DexNom/VIctory, fxceless/victory-fork, stellarr-studio/kelvaroq +- Checked for 6.11: lepotane/VIctory-leonida (19.4 fps on an RTX 4060 Ti + 16 GB; memory settings sized for 16 GB cards), bolado-dev/mandy-port, + 1R0nim/iR0-fork and RandomSkelly/Series0nLinux (nothing for us). diff --git a/scripts/try/README.md b/scripts/try/README.md index b8db440ff9..6a04408428 100644 --- a/scripts/try/README.md +++ b/scripts/try/README.md @@ -24,18 +24,698 @@ of the fork, oldest first: The window lists what was added and what was skipped. +## Keeping itself up to date + +From 1.3 on, VIctory Try checks the branch's `scripts/try/try.ps1` each time +it updates. If that one is newer than the one inside your VIctoryTry.exe, it +runs the newer one, so fixes to VIctory Try itself need no new download. + +## Safety checks + +- The game exe can't be VIctoryTry.exe, victory.exe or anything inside + `%LOCALAPPDATA%\VIctoryTry`. Choosing VIctoryTry.exe as the "game" made + VIctory run VIctory Try, which started itself again in a loop. A saved path + like that is rejected and you are asked again. +- A VIctory Try started from inside a game run stops at once. +- Only one VIctory Try runs at a time, because two would build in the same + folders. +- When a build fails, the window shows the first error. + ## What it does -1. Asks for the game folder and the game exe, and remembers them. If the +1. Asks for the game files folder (the one with the `.rpf` archives) and the + game exe, which may be in another folder, and remembers them. VIctory uses + the folder holding the game's archives as the console's `G:` drive. If the folder holds several exe files, it lists them so you can pick one by number. 2. Installs Rust and the C++ Build Tools if they are missing. 3. Downloads the newest source, adds upstream's new fixes, and builds `victory.exe`. The first build takes a while; after that it only rebuilds when the source changed. -4. Runs `victory.exe run --execute` and shows the output. -5. When the game stops, you choose what's next: +4. Runs `victory.exe run --execute --console series-x` and shows + the output. From 3.0 the fork stands on fxceless/victory-gta6, which + renders the world on NVIDIA as a Series X (the Series S profile loses the + device before the first frame there). Defaults: shader loop limit 256, + `VICTORY_RELAY=2`, the two programs known to hang the card skipped, and + a cache folder of its own. + Each run keeps a recipe of every pipeline the game asks for (3.5). After + the game closes, and before the first run of a new build, VIctory Try + runs `victory.exe prepare`: with the game closed it compiles every one of + them into the pipeline library, on all cores but two (output in + `logs\prepare.log`). The next launch has them all from its start, so + one run that reaches a place is enough: no restarting again and again + while the world fills in a few pipelines a minute. + From 3.6 the compute shaders that ask for 64-lane waves, which 32-lane + NVIDIA cards refuse ("pipelines the card refused"), are translated in a + slower form that the card accepts (`VICTORY_WAVE_WIDE=0` turns it off). + 3.7 adds fxceless/victory-gta6's newest work: textures a draw needs are + put on the card before it, faster defaults (relay, copy-back on all + threads), packed textures stay queued, skin and hair colours checked + again after upload, and the fx-prs fixes (`VICTORY_RELAY=0`, + `VICTORY_WIDE_BACK=0` turn the new defaults off). + 3.8 adds, each with its own switch to turn it off: + - a draw whose pipeline is still being made is drawn with a ready one of + the same shaders instead of left out (`VICTORY_STAND_IN=0`); + - texture checks (read, compare, detile) on all cores at once + (`VICTORY_WIDE_TEXTURES=0`); + - upload memory in the card's own memory when Resizable BAR is on + (`VICTORY_GPU_UPLOAD=0`); + - buffers the card's memory has no room for compared on the card, their + shaders' side in the PC's memory, up to 768 MB (`VICTORY_PC_CARD_MB=0`); + - empty views no longer counted as refused, and the first calls of the two + unknown pipeline methods write their pieces to the log for the next fix + (`VICTORY_RAW_TYPED=1` tries a fix for raw views off 16 bytes). + 3.9 adds, each with its own switch to turn it off: + - texture checks no longer wait while the game streams memory in and out + (that wait was nearly all of the 1-2 s "textures" spikes; + `VICTORY_TEXTURE_NO_WAIT=0`); + - lazy copy-back: the game hears the card is done at once, and a game + thread that touches what the card wrote waits only for that + (`VICTORY_LAZY_BACK=0`; off by itself after a crash on a memory access); + - what the card wrote is fetched on its copy engine, not behind the + drawing work (`VICTORY_COPY_FETCH=0`); + - only bytes that really changed go to the card's copies + (`VICTORY_SAME_SKIP=0`); + - pipelines that the most draws wait for are compiled first + (`VICTORY_PIPELINE_MOST_ASKED=0`); + - DirectStorage reads up to 128 MB at once instead of 32 + (`VICTORY_DSTORAGE_STAGING_MB`). + 4.0 adds, each with its own switch to turn it off: + - copy back only what the game reads (like Dolphin skipping EFB copies): + buffers nothing on the CPU has touched for 64 batches stay on the card + (`VICTORY_READ_BACK_ONLY=0`); + - late results (like Xenia's fast readback): the game's uploads no longer + wait for the card's last results to come back; they use the ones before + (`VICTORY_LATE_RESULTS=0`); + - a second kind of stand-in pipeline (Dolphin's ubershader idea): an + object whose pipeline is still compiling borrows one with the same + shaders that only writes depth differently, instead of vanishing + (`VICTORY_STAND_IN_LOOSE=0`); + - a shared pipeline list: pipelines other players met start compiling + while the game loads (`VICTORY_SHARED_PIPELINES=0`); your own list goes + into the report zip (`early-pipelines.txt`), so it can be added; + - large 2 MB memory pages for the game's CPU memory, if Windows allows it + ("Lock pages in memory"; `VICTORY_LARGE_PAGES=0`); + - barrier trimming: GPU waits between two reads are dropped + (`VICTORY_TRIM_BARRIERS=0`; off by itself after the card is lost). + Occlusion queries already answer "visible" at once (nothing hidden by + them). + 4.1 fixes the build: up to 4.0 a failed build still counted as built + (cargo's lines became the build step's answer), so the old victory.exe + kept running and none of 3.9 or 4.0 reached the game. Upstream's new + commits are no longer added by default (one of them, upstream #1180, + does not build with this fork; `VICTORY_TRY_UPSTREAM=1` adds them, and + falls back to the fork alone when they do not build). It also brings + fxceless's newest fixes (the ones ztrx is made from): a write through one + view of a memory page is seen at its other views, descriptors the game + copies as bytes are mirrored (the first room renders right), a much + cheaper descriptor sync, and a shader cache that survives updates (no + re-translating every shader after each update, so less stutter at the + intro). + Also new in 4.1: + - the screen the game is told it has is 1080p (a Series X on a 1080p + TV); at 4K it rendered 2560x1440 inside and upscaled to 3840x2160 every + frame. **R** switches between 1080p and 4K; + - **Z** switches plain mode: VICTORY's own defaults for every speed and + safety switch, exactly as ztrx's launcher runs the game, to compare + the picture with Try's settings; + - the intro stutter: one pipeline worker is kept for pipelines the game + is drawing with right now, and pipelines only started early no longer + run above the game's own threads (`VICTORY_PIPELINE_KEEP_WORKER=0`, + `VICTORY_PIPELINE_EARLY_BOOST=1` restore the old way). + 4.2 brings seven frame-rate ideas taken from other places: + - **render scale** (as DLSS/FSR mods do): the game is told a screen 75% + the size (`VICTORY_RENDER_SCALE`, 50-100) and renders every pass that + small; our present scales each frame up to the window with a clamped + Catmull-Rom filter and sharpens it (`VICTORY_SHARPEN`, percent, 35; 5.8: + RCAS, 80); + - **no ray tracing** (as "RT off" mods): the console's ray structures + are not built here, so the rays walked empty memory, cost the card time + and gave black shadows and overbright light; with `VICTORY_SKIP_RT=1` + every ray misses at once. **B** switches both of these (on by default); + - **frames in between** (as VR's spacewarp): `VICTORY_FRAMEGEN=1` (**M**) + finds how each 16x16 block moved between the game's last two frames + and shows the last one moved on along that motion every + `VICTORY_FRAMEGEN_MS` (33) until the next arrives. The fps line still + counts only the game's frames; + - **copy back only what is read** (as CUDA's unified memory): buffers in + the PC's memory that nothing on the CPU reads are no longer compared + after every submission (350-520 MB a frame in the last reports); a + read while the results are held has them compared first + (`VICTORY_READ_BACK_ONLY_PC=0` restores; `VICTORY_QUIET_LANDINGS`, + `VICTORY_PROBE_EVERY`); + - **shared small buffers** (as one-memory machines): `VICTORY_INPLACE=3` + (**H**) makes buffers up to `VICTORY_INPLACE_SMALL_MB` (8) the game's + own memory, shared with the card, so they are neither copied in nor + compared; the big ones stay on the card. Off by default (riskier); + - **reuse**: a constant buffer many draws of a list name is copied to + upload memory once, not once per draw (`VICTORY_SHARE_CONSTANTS=0`); + - **textures detiled on 4 threads** (`VICTORY_DETILE_THREADS`, 1 for the + old way). + 4.3: the game's output (its rendering lines) opens in a window of its + own, "VIctory - game output"; the VIctory Try window keeps the menu, + updates, versions and settings. It closes by itself when the game stops + and the summary appears in the menu window (`VICTORY_TRY_ONE_WINDOW=1` + keeps everything in one window, as before). + 4.4, the picture fixes (each on by default): + - **ambient light** (A; from Belobug/VIctory-Belobug-AMD): the game's + bounced light comes from ray-traced probes that do not run here, so + everything the sun missed was black. A soft constant light replaces + it, shaded in corners from the depth (`VICTORY_AMBIENT=`, 0.6; + `off`; `VICTORY_AMBIENT_TINT=r,g,b`, `VICTORY_AMBIENT_SHADE`); + - **textures level by level** (L; fxceless's `VICTORY_LEVELS_ON_DEMAND`): + a texture takes the card's memory only for the sizes the game holds. + On an 8 GB card about 4.9 GB of textures filled it and some 16,000 + more waited for good: doors, props and people that streamed in later + stayed black or missing; + - **no stop when a pool is full** (mangrove's `VICTORY_POOL_NO_ASSERT`, + VIctory #698): the game stopped about 8 minutes in; + - pixel shaders read the other pixels of their 2x2 group through quad + reads (Belobug's fix for lines on car paint, glass and skin). The + first run after this update translates the shaders again. + 4.5, walls, ceilings and loading (from the 4.3 reports; each on by default): + - **shader clean-up off** (O; `VICTORY_SHADER_OPT=0`): the clean-up + passes left the prison cell's walls, roof and floor out (sky where + they should be) on an RTX 4080 and an RX 7800 XT; off, they are back + (Xeltax/VIcky, same-save A/B); + - **shadow fix** (W; from Xeltax/VIcky 05ee4e9, fxceless/victory-fork + #62): on 32-lane NVIDIA cards the 14 cascade-shadow programs are wrong + in one 64-lane form (missing ceiling, dark room); they are kept out of + it (`VICTORY_WAVE_DEEP_SKIPS_NOT=,...` sets the list, `none` + empties it; `VICTORY_WAVE_DEEP_SKIPS_ONLY` the other way round); + - one more compute program translates on 32-lane cards (`f133e35efed2a48a`, + fxceless/victory-fork #190 by gdawid94); + - streaming: the card's page-mapping copies map runs of pages as one + view instead of one 64 KiB page at a time under the lock texture reads + wait on (Felix2180, fxceless/victory-fork #823): up to 2 s a frame of + waiting while the world streams in; + - the summary no longer calls the ~370 draws a frame skipped at the end + "waiting for pipelines": with none being made they are compute work + (mostly the ray-tracing builder, which is off), not missing objects. + The first run after this update translates the shaders again. + 4.6, Series S and the command list: + - **Series S shows the game** (C; fxceless/victory-fork #188 by + sagouindupm and Filip722): in Series S mode the game presents two + planes, its picture (1920x1080) and its interface over it (3840x2160, + see-through where empty), and calls the console's FidelityFX upscaler + to make the picture from a 1280x720 render. Only the first plane was + shown and the upscaler's output stayed black: a black window after + loading. The interface is now drawn over the picture, and the upscale + dispatch becomes a plain stretch of the 720p render. In Series S, Try + leaves out the 75% render size and the frames in between (the game + already renders smaller); ray tracing stays skipped with B; + - **the menu lists every command**: its key, what it is, whether it is + on now and what it does. Switches flip at once and show the list + again; Enter runs the game. V shows the version. + 4.7, speed (K switches both): + - **the game's buffer copies run on the card** (pablogonz12/Scarlight #86, + `VICTORY_GPU_COPIES`): a copy between two buffers that already have a + copy on the card is one copy command in the card's list, in order with + the game's work, and the result goes back to the game like anything + else the card writes. On the CPU, each such copy that touched memory + the card was still writing made us wait for the card to finish all it + had been sent: about 157 ms of every 485 ms frame in the 2026-11-25 + report (the card was idle almost half the frame). The frame-rate line + now says how many copies ran on the card; + - **the card's checks are joined** (`VICTORY_CARD_REHASH_RUNS=1`): after + each upload the card re-checks the pieces it received, about 1,900 + tiny one-after-the-other passes a frame; now one pass per run of + pieces. The same pieces are checked either way. + 4.9, this fork's engine again, with AvatarManz's fixes copied in + (avatarmanz/VIctory-7900XTX, its fixes only, not its engine): + - **no more waiting for the card every frame** for memory the game + changed under the card's writes: each frame of the 2026-11-25 report + stood 400 ms for the card while only 3 pages were checked. The changed + bytes are now put in beside the card's writes (`VICTORY_MERGE_RUNS`, + `VICTORY_MERGE_UNWATCHED_MB`), so the CPU and the card work together; + - **the card is kept awake** between the game's submissions + (`VICTORY_CARD_AWAKE=1`): it stood idle 180 ms a frame and lowered its + clocks; + - **textures show on a full card**: the 8 GB card was full for the + whole run and 17,000 textures waited for room, drawn black or grey. + Now a new texture gets memory for its small levels only (blurred, with + its colours) until there is room (`VICTORY_SQUEEZE_TILES`, 0: off); + - **textures stop popping to black**: a slot that gets a sharper or moved + copy of its texture keeps showing the old one until the new one is up + (`VICTORY_KEEP_SHOWN=1`); + - **shader fixes**: exact values from packed buffer formats (wrong + materials), cube-map reflections at the right sharpness, unordered + views of vertex programs declared; + - render targets not set again when they did not change + (`VICTORY_BIND_CACHE`), ranges of changed memory joined before the + texture lookup; + - the report lists which programs the dropped draws belong to. + 5.0, every shader the 2026-11-25 16:10 report named fixed in the + translator: + - **f133e35efed2a48a translates**: a select on a constant lane mask and + a lane write are now taken when each 32-lane host wave runs on its own + (each thread knows its console lane, so it is exact). The same was all + that kept other 64-lane compute programs asking for 64-lane waves, which + the RTX 4060 refuses (6 pipelines in every run); + - **7f05ddab771799a9 translates**: the loop mask of lanes still looping + (`s_andn2 rest, rest, exec`) is read as the ballot of the lanes in its + block (`VICTORY_MASK_ELSEWHERE=0`: refused as before); + - **ceb5eb68cd99cb07 translates**: a buffer's record count is read from + the host view (0 for a view that is not there, which the program tests + to skip itself: the "buffer view that is not there" warning); + - a texture the game fills itself after its upload is now told as + information, not a warning (it was already uploaded again); + - **recommended settings by default**: the first 5.0 run puts every switch + back to the recommended one (whatever a lost card or an earlier version + switched off); **D** does it again any time; + - the refused pipelines' console shaders are in the report, for the next + round. + 5.1, the 6 pipelines the RTX 4060 refused in every run (they asked for + 64-lane waves, which NVIDIA cards do not have): + - **64-lane programs split in two 32-lane halves even around shared + memory**: the way the open VIctory pull requests run them (#1890 "split + waves", #233), taken further where those still refuse: the halves meet + wherever every lane runs, and are not made to meet inside branches + only some lanes take (a meeting there would freeze the card). Close + results instead of a pipeline that is never made and dispatches that + are dropped (`VICTORY_WAVE_FORCE_SPLIT=0`: refused as before); + - in that last form also: wave-wide branches, lane permutes, 16-bit wave + sums and lane masks are taken within each half. + 5.2, the fixes of codec_d's cool_fox (the build said to reach 25 fps on + NVIDIA cards), taken into this fork (not its engine): + - **2da4beb386509b77 translates** (transmission prefilter): the lanes an + access really runs for are known when join edges are pruned; its buffer + stayed empty, so eyes, glass and alpha came out as black squares; + - **faces no longer deform**: 16-bit data of integer buffer views keeps + its bits (the face network's output was noise), for table views too; + - **draws no longer lose their tables**: descriptor slots come back as soon + as the card has run a submission, and a draw out of slots waits for them; + - **one bad indirect record no longer empties the rest** + (`VICTORY_INDIRECT_REST=1`: as before); + - more 64-lane programs lowered for 32-lane cards (driver-compiled loops, + two scene kernels, lane spills), and each view heap gets its own buffer + refresh every frame. + 5.3, our own memory guard, after the one in codec_d's cool_fox (its + block pool and residency module are not in this fork): + - **upload buffers are reused**: texture and buffer copies took a new + upload buffer from the driver for every copy and freed it again after + the frame; now they go back to a pool by size and the next copy takes + one (`VICTORY_UPLOAD_POOL=0`: as before); + - **three memory levels** (normal, getting short, nearly out) from the + memory Windows has left to commit, the free memory and the card's + budget: idle copies are let go sooner as memory runs short, and when + nearly out the texture pass takes half (`VICTORY_PRESSURE=0`: off); + - **after a refused allocation**: what is kept for reuse is let go and the + allocation asked once more, and new texture staging waits half a second + instead of a burst of failing calls (a stutter); + - the game log says each report which level it is at, and how many upload + buffers were reused. + 5.4: report zips go to a folder of their own, `Downloads\VIctory-reports` + (no more Desktop); **S** changes the folder, **E** opens it. + 5.5, black roads, buildings and people (the 2026-11-25 and 11-26 reports: + 17,000 to 27,000 textures waiting for room on 6 and 8 GB cards): + - **cards under 8 GB of budget run as Series S once by themselves** + (render targets of 1280x720 take far less of the card); **C** goes + back to Series X, and the choice then stays yours; + - the room kept for render targets is 1,536 MB on Series S and never more + than 35 % of the card (it was 3,072 MB on every card); + - a texture that finds no room gets its small levels (blurred, not black) + up to the card's budget, not only up to 97 % of it; + - the memory guard no longer halves the texture pass when nearly out; + - the summary says how many textures still waited at the end. + 5.6, the cause of the black textures found (the 2026-11-26 report: + 1,448 textures made "level by level", 2.9 GB, and **0 MB ever given to + them**): + - the step that gives such a texture its memory ran *before* the check + that reads the texture (the checks run in batches on several threads): + it always saw no level ready, so these textures stayed black for the + whole run. It now runs right after the checks; + - **texture quality on 6 and 8 GB cards**: the largest level of each big + texture (three quarters of its memory) is left out, as PC games' + "texture quality: medium" does (`VICTORY_TEXTURE_TOP_DROP=0` to 3; one + more while the card is full). Every big texture is made level by level + on such cards, so it only takes memory for the levels it shows; + - the memory for a texture's levels is given in one call instead of one + per level; + - small levels are given up to an eighth past the card's budget (blurred + instead of black); + - the Series S switch reads the card's memory from Windows itself when no + log tells it (5.5 never found it in the log), and runs once more. + 5.7 (the 2026-11-26 12:53 report: textures now get their memory, 108 MB + to 1,024 levels, but the run was **still Series X** and the card stood at + 5.8 GB of a 5.2 GB budget with 22,500 textures waiting): + - **VIctory itself picks Series S** on a card with 9 GB of its own memory + or less when Series X is asked for (the launcher's switch never reached + a launcher that had updated itself with U). A Series X picked with + **C** stays Series X (`VICTORY_CONSOLE_AUTO=0`); + - **U** now hands over to the newer VIctory Try at once, so the + launcher's own fixes apply without closing the window; + - texture quality now reaches small textures too: textures of 256 KB or + more are made level by level on 6 and 8 GB cards (the report's textures + were 411 KB on average, nearly all under the old 1 MB line), and their + largest level is left out from 256 KB up; + - a new log line says where the card's memory goes (render targets, + textures, tiles, staging buffers) and which console ran. + 5.8 (a sharper image, not a blurrier one): + - the scaled-up frame is sharpened with **FSR 1's RCAS** (contrast-adaptive: + edges and texture detail get their contrast back, flat areas and noise + are left alone), 80 % by default (`VICTORY_SHARPEN`, percent); the old + sharpening was mostly undone by its own clamp; + - **16x anisotropic filtering** on every textured sampler that filters + between levels (roads and walls seen at an angle stay sharp; + `VICTORY_ANISO=1` to 16), and a **negative level bias** for the render + scale (-0.42 at 75 %, as DLSS and FSR ask of games; `VICTORY_LOD_BIAS`, + in hundredths); + - **adaptive texture quality**: the largest levels are left out only while + the card is past 70 % of its budget, not always; textures uploaded + blurred get their full detail back once memory frees up (256 a frame; + `VICTORY_TEXTURE_TOP_DROP` still fixes the count); + - **placeholders instead of black**: a texture not on the card yet reads + a mid grey (colour), a flat normal (normal maps) or white (occlusion and + masks) instead of zeros, so surfaces look plain rather than black while + they load (`VICTORY_PLACEHOLDERS=0`: off); + - a log line counts levels left out, textures made sharp again and + placeholders shown. + 5.9 (the 2026-11-26 13:36 report: Series S at last, the card under its + budget at 3.7-4.1 of 5.2 GB, yet 14,000 textures still waiting: this + engine prepares them on the CPU at about 11 MB/s, 4.3 s a frame, with the + card 10-21 % busy): + - **N: the engine.** By default VIctory Try now builds and runs + **soldsawn/victory-nvidia-8gb** (soldsawn's build of + fxceless/victory-fork, the community's main line), measured on an + RTX 4060 Laptop 8 GB at 8-10 fps with clean textures. It is kept in its + own folders (`victory-8gb`, `target-8gb`, `cache-8gb`), so this fork's + build stays and N switches back at once; this fork's source is still + fetched, so VIctory Try keeps updating itself; + - it runs with that build's own launcher settings + (`VICTORY_TEXTURE_DROP_MIPS=2`, `VICTORY_RESOLUTION=1920x1080`, the + texture upload thread `VICTORY_HEAP_WORKER=1` and the rest), none of + this fork's, plus Series S and halved card budgets on cards under 7 GB. + Settings made before VIctory Try started are kept; + - if it cannot be downloaded or built, this fork's engine runs instead; + - the `8 GB engine builds` workflow checks every 6 hours that its newest + main still compiles on Windows. + 6.0 (the 2026-11-26 14:16 report on this fork's engine: the world at 1.0-1.7 s + a frame, not 5 s; textures are fast now, but the submitting thread spends + 0.5-1.1 s a frame on the heap passes, 160-230 ms syncing descriptor + records, 100-150 MB of CPU compares, with the card 40-74 % idle and the + PC under 1 GB of free memory): + - **this fork's engine is the default again** (5.9's 8 GB engine made no + difference); N still switches to it (`engine` = `8gb`); + - **all of the CPU**: the threads that copy back, refresh and compare are + all of the CPU's threads but two, at most 16 (`VICTORY_WIDE_THREADS`; + they were a quarter, at most 6), and run above normal priority, as does + the copy-back thread (`VICTORY_WIDE_PRIORITY=0`: normal); big textures + are detiled on half the CPU's threads (`VICTORY_DETILE_THREADS`; 4 + before); + - **descriptor sync on every thread**: the records the title copies into + its heaps as bytes are looked at page by page on those threads + (`VICTORY_HEAP_SYNC_WIDE=0`: one thread), and without a lock per record + (one atomic per slot; fxceless #1043 found the same lock churn); + - **the whole machine**: the process runs above normal priority, Windows + is told not to throttle it onto efficiency cores (EcoQoS off), and it + gets a soft minimum working set of a quarter of the PC's memory, at + most 4 GB (`VICTORY_WHOLE_MACHINE=0`: none of it); + - **the card first**: the graphics and copy queues ask for high priority + (`VICTORY_QUEUE_HIGH=0`: normal); the device is made on the adapter + Windows ranks fastest (`EnumAdapterByGpuPreference`; `VICTORY_ADAPTER=first`: + the first one), every adapter is named in the log, and victory.exe is + set to "High performance" in Windows' graphics settings; + - **the card looks for shader writes** in title buffers of 4 MB and more + (16 MB before on 6-12 GB cards; `VICTORY_CARD_BUFFERS_MIN_MB`); + - **the CPU's own graphics as a helper (I)**: on a PC whose CPU has + graphics of its own, the browsers, Discord, Spotify and Steam's web + views that are running are set to "Power saving" (that chip) if they + had no setting, so they leave the NVIDIA card's memory to the game after + their next start; I switches it off and removes those settings again; + - **power**: the High performance plan (and Windows 11's Best performance + mode) while the game runs, the old one back afterwards + (`VICTORY_TRY_POWER=0`: left alone); + - **a build for this PC**: `-C target-cpu=native` and thin LTO + (fxceless #1117); if that fails, the plain build + (`VICTORY_TRY_PLAIN_BUILD=1`: plain only). The first build after the + update rebuilds everything once. + 6.1 (6.0 ran: much better than 5.4, but people looked low-detail at first + and buildings came in late; and U had never moved a window past 5.4): + - **U really updates**: the newer version takes over in the same window + with an `UPDATING` line, and starts from the settings made before + VIctory Try started (it took the old window's run settings for the + user's own and kept their old values); after U with nothing newer it + says so; + - **the version everywhere**: window titles, the first line of the game + log (`VICTORY_TRY_VERSION`, printed by victory.exe), the report name + (`VIctory-report--.zip`) and `try-version.txt` in it; + - **loading screens pre-load the world** (the console's way): a frame + after one of fewer than 400 draws (`VICTORY_LOADING_DRAWS`; 0: off) + gives the pass over textures picked by index up to 1.2 s and 768 MB + (384 MB when the PC is short of memory); + - **full detail until 85 %** of the card's budget + (`VICTORY_TEXTURE_SHARP_PERCENT`; 70 before, and a 6 GB card sat at + 73 %), and 1,024 blurred textures a pass made sharp again (256 before); + - **DirectStorage workers above normal priority** (the title's streamer + waits for them; `VICTORY_WIDE_PRIORITY=0`: normal). + 6.2 (6.0 and 6.1: the picture right, but it takes long to come in): + - **the picture first, the detail after**: while 1,500 or more textures + picked by index are due (until under 300), a texture made level by + level is detiled and uploaded without its largest levels of 512 KiB or + more (`VICTORY_TEXTURE_RUSH`, 2 unless set, 0: off; never past the + fourth level from the smallest): about a sixteenth of the bytes and + CPU time, so the whole scene is there, soft, in a fraction of the + time. When the backlog has drained, those textures are uploaded whole + again (`sharpen`, 1,024 a pass) and textures that draws read through + tables are detiled whole at their next use. + 6.3 (the 6.2 report, 154745): + - **loading screens really pre-load**: the pass that runs behind a + loading screen is the early one (12 ms and 64 MB a frame); the 6.1 + loading budget was only in the world's pass. Now a loading screen gives + the early pass `VICTORY_LOADING_MS` (200) and 768 MB a frame. + - **a loading screen is 30 frames of few draws in a row** + (`VICTORY_LOADING_FRAMES`); one such frame turned the 1.2 s budget on + in the world (passes of 750 ms to 2 s at 1-2 fps). + - no texture rush behind a loading screen; textures it made soft are + uploaded again once it is over (`unrush`), not only under the sharp line. + - the pipeline library (770 MB) is saved at most every + `VICTORY_LIBRARY_SAVE_S` (180) in the world when the PC is short of + memory. + 6.4: + - **the world's curtain**: for up to `VICTORY_JOIN_HOLD_MS` (10,000; 0: + none) after a loading screen went, while 300 or more textures picked + by index are due, the world's pass gets 1.5 s and 768 MB (384 MB short + of memory); a line says when the curtain is down. + - **priority** (`VICTORY_TEXTURE_PRIORITY=0`: off): the slots looked at + again first, then the queue's order (newest and oldest write in turns) + with three textures of up to 256 KiB to one larger. + - **staging pool**: texture staging buffers go back to a pool by size + class (`VICTORY_STAGING_POOL_MB`; 128, 96 short of memory, 48 nearly + out) and are zeroed when taken again. + - **library read-ahead** (`VICTORY_LIBRARY_PREFETCH=0`: off): the mapped + pipeline library is prefetched at the start when the PC has its size + and 4 GB more free. + - Resizable BAR uploads on their own config switch (`rebar`), off again + after a lost card; ambient light 0.45 (A: normal / low / high / off). + 6.5: + - the world's texture pass takes at most `VICTORY_TEXTURE_FRAME_SHARE` + (35) percent of the frame before, never under 60 ms (not behind a + loading screen or the curtain). + - adaptive texture quality with a band: short from the sharp line, + sharp again 5 points under it. + - a line every 100 passes: where the texture pass's time goes. + 6.6: + - write-watch askings run with the journal let go; only askings of the + same pages wait for each other (`VICTORY_WATCH_UNLOCKED=0`: as before). + - the title's CPU buffer copies that read what a flight's shaders may + write take the results one flight late (`VICTORY_LATE_COPIES`, 1; 2 + also copies that write there; 0 settles as before). + - `VICTORY_CARD_FETCH_INFLIGHT=1` from Try with the relay (off with the + 3.8 additions after a lost card). + - the ambient light follows the brightness of the lit scene the probe + resolve reads, measured on the card (`VICTORY_AMBIENT_FOLLOW=0`: off; + `_MIN` 0.35, `_STEEP` 0.35). + - the world's texture pass: at most `VICTORY_TEXTURE_PASS_MS` (120) and + a share of the eased frame time. + 6.7: + - **saved game** before every launch: Enter continues the auto-save, N + starts a new game from the very beginning (the title's `saves` and + `storage` folders under `%LOCALAPPDATA%\victory\data\7952987A` are + renamed `*.bak-