D3D12.X: clamp ExecuteIndirect argument records and total work on the GPU #1785

Open
mastrr9 wants to merge 1 commit from upstream-pr/1795 into main
mastrr9 commented 2026-11-24 20:51:47 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by mastrr9 on 2026-11-24T20:51:47Z.


Summary

Adds a small GPU compute clamp pass (indirect_clamp.hlsl / indirect_clamp.rs) that runs before ExecuteIndirect for command signatures without root arguments. Corrupt or garbage indirect draw/dispatch counts can no longer trigger DXGI_ERROR_DEVICE_HUNG (0x887a0006): argument records and total work are bounded on the GPU before the PC reads them.

  • Enabled by default.
  • XCL_INDIRECT_CLAMP=0 disables it.

Tested

Windows 11 x64, NVIDIA GeForce RTX 5080 16 GB.

  • cargo test -p xcl --lib indirect_clamp -- --nocapture --test-threads=1: 4 passed, 0 failed (includes live GPU execution of gpu_records_are_clamped_and_budgeted)
  • cargo test -p xcl --lib execute_indirect -- --test-threads=1: 2 passed, 0 failed
  • cargo test -p xcl --lib -- --test-threads=1: 844 passed, 0 failed, 22 ignored (no new warnings)

Regression run
Smoke run by @Anon64 in comment below: https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7148374202
Contributed by a community tester; the PR author did not run it. Both blocks are pasted as posted.

main:

xcl-smoke v1
commit: 689f2db477c3c062cf162649781640ef8a977c18
gpu: NVIDIA GeForce RTX 3060
title: 21222967
seconds: 60
exit: 0x0
frames shown: 1590 (PresentX 1591)
presents per 2 s (last 3): 44 53 35
device removals: 0
crashes: 0
peak commit: 25217 MB

PR:

xcl-smoke v1
commit: 201d67da8bee82a099c99fd78ba5626373d6f932
gpu: NVIDIA GeForce RTX 3060
title: 21222967
seconds: 60
exit: 0x0
frames shown: 1616 (PresentX 1617)
presents per 2 s (last 3): 60 40 54
device removals: 0
crashes: 0
peak commit: 23909 MB

Tester's setup: RTX 3060 12 GB (581.80, wave32), Windows 11 26200, release, XCL_NETWORK=0, A pressed every 4 s from 20 s, scripts/smoke.ps1 on a retail title for 60 s, in one batch with the main run.

No device removals or crashes; 101 % of main's frames, 94 % of its peak commit.

Tester's AI use: Written with Claude Code (Claude Opus 5.5) from runs on the tester's machine.

Not tested

  • A full cargo test --workspace run by the author: the widest run reported above is the xcl library tests.
  • Reproducing the device removal with and without the clamp in a title: not reported by the author.
  • AMD and Intel GPUs, by the author.
  • Whether the community regression run above reaches the code this PR changes.

AI use

  • Claude Code assisted with the change (the commit's Assisted-by trailer); the model is not recorded there.
  • Claude Code (Claude Sonnet 5.5) added the community regression run to this description and updated the lines that it made out of date or that the PR check requires.
<!-- greyfinch-sync:ivall/xcl:issue:5480122647 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795). Originally posted by [mastrr9](https://github.com/mastrr9) on 2026-11-24T20:51:47Z. --- ## Summary Adds a small GPU compute clamp pass (`indirect_clamp.hlsl` / `indirect_clamp.rs`) that runs before `ExecuteIndirect` for command signatures without root arguments. Corrupt or garbage indirect draw/dispatch counts can no longer trigger `DXGI_ERROR_DEVICE_HUNG` (`0x887a0006`): argument records and total work are bounded on the GPU before the PC reads them. - Enabled by default. - `XCL_INDIRECT_CLAMP=0` disables it. **Tested** Windows 11 x64, NVIDIA GeForce RTX 5080 16 GB. - `cargo test -p xcl --lib indirect_clamp -- --nocapture --test-threads=1`: 4 passed, 0 failed (includes live GPU execution of `gpu_records_are_clamped_and_budgeted`) - `cargo test -p xcl --lib execute_indirect -- --test-threads=1`: 2 passed, 0 failed - `cargo test -p xcl --lib -- --test-threads=1`: 844 passed, 0 failed, 22 ignored (no new warnings) **Regression run** Smoke run by @Anon64 in comment below: https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7148374202 Contributed by a community tester; the PR author did not run it. Both blocks are pasted as posted. main: ``` xcl-smoke v1 commit: 689f2db477c3c062cf162649781640ef8a977c18 gpu: NVIDIA GeForce RTX 3060 title: 21222967 seconds: 60 exit: 0x0 frames shown: 1590 (PresentX 1591) presents per 2 s (last 3): 44 53 35 device removals: 0 crashes: 0 peak commit: 25217 MB ``` PR: ``` xcl-smoke v1 commit: 201d67da8bee82a099c99fd78ba5626373d6f932 gpu: NVIDIA GeForce RTX 3060 title: 21222967 seconds: 60 exit: 0x0 frames shown: 1616 (PresentX 1617) presents per 2 s (last 3): 60 40 54 device removals: 0 crashes: 0 peak commit: 23909 MB ``` Tester's setup: RTX 3060 12 GB (581.80, wave32), Windows 11 26200, release, `XCL_NETWORK=0`, A pressed every 4 s from 20 s, `scripts/smoke.ps1` on a retail title for 60 s, in one batch with the `main` run. No device removals or crashes; 101 % of main's frames, 94 % of its peak commit. Tester's AI use: Written with Claude Code (Claude Opus 5.5) from runs on the tester's machine. **Not tested** - A full `cargo test --workspace` run by the author: the widest run reported above is the `xcl` library tests. - Reproducing the device removal with and without the clamp in a title: not reported by the author. - AMD and Intel GPUs, by the author. - Whether the community regression run above reaches the code this PR changes. **AI use** - Claude Code assisted with the change (the commit's `Assisted-by` trailer); the model is not recorded there. - Claude Code (Claude Sonnet 5.5) added the community regression run to this description and updated the lines that it made out of date or that the PR check requires.
futurepro62 commented 2026-11-24 22:06:52 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by futurepro62 on 2026-11-24T21:31:29Z.


Full-suite run, since this PR has no test report yet. Tested exact head 7b9a1e0 (on its base b9b6ea6).

Tested

  • NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 616.64, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.100.0 MSVC, DXC + dxil.dll 1.9.2602.17 (Windows SDK 10.0.26100), debug, D3D12 debug layer installed.
  • cargo build --workspace, then XCL_REQUIRE_GPU=mesh cargo test --workspace -- --test-threads=4 --skip heap_window_out_of_memory_falls_back_to_the_switch_form --skip pso_measurement_compiles_an_exact_synthetic_record: 891 passed, 0 failed, 42 ignored. SKIPPED (no wave64): gpu_geometry_wave32_prefix_count_over_a_mask, gpu_wave32_program_in_wave64_hardware.
  • The new tests ran and passed: signatures_without_root_arguments_are_bounded, a_signature_that_cannot_be_bounded_replaces_one_at_the_same_address, config_words_follow_the_shader, gpu_records_are_clamped_and_budgeted.
  • Same head on the AMD Radeon integrated GPU (iGPU) of the Ryzen 7 9800X3D (RDNA2, XCL_ADAPTER=radeon), cargo test --workspace -- --test-threads=4: 893 passed, 0 failed, 42 ignored. SKIPPED: heap_window_out_of_memory_falls_back_to_the_switch_form (no heap windows), pso_measurement_compiles_an_exact_synthetic_record (cannot disable the driver cache (Windows Developer Mode is required): The application requested an operation that depends on an SDK component that is missing or mismatched. (0x887A002D)).
  • Two tests were skipped with --skip on NVIDIA. Both fail on main 7f7e768 too, not because of this PR: under XCL_REQUIRE_GPU=mesh, runner::skip_test turns their skips into failures. heap_window_out_of_memory_falls_back_to_the_switch_form skips when XCL_HEAP_WINDOWS is unset (#1651), and shaders::tests::pso_measurement_compiles_an_exact_synthetic_record skips because Developer Mode is off on this PC (it cannot disable the driver cache). The AMD run does not set XCL_REQUIRE_GPU, so there both just print SKIPPED.

Not tested

  • a release build, a game (test run only).

AI use

  • Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.
<!-- greyfinch-sync:ivall/xcl:comment:7145043636 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7145043636). Originally posted by [futurepro62](https://github.com/futurepro62) on 2026-11-24T21:31:29Z. --- Full-suite run, since this PR has no test report yet. Tested exact head `7b9a1e0` (on its base `b9b6ea6`). **Tested** - NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 616.64, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.100.0 MSVC, DXC + dxil.dll 1.9.2602.17 (Windows SDK 10.0.26100), debug, D3D12 debug layer installed. - `cargo build --workspace`, then `XCL_REQUIRE_GPU=mesh cargo test --workspace -- --test-threads=4 --skip heap_window_out_of_memory_falls_back_to_the_switch_form --skip pso_measurement_compiles_an_exact_synthetic_record`: **891 passed, 0 failed, 42 ignored**. SKIPPED (no wave64): `gpu_geometry_wave32_prefix_count_over_a_mask`, `gpu_wave32_program_in_wave64_hardware`. - The new tests ran and passed: `signatures_without_root_arguments_are_bounded`, `a_signature_that_cannot_be_bounded_replaces_one_at_the_same_address`, `config_words_follow_the_shader`, `gpu_records_are_clamped_and_budgeted`. - Same head on the AMD Radeon integrated GPU (iGPU) of the Ryzen 7 9800X3D (RDNA2, `XCL_ADAPTER=radeon`), `cargo test --workspace -- --test-threads=4`: **893 passed, 0 failed, 42 ignored**. SKIPPED: `heap_window_out_of_memory_falls_back_to_the_switch_form` (no heap windows), `pso_measurement_compiles_an_exact_synthetic_record` (cannot disable the driver cache (Windows Developer Mode is required): The application requested an operation that depends on an SDK component that is missing or mismatched. (0x887A002D)). - Two tests were skipped with `--skip` on NVIDIA. Both fail on main `7f7e768` too, not because of this PR: under `XCL_REQUIRE_GPU=mesh`, `runner::skip_test` turns their skips into failures. `heap_window_out_of_memory_falls_back_to_the_switch_form` skips when `XCL_HEAP_WINDOWS` is unset (#1651), and `shaders::tests::pso_measurement_compiles_an_exact_synthetic_record` skips because Developer Mode is off on this PC (it cannot disable the driver cache). The AMD run does not set `XCL_REQUIRE_GPU`, so there both just print SKIPPED. **Not tested** - a release build, a game (test run only). **AI use** - Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.
DavidM1911 commented 2026-11-25 00:09:01 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by DavidM1911 on 2026-11-24T23:41:49Z.


Verification on RTX 3060 Ti (Windows 11): merge conflict with current main — needs a rebase before it can be tested.

<!-- greyfinch-sync:ivall/xcl:comment:7147692905 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7147692905). Originally posted by [DavidM1911](https://github.com/DavidM1911) on 2026-11-24T23:41:49Z. --- Verification on RTX 3060 Ti (Windows 11): **merge conflict with current `main`** — needs a rebase before it can be tested.
ofc0urse commented 2026-11-25 00:09:04 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by ofc0urse on 2026-11-24T23:46:52Z.


Title run of 7b9a1e0 on an 8 GB NVIDIA card, with the skipping it is meant for. The new head 201d67d has the same indirect_clamp.rs and .hlsl and resolves the bind.rs conflict the way I did below, so this should hold for it too. The clamp builds and runs, but it does not prevent the device removal here: every run with it on still ended in 0x887a0006, at 152 to 269 s.

Tested: main c4d37be + #1798 + #1284 + this PR, release, merged locally. The only conflict was execute_indirect in bind.rs, where main now wraps the PC call in fresh_indirect_arguments; I kept that wrapper around both calls (bounded copy and original). RTX 4060 Ti 8 GB (32-lane waves, split wave64), driver 621.24, i5-14400F, 32 GB, Windows 11 Pro 26300, retail 1.0.2.1. XCL_PSO_WAIT_MS=50 (so dispatches of pipelines still being built are skipped), A pressed at 115, 125 and 150 s, 600 s cap.

run XCL_LOOP_BUDGET clamp device removed at frames
1 256 on 264 s 4,534
2 256 off (XCL_INDIRECT_CLAMP=0, same binary) 206 s 4,449
3 256 on 152 s 4,224
4 unset on 214 s 4,405
5 unset on 236 s 4,451
6 unset on 269 s 4,446
7 unset on, plus #1702 (XCL_TEXTURE_PAGES_SYSTEM_MEMORY=1) 226 s 4,462
8 as run 7, with #1323's markers also around draws on 225 s 4,467

Runs 3 to 8 also had #1323 (XCL_GPU_CULPRIT=1) and a local line that logs its markers at the device removal, not only at a watchdog release. Runs 5 to 8 skipped compute programs by hash (a local test switch, below). In runs 7 and 8 local video memory peaked at 4,433 and 4,846 MB, against 14,000 to 15,000 MB in the others, so on this card the removal does not come from oversubscribed video memory.

  • With the clamp on and off, the removal comes in the same phase, right after the world starts loading. One run per arm is not enough to say whether the clamp moves it.
  • In run 4 #1323 named one dispatch started and not done at the removal: cs df837c748fdf56b8 (CS_ScreenProbes_RadianceSpatialFilter), 14,400 groups, a direct Dispatch, not an ExecuteIndirect. Its loop bounds come from memory.
  • In runs 3, 5, 6 and 7 #1323 found no dispatch in flight (0 of 8, 0 of 263, 0 of 275, 0 of 137 lists). Whatever ran too long there was not a compute dispatch, so a clamp on indirect dispatch arguments could not reach it.
  • For run 8 I put the same markers around DrawInstanced, DrawIndexedInstanced and graphics ExecuteIndirect too (local change). Still nothing in flight at the removal (0 of 236 lists). What is left are the paths without a marker: XCL's own copies and texture uploads, CPU-expanded rect lists, clears and resolves.
  • Run 5 skipped every dispatch of df837c748fdf56b8; runs 6 to 8 also skipped 45a2f1928c4e6f73 (CS_AllocBatchCSCullOutput) and cd4c7be781d7d2df (CS_ComputeHitDetectionSkinnedResults). Those two are the programs VIctory's NVIDIA testers skip with VICTORY_SKIP_PIPELINES=eeed82b877b44b5f,b83629b90cd2b7bc: VIctory names a shader by the first 16 hex digits of the BLAKE3 hash of the same bytes that XCL hashes with FNV-1a, and the two match these records. The device was still removed.
  • One more run with run 6's settings is not in the table: it ended at 180 s in an access violation in gpu::tiling::Chain::detile_level (tiling.rs:438, called from title_textures::subresources), reading title memory that was no longer mapped, before any skipped program had run.

Not tested: more than one run with the clamp off. What was running at the removal in runs 3 and 5 to 8: XCL_DRED=1 made the driver rebuild every pipeline from the start, so the title never got past its first minutes. AMD.

AI use: Claude Code (Claude Opus 5.5) merged the build, ran the title, read the logs and wrote this comment.

<!-- greyfinch-sync:ivall/xcl:comment:7147786799 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7147786799). Originally posted by [ofc0urse](https://github.com/ofc0urse) on 2026-11-24T23:46:52Z. --- Title run of `7b9a1e0` on an 8 GB NVIDIA card, with the skipping it is meant for. The new head `201d67d` has the same `indirect_clamp.rs` and `.hlsl` and resolves the `bind.rs` conflict the way I did below, so this should hold for it too. The clamp builds and runs, but it does not prevent the device removal here: every run with it on still ended in `0x887a0006`, at 152 to 269 s. **Tested:** `main` `c4d37be` + #1798 + #1284 + this PR, release, merged locally. The only conflict was `execute_indirect` in `bind.rs`, where `main` now wraps the PC call in `fresh_indirect_arguments`; I kept that wrapper around both calls (bounded copy and original). RTX 4060 Ti 8 GB (32-lane waves, split wave64), driver 621.24, i5-14400F, 32 GB, Windows 11 Pro 26300, retail 1.0.2.1. `XCL_PSO_WAIT_MS=50` (so dispatches of pipelines still being built are skipped), A pressed at 115, 125 and 150 s, 600 s cap. | run | `XCL_LOOP_BUDGET` | clamp | device removed at | frames | |---|---|---|---|---:| | 1 | 256 | on | 264 s | 4,534 | | 2 | 256 | off (`XCL_INDIRECT_CLAMP=0`, same binary) | 206 s | 4,449 | | 3 | 256 | on | 152 s | 4,224 | | 4 | unset | on | 214 s | 4,405 | | 5 | unset | on | 236 s | 4,451 | | 6 | unset | on | 269 s | 4,446 | | 7 | unset | on, plus #1702 (`XCL_TEXTURE_PAGES_SYSTEM_MEMORY=1`) | 226 s | 4,462 | | 8 | as run 7, with #1323's markers also around draws | on | 225 s | 4,467 | Runs 3 to 8 also had #1323 (`XCL_GPU_CULPRIT=1`) and a local line that logs its markers at the device removal, not only at a watchdog release. Runs 5 to 8 skipped compute programs by hash (a local test switch, below). In runs 7 and 8 local video memory peaked at 4,433 and 4,846 MB, against 14,000 to 15,000 MB in the others, so on this card the removal does not come from oversubscribed video memory. - With the clamp on and off, the removal comes in the same phase, right after the world starts loading. One run per arm is not enough to say whether the clamp moves it. - In run 4 #1323 named one dispatch started and not done at the removal: cs `df837c748fdf56b8` (`CS_ScreenProbes_RadianceSpatialFilter`), 14,400 groups, a direct `Dispatch`, not an `ExecuteIndirect`. Its loop bounds come from memory. - In runs 3, 5, 6 and 7 #1323 found no dispatch in flight (0 of 8, 0 of 263, 0 of 275, 0 of 137 lists). Whatever ran too long there was not a compute dispatch, so a clamp on indirect dispatch arguments could not reach it. - For run 8 I put the same markers around `DrawInstanced`, `DrawIndexedInstanced` and graphics `ExecuteIndirect` too (local change). Still nothing in flight at the removal (0 of 236 lists). What is left are the paths without a marker: XCL's own copies and texture uploads, CPU-expanded rect lists, clears and resolves. - Run 5 skipped every dispatch of `df837c748fdf56b8`; runs 6 to 8 also skipped `45a2f1928c4e6f73` (`CS_AllocBatchCSCullOutput`) and `cd4c7be781d7d2df` (`CS_ComputeHitDetectionSkinnedResults`). Those two are the programs VIctory's NVIDIA testers skip with `VICTORY_SKIP_PIPELINES=eeed82b877b44b5f,b83629b90cd2b7bc`: VIctory names a shader by the first 16 hex digits of the BLAKE3 hash of the same bytes that XCL hashes with FNV-1a, and the two match these records. The device was still removed. - One more run with run 6's settings is not in the table: it ended at 180 s in an access violation in `gpu::tiling::Chain::detile_level` (`tiling.rs:438`, called from `title_textures::subresources`), reading title memory that was no longer mapped, before any skipped program had run. **Not tested:** more than one run with the clamp off. What was running at the removal in runs 3 and 5 to 8: `XCL_DRED=1` made the driver rebuild every pipeline from the start, so the title never got past its first minutes. AMD. **AI use:** Claude Code (Claude Opus 5.5) merged the build, ran the title, read the logs and wrote this comment.
Anon64 commented 2026-11-25 01:10:39 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Anon64 on 2026-11-25T00:18:36Z.


Regression run for this PR: head 201d67d, based on main 689f2db. RTX 3060 12 GB (581.80, wave32), Windows 11 26200, release, XCL_NETWORK=0, A pressed every 4 s from 20 s, scripts/smoke.ps1 on a retail title for 60 s, in one batch with the main run.

main 689f2db:

xcl-smoke v1
commit: 689f2db477c3c062cf162649781640ef8a977c18
gpu: NVIDIA GeForce RTX 3060
title: 21222967
seconds: 60
exit: 0x0
frames shown: 1590 (PresentX 1591)
presents per 2 s (last 3): 44 53 35
device removals: 0
crashes: 0
peak commit: 25217 MB

this PR:

xcl-smoke v1
commit: 201d67da8bee82a099c99fd78ba5626373d6f932
gpu: NVIDIA GeForce RTX 3060
title: 21222967
seconds: 60
exit: 0x0
frames shown: 1616 (PresentX 1617)
presents per 2 s (last 3): 60 40 54
device removals: 0
crashes: 0
peak commit: 23909 MB

No device removals or crashes; 101 % of main's frames, 94 % of its peak commit.

Not tested: the whole suite; whether the title reaches the changed code in these 60 s.

Written with Claude Code (Claude Opus 5.5) from runs on this machine.

<!-- greyfinch-sync:ivall/xcl:comment:7148374202 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7148374202). Originally posted by [Anon64](https://github.com/Anon64) on 2026-11-25T00:18:36Z. --- Regression run for this PR: head `201d67d`, based on `main` `689f2db`. RTX 3060 12 GB (581.80, wave32), Windows 11 26200, release, `XCL_NETWORK=0`, A pressed every 4 s from 20 s, `scripts/smoke.ps1` on a retail title for 60 s, in one batch with the `main` run. main `689f2db`: ``` xcl-smoke v1 commit: 689f2db477c3c062cf162649781640ef8a977c18 gpu: NVIDIA GeForce RTX 3060 title: 21222967 seconds: 60 exit: 0x0 frames shown: 1590 (PresentX 1591) presents per 2 s (last 3): 44 53 35 device removals: 0 crashes: 0 peak commit: 25217 MB ``` this PR: ``` xcl-smoke v1 commit: 201d67da8bee82a099c99fd78ba5626373d6f932 gpu: NVIDIA GeForce RTX 3060 title: 21222967 seconds: 60 exit: 0x0 frames shown: 1616 (PresentX 1617) presents per 2 s (last 3): 60 40 54 device removals: 0 crashes: 0 peak commit: 23909 MB ``` No device removals or crashes; 101 % of main's frames, 94 % of its peak commit. **Not tested:** the whole suite; whether the title reaches the changed code in these 60 s. Written with Claude Code (Claude Opus 5.5) from runs on this machine.
JJAutoCompare commented 2026-11-25 04:10:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by JJAutoCompare on 2026-11-25T03:20:42Z.


PR #1795 — ExecuteIndirect clamp on Intel Arc A770

Tested commit 201d67da8bee82a099c99fd78ba5626373d6f932 on STOR-WINLAB. Windows 11 Enterprise Evaluation build 26200.9974, Ryzen 7 3800X, Intel Arc A770 16 GiB with driver 32.0.101.9175, wave sizes 8–32, no double-precision float shader ops or D3D12 debug layers. Rust 1.100.0 and DXC/DXIL 1.9.2609.5.

Tested

  • cargo build --workspace and cargo test --workspace --no-run passed with debug info and incremental compilation disabled.
  • cargo test -p xcl --lib indirect_clamp::tests -- --nocapture passed all 4 tests. Three CPU tests checked signature parsing, signature replacement at a reused address, and shader config packing. The GPU test read back 2,000 indexed-draw records and verified per-record limits, preservation of other fields, and a total-work cutoff at record 1,383 (zero-based) across two shader chunks. It completed without skipping.
  • cargo test -p xcl --lib execute_indirect -- --nocapture passed all 3 existing binding tests, including a GPU check that ExecuteIndirect reads freshly written arguments. Both focused runs had 0 failed, 0 ignored, and 0 skip lines.
  • One Arc-locked cargo test --workspace --no-fail-fast -- --test-threads=4 run exited 1. Summing 20 libtest summaries gives 954 passed, 25 failed, 45 ignored. The log contains 22 SKIPPED lines representing coverage gaps within the reported passes. All 7 focused tests also passed in this run.

Failures and skips

  • 20 shader tests failed at CreateComputePipelineState with 0x80070057. Four shader output checks disagreed on fused FMA, mip sampling, FP16 upper-half preservation, and a pixel wave reduction. The test-title E2E reported a blue pixel where the dynamic depth-bias check expected green.
  • 17 skips were for unavailable wave64, 3 for unsupported per-lane FP16 arithmetic or conversion forms, 1 for unavailable heap windows, and 1 for inability to disable the driver cache.

Not tested

No main baseline or retail-title smoke run, sample-data coverage, or other GPU vendors. The clamp readback exercised indexed draws. GPU dispatch and mesh clamping and the full title-to-clamp path were outside that test.

AI use

T3 Code / Codex (gpt-6.2-sol, reasoningEffort: high) ran the build and verification. Coordinator #2 (T3 Code / Antigravity, gemini-4-neon) verified counts against pr1795-suite.log and published this report.

<!-- greyfinch-sync:ivall/xcl:comment:7151826302 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7151826302). Originally posted by [JJAutoCompare](https://github.com/JJAutoCompare) on 2026-11-25T03:20:42Z. --- # PR #1795 — ExecuteIndirect clamp on Intel Arc A770 Tested commit `201d67da8bee82a099c99fd78ba5626373d6f932` on STOR-WINLAB. Windows 11 Enterprise Evaluation build 26200.9974, Ryzen 7 3800X, Intel Arc A770 16 GiB with driver 32.0.101.9175, wave sizes 8–32, no double-precision float shader ops or D3D12 debug layers. Rust 1.100.0 and DXC/DXIL 1.9.2609.5. **Tested** - `cargo build --workspace` and `cargo test --workspace --no-run` passed with debug info and incremental compilation disabled. - `cargo test -p xcl --lib indirect_clamp::tests -- --nocapture` passed all 4 tests. Three CPU tests checked signature parsing, signature replacement at a reused address, and shader config packing. The GPU test read back 2,000 indexed-draw records and verified per-record limits, preservation of other fields, and a total-work cutoff at record 1,383 (zero-based) across two shader chunks. It completed without skipping. - `cargo test -p xcl --lib execute_indirect -- --nocapture` passed all 3 existing binding tests, including a GPU check that ExecuteIndirect reads freshly written arguments. Both focused runs had 0 failed, 0 ignored, and 0 skip lines. - One Arc-locked `cargo test --workspace --no-fail-fast -- --test-threads=4` run exited 1. Summing 20 libtest summaries gives **954 passed, 25 failed, 45 ignored**. The log contains **22 `SKIPPED` lines** representing coverage gaps within the reported passes. All 7 focused tests also passed in this run. **Failures and skips** - 20 shader tests failed at `CreateComputePipelineState` with `0x80070057`. Four shader output checks disagreed on fused FMA, mip sampling, FP16 upper-half preservation, and a pixel wave reduction. The test-title E2E reported a blue pixel where the dynamic depth-bias check expected green. - 17 skips were for unavailable wave64, 3 for unsupported per-lane FP16 arithmetic or conversion forms, 1 for unavailable heap windows, and 1 for inability to disable the driver cache. **Not tested** No main baseline or retail-title smoke run, sample-data coverage, or other GPU vendors. The clamp readback exercised indexed draws. GPU dispatch and mesh clamping and the full title-to-clamp path were outside that test. **AI use** T3 Code / Codex (`gpt-6.2-sol`, `reasoningEffort: high`) ran the build and verification. Coordinator #2 (T3 Code / Antigravity, `gemini-4-neon`) verified counts against `pr1795-suite.log` and published this report.
MacieGx commented 2026-11-25 12:06:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by MacieGx on 2026-11-25T11:49:31Z.


FYI, a lock-order note from running this PR in the newer retail title's world (#505) on an RTX 5080, on a tree based on an older main (689f2db) plus this PR, #1993 and others. On current main it should not happen any more, because 892177b ("a buffer's last release does not wait for the sparse state's lock") removed one half of it; I mention it because allocator_reset depends on that.

There, from a symbolised thread dump when every title thread had stopped:

  • sparse::readback_after_execute held the sparse STATE lock and reset an allocator → indirect_clamp::allocator_reset → waits for SCRATCH;
  • indirect_clamp::allocator_reset held SCRATCH and dropped the buffers over FREE_KEPT (s.free.truncate(FREE_KEPT)) → last Release → real::res_release → sparse::forget_buffer → waits for STATE.

If you want allocator_reset not to rely on what a buffer's Release does: split the extra buffers off inside the lock (let over = s.free.split_off(FREE_KEPT);) and drop them after it. That was 15 lines locally, and the scene then ran 90–100 s of world frames with no stop.

AI use: Claude Code (Claude Opus 5.5; a Claude Fable 5.2 subagent read the dump and wrote the local fix). I checked both call chains and that 892177b is in main.

<!-- greyfinch-sync:ivall/xcl:comment:7161547806 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7161547806). Originally posted by [MacieGx](https://github.com/MacieGx) on 2026-11-25T11:49:31Z. --- FYI, a lock-order note from running this PR in the newer retail title's world (#505) on an RTX 5080, on a tree based on an older `main` (689f2db) plus this PR, #1993 and others. On current `main` it should not happen any more, because 892177b ("a buffer's last release does not wait for the sparse state's lock") removed one half of it; I mention it because `allocator_reset` depends on that. There, from a symbolised thread dump when every title thread had stopped: - `sparse::readback_after_execute` held the sparse `STATE` lock and reset an allocator → `indirect_clamp::allocator_reset` → waits for `SCRATCH`; - `indirect_clamp::allocator_reset` held `SCRATCH` and dropped the buffers over `FREE_KEPT` (`s.free.truncate(FREE_KEPT)`) → last Release → `real::res_release` → `sparse::forget_buffer` → waits for `STATE`. If you want `allocator_reset` not to rely on what a buffer's Release does: split the extra buffers off inside the lock (`let over = s.free.split_off(FREE_KEPT);`) and drop them after it. That was 15 lines locally, and the scene then ran 90–100 s of world frames with no stop. AI use: Claude Code (Claude Opus 5.5; a Claude Fable 5.2 subagent read the dump and wrote the local fix). I checked both call chains and that 892177b is in `main`.
Royalflamejlh commented 2026-11-25 16:12:07 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-11-25T15:19:05Z.


Linux (Wine + vkd3d-proton) + NVIDIA, the title, 3 runs with #1795 and 3 without: in each run with it, the clamp bounded each of the first 256 ExecuteIndirect calls that reached it, and none of those 256 ran unbounded. The counter prints at the first 4 calls and then at powers of two; its last line was the 256th, so each run had 256 to 511 such calls, and those after the 256th were not seen one by one. The first bounded call came 0.9 to 1.8 s after the first #101 stub call. Presents stopped 1.4 to 2.3 s after the first #101 with #1795 and 0.6 to 2.4 s after it without. Neither tree had a fault, a device removal or a new kind of warning.

Setup: main f087b99 + #684 e56dbc3 + #1795 201d67d, merged locally, plus one local commit that logs what indirect_clamp::bound returns at its call in bind.rs (8f2b802). Against main f087b99 + #684, merged locally (2f6a4ae); all six runs within one hour. Measured on f087b99; at 201d67d, #1795 conflicts with main 06c9f55 in crates/xcl/src/hle/d3d12x/bind.rs. RTX 4070 12 GB (615.71.09), Fedora 44, Wine 11.21 Staging, vkd3d-proton v3.1-90-g30b0eb9b with the relaxed-vtable patch from #175 and a local dxil-spirv patch, release, Series X profile, 120 s. The first-run screens were completed once, with no story progress. A was pressed once the title presented steadily (16.0 to 18.3 s). XCL_PSO_PRELOAD=0, WINEDEBUG=err+all,fixme-all.

main + #684 (3 runs) #1795 (3 runs)
ExecuteIndirect calls with a translated pipeline, bounded / not (the count prints at powers of two) – 256 / 0 at the 256th call, the last line (256 to 511 calls per run)
first #101 75.7, 78.4, 86.1 s 78.7, 80.2, 83.5 s
first and 256th bounded call – 79.6–79.9, 81.1–81.3, 85.3–85.7 s
last 2 s with a present 76.3, 80.7, 88.3 s 80.1, 82.5, 85.5 s
ExecuteIndirect arguments run unbounded, ExecuteIndirect … skipped –, 0 0, 0
WARN lines 76, 77, 78 78, 78, 77
  • The counter sits at indirect_clamp::bound's call in bind.rs, so calls on PC pipelines and calls skipped before it are not in it. Each printed line was for a call with MaxCommandCount 1.
  • indirect_clamp and execute_indirect tests under Wine on the same card: 8 passed, 0 SKIPPED lines; gpu_records_are_clamped_and_budgeted ran on the card.
  • The runs give no count of records the shader changed, so whether the clamp cut down any record here was not seen.

Not tested: today's main 06c9f55 (the head conflicts with it); the GPU time of the copy pass; a run with a garbage record (the hang it prevents; neither tree hung here); the rest of the suite; Windows; AMD and Intel.

AI use: Claude Code (Claude Opus 5.5) read the change, wrote the counter, ran the title and the tests, and wrote this comment.

Posted without review by a person: the account owner was away and reads replies later.

<!-- greyfinch-sync:ivall/xcl:comment:7166651597 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7166651597). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-11-25T15:19:05Z. --- Linux (Wine + vkd3d-proton) + NVIDIA, the title, 3 runs with #1795 and 3 without: in each run with it, the clamp bounded each of the first 256 `ExecuteIndirect` calls that reached it, and none of those 256 ran unbounded. The counter prints at the first 4 calls and then at powers of two; its last line was the 256th, so each run had 256 to 511 such calls, and those after the 256th were not seen one by one. The first bounded call came 0.9 to 1.8 s after the first `#101` stub call. Presents stopped 1.4 to 2.3 s after the first `#101` with #1795 and 0.6 to 2.4 s after it without. Neither tree had a fault, a device removal or a new kind of warning. **Setup:** `main` `f087b99` + #684 `e56dbc3` + #1795 `201d67d`, merged locally, plus one local commit that logs what `indirect_clamp::bound` returns at its call in `bind.rs` (`8f2b802`). Against `main` `f087b99` + #684, merged locally (`2f6a4ae`); all six runs within one hour. Measured on `f087b99`; at `201d67d`, #1795 conflicts with `main` `06c9f55` in `crates/xcl/src/hle/d3d12x/bind.rs`. RTX 4070 12 GB (615.71.09), Fedora 44, Wine 11.21 Staging, vkd3d-proton v3.1-90-g30b0eb9b with the relaxed-vtable patch from #175 and a local dxil-spirv patch, release, Series X profile, 120 s. The first-run screens were completed once, with no story progress. A was pressed once the title presented steadily (16.0 to 18.3 s). `XCL_PSO_PRELOAD=0`, `WINEDEBUG=err+all,fixme-all`. | | `main` + #684 (3 runs) | #1795 (3 runs) | |---|---|---| | `ExecuteIndirect` calls with a translated pipeline, bounded / not (the count prints at powers of two) | – | 256 / 0 at the 256th call, the last line (256 to 511 calls per run) | | first `#101` | 75.7, 78.4, 86.1 s | 78.7, 80.2, 83.5 s | | first and 256th bounded call | – | 79.6–79.9, 81.1–81.3, 85.3–85.7 s | | last 2 s with a present | 76.3, 80.7, 88.3 s | 80.1, 82.5, 85.5 s | | `ExecuteIndirect arguments run unbounded`, `ExecuteIndirect … skipped` | –, 0 | 0, 0 | | `WARN` lines | 76, 77, 78 | 78, 78, 77 | - The counter sits at `indirect_clamp::bound`'s call in `bind.rs`, so calls on PC pipelines and calls skipped before it are not in it. Each printed line was for a call with `MaxCommandCount` 1. - `indirect_clamp` and `execute_indirect` tests under Wine on the same card: 8 passed, 0 `SKIPPED` lines; `gpu_records_are_clamped_and_budgeted` ran on the card. - The runs give no count of records the shader changed, so whether the clamp cut down any record here was not seen. **Not tested:** today's `main` `06c9f55` (the head conflicts with it); the GPU time of the copy pass; a run with a garbage record (the hang it prevents; neither tree hung here); the rest of the suite; Windows; AMD and Intel. **AI use:** Claude Code (Claude Opus 5.5) read the change, wrote the counter, ran the title and the tests, and wrote this comment. Posted without review by a person: the account owner was away and reads replies later.
jessenic commented 2026-11-25 22:06:38 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by jessenic on 2026-11-25T21:12:54Z.


A frame-rate cost of this PR on a retail title, and a fix: the scratch pool churns, under a lock every render thread takes. RTX 5070 Ti 16 GB (driver 610.88), Windows 11 26300, release. The PR is in a local integration tree (main 0829441 + about 40 open PRs). Newer retail title of #505, in the world.

What the stack dumps showed. cdb dumps were taken while the title logged nothing for over 6 s. In every one, 3–4 of the title's render threads were waiting on SCRATCH, in indirect_clamp::scratch / allocator_reset. The thread holding it was in one of two places:

  • CreateCommittedResource, waiting in D3D12Core!CDevice::MakeResident_Worker → PerNodePagingOperation::Wait. Video memory was over budget, so a new committed resource waits for paging.
  • allocator_reset → Vec::truncate → the resources' last Release. With late release, that can wait on fences.

Why it happens. A frame takes one scratch buffer per bounded ExecuteIndirect, and this title has hundreds. FREE_KEPT = 64, so every allocator reset released everything past 64, and the next frame made them again. Each make and each release ran inside the global SCRATCH lock.

The change (diff below, against this PR's indirect_clamp.rs):

  • Free buffers are kept by bytes, 256 MB by default (XCL_INDIRECT_SCRATCH_MB), not by count.
  • CreateCommittedResource and the releases happen outside the lock.
  • It logs how many buffers were made in all.

Measured. One run each, same switches, warm caches, frames counted from the world's first #101 + 60 s to the end of a 480 s run:

presents/s in the world longest gap with no activity line
this PR as is 0.28 23.4 s
with the change 0.68 4.0 s

With the change, the pool stopped growing at about 4,096 buffers (256 MB). No device removal, no crash.

diff
diff --git a/crates/xcl/src/hle/d3d12x/indirect_clamp.rs b/crates/xcl/src/hle/d3d12x/indirect_clamp.rs
index 93dec17..cdcc9e0 100644
--- a/crates/xcl/src/hle/d3d12x/indirect_clamp.rs
+++ b/crates/xcl/src/hle/d3d12x/indirect_clamp.rs
@@ -156,17 +156,28 @@ struct Scratch {
 }
 
 static SCRATCH: Mutex<Option<Scratch>> = Mutex::new(None);
-/// free buffers kept for reuse (the rest are released)
-const FREE_KEPT: usize = 64;
+/// Bytes of free buffers kept for reuse (the rest are released). A frame takes one buffer per
+/// bounded call, often hundreds; keeping too few made and released them again every frame, each
+/// make waiting on the device's paging queue and each release on XCL's late release. LOCAL
+fn free_kept_bytes() -> u64 {
+    static N: OnceLock<u64> = OnceLock::new();
+    *N.get_or_init(|| std::env::var("XCL_INDIRECT_SCRATCH_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256u64) << 20)
+}
+static MADE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+static MADE_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
 
 /// A buffer of at least `bytes` in UNORDERED_ACCESS, held for `allocator` until its reset.
 unsafe fn scratch(dev: &ID3D12Device, allocator: usize, bytes: u64) -> Option<ID3D12Resource> {
     let key = dev.as_raw() as usize;
-    let mut g = SCRATCH.lock().unwrap();
-    let s = g.get_or_insert_with(Default::default);
-    let reuse = s.free.iter().enumerate().filter(|(_, (d, n, _))| *d == key && *n >= bytes).min_by_key(|(_, (_, n, _))| *n).map(|(i, _)| i);
-    let entry = match reuse {
-        Some(i) => s.free.swap_remove(i),
+    let reused = {
+        let mut g = SCRATCH.lock().unwrap();
+        let s = g.get_or_insert_with(Default::default);
+        let reuse = s.free.iter().enumerate().filter(|(_, (d, n, _))| *d == key && *n >= bytes).min_by_key(|(_, (_, n, _))| *n).map(|(i, _)| i);
+        reuse.map(|i| s.free.swap_remove(i))
+    };
+    // made outside the lock: CreateCommittedResource can wait on the paging queue for seconds
+    let entry = match reused {
+        Some(e) => e,
         None => {
             let size = bytes.next_power_of_two().max(64 << 10);
             let mut out: Option<ID3D12Resource> = None;
@@ -189,26 +200,43 @@ unsafe fn scratch(dev: &ID3D12Device, allocator: usize, bytes: u64) -> Option<ID
                 &mut out,
             )
             .ok()?;
+            let n = MADE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
+            let b = MADE_BYTES.fetch_add(size, std::sync::atomic::Ordering::Relaxed) + size;
+            if n.is_power_of_two() || n.is_multiple_of(1024) {
+                crate::xlog_info!("D3D12.X: ExecuteIndirect bounding: {n} scratch buffers made ({} MB in all)", b >> 20);
+            }
             (key, size, out?)
         }
     };
     let r = entry.2.clone();
-    s.held.entry(allocator).or_default().push(entry);
+    SCRATCH.lock().unwrap().get_or_insert_with(Default::default).held.entry(allocator).or_default().push(entry);
     Some(r)
 }
 
 /// The GPU is done with what lists recorded from `allocator` (reset or released): its copies
 /// can be reused.
 pub(super) fn allocator_reset(allocator: usize) {
-    let mut g = SCRATCH.lock().unwrap();
-    let Some(s) = g.as_mut() else { return };
-    if let Some(done) = s.held.remove(&allocator) {
+    let dropped = {
+        let mut g = SCRATCH.lock().unwrap();
+        let Some(s) = g.as_mut() else { return };
+        let Some(done) = s.held.remove(&allocator) else { return };
         s.free.extend(done);
-        if s.free.len() > FREE_KEPT {
-            s.free.sort_by_key(|e| std::cmp::Reverse(e.1));
-            s.free.truncate(FREE_KEPT);
+        let mut total: u64 = s.free.iter().map(|e| e.1).sum();
+        let kept = free_kept_bytes();
+        let mut dropped = Vec::new();
+        if total > kept {
+            // the largest go first; small ones are the common case
+            s.free.sort_by_key(|e| e.1);
+            while total > kept {
+                let Some(e) = s.free.pop() else { break };
+                total -= e.1;
+                dropped.push(e);
+            }
         }
-    }
+        dropped
+    };
+    // released outside the lock: a release runs XCL's late release, which can wait on fences
+    drop(dropped);
 }
 
 /// Where `bytes` at console offset `offset` of console buffer `res` are on the GPU: the GPU

Not tested: AMD; other titles; a scripts/smoke.ps1 run; more than one run each. The 256 MB default is a guess: a title with bigger records may want more or less.

AI use: Claude Code (Claude Opus 5.5) found this in the stack dumps, wrote the change, ran the runs and wrote this comment.

<!-- greyfinch-sync:ivall/xcl:comment:7174766648 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7174766648). Originally posted by [jessenic](https://github.com/jessenic) on 2026-11-25T21:12:54Z. --- **A frame-rate cost of this PR on a retail title, and a fix: the scratch pool churns, under a lock every render thread takes.** RTX 5070 Ti 16 GB (driver 610.88), Windows 11 26300, release. The PR is in a local integration tree (`main` `0829441` + about 40 open PRs). Newer retail title of #505, in the world. **What the stack dumps showed.** cdb dumps were taken while the title logged nothing for over 6 s. In every one, 3–4 of the title's render threads were waiting on `SCRATCH`, in `indirect_clamp::scratch` / `allocator_reset`. The thread holding it was in one of two places: - `CreateCommittedResource`, waiting in `D3D12Core!CDevice::MakeResident_Worker` → `PerNodePagingOperation::Wait`. Video memory was over budget, so a new committed resource waits for paging. - `allocator_reset` → `Vec::truncate` → the resources' last `Release`. With late release, that can wait on fences. **Why it happens.** A frame takes one scratch buffer per bounded `ExecuteIndirect`, and this title has hundreds. `FREE_KEPT = 64`, so every allocator reset released everything past 64, and the next frame made them again. Each make and each release ran inside the global `SCRATCH` lock. **The change** (diff below, against this PR's `indirect_clamp.rs`): - Free buffers are kept by bytes, 256 MB by default (`XCL_INDIRECT_SCRATCH_MB`), not by count. - `CreateCommittedResource` and the releases happen outside the lock. - It logs how many buffers were made in all. **Measured.** One run each, same switches, warm caches, frames counted from the world's first `#101` + 60 s to the end of a 480 s run: | | presents/s in the world | longest gap with no activity line | |---|---|---| | this PR as is | 0.28 | 23.4 s | | with the change | 0.68 | 4.0 s | With the change, the pool stopped growing at about 4,096 buffers (256 MB). No device removal, no crash. <details><summary>diff</summary> ```diff diff --git a/crates/xcl/src/hle/d3d12x/indirect_clamp.rs b/crates/xcl/src/hle/d3d12x/indirect_clamp.rs index 93dec17..cdcc9e0 100644 --- a/crates/xcl/src/hle/d3d12x/indirect_clamp.rs +++ b/crates/xcl/src/hle/d3d12x/indirect_clamp.rs @@ -156,17 +156,28 @@ struct Scratch { } static SCRATCH: Mutex<Option<Scratch>> = Mutex::new(None); -/// free buffers kept for reuse (the rest are released) -const FREE_KEPT: usize = 64; +/// Bytes of free buffers kept for reuse (the rest are released). A frame takes one buffer per +/// bounded call, often hundreds; keeping too few made and released them again every frame, each +/// make waiting on the device's paging queue and each release on XCL's late release. LOCAL +fn free_kept_bytes() -> u64 { + static N: OnceLock<u64> = OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_INDIRECT_SCRATCH_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256u64) << 20) +} +static MADE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static MADE_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// A buffer of at least `bytes` in UNORDERED_ACCESS, held for `allocator` until its reset. unsafe fn scratch(dev: &ID3D12Device, allocator: usize, bytes: u64) -> Option<ID3D12Resource> { let key = dev.as_raw() as usize; - let mut g = SCRATCH.lock().unwrap(); - let s = g.get_or_insert_with(Default::default); - let reuse = s.free.iter().enumerate().filter(|(_, (d, n, _))| *d == key && *n >= bytes).min_by_key(|(_, (_, n, _))| *n).map(|(i, _)| i); - let entry = match reuse { - Some(i) => s.free.swap_remove(i), + let reused = { + let mut g = SCRATCH.lock().unwrap(); + let s = g.get_or_insert_with(Default::default); + let reuse = s.free.iter().enumerate().filter(|(_, (d, n, _))| *d == key && *n >= bytes).min_by_key(|(_, (_, n, _))| *n).map(|(i, _)| i); + reuse.map(|i| s.free.swap_remove(i)) + }; + // made outside the lock: CreateCommittedResource can wait on the paging queue for seconds + let entry = match reused { + Some(e) => e, None => { let size = bytes.next_power_of_two().max(64 << 10); let mut out: Option<ID3D12Resource> = None; @@ -189,26 +200,43 @@ unsafe fn scratch(dev: &ID3D12Device, allocator: usize, bytes: u64) -> Option<ID &mut out, ) .ok()?; + let n = MADE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let b = MADE_BYTES.fetch_add(size, std::sync::atomic::Ordering::Relaxed) + size; + if n.is_power_of_two() || n.is_multiple_of(1024) { + crate::xlog_info!("D3D12.X: ExecuteIndirect bounding: {n} scratch buffers made ({} MB in all)", b >> 20); + } (key, size, out?) } }; let r = entry.2.clone(); - s.held.entry(allocator).or_default().push(entry); + SCRATCH.lock().unwrap().get_or_insert_with(Default::default).held.entry(allocator).or_default().push(entry); Some(r) } /// The GPU is done with what lists recorded from `allocator` (reset or released): its copies /// can be reused. pub(super) fn allocator_reset(allocator: usize) { - let mut g = SCRATCH.lock().unwrap(); - let Some(s) = g.as_mut() else { return }; - if let Some(done) = s.held.remove(&allocator) { + let dropped = { + let mut g = SCRATCH.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + let Some(done) = s.held.remove(&allocator) else { return }; s.free.extend(done); - if s.free.len() > FREE_KEPT { - s.free.sort_by_key(|e| std::cmp::Reverse(e.1)); - s.free.truncate(FREE_KEPT); + let mut total: u64 = s.free.iter().map(|e| e.1).sum(); + let kept = free_kept_bytes(); + let mut dropped = Vec::new(); + if total > kept { + // the largest go first; small ones are the common case + s.free.sort_by_key(|e| e.1); + while total > kept { + let Some(e) = s.free.pop() else { break }; + total -= e.1; + dropped.push(e); + } } - } + dropped + }; + // released outside the lock: a release runs XCL's late release, which can wait on fences + drop(dropped); } /// Where `bytes` at console offset `offset` of console buffer `res` are on the GPU: the GPU ``` </details> **Not tested:** AMD; other titles; a `scripts/smoke.ps1` run; more than one run each. The 256 MB default is a guess: a title with bigger records may want more or less. **AI use:** Claude Code (Claude Opus 5.5) found this in the stack dumps, wrote the change, ran the runs and wrote this comment.
DavidM1911 commented 2026-11-26 01:05:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by DavidM1911 on 2026-11-26T00:34:56Z.


Re-verification on RTX 3060 Ti (Windows 11): still a merge conflict with current main on the new head — needs another rebase before it can be tested.

<!-- greyfinch-sync:ivall/xcl:comment:7178904881 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7178904881). Originally posted by [DavidM1911](https://github.com/DavidM1911) on 2026-11-26T00:34:56Z. --- Re-verification on RTX 3060 Ti (Windows 11): still a **merge conflict with current `main`** on the new head — needs another rebase before it can be tested.
MacieGx commented 2026-11-26 13:05:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by MacieGx on 2026-11-26T12:36:20Z.


Two points on this PR (head 201d67d), from reading indirect_clamp.hlsl at that head and from runs of the newer retail title (#505) on a lab tree that carries this PR. The first is measured, the second is arithmetic from the shader and not measured.

1. A legitimate dispatch record wider than 65,535 groups loses the rest of its work.

clamp_args cuts every dimension to MAX_GROUPS_DIM (65,535). The newer retail title's indirect diffuse final gather (indirect_diffuse_lighting:CS_FinalGather_0_1_1_0, record hash 9c1e6716e59ecf21) dispatches a 1-D pixel list: in our runs every call asked for 114,624 to 115,200 groups in x (115,200 = 2560 x 1440 / 32), with y = z = 1. With this PR it gets 65,535, so about 43 % of the list is never gathered. Measured on an RTX 5080 (driver 621.24) by reading back the title's own records and the bounded copies of the same calls: 14 of 14 sampled calls of that program asked for [115200, 1, 1]; the bounded copies of earlier runs had [65535, 1, 1]. No other program of the 188 sampled asked for more than 65,535 in a dimension.

main passes such a record to the PC unchanged. That is outside D3D12's limit, so it is not a fix either, and I have not measured what NVIDIA or AMD do with it on main. But with this PR the cut becomes silent and certain. Suggestions, either of which would do for this PR:

  • count and log the records the clamp cuts (first few, then powers of two, like the other warnings), so the loss shows up in a log; and/or
  • leave records whose only fault is a dimension over 65,535 (y = z = 1, x under MAX_GROUPS) for a follow-up that runs them as rows. We tried that in a lab build: the program's group id is folded (x + y * row) by the translator and the clamp writes [row, ceil(x / row), 1]. It needs the translator to know the row width, so it is not a change for this PR.

2. One oversized record empties every record after it in the same call.

The budget is a prefix sum over the records, and every record whose running total is over BUDGET (2^29 threads) is emptied, including all records after the one that crossed it. The per-record limits allow a single record to take almost the whole budget:

  • dispatch: a garbage record clamps to [65535, 64, 1] = 4,194,240 groups x 64 = 268,431,360 threads. Two such records leave 8,192 threads (128 groups) for every later record of the call;
  • mesh dispatch: one garbage record = 4,194,240 x 128 = 536,862,720 threads, again leaving 8,192 threads (64 mesh groups) for the rest;
  • draw: a record is limited to 2^26 vertex instances, so eight garbage records use the whole budget and every draw after them is emptied.

So the records that are cut are the legitimate ones that come after the garbage, not the garbage itself (which keeps its clamped, still very large, work). Which records hold garbage depends on what ran before, so this could show up as geometry or passes that are there in one run and missing in another. I have not measured how often it happens in a title. Suggestions:

  • empty a record that is over a per-record limit (it is garbage, not a big legitimate call) and give it no share of the budget; or
  • apply the budget per record rather than across the call;
  • and a counter the clamp writes next to its copy (records emptied by the budget), read back in a test, so this can be measured.

AI use: Claude Code (Claude Opus 5.5) wrote this from our lab's notes and runs; the arithmetic in point 2 was checked against the shader at 201d67d, and the person posting it checked both points.

<!-- greyfinch-sync:ivall/xcl:comment:7192218935 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7192218935). Originally posted by [MacieGx](https://github.com/MacieGx) on 2026-11-26T12:36:20Z. --- Two points on this PR (head `201d67d`), from reading `indirect_clamp.hlsl` at that head and from runs of the newer retail title (#505) on a lab tree that carries this PR. The first is measured, the second is arithmetic from the shader and not measured. **1. A legitimate dispatch record wider than 65,535 groups loses the rest of its work.** `clamp_args` cuts every dimension to `MAX_GROUPS_DIM` (65,535). The newer retail title's indirect diffuse final gather (`indirect_diffuse_lighting:CS_FinalGather_0_1_1_0`, record hash `9c1e6716e59ecf21`) dispatches a 1-D pixel list: in our runs every call asked for 114,624 to 115,200 groups in x (115,200 = 2560 x 1440 / 32), with y = z = 1. With this PR it gets 65,535, so about 43 % of the list is never gathered. Measured on an RTX 5080 (driver 621.24) by reading back the title's own records and the bounded copies of the same calls: 14 of 14 sampled calls of that program asked for `[115200, 1, 1]`; the bounded copies of earlier runs had `[65535, 1, 1]`. No other program of the 188 sampled asked for more than 65,535 in a dimension. `main` passes such a record to the PC unchanged. That is outside D3D12's limit, so it is not a fix either, and I have not measured what NVIDIA or AMD do with it on `main`. But with this PR the cut becomes silent and certain. Suggestions, either of which would do for this PR: - count and log the records the clamp cuts (first few, then powers of two, like the other warnings), so the loss shows up in a log; and/or - leave records whose only fault is a dimension over 65,535 (y = z = 1, x under `MAX_GROUPS`) for a follow-up that runs them as rows. We tried that in a lab build: the program's group id is folded (x + y * row) by the translator and the clamp writes `[row, ceil(x / row), 1]`. It needs the translator to know the row width, so it is not a change for this PR. **2. One oversized record empties every record after it in the same call.** The budget is a prefix sum over the records, and every record whose running total is over `BUDGET` (2^29 threads) is emptied, including all records after the one that crossed it. The per-record limits allow a single record to take almost the whole budget: - dispatch: a garbage record clamps to `[65535, 64, 1]` = 4,194,240 groups x 64 = 268,431,360 threads. Two such records leave 8,192 threads (128 groups) for every later record of the call; - mesh dispatch: one garbage record = 4,194,240 x 128 = 536,862,720 threads, again leaving 8,192 threads (64 mesh groups) for the rest; - draw: a record is limited to 2^26 vertex instances, so eight garbage records use the whole budget and every draw after them is emptied. So the records that are cut are the legitimate ones that come after the garbage, not the garbage itself (which keeps its clamped, still very large, work). Which records hold garbage depends on what ran before, so this could show up as geometry or passes that are there in one run and missing in another. I have not measured how often it happens in a title. Suggestions: - empty a record that is over a per-record limit (it is garbage, not a big legitimate call) and give it no share of the budget; or - apply the budget per record rather than across the call; - and a counter the clamp writes next to its copy (records emptied by the budget), read back in a test, so this can be measured. AI use: Claude Code (Claude Opus 5.5) wrote this from our lab's notes and runs; the arithmetic in point 2 was checked against the shader at `201d67d`, and the person posting it checked both points.
jessenic commented 2026-11-26 16:06:17 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by jessenic on 2026-11-26T15:30:27Z.


A measurement for @MacieGx's second point (one oversized record takes the call's budget). It points to the per-record and per-call limits as a GPU-hang source on NVIDIA.

Setup: RTX 5070 Ti 16 GB (driver 610.88), 32 GB RAM, Windows 11 26300, release. My integration tree carries this PR's clamp, unchanged at the head I ported from (MAX_GROUPS 2^22, BUDGET 2^29). Newer retail title, Series S profile, warm caches.

  • With those limits, every warm 420–900 s run of the last day ended in a TDR (0x887a0006), seven runs in all. They hung 22–378 s into the world, after 66, 222, 307, 313, 565, 584 and 602 presents. The runs differed in other local changes, and the hang came with and without them.
  • With two lines of indirect_clamp.hlsl changed, MAX_GROUPS to 2^18 and BUDGET to 2^26, two 900 s runs had no removal. They got 1,344 and 1,576 presents into the world, at 1.84 and 2.19 presents/s. The second run also had #2798/#2799/#2801 and #2753.
  • This is two runs per arm on one card, so read it as a direction. I have not confirmed which record or program hangs: XCL_DRED=1 froze those runs on the CPU before they reached the hang.

My reading is that a garbage record clamped to [65535, 64, 1] groups (4.2 M groups, 268 M threads), on a heavy program, runs past the 2 s TDR limit on its own. Your suggestion to empty a record that is over a per-record limit, instead of clamping it, would remove that case without lowering the limits for legitimate calls. The largest legitimate call either of us has seen is the final gather's 115,200 groups, which 2^18 still allows.

AI use: Claude Code (Claude Opus 5.5) ran the runs and wrote this comment.

<!-- greyfinch-sync:ivall/xcl:comment:7196363114 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7196363114). Originally posted by [jessenic](https://github.com/jessenic) on 2026-11-26T15:30:27Z. --- A measurement for @MacieGx's second point (one oversized record takes the call's budget). It points to the per-record and per-call limits as a GPU-hang source on NVIDIA. **Setup:** RTX 5070 Ti 16 GB (driver 610.88), 32 GB RAM, Windows 11 26300, release. My integration tree carries this PR's clamp, unchanged at the head I ported from (`MAX_GROUPS` 2^22, `BUDGET` 2^29). Newer retail title, Series S profile, warm caches. - With those limits, every warm 420–900 s run of the last day ended in a TDR (`0x887a0006`), seven runs in all. They hung 22–378 s into the world, after 66, 222, 307, 313, 565, 584 and 602 presents. The runs differed in other local changes, and the hang came with and without them. - With two lines of `indirect_clamp.hlsl` changed, `MAX_GROUPS` to 2^18 and `BUDGET` to 2^26, two 900 s runs had no removal. They got 1,344 and 1,576 presents into the world, at 1.84 and 2.19 presents/s. The second run also had #2798/#2799/#2801 and #2753. - This is two runs per arm on one card, so read it as a direction. I have not confirmed which record or program hangs: `XCL_DRED=1` froze those runs on the CPU before they reached the hang. My reading is that a garbage record clamped to `[65535, 64, 1]` groups (4.2 M groups, 268 M threads), on a heavy program, runs past the 2 s TDR limit on its own. Your suggestion to empty a record that is over a per-record limit, instead of clamping it, would remove that case without lowering the limits for legitimate calls. The largest legitimate call either of us has seen is the final gather's 115,200 groups, which 2^18 still allows. AI use: Claude Code (Claude Opus 5.5) ran the runs and wrote this comment.
Foniass commented 2026-12-01 06:48:55 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T06:48:55Z.


Triage (#1607) – head 201d67d

Update (rechecked against main 6bfb5c51): withdrawn from the close list; recommendation: keep open. Main's indirect_guard bounds only ExecuteIndirect calls with MaxCommandCount 1 and no count buffer (indirect_guard.rs:324-326); this PR bounds multi-record, count-buffer and DispatchMesh calls. Not superseded; judge it on the problems reported in this thread.

Main already has this protection in hle/d3d12x/indirect_guard.rs (commits 16826cb6 and 38774461, merged through #2572). Before an ExecuteIndirect, a compute pass of XCL's own reads the draw and dispatch arguments, zeros counts that are out of range (MAX_VERTICES / MAX_INSTANCES, XCL_INDIRECT_MAX_GROUPS), and passes the PC call a buffer of its own. It has the XCL_INDIRECT_GUARD switch, and bind.rs already calls indirect_guard::check. This PR's indirect_clamp module is a second pass for the same job: it clamps where main zeros, and it adds a per-call budget. It conflicts with execute_indirect on main. If clamping or a per-call budget is wanted, it would be a change to indirect_guard.
Recommendation: close (superseded by main commits 16826cb / 3877446).

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run.

<!-- greyfinch-sync:ivall/xcl:comment:7303310063 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#issuecomment-7303310063). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T06:48:55Z. --- **Triage (#1607)** – head 201d67d **Update (rechecked against main 6bfb5c51): withdrawn from the close list; recommendation: keep open.** Main's `indirect_guard` bounds only ExecuteIndirect calls with MaxCommandCount 1 and no count buffer (`indirect_guard.rs:324-326`); this PR bounds multi-record, count-buffer and DispatchMesh calls. Not superseded; judge it on the problems reported in this thread. Main already has this protection in `hle/d3d12x/indirect_guard.rs` (commits 16826cb6 and 38774461, merged through #2572). Before an ExecuteIndirect, a compute pass of XCL's own reads the draw and dispatch arguments, zeros counts that are out of range (MAX_VERTICES / MAX_INSTANCES, `XCL_INDIRECT_MAX_GROUPS`), and passes the PC call a buffer of its own. It has the `XCL_INDIRECT_GUARD` switch, and `bind.rs` already calls `indirect_guard::check`. This PR's `indirect_clamp` module is a second pass for the same job: it clamps where main zeros, and it adds a per-call budget. It conflicts with `execute_indirect` on main. If clamping or a per-call budget is wanted, it would be a change to `indirect_guard`. ~~Recommendation: close (superseded by main commits 16826cb / 3877446).~~ AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run.
gut0to commented 2026-12-02 22:14:14 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by gut0to on 2026-12-02T22:14:14Z.

Review: COMMENTED


AI-assisted review: GPT-6 helped inspect this cache lifecycle; I checked its call sites and current teardown paths.

<!-- greyfinch-sync:ivall/xcl:review:6159974842 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#pullrequestreview-6159974842). Originally posted by [gut0to](https://github.com/gut0to) on 2026-12-02T22:14:14Z. **Review:** COMMENTED --- AI-assisted review: GPT-6 helped inspect this cache lifecycle; I checked its call sites and current teardown paths.
gut0to commented 2026-12-02 22:14:15 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by gut0to on 2026-12-02T22:14:15Z.

Code review location: crates/xcl/src/hle/d3d12x/indirect_clamp.rs; line 99

@@ -0,0 +1,455 @@
+//! ExecuteIndirect's arguments, bounded on the GPU before the PC reads them.
+//!
+//! A title's own compute passes write most indirect arguments. A pass XCL skips (its pipeline
+//! still being built, or untranslated) or translates wrongly leaves whatever the memory held,
+//! and a draw of four billion vertices or a dispatch past the PC's limits runs until Windows
+//! resets the display driver (0x887a0006). So, before an ExecuteIndirect with a translated
+//! pipeline, a compute shader of ours (`indirect_clamp.hlsl`) copies the call's records into a
+//! buffer of ours, clamps each record's draw or dispatch arguments, and empties the records past
+//! a budget for the whole call; the PC call then reads that copy. The idea is VIctory's
+//! (github.com/Marvisak/VIctory, `victory-gpu/src/indirect.rs`); this is XCL's own code.
+//!
+//! Only signatures without root arguments are bounded (those with them are skipped on
+//! translated pipelines anyway), and only records in console buffers in unified memory; any
+//! other call runs as before. `XCL_INDIRECT_CLAMP=0` turns it off.
+//!
+//! The limits (`indirect_clamp.hlsl`) are estimates, not measurements: 2^24 vertices per
+//! instance, 2^26 vertex instances and 2^22 groups (65,535 per dimension) per record, 2^29
+//! vertex instances or threads per call. A title that really needs more loses that work.
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::mem::ManuallyDrop;
+use std::sync::{Arc, Mutex, OnceLock};
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+
+use super::real;
+
+/// Bytes of records one call may copy (larger calls run unbounded).
+const MAX_BYTES: u64 = 16 << 20;
+const CONFIG_WORDS: u32 = 6;
+const NO_COUNT: u32 = u32::MAX;
+
+pub(super) fn enabled() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| !std::env::var("XCL_INDIRECT_CLAMP").is_ok_and(|v| v.trim() == "0"))
+}
+
+/// A command signature whose records can be bounded: bytes per record, where its draw or
+/// dispatch arguments start in one, and their kind (0 draw, 1 indexed draw, 2 dispatch,
+/// 3 mesh dispatch).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct Signature {
+    stride: u32,
+    action_at: u32,
+    kind: u32,
+}
+
+static SIGNATURES: Mutex<Option<HashMap<usize, Signature>>> = Mutex::new(None);
+
+impl Signature {
+    /// From the PC argument list (`[type, …]` per argument, the action last): None for a
+    /// signature that sets root arguments or whose action is not a draw or dispatch.
+    fn parse(stride: u32, args: &[[u32; 4]]) -> Option<Self> {
+        let ([action, ..], before) = args.split_last()?;
+        let (kind, action_bytes) = match D3D12_INDIRECT_ARGUMENT_TYPE(*action as i32) {
+            D3D12_INDIRECT_ARGUMENT_TYPE_DRAW => (0, 16),
+            D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED => (1, 20),
+            D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH => (2, 12),
+            D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH => (3, 12),
+            _ => return None,
+        };
+        let mut at = 0u32;
+        for &[ty, ..] in before {
+            at += match D3D12_INDIRECT_ARGUMENT_TYPE(ty as i32) {
+                // D3D12_VERTEX_BUFFER_VIEW, D3D12_INDEX_BUFFER_VIEW
+                D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW | D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW => 16,
+                _ => return None,
+            };
+        }
+        if stride == 0 || !stride.is_multiple_of(4) || at + action_bytes > stride {
+            return None;
+        }
+        Some(Self { stride, action_at: at, kind })
+    }
+}
+
+/// Note a command signature the title created (its PC argument list); one that cannot be
+/// bounded is forgotten, so a new signature at a released one's address is never mistaken for it.
+pub(super) fn note_signature(sig: usize, stride: u32, args: &[[u32; 4]]) {
+    let mut g = SIGNATURES.lock().unwrap();
+    let map = g.get_or_insert_with(HashMap::new);
+    match Signature::parse(stride, args) {
+        Some(s) => map.insert(sig, s),
+        None => map.remove(&sig),
+    };
+}
+
+fn signature(sig: usize) -> Option<Signature> {
+    SIGNATURES.lock().unwrap().as_ref()?.get(&sig).copied()
+}
+
+struct Clamper {
+    root: ID3D12RootSignature,
+    pso: ID3D12PipelineState,
+}
+
+/// per device; None: it could not be made (logged once, not tried again)
+static CLAMPERS: Mutex<Option<HashMap<usize, Option<Arc<Clamper>>>>> = Mutex::new(None);

Low: CLAMPERS is process-wide and stores strong ID3D12RootSignature / ID3D12PipelineState references for each raw device pointer, but I found no removal path when a device is released. Recreating the D3D12 device therefore leaves each old clamp pair alive for the process lifetime. Could this entry be removed during device teardown, or owned by a cache with the device's lifetime, with a device-recreation test? AI-assisted review: GPT-6 helped inspect the cache lifecycle; I checked the call sites and cleanup paths.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776850477 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/1795#discussion_r4776850477). Originally posted by [gut0to](https://github.com/gut0to) on 2026-12-02T22:14:15Z. **Code review location:** `crates/xcl/src/hle/d3d12x/indirect_clamp.rs`; line 99 ~~~~diff @@ -0,0 +1,455 @@ +//! ExecuteIndirect's arguments, bounded on the GPU before the PC reads them. +//! +//! A title's own compute passes write most indirect arguments. A pass XCL skips (its pipeline +//! still being built, or untranslated) or translates wrongly leaves whatever the memory held, +//! and a draw of four billion vertices or a dispatch past the PC's limits runs until Windows +//! resets the display driver (0x887a0006). So, before an ExecuteIndirect with a translated +//! pipeline, a compute shader of ours (`indirect_clamp.hlsl`) copies the call's records into a +//! buffer of ours, clamps each record's draw or dispatch arguments, and empties the records past +//! a budget for the whole call; the PC call then reads that copy. The idea is VIctory's +//! (github.com/Marvisak/VIctory, `victory-gpu/src/indirect.rs`); this is XCL's own code. +//! +//! Only signatures without root arguments are bounded (those with them are skipped on +//! translated pipelines anyway), and only records in console buffers in unified memory; any +//! other call runs as before. `XCL_INDIRECT_CLAMP=0` turns it off. +//! +//! The limits (`indirect_clamp.hlsl`) are estimates, not measurements: 2^24 vertices per +//! instance, 2^26 vertex instances and 2^22 groups (65,535 per dimension) per record, 2^29 +//! vertex instances or threads per call. A title that really needs more loses that work. +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use super::real; + +/// Bytes of records one call may copy (larger calls run unbounded). +const MAX_BYTES: u64 = 16 << 20; +const CONFIG_WORDS: u32 = 6; +const NO_COUNT: u32 = u32::MAX; + +pub(super) fn enabled() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_INDIRECT_CLAMP").is_ok_and(|v| v.trim() == "0")) +} + +/// A command signature whose records can be bounded: bytes per record, where its draw or +/// dispatch arguments start in one, and their kind (0 draw, 1 indexed draw, 2 dispatch, +/// 3 mesh dispatch). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Signature { + stride: u32, + action_at: u32, + kind: u32, +} + +static SIGNATURES: Mutex<Option<HashMap<usize, Signature>>> = Mutex::new(None); + +impl Signature { + /// From the PC argument list (`[type, …]` per argument, the action last): None for a + /// signature that sets root arguments or whose action is not a draw or dispatch. + fn parse(stride: u32, args: &[[u32; 4]]) -> Option<Self> { + let ([action, ..], before) = args.split_last()?; + let (kind, action_bytes) = match D3D12_INDIRECT_ARGUMENT_TYPE(*action as i32) { + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW => (0, 16), + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED => (1, 20), + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH => (2, 12), + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH => (3, 12), + _ => return None, + }; + let mut at = 0u32; + for &[ty, ..] in before { + at += match D3D12_INDIRECT_ARGUMENT_TYPE(ty as i32) { + // D3D12_VERTEX_BUFFER_VIEW, D3D12_INDEX_BUFFER_VIEW + D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW | D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW => 16, + _ => return None, + }; + } + if stride == 0 || !stride.is_multiple_of(4) || at + action_bytes > stride { + return None; + } + Some(Self { stride, action_at: at, kind }) + } +} + +/// Note a command signature the title created (its PC argument list); one that cannot be +/// bounded is forgotten, so a new signature at a released one's address is never mistaken for it. +pub(super) fn note_signature(sig: usize, stride: u32, args: &[[u32; 4]]) { + let mut g = SIGNATURES.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + match Signature::parse(stride, args) { + Some(s) => map.insert(sig, s), + None => map.remove(&sig), + }; +} + +fn signature(sig: usize) -> Option<Signature> { + SIGNATURES.lock().unwrap().as_ref()?.get(&sig).copied() +} + +struct Clamper { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +/// per device; None: it could not be made (logged once, not tried again) +static CLAMPERS: Mutex<Option<HashMap<usize, Option<Arc<Clamper>>>>> = Mutex::new(None); ~~~~ --- **Low**: `CLAMPERS` is process-wide and stores strong `ID3D12RootSignature` / `ID3D12PipelineState` references for each raw device pointer, but I found no removal path when a device is released. Recreating the D3D12 device therefore leaves each old clamp pair alive for the process lifetime. Could this entry be removed during device teardown, or owned by a cache with the device's lifetime, with a device-recreation test? AI-assisted review: GPT-6 helped inspect the cache lifecycle; I checked the call sites and cleanup paths.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/1795:upstream-pr/1795'
git switch 'upstream-pr/1795'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/1795'
git switch 'upstream-pr/1795'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/1795'
git switch 'upstream-pr/1795'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/1795'
git switch 'main'
git merge --squash 'upstream-pr/1795'
git switch 'main'
git merge --ff-only 'upstream-pr/1795'
git switch 'main'
git merge 'upstream-pr/1795'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!1785
No description provided.