Memory windows from the descriptor heap (no per-access switch); NVIDIA OOM fallback; physical-page fixes #187

Closed
github-bot wants to merge 6 commits from gh-pr/187/head into gh-pr/187/base
Owner

@⁠RemingtonWilcox on GitHub · 2026-11-23 19:34 UTC · original
memory-windows-redesign → main · +1348 −25 · 14 files · 6 commits · closed without merging

What the PR is now:

  1. Memory windows from the shared descriptor heap: ResourceDescriptorHeap[NonUniformResourceIndex(MEM_HEAP_BASE + w)] instead of the per-access switch over root UAVs. XCL_HEAP_WINDOWS=0 turns it off. The raw views are 2^30 − 1 dwords, so a sparse window's last 64 KiB tile is reachable; only the window's last dword is not.
  2. SetDescriptorHeaps(0, NULL) clears the record, so the shared heap is bound again before the next translated draw.
  3. NVIDIA E_OUTOFMEMORY fallback (from the retail numbers in #156): when the driver refuses a pipeline built with heap windows with 0x8007000E, the program is translated again in the switch form and built from that, before the stand-in. Tested by injecting the refusal through the PSO hook, then dispatching and checking the output.
  4. Physical pages on your design: FreeTitlePhysicalPages keeps AWAY held while it releases homes (plain homes are MEM_RELEASEd, so a concurrent map/read/write could touch released memory), and a page freed from a block that lives on gives its lazy home back at once. Tests included.

Full suite green on an RTX 3090 (driver 616.92). Not run against a retail title after the rebase.

Earlier versions of this PR also moved physical-page homes out of GPU address space; that part is dropped in favour of main's 38b05b7 design (see the comment thread).

🤖 Generated with Claude Code

**@⁠RemingtonWilcox** on GitHub · 2026-11-23 19:34 UTC · [original](https://github.com/xcl-dev/xcl/pull/187) `memory-windows-redesign` → `main` · +1348 −25 · 14 files · 6 commits · closed without merging **What the PR is now:** 1. **Memory windows from the shared descriptor heap**: `ResourceDescriptorHeap[NonUniformResourceIndex(MEM_HEAP_BASE + w)]` instead of the per-access `switch` over root UAVs. `XCL_HEAP_WINDOWS=0` turns it off. The raw views are 2^30 − 1 dwords, so a sparse window's last 64 KiB tile is reachable; only the window's last dword is not. 2. **`SetDescriptorHeaps(0, NULL)`** clears the record, so the shared heap is bound again before the next translated draw. 3. **NVIDIA E_OUTOFMEMORY fallback** (from the retail numbers in #156): when the driver refuses a pipeline built with heap windows with `0x8007000E`, the program is translated again in the switch form and built from that, before the stand-in. Tested by injecting the refusal through the PSO hook, then dispatching and checking the output. 4. **Physical pages on your design:** `FreeTitlePhysicalPages` keeps `AWAY` held while it releases homes (plain homes are `MEM_RELEASE`d, so a concurrent map/read/write could touch released memory), and a page freed from a block that lives on gives its lazy home back at once. Tests included. Full suite green on an RTX 3090 (driver 616.92). Not run against a retail title after the rebase. Earlier versions of this PR also moved physical-page homes out of GPU address space; that part is dropped in favour of main's 38b05b7 design (see the comment thread). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
With more than one memory window every access in a translated shader was inlined once per
window (a switch over the root UAVs mem, mem1..). Now window k is a raw UAV at MEM_HEAP_BASE + k
of the shared shader-visible heap, and each access is one ResourceDescriptorHeap load/store.

- Options::heap_windows / HEAP_WINDOWS flag in the windows count (so the translation and DXIL
  cache keys differ); on unless XCL_HEAP_WINDOWS=0 or the views could not be made.
- console_heap: the first 4 descriptors of the shared heap are the windows' raw views
  (4 GiB - 64 KiB at most: a 4 GiB raw view does not fit a 32-bit byte size).
- Lists bind the shared heap before an ABI dispatch / draw when they set none.
- xcl shaders --precompile uses the same key.
- Experiments (aperture_tests.rs), RTX 3090:
  E1: one structured view over a 16 GiB reserved buffer wraps at 4 GiB (root UAV and heap
  view) - a single aperture binding is not possible on NVIDIA.
  E1b (debug layer): a 4 GiB - 64 KiB raw view and a 1 GiB raw view at FirstElement 5 GiB
  both work, no debug-layer messages.
  E2 (ignored, run alone): a 19 601-instruction CS, DXC 12.1 s with one window, 150.7 s with
  the 4-window switch, 12.5 s with heap windows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- runner::dispatch_on: a PSO built by the backend hook uses the runtime's window count, so
  with heap windows its accesses go through the descriptor heap; every window slot is now a
  raw view of the test's memory (gpu_compute_e2e read zeros through LDS).
- draw_indexed_x test: the fake list gets SetDescriptorHeaps (#28), which bind now calls when
  the list set no heap (it called a null slot).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The window views stopped at 4 GiB - 64 KiB on the assumption that a window's last tile is never
handed out. Sparse windows do hand it out (sparse_reserve / sparse_alloc; a reservation across
two windows always covers it), and through the view it read zeros and dropped stores.

The view is now 2^30 - 1 dwords, the largest byte size a 32-bit field holds (AMD's V#
NUM_RECORDS): only the window's last dword stays out of reach. E1c (RTX 3090, debug layer):
4 GiB - 64 KiB view 0/64 lanes at the last tile; 2^30 - 1 dwords 64/64 there and 63/64 at the
last 256 bytes; exactly 2^30 dwords 64/64 too, no debug-layer messages (AMD not measured).
gpu_raw_window_view_reaches_its_top now checks the last tile and its last dwords.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Unbinding every heap left the list's record of bound heaps as it was, so ensure_view_heap saw a
heap and did not bind the shared one: the next translated draw or dispatch read the memory
windows (ResourceDescriptorHeap[0..3]) with no heap bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
NVIDIA 616.92 (RTX 5070 Ti, reported in #156) refuses some big programs whose
descriptor-heap index depends on the memory window with E_OUTOFMEMORY, and builds
the same programs in the switch form. A translated compute, graphics, mesh or GS
pipeline whose driver call fails that way with heap windows is now translated again
in the switch form (other cache keys; same root signature and binds) and built from
that before the stand-in or the error path.

Test: heap_window_out_of_memory_falls_back_to_the_switch_form injects the refusals
through the CreateComputePipelineState hook, then dispatches the rebuilt pipeline
and checks every thread's output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
FreeTitlePhysicalPages dropped AWAY before it released a block's home; with plain-memory
homes (MEM_RELEASE) a map, read or write of those pages on another thread could reach
memory released under it. AWAY now stays held across the PHYS_BLOCKS section (the order
AWAY -> PHYS_BLOCKS, as in the map calls). A page freed while its block lives on gives
its lazy home (sparse window or plain memory) back at once instead of when the whole
block goes. unmap_away looks the page's home up once.

Tests: a_freed_page_gives_its_home_back, physical_pages_from_several_threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:14:21 +00:00
github-bot closed this pull request 2026-11-26 04:14:21 +00:00
Author
Owner

@⁠TheHoracio on GitHub · 2026-11-23 19:39 UTC · original

AMD run of the two tests you asked about. This is not the RX 9070: it is RDNA3 Radeon RX 7800 XT (16 GB, native 64-lane waves, amdxc64), driver 32.0.32015.7029, Windows 11 Pro 10.0.26300, Rust 1.100.0 x86_64-pc-windows-msvc, DXC 1.9.2602.17, debug build, PR head 8c0346d. cargo test -p xcl --lib:

Run Result
plain 540 passed, 1 failed, 21 ignored
XCL_SPLIT_WAVE64=1 541 passed, 0 failed, 21 ignored
XCL_HEAP_WINDOWS=0 (gpu:: tests) 258 passed, 1 failed, 20 ignored
  • gpu_memory_windows_from_the_heap and gpu_raw_window_view_reaches_its_top pass in all three runs, natively at 64 lanes and split. No driver crash, no TDR or device removal.
  • The one failure is gpu_wave64_ps_whole_wave_reductions. It fails the same way on main 956a476 on RDNA2/RDNA3 and is fixed by #155. It is unrelated to this PR.
  • I did not run a retail pack or any title.
**@⁠TheHoracio** on GitHub · 2026-11-23 19:39 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7111913830) AMD run of the two tests you asked about. This is not the RX 9070: it is **RDNA3 Radeon RX 7800 XT** (16 GB, native 64-lane waves, `amdxc64`), driver 32.0.32015.7029, Windows 11 Pro 10.0.26300, Rust 1.100.0 `x86_64-pc-windows-msvc`, DXC 1.9.2602.17, debug build, PR head `8c0346d`. `cargo test -p xcl --lib`: | Run | Result | |---|---| | plain | 540 passed, 1 failed, 21 ignored | | `XCL_SPLIT_WAVE64=1` | 541 passed, 0 failed, 21 ignored | | `XCL_HEAP_WINDOWS=0` (`gpu::` tests) | 258 passed, 1 failed, 20 ignored | - `gpu_memory_windows_from_the_heap` and `gpu_raw_window_view_reaches_its_top` pass in all three runs, natively at 64 lanes and split. No driver crash, no TDR or device removal. - The one failure is `gpu_wave64_ps_whole_wave_reductions`. It fails the same way on `main` 956a476 on RDNA2/RDNA3 and is fixed by #155. It is unrelated to this PR. - I did not run a retail pack or any title.
Author
Owner

@⁠MiguelMachado-dev on GitHub · 2026-11-23 20:00 UTC · original

I tested 8c0346d on a GeForce RTX 5080 (driver 32.0.16.2124), Core i7-14700KF, Windows 11 Pro build 26300, Rust 1.97.1 MSVC, DXC 1.8.2502.11 (Windows SDK 10.0.26100.0), debug profile.

  • gpu_memory_windows_above_4_gib, gpu_memory_windows_from_the_heap, and gpu_raw_window_view_reaches_its_top all passed.
  • cargo test --locked -p xcl --lib -- --test-threads=4 reported 541 passes, 0 failures and 21 ignored. Two GPU tests reported SKIPPED for requiring hardware wave64 and are included in the pass count. The optional game sample variables were unset.
  • e2_window_compile_time with XCL_E2_BLOCKS=250 and XCL_E2_REPS=3 used a synthetic compute shader of about 7,000 instructions. Median DXC time was 2.55 s with one window, 21.56 s with four windows using the switch, and 2.78 s with four windows from the descriptor heap. The DXC samples for the two four-window paths were [18.49, 21.56, 25.08] s and [2.70, 2.78, 2.78] s, respectively.

The measurements cover the synthetic cases on this setup. AI-assisted with Codex.

**@⁠MiguelMachado-dev** on GitHub · 2026-11-23 20:00 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7112432194) I tested `8c0346d` on a GeForce RTX 5080 (driver 32.0.16.2124), Core i7-14700KF, Windows 11 Pro build 26300, Rust 1.97.1 MSVC, DXC 1.8.2502.11 (Windows SDK 10.0.26100.0), debug profile. - `gpu_memory_windows_above_4_gib`, `gpu_memory_windows_from_the_heap`, and `gpu_raw_window_view_reaches_its_top` all passed. - `cargo test --locked -p xcl --lib -- --test-threads=4` reported 541 passes, 0 failures and 21 ignored. Two GPU tests reported `SKIPPED` for requiring hardware wave64 and are included in the pass count. The optional game sample variables were unset. - `e2_window_compile_time` with `XCL_E2_BLOCKS=250` and `XCL_E2_REPS=3` used a synthetic compute shader of about 7,000 instructions. Median DXC time was 2.55 s with one window, 21.56 s with four windows using the switch, and 2.78 s with four windows from the descriptor heap. The DXC samples for the two four-window paths were [18.49, 21.56, 25.08] s and [2.70, 2.78, 2.78] s, respectively. The measurements cover the synthetic cases on this setup. AI-assisted with Codex.
Author
Owner

@⁠gw1337x on GitHub · 2026-11-23 20:19 UTC · original

Setup: AMD Radeon RX 7800 XT (RDNA3, 16 GB), driver 32.0.32015.7029, 32 GB RAM, Windows 11 Pro 26200, GTA VI retail, XCL_NETWORK=0, release build.
Test branch: main 956a476 + #170 (incl. #163 @ 634c423) + #162 @ 641f551 + #168 @ 070a737 + xg.rs of #169 + #176 + #164.

Tested 8c0346d merged onto the branch above (clean merge, release build), two runs: cold and warm cache. Both runs: 0 presents, no DXC compiles, private commit flat at 18 GB from ~1 s on, then the game's watchdog at 31.5 s (+0x2215c35, write at 0).

The thread dump shows a game thread inside XCL for those 30 s:

game … → xcl::hle::kernelx::XMemMapPhysicalPagesScatter → map_pages → unmap_away
       → hle::d3d12x::sparse::decommitted → Vec::retain<(usize, usize)>

It looks like page mapping became quadratic: a retain over a list for every page mapped. Also logged at 0.4 s:

mem: reservation of 24576 MB (flags 0x20402000) at 0x20b9c200000 is outside the GPU's windows – shaders read zeros there (24576 MB so far)

Without #187 the same branch presents from ~3 s. Debug info: release build with line-tables-only.

🤖 Generated with Claude Code

**@⁠gw1337x** on GitHub · 2026-11-23 20:19 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7112910212) **Setup:** AMD Radeon RX 7800 XT (RDNA3, 16 GB), driver 32.0.32015.7029, 32 GB RAM, Windows 11 Pro 26200, GTA VI retail, `XCL_NETWORK=0`, release build. Test branch: `main` 956a476 + #170 (incl. #163 @ 634c423) + #162 @ 641f551 + #168 @ 070a737 + `xg.rs` of #169 + #176 + #164. Tested 8c0346d merged onto the branch above (clean merge, release build), two runs: cold and warm cache. Both runs: **0 presents**, no DXC compiles, private commit flat at 18 GB from ~1 s on, then the game's watchdog at 31.5 s (`+0x2215c35`, write at 0). The thread dump shows a game thread inside XCL for those 30 s: ``` game … → xcl::hle::kernelx::XMemMapPhysicalPagesScatter → map_pages → unmap_away → hle::d3d12x::sparse::decommitted → Vec::retain<(usize, usize)> ``` It looks like page mapping became quadratic: a `retain` over a list for every page mapped. Also logged at 0.4 s: ``` mem: reservation of 24576 MB (flags 0x20402000) at 0x20b9c200000 is outside the GPU's windows – shaders read zeros there (24576 MB so far) ``` Without #187 the same branch presents from ~3 s. Debug info: release build with `line-tables-only`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Author
Owner

@⁠mastrr9 on GitHub · 2026-11-23 20:27 UTC · original

Independent Windows + RTX 5080 GPU verification of 8c0346da2 (merge-base 956a476bf) on NVIDIA GeForce RTX 5080 (Blackwell desktop, driver 617.42, D3D12 SM 6.6 + mesh shaders, 32-wide waves, Windows 11, Ryzen 7 9800X3D, Rust 1.100.0, DXC 1.9.2602.17, no XCL_SAMPLE_*, no game files):

Build & Tests

  • cargo build --workspace && cargo test --workspace -- --test-threads=4: 574 passed, 0 failed, 41 ignored (git diff --check clean; 2 expected no wave64 skips).
  • All 6 new GPU & unit tests passed on RTX 5080: gpu_memory_windows_from_the_heap, gpu_aperture_structured_rows_above_4_gib, gpu_raw_window_view_reaches_its_top, gpu_aperture_probe_where_it_wraps, a_6_gib_reservation_fits_once_page_homes_take_no_window_space, and physical_pages_have_cpu_homes_and_map_into_the_windows.

Code review note (edge case)

  • shared_heap slot reservation (0..MAX_WINDOWS), set_window_views fallback to window 0, and emit.rs clamping (xcl_w < windows ? xcl_w : 0u) before ResourceDescriptorHeap[NonUniformResourceIndex(...)] all look solid.
  • Edge case in list_x.rs::ensure_view_heap() / console_list.rs: ensure_view_heap() checks if b.heaps.is_empty() (and console_list.rs sets heaps_set = true). If a command list calls SetDescriptorHeaps(1, &[sampler_heap]) with only a sampler heap (no CBV/SRV/UAV heap), heaps is non-empty, so global_heap() won't be bound—leaving ResourceDescriptorHeap[MEM_HEAP_BASE + w] unbound on draw/dispatch. Tracking whether a CBV/SRV/UAV heap is bound (rather than heaps.is_empty()) would close that case cleanly.

(AI-assisted)

**@⁠mastrr9** on GitHub · 2026-11-23 20:27 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7113099314) Independent Windows + RTX 5080 GPU verification of `8c0346da2` (merge-base `956a476bf`) on **NVIDIA GeForce RTX 5080** (Blackwell desktop, driver `617.42`, D3D12 SM 6.6 + mesh shaders, 32-wide waves, Windows 11, Ryzen 7 9800X3D, Rust `1.100.0`, DXC `1.9.2602.17`, no `XCL_SAMPLE_*`, no game files): ### Build & Tests - `cargo build --workspace && cargo test --workspace -- --test-threads=4`: **574 passed, 0 failed, 41 ignored** (`git diff --check` clean; 2 expected `no wave64` skips). - All 6 new GPU & unit tests passed on RTX 5080: `gpu_memory_windows_from_the_heap`, `gpu_aperture_structured_rows_above_4_gib`, `gpu_raw_window_view_reaches_its_top`, `gpu_aperture_probe_where_it_wraps`, `a_6_gib_reservation_fits_once_page_homes_take_no_window_space`, and `physical_pages_have_cpu_homes_and_map_into_the_windows`. ### Code review note (edge case) - `shared_heap` slot reservation (`0..MAX_WINDOWS`), `set_window_views` fallback to window 0, and `emit.rs` clamping (`xcl_w < windows ? xcl_w : 0u`) before `ResourceDescriptorHeap[NonUniformResourceIndex(...)]` all look solid. - **Edge case in `list_x.rs::ensure_view_heap()` / `console_list.rs`:** `ensure_view_heap()` checks `if b.heaps.is_empty()` (and `console_list.rs` sets `heaps_set = true`). If a command list calls `SetDescriptorHeaps(1, &[sampler_heap])` with **only a sampler heap** (no CBV/SRV/UAV heap), `heaps` is non-empty, so `global_heap()` won't be bound—leaving `ResourceDescriptorHeap[MEM_HEAP_BASE + w]` unbound on draw/dispatch. Tracking whether a CBV/SRV/UAV heap is bound (rather than `heaps.is_empty()`) would close that case cleanly. *(AI-assisted)*
Author
Owner

@⁠Kalmarv on GitHub · 2026-11-23 20:29 UTC · original

AI-assisted review (Claude Code). Windows 11 (10.0.26200), Ryzen 9 9950X, RTX 5070 Ti (NVIDIA 610.74), Rust 1.99.0 MSVC, debug profile. Synthetic memory only, no game files.

Tested 8c0346d (3 commits directly on main 956a476, so the PR head is the merge result).

GPU (5070 Ti): gpu_memory_windows_from_the_heap, gpu_memory_windows_above_4_gib and gpu_raw_window_view_reaches_its_top pass (no skips). I did not run the full suite; the 5080 runs above cover that.

Negative control for the homes change. I carried the behavioural assertions of physical_pages_have_cpu_homes_and_map_into_the_windows onto main, keeping only the lines that compile there (no AUTO_MAPPED / PhysPages fields):

  • main: fails a home takes no GPU address space. The home is 0x420010000, inside UMA, and MapTitlePhysicalPages(NULL, 3, …) returns the home itself.
  • this PR: passes. The home is outside UMA, and the same call returns a sparse-window range.

On gw1337x's 30 s stall (unmap_away → sparse::decommitted → Vec::retain). This cost is in sparse.rs and predates this PR. The PR only routes the retail reservation onto it.

Before the sparse state exists (no device yet):

  • sparse::committed appends one (addr, len) per mapped page to EARLY;
  • sparse::decommitted does EARLY.retain(..), a scan of the whole list, once per page moved away.

So remapping N pages that sit in a sparse range costs O(N²).

To show this I used a CPU-only probe (no D3D12 device). It allocates N pages, maps them consecutively, remaps them in reverse order with XMemMapPhysicalPagesScatter, then unmaps them. It runs the same calls into a plain VirtualAlloc reservation and into a sparse_reserve range. The kernelx code is identical for both targets, so the difference between them is only committed/decommitted. One run each, in ms:

pages side scatter, plain scatter, sparse unmap, plain unmap, sparse sparse − plain (unmap)
2,048 main 469 530 51 84 34
4,096 main 1,587 1,829 91 244 152
8,192 main 4,405 5,235 199 896 697
16,384 main 9,157 11,782 394 2,893 2,500
2,048 PR 380 434 42 60 18
4,096 PR 1,414 1,528 86 165 79
8,192 PR 3,478 3,949 151 476 325
16,384 PR 7,036 8,705 294 1,539 1,246
  • The sparse-only part grows about 3.5–4× per doubling on both sides, so it is quadratic. The PR is faster than main in every row.
  • On main the retail title's reservation was plain Windows memory, so it never took this path. With this PR it lands in the sparse windows. At about 100,000 pages, a quadratic term that is already 1.2–2.5 s at 16k would plausibly take tens of seconds, past the 30 s watchdog. That is an estimate, not measured.
  • This matches the stack in the report. I can't tell from here whether the retail device already existed at that point. If it did, the to_zero.retain in decommit_tiles is the other Vec<(usize, usize)>::retain to look at.
  • A possible fix: keep EARLY keyed by address (a BTreeMap of ranges, merging neighbours), so decommitted before the device is O(log n), not O(n).

Also seen, but not attributed: the reverse remap is slow on plain memory as well, on both sides (16k pages: 7–9 s). One candidate is unmap_away's away.gone.retain(|&h| Some(h) != page_home(page)), which calls page_home (a lock and a BTreeMap lookup) for each of up to 4,096 entries per page. I haven't measured that.

Not tested: the retail title, the full suite on this GPU, AMD, Wine, and the timing with a D3D12 device present (sparse state set up).

I'll open a separate small PR that keys EARLY by address so the pre-device decommitted is O(log n), with this probe as its test, unless someone is already on it.

**@⁠Kalmarv** on GitHub · 2026-11-23 20:29 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7113138761) AI-assisted review (Claude Code). Windows 11 (10.0.26200), Ryzen 9 9950X, RTX 5070 Ti (NVIDIA 610.74), Rust 1.99.0 MSVC, debug profile. Synthetic memory only, no game files. Tested `8c0346d` (3 commits directly on `main` `956a476`, so the PR head is the merge result). **GPU (5070 Ti):** `gpu_memory_windows_from_the_heap`, `gpu_memory_windows_above_4_gib` and `gpu_raw_window_view_reaches_its_top` pass (no skips). I did not run the full suite; the 5080 runs above cover that. **Negative control for the homes change.** I carried the behavioural assertions of `physical_pages_have_cpu_homes_and_map_into_the_windows` onto `main`, keeping only the lines that compile there (no `AUTO_MAPPED` / `PhysPages` fields): - `main`: fails `a home takes no GPU address space`. The home is `0x420010000`, inside UMA, and `MapTitlePhysicalPages(NULL, 3, …)` returns the home itself. - this PR: passes. The home is outside UMA, and the same call returns a sparse-window range. **On gw1337x's 30 s stall (`unmap_away → sparse::decommitted → Vec::retain`).** This cost is in `sparse.rs` and predates this PR. The PR only routes the retail reservation onto it. Before the sparse state exists (no device yet): - `sparse::committed` appends one `(addr, len)` per mapped page to `EARLY`; - `sparse::decommitted` does `EARLY.retain(..)`, a scan of the whole list, once per page moved away. So remapping N pages that sit in a sparse range costs O(N²). To show this I used a CPU-only probe (no D3D12 device). It allocates N pages, maps them consecutively, remaps them in reverse order with `XMemMapPhysicalPagesScatter`, then unmaps them. It runs the same calls into a plain `VirtualAlloc` reservation and into a `sparse_reserve` range. The kernelx code is identical for both targets, so the difference between them is only `committed`/`decommitted`. One run each, in ms: | pages | side | scatter, plain | scatter, sparse | unmap, plain | unmap, sparse | sparse − plain (unmap) | |---:|---|---:|---:|---:|---:|---:| | 2,048 | main | 469 | 530 | 51 | 84 | 34 | | 4,096 | main | 1,587 | 1,829 | 91 | 244 | 152 | | 8,192 | main | 4,405 | 5,235 | 199 | 896 | 697 | | 16,384 | main | 9,157 | 11,782 | 394 | 2,893 | 2,500 | | 2,048 | PR | 380 | 434 | 42 | 60 | 18 | | 4,096 | PR | 1,414 | 1,528 | 86 | 165 | 79 | | 8,192 | PR | 3,478 | 3,949 | 151 | 476 | 325 | | 16,384 | PR | 7,036 | 8,705 | 294 | 1,539 | 1,246 | - The sparse-only part grows about 3.5–4× per doubling on both sides, so it is quadratic. The PR is faster than `main` in every row. - On `main` the retail title's reservation was plain Windows memory, so it never took this path. With this PR it lands in the sparse windows. At about 100,000 pages, a quadratic term that is already 1.2–2.5 s at 16k would plausibly take tens of seconds, past the 30 s watchdog. That is an estimate, not measured. - This matches the stack in the report. I can't tell from here whether the retail device already existed at that point. If it did, the `to_zero.retain` in `decommit_tiles` is the other `Vec<(usize, usize)>::retain` to look at. - A possible fix: keep `EARLY` keyed by address (a `BTreeMap` of ranges, merging neighbours), so `decommitted` before the device is O(log n), not O(n). Also seen, but not attributed: the reverse remap is slow on plain memory as well, on both sides (16k pages: 7–9 s). One candidate is `unmap_away`'s `away.gone.retain(|&h| Some(h) != page_home(page))`, which calls `page_home` (a lock and a `BTreeMap` lookup) for each of up to 4,096 entries per page. I haven't measured that. Not tested: the retail title, the full suite on this GPU, AMD, Wine, and the timing with a D3D12 device present (sparse state set up). I'll open a separate small PR that keys `EARLY` by address so the pre-device `decommitted` is O(log n), with this probe as its test, unless someone is already on it.
Author
Owner

@⁠srcamarda on GitHub · 2026-11-23 20:54 UTC · original

Found the cause of the stall @⁠gw1337x reported (game thread stuck in XMemMapPhysicalPagesScatter → … → sparse::decommitted → Vec::retain). Reproduced on RDNA3: RX 7800 XT, driver 32.0.32029.2010, Windows 11 26300, PR head 8c0346d, release build, retail title with XCL_NETWORK=0, XCL_RUN_SECONDS=60, cold shader cache:

build first frame presents in 60 s end
8c0346d never 0 title's watchdog at 32 s (+0x2215c35, write at 0)
8c0346d + the patch below 9.75 s 2 (cold cache, as on main) XCL_RUN_SECONDS, exit 0

At the watchdog, the thread dump has a title thread running in XCL. Symbolized with the build's PDB: Vec<(usize, usize)>::retain in sparse::decommit_tiles ← sparse::decommitted ← kernelx::XMemMapPhysicalPagesScatter.

Two quadratic pieces, both needed

  1. to_zero.retain at every tile unmap. The scatter mapping's pattern is: unmap a page (a whole 64 KiB tile goes, so retain runs over all of to_zero), then map one (a reused tile queues a whole-tile clear). to_zero only drains at the next before_execute, so it grows by one entry per page, and every unmap walks all of it.
  2. FxHasher::finish returns k * C unchanged. Keys of mapped are tile addresses (multiples of 64 KiB), so the low 16 bits of every hash are zero. hashbrown takes the bucket from the low bits, so past 64 K entries every lookup walks one long probe chain. That includes the mapped.contains_key inside the retain closure, and the mapped lookups on the submit path (before_execute).

Synthetic measurement, 100 000 map / unmap steps (many_tile_unmaps_stay_linear, debug build):

  • per-tile list, old hasher: 34.8 s
  • old retain, fixed hasher: 84 s
  • both fixed: 0.16 s

The patch (sparse.rs only)

  • ZeroList: to_zero kept per tile. Unmapping a tile drops its entries in O(1) (forget_tile). This is exactly what the retain removed: only decommit_tiles removes tiles from mapped, and every entry is pushed for a tile that is mapped at that point. The drains get the same ranges, sorted by address (the order doesn't matter to the clears).
  • FxHasher::finish → rotate_left(26), as rustc-hash 2 does.
  • EARLY (commits before the device exists) had the same shape: a push per commit and a retain per decommit. It is now a set of disjoint ranges (RangeSet, merges on insert, cuts on remove). One behaviour change: decommitting a page out of a larger early commit now keeps the rest of that commit. Before, the whole entry was dropped, so those pages were never mapped once the device came up. Not hit in this run (the stall was the to_zero one); happy to drop this part if you'd rather keep the PR minimal.
  • Tests: many_tile_unmaps_stay_linear, early_commits_stay_linear, range_set_merges_and_cuts; decommit_sub_tile_reclaims_pool_tile_when_all_pages_become_holes adapted to ZeroList.

cargo test -p xcl --lib: 543 passed, 1 failed (gpu_wave64_ps_whole_wave_reductions, the 32-lane PS case on RDNA2/3, fixed by #155). Patch below.

Not checked: the rendered image (the run only got as far as cold-cache loading), NVIDIA, and a warm-cache run.

Patch against 8c0346d (git apply)
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index ff20199..79a828b 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -73,14 +73,109 @@ impl Hasher for FxHasher {
     fn write_u64(&mut self, i: u64) {
         self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x517C_C1B7_2722_0A95);
     }
+    /// The product's well-mixed high bits moved down (as rustc-hash 2 does): the table takes the
+    /// bucket from the low bits, and keys that are tile / page addresses (multiples of 64 KiB)
+    /// would leave the low 16 bits of `k * C` zero – past 64 K entries every lookup walked one
+    /// long probe chain.
     #[inline]
     fn finish(&self) -> u64 {
-        self.0
+        self.0.rotate_left(26)
     }
 }
 
 type FxHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>;
 
+/// Ranges to clear on the GPU before the next upload, kept per 64 KiB tile: every entry
+/// belongs to a tile that was mapped when it was added, and unmapping a tile drops its
+/// entries in O(1) (`forget_tile`). A plain list pruned with `retain` at every unmap was
+/// quadratic: a title mapping physical pages one by one (each unmap a whole tile, each map
+/// a reused, to-be-cleared tile) spent seconds per GB there.
+#[derive(Default, Debug)]
+struct ZeroList {
+    by_tile: FxHashMap<usize, Vec<(usize, usize)>>,
+}
+
+impl ZeroList {
+    fn push(&mut self, a: usize, n: usize) {
+        self.by_tile.entry(a & !(TILE - 1)).or_default().push((a, n));
+    }
+    fn forget_tile(&mut self, t: usize) {
+        self.by_tile.remove(&t);
+    }
+    #[cfg(test)]
+    fn is_empty(&self) -> bool {
+        self.by_tile.is_empty()
+    }
+    /// every range, sorted by address (the order does not matter to the clears)
+    fn entries(&self) -> Vec<(usize, usize)> {
+        let mut v: Vec<(usize, usize)> = self.by_tile.values().flatten().copied().collect();
+        v.sort_unstable();
+        v
+    }
+    fn take(&mut self) -> Vec<(usize, usize)> {
+        let v = self.entries();
+        self.by_tile.clear();
+        v
+    }
+}
+
+/// Disjoint, sorted address ranges `start → end` (commits before the device existed): adding
+/// merges with neighbours, removing cuts only what it covers – both O(log n + ranges touched).
+#[derive(Default, Debug)]
+struct RangeSet {
+    map: std::collections::BTreeMap<usize, usize>,
+}
+
+impl RangeSet {
+    const fn new() -> Self {
+        Self { map: std::collections::BTreeMap::new() }
+    }
+    fn insert(&mut self, a: usize, n: usize) {
+        if n == 0 {
+            return;
+        }
+        let (mut s, mut e) = (a, a.saturating_add(n));
+        // a range starting at or before `s` that reaches it
+        if let Some((&ps, &pe)) = self.map.range(..=s).next_back() {
+            if pe >= s {
+                s = ps;
+                e = e.max(pe);
+            }
+        }
+        // ranges starting inside [s, e]
+        while let Some((&ns, &ne)) = self.map.range(s..=e).next() {
+            self.map.remove(&ns);
+            e = e.max(ne);
+        }
+        self.map.insert(s, e);
+    }
+    fn remove(&mut self, a: usize, n: usize) {
+        if n == 0 {
+            return;
+        }
+        let end = a.saturating_add(n);
+        // a range starting before `a` that reaches into [a, end)
+        if let Some((&ps, &pe)) = self.map.range(..a).next_back() {
+            if pe > a {
+                self.map.insert(ps, a);
+                if pe > end {
+                    self.map.insert(end, pe);
+                }
+            }
+        }
+        // ranges starting inside [a, end)
+        while let Some((&ns, &ne)) = self.map.range(a..end).next() {
+            self.map.remove(&ns);
+            if ne > end {
+                self.map.insert(end, ne);
+            }
+        }
+    }
+    fn take(&mut self) -> Vec<(usize, usize)> {
+        std::mem::take(&mut self.map).into_iter().map(|(s, e)| (s, e - s)).collect()
+    }
+}
+
 struct TileEntry {
     pool: (u32, u32),
     /// bit `i` set => 4 KiB page `i` of this 64 KiB tile is uncommitted (a hole)
@@ -133,7 +228,7 @@ fn decommit_tiles(
     mapped: &mut FxHashMap<usize, TileEntry>,
     pinned: &FxHashMap<(u32, u32), u32>,
     free: &mut Vec<(u32, u32)>,
-    to_zero: &mut Vec<(usize, usize)>,
+    to_zero: &mut ZeroList,
     a: usize,
     n: usize,
 ) -> Vec<usize> {
@@ -164,7 +259,7 @@ fn decommit_tiles(
             } else if newly_holed != 0 {
                 for idx in 0..PAGES_PER_TILE {
                     if newly_holed & (1u16 << idx) != 0 {
-                        to_zero.push((t + idx * PAGE, PAGE));
+                        to_zero.push(t + idx * PAGE, PAGE);
                     }
                 }
             }
@@ -180,9 +275,7 @@ fn decommit_tiles(
                 free.push(entry.pool);
             }
         }
-    }
-    if !unmapped.is_empty() {
-        to_zero.retain(|&(za, _)| mapped.contains_key(&(za & !(TILE - 1))));
+        to_zero.forget_tile(t);
     }
     unmapped
 }
@@ -214,7 +307,7 @@ struct State {
     /// placed buffers → the pool tiles they use
     buffers: FxHashMap<usize, Vec<(u32, u32)>>,
     /// reused tiles / decommitted partial pages to clear: (address, bytes)
-    to_zero: Vec<(usize, usize)>,
+    to_zero: ZeroList,
     /// ring-buffered upload staging heap (`STAGING` bytes, persistently mapped)
     staging: Option<(ID3D12Resource, *mut u8)>,
     /// monotonic ring-buffer write/submitted/retired byte cursors
@@ -384,7 +477,7 @@ unsafe impl Send for State {}
 
 static STATE: Mutex<Option<State>> = Mutex::new(None);
 /// commits before the device existed
-static EARLY: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
+static EARLY: Mutex<RangeSet> = Mutex::new(RangeSet::new());
 /// generation counter incremented whenever the set of mapped tiles changes (for watch_ranges cache)
 static MAPPED_GEN: AtomicU64 = AtomicU64::new(0);
 
@@ -459,7 +552,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> {
             mapped: FxHashMap::default(),
             pinned: FxHashMap::default(),
             buffers: FxHashMap::default(),
-            to_zero: Vec::new(),
+            to_zero: ZeroList::default(),
             staging: None,
             ring_write: 0,
             ring_submitted: 0,
@@ -481,7 +574,8 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> {
         Ok(s) => {
             crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len());
             *STATE.lock().unwrap() = Some(s);
-            for (a, n) in std::mem::take(&mut *EARLY.lock().unwrap()) {
+            let early = EARLY.lock().unwrap().take();
+            for (a, n) in early {
                 committed(a, n);
             }
             out
@@ -624,7 +718,7 @@ impl State {
                 self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
                 self.runs = None;
                 if reused {
-                    self.to_zero.push((t, TILE));
+                    self.to_zero.push(t, TILE);
                 }
                 new.push((t, tile));
             }
@@ -1103,7 +1197,7 @@ pub unsafe fn readback_now(va: usize, len: usize) {
     if s.window_index(va).is_none() {
         return;
     }
-    let zeroed = std::mem::take(&mut s.to_zero);
+    let zeroed = s.to_zero.take();
     if !zeroed.is_empty() {
         for &(a, n) in &zeroed {
             s.clear_sent_range(a, n);
@@ -1144,7 +1238,7 @@ pub unsafe fn committed(a: usize, n: usize) {
     }
     let mut g = STATE.lock().unwrap();
     let Some(s) = g.as_mut() else {
-        EARLY.lock().unwrap().push((a, n));
+        EARLY.lock().unwrap().insert(a, n);
         return;
     };
     s.ensure_mapped(a, n, |_| 0xFFFF);
@@ -1176,7 +1270,7 @@ pub unsafe fn decommitted(a: usize, n: usize) {
     }
     let mut g = STATE.lock().unwrap();
     let Some(s) = g.as_mut() else {
-        EARLY.lock().unwrap().retain(|&(x, m)| x + m <= a || x >= a + n);
+        EARLY.lock().unwrap().remove(a, n);
         return;
     };
     let tiles = decommit_tiles(&mut s.mapped, &s.pinned, &mut s.free, &mut s.to_zero, a, n);
@@ -1246,7 +1340,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page:
     let Some(s) = g.as_mut() else { return };
     let t_locked = std::time::Instant::now();
     PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed);
-    let zero_runs = std::mem::take(&mut s.to_zero);
+    let zero_runs = s.to_zero.take();
     for &(a, n) in &zero_runs {
         s.clear_sent_range(a, n);
     }
@@ -1539,7 +1633,7 @@ mod tests {
                 mapped: FxHashMap::default(),
                 pinned: FxHashMap::default(),
                 buffers: FxHashMap::default(),
-                to_zero: Vec::new(),
+                to_zero: ZeroList::default(),
                 staging: None,
                 ring_write: 0,
                 ring_submitted: 0,
@@ -1594,14 +1688,14 @@ mod tests {
         let mut mapped: FxHashMap<usize, TileEntry> = FxHashMap::default();
         let mut pinned: FxHashMap<(u32, u32), u32> = FxHashMap::default();
         let mut free: Vec<(u32, u32)> = Vec::new();
-        let mut to_zero: Vec<(usize, usize)> = Vec::new();
+        let mut to_zero = ZeroList::default();
 
         // 1. Two 32 KiB decommits across a full 64 KiB tile.
         let t0 = 0x10_0000usize;
         mapped.insert(t0, TileEntry::with_holes((0, 10), 0));
         assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t0, TILE / 2).is_empty());
         assert_eq!(mapped[&t0].holes, 0x00FF);
-        assert_eq!(to_zero.len(), 8);
+        assert_eq!(to_zero.entries().len(), 8);
         assert!(free.is_empty());
 
         let unmapped = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t0 + TILE / 2, TILE / 2);
@@ -1643,10 +1737,83 @@ mod tests {
         mapped.insert(t3, TileEntry::with_holes((0, 13), 0xFFFF & !(1u16 << 2)));
         mapped.insert(t4, TileEntry::with_holes((0, 14), 0));
         assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t4, PAGE).is_empty());
-        assert_eq!(to_zero, vec![(t4, PAGE)]);
+        assert_eq!(to_zero.entries(), vec![(t4, PAGE)]);
         let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t3 + 2 * PAGE, PAGE);
         assert_eq!(u, vec![t3]);
         assert_eq!(free, vec![(0, 13)]);
-        assert_eq!(to_zero, vec![(t4, PAGE)], "unrelated mapped tile's to_zero must remain");
+        assert_eq!(to_zero.entries(), vec![(t4, PAGE)], "unrelated mapped tile's to_zero must remain");
+    }
+    /// The physical-page pattern: every step maps a reused tile (a whole-tile clear queued)
+    /// and unmaps another whole tile. With the list pruned by `retain` at every unmap this
+    /// was O(n²) (~30 s for a few GB of 64 KiB pages); it must stay linear.
+    #[test]
+    fn many_tile_unmaps_stay_linear() {
+        let mut mapped: FxHashMap<usize, TileEntry> = FxHashMap::default();
+        let pinned: FxHashMap<(u32, u32), u32> = FxHashMap::default();
+        let mut free: Vec<(u32, u32)> = Vec::new();
+        let mut to_zero = ZeroList::default();
+        const N: usize = 100_000; // 6.25 GB of 64 KiB pages
+        let base = 0x100_0000_0000usize;
+        let t0 = std::time::Instant::now();
+        for i in 0..N {
+            let t = base + i * TILE;
+            mapped.insert(t, TileEntry::with_holes((0, i as u32), 0));
+            to_zero.push(t, TILE);
+            if i % 2 == 1 {
+                // the previous tile goes away whole: its clear is dropped, this one's stays
+                let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t - TILE, TILE);
+                assert_eq!(u, vec![t - TILE]);
+            }
+        }
+        let e = to_zero.entries();
+        assert_eq!(e.len(), N / 2);
+        assert!(e.iter().all(|&(a, n)| n == TILE && mapped.contains_key(&a)));
+        assert_eq!(free.len(), N / 2);
+        let took = t0.elapsed();
+        assert!(took < std::time::Duration::from_secs(5), "{N} map / unmap steps took {took:?}");
+    }
+
+    #[test]
+    fn range_set_merges_and_cuts() {
+        let mut r = RangeSet::default();
+        r.insert(0x1000, 0x1000);
+        r.insert(0x3000, 0x1000);
+        r.insert(0x2000, 0x1000); // joins both neighbours
+        assert_eq!(r.map.iter().map(|(&s, &e)| (s, e)).collect::<Vec<_>>(), vec![(0x1000, 0x4000)]);
+        r.insert(0x1800, 0x100); // inside: nothing changes
+        r.insert(0x8000, 0x1000);
+        assert_eq!(r.map.len(), 2);
+        // a page cut out of the middle keeps both sides (the old list dropped the whole commit)
+        r.remove(0x2000, 0x1000);
+        assert_eq!(r.map.iter().map(|(&s, &e)| (s, e)).collect::<Vec<_>>(), vec![(0x1000, 0x2000), (0x3000, 0x4000), (0x8000, 0x9000)]);
+        // across several ranges, partly covering the first and last
+        r.remove(0x1800, 0x7000);
+        assert_eq!(r.map.iter().map(|(&s, &e)| (s, e)).collect::<Vec<_>>(), vec![(0x1000, 0x1800), (0x8800, 0x9000)]);
+        r.remove(0x0, 0x1_0000);
+        assert!(r.map.is_empty());
+        r.insert(0x5000, 0x2000);
+        r.insert(0x4000, 0x4000); // covers it
+        assert_eq!(r.take(), vec![(0x4000, 0x4000)]);
+        assert!(r.map.is_empty());
+    }
+
+    /// Commit / decommit pairs before the device exists, as the physical-page mapping does
+    /// them: linear, and what is left is exactly the still-committed pages.
+    #[test]
+    fn early_commits_stay_linear() {
+        let mut r = RangeSet::default();
+        const N: usize = 200_000;
+        let t0 = std::time::Instant::now();
+        for i in 0..N {
+            r.insert(i * TILE, TILE);
+            if i % 2 == 1 {
+                r.remove((i - 1) * TILE, TILE);
+            }
+        }
+        let left = r.take();
+        assert_eq!(left.len(), N / 2);
+        assert!(left.iter().enumerate().all(|(k, &(a, n))| a == (2 * k + 1) * TILE && n == TILE));
+        let took = t0.elapsed();
+        assert!(took < std::time::Duration::from_secs(5), "{N} early commits took {took:?}");
     }
 }
**@⁠srcamarda** on GitHub · 2026-11-23 20:54 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7113728044) Found the cause of the stall @⁠gw1337x reported (game thread stuck in `XMemMapPhysicalPagesScatter → … → sparse::decommitted → Vec::retain`). Reproduced on **RDNA3: RX 7800 XT**, driver 32.0.32029.2010, Windows 11 26300, PR head `8c0346d`, release build, retail title with `XCL_NETWORK=0`, `XCL_RUN_SECONDS=60`, cold shader cache: | build | first frame | presents in 60 s | end | |---|---|---|---| | `8c0346d` | never | 0 | title's watchdog at 32 s (`+0x2215c35`, write at 0) | | `8c0346d` + the patch below | 9.75 s | 2 (cold cache, as on `main`) | `XCL_RUN_SECONDS`, exit 0 | At the watchdog, the thread dump has a title thread running in XCL. Symbolized with the build's PDB: `Vec<(usize, usize)>::retain` in `sparse::decommit_tiles` ← `sparse::decommitted` ← `kernelx::XMemMapPhysicalPagesScatter`. ### Two quadratic pieces, both needed 1. **`to_zero.retain` at every tile unmap.** The scatter mapping's pattern is: unmap a page (a whole 64 KiB tile goes, so `retain` runs over all of `to_zero`), then map one (a reused tile queues a whole-tile clear). `to_zero` only drains at the next `before_execute`, so it grows by one entry per page, and every unmap walks all of it. 2. **`FxHasher::finish` returns `k * C` unchanged.** Keys of `mapped` are tile addresses (multiples of 64 KiB), so the low 16 bits of every hash are zero. hashbrown takes the bucket from the low bits, so past 64 K entries every lookup walks one long probe chain. That includes the `mapped.contains_key` inside the `retain` closure, and the `mapped` lookups on the submit path (`before_execute`). Synthetic measurement, 100 000 map / unmap steps (`many_tile_unmaps_stay_linear`, debug build): - per-tile list, old hasher: **34.8 s** - old `retain`, fixed hasher: **84 s** - both fixed: **0.16 s** ### The patch (`sparse.rs` only) - `ZeroList`: `to_zero` kept per tile. Unmapping a tile drops its entries in O(1) (`forget_tile`). This is exactly what the `retain` removed: only `decommit_tiles` removes tiles from `mapped`, and every entry is pushed for a tile that is mapped at that point. The drains get the same ranges, sorted by address (the order doesn't matter to the clears). - `FxHasher::finish` → `rotate_left(26)`, as rustc-hash 2 does. - `EARLY` (commits before the device exists) had the same shape: a push per commit and a `retain` per decommit. It is now a set of disjoint ranges (`RangeSet`, merges on insert, cuts on remove). **One behaviour change:** decommitting a page out of a larger early commit now keeps the rest of that commit. Before, the whole entry was dropped, so those pages were never mapped once the device came up. Not hit in this run (the stall was the `to_zero` one); happy to drop this part if you'd rather keep the PR minimal. - Tests: `many_tile_unmaps_stay_linear`, `early_commits_stay_linear`, `range_set_merges_and_cuts`; `decommit_sub_tile_reclaims_pool_tile_when_all_pages_become_holes` adapted to `ZeroList`. `cargo test -p xcl --lib`: 543 passed, 1 failed (`gpu_wave64_ps_whole_wave_reductions`, the 32-lane PS case on RDNA2/3, fixed by #155). Patch below. Not checked: the rendered image (the run only got as far as cold-cache loading), NVIDIA, and a warm-cache run. <details><summary>Patch against <code>8c0346d</code> (<code>git apply</code>)</summary> ```diff diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index ff20199..79a828b 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -73,14 +73,109 @@ impl Hasher for FxHasher { fn write_u64(&mut self, i: u64) { self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x517C_C1B7_2722_0A95); } + /// The product's well-mixed high bits moved down (as rustc-hash 2 does): the table takes the + /// bucket from the low bits, and keys that are tile / page addresses (multiples of 64 KiB) + /// would leave the low 16 bits of `k * C` zero – past 64 K entries every lookup walked one + /// long probe chain. #[inline] fn finish(&self) -> u64 { - self.0 + self.0.rotate_left(26) } } type FxHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>; +/// Ranges to clear on the GPU before the next upload, kept per 64 KiB tile: every entry +/// belongs to a tile that was mapped when it was added, and unmapping a tile drops its +/// entries in O(1) (`forget_tile`). A plain list pruned with `retain` at every unmap was +/// quadratic: a title mapping physical pages one by one (each unmap a whole tile, each map +/// a reused, to-be-cleared tile) spent seconds per GB there. +#[derive(Default, Debug)] +struct ZeroList { + by_tile: FxHashMap<usize, Vec<(usize, usize)>>, +} + +impl ZeroList { + fn push(&mut self, a: usize, n: usize) { + self.by_tile.entry(a & !(TILE - 1)).or_default().push((a, n)); + } + fn forget_tile(&mut self, t: usize) { + self.by_tile.remove(&t); + } + #[cfg(test)] + fn is_empty(&self) -> bool { + self.by_tile.is_empty() + } + /// every range, sorted by address (the order does not matter to the clears) + fn entries(&self) -> Vec<(usize, usize)> { + let mut v: Vec<(usize, usize)> = self.by_tile.values().flatten().copied().collect(); + v.sort_unstable(); + v + } + fn take(&mut self) -> Vec<(usize, usize)> { + let v = self.entries(); + self.by_tile.clear(); + v + } +} + +/// Disjoint, sorted address ranges `start → end` (commits before the device existed): adding +/// merges with neighbours, removing cuts only what it covers – both O(log n + ranges touched). +#[derive(Default, Debug)] +struct RangeSet { + map: std::collections::BTreeMap<usize, usize>, +} + +impl RangeSet { + const fn new() -> Self { + Self { map: std::collections::BTreeMap::new() } + } + fn insert(&mut self, a: usize, n: usize) { + if n == 0 { + return; + } + let (mut s, mut e) = (a, a.saturating_add(n)); + // a range starting at or before `s` that reaches it + if let Some((&ps, &pe)) = self.map.range(..=s).next_back() { + if pe >= s { + s = ps; + e = e.max(pe); + } + } + // ranges starting inside [s, e] + while let Some((&ns, &ne)) = self.map.range(s..=e).next() { + self.map.remove(&ns); + e = e.max(ne); + } + self.map.insert(s, e); + } + fn remove(&mut self, a: usize, n: usize) { + if n == 0 { + return; + } + let end = a.saturating_add(n); + // a range starting before `a` that reaches into [a, end) + if let Some((&ps, &pe)) = self.map.range(..a).next_back() { + if pe > a { + self.map.insert(ps, a); + if pe > end { + self.map.insert(end, pe); + } + } + } + // ranges starting inside [a, end) + while let Some((&ns, &ne)) = self.map.range(a..end).next() { + self.map.remove(&ns); + if ne > end { + self.map.insert(end, ne); + } + } + } + fn take(&mut self) -> Vec<(usize, usize)> { + std::mem::take(&mut self.map).into_iter().map(|(s, e)| (s, e - s)).collect() + } +} + struct TileEntry { pool: (u32, u32), /// bit `i` set => 4 KiB page `i` of this 64 KiB tile is uncommitted (a hole) @@ -133,7 +228,7 @@ fn decommit_tiles( mapped: &mut FxHashMap<usize, TileEntry>, pinned: &FxHashMap<(u32, u32), u32>, free: &mut Vec<(u32, u32)>, - to_zero: &mut Vec<(usize, usize)>, + to_zero: &mut ZeroList, a: usize, n: usize, ) -> Vec<usize> { @@ -164,7 +259,7 @@ fn decommit_tiles( } else if newly_holed != 0 { for idx in 0..PAGES_PER_TILE { if newly_holed & (1u16 << idx) != 0 { - to_zero.push((t + idx * PAGE, PAGE)); + to_zero.push(t + idx * PAGE, PAGE); } } } @@ -180,9 +275,7 @@ fn decommit_tiles( free.push(entry.pool); } } - } - if !unmapped.is_empty() { - to_zero.retain(|&(za, _)| mapped.contains_key(&(za & !(TILE - 1)))); + to_zero.forget_tile(t); } unmapped } @@ -214,7 +307,7 @@ struct State { /// placed buffers → the pool tiles they use buffers: FxHashMap<usize, Vec<(u32, u32)>>, /// reused tiles / decommitted partial pages to clear: (address, bytes) - to_zero: Vec<(usize, usize)>, + to_zero: ZeroList, /// ring-buffered upload staging heap (`STAGING` bytes, persistently mapped) staging: Option<(ID3D12Resource, *mut u8)>, /// monotonic ring-buffer write/submitted/retired byte cursors @@ -384,7 +477,7 @@ unsafe impl Send for State {} static STATE: Mutex<Option<State>> = Mutex::new(None); /// commits before the device existed -static EARLY: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); +static EARLY: Mutex<RangeSet> = Mutex::new(RangeSet::new()); /// generation counter incremented whenever the set of mapped tiles changes (for watch_ranges cache) static MAPPED_GEN: AtomicU64 = AtomicU64::new(0); @@ -459,7 +552,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { mapped: FxHashMap::default(), pinned: FxHashMap::default(), buffers: FxHashMap::default(), - to_zero: Vec::new(), + to_zero: ZeroList::default(), staging: None, ring_write: 0, ring_submitted: 0, @@ -481,7 +574,8 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { Ok(s) => { crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len()); *STATE.lock().unwrap() = Some(s); - for (a, n) in std::mem::take(&mut *EARLY.lock().unwrap()) { + let early = EARLY.lock().unwrap().take(); + for (a, n) in early { committed(a, n); } out @@ -624,7 +718,7 @@ impl State { self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); self.runs = None; if reused { - self.to_zero.push((t, TILE)); + self.to_zero.push(t, TILE); } new.push((t, tile)); } @@ -1103,7 +1197,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { if s.window_index(va).is_none() { return; } - let zeroed = std::mem::take(&mut s.to_zero); + let zeroed = s.to_zero.take(); if !zeroed.is_empty() { for &(a, n) in &zeroed { s.clear_sent_range(a, n); @@ -1144,7 +1238,7 @@ pub unsafe fn committed(a: usize, n: usize) { } let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { - EARLY.lock().unwrap().push((a, n)); + EARLY.lock().unwrap().insert(a, n); return; }; s.ensure_mapped(a, n, |_| 0xFFFF); @@ -1176,7 +1270,7 @@ pub unsafe fn decommitted(a: usize, n: usize) { } let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { - EARLY.lock().unwrap().retain(|&(x, m)| x + m <= a || x >= a + n); + EARLY.lock().unwrap().remove(a, n); return; }; let tiles = decommit_tiles(&mut s.mapped, &s.pinned, &mut s.free, &mut s.to_zero, a, n); @@ -1246,7 +1340,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let Some(s) = g.as_mut() else { return }; let t_locked = std::time::Instant::now(); PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed); - let zero_runs = std::mem::take(&mut s.to_zero); + let zero_runs = s.to_zero.take(); for &(a, n) in &zero_runs { s.clear_sent_range(a, n); } @@ -1539,7 +1633,7 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), buffers: FxHashMap::default(), - to_zero: Vec::new(), + to_zero: ZeroList::default(), staging: None, ring_write: 0, ring_submitted: 0, @@ -1594,14 +1688,14 @@ mod tests { let mut mapped: FxHashMap<usize, TileEntry> = FxHashMap::default(); let mut pinned: FxHashMap<(u32, u32), u32> = FxHashMap::default(); let mut free: Vec<(u32, u32)> = Vec::new(); - let mut to_zero: Vec<(usize, usize)> = Vec::new(); + let mut to_zero = ZeroList::default(); // 1. Two 32 KiB decommits across a full 64 KiB tile. let t0 = 0x10_0000usize; mapped.insert(t0, TileEntry::with_holes((0, 10), 0)); assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t0, TILE / 2).is_empty()); assert_eq!(mapped[&t0].holes, 0x00FF); - assert_eq!(to_zero.len(), 8); + assert_eq!(to_zero.entries().len(), 8); assert!(free.is_empty()); let unmapped = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t0 + TILE / 2, TILE / 2); @@ -1643,10 +1737,83 @@ mod tests { mapped.insert(t3, TileEntry::with_holes((0, 13), 0xFFFF & !(1u16 << 2))); mapped.insert(t4, TileEntry::with_holes((0, 14), 0)); assert!(decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t4, PAGE).is_empty()); - assert_eq!(to_zero, vec![(t4, PAGE)]); + assert_eq!(to_zero.entries(), vec![(t4, PAGE)]); let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t3 + 2 * PAGE, PAGE); assert_eq!(u, vec![t3]); assert_eq!(free, vec![(0, 13)]); - assert_eq!(to_zero, vec![(t4, PAGE)], "unrelated mapped tile's to_zero must remain"); + assert_eq!(to_zero.entries(), vec![(t4, PAGE)], "unrelated mapped tile's to_zero must remain"); + } + /// The physical-page pattern: every step maps a reused tile (a whole-tile clear queued) + /// and unmaps another whole tile. With the list pruned by `retain` at every unmap this + /// was O(n²) (~30 s for a few GB of 64 KiB pages); it must stay linear. + #[test] + fn many_tile_unmaps_stay_linear() { + let mut mapped: FxHashMap<usize, TileEntry> = FxHashMap::default(); + let pinned: FxHashMap<(u32, u32), u32> = FxHashMap::default(); + let mut free: Vec<(u32, u32)> = Vec::new(); + let mut to_zero = ZeroList::default(); + const N: usize = 100_000; // 6.25 GB of 64 KiB pages + let base = 0x100_0000_0000usize; + let t0 = std::time::Instant::now(); + for i in 0..N { + let t = base + i * TILE; + mapped.insert(t, TileEntry::with_holes((0, i as u32), 0)); + to_zero.push(t, TILE); + if i % 2 == 1 { + // the previous tile goes away whole: its clear is dropped, this one's stays + let u = decommit_tiles(&mut mapped, &pinned, &mut free, &mut to_zero, t - TILE, TILE); + assert_eq!(u, vec![t - TILE]); + } + } + let e = to_zero.entries(); + assert_eq!(e.len(), N / 2); + assert!(e.iter().all(|&(a, n)| n == TILE && mapped.contains_key(&a))); + assert_eq!(free.len(), N / 2); + let took = t0.elapsed(); + assert!(took < std::time::Duration::from_secs(5), "{N} map / unmap steps took {took:?}"); + } + + #[test] + fn range_set_merges_and_cuts() { + let mut r = RangeSet::default(); + r.insert(0x1000, 0x1000); + r.insert(0x3000, 0x1000); + r.insert(0x2000, 0x1000); // joins both neighbours + assert_eq!(r.map.iter().map(|(&s, &e)| (s, e)).collect::<Vec<_>>(), vec![(0x1000, 0x4000)]); + r.insert(0x1800, 0x100); // inside: nothing changes + r.insert(0x8000, 0x1000); + assert_eq!(r.map.len(), 2); + // a page cut out of the middle keeps both sides (the old list dropped the whole commit) + r.remove(0x2000, 0x1000); + assert_eq!(r.map.iter().map(|(&s, &e)| (s, e)).collect::<Vec<_>>(), vec![(0x1000, 0x2000), (0x3000, 0x4000), (0x8000, 0x9000)]); + // across several ranges, partly covering the first and last + r.remove(0x1800, 0x7000); + assert_eq!(r.map.iter().map(|(&s, &e)| (s, e)).collect::<Vec<_>>(), vec![(0x1000, 0x1800), (0x8800, 0x9000)]); + r.remove(0x0, 0x1_0000); + assert!(r.map.is_empty()); + r.insert(0x5000, 0x2000); + r.insert(0x4000, 0x4000); // covers it + assert_eq!(r.take(), vec![(0x4000, 0x4000)]); + assert!(r.map.is_empty()); + } + + /// Commit / decommit pairs before the device exists, as the physical-page mapping does + /// them: linear, and what is left is exactly the still-committed pages. + #[test] + fn early_commits_stay_linear() { + let mut r = RangeSet::default(); + const N: usize = 200_000; + let t0 = std::time::Instant::now(); + for i in 0..N { + r.insert(i * TILE, TILE); + if i % 2 == 1 { + r.remove((i - 1) * TILE, TILE); + } + } + let left = r.take(); + assert_eq!(left.len(), N / 2); + assert!(left.iter().enumerate().all(|(k, &(a, n))| a == (2 * k + 1) * TILE && n == TILE)); + let took = t0.elapsed(); + assert!(took < std::time::Duration::from_secs(5), "{N} early commits took {took:?}"); } } ``` </details>
Author
Owner

@⁠Kalmarv on GitHub · 2026-11-23 21:07 UTC · original

Linux / Turing run of 8c0346d on its own base 956a476. That's the head before the four commits pushed at 21:02 (now 603f546); the heap-window path these numbers cover is the same, and I'll rerun on the rebased head. It doesn't merge onto current main eaa36b6: 10 conflicting hunks in hle/kernelx.rs, where main's coherent-heap VirtualAlloc branch and its physical-page home rework (PHYS_BLOCKS, lazy_home, sparse decommit) meet this PR's PhysPages / AUTO_MAPPED / sparse-reserve changes. A rebase onto eaa36b6 is needed (as asked on #198), and the numbers below should be rerun afterwards. Ubuntu 24.04, RTX 2060 (Turing, 32-lane waves), NVIDIA 595.91.07, Wine 11.21 Staging (wow64), vkd3d-proton master 30b0eb9 (relaxed as in #175), DXVK 3.1.1 dxgi; cross-built for x86_64-pc-windows-gnu, release.

This stack has the known zero-read gap: Wine without userfaultfd write watches, so the imported UMA heap falls back to a copy of its own (#175). So I ran the PR twice: as is, and with MEM_WRITE_WATCH = 0 in gpu/uma.rs (an experiment that makes the import work here).

gpu::recomp filter, --test-threads=1:

Build passed failed ignored
main 956a476 (the base) 160 5 18
PR 8c0346d 163 6 20
PR 8c0346d, MEM_WRITE_WATCH = 0 168 1 20

(main eaa36b6 for reference: 166 passed / 5 failed / 18 ignored, the same 5.)

  • The base's 5 failures are the zero-read ones: gpu_memory_windows_above_4_gib, gpu_unified_memory_arena, gpu_mesh_mode_reads_memory_windows, gpu_bvh64_… and gpu_sparse_vram_descriptors_buffers_and_xmem.
  • The PR adds one: gpu_memory_windows_from_the_heap fails as is ("s_load from window 1", left (0, 0), right (12648430, 4660)), with the same signature as the others. With the import working it passes, along with 4 of the 5 old ones.
  • So the heap-window path (ResourceDescriptorHeap[NonUniformResourceIndex(...)]) reads correctly through vkd3d-proton / dxil-spirv on Turing. Its failure here is the import gap, not this PR.
  • gpu_raw_window_view_reaches_its_top, gpu_aperture_structured_rows_above_4_gib and gpu_aperture_probe_where_it_wraps pass in both builds. e1b_raw_views_under_debug_layer and e2_window_compile_time are ignored.
  • gpu_sparse_vram_descriptors_buffers_and_xmem still fails with the import working, as on main: a second, separate cause on this stack (#175).
  • hle::kernelx tests: 13 passed, 1 failed at both the base and the PR. The failure is the known Wine error-code difference, get_proc_address_and_load_library_ex_reject_null_name. physical_pages_have_cpu_homes_and_map_into_the_windows passes.

Not covered: the rebased PR; AMD; the DXC timing (e2); XCL_HEAP_WINDOWS=0; XCL_SPARSE_RESERVE_MB; any title.

AI-assisted test report (Claude); tests run locally as stated.

**@⁠Kalmarv** on GitHub · 2026-11-23 21:07 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7114047984) Linux / Turing run of `8c0346d` **on its own base `956a476`**. That's the head before the four commits pushed at 21:02 (now `603f546`); the heap-window path these numbers cover is the same, and I'll rerun on the rebased head. It doesn't merge onto current `main` `eaa36b6`: 10 conflicting hunks in `hle/kernelx.rs`, where main's coherent-heap `VirtualAlloc` branch and its physical-page home rework (`PHYS_BLOCKS`, `lazy_home`, sparse decommit) meet this PR's `PhysPages` / `AUTO_MAPPED` / sparse-reserve changes. **A rebase onto `eaa36b6` is needed** (as asked on #198), and the numbers below should be rerun afterwards. Ubuntu 24.04, **RTX 2060 (Turing, 32-lane waves)**, NVIDIA 595.91.07, Wine 11.21 Staging (wow64), vkd3d-proton `master` 30b0eb9 (relaxed as in #175), DXVK 3.1.1 `dxgi`; cross-built for `x86_64-pc-windows-gnu`, release. This stack has the known zero-read gap: Wine without `userfaultfd` write watches, so the imported UMA heap falls back to a copy of its own (#175). So I ran the PR twice: as is, and with `MEM_WRITE_WATCH` = 0 in `gpu/uma.rs` (an experiment that makes the import work here). `gpu::recomp` filter, `--test-threads=1`: | Build | passed | failed | ignored | |---|---|---|---| | `main` 956a476 (the base) | 160 | 5 | 18 | | PR `8c0346d` | 163 | 6 | 20 | | PR `8c0346d`, `MEM_WRITE_WATCH` = 0 | 168 | **1** | 20 | (`main` `eaa36b6` for reference: 166 passed / 5 failed / 18 ignored, the same 5.) - The base's 5 failures are the zero-read ones: `gpu_memory_windows_above_4_gib`, `gpu_unified_memory_arena`, `gpu_mesh_mode_reads_memory_windows`, `gpu_bvh64_…` and `gpu_sparse_vram_descriptors_buffers_and_xmem`. - The PR adds one: **`gpu_memory_windows_from_the_heap` fails as is** ("s_load from window 1", left `(0, 0)`, right `(12648430, 4660)`), with the same signature as the others. With the import working it **passes**, along with 4 of the 5 old ones. - So the heap-window path (`ResourceDescriptorHeap[NonUniformResourceIndex(...)]`) reads correctly through vkd3d-proton / dxil-spirv on Turing. Its failure here is the import gap, not this PR. - `gpu_raw_window_view_reaches_its_top`, `gpu_aperture_structured_rows_above_4_gib` and `gpu_aperture_probe_where_it_wraps` pass in both builds. `e1b_raw_views_under_debug_layer` and `e2_window_compile_time` are ignored. - `gpu_sparse_vram_descriptors_buffers_and_xmem` still fails with the import working, as on `main`: a second, separate cause on this stack (#175). - `hle::kernelx` tests: 13 passed, 1 failed at both the base and the PR. The failure is the known Wine error-code difference, `get_proc_address_and_load_library_ex_reject_null_name`. `physical_pages_have_cpu_homes_and_map_into_the_windows` passes. **Not covered:** the rebased PR; AMD; the DXC timing (`e2`); `XCL_HEAP_WINDOWS=0`; `XCL_SPARSE_RESERVE_MB`; any title. _AI-assisted test report (Claude); tests run locally as stated._
Author
Owner

@⁠Kalmarv on GitHub · 2026-11-23 21:15 UTC · original

Driver and GPU timings for the heap form next to the switch and #174's linked form, on an RTX 5070 Ti. In short: on an access-dense compute program the heap form brings the driver's compile back to what one window costs, and it does not cost GPU time.

Driver compile. A synthetic split-wave64 compute program with a load and a store of title memory every round and an exec-masked block every 4 rounds. Each row is 2 programs the driver had never seen, created from one thread:

rounds form DXIL DXC driver, first creation
1000 1 window 202 KB 3.0 s 3.8 / 4.4 s
1000 4 windows, switch (main) 447 KB 5.0–5.6 s 139.5 / 159.6 s
1000 4 windows, switch, linked (#174) 450 KB 4.0–4.1 s 156.3 / 167.4 s
1000 4 windows, heap (this PR) 274 KB 3.7–3.8 s 3.6 / 3.6 s
2000 1 window 416 KB 8.7–8.9 s 20.2 / 21.3 s
2000 4 windows, heap (this PR) 580 KB 10.8–11.2 s 15.1 / 18.9 s
  • During the switch-form compiles the process's working set was about 12 GB (tasklist samples of 11.8–12.1 GB).
  • Structure matters at equal size once accesses are dense: 447 KB of switch form took 7× as long as 416 KB of one-window form. The earlier probe on #156 that found no effect had an access every 8 rounds.

GPU time. #174's bench_memory_window_accessors with a heap form added, 1600 accesses, GPU timestamps around a dispatch of 2048 groups, 2 rounds:

form DXC DXIL GPU time
1 window 1.0 s 73 KB 0.236 / 0.238 ms
4 windows, switch 11.0 s 188 KB 0.273 / 0.274 ms
4 windows, switch, linked (#174) 1.6 s 189 KB 0.271 / 0.272 ms
4 windows, heap 1.2 s 86 KB 0.243 / 0.243 ms

The 0x8007000E refusal from #156 does not reproduce here with hand-written HLSL. I tried n distinct dynamically indexed raw UAVs from ResourceDescriptorHeap, with loops, atomics and globallycoherent: compute with n up to 2048 and pixel with n up to 4096 all build. This card is on driver 610.74 and the report was on 616.92, so this narrows nothing down beyond "not the handle count alone on 610.74".

Two notes on the code:

  • With #174: the two merge with one conflict, in emit.rs::mem_accessors. Keeping #174's mem_methods() split and putting this PR's heap branch at the top of mem_accessors(windows, heap) resolves it (linked_form then calls mem_accessors(w, None)). linked_form finds no switch accessors in a heap program, so such a program is compiled whole once, and #174 then only serves programs in the switch form, including the ones 603f546 rebuilds.
  • Precompile and the fallback (read in 603f546, not run): with_switch_fallback wraps the D3D12.X pipeline hooks, while xcl shaders --precompile --pipelines (shaders.rs) counts a refused pipeline and goes on. A program the driver refuses in the heap form would then still pay its switch-form driver compile at its first bind in the title.

Offer: I can add differential GPU tests on top of this PR: each existing multi-window test program (gpu_memory_windows_above_4_gib, the 4-window compute one, mesh mode, the other arena tests) run in the switch form and in the heap form, with registers and memory compared bit for bit. Today only one program runs in both forms. Tell me whether you would rather have that as a PR against your branch or after this lands.

Tested

  • RTX 5070 Ti (16 GB), driver 610.74, Windows 11 26200, Ryzen 9 9950X, DXC 1.9.2602.17, release build.
  • One binary: main 956a476 + this PR at 8c0346d + #174 at 328cf29, merged locally, plus local ignored benches (not pushed).
  • Driver rows: the bench from #156 with XCL_BENCH_MEMORY_EVERY=1 XCL_BENCH_WAVE64=1 XCL_BENCH_BRANCH_EVERY=4, one process per row, 14 GiB commit cap.
  • No game files: synthetic programs and hand-written HLSL only.

Not tested

  • This PR's commits after 8c0346d (4eae211, c014788, 375fc07, 603f546): read, not built or run.
  • The 2000-round switch rows: stopped after 20 s of driver time to keep the GPU free for others.
  • Graphics pipelines in the driver table, AMD, any retail program, DXC's own memory use.
  • Each row is 2 programs.

AI use: Claude Code, Claude Fable 5.2.

**@⁠Kalmarv** on GitHub · 2026-11-23 21:15 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7114215822) Driver and GPU timings for the heap form next to the switch and #174's linked form, on an RTX 5070 Ti. In short: on an access-dense compute program the heap form brings the driver's compile back to what one window costs, and it does not cost GPU time. **Driver compile.** A synthetic split-wave64 compute program with a load and a store of title memory every round and an exec-masked block every 4 rounds. Each row is 2 programs the driver had never seen, created from one thread: | rounds | form | DXIL | DXC | driver, first creation | |---|---|---:|---:|---:| | 1000 | 1 window | 202 KB | 3.0 s | 3.8 / 4.4 s | | 1000 | 4 windows, switch (`main`) | 447 KB | 5.0–5.6 s | **139.5 / 159.6 s** | | 1000 | 4 windows, switch, linked (#174) | 450 KB | 4.0–4.1 s | **156.3 / 167.4 s** | | 1000 | 4 windows, heap (this PR) | 274 KB | 3.7–3.8 s | **3.6 / 3.6 s** | | 2000 | 1 window | 416 KB | 8.7–8.9 s | 20.2 / 21.3 s | | 2000 | 4 windows, heap (this PR) | 580 KB | 10.8–11.2 s | 15.1 / 18.9 s | - During the switch-form compiles the process's working set was about 12 GB (`tasklist` samples of 11.8–12.1 GB). - Structure matters at equal size once accesses are dense: 447 KB of switch form took 7× as long as 416 KB of one-window form. The earlier probe on #156 that found no effect had an access every 8 rounds. **GPU time.** #174's `bench_memory_window_accessors` with a heap form added, 1600 accesses, GPU timestamps around a dispatch of 2048 groups, 2 rounds: | form | DXC | DXIL | GPU time | |---|---:|---:|---:| | 1 window | 1.0 s | 73 KB | 0.236 / 0.238 ms | | 4 windows, switch | 11.0 s | 188 KB | 0.273 / 0.274 ms | | 4 windows, switch, linked (#174) | 1.6 s | 189 KB | 0.271 / 0.272 ms | | 4 windows, heap | 1.2 s | 86 KB | 0.243 / 0.243 ms | **The `0x8007000E` refusal from #156 does not reproduce here with hand-written HLSL.** I tried n distinct dynamically indexed raw UAVs from `ResourceDescriptorHeap`, with loops, atomics and `globallycoherent`: compute with n up to 2048 and pixel with n up to 4096 all build. This card is on driver 610.74 and the report was on 616.92, so this narrows nothing down beyond "not the handle count alone on 610.74". **Two notes on the code:** - **With #174:** the two merge with one conflict, in `emit.rs::mem_accessors`. Keeping #174's `mem_methods()` split and putting this PR's heap branch at the top of `mem_accessors(windows, heap)` resolves it (`linked_form` then calls `mem_accessors(w, None)`). `linked_form` finds no switch accessors in a heap program, so such a program is compiled whole once, and #174 then only serves programs in the switch form, including the ones `603f546` rebuilds. - **Precompile and the fallback (read in `603f546`, not run):** `with_switch_fallback` wraps the D3D12.X pipeline hooks, while `xcl shaders --precompile --pipelines` (`shaders.rs`) counts a refused pipeline and goes on. A program the driver refuses in the heap form would then still pay its switch-form driver compile at its first bind in the title. **Offer:** I can add differential GPU tests on top of this PR: each existing multi-window test program (`gpu_memory_windows_above_4_gib`, the 4-window compute one, mesh mode, the other arena tests) run in the switch form and in the heap form, with registers and memory compared bit for bit. Today only one program runs in both forms. Tell me whether you would rather have that as a PR against your branch or after this lands. **Tested** - RTX 5070 Ti (16 GB), driver 610.74, Windows 11 26200, Ryzen 9 9950X, DXC 1.9.2602.17, release build. - One binary: `main` `956a476` + this PR at `8c0346d` + #174 at `328cf29`, merged locally, plus local ignored benches (not pushed). - Driver rows: the bench from #156 with `XCL_BENCH_MEMORY_EVERY=1 XCL_BENCH_WAVE64=1 XCL_BENCH_BRANCH_EVERY=4`, one process per row, 14 GiB commit cap. - No game files: synthetic programs and hand-written HLSL only. **Not tested** - This PR's commits after `8c0346d` (`4eae211`, `c014788`, `375fc07`, `603f546`): read, not built or run. - The 2000-round switch rows: stopped after 20 s of driver time to keep the GPU free for others. - Graphics pipelines in the driver table, AMD, any retail program, DXC's own memory use. - Each row is 2 programs. **AI use:** Claude Code, Claude Fable 5.2.
Author
Owner

@⁠TheFrenchPepeAI on GitHub · 2026-11-23 21:16 UTC · original

Data point from an RTX 4090 / Windows 10 machine: #187 brings back the null write that #169 clears.

build result
956a476 + #169 presents a frame, then 0x80000003 at +0x344196 (PS pipelines)
956a476 + #187 alone no present, 0xc0000005 write at 0x0 at +0x2215c35
956a476 + #169 + #187 no present, same +0x2215c35 null write

So on this machine #187 lands earlier than #169 alone, and adding #169 on top does not recover it — the subresource layout from #169 is presumably computed against a window #187 has moved out of the GPU reservation. Both runs use anaconda, title_memory = auto, XCL_NETWORK=0; a partial precompile cache (22 800 of 26 503 programs) is in place, so this is not a shader-compilation artefact.

**@⁠TheFrenchPepeAI** on GitHub · 2026-11-23 21:16 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7114244717) Data point from an RTX 4090 / Windows 10 machine: **#187 brings back the null write that #169 clears.** | build | result | |---|---| | 956a476 + #169 | presents a frame, then `0x80000003` at `+0x344196` (PS pipelines) | | 956a476 + #187 alone | no present, `0xc0000005` write at 0x0 at `+0x2215c35` | | 956a476 + #169 + #187 | no present, same `+0x2215c35` null write | So on this machine #187 lands earlier than #169 alone, and adding #169 on top does not recover it — the subresource layout from #169 is presumably computed against a window #187 has moved out of the GPU reservation. Both runs use `anaconda`, `title_memory = auto`, `XCL_NETWORK=0`; a partial precompile cache (22 800 of 26 503 programs) is in place, so this is not a shader-compilation artefact.
Author
Owner

@⁠Kalmarv on GitHub · 2026-11-23 21:38 UTC · original

On the null write @⁠TheFrenchPepeAI reports above: in compute on NVIDIA, the heap form and the switch form give the same results, including through the views open_uma makes. So that crash isn't explained by the two forms computing different values. Two commits on c74b03a you can take if they're useful; neither changes any program's HLSL:

  • 1562dd7, tests only (recomp/tests.rs, +311 / −3). It adds two tests that run one program in both forms and compare all SGPRs, all VGPRs and the first 64 KiB of every window:

    • gpu_window_forms_agree_on_every_access_kind covers every accessor kind (scalar loads, bounds-checked scalar buffer loads, buffer loads and stores including sub-dword, global stores, 32- and 64-bit atomics) over four windows.
    • gpu_runtime_windows_agree_in_both_forms uses the runtime layout: sparse windows 0..2, coherent window 3, and V#s loaded from a console descriptor heap in title memory.

    The mesh and BVH window tests also run in the heap form.

  • 9263711, precompile (shaders.rs, +78 / −10). xcl shaders --precompile --pipelines didn't make the switch form of a pipeline the driver refuses with E_OUTOFMEMORY, so that program's DXC and driver compiles were still paid at its first bind. It now does what with_switch_fallback does, under the same cache keys. Its test injects the refusals, because 610.74 refused none of my programs.

Controls

  • With the heap accessor forced to window 0, 5 of the 8 window tests fail.
  • With the runtime's view of window 2 built from window 0's buffer, only gpu_runtime_windows_agree_in_both_forms fails. None of the PR's existing tests reads through the views open_uma makes, so none of them would catch a wrong view.

Tested

  • RTX 5070 Ti, NVIDIA 610.74, Windows 11 26200. c74b03a merged onto main 0cd0a53.
  • The 8 window tests with the SDK's DXC and with DXC 1.9.2602.17: 8/8 pass both times.
  • Whole library suite, 4 threads: 590 / 0 / 23 (passed / failed / ignored) without the two commits, 593 / 0 / 23 with them.

Not tested

  • AMD and Intel.
  • Pixel and vertex stages in the heap form.
  • A real E_OUTOFMEMORY refusal.
  • Timing effects on the title.
  • The two commits on c74b03a alone: type-checked only.

🤖 Claude Fable 5.2, Claude Opus 5.5

**@⁠Kalmarv** on GitHub · 2026-11-23 21:38 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7114718401) On the null write @⁠TheFrenchPepeAI reports above: **in compute on NVIDIA, the heap form and the switch form give the same results, including through the views `open_uma` makes.** So that crash isn't explained by the two forms computing different values. Two commits on `c74b03a` you can take if they're useful; neither changes any program's HLSL: - **[`1562dd7`](https://github.com/Kalmarv/xcl/commit/1562dd7d16088c0a628cb42b7ce824902c2bafd7), tests only** (`recomp/tests.rs`, +311 / −3). It adds two tests that run one program in both forms and compare all SGPRs, all VGPRs and the first 64 KiB of every window: - `gpu_window_forms_agree_on_every_access_kind` covers every accessor kind (scalar loads, bounds-checked scalar buffer loads, buffer loads and stores including sub-dword, global stores, 32- and 64-bit atomics) over four windows. - `gpu_runtime_windows_agree_in_both_forms` uses the runtime layout: sparse windows 0..2, coherent window 3, and V#s loaded from a console descriptor heap in title memory. The mesh and BVH window tests also run in the heap form. - **[`9263711`](https://github.com/Kalmarv/xcl/commit/9263711cb334ce854285980865aa183ab8cd7f17), precompile** (`shaders.rs`, +78 / −10). `xcl shaders --precompile --pipelines` didn't make the switch form of a pipeline the driver refuses with `E_OUTOFMEMORY`, so that program's DXC and driver compiles were still paid at its first bind. It now does what `with_switch_fallback` does, under the same cache keys. Its test injects the refusals, because 610.74 refused none of my programs. **Controls** - With the heap accessor forced to window 0, 5 of the 8 window tests fail. - With the runtime's view of window 2 built from window 0's buffer, only `gpu_runtime_windows_agree_in_both_forms` fails. None of the PR's existing tests reads through the views `open_uma` makes, so none of them would catch a wrong view. ### Tested - RTX 5070 Ti, NVIDIA 610.74, Windows 11 26200. `c74b03a` merged onto `main` `0cd0a53`. - The 8 window tests with the SDK's DXC and with DXC 1.9.2602.17: 8/8 pass both times. - Whole library suite, 4 threads: 590 / 0 / 23 (passed / failed / ignored) without the two commits, 593 / 0 / 23 with them. ### Not tested - AMD and Intel. - Pixel and vertex stages in the heap form. - A real `E_OUTOFMEMORY` refusal. - Timing effects on the title. - The two commits on `c74b03a` alone: type-checked only. 🤖 Claude Fable 5.2, Claude Opus 5.5
Author
Owner

@⁠srcamarda on GitHub · 2026-11-23 22:15 UTC · original

Follow-up to my comment above, on the current head c74b03a: the startup hang is gone, and nothing from my patch is needed any more.

  • The hash part is on main as #230 (rotate_right(23)), and the EARLY part as 68a6640 (merged page ranges).
  • The to_zero part (per-tile list instead of retain at every unmap) still applies. With it the run below is the same within run-to-run noise (934 / 1116 frames vs 877 / 1101), so this title no longer reaches that path hard enough to matter. I'm not proposing it here.

Regression run (scripts/smoke.ps1, 90 s, the retail title, XCL_NETWORK=0), RX 7800 XT (RDNA3, driver 32.0.32029.2010), Ryzen 5 5600G, 32 GB, Windows 11 26300, release build. c74b03a merged onto main (clean merge; the PR conflicts with nothing in my tree).

Two runs each: the first with a cold translation cache, since each binary has its own, and the second warm. The gpu: line names a virtual display adapter on this machine, but XCL ran on the RX 7800 XT.

main (9ab7d76):

xcl-smoke v1
commit: 9ab7d763197c7f420bff10cd9bf1310f07e2a9aa
gpu: SudoMaker Virtual Display Adapter
title: main_game.exe
seconds: 90
exit: 0x0
frames shown: 1164 (PresentX 1164)
presents per 2 s (last 3): 25 25 24
device removals: 0
crashes: 0
peak commit: 17183 MB

(cold run: 1129 frames, peak 17169 MB)

main + c74b03a:

xcl-smoke v1
commit: fedba9354d18ddc0183907774bdd3a08a6d5f750
gpu: SudoMaker Virtual Display Adapter
title: main_game.exe
seconds: 90
exit: 0x0
frames shown: 1101 (PresentX 1101)
presents per 2 s (last 3): 24 26 20
device removals: 0
crashes: 0
peak commit: 17180 MB

(cold run: 877 frames, peak 17229 MB; the heap form recompiles every translated shader once)

  • First frame at 2.7 s in both. No device removal, no crash, the same peak commit.
  • Warm, it is within ~5 % of main's frames. Both sit at ~12 presents/s on the account prompt.
  • Not covered: past the account prompt (no input given), NVIDIA (#232's null write), XDefiant.
**@⁠srcamarda** on GitHub · 2026-11-23 22:15 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7115532020) Follow-up to my comment above, on the current head `c74b03a`: **the startup hang is gone, and nothing from my patch is needed any more.** - The hash part is on `main` as #230 (`rotate_right(23)`), and the `EARLY` part as `68a6640` (merged page ranges). - The `to_zero` part (per-tile list instead of `retain` at every unmap) still applies. With it the run below is the same within run-to-run noise (934 / 1116 frames vs 877 / 1101), so this title no longer reaches that path hard enough to matter. I'm not proposing it here. **Regression run** (`scripts/smoke.ps1`, 90 s, the retail title, `XCL_NETWORK=0`), **RX 7800 XT** (RDNA3, driver 32.0.32029.2010), Ryzen 5 5600G, 32 GB, Windows 11 26300, release build. `c74b03a` merged onto `main` (clean merge; the PR conflicts with nothing in my tree). Two runs each: the first with a cold translation cache, since each binary has its own, and the second warm. The `gpu:` line names a virtual display adapter on this machine, but XCL ran on the RX 7800 XT. `main` (9ab7d76): ``` xcl-smoke v1 commit: 9ab7d763197c7f420bff10cd9bf1310f07e2a9aa gpu: SudoMaker Virtual Display Adapter title: main_game.exe seconds: 90 exit: 0x0 frames shown: 1164 (PresentX 1164) presents per 2 s (last 3): 25 25 24 device removals: 0 crashes: 0 peak commit: 17183 MB ``` (cold run: 1129 frames, peak 17169 MB) `main` + `c74b03a`: ``` xcl-smoke v1 commit: fedba9354d18ddc0183907774bdd3a08a6d5f750 gpu: SudoMaker Virtual Display Adapter title: main_game.exe seconds: 90 exit: 0x0 frames shown: 1101 (PresentX 1101) presents per 2 s (last 3): 24 26 20 device removals: 0 crashes: 0 peak commit: 17180 MB ``` (cold run: 877 frames, peak 17229 MB; the heap form recompiles every translated shader once) - First frame at 2.7 s in both. No device removal, no crash, the same peak commit. - Warm, it is within ~5 % of `main`'s frames. Both sit at ~12 presents/s on the account prompt. - Not covered: past the account prompt (no input given), NVIDIA (#232's null write), XDefiant.
Author
Owner

@⁠shelbykb2 on GitHub · 2026-11-23 22:20 UTC · original

RDNA2 result for the two tests asked about: AMD Radeon RX 6800 (16 GB), driver 32.0.21045.29003, Windows 11, Rust 1.100.0, release, head c74b03a.

  • cargo test --release -p xcl --lib -- --test-threads=1 gpu_memory_windows_from_the_heap gpu_raw_window_view_reaches_its_top: 2 passed, 0 failed, no SKIPPED.
  • At the earlier head 8c0346d (on main 956a476 + #170) the startup stall reported above reproduced on this card as well: no present, and the title's watchdog fired at 32.0 s. Not rerun on a title at c74b03a.
  • Not tested: the whole suite at this head.

Report written with Claude Code, from our own runs.

**@⁠shelbykb2** on GitHub · 2026-11-23 22:20 UTC · [original](https://github.com/xcl-dev/xcl/pull/187#issuecomment-7115635776) RDNA2 result for the two tests asked about: AMD Radeon RX 6800 (16 GB), driver 32.0.21045.29003, Windows 11, Rust 1.100.0, release, head `c74b03a`. - `cargo test --release -p xcl --lib -- --test-threads=1 gpu_memory_windows_from_the_heap gpu_raw_window_view_reaches_its_top`: 2 passed, 0 failed, no SKIPPED. - At the earlier head `8c0346d` (on main `956a476` + #170) the startup stall reported above reproduced on this card as well: no present, and the title's watchdog fired at 32.0 s. Not rerun on a title at `c74b03a`. - **Not tested:** the whole suite at this head. Report written with Claude Code, from our own runs.

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.