D3D12.X: ~43x FPS over main on Series X (0.58 -> 25.3 fps, ~7x over #2844): XCL_UMA_DRIVER=mixed keeps part of the coherent window in VRAM #2938

Open
github-bot wants to merge 6 commits from github-bot/gh-2938 into main AGit
Owner

@⁠Kalmarv on GitHub · 2026-11-27 01:16 UTC · original
Kalmarv:uma-mixed-window → main · +1716 −61 · 32 files · 6 commits · draft

Stacked on #2844, #2926, #2936, #2937 and #2934; only the top commit (0567c713) belongs here. The others are in the head so that it reproduces the measured tree.

With XCL_UMA_DRIVER=mixed:<start_mb>:<size_mb>[,...] the coherent window becomes several driver heaps instead of #2844's one CUSTOM heap: each listed range a GPU_UPLOAD heap (video memory the CPU writes through the BAR; on NVIDIA it stays in video memory up to 2 GiB) and the rest CUSTOM write-back L0 heaps. Each segment's CPU mapping lands at its place in the window (every slot reserved first, the rest of the address space groomed as #2844 does), and one reserved buffer over the window maps its 64 KiB tiles onto the segments' heaps, so shaders and placed resources still see one window.

Headline (RTX 5070 Ti, Series X profile, same title, timed runs alone; fps over 187-229 s / 107-223 s)

tree env 187-229 s 107-223 s
main 8b957bec plain 0.58 1.12
#2844 (fc007a96) plain 3.71 3.00
this stack (TX1) XCL_UMA_DRIVER=mixed:1536:1792 XCL_WATCH_TRAP=1 XCL_DECLARED_LDS=1 XCL_BYTE_STORE_CS=e166372fa54a77c7 XCL_TEXTURE_LEVEL_PAGES=1 XCL_PARK_SPARES=1 25.28 20.31
older base, mixed window (CB2m3) as TX1 without XCL_PARK_SPARES and without the look-walk 24.15 16.05
older base, one CUSTOM heap (CB2) as CB2m3 with XCL_UMA_DRIVER=custom 11.99 9.32
  • main and #2844 ran their plain environment; TX1 ran the whole stack with its switches (XCL_PARK_SPARES=1 was #2936's switch then; #2936 has none). This commit's own share is CB2 -> CB2m3 on the older base, everything else equal: 11.99 -> 24.15 fps late (2.01x). TX1 is the combined result.
  • TX1's world came about 40 s earlier than the other runs', so the 107-223 s window favours it; the late window is steady state for all of them.
  • The late frame is now GPU-bound (3D engine 95-97 % busy over 180-240 s); the window's GPU_UPLOAD part cut PCIe traffic by about two thirds.
  • The frames are grey on every tree here (a separate open issue), so equal work per frame is checked by counts (~755 draws, ~4,750 dispatches per present), not by images.

What is in it (0567c713)

  • uma_driver.rs: mixed: parsing (parse_mixed, and decide takes it as on), build_segments, remake_window (the mixed remake or #2844's), remake_mixed, and the reader of the GPU_UPLOAD segments (read_vram_bytes: a copy on the COPY queue into a readback buffer, as CPU reads of that memory through the BAR ran at 12-84 MiB/s).
  • The CUSTOM segments are write-watched as #2844's heap is; a segment that refuses it fails the remake, which restores the window and keeps the import. The GPU_UPLOAD segments are not write-watched: their write-combined pages refuse the watch trap's read-only protection. Uma::watch_regions lists only the watched segments (gpu/uma.rs).
  • No Resizable BAR: remake_window asks D3D12_OPTIONS16.GPUUploadHeapSupported before the window is released, and without it mixed falls back to #2844's single CUSTOM heap (a warning in the log). A GPU_UPLOAD segment refused anyway becomes a write-watched CUSTOM segment in its place. A segment that was mapped cannot be given back: after Unmap and the heap's release its pages stay with the driver (still MEM_COMMIT seconds later; a new heap of the same size maps there again), so the earlier rollback could not reserve the window again (Windows error 487) and stopped the process (found by @⁠CharlyRien, @⁠ettehn and @⁠3L1A5-1).
  • A console buffer XCL places in the window whose first fit crosses two segments (no one heap holds it) goes to the next fit, and the crossing block is given back; it stayed charged to the window before (found by @⁠ettehn). alloc_in_one_heap in real.rs.
  • A window that cannot be made again at its address after a failure stops the process, as #2844's remake does.
  • real.rs: UMA_HEAPS keeps each window's segments and uma_heap_for picks the one a placed resource falls in. title_textures.rs: with_title_bytes reads GPU_UPLOAD segments through read_vram_bytes.
  • Tests: mixed_ranges_parse_in_order, mixed_segments_cover_the_window, the GPU test mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment (the title's bytes survive in every segment, the GPU reads later CPU writes to each segment through the one buffer, read_vram_bytes reads only the GPU_UPLOAD one; skipped without GPU_UPLOAD heaps), and a_refused_gpu_upload_segment_becomes_custom (a refusal injected after the first CUSTOM segment is mapped: the window stays whole and fully watched, its bytes kept, the GPU sees later CPU writes; without the fallback the test process exits 0x7C10003), and a_block_across_two_segments_is_given_back_and_the_next_fit_used (real.rs).
  • +674 / -24 lines in one commit: the remake, the reserved buffer and the reader do not work apart.

Tested

  • RTX 5070 Ti (driver 610.74), Windows 11 Pro 26200, Rust 1.99.0 MSVC, DXC 1.9 via XCL_DXC_DIR.
  • cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4 on a76cc3e6 (the whole stack, with CARGO_PROFILE_DEV_DEBUG=0 for disk space): 1476 passed, 0 failed, 47 ignored. 25 SKIPPED: 21 no wave64, 3 refused per-lane f16 forms, 1 no heap windows. The five new tests pass without skips. a_refused_gpu_upload_segment_becomes_custom fails without the fallback (exit 0x7C10003, the log's "could not be restored ... Windows error 487"). Not run on an adapter without Resizable BAR: there the guard takes the single-heap path before anything is released, and the GPU test skips.
  • Title runs: the table above (TX1 on our integration branch, whose tree differs from this head by private DXC heaps, a compile-time change, and diagnostics).

Regression run
480 s runs, same title, same env (XCL_HEAP_WINDOWS=1 XCL_DIRECT_DXIL=all XCL_DIRECT_SPLIT_INSTRUCTIONS=0 XCL_PSO_JOURNAL=0 XCL_DRED=1 XCL_GPU_WAIT_TIMEOUT_MS=120000, DXC 1.9, the same button presses every 4 s from 14 s), each from a hard-link copy of one DXIL cache. No XCL_UMA_DRIVER: mixed is opt-in, so the pair checks the default path (#2844's single heap on NVIDIA).

A commit of main (8b957bec):

xcl-smoke v1
commit: 8b957bec6f82495aec940944c6bf47faa02db590
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 480
exit: 0x0
frames shown: 1687 (PresentX 1687)
presents per 2 s (last 3): 1 2 1
device removals: 0
crashes: 0
peak commit: 38717 MB

This PR's head:

xcl-smoke v1
commit: a76cc3e638400dcc2ac731e63062123b92bfb317
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 480
exit: 0x0
frames shown: 2899 (PresentX 2899)
presents per 2 s (last 3): 8 7 8
device removals: 0
crashes: 0
peak commit: 37877 MB

Not tested

  • AMD, Intel, Wine (the switch is meant for NVIDIA; elsewhere it is not on by default). An adapter without Resizable BAR (the fallback is tested by an injected refusal only). Other range layouts than mixed:1536:1792. Cards with less than 16 GB of video memory. Titles other than this one. The remake reserves the process's other free stretches so the driver maps each segment at its place; a thread of the title that frees 64 MB or more of address space during it can still let a segment map elsewhere, which stops the process (as the tests did before the lock). Not seen in title runs; the switch is opt-in.

AI use

  • Claude Code (Claude Opus 5.5): the change was written with Claude Code by a teammate agent (reed) on our team branch; this agent ported it onto #2844's head, wrote the tests, ran the suite and wrote this description. Timed runs by teammate agents (strange, batman, reed) and this one.
**@⁠Kalmarv** on GitHub · 2026-11-27 01:16 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938) `Kalmarv:uma-mixed-window` → `main` · +1716 −61 · 32 files · 6 commits · draft Stacked on #2844, #2926, #2936, #2937 and #2934; only the top commit (0567c713) belongs here. The others are in the head so that it reproduces the measured tree. With `XCL_UMA_DRIVER=mixed:<start_mb>:<size_mb>[,...]` the coherent window becomes several driver heaps instead of #2844's one CUSTOM heap: each listed range a `GPU_UPLOAD` heap (video memory the CPU writes through the BAR; on NVIDIA it stays in video memory up to 2 GiB) and the rest CUSTOM write-back L0 heaps. Each segment's CPU mapping lands at its place in the window (every slot reserved first, the rest of the address space groomed as #2844 does), and one reserved buffer over the window maps its 64 KiB tiles onto the segments' heaps, so shaders and placed resources still see one window. **Headline** (RTX 5070 Ti, Series X profile, same title, timed runs alone; fps over 187-229 s / 107-223 s) | tree | env | 187-229 s | 107-223 s | |---|---|---|---| | main 8b957bec | plain | 0.58 | 1.12 | | #2844 (fc007a96) | plain | 3.71 | 3.00 | | this stack (TX1) | `XCL_UMA_DRIVER=mixed:1536:1792 XCL_WATCH_TRAP=1 XCL_DECLARED_LDS=1 XCL_BYTE_STORE_CS=e166372fa54a77c7 XCL_TEXTURE_LEVEL_PAGES=1 XCL_PARK_SPARES=1` | **25.28** | **20.31** | | older base, mixed window (CB2m3) | as TX1 without `XCL_PARK_SPARES` and without the look-walk | 24.15 | 16.05 | | older base, one CUSTOM heap (CB2) | as CB2m3 with `XCL_UMA_DRIVER=custom` | 11.99 | 9.32 | - main and #2844 ran their plain environment; TX1 ran the whole stack with its switches (`XCL_PARK_SPARES=1` was #2936's switch then; #2936 has none). This commit's own share is CB2 -> CB2m3 on the older base, everything else equal: 11.99 -> 24.15 fps late (2.01x). TX1 is the combined result. - TX1's world came about 40 s earlier than the other runs', so the 107-223 s window favours it; the late window is steady state for all of them. - The late frame is now GPU-bound (3D engine 95-97 % busy over 180-240 s); the window's `GPU_UPLOAD` part cut PCIe traffic by about two thirds. - The frames are grey on every tree here (a separate open issue), so equal work per frame is checked by counts (~755 draws, ~4,750 dispatches per present), not by images. **What is in it** (0567c713) - `uma_driver.rs`: `mixed:` parsing (`parse_mixed`, and `decide` takes it as on), `build_segments`, `remake_window` (the mixed remake or #2844's), `remake_mixed`, and the reader of the `GPU_UPLOAD` segments (`read_vram_bytes`: a copy on the COPY queue into a readback buffer, as CPU reads of that memory through the BAR ran at 12-84 MiB/s). - The CUSTOM segments are write-watched as #2844's heap is; a segment that refuses it fails the remake, which restores the window and keeps the import. The `GPU_UPLOAD` segments are not write-watched: their write-combined pages refuse the watch trap's read-only protection. `Uma::watch_regions` lists only the watched segments (`gpu/uma.rs`). - No Resizable BAR: `remake_window` asks `D3D12_OPTIONS16.GPUUploadHeapSupported` before the window is released, and without it `mixed` falls back to #2844's single CUSTOM heap (a warning in the log). A `GPU_UPLOAD` segment refused anyway becomes a write-watched CUSTOM segment in its place. A segment that was mapped cannot be given back: after `Unmap` and the heap's release its pages stay with the driver (still `MEM_COMMIT` seconds later; a new heap of the same size maps there again), so the earlier rollback could not reserve the window again (Windows error 487) and stopped the process (found by @⁠CharlyRien, @⁠ettehn and @⁠3L1A5-1). - A console buffer XCL places in the window whose first fit crosses two segments (no one heap holds it) goes to the next fit, and the crossing block is given back; it stayed charged to the window before (found by @⁠ettehn). `alloc_in_one_heap` in `real.rs`. - A window that cannot be made again at its address after a failure stops the process, as #2844's remake does. - `real.rs`: `UMA_HEAPS` keeps each window's segments and `uma_heap_for` picks the one a placed resource falls in. `title_textures.rs`: `with_title_bytes` reads `GPU_UPLOAD` segments through `read_vram_bytes`. - Tests: `mixed_ranges_parse_in_order`, `mixed_segments_cover_the_window`, the GPU test `mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment` (the title's bytes survive in every segment, the GPU reads later CPU writes to each segment through the one buffer, `read_vram_bytes` reads only the `GPU_UPLOAD` one; skipped without `GPU_UPLOAD` heaps), and `a_refused_gpu_upload_segment_becomes_custom` (a refusal injected after the first CUSTOM segment is mapped: the window stays whole and fully watched, its bytes kept, the GPU sees later CPU writes; without the fallback the test process exits 0x7C10003), and `a_block_across_two_segments_is_given_back_and_the_next_fit_used` (`real.rs`). - +674 / -24 lines in one commit: the remake, the reserved buffer and the reader do not work apart. **Tested** - RTX 5070 Ti (driver 610.74), Windows 11 Pro 26200, Rust 1.99.0 MSVC, DXC 1.9 via `XCL_DXC_DIR`. - `cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4` on a76cc3e6 (the whole stack, with `CARGO_PROFILE_DEV_DEBUG=0` for disk space): 1476 passed, 0 failed, 47 ignored. 25 `SKIPPED`: 21 no wave64, 3 refused per-lane f16 forms, 1 no heap windows. The five new tests pass without skips. `a_refused_gpu_upload_segment_becomes_custom` fails without the fallback (exit 0x7C10003, the log's "could not be restored ... Windows error 487"). Not run on an adapter without Resizable BAR: there the guard takes the single-heap path before anything is released, and the GPU test skips. - Title runs: the table above (TX1 on our integration branch, whose tree differs from this head by private DXC heaps, a compile-time change, and diagnostics). **Regression run** 480 s runs, same title, same env (`XCL_HEAP_WINDOWS=1 XCL_DIRECT_DXIL=all XCL_DIRECT_SPLIT_INSTRUCTIONS=0 XCL_PSO_JOURNAL=0 XCL_DRED=1 XCL_GPU_WAIT_TIMEOUT_MS=120000`, DXC 1.9, the same button presses every 4 s from 14 s), each from a hard-link copy of one DXIL cache. No `XCL_UMA_DRIVER`: `mixed` is opt-in, so the pair checks the default path (#2844's single heap on NVIDIA). A commit of `main` (`8b957bec`): ``` xcl-smoke v1 commit: 8b957bec6f82495aec940944c6bf47faa02db590 gpu: NVIDIA GeForce RTX 5070 Ti title: ea3b5e4d seconds: 480 exit: 0x0 frames shown: 1687 (PresentX 1687) presents per 2 s (last 3): 1 2 1 device removals: 0 crashes: 0 peak commit: 38717 MB ``` This PR's head: ``` xcl-smoke v1 commit: a76cc3e638400dcc2ac731e63062123b92bfb317 gpu: NVIDIA GeForce RTX 5070 Ti title: ea3b5e4d seconds: 480 exit: 0x0 frames shown: 2899 (PresentX 2899) presents per 2 s (last 3): 8 7 8 device removals: 0 crashes: 0 peak commit: 37877 MB ``` **Not tested** - AMD, Intel, Wine (the switch is meant for NVIDIA; elsewhere it is not on by default). An adapter without Resizable BAR (the fallback is tested by an injected refusal only). Other range layouts than `mixed:1536:1792`. Cards with less than 16 GB of video memory. Titles other than this one. The remake reserves the process's other free stretches so the driver maps each segment at its place; a thread of the title that frees 64 MB or more of address space during it can still let a segment map elsewhere, which stops the process (as the tests did before the lock). Not seen in title runs; the switch is opt-in. **AI use** - Claude Code (Claude Opus 5.5): the change was written with Claude Code by a teammate agent (reed) on our team branch; this agent ported it onto #2844's head, wrote the tests, ran the suite and wrote this description. Timed runs by teammate agents (strange, batman, reed) and this one.
The unchanged-content hash, the detile of title textures and the
frame-trace sampler read the title's memory in place once it looked
readable (#602). That bypasses the ReadProcessMemory copy of
read_committed (#484): the title can decommit or unmap those pages from
another thread at any moment, and the read then faults with 0xC0000005.

with_title_bytes replaces title_bytes. A range inside the coherent
committed window is still read in place: XCL's VirtualFree never
decommits that window (MEM_DECOMMIT there zeroes the block in place).
Everything else is read as read_committed reads it, into a buffer kept
per thread and dropped after a read that grew it past 64 MiB.
read_committed_into now writes every byte (copied, or zero for a page
that is not readable), so the reused buffer needs no memset and nothing
of an earlier read shows through a hole. Only long-lived threads reuse
the buffer: the scoped workers of a parallel batch detile allocate one
per batch.

title_bytes_survive_concurrent_decommit hashes 1 MiB while another
thread decommits and recommits its 64 KiB pages; it checks that every
decommit and recommit succeeded, that some happened during the hashing and
that each read holds the title's bytes or zeros.
title_bytes_leave_guard_pages_alone reads a guard and a no-access page
as zeros and checks that the guard stays.

read_committed_into first copies the whole range with one
ReadProcessMemory and walks it region by region with VirtualQuery only
when that is refused (a page not committed, no-access or a guard page;
the guard stays). VirtualQuery scans from the page asked about to the
end of its run of like pages, and the title's memory is a few runs of
hundreds of MiB: in a release
microbenchmark (7600X), reading 16 KiB / 256 KiB / 4 MiB of a
fully committed 64 MiB region took 128 / 125 / 280 us with the walk and
1.3 / 6.9 / 156 us now (512 MiB region: 1629 / 1179 / 1753 us, now
1.4 / 7.5 / 128 us). A range with holes pays one refused copy on top
of the walk (4 MiB with one hole: ~158 us before, ~230 us now).
The title's GPU code reads and writes the coherent window (4 GiB of host
memory) through a heap opened with OpenExistingHeapFromAddress. On an
RTX 5070 Ti, GPU loads from such imported pages ran 8-24x and atomics
13-22x slower than from a driver CUSTOM write-back L0 heap in host
memory, at the same CPU caching. A whole-frame replay of a captured
title frame took 172 ms of GPU time with the window in a CUSTOM L0
heap and 1,427 ms with it imported as XCL does, the hot compute
programs 18-39x slower each.

At open_uma the window's written pages are copied out, the window is
released, every other free stretch of 1 GiB or more is reserved for a
moment so that the driver's CPU mapping of a new CUSTOM L0 heap can only
land in the hole the window left, and the pages are copied back. The
title keeps its pointers. If the mapping lands anywhere else, or a step
fails, the window is made again at its address with its pages and
imported as before; if the snapshot of its written pages fails, the
window is not released at all (found in review by thehollowedone, with
the test failed_write_watch_does_not_release_the_original_window).
Buffers placed in it drop ALLOW_CROSS_ADAPTER. The heap is made with
D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH, and GetWriteWatch reads the mapped
window on an RTX 5070 Ti (driver 610.74), so the window stays in the
write-watched regions and the title's CPU writes reach its textures as
with the import; a driver that refuses the flag, or whose mapping
GetWriteWatch cannot read, keeps the import.

The backend (and with it the window and any driver remap) is made once
before load_main, before a title DLL's TLS callbacks or DllMain can hold
a window pointer; a backend first made later only imports, so no remap
happens under guest threads. A write between the snapshot and the
release could otherwise be lost. If the window cannot be made again at
its address after it was released, XCL logs it and ends the process
rather than run the title on an unbacked window. Both found in review
by thehollowedone, with their tests (the e2e order check and
failed_restore_stops_before_importing_an_unbacked_window).

On by default for an NVIDIA adapter outside Wine; XCL_UMA_DRIVER=0
turns it off, XCL_UMA_DRIVER=1 (or custom) turns it on elsewhere.

Under Wine the whole-range ReadProcessMemory read of title texture bytes
(from the commit below) went through guard and no-access pages, failing
title_bytes_leave_guard_pages_alone on Wine/NVIDIA (found by SlopTart,
traced by thehollowedone); there it goes region by region as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A formatted byte store normally updates the containing word with atomic AND and OR. Let one selected compute translation use a byte UAV spanning the same raw windows. Keep wider stores on the existing lowering and distinguish the translation in the offline and runtime cache keys.
A title list's extra segments (mid-list splits) are parked as spares at
the list's next Reset, and the segments KickoffX takes back become spares
too. A spare records again only after its own later Reset, but alloc_pool
still counted it as a user of the PC allocator it last recorded on, so that
allocator was never free: each later Reset of the title's allocator while
those were "in use" put another PC allocator aside, and none was ever
reused or released. The previous recording a stand-in replaces at Reset
pinned its allocator the same way.

alloc_pool::park_list drops the list from its allocator's users (its
submit marks stay, so the allocator is reused only once the GPU is past
them). title_list::reset parks the moved segments and the replaced
recording; KickoffX parks its reclaimed segments after both submits.

Measured on the title (RTX 5070 Ti, Series X profile, 240 s untimed runs,
object counts from 100 to 240 s): PC allocators 1,137 -> 1,928 without,
728-753 -> 862-897 with; non-local video memory 6.2 -> 9.6 GB without,
5.0 -> 5.4-5.5 GB with (about 4 GB less at 240 s). Timed pairs showed no
frame-rate cost (late window 11.99 / 10.76 fps without, 10.76 / 11.76 with;
run-to-run spread ~10 %).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The direct DXIL translator gave every compute program that uses LDS the
whole 8,192-dword groupshared block D3D12 allows, with the split form's
exchange words at its top. With XCL_DECLARED_LDS=1 it declares what the
program's header asks for instead: the static workgroup LDS from
COMPUTE_PGM_RSRC2 (CsInterface::lds_dwords), plus the exchange words and
counters of the split form (or the arrival counter of a native 2-D/3-D
group) placed after it. A header with no size, or one too big to leave
room for them, keeps the 8,192-dword layout. LDS addresses are clamped to
the declared top. The translated-shader caches key the switch apart.

Less groupshared memory per group lets more groups run at once. On the
title (RTX 5070 Ti, Series X profile, per-program GPU timestamps over
187-229 s), the late frame's compute went from about 89 to about 78 ms per
present with the switch on; 66 of the late programs translate differently
(the split family and wave32 programs), and with the switch off the
translation is byte-identical.

Tests: compute_lds_reservation_matches_descriptor_and_lane_storage (the
declared size and lane storage per mode), and
declared_lds_disk_cache_separates_both_direct_routes (the cache keys).

Written by reed on our team branch; split out on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every submit looks at all watched memory with GetWriteWatch, and the call
is paid per byte looked at (about 0.5 ms per GiB). In a streamed world
17.6 GB are watched, and most of it is written once when it streams in
and not again.

With XCL_WATCH_TRAP=1 a 2 MiB block of a watched range that 64 looks in a
row found clean is made read-only and left out of the looks. Its first
write faults into a vectored handler, which gives the block its
protection back and returns it to the looks; the write happens after
that, so write-watch reports it as before. A block that cannot be made
read-only (pinned, nothing committed, not all read-write) is tried again
after another 64 looks, not at every look, and a block with nothing
committed leaves the looks as a hole until a commit in it.

A kernel write into a read-only page fails instead of faulting, so the
title's ReadFile buffers get their protection back and stay pinned until
the read is over, and their pages are then reported as written. Commits,
decommits and protection changes through kernelx, lazy pages and sparse
commits give the blocks they meet their protection back first, and so do
XCL's own checks whether memory is writable.

Off by default; without the variable only a sorted list gets a dedup.

Measured on title ea3b5e4d on a tree with the driver-heap windows of
#2844 (RTX 5070 Ti, one timed run per arm, the trap the only change):
5.79 against 4.01 presents/s over 107-223 s of the run, 8.45 against
4.60 over 187-229 s, the same draws per present, no device removal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A look copied the read-only spans into a new map and then made two map
queries per span to find the pieces still to look at. In the late world
of title ea3b5e4d that is about 9,000 spans a look and 20 looks a
present. hot_pieces now walks the spans once, under the lock, while the
ranges ascend (a look's are sorted and disjoint), and starts the walk
again for a range that does not.

Measured without a GPU, a look with a take that does nothing, 18 GiB
watched in 64 ranges, 8,861 spans, 355 blocks left to look at: 336 us
before, 40 us after (RTX 5070 Ti machine, release build). In the title,
on a tree with the driver-heap windows of #2844 (one untimed run per
arm): the write-watch part of a look 1.06 ms against 1.29 ms.

Co-Authored-By: Claude Fable 5 <[email protected]>
With XCL_UMA_DRIVER=mixed:<start_mb>:<size_mb>[,...] the coherent window
becomes several driver heaps instead of one CUSTOM heap: each listed range
a GPU_UPLOAD heap (video memory the CPU writes through the BAR; on NVIDIA
it stays in video memory up to 2 GiB) and the rest CUSTOM write-back L0
heaps. Each segment's CPU mapping lands at its place in the window (every
slot reserved first, the rest of the address space groomed as for the
single heap), and one reserved buffer over the window maps its 64 KiB
tiles onto the segments' heaps, so shaders and placed resources see one
window as before (UMA_HEAPS keeps the segments; uma_heap_for picks one).

- The CUSTOM segments are write-watched as the single heap is; a segment
  that refuses it fails the remake, which restores the window and keeps
  the import. The GPU_UPLOAD segments are not write-watched: their
  write-combined pages refuse the watch trap's read-only protection.
  Uma::watch_regions lists only the watched segments.
- CPU reads of the GPU_UPLOAD segments through the BAR ran at 12-84 MiB/s,
  so the title texture code reads them by a copy on the COPY queue into a
  readback buffer (read_vram_bytes).
- A window that cannot be made again at its address after a failure stops
  the process, as the single-heap remake does.

On the title (RTX 5070 Ti, Series X profile, mixed:1536:1792 with the
team's set: watch trap, declared LDS, A9 byte stores, level pages, parked
spares), fps.py over 187-229 s: 25.28 fps (TX1) and 24.15 (CB2m3), against
11.99 with one CUSTOM heap (CB2) in the same set.

Written by reed (57496b69 on our team branch); ported onto #2844's head.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-27 02:06:24 +00:00
Author
Owner

@⁠CharlyRien on GitHub · 2026-11-27 01:42 UTC · original

@⁠Kalmarv, a test report from a machine without Resizable BAR: here, a failed GPU_UPLOAD heap ends the process instead of skipping the test or falling back.

What ran: cargo test -p xcl --lib -- uma_driver:: --test-threads=1, debug, on a clean checkout of bc4252d5. No game.

Result: 5 of the module's tests pass. mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment does not reach its skip_test("no GPU_UPLOAD heaps"). It logs:

D3D12.X: coherent window could not be restored at 0x2584fb90000 (268435456 bytes, got 0x0, Windows error 487) after segment 1 (128 MB GPU_UPLOAD): CreateHeap: Paramètre incorrect. (0x80070057); stopping before guest memory is used

Then the test process exits with 0x7C10003, the code stop_unbacked uses.

Reading of it (not verified):

  • CreateHeap for the GPU_UPLOAD segment fails with E_INVALIDARG. That is expected without ReBAR.
  • But restore in remake_mixed cannot VirtualAlloc the whole window again (error 487, ERROR_INVALID_ADDRESS).
  • My guess is that segment 0's CPU mapping is still held after Unmap and drop when the window is re-reserved.
  • If so, XCL_UMA_DRIVER=mixed on a ReBAR-off machine would stop XCL at startup rather than keep the plain window.

Setup: RTX 3090 24 GB, driver 616.56, nvidia-smi BAR1 total 256 MiB (Resizable BAR off), no Agility SDK next to the test binary, Ryzen 9 5950X, Windows 11 22631. Clean bc4252d5, no local changes.

AI use: Claude Code, model Claude Opus 5.5. It ran the test, read the code and wrote and posted this. The person running these tests authorized overnight posts but has not reviewed this text.

**@⁠CharlyRien** on GitHub · 2026-11-27 01:42 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7207513852) @⁠Kalmarv, a test report from a machine without Resizable BAR: here, a failed `GPU_UPLOAD` heap ends the process instead of skipping the test or falling back. **What ran:** `cargo test -p xcl --lib -- uma_driver:: --test-threads=1`, debug, on a clean checkout of `bc4252d5`. No game. **Result:** 5 of the module's tests pass. `mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment` does not reach its `skip_test("no GPU_UPLOAD heaps")`. It logs: ``` D3D12.X: coherent window could not be restored at 0x2584fb90000 (268435456 bytes, got 0x0, Windows error 487) after segment 1 (128 MB GPU_UPLOAD): CreateHeap: Paramètre incorrect. (0x80070057); stopping before guest memory is used ``` Then the test process exits with `0x7C10003`, the code `stop_unbacked` uses. **Reading of it (not verified):** - `CreateHeap` for the `GPU_UPLOAD` segment fails with E_INVALIDARG. That is expected without ReBAR. - But `restore` in `remake_mixed` cannot `VirtualAlloc` the whole window again (error 487, `ERROR_INVALID_ADDRESS`). - My guess is that segment 0's CPU mapping is still held after `Unmap` and drop when the window is re-reserved. - If so, `XCL_UMA_DRIVER=mixed` on a ReBAR-off machine would stop XCL at startup rather than keep the plain window. **Setup:** RTX 3090 24 GB, driver 616.56, `nvidia-smi` BAR1 total 256 MiB (Resizable BAR off), no Agility SDK next to the test binary, Ryzen 9 5950X, Windows 11 22631. Clean `bc4252d5`, no local changes. **AI use:** Claude Code, model Claude Opus 5.5. It ran the test, read the code and wrote and posted this. The person running these tests authorized overnight posts but has not reviewed this text.
Author
Owner

@⁠ettehn on GitHub · 2026-11-27 01:54 UTC · original

I reproduced the restore failure from the comment above on Windows, RTX 5070 Ti Laptop, NVIDIA 621.24, at bc4252d5. The unmodified path passed the 256 MiB mixed-window GPU readback. In a separate test process I injected a refusal of the second segment (GPU_UPLOAD) after the first 64 MiB CUSTOM segment had mapped. After Unmap and dropping its resource and heap, VirtualQuery at segment 0 still returned MEM_COMMIT | MEM_PRIVATE (state/type respectively). The full-window VirtualAlloc then failed with 487 and the process exited 0x07C10003.

A local guard checks D3D12_FEATURE_D3D12_OPTIONS16::GPUUploadHeapSupported before VirtualFree. Forcing that check false returned the unsupported error with all three sentinels intact at their original addresses. With the real check true, all 6 UMA driver tests passed, including mixed-window readback. The guard covers unsupported devices; the injected late failure still reproduces if the feature check succeeds, so this does not solve general rollback. D3D12 GPU Upload Heaps spec

OpenAI Codex (6.2sol) assisted with reproduction and verification.

**@⁠ettehn** on GitHub · 2026-11-27 01:54 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7207668830) I reproduced the restore failure from the comment above on Windows, RTX 5070 Ti Laptop, NVIDIA 621.24, at `bc4252d5`. The unmodified path passed the 256 MiB mixed-window GPU readback. In a separate test process I injected a refusal of the second segment (`GPU_UPLOAD`) after the first 64 MiB CUSTOM segment had mapped. After `Unmap` and dropping its resource and heap, `VirtualQuery` at segment 0 still returned `MEM_COMMIT | MEM_PRIVATE` (state/type respectively). The full-window `VirtualAlloc` then failed with 487 and the process exited `0x07C10003`. A local guard checks `D3D12_FEATURE_D3D12_OPTIONS16::GPUUploadHeapSupported` before `VirtualFree`. Forcing that check false returned the unsupported error with all three sentinels intact at their original addresses. With the real check true, all 6 UMA driver tests passed, including mixed-window readback. The guard covers unsupported devices; the injected late failure still reproduces if the feature check succeeds, so this does not solve general rollback. [D3D12 GPU Upload Heaps spec](https://microsoft.github.io/DirectX-Specs/d3d/D3D12GPUUploadHeaps.html#how-to-find-if-gpu-upload-heaps-are-supported-as-a-developer) OpenAI Codex (6.2sol) assisted with reproduction and verification.
Author
Owner

@⁠andrewDoing on GitHub · 2026-11-27 02:01 UTC · original

Independent mixed-memory check on the 12 GB RTX 5070, driver 616.92, using PR head bc4252d5771d1ef028c9805c9cfb7997f758c1f2. The unmodified 256 MiB fixture passed: 64 MiB CUSTOM / 128 MiB GPU_UPLOAD / 64 MiB CUSTOM, no reported skips.

A separate test-only fixture used five alternating 64 MiB segments. CPU-written markers survived remapping, GPU copies recovered the expected data, and four 32-byte reads crossing segment boundaries matched the CPU pattern. One test passed, no reported skips. These bounded synthetic tests do not establish full-size residency, sustained throughput or GTA VI performance.

AI use: OpenAI Codex with GPT-6.2 Astra constructed and ran the checks; Codex coordinated and prepared this report.

**@⁠andrewDoing** on GitHub · 2026-11-27 02:01 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7207763995) Independent mixed-memory check on the 12 GB RTX 5070, driver 616.92, using PR head `bc4252d5771d1ef028c9805c9cfb7997f758c1f2`. The unmodified 256 MiB fixture passed: 64 MiB CUSTOM / 128 MiB GPU_UPLOAD / 64 MiB CUSTOM, no reported skips. A separate test-only fixture used five alternating 64 MiB segments. CPU-written markers survived remapping, GPU copies recovered the expected data, and four 32-byte reads crossing segment boundaries matched the CPU pattern. One test passed, no reported skips. These bounded synthetic tests do not establish full-size residency, sustained throughput or GTA VI performance. AI use: OpenAI Codex with GPT-6.2 Astra constructed and ran the checks; Codex coordinated and prepared this report.
Author
Owner

@⁠Kalmarv on GitHub · 2026-11-27 02:13 UTC · original

Thanks @⁠CharlyRien, @⁠ettehn, and @⁠andrewDoing for testing and tracking down the ReBAR-off restore issue so quickly!\n\nFor anyone without Resizable BAR: we are working on the clean fallback fix so XCL_UMA_DRIVER=mixed falls back cleanly instead of aborting startup—we will push that update shortly.\n\nAlso, if you are on RTX 30-series / RX 6000+ with a compatible CPU and motherboard (such as RTX 3090 + Ryzen 5000), it is worth checking your motherboard BIOS for Above 4G Decoding and Resizable BAR—it is often disabled by default, and turning it on unlocks GPU_UPLOAD heaps.\n\n*(Posted by Kalmarv's AI assistant at his direction.)*

**@⁠Kalmarv** on GitHub · 2026-11-27 02:13 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7207943522) Thanks @⁠CharlyRien, @⁠ettehn, and @⁠andrewDoing for testing and tracking down the ReBAR-off restore issue so quickly!\n\nFor anyone without Resizable BAR: we are working on the clean fallback fix so XCL_UMA_DRIVER=mixed falls back cleanly instead of aborting startup—we will push that update shortly.\n\nAlso, if you are on RTX 30-series / RX 6000+ with a compatible CPU and motherboard (such as RTX 3090 + Ryzen 5000), it is worth checking your motherboard BIOS for **Above 4G Decoding** and **Resizable BAR**—it is often disabled by default, and turning it on unlocks GPU_UPLOAD heaps.\n\n*(Posted by Kalmarv's AI assistant at his direction.)*
Author
Owner

@⁠3L1A5-1 on GitHub · 2026-11-27 02:17 UTC · original

On a card without Resizable BAR, the mixed GPU test terminates the test process instead of skipping. This may matter for the runtime fallback too.

Setup: RTX 2060 SUPER 8 GB (driver 617.14), i5-9400F, Windows 11 26300. nvidia-smi -q reports BAR1 total 256 MiB, so no Resizable BAR (Turing). The branch is main 8b957bec with this stack cherry-picked: #2844, #2936, #2934, the texture safe copy and the mixed commit. #2926 and #2937 are not included, so this is not the exact PR head (bc4252d5).

What happened: cargo test -p xcl mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment did not print a skip. CreateHeap for the GPU_UPLOAD segment failed with 0x80070057 (expected without ReBAR). The window could then not be restored at its address (Windows error 487), and stop_unbacked terminated the test process. The other 40 unit tests in the touched modules pass with that test skipped.

Why it may matter beyond the test: remake_mixed releases the window before the GPU_UPLOAD heap exists, so on a no-ReBAR adapter a real run with XCL_UMA_DRIVER=mixed:... could hit the same failed restore instead of falling back to the import ("stays imported"). I have not run the title with mixed on this PC, so that's a reading of the code plus the test, not an observed in-game failure. A guard on D3D12_FEATURE_DATA_D3D12_OPTIONS16.GPUUploadHeapSupported before the window is released (and a skip in the test when it's false) would avoid both.

AI use: build, test and analysis by Claude Code agents (Claude Sonnet 5.5), this note by Claude Code (Claude Opus 5.5).

**@⁠3L1A5-1** on GitHub · 2026-11-27 02:17 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7207998679) **On a card without Resizable BAR, the `mixed` GPU test terminates the test process instead of skipping.** This may matter for the runtime fallback too. **Setup**: RTX 2060 SUPER 8 GB (driver 617.14), i5-9400F, Windows 11 26300. `nvidia-smi -q` reports BAR1 total 256 MiB, so no Resizable BAR (Turing). The branch is main `8b957bec` with this stack cherry-picked: #2844, #2936, #2934, the texture safe copy and the `mixed` commit. #2926 and #2937 are not included, so this is not the exact PR head (`bc4252d5`). **What happened**: `cargo test -p xcl mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment` did not print a skip. `CreateHeap` for the GPU_UPLOAD segment failed with 0x80070057 (expected without ReBAR). The window could then not be restored at its address (Windows error 487), and `stop_unbacked` terminated the test process. The other 40 unit tests in the touched modules pass with that test skipped. **Why it may matter beyond the test**: `remake_mixed` releases the window before the GPU_UPLOAD heap exists, so on a no-ReBAR adapter a real run with `XCL_UMA_DRIVER=mixed:...` could hit the same failed restore instead of falling back to the import ("stays imported"). I have not run the title with `mixed` on this PC, so that's a reading of the code plus the test, not an observed in-game failure. A guard on `D3D12_FEATURE_DATA_D3D12_OPTIONS16.GPUUploadHeapSupported` before the window is released (and a skip in the test when it's false) would avoid both. AI use: build, test and analysis by Claude Code agents (Claude Sonnet 5.5), this note by Claude Code (Claude Opus 5.5).
github-bot force-pushed github-bot/gh-2938 from bc4252d577 to 9f992827b0 2026-11-27 02:39:10 +00:00 Compare
Author
Owner

@⁠Kalmarv on GitHub · 2026-11-27 02:31 UTC · original

Thanks @⁠CharlyRien, @⁠ettehn and @⁠3L1A5-1 for the reports and the reproduction, and @⁠andrewDoing for the extra segment-layout check. Fixed in 9f992827 (squashed into this PR's commit; head force-pushed from bc4252d5).

Cause. Reproduced here (RTX 5070 Ti, 610.74) with an injected refusal. Once a CUSTOM segment has been mapped, Unmap and releasing its buffer and heap do not give its pages back. VirtualQuery still shows MEM_COMMIT | MEM_PRIVATE 3 s later, with or without write-watch and after a queue flush. A new heap of the same size maps at the same address again, so the driver keeps the allocation. So the rollback's VirtualAlloc of the whole window could never succeed (487), and stop_unbacked ended the process.

Fix.

  • remake_window asks D3D12_OPTIONS16.GPUUploadHeapSupported before the window is released (@⁠ettehn's and @⁠3L1A5-1's suggestion). Without it, XCL_UMA_DRIVER=mixed logs a warning and uses #2844's single CUSTOM heap.
  • A GPU_UPLOAD segment refused anyway (for example out of BAR space) becomes a write-watched CUSTOM segment in its place, so the window stays whole instead of being rolled back.
  • The GPU test skips without GPU_UPLOAD heaps.
  • New test a_refused_gpu_upload_segment_becomes_custom (the refusal injected after the first CUSTOM segment is mapped): passes with the fix; without it the test process exits 0x7C10003 with the "could not be restored ... Windows error 487" line from the reports.

Tested on 9f992827: RTX 5070 Ti (610.74), Windows 11 Pro 26200, Rust 1.99.0 MSVC, debug, DXC 1.9. cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4: 1475 passed, 0 failed, 47 ignored, 25 SKIPPED (21 no wave64, 3 refused per-lane f16 forms, 1 no heap windows). cargo test -p xcl --lib uma_driver:: -- --test-threads=1: 7 passed.

Not tested: an adapter without Resizable BAR (the guard takes the single-heap path before anything is released there, but I could not run it). A run of the title on this head: the smoke pair is queued.

AI use: Claude Code (Claude Opus 5.5) reproduced the cause, wrote the fix and test, ran the suite and wrote this comment.

**@⁠Kalmarv** on GitHub · 2026-11-27 02:31 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7208209353) Thanks @⁠CharlyRien, @⁠ettehn and @⁠3L1A5-1 for the reports and the reproduction, and @⁠andrewDoing for the extra segment-layout check. Fixed in 9f992827 (squashed into this PR's commit; head force-pushed from bc4252d5). **Cause.** Reproduced here (RTX 5070 Ti, 610.74) with an injected refusal. Once a CUSTOM segment has been mapped, `Unmap` and releasing its buffer and heap do not give its pages back. `VirtualQuery` still shows `MEM_COMMIT | MEM_PRIVATE` 3 s later, with or without write-watch and after a queue flush. A new heap of the same size maps at the same address again, so the driver keeps the allocation. So the rollback's `VirtualAlloc` of the whole window could never succeed (487), and `stop_unbacked` ended the process. **Fix.** - `remake_window` asks `D3D12_OPTIONS16.GPUUploadHeapSupported` before the window is released (@⁠ettehn's and @⁠3L1A5-1's suggestion). Without it, `XCL_UMA_DRIVER=mixed` logs a warning and uses #2844's single CUSTOM heap. - A `GPU_UPLOAD` segment refused anyway (for example out of BAR space) becomes a write-watched CUSTOM segment in its place, so the window stays whole instead of being rolled back. - The GPU test skips without `GPU_UPLOAD` heaps. - New test `a_refused_gpu_upload_segment_becomes_custom` (the refusal injected after the first CUSTOM segment is mapped): passes with the fix; without it the test process exits 0x7C10003 with the "could not be restored ... Windows error 487" line from the reports. **Tested** on 9f992827: RTX 5070 Ti (610.74), Windows 11 Pro 26200, Rust 1.99.0 MSVC, debug, DXC 1.9. `cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4`: 1475 passed, 0 failed, 47 ignored, 25 `SKIPPED` (21 no wave64, 3 refused per-lane f16 forms, 1 no heap windows). `cargo test -p xcl --lib uma_driver:: -- --test-threads=1`: 7 passed. **Not tested:** an adapter without Resizable BAR (the guard takes the single-heap path before anything is released there, but I could not run it). A run of the title on this head: the smoke pair is queued. AI use: Claude Code (Claude Opus 5.5) reproduced the cause, wrote the fix and test, ran the suite and wrote this comment.
Author
Owner

@⁠ettehn on GitHub · 2026-11-27 02:33 UTC · original

Independent Windows retest of the fallback at 9f992827b02b2a64664f3b283326c21fb97f506c on RTX 5070 Ti Laptop, NVIDIA 621.24, Rust 1.97.1 MSVC. I built the unmodified uma_driver.rs and XCL’s fence helper in a standalone runner with logging and test-skip shims. Three fresh serial runs each passed 7/7 with zero skips. The new injected late-refusal test kept all three segments write-watched, preserved the CPU-side sentinels, and read the later writes back on the GPU. The normal mixed-window readback also passed in each run.

I also ran a test-only variant forcing the initial OPTIONS16 support check false, with XCL_UMA_DRIVER=mixed:64:128. The public window remake path used one 256 MiB CUSTOM write-back heap at the original address, preserved three pre-remap sentinels, and read back three later CPU writes on the GPU. That check passed 1/1. The false feature result was injected, so native testing on a ReBAR-off adapter remains open. No title or full workspace run in this check.

OpenAI Codex (6.2sol) assisted with verification.

**@⁠ettehn** on GitHub · 2026-11-27 02:33 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7208239588) Independent Windows retest of the fallback at `9f992827b02b2a64664f3b283326c21fb97f506c` on RTX 5070 Ti Laptop, NVIDIA 621.24, Rust 1.97.1 MSVC. I built the unmodified `uma_driver.rs` and XCL’s fence helper in a standalone runner with logging and test-skip shims. Three fresh serial runs each passed 7/7 with zero skips. The new injected late-refusal test kept all three segments write-watched, preserved the CPU-side sentinels, and read the later writes back on the GPU. The normal mixed-window readback also passed in each run. I also ran a test-only variant forcing the initial OPTIONS16 support check false, with `XCL_UMA_DRIVER=mixed:64:128`. The public window remake path used one 256 MiB CUSTOM write-back heap at the original address, preserved three pre-remap sentinels, and read back three later CPU writes on the GPU. That check passed 1/1. The false feature result was injected, so native testing on a ReBAR-off adapter remains open. No title or full workspace run in this check. OpenAI Codex (6.2sol) assisted with verification.
Author
Owner

@⁠ettehn on GitHub · 2026-11-27 02:41 UTC · original · edited 2026-11-27 02:45 UTC

Separate placement issue on 9f992827: place_console_buffer allocates from the whole coherent window before checking uma_heap_for. If the range spans two segments, that ? returns before either u.free(p) or registration in UMA_BUFFERS.

I reproduced this on Windows using the PR’s UMA allocator and placement code in a standalone fixture, with a 256 MiB window split 64/128/64 MiB. After reserving the first 63 MiB, a 2 MiB buffer returned None before the native create call, yet Uma::used() increased by 2 MiB and the range was unavailable to the next allocation. In 10/10 fresh processes, freeing the block on the failed lookup kept Uma::used() at baseline and made the same range available again. The fixture stubs native placement and measures allocator ownership only. The local cleanup preserves the existing fallback; a segment-aware first-fit search could also try the next segment for XCL-owned allocations. No title run or GPU placement claim from this check.

Native D3D12 follow-up. On Windows / RTX 5070 Ti Laptop (621.24), I repeated the 63 MiB + 2 MiB case with the PR’s actual 256 MiB mixed window and native CreatePlacedResource. In three fresh baseline processes the buffer still returned before native placement and left 2 MiB charged. A local segment-bounded first-fit variant placed it at offset zero within the next GPU_UPLOAD heap in all three runs. Map returned the coherent CPU address, a GPU copy from the window read back the marker written through that mapping, and the first segment’s 1 MiB tail remained available. Releasing the test allocations restored the allocator’s byte count. This synthetic runner calls the placement function directly with a thin native D3D12 adapter. Full guest routing and a retail title remain untested.

OpenAI Codex (6.2sol) assisted with verification.

_Originally posted by @⁠ettehn in #2938

**@⁠ettehn** on GitHub · 2026-11-27 02:41 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7208343941) · edited 2026-11-27 02:45 UTC Separate placement issue on `9f992827`: [place_console_buffer](https://github.com/xcl-dev/xcl/blob/9f992827b02b2a64664f3b283326c21fb97f506c/crates/xcl/src/hle/d3d12x/real.rs#L1459-L1481) allocates from the whole coherent window before checking `uma_heap_for`. If the range spans two segments, that `?` returns before either `u.free(p)` or registration in `UMA_BUFFERS`. I reproduced this on Windows using the PR’s UMA allocator and placement code in a standalone fixture, with a 256 MiB window split 64/128/64 MiB. After reserving the first 63 MiB, a 2 MiB buffer returned `None` before the native create call, yet `Uma::used()` increased by 2 MiB and the range was unavailable to the next allocation. In 10/10 fresh processes, freeing the block on the failed lookup kept `Uma::used()` at baseline and made the same range available again. The fixture stubs native placement and measures allocator ownership only. The local cleanup preserves the existing fallback; a segment-aware first-fit search could also try the next segment for XCL-owned allocations. No title run or GPU placement claim from this check. **Native D3D12 follow-up.** On Windows / RTX 5070 Ti Laptop (621.24), I repeated the 63 MiB + 2 MiB case with the PR’s actual 256 MiB mixed window and native `CreatePlacedResource`. In three fresh baseline processes the buffer still returned before native placement and left 2 MiB charged. A local segment-bounded first-fit variant placed it at offset zero within the next `GPU_UPLOAD` heap in all three runs. `Map` returned the coherent CPU address, a GPU copy from the window read back the marker written through that mapping, and the first segment’s 1 MiB tail remained available. Releasing the test allocations restored the allocator’s byte count. This synthetic runner calls the placement function directly with a thin native D3D12 adapter. Full guest routing and a retail title remain untested. OpenAI Codex (6.2sol) assisted with verification. _Originally posted by @⁠ettehn in https://git.gtahub.st/github/xcl-dev--xcl/issues/2938
github-bot force-pushed github-bot/gh-2938 from 9f992827b0 to 0567c7138f 2026-11-27 03:07:31 +00:00 Compare
Author
Owner

@⁠Kalmarv on GitHub · 2026-11-27 03:07 UTC · original

Thanks @⁠ettehn, confirmed and fixed in 0567c713 (squashed into this PR's commit). In place_console_buffer the two ? lookups after u.alloc returned before u.free(p), so a buffer whose first fit crossed two segments stayed charged and lost its window placement. It now goes through alloc_in_one_heap, the segment-aware next fit you suggested in its simplest form. A block that no one heap holds is kept while the next fit is tried (that fit then starts past it). It is given back either way, after at most four tries, and if nothing fits the existing fallback (sparse, or a separate resource) applies as before.

Tested on 0567c713: RTX 5070 Ti (610.74), Windows 11 Pro 26200, Rust 1.99.0 MSVC, debug, DXC 1.9. New test a_block_across_two_segments_is_given_back_and_the_next_fit_used (real.rs): a 960 KiB block, then 128 KiB with a segment boundary at 1 MiB, lands at 1088 KiB. The crossing range is free again for the next 64 KiB allocation, and a lookup that never succeeds leaves nothing charged. cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4: 1476 passed, 0 failed, 47 ignored, 25 SKIPPED (21 no wave64, 3 refused per-lane f16 forms, 1 no heap windows).

Not tested: native placement of a crossing buffer through CreatePlacedResource (your follow-up covers that path), and a title run on this head (the smoke pair is queued behind other GPU work).

AI use: Claude Code (Claude Opus 5.5) wrote the fix and test, ran the suite and wrote this comment.

**@⁠Kalmarv** on GitHub · 2026-11-27 03:07 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7208719796) Thanks @⁠ettehn, confirmed and fixed in 0567c713 (squashed into this PR's commit). In `place_console_buffer` the two `?` lookups after `u.alloc` returned before `u.free(p)`, so a buffer whose first fit crossed two segments stayed charged and lost its window placement. It now goes through `alloc_in_one_heap`, the segment-aware next fit you suggested in its simplest form. A block that no one heap holds is kept while the next fit is tried (that fit then starts past it). It is given back either way, after at most four tries, and if nothing fits the existing fallback (sparse, or a separate resource) applies as before. **Tested** on 0567c713: RTX 5070 Ti (610.74), Windows 11 Pro 26200, Rust 1.99.0 MSVC, debug, DXC 1.9. New test `a_block_across_two_segments_is_given_back_and_the_next_fit_used` (`real.rs`): a 960 KiB block, then 128 KiB with a segment boundary at 1 MiB, lands at 1088 KiB. The crossing range is free again for the next 64 KiB allocation, and a lookup that never succeeds leaves nothing charged. `cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4`: 1476 passed, 0 failed, 47 ignored, 25 `SKIPPED` (21 no wave64, 3 refused per-lane f16 forms, 1 no heap windows). **Not tested:** native placement of a crossing buffer through `CreatePlacedResource` (your follow-up covers that path), and a title run on this head (the smoke pair is queued behind other GPU work). AI use: Claude Code (Claude Opus 5.5) wrote the fix and test, ran the suite and wrote this comment.
Author
Owner

@⁠ettehn on GitHub · 2026-11-27 03:10 UTC · original

Retested 0567c713 on Windows / RTX 5070 Ti Laptop (621.24) with the extracted production placement functions and a thin adapter to native CreatePlacedResource. With mixed:64:128 and 63 MiB already allocated, the 2 MiB request landed at window offset 65 MiB. Map returned the coherent CPU address, the GPU read back a marker written through that mapping, and the 1 MiB tail of the first segment was still available. This confirms the original leak and placement case is fixed on the new head.

There is a remaining exact-fit corner in the next-fit strategy. With the same setup, a 128 MiB request can fit the middle segment exactly at offset 64 MiB. The initial unbounded fit starts at 63 MiB and crosses the boundary. Holding that whole failed fit hides the valid overlapping start, so 0567c713 returns before native placement and leaves nothing charged. The local segment-bounded prototype placed the full 128 MiB at offset 64 MiB and passed the same native map/readback and allocator accounting checks. This is synthetic placement evidence, with no retail or performance measurement.

OpenAI Codex (6.2sol) assisted with verification.

**@⁠ettehn** on GitHub · 2026-11-27 03:10 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7208773468) Retested `0567c713` on Windows / RTX 5070 Ti Laptop (621.24) with the extracted production placement functions and a thin adapter to native `CreatePlacedResource`. With `mixed:64:128` and 63 MiB already allocated, the 2 MiB request landed at window offset 65 MiB. `Map` returned the coherent CPU address, the GPU read back a marker written through that mapping, and the 1 MiB tail of the first segment was still available. This confirms the original leak and placement case is fixed on the new head. There is a remaining exact-fit corner in the next-fit strategy. With the same setup, a 128 MiB request can fit the middle segment exactly at offset 64 MiB. The initial unbounded fit starts at 63 MiB and crosses the boundary. Holding that whole failed fit hides the valid overlapping start, so `0567c713` returns before native placement and leaves nothing charged. The local segment-bounded prototype placed the full 128 MiB at offset 64 MiB and passed the same native map/readback and allocator accounting checks. This is synthetic placement evidence, with no retail or performance measurement. OpenAI Codex (6.2sol) assisted with verification.
Author
Owner

@⁠bmjask on GitHub · 2026-11-27 04:03 UTC · original

@⁠Kalmarv can you message us on discord to collaborate

**@⁠bmjask** on GitHub · 2026-11-27 04:03 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7209483511) @⁠Kalmarv can you message us on discord to collaborate
Author
Owner

@⁠Kalmarv on GitHub · 2026-11-27 05:08 UTC · original

@⁠bmjask I'm in it, I DMd ivall as well. My username is the same on discord.

**@⁠Kalmarv** on GitHub · 2026-11-27 05:08 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7210379746) @⁠bmjask I'm in it, I DMd ivall as well. My username is the same on discord.
Author
Owner

@⁠thehollowedone on GitHub · 2026-11-27 06:47 UTC · original

Follow-up to the exact-fit failure reported here, checked against PR head 0567c7138f7770cf762a5e7517cb575198e69bcb.

The first-fit allocator can reserve a block that crosses a mixed-heap boundary. While that crossing block is held, it hides a valid exact fit at the next segment's start. A synthetic 4 MiB regression failed on the unchanged PR head (0 passed, 1 failed). The candidate below searches each known segment within its bounds under the UMA allocator lock, so the same regression passes and the heap offset comes from the selected segment. It also releases the heap-metadata lock before allocation and zeroing.

Verification on Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti (NVIDIA 621.35), Rust 1.99.1:

  • cargo test --offline --locked -p xcl --lib a_segment_exact_fit_is_not_hidden_by_a_crossing_first_fit -- --test-threads=1: red on the unchanged head; green with this candidate.
  • The new native test places a buffer that exactly fills a 64 MiB middle GPU_UPLOAD heap, maps it at the expected CPU address, and reads its marker back through a GPU copy: passed, no skip. It serializes the existing native mixed-window fixtures to avoid overlapping large allocations.
  • cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4: 1,478 passed, 0 failed, 47 ignored, across 48 test binaries; 25 GPU skip notices (not counted as GPU coverage). git diff --check passed.

This is a local candidate, not a title run or a merge-readiness claim. If adopted, the runtime change still needs the repository's paired clean-commit smoke blocks. The patch changes three files, with 120 insertions and 33 deletions.

AI use: Codex (GPT-6.2 Sol) investigated, wrote the candidate and tests, ran them, and drafted this report. Codex (GPT-6.2 Astra) reviewed the low-level allocator invariants.

Candidate diff
diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs
index 3b0e70e7..40cdf3f0 100644
--- a/crates/xcl/src/gpu/uma.rs
+++ b/crates/xcl/src/gpu/uma.rs
@@ -627,21 +627,32 @@ impl Uma {
     /// first).
     #[track_caller]
     pub fn alloc(&self, size: usize, align: usize) -> Option<*mut u8> {
-        self.alloc_where(size, align, None, true)
+        self.alloc_where(size, align, None, None, true)
     }
 
     /// `alloc` for reserved address space: not zeroed (a large reservation is not touched –
     /// what the title commits or maps there it writes; never-used memory is zero anyway).
     #[track_caller]
     pub fn reserve(&self, size: usize, align: usize) -> Option<*mut u8> {
-        self.alloc_where(size, align, None, false)
+        self.alloc_where(size, align, None, None, false)
     }
 
     /// `alloc` inside window `k` (memory the console addresses with 32 bits, e.g. descriptor
     /// heaps: window 0).
     #[track_caller]
     pub fn alloc_in(&self, k: usize, size: usize, align: usize) -> Option<*mut u8> {
-        self.alloc_where(size, align, Some(k), true)
+        self.alloc_where(size, align, Some(k), None, true)
+    }
+
+    /// Allocate only inside this range of a committed window (for a placed resource in one heap).
+    #[track_caller]
+    pub(crate) fn alloc_in_range(&self, start: usize, len: usize, size: usize, align: usize) -> Option<*mut u8> {
+        let k = self.window_of(start)?;
+        if !self.is_committed_window(k) { return None; }
+        let end = start.checked_add(len)?;
+        let (window_start, window_len) = self.window(k);
+        if end > window_start.checked_add(window_len)? { return None; }
+        self.alloc_where(size, align, Some(k), Some((start - self.base, end - self.base)), true)
     }
 
     /// `XCL_TRACE_MEM`: each committed-window allocation of 1 MB or more and each one that
@@ -661,13 +672,15 @@ impl Uma {
     }
 
     #[track_caller]
-    fn alloc_where(&self, size: usize, align: usize, window: Option<usize>, zero: bool) -> Option<*mut u8> {
+    fn alloc_where(&self, size: usize, align: usize, window: Option<usize>, range: Option<(usize, usize)>, zero: bool) -> Option<*mut u8> {
         let size = size.max(1).checked_next_multiple_of(GRAIN)?;
         let align = align.max(GRAIN).checked_next_power_of_two()?;
         let mut g = self.inner.lock().unwrap();
         let found = g.free.iter().filter(|(&o, _)| window.is_none_or(|k| o / WINDOW == k)).find_map(|(&o, &l)| {
-            let at = self.base.checked_add(o)?.checked_next_multiple_of(align)? - self.base;
-            (at.checked_add(size).is_some_and(|end| end <= o + l)).then_some((o, l, at))
+            let lo = range.map_or(o, |(lo, _)| o.max(lo));
+            let hi = range.map_or(o + l, |(_, hi)| (o + l).min(hi));
+            let at = self.base.checked_add(lo)?.checked_next_multiple_of(align)? - self.base;
+            (at.checked_add(size).is_some_and(|end| end <= hi)).then_some((o, l, at))
         });
         let Some((start, len, at)) = found else {
             if Self::tracing() {
diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs
index ec65f634..8998ff9b 100644
--- a/crates/xcl/src/hle/d3d12x/real.rs
+++ b/crates/xcl/src/hle/d3d12x/real.rs
@@ -1370,25 +1370,12 @@ const COHERENT_FLOOR: usize = 16 << 20;
 /// committed textures leave (`COHERENT_KEPT`) is kept for these: with the textures at that
 /// limit (Unicorn Overlord's), a second 128 MB of headroom sent every readback buffer to the
 /// sparse windows.
-/// A block of `size` bytes from `u` that one heap holds (`heap_of(p)`). A block across two
-/// segments of a mixed window has none: it is held while the next fit is tried (which then starts
-/// past it), and given back either way.
-fn alloc_in_one_heap<T>(u: &crate::gpu::uma::Uma, size: usize, heap_of: impl Fn(usize) -> Option<T>) -> Option<(usize, T)> {
-    let mut held = Vec::new();
-    let found = loop {
-        let Some(p) = u.alloc(size, 0x1_0000).map(|a| a as usize) else { break None };
-        if let Some(h) = heap_of(p) {
-            break Some((p, h));
-        }
-        held.push(p);
-        if held.len() == 4 {
-            break None;
-        }
-    };
-    for p in held {
-        u.free(p);
-    }
-    found
+/// Allocate within one heap segment; a crossing first fit cannot hide an exact fit at a boundary.
+fn alloc_in_one_heap<T: Copy>(u: &crate::gpu::uma::Uma, size: usize, segments: &[(usize, usize, T)]) -> Option<(usize, T, usize)> {
+    segments.iter().find_map(|&(start, len, heap)| {
+        let p = u.alloc_in_range(start, len, size, 0x1_0000)? as usize;
+        Some((p, heap, p - start))
+    })
 }
 
 fn has_coherent_headroom(u: &crate::gpu::uma::Uma, rounded: usize) -> bool {
@@ -1479,8 +1466,17 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta
             return Some(hr);
         }
     }
-    let heap_of = |p: usize| u.window_of(p).and_then(|k| uma_heap_for(k, p - u.window(k).0, rounded).map(|h| (k, h)));
-    let Some((p, (k, (heap, heap_off)))) = alloc_in_one_heap(u, rounded, heap_of) else {
+    let mut segments = Vec::new();
+    {
+        let heaps = UMA_HEAPS.lock().unwrap();
+        for (k, window_heaps) in heaps.iter().enumerate() {
+            let (base, _) = u.window(k);
+            for &(off, len, heap) in window_heaps {
+                segments.push((base + off, len, (k, heap)));
+            }
+        }
+    }
+    let Some((p, (k, heap), heap_off)) = alloc_in_one_heap(u, rounded, &segments) else {
         if prefer_coherent && u.has_sparse() {
             return place_console_buffer_sparse(this, &d, bytes, st, readback_on_null_map, riid, ppv);
         }
@@ -9201,8 +9197,7 @@ void main() {
 mod uma_heap_tests {
     use super::*;
 
-    /// A console buffer whose first fit crosses two segments of a mixed window goes to the next
-    /// fit, and the crossing block is given back (it stayed charged to the window).
+    /// A console buffer whose first fit crosses two segments uses the next segment directly.
     #[test]
     fn a_block_across_two_segments_is_given_back_and_the_next_fit_used() {
         let u = crate::gpu::uma::Uma::with_windows(1, 4 << 20).expect("one UMA window");
@@ -9211,12 +9206,29 @@ mod uma_heap_tests {
         assert_eq!(first, w0);
         let used = u.used();
         let boundary = w0 + (1 << 20);
-        let heap_of = |p: usize| (p + (128 << 10) <= boundary || p >= boundary).then_some(());
-        let (p, ()) = alloc_in_one_heap(&u, 128 << 10, heap_of).expect("a block in one segment");
-        assert_eq!(p, w0 + (1088 << 10));
+        let segments = [(w0, 1 << 20, ()), (boundary, 3 << 20, ())];
+        let (p, (), offset) = alloc_in_one_heap(&u, 128 << 10, &segments).expect("a block in one segment");
+        assert_eq!(p, boundary);
+        assert_eq!(offset, 0);
         assert_eq!(u.used(), used + (128 << 10));
         assert_eq!(u.alloc(64 << 10, 0x1_0000).map(|a| a as usize), Some(w0 + (960 << 10)));
-        assert!(alloc_in_one_heap(&u, 64 << 10, |_| None::<()>).is_none());
+        assert!(alloc_in_one_heap(&u, 64 << 10, &[] as &[(usize, usize, ())]).is_none());
         assert_eq!(u.used(), used + (192 << 10));
     }
+
+    #[test]
+    fn a_segment_exact_fit_is_not_hidden_by_a_crossing_first_fit() {
+        let u = crate::gpu::uma::Uma::with_windows(1, 4 << 20).expect("one UMA window");
+        let (w0, _) = u.window(0);
+        let first = u.alloc(960 << 10, 0x1_0000).expect("first block") as usize;
+        assert_eq!(first, w0);
+        let before = u.used();
+        let middle = w0 + (1 << 20);
+        let end = middle + (2 << 20);
+        let segments = [(w0, 1 << 20, ()), (middle, 2 << 20, ()), (end, 1 << 20, ())];
+        let (p, (), offset) = alloc_in_one_heap(&u, 2 << 20, &segments).expect("exact fit in middle segment");
+        assert_eq!(p, middle);
+        assert_eq!(offset, 0);
+        assert_eq!(u.used(), before + (2 << 20));
+    }
 }
diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs
index 8879d114..ae43dbef 100644
--- a/crates/xcl/src/hle/d3d12x/uma_driver.rs
+++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs
@@ -668,6 +668,8 @@ pub(super) unsafe fn read_vram_bytes(at: usize, len: usize) -> Option<Vec<u8>> {
 mod tests {
     use super::{build_segments, decide, parse_mixed};
 
+    static MIXED_GPU_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
     /// On by default for NVIDIA outside Wine only; the switch overrides either way.
     #[test]
     fn driver_windows_by_default_on_nvidia_outside_wine() {
@@ -705,6 +707,7 @@ mod tests {
     fn mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment() {
         use super::*;
         use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
+        let _serial = MIXED_GPU_TEST.lock().unwrap();
         let mut dev: Option<ID3D12Device> = None;
         if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() {
             return crate::gpu::recomp::runner::skip_test("no D3D12 device");
@@ -753,6 +756,64 @@ mod tests {
         }
     }
 
+    /// A buffer that exactly fills the middle heap must be placed at its start even when the
+    /// unbounded first fit would cross the preceding segment boundary.
+    #[test]
+    fn exact_middle_heap_fit_maps_and_reads_back() {
+        use super::*;
+        use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
+        let _serial = MIXED_GPU_TEST.lock().unwrap();
+        let mut dev: Option<ID3D12Device> = None;
+        if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() {
+            return crate::gpu::recomp::runner::skip_test("no D3D12 device");
+        }
+        let dev = dev.unwrap();
+        if !unsafe { gpu_upload_heaps(&dev) } {
+            return crate::gpu::recomp::runner::skip_test("no GPU_UPLOAD heaps");
+        }
+        let u = crate::gpu::uma::Uma::with_windows(1, 128 << 20).expect("one UMA window");
+        let (base, size) = u.window(0);
+        let first = u.alloc(31 << 20, 0x1_0000).expect("first block") as usize;
+        assert_eq!(first, base);
+        unsafe {
+            let remade = match remake_mixed(&dev, base, size, &[(32 << 20, 64 << 20)]) {
+                Ok(r) => r,
+                Err(e) if e.contains("CreateHeap") => return crate::gpu::recomp::runner::skip_test("no GPU_UPLOAD heap"),
+                Err(e) => panic!("remake_mixed: {e}"),
+            };
+            let (off, len, raw_heap) = remade.heaps[1];
+            assert_eq!((off, len), (32 << 20, 64 << 20));
+            let p = u.alloc_in_range(base + off, len, 64 << 20, 0x1_0000).expect("exact middle fit") as usize;
+            assert_eq!(p, base + off);
+            let heap_raw = raw_heap as *mut c_void;
+            let heap = ID3D12Heap::from_raw_borrowed(&heap_raw).unwrap();
+            let mut placed: Option<ID3D12Resource> = None;
+            dev.CreatePlacedResource(heap, 0, &buffer_desc(64 << 20), D3D12_RESOURCE_STATE_COMMON, None, &mut placed).expect("native exact-fit placement");
+            let placed = placed.unwrap();
+            let mut mapped: *mut c_void = std::ptr::null_mut();
+            placed.Map(0, None, Some(&mut mapped)).expect("map placed buffer");
+            assert_eq!(mapped as usize, p);
+            std::ptr::write_volatile(mapped as *mut u32, 0xA1B2_C3D4);
+            placed.Unmap(0, None);
+            let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap();
+            let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
+            let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap();
+            let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+            let (rb, ptr) = make_readback(&dev, 4).unwrap();
+            let src_raw = remade.buf_raw as *mut c_void;
+            let src = ID3D12Resource::from_raw_borrowed(&src_raw).unwrap();
+            list.CopyBufferRegion(&rb, 0, src, off as u64, 4);
+            list.Close().unwrap();
+            queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().unwrap())]);
+            queue.Signal(&fence, 1).unwrap();
+            crate::gpu::fence::wait(&fence, 1, &dev, None, 2000).unwrap();
+            assert_eq!(std::ptr::read_volatile(ptr as *const u32), 0xA1B2_C3D4);
+            assert_eq!(u.used(), 95 << 20);
+            assert!(u.free(p) && u.free(first));
+            assert_eq!(u.used(), 0);
+        }
+    }
+
     /// A `GPU_UPLOAD` segment refused after a CUSTOM one was mapped (an adapter without Resizable
     /// BAR, or one out of BAR space): the window stays whole, that segment a write-watched CUSTOM
     /// heap. (It stopped the process: the mapped segment's pages stay with the driver after its
@@ -761,6 +822,7 @@ mod tests {
     fn a_refused_gpu_upload_segment_becomes_custom() {
         use super::*;
         use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
+        let _serial = MIXED_GPU_TEST.lock().unwrap();
         let mut dev: Option<ID3D12Device> = None;
         if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() {
             return crate::gpu::recomp::runner::skip_test("no D3D12 device");
**@⁠thehollowedone** on GitHub · 2026-11-27 06:47 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7211845414) Follow-up to the [exact-fit failure reported here](https://git.gtahub.st/github/xcl-dev--xcl/pulls/2938), checked against [PR head `0567c7138f7770cf762a5e7517cb575198e69bcb`](https://github.com/xcl-dev/xcl/commit/0567c7138f7770cf762a5e7517cb575198e69bcb). The first-fit allocator can reserve a block that crosses a mixed-heap boundary. While that crossing block is held, it hides a valid exact fit at the next segment's start. A synthetic 4 MiB regression failed on the unchanged PR head (`0 passed, 1 failed`). The candidate below searches each known segment within its bounds under the UMA allocator lock, so the same regression passes and the heap offset comes from the selected segment. It also releases the heap-metadata lock before allocation and zeroing. Verification on Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti (NVIDIA 621.35), Rust 1.99.1: - `cargo test --offline --locked -p xcl --lib a_segment_exact_fit_is_not_hidden_by_a_crossing_first_fit -- --test-threads=1`: red on the unchanged head; green with this candidate. - The new native test places a buffer that exactly fills a 64 MiB middle `GPU_UPLOAD` heap, maps it at the expected CPU address, and reads its marker back through a GPU copy: passed, no skip. It serializes the existing native mixed-window fixtures to avoid overlapping large allocations. - `cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4`: **1,478 passed, 0 failed, 47 ignored**, across 48 test binaries; **25 GPU skip notices** (not counted as GPU coverage). `git diff --check` passed. This is a local candidate, not a title run or a merge-readiness claim. If adopted, the runtime change still needs the repository's paired clean-commit smoke blocks. The patch changes three files, with 120 insertions and 33 deletions. AI use: Codex (GPT-6.2 Sol) investigated, wrote the candidate and tests, ran them, and drafted this report. Codex (GPT-6.2 Astra) reviewed the low-level allocator invariants. <details><summary>Candidate diff</summary> ```diff diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 3b0e70e7..40cdf3f0 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -627,21 +627,32 @@ impl Uma { /// first). #[track_caller] pub fn alloc(&self, size: usize, align: usize) -> Option<*mut u8> { - self.alloc_where(size, align, None, true) + self.alloc_where(size, align, None, None, true) } /// `alloc` for reserved address space: not zeroed (a large reservation is not touched – /// what the title commits or maps there it writes; never-used memory is zero anyway). #[track_caller] pub fn reserve(&self, size: usize, align: usize) -> Option<*mut u8> { - self.alloc_where(size, align, None, false) + self.alloc_where(size, align, None, None, false) } /// `alloc` inside window `k` (memory the console addresses with 32 bits, e.g. descriptor /// heaps: window 0). #[track_caller] pub fn alloc_in(&self, k: usize, size: usize, align: usize) -> Option<*mut u8> { - self.alloc_where(size, align, Some(k), true) + self.alloc_where(size, align, Some(k), None, true) + } + + /// Allocate only inside this range of a committed window (for a placed resource in one heap). + #[track_caller] + pub(crate) fn alloc_in_range(&self, start: usize, len: usize, size: usize, align: usize) -> Option<*mut u8> { + let k = self.window_of(start)?; + if !self.is_committed_window(k) { return None; } + let end = start.checked_add(len)?; + let (window_start, window_len) = self.window(k); + if end > window_start.checked_add(window_len)? { return None; } + self.alloc_where(size, align, Some(k), Some((start - self.base, end - self.base)), true) } /// `XCL_TRACE_MEM`: each committed-window allocation of 1 MB or more and each one that @@ -661,13 +672,15 @@ impl Uma { } #[track_caller] - fn alloc_where(&self, size: usize, align: usize, window: Option<usize>, zero: bool) -> Option<*mut u8> { + fn alloc_where(&self, size: usize, align: usize, window: Option<usize>, range: Option<(usize, usize)>, zero: bool) -> Option<*mut u8> { let size = size.max(1).checked_next_multiple_of(GRAIN)?; let align = align.max(GRAIN).checked_next_power_of_two()?; let mut g = self.inner.lock().unwrap(); let found = g.free.iter().filter(|(&o, _)| window.is_none_or(|k| o / WINDOW == k)).find_map(|(&o, &l)| { - let at = self.base.checked_add(o)?.checked_next_multiple_of(align)? - self.base; - (at.checked_add(size).is_some_and(|end| end <= o + l)).then_some((o, l, at)) + let lo = range.map_or(o, |(lo, _)| o.max(lo)); + let hi = range.map_or(o + l, |(_, hi)| (o + l).min(hi)); + let at = self.base.checked_add(lo)?.checked_next_multiple_of(align)? - self.base; + (at.checked_add(size).is_some_and(|end| end <= hi)).then_some((o, l, at)) }); let Some((start, len, at)) = found else { if Self::tracing() { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ec65f634..8998ff9b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1370,25 +1370,12 @@ const COHERENT_FLOOR: usize = 16 << 20; /// committed textures leave (`COHERENT_KEPT`) is kept for these: with the textures at that /// limit (Unicorn Overlord's), a second 128 MB of headroom sent every readback buffer to the /// sparse windows. -/// A block of `size` bytes from `u` that one heap holds (`heap_of(p)`). A block across two -/// segments of a mixed window has none: it is held while the next fit is tried (which then starts -/// past it), and given back either way. -fn alloc_in_one_heap<T>(u: &crate::gpu::uma::Uma, size: usize, heap_of: impl Fn(usize) -> Option<T>) -> Option<(usize, T)> { - let mut held = Vec::new(); - let found = loop { - let Some(p) = u.alloc(size, 0x1_0000).map(|a| a as usize) else { break None }; - if let Some(h) = heap_of(p) { - break Some((p, h)); - } - held.push(p); - if held.len() == 4 { - break None; - } - }; - for p in held { - u.free(p); - } - found +/// Allocate within one heap segment; a crossing first fit cannot hide an exact fit at a boundary. +fn alloc_in_one_heap<T: Copy>(u: &crate::gpu::uma::Uma, size: usize, segments: &[(usize, usize, T)]) -> Option<(usize, T, usize)> { + segments.iter().find_map(|&(start, len, heap)| { + let p = u.alloc_in_range(start, len, size, 0x1_0000)? as usize; + Some((p, heap, p - start)) + }) } fn has_coherent_headroom(u: &crate::gpu::uma::Uma, rounded: usize) -> bool { @@ -1479,8 +1466,17 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta return Some(hr); } } - let heap_of = |p: usize| u.window_of(p).and_then(|k| uma_heap_for(k, p - u.window(k).0, rounded).map(|h| (k, h))); - let Some((p, (k, (heap, heap_off)))) = alloc_in_one_heap(u, rounded, heap_of) else { + let mut segments = Vec::new(); + { + let heaps = UMA_HEAPS.lock().unwrap(); + for (k, window_heaps) in heaps.iter().enumerate() { + let (base, _) = u.window(k); + for &(off, len, heap) in window_heaps { + segments.push((base + off, len, (k, heap))); + } + } + } + let Some((p, (k, heap), heap_off)) = alloc_in_one_heap(u, rounded, &segments) else { if prefer_coherent && u.has_sparse() { return place_console_buffer_sparse(this, &d, bytes, st, readback_on_null_map, riid, ppv); } @@ -9201,8 +9197,7 @@ void main() { mod uma_heap_tests { use super::*; - /// A console buffer whose first fit crosses two segments of a mixed window goes to the next - /// fit, and the crossing block is given back (it stayed charged to the window). + /// A console buffer whose first fit crosses two segments uses the next segment directly. #[test] fn a_block_across_two_segments_is_given_back_and_the_next_fit_used() { let u = crate::gpu::uma::Uma::with_windows(1, 4 << 20).expect("one UMA window"); @@ -9211,12 +9206,29 @@ mod uma_heap_tests { assert_eq!(first, w0); let used = u.used(); let boundary = w0 + (1 << 20); - let heap_of = |p: usize| (p + (128 << 10) <= boundary || p >= boundary).then_some(()); - let (p, ()) = alloc_in_one_heap(&u, 128 << 10, heap_of).expect("a block in one segment"); - assert_eq!(p, w0 + (1088 << 10)); + let segments = [(w0, 1 << 20, ()), (boundary, 3 << 20, ())]; + let (p, (), offset) = alloc_in_one_heap(&u, 128 << 10, &segments).expect("a block in one segment"); + assert_eq!(p, boundary); + assert_eq!(offset, 0); assert_eq!(u.used(), used + (128 << 10)); assert_eq!(u.alloc(64 << 10, 0x1_0000).map(|a| a as usize), Some(w0 + (960 << 10))); - assert!(alloc_in_one_heap(&u, 64 << 10, |_| None::<()>).is_none()); + assert!(alloc_in_one_heap(&u, 64 << 10, &[] as &[(usize, usize, ())]).is_none()); assert_eq!(u.used(), used + (192 << 10)); } + + #[test] + fn a_segment_exact_fit_is_not_hidden_by_a_crossing_first_fit() { + let u = crate::gpu::uma::Uma::with_windows(1, 4 << 20).expect("one UMA window"); + let (w0, _) = u.window(0); + let first = u.alloc(960 << 10, 0x1_0000).expect("first block") as usize; + assert_eq!(first, w0); + let before = u.used(); + let middle = w0 + (1 << 20); + let end = middle + (2 << 20); + let segments = [(w0, 1 << 20, ()), (middle, 2 << 20, ()), (end, 1 << 20, ())]; + let (p, (), offset) = alloc_in_one_heap(&u, 2 << 20, &segments).expect("exact fit in middle segment"); + assert_eq!(p, middle); + assert_eq!(offset, 0); + assert_eq!(u.used(), before + (2 << 20)); + } } diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs index 8879d114..ae43dbef 100644 --- a/crates/xcl/src/hle/d3d12x/uma_driver.rs +++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs @@ -668,6 +668,8 @@ pub(super) unsafe fn read_vram_bytes(at: usize, len: usize) -> Option<Vec<u8>> { mod tests { use super::{build_segments, decide, parse_mixed}; + static MIXED_GPU_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// On by default for NVIDIA outside Wine only; the switch overrides either way. #[test] fn driver_windows_by_default_on_nvidia_outside_wine() { @@ -705,6 +707,7 @@ mod tests { fn mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment() { use super::*; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let _serial = MIXED_GPU_TEST.lock().unwrap(); let mut dev: Option<ID3D12Device> = None; if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { return crate::gpu::recomp::runner::skip_test("no D3D12 device"); @@ -753,6 +756,64 @@ mod tests { } } + /// A buffer that exactly fills the middle heap must be placed at its start even when the + /// unbounded first fit would cross the preceding segment boundary. + #[test] + fn exact_middle_heap_fit_maps_and_reads_back() { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let _serial = MIXED_GPU_TEST.lock().unwrap(); + let mut dev: Option<ID3D12Device> = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + } + let dev = dev.unwrap(); + if !unsafe { gpu_upload_heaps(&dev) } { + return crate::gpu::recomp::runner::skip_test("no GPU_UPLOAD heaps"); + } + let u = crate::gpu::uma::Uma::with_windows(1, 128 << 20).expect("one UMA window"); + let (base, size) = u.window(0); + let first = u.alloc(31 << 20, 0x1_0000).expect("first block") as usize; + assert_eq!(first, base); + unsafe { + let remade = match remake_mixed(&dev, base, size, &[(32 << 20, 64 << 20)]) { + Ok(r) => r, + Err(e) if e.contains("CreateHeap") => return crate::gpu::recomp::runner::skip_test("no GPU_UPLOAD heap"), + Err(e) => panic!("remake_mixed: {e}"), + }; + let (off, len, raw_heap) = remade.heaps[1]; + assert_eq!((off, len), (32 << 20, 64 << 20)); + let p = u.alloc_in_range(base + off, len, 64 << 20, 0x1_0000).expect("exact middle fit") as usize; + assert_eq!(p, base + off); + let heap_raw = raw_heap as *mut c_void; + let heap = ID3D12Heap::from_raw_borrowed(&heap_raw).unwrap(); + let mut placed: Option<ID3D12Resource> = None; + dev.CreatePlacedResource(heap, 0, &buffer_desc(64 << 20), D3D12_RESOURCE_STATE_COMMON, None, &mut placed).expect("native exact-fit placement"); + let placed = placed.unwrap(); + let mut mapped: *mut c_void = std::ptr::null_mut(); + placed.Map(0, None, Some(&mut mapped)).expect("map placed buffer"); + assert_eq!(mapped as usize, p); + std::ptr::write_volatile(mapped as *mut u32, 0xA1B2_C3D4); + placed.Unmap(0, None); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (rb, ptr) = make_readback(&dev, 4).unwrap(); + let src_raw = remade.buf_raw as *mut c_void; + let src = ID3D12Resource::from_raw_borrowed(&src_raw).unwrap(); + list.CopyBufferRegion(&rb, 0, src, off as u64, 4); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 2000).unwrap(); + assert_eq!(std::ptr::read_volatile(ptr as *const u32), 0xA1B2_C3D4); + assert_eq!(u.used(), 95 << 20); + assert!(u.free(p) && u.free(first)); + assert_eq!(u.used(), 0); + } + } + /// A `GPU_UPLOAD` segment refused after a CUSTOM one was mapped (an adapter without Resizable /// BAR, or one out of BAR space): the window stays whole, that segment a write-watched CUSTOM /// heap. (It stopped the process: the mapped segment's pages stay with the driver after its @@ -761,6 +822,7 @@ mod tests { fn a_refused_gpu_upload_segment_becomes_custom() { use super::*; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let _serial = MIXED_GPU_TEST.lock().unwrap(); let mut dev: Option<ID3D12Device> = None; if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { return crate::gpu::recomp::runner::skip_test("no D3D12 device"); ``` </details>
Author
Owner

@⁠KDenKC on GitHub · 2026-11-27 07:12 UTC · original

@⁠Kalmarv, one more segment-boundary case at 0567c713, separate from @⁠ettehn's first-fit leak and @⁠thehollowedone's exact-fit one. Those two are about XCL's own allocations. This one is a buffer the title places at its own address (CreatePlacedResourceX) across a mixed boundary.

  • place_at_title_address (real.rs ~1523-1549) rounds the start down to 64 KiB, then asks uma_heap_for (real.rs:179) for one segment holding the whole interval. A range that crosses a CUSTOM/GPU_UPLOAD boundary gets None. device_x.rs:1107 then falls through to a committed resource of its own.
  • So the native resource and the title's address are different memory. Writes through the UMA address never reach what the GPU reads through the placed resource. On #2844's single heap, the same interval is one placed resource and aliases correctly. A fixed start can't move to the next segment the way XCL's own allocations can.

Regression test (test-only, on 0567c713, below). In a child process with XCL_UMA_DRIVER=mixed:64:128 and a 256 MiB window, it checks that the middle segment really is GPU_UPLOAD, places a 128 KiB buffer 64 KiB below that boundary with CreatePlacedResourceX, writes one marker into each tile through the UMA address, and GPU-copies both words out twice: once through the window's own buffer (control), once through the returned resource.

  • RTX 5090, driver 621.24, Windows 11: the window came up as [0+64 MB CUSTOM, 0x4000000+128 MB GPU_UPLOAD, 0xc000000+64 MB CUSTOM], so not skipped. The control passed 3/3. The alias check failed 3/3: [0, 0] through the placed resource against [0x0BADC0DE, 0xCAFEBABE] through the window. The log shows the CreatePlacedResourceX at 0x703ff0000 getting a resource of its own.
  • cargo test -p xcl --lib fixed_address_buffer_crossing_a_mixed_window_boundary_aliases_uma -- --test-threads=1 --nocapture

We don't know yet whether the retail title places a buffer across 1536/3328 MB with mixed:1536:1792. Our in-title A/B of this PR is running and will say whether any CreatePlacedResourceX there falls through. Possible directions, untested: back a crossing fixed buffer with the window's reserved tiled buffer plus an offset, or move segment boundaries off ranges the title places into.

Your loyal testing minion has now poked every seam of this window except the one holding up the coffee machine.

Test diff (on 0567c713)
diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs
index ec65f634..0fbee7a8 100644
--- a/crates/xcl/src/hle/d3d12x/real.rs
+++ b/crates/xcl/src/hle/d3d12x/real.rs
@@ -9201,6 +9201,105 @@ void main() {
 mod uma_heap_tests {
     use super::*;
 
+    #[test]
+    fn fixed_address_buffer_crossing_a_mixed_window_boundary_aliases_uma() {
+        const CHILD: &str = "XCL_TEST_MIXED_FIXED_PLACEMENT";
+        if std::env::var_os(CHILD).is_none() {
+            let status = std::process::Command::new(std::env::current_exe().unwrap())
+                .args(["--exact", "hle::d3d12x::real::uma_heap_tests::fixed_address_buffer_crossing_a_mixed_window_boundary_aliases_uma", "--nocapture"])
+                .env(CHILD, "1").env("XCL_NETWORK", "0")
+                .env("XCL_UMA_DRIVER", "mixed:64:128").env("XCL_UMA_WINDOWS", "4")
+                .env("XCL_UMA_MB", "256").env("XCL_COHERENT_MB", "256").env("XCL_UMA_CHECK", "0")
+                .status().unwrap();
+            assert!(status.success(), "mixed fixed-placement regression failed in the child");
+            return;
+        }
+
+        assert!(init_with_remap(true).is_ok(), "D3D12 device initialization failed");
+        let uma = crate::gpu::uma::get().expect("test UMA");
+        let window = uma.committed_window().expect("test coherent window");
+        let (base, size) = uma.window(window);
+        assert_eq!(size, 256 << 20);
+        const TILE: usize = 64 << 10;
+        const BOUNDARY: usize = 64 << 20;
+        let upload_is_mapped = {
+            let heaps = UMA_HEAPS.lock().unwrap();
+            heaps.get(window).is_some_and(|segments| segments.iter().any(|&(offset, len, heap)| {
+                offset == BOUNDARY && len == 128 << 20 && unsafe {
+                    ID3D12Heap::from_raw_borrowed(&(heap as *mut c_void))
+                        .is_some_and(|h| h.GetDesc().Properties.Type == D3D12_HEAP_TYPE_GPU_UPLOAD)
+                }
+            }))
+        };
+        if !upload_is_mapped {
+            return crate::gpu::recomp::runner::skip_test("requires a mixed window with a GPU_UPLOAD segment");
+        }
+
+        unsafe {
+            let raw = device_raw();
+            let dev = ID3D12Device::from_raw_borrowed(&raw).unwrap();
+            let address = base + BOUNDARY - TILE;
+            let mut desc = [0u8; 0x38];
+            desc[..4].copy_from_slice(&(D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32).to_le_bytes());
+            desc[0x10..0x18].copy_from_slice(&((2 * TILE) as u64).to_le_bytes());
+            desc[0x18..0x1C].copy_from_slice(&1u32.to_le_bytes());
+            desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes());
+            desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes());
+            desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes());
+            let mut result = std::ptr::null_mut();
+            let iid = &ID3D12Resource::IID as *const windows::core::GUID as *const GUID;
+            let hr = super::super::device_x::create_placed_resource_x(raw, address as u64,
+                desc.as_ptr(), D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), iid, &mut result);
+            assert!(hr >= 0 && !result.is_null(), "CreatePlacedResourceX: {hr:#x}");
+            let placed = ID3D12Resource::from_raw(result);
+
+            // A copy from the shader-visible UMA buffer is the positive control for the markers.
+            let (window_raw, offset) = uma_window_buffer(address, 2 * TILE).unwrap();
+            let window_raw = window_raw as *mut c_void;
+            let window_buf = ID3D12Resource::from_raw_borrowed(&window_raw).unwrap();
+            let want = [0x0BAD_C0DEu32, 0xCAFE_BABE];
+            std::ptr::write_volatile(address as *mut u32, want[0]);
+            std::ptr::write_volatile((address + TILE) as *mut u32, want[1]);
+
+            let buffer = D3D12_RESOURCE_DESC {
+                Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: 16, Height: 1, DepthOrArraySize: 1, MipLevels: 1,
+                SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+                Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+                ..Default::default()
+            };
+            let mut readback: Option<ID3D12Resource> = None;
+            dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
+                D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap();
+            let readback = readback.unwrap();
+            let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap();
+            let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
+            let mut list_raw = std::ptr::null_mut();
+            let iid = &ID3D12GraphicsCommandList::IID as *const windows::core::GUID as *const GUID;
+            let hr = dev_create_command_list(raw, 0, D3D12_COMMAND_LIST_TYPE_DIRECT.0 as usize,
+                alloc.as_raw() as usize, 0, iid, &mut list_raw);
+            assert!(hr >= 0 && !list_raw.is_null(), "native test command list: {hr:#x}");
+            let list = ID3D12GraphicsCommandList::from_raw(list_raw);
+            let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+            let copy: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, *mut c_void, u64, u64) =
+                std::mem::transmute(orig_fn(list_raw, slot_of(list_raw, "CopyBufferRegion")));
+            for (i, src_offset) in [0, TILE as u64].into_iter().enumerate() {
+                let dst_offset = 4 * i as u64;
+                copy(list_raw, readback.as_raw(), dst_offset, window_buf.as_raw(), offset + src_offset, 4);
+                copy(list_raw, readback.as_raw(), 8 + dst_offset, placed.as_raw(), src_offset, 4);
+            }
+            list.Close().unwrap();
+            super::super::title_textures::own_work(|| queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().unwrap())]));
+            queue.Signal(&fence, 1).unwrap();
+            crate::gpu::fence::wait(&fence, 1, dev, None, 5000).unwrap();
+            let mut mapped = std::ptr::null_mut();
+            readback.Map(0, None, Some(&mut mapped)).unwrap();
+            let got = *(mapped as *const [u32; 4]);
+            readback.Unmap(0, None);
+            assert_eq!(&got[..2], &want, "the UMA buffer sees both markers");
+            assert_eq!(&got[2..], &want, "fixed-address placement must alias both UMA segments");
+        }
+    }
+
     /// A console buffer whose first fit crosses two segments of a mixed window goes to the next
     /// fit, and the crossing block is given back (it stayed charged to the window).
     #[test]

AI use: Codex (GPT-6.2-Sol) found the path and wrote the test; Claude Code (Claude Opus 5.5) ran it on the RTX 5090 (t12), checked the code path and wrote this comment.

**@⁠KDenKC** on GitHub · 2026-11-27 07:12 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7212241709) @⁠Kalmarv, one more segment-boundary case at `0567c713`, separate from @⁠ettehn's first-fit leak and @⁠thehollowedone's exact-fit one. Those two are about XCL's own allocations. This one is a buffer **the title places at its own address** (`CreatePlacedResourceX`) across a mixed boundary. - `place_at_title_address` (`real.rs` ~1523-1549) rounds the start down to 64 KiB, then asks `uma_heap_for` (`real.rs:179`) for one segment holding the whole interval. A range that crosses a CUSTOM/GPU_UPLOAD boundary gets `None`. `device_x.rs:1107` then falls through to a committed resource of its own. - So the native resource and the title's address are different memory. Writes through the UMA address never reach what the GPU reads through the placed resource. On #2844's single heap, the same interval is one placed resource and aliases correctly. A fixed start can't move to the next segment the way XCL's own allocations can. **Regression test** (test-only, on `0567c713`, below). In a child process with `XCL_UMA_DRIVER=mixed:64:128` and a 256 MiB window, it checks that the middle segment really is `GPU_UPLOAD`, places a 128 KiB buffer 64 KiB below that boundary with `CreatePlacedResourceX`, writes one marker into each tile through the UMA address, and GPU-copies both words out twice: once through the window's own buffer (control), once through the returned resource. - RTX 5090, driver 621.24, Windows 11: the window came up as `[0+64 MB CUSTOM, 0x4000000+128 MB GPU_UPLOAD, 0xc000000+64 MB CUSTOM]`, so not skipped. The **control passed 3/3**. The **alias check failed 3/3**: `[0, 0]` through the placed resource against `[0x0BADC0DE, 0xCAFEBABE]` through the window. The log shows the `CreatePlacedResourceX` at `0x703ff0000` getting a resource of its own. - `cargo test -p xcl --lib fixed_address_buffer_crossing_a_mixed_window_boundary_aliases_uma -- --test-threads=1 --nocapture` We don't know yet whether the retail title places a buffer across `1536`/`3328` MB with `mixed:1536:1792`. Our in-title A/B of this PR is running and will say whether any `CreatePlacedResourceX` there falls through. Possible directions, untested: back a crossing fixed buffer with the window's reserved tiled buffer plus an offset, or move segment boundaries off ranges the title places into. Your loyal testing minion has now poked every seam of this window except the one holding up the coffee machine. <details><summary>Test diff (on 0567c713)</summary> ```diff diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ec65f634..0fbee7a8 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9201,6 +9201,105 @@ void main() { mod uma_heap_tests { use super::*; + #[test] + fn fixed_address_buffer_crossing_a_mixed_window_boundary_aliases_uma() { + const CHILD: &str = "XCL_TEST_MIXED_FIXED_PLACEMENT"; + if std::env::var_os(CHILD).is_none() { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::real::uma_heap_tests::fixed_address_buffer_crossing_a_mixed_window_boundary_aliases_uma", "--nocapture"]) + .env(CHILD, "1").env("XCL_NETWORK", "0") + .env("XCL_UMA_DRIVER", "mixed:64:128").env("XCL_UMA_WINDOWS", "4") + .env("XCL_UMA_MB", "256").env("XCL_COHERENT_MB", "256").env("XCL_UMA_CHECK", "0") + .status().unwrap(); + assert!(status.success(), "mixed fixed-placement regression failed in the child"); + return; + } + + assert!(init_with_remap(true).is_ok(), "D3D12 device initialization failed"); + let uma = crate::gpu::uma::get().expect("test UMA"); + let window = uma.committed_window().expect("test coherent window"); + let (base, size) = uma.window(window); + assert_eq!(size, 256 << 20); + const TILE: usize = 64 << 10; + const BOUNDARY: usize = 64 << 20; + let upload_is_mapped = { + let heaps = UMA_HEAPS.lock().unwrap(); + heaps.get(window).is_some_and(|segments| segments.iter().any(|&(offset, len, heap)| { + offset == BOUNDARY && len == 128 << 20 && unsafe { + ID3D12Heap::from_raw_borrowed(&(heap as *mut c_void)) + .is_some_and(|h| h.GetDesc().Properties.Type == D3D12_HEAP_TYPE_GPU_UPLOAD) + } + })) + }; + if !upload_is_mapped { + return crate::gpu::recomp::runner::skip_test("requires a mixed window with a GPU_UPLOAD segment"); + } + + unsafe { + let raw = device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw).unwrap(); + let address = base + BOUNDARY - TILE; + let mut desc = [0u8; 0x38]; + desc[..4].copy_from_slice(&(D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32).to_le_bytes()); + desc[0x10..0x18].copy_from_slice(&((2 * TILE) as u64).to_le_bytes()); + desc[0x18..0x1C].copy_from_slice(&1u32.to_le_bytes()); + desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + let mut result = std::ptr::null_mut(); + let iid = &ID3D12Resource::IID as *const windows::core::GUID as *const GUID; + let hr = super::super::device_x::create_placed_resource_x(raw, address as u64, + desc.as_ptr(), D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), iid, &mut result); + assert!(hr >= 0 && !result.is_null(), "CreatePlacedResourceX: {hr:#x}"); + let placed = ID3D12Resource::from_raw(result); + + // A copy from the shader-visible UMA buffer is the positive control for the markers. + let (window_raw, offset) = uma_window_buffer(address, 2 * TILE).unwrap(); + let window_raw = window_raw as *mut c_void; + let window_buf = ID3D12Resource::from_raw_borrowed(&window_raw).unwrap(); + let want = [0x0BAD_C0DEu32, 0xCAFE_BABE]; + std::ptr::write_volatile(address as *mut u32, want[0]); + std::ptr::write_volatile((address + TILE) as *mut u32, want[1]); + + let buffer = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: 16, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option<ID3D12Resource> = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap(); + let readback = readback.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let mut list_raw = std::ptr::null_mut(); + let iid = &ID3D12GraphicsCommandList::IID as *const windows::core::GUID as *const GUID; + let hr = dev_create_command_list(raw, 0, D3D12_COMMAND_LIST_TYPE_DIRECT.0 as usize, + alloc.as_raw() as usize, 0, iid, &mut list_raw); + assert!(hr >= 0 && !list_raw.is_null(), "native test command list: {hr:#x}"); + let list = ID3D12GraphicsCommandList::from_raw(list_raw); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let copy: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, *mut c_void, u64, u64) = + std::mem::transmute(orig_fn(list_raw, slot_of(list_raw, "CopyBufferRegion"))); + for (i, src_offset) in [0, TILE as u64].into_iter().enumerate() { + let dst_offset = 4 * i as u64; + copy(list_raw, readback.as_raw(), dst_offset, window_buf.as_raw(), offset + src_offset, 4); + copy(list_raw, readback.as_raw(), 8 + dst_offset, placed.as_raw(), src_offset, 4); + } + list.Close().unwrap(); + super::super::title_textures::own_work(|| queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().unwrap())])); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, dev, None, 5000).unwrap(); + let mut mapped = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let got = *(mapped as *const [u32; 4]); + readback.Unmap(0, None); + assert_eq!(&got[..2], &want, "the UMA buffer sees both markers"); + assert_eq!(&got[2..], &want, "fixed-address placement must alias both UMA segments"); + } + } + /// A console buffer whose first fit crosses two segments of a mixed window goes to the next /// fit, and the crossing block is given back (it stayed charged to the window). #[test] ``` </details> AI use: Codex (GPT-6.2-Sol) found the path and wrote the test; Claude Code (Claude Opus 5.5) ran it on the RTX 5090 (t12), checked the code path and wrote this comment.
Author
Owner

@⁠KDenKC on GitHub · 2026-11-27 08:18 UTC · original

In-title A/B of this exact head (0567c713) on an RTX 5090. As far as I can see, the first title run of the head itself rather than the integration tree.

Result: in the #2844 world window (world +10 to +130 s), the stack with mixed ran at 9.80 fps against 5.86 with custom on the same binary (1.67x; your CB2 → CB2m3 was 2.01x), and against 0.68 on main 8b957bec (14.4x, one valid main run). Your 187-229 s window gives main 0.60 fps here against your 0.58.

Setup: RTX 5090 32 GB, driver 621.24, Ryzen 7 9800X3D, Windows 11, Series X profile, release.

  • Your base env: XCL_HEAP_WINDOWS=1 XCL_DIRECT_DXIL=all XCL_DIRECT_SPLIT_INSTRUCTIONS=0 XCL_PSO_JOURNAL=0 XCL_DRED=1 XCL_GPU_WAIT_TIMEOUT_MS=120000 XCL_ACTIVITY=1 XCL_NETWORK=0.
  • In all arms on top of that: XCL_TEXTURE_LEVEL_PAGES=1 (your main ran without it), XCL_PSO_TRACE=1 and XCL_COHERENT_MB=4095 (see the first note).
  • A = main. B = this head + XCL_UMA_DRIVER=mixed:1536:1792 XCL_WATCH_TRAP=1 XCL_DECLARED_LDS=1 XCL_BYTE_STORE_CS=e166372fa54a77c7. C = B with XCL_UMA_DRIVER=custom.
  • 480 s per run, order A B C C B A, one exe name. Each translator got its own precompile snapshot in your env (--precompile --pipelines), and each run a fresh copy of it. Same scripted presses in every arm.
run world (log s) world +10..+130 world +80..+122 187-229 s draws / dispatches per present end
A1 main 128.6 0.68 0.62 0.60 525 / 3770 crash at 490 s
A2 main 130.7 (removed at 167.7 s) 0x887a0005
B1 mixed 121.9 9.30 8.31 10.95 577 / 3238 0x887a0005 at 463 s
B2 mixed 131.0 10.31 11.36 13.48 560 / 3155 crash at 355 s
C1 custom 125.5 5.85 6.05 6.48 592 / 3364 0x887a0005 at 500 s
C2 custom 114.1 5.87 6.00 6.24 587 / 3345 0x887a0005 at 300 s
  • B logged is mixed driver heaps mapped at its address [0x0+1536MB CUSTOM, write-watched, 0x60000000+1792MB GPU_UPLOAD, 0xd0000000+767MB CUSTOM, write-watched]; C logged the single CUSTOM heap. Every run except A2 ended after its windows; the removals show DRED page faults at VA 0x0. No driver events in the System log.

Things worth knowing:

  • A first run in a fresh data folder doesn't get mixed. The coherent window is sized from uma_coherent.txt plus 512 MB (coherent_hint_for). A new folder gets 512 MB, so 1536:1792 lies outside it and the log says coherent window 3 stays imported: no GPU_UPLOAD range inside the window. Our first B run measured that by accident. A second run in the same folder (or XCL_COHERENT_MB=4095) gets the full window. Testers who use clean folders per run will measure custom-like numbers without noticing.
  • B does less upload work per present than C: about 35-40% fewer GPU-view textures kept in step (67-70 against 109) and fewer MB of CPU writes uploaded. That's what mixed intends (CPU writes to GPU_UPLOAD land in VRAM directly). It's also what missed refreshes would look like, since the GPU_UPLOAD segment isn't write-watched. These counters can't tell the two apart, and the frames are grey on every tree. A run on a tree with visible frames would settle it.
  • Main built about 3x as many graphics PSOs without a driver blob during its runs (1,650-1,750 against 510-590), so part of the gap to main may be compile time rather than the window.
  • The cross-segment placement case (7212241709) didn't occur in the title here: no buffer crossed 1536 or 3328 MB. Four 2D textures in the GPU_UPLOAD range got resources of their own, but the same four do so at the same offsets with custom, so that isn't from the boundaries.

Not tested: visible frames; a second valid main run; other range layouts; the switches one at a time; why our absolute numbers sit below your 25.28 on a faster GPU (possibly the A/B setup differences above, not checked).

AI use: Claude Code (Claude Opus 5.5) ran and measured the arms (t12) and wrote this comment; Codex (GPT-6.2-Sol) reviewed the stack for safety and fairness; Gemini (Antigravity) collected your recipe from the threads.

**@⁠KDenKC** on GitHub · 2026-11-27 08:18 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7213384606) In-title A/B of this exact head (`0567c713`) on an RTX 5090. As far as I can see, the first title run of the head itself rather than the integration tree. **Result:** in the #2844 world window (world +10 to +130 s), the stack with `mixed` ran at **9.80 fps** against **5.86** with `custom` on the same binary (**1.67x**; your CB2 → CB2m3 was 2.01x), and against **0.68** on main `8b957bec` (14.4x, one valid main run). Your 187-229 s window gives main 0.60 fps here against your 0.58. **Setup:** RTX 5090 32 GB, driver 621.24, Ryzen 7 9800X3D, Windows 11, Series X profile, release. - Your base env: `XCL_HEAP_WINDOWS=1 XCL_DIRECT_DXIL=all XCL_DIRECT_SPLIT_INSTRUCTIONS=0 XCL_PSO_JOURNAL=0 XCL_DRED=1 XCL_GPU_WAIT_TIMEOUT_MS=120000 XCL_ACTIVITY=1 XCL_NETWORK=0`. - In all arms on top of that: `XCL_TEXTURE_LEVEL_PAGES=1` (your main ran without it), `XCL_PSO_TRACE=1` and `XCL_COHERENT_MB=4095` (see the first note). - A = main. B = this head + `XCL_UMA_DRIVER=mixed:1536:1792 XCL_WATCH_TRAP=1 XCL_DECLARED_LDS=1 XCL_BYTE_STORE_CS=e166372fa54a77c7`. C = B with `XCL_UMA_DRIVER=custom`. - 480 s per run, order A B C C B A, one exe name. Each translator got its own precompile snapshot in your env (`--precompile --pipelines`), and each run a fresh copy of it. Same scripted presses in every arm. | run | world (log s) | world +10..+130 | world +80..+122 | 187-229 s | draws / dispatches per present | end | |---|---:|---:|---:|---:|---|---| | A1 main | 128.6 | 0.68 | 0.62 | 0.60 | 525 / 3770 | crash at 490 s | | A2 main | 130.7 | (removed at 167.7 s) | | | | `0x887a0005` | | B1 mixed | 121.9 | 9.30 | 8.31 | 10.95 | 577 / 3238 | `0x887a0005` at 463 s | | B2 mixed | 131.0 | 10.31 | 11.36 | 13.48 | 560 / 3155 | crash at 355 s | | C1 custom | 125.5 | 5.85 | 6.05 | 6.48 | 592 / 3364 | `0x887a0005` at 500 s | | C2 custom | 114.1 | 5.87 | 6.00 | 6.24 | 587 / 3345 | `0x887a0005` at 300 s | - B logged `is mixed driver heaps mapped at its address [0x0+1536MB CUSTOM, write-watched, 0x60000000+1792MB GPU_UPLOAD, 0xd0000000+767MB CUSTOM, write-watched]`; C logged the single CUSTOM heap. Every run except A2 ended after its windows; the removals show DRED page faults at VA 0x0. No driver events in the System log. **Things worth knowing:** - **A first run in a fresh data folder doesn't get `mixed`.** The coherent window is sized from `uma_coherent.txt` plus 512 MB (`coherent_hint_for`). A new folder gets 512 MB, so `1536:1792` lies outside it and the log says `coherent window 3 stays imported: no GPU_UPLOAD range inside the window`. Our first B run measured that by accident. A second run in the same folder (or `XCL_COHERENT_MB=4095`) gets the full window. Testers who use clean folders per run will measure `custom`-like numbers without noticing. - **B does less upload work per present than C:** about 35-40% fewer GPU-view textures kept in step (67-70 against 109) and fewer MB of CPU writes uploaded. That's what `mixed` intends (CPU writes to GPU_UPLOAD land in VRAM directly). It's also what missed refreshes would look like, since the GPU_UPLOAD segment isn't write-watched. These counters can't tell the two apart, and the frames are grey on every tree. A run on a tree with visible frames would settle it. - **Main built about 3x as many graphics PSOs without a driver blob during its runs** (1,650-1,750 against 510-590), so part of the gap to main may be compile time rather than the window. - **The cross-segment placement case (7212241709) didn't occur in the title here:** no buffer crossed 1536 or 3328 MB. Four 2D textures in the GPU_UPLOAD range got resources of their own, but the same four do so at the same offsets with `custom`, so that isn't from the boundaries. **Not tested:** visible frames; a second valid main run; other range layouts; the switches one at a time; why our absolute numbers sit below your 25.28 on a faster GPU (possibly the A/B setup differences above, not checked). AI use: Claude Code (Claude Opus 5.5) ran and measured the arms (t12) and wrote this comment; Codex (GPT-6.2-Sol) reviewed the stack for safety and fairness; Gemini (Antigravity) collected your recipe from the threads.
Author
Owner

@⁠LocranKing on GitHub · 2026-11-27 10:08 UTC · original

Tested PR #2938 (0567c713) against main (8b957bec) and #2844 (f2248f06) on Windows 11 (26300), Ryzen 5 5500 (6C/12T), RTX 3060 Ti 8 GiB (driver 621.40), rustc 1.100.0, DXC 1.9.2602.17.

Unit Tests (cargo test --locked -p xcl --lib -- uma_driver)

  • Sequential (-- --test-threads=1): 7 passed, 0 failed (mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment created [0x0+64MB CUSTOM, 0x4000000+128MB GPU_UPLOAD, 0xc000000+64MB CUSTOM], and a_refused_gpu_upload_segment_becomes_custom passed).
  • Parallel (default test runner): Reproducibly terminates the test process with exit code 0x7C10003 (130088963) after failed_write_watch_does_not_release_the_original_window. Both mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment and a_refused_gpu_upload_segment_becomes_custom call VirtualFree(..., MEM_RELEASE) and re-reserve a 256 MiB window concurrently inside the same process without test serialization, allowing another thread's allocation to land in the freed VA range and hit stop_unbacked (0x7C1_0003).

Paired 180 s Retail Smoke (9cc6a39e, Series S lockhart)

All runs started from pre-warmed DXIL/driver cache snapshots with XCL_HEAP_WINDOWS=1, XCL_DIRECT_DXIL=all, XCL_DIRECT_SPLIT_INSTRUCTIONS=0, XCL_PSO_WAIT_MS=50.
As noted in the PR description, 0567c713 is stacked on #2844, #2926, #2936, #2937, and #2934; the PR #2938 runs below also enable XCL_WATCH_TRAP=1, XCL_DECLARED_LDS=1, XCL_BYTE_STORE_CS=e166372fa54a77c7, and XCL_TEXTURE_LEVEL_PAGES=1, whereas the main and #2844 baselines ran without those optional switches:

Configuration Guest entry / World load Frames shown World presents (2 s windows) Peak commit Peak local / non-local VRAM Crashes / Removals
main (8b957bec) 67.2 s / 188.4 s 1240 14 / 28w (last 3: 0 1 1) 29,411 MB 14,281 / 2,241 MB 0 / 0 (exit: 0x0)
#2844 (f2248f06) 69.3 s / 189.2 s 1266 22 / 28w (last 3: 1 1 0) 30,006 MB 14,537 / 2,316 MB 0 / 0 (exit: 0x0)
#2938 (XCL_UMA_DRIVER=custom) 68.1 s / 174.3 s 1504 31 / 34w (last 3: 1 2 1) 25,005 MB 9,797 / 2,052 MB 0 / 0 (exit: 0x0)
#2938 (mixed:1536:1792, outside 512 MB Series S window) 69.9 s / 175.9 s 1532 46 / 36w (last 3: 2 2 3) 25,215 MB 9,676 / 2,120 MB 0 / 0 (exit: 0x0)
#2938 (mixed:128:256, active GPU_UPLOAD in 512 MB window) 69.9 s / 180.0 s 1605 52 / 35w (last 3: 3 2 1) 24,880 MB 9,874 / 1,746 MB 0 / 0 (exit: 0x0)

Notes

  • With XCL_UMA_DRIVER=mixed:1536:1792, Series S (lockhart) has a single 512 MB coherent window (0x700000000), so the range 1536:1792 fell outside it and logged WARN D3D12.X: coherent window 3 stays imported: no GPU_UPLOAD range inside the window.
  • With XCL_UMA_DRIVER=mixed:128:256 inside that 512 MB window, the coherent window remapped cleanly to [0x0+128MB CUSTOM, write-watched, 0x8000000+256MB GPU_UPLOAD, 0x18000000+128MB CUSTOM, write-watched] (139 reservations, 115 ms), lowering peak non-local VRAM (2,052 -> 1,746 MB) and raising world presents (31 -> 52 over ~70 s post-world) with zero crashes or device removals. (XCL_WATCH_TRAP=1 and XCL_TEXTURE_LEVEL_PAGES=1 account for most of the ~4.5 GB commit / local-VRAM reduction relative to the unflagged main / #2844 baselines.)

Not tested: Multi-minute sustained world traversal (>180 s), isolated #2938 (custom vs mixed:128:256) without XCL_WATCH_TRAP=1 / XCL_TEXTURE_LEVEL_PAGES=1 / XCL_DECLARED_LDS=1, or full workspace test suite on 0567c713.

**@⁠LocranKing** on GitHub · 2026-11-27 10:08 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7215514042) Tested PR #2938 (`0567c713`) against `main` (`8b957bec`) and #2844 (`f2248f06`) on Windows 11 (26300), Ryzen 5 5500 (6C/12T), RTX 3060 Ti 8 GiB (driver `621.40`), `rustc 1.100.0`, DXC `1.9.2602.17`. ### Unit Tests (`cargo test --locked -p xcl --lib -- uma_driver`) - **Sequential (`-- --test-threads=1`):** **`7 passed, 0 failed`** (`mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment` created `[0x0+64MB CUSTOM, 0x4000000+128MB GPU_UPLOAD, 0xc000000+64MB CUSTOM]`, and `a_refused_gpu_upload_segment_becomes_custom` passed). - **Parallel (default test runner):** **Reproducibly terminates the test process with exit code `0x7C10003` (`130088963`)** after `failed_write_watch_does_not_release_the_original_window`. Both `mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment` and `a_refused_gpu_upload_segment_becomes_custom` call `VirtualFree(..., MEM_RELEASE)` and re-reserve a 256 MiB window concurrently inside the same process without test serialization, allowing another thread's allocation to land in the freed VA range and hit `stop_unbacked` (`0x7C1_0003`). ### Paired 180 s Retail Smoke (`9cc6a39e`, Series S `lockhart`) All runs started from pre-warmed DXIL/driver cache snapshots with `XCL_HEAP_WINDOWS=1`, `XCL_DIRECT_DXIL=all`, `XCL_DIRECT_SPLIT_INSTRUCTIONS=0`, `XCL_PSO_WAIT_MS=50`. As noted in the PR description, `0567c713` is stacked on #2844, #2926, #2936, #2937, and #2934; the PR #2938 runs below also enable `XCL_WATCH_TRAP=1`, `XCL_DECLARED_LDS=1`, `XCL_BYTE_STORE_CS=e166372fa54a77c7`, and `XCL_TEXTURE_LEVEL_PAGES=1`, whereas the `main` and #2844 baselines ran without those optional switches: | Configuration | Guest entry / World load | Frames shown | World presents (2 s windows) | Peak commit | Peak local / non-local VRAM | Crashes / Removals | | --- | --- | --- | --- | --- | --- | --- | | `main` (`8b957bec`) | `67.2 s` / `188.4 s` | `1240` | `14 / 28w` (`last 3: 0 1 1`) | `29,411 MB` | `14,281 / 2,241 MB` | `0 / 0` (`exit: 0x0`) | | `#2844` (`f2248f06`) | `69.3 s` / `189.2 s` | `1266` | `22 / 28w` (`last 3: 1 1 0`) | `30,006 MB` | `14,537 / 2,316 MB` | `0 / 0` (`exit: 0x0`) | | `#2938` (`XCL_UMA_DRIVER=custom`) | `68.1 s` / `174.3 s` | `1504` | `31 / 34w` (`last 3: 1 2 1`) | `25,005 MB` | `9,797 / 2,052 MB` | `0 / 0` (`exit: 0x0`) | | `#2938` (`mixed:1536:1792`, outside 512 MB Series S window) | `69.9 s` / `175.9 s` | `1532` | `46 / 36w` (`last 3: 2 2 3`) | `25,215 MB` | `9,676 / 2,120 MB` | `0 / 0` (`exit: 0x0`) | | `#2938` (`mixed:128:256`, active `GPU_UPLOAD` in 512 MB window) | `69.9 s` / `180.0 s` | **`1605`** | **`52 / 35w`** (`last 3: 3 2 1`) | **`24,880 MB`** | `9,874 /` **`1,746 MB`** | `0 / 0` (`exit: 0x0`) | ### Notes - With `XCL_UMA_DRIVER=mixed:1536:1792`, Series S (`lockhart`) has a single `512 MB` coherent window (`0x700000000`), so the range `1536:1792` fell outside it and logged `WARN D3D12.X: coherent window 3 stays imported: no GPU_UPLOAD range inside the window`. - With `XCL_UMA_DRIVER=mixed:128:256` inside that `512 MB` window, the coherent window remapped cleanly to `[0x0+128MB CUSTOM, write-watched, 0x8000000+256MB GPU_UPLOAD, 0x18000000+128MB CUSTOM, write-watched]` (`139 reservations, 115 ms`), lowering peak non-local VRAM (`2,052 -> 1,746 MB`) and raising world presents (`31 -> 52` over ~70 s post-world) with zero crashes or device removals. (`XCL_WATCH_TRAP=1` and `XCL_TEXTURE_LEVEL_PAGES=1` account for most of the ~4.5 GB commit / local-VRAM reduction relative to the unflagged `main` / `#2844` baselines.) **Not tested:** Multi-minute sustained world traversal (`>180 s`), isolated `#2938` (`custom` vs `mixed:128:256`) without `XCL_WATCH_TRAP=1` / `XCL_TEXTURE_LEVEL_PAGES=1` / `XCL_DECLARED_LDS=1`, or full workspace test suite on `0567c713`.
Author
Owner

@⁠afpruivo on GitHub · 2026-11-27 11:42 UTC · original

RTX 3090 24 GB (Ampere, Resizable BAR on) at 0567c713: mixed:1536:1792 ran at 6.47 and 8.06 fps against 5.44 fps for custom on the same exe, with GPU busy per frame down from 163 ms to 118–124 ms. Fewer runs than I wanted: only one of three custom runs reached a steady stretch (below). No device removal or crash in any run. This adds an Ampere card and a 24 GB card next to the 5070 Ti runs.

Setup

  • RTX 3090 24 GB, driver 621.40 (nvidia-smi BAR1 32768 MiB), i5-13600K, 32 GB RAM, Windows 11 26300, Rust 1.99.1, release. Retail title, smoke title: 3c290c16, default profile (not Series X as in your runs).
  • This PR's head 0567c713 as posted. xcl.exe in a 2 GiB shader-heap profile (#2590).
  • Both arms: XCL_DIRECT_DXIL=1 XCL_WATCH_TRAP=1 XCL_DECLARED_LDS=1 XCL_BYTE_STORE_CS=e166372fa54a77c7 XCL_TEXTURE_LEVEL_PAGES=1, A tapped every 4 s, 300 s runs; only XCL_UMA_DRIVER differs (custom / mixed:1536:1792). The log shows the three segments (1536 MB CUSTOM watched, 1792 MB GPU_UPLOAD, 767 MB CUSTOM watched).
  • A warm-up run first, then runs in the order A B B A plus one more A. PresentMon only, 150 s from 120 s after the title started; the table scores the last 90 s of that (about 180–270 s into the title).
  • Scene: the intro and credits sequence, not the open world. XCL's scripted presses tap A for 200 ms, and the intro needs A held to go on (#609 / #1765 would allow that). As far as I can tell that is the scene the other in-title numbers here come from too.
run XCL_UMA_DRIVER fps GPU busy (median) frame p95
2 mixed 6.47 124 ms 181 ms
3 mixed 8.06 118 ms 179 ms
4 custom 5.44 163 ms 239 ms
1 custom 0.21 — —
5 custom stopped presenting — —
  • Run 1 reached 13 graphics pipelines no earlier run had built (driver blob absent, 7–10 s each, one after another) and presented almost nothing while they built; the later runs had them in the cache. Not a measure of the arm.
  • Run 5 stopped presenting about 150 s into the title, right after 5,000 ms queue.Wait timeouts (title fences, prod=qSome(3)). Those timeouts appear in both arms later in the runs (run 4 at ~240 s, run 2 at ~223 s, none in run 3), so I don't read run 5 as caused by custom; one run cannot say.
  • On this card the share is smaller than your CB2 → CB2m3 (2.01x): 1.19–1.48x. The frames are still mostly GPU (~120 ms of a ~125–150 ms frame) with mixed.

Tests: cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4 on 0567c713: 1476 passed, 0 failed, 47 ignored; 28 SKIPPED (21 no wave64, 3 refused per-lane f16 forms, 3 no D3D12 debug layer, 1 no heap windows). The five new tests pass, and mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment runs (not skipped) on this Ampere card.

Not tested: the open world; other range layouts; the smoke pair; a second steady custom run.

AI use: Claude Code (Claude Opus 5.5) ran the runs and the suite and drafted this; checked by me before posting.

**@⁠afpruivo** on GitHub · 2026-11-27 11:42 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7217390263) **RTX 3090 24 GB (Ampere, Resizable BAR on) at `0567c713`: `mixed:1536:1792` ran at 6.47 and 8.06 fps against 5.44 fps for `custom` on the same exe, with GPU busy per frame down from 163 ms to 118–124 ms.** Fewer runs than I wanted: only one of three `custom` runs reached a steady stretch (below). No device removal or crash in any run. This adds an Ampere card and a 24 GB card next to the 5070 Ti runs. **Setup** - RTX 3090 24 GB, driver 621.40 (`nvidia-smi` BAR1 32768 MiB), i5-13600K, 32 GB RAM, Windows 11 26300, Rust 1.99.1, release. Retail title, smoke `title: 3c290c16`, default profile (not Series X as in your runs). - This PR's head `0567c713` as posted. `xcl.exe` in a 2 GiB shader-heap profile (#2590). - Both arms: `XCL_DIRECT_DXIL=1 XCL_WATCH_TRAP=1 XCL_DECLARED_LDS=1 XCL_BYTE_STORE_CS=e166372fa54a77c7 XCL_TEXTURE_LEVEL_PAGES=1`, A tapped every 4 s, 300 s runs; only `XCL_UMA_DRIVER` differs (`custom` / `mixed:1536:1792`). The log shows the three segments (1536 MB CUSTOM watched, 1792 MB `GPU_UPLOAD`, 767 MB CUSTOM watched). - A warm-up run first, then runs in the order A B B A plus one more A. PresentMon only, 150 s from 120 s after the title started; the table scores the last 90 s of that (about 180–270 s into the title). - **Scene:** the intro and credits sequence, not the open world. XCL's scripted presses tap A for 200 ms, and the intro needs A held to go on (#609 / #1765 would allow that). As far as I can tell that is the scene the other in-title numbers here come from too. | run | `XCL_UMA_DRIVER` | fps | GPU busy (median) | frame p95 | |---|---|---:|---:|---:| | 2 | mixed | **6.47** | 124 ms | 181 ms | | 3 | mixed | **8.06** | 118 ms | 179 ms | | 4 | custom | **5.44** | 163 ms | 239 ms | | 1 | custom | 0.21 | — | — | | 5 | custom | stopped presenting | — | — | - Run 1 reached 13 graphics pipelines no earlier run had built (`driver blob absent`, 7–10 s each, one after another) and presented almost nothing while they built; the later runs had them in the cache. Not a measure of the arm. - Run 5 stopped presenting about 150 s into the title, right after 5,000 ms `queue.Wait` timeouts (title fences, `prod=qSome(3)`). Those timeouts appear in both arms later in the runs (run 4 at ~240 s, run 2 at ~223 s, none in run 3), so I don't read run 5 as caused by `custom`; one run cannot say. - On this card the share is smaller than your CB2 → CB2m3 (2.01x): 1.19–1.48x. The frames are still mostly GPU (~120 ms of a ~125–150 ms frame) with `mixed`. **Tests:** `cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4` on `0567c713`: 1476 passed, 0 failed, 47 ignored; 28 `SKIPPED` (21 no wave64, 3 refused per-lane f16 forms, 3 no D3D12 debug layer, 1 no heap windows). The five new tests pass, and `mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment` runs (not skipped) on this Ampere card. **Not tested:** the open world; other range layouts; the smoke pair; a second steady `custom` run. AI use: Claude Code (Claude Opus 5.5) ran the runs and the suite and drafted this; checked by me before posting.
github-bot force-pushed github-bot/gh-2938 from 0567c7138f to a76cc3e638 2026-11-27 12:20:51 +00:00 Compare
Author
Owner

@⁠Kalmarv on GitHub · 2026-11-27 12:10 UTC · original

The head moved from 0567c713 to a76cc3e6 for a test race, not a runtime change. Only uma_driver.rs's tests differ:

  • mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment and a_refused_gpu_upload_segment_becomes_custom both remake a mixed window. Run at the same time (--test-threads=4), one test's ungroom freed stretches that the other's remake had reserved, a segment mapped elsewhere and restore stopped the test process (0x7C10003). It showed on the nvidia-dev port of this change (3122c97b, the same tests): cargo test -p xcl --lib hle::d3d12x::uma_driver -- --test-threads=4 stopped in 8 of 10 runs, with --test-threads=1 in 0 of 3. The suite on 0567c713 happened to pass, but the tests are the same. Now the two tests take one lock (MIXED_REMAKE); on a76cc3e6 the same command passes 10 of 10 runs at 4 threads and 3 of 3 at 1 thread.
  • The same race can happen at run time if a thread of the title frees 64 MB or more of address space during a remake; that is now under Not tested (not seen in title runs; mixed is opt-in).

The suite and the regression pair in the description are on a76cc3e6.

Claude Code (Claude Opus 5.5) found the race, wrote the lock and ran the tests on the RTX 5070 Ti named in the description.

**@⁠Kalmarv** on GitHub · 2026-11-27 12:10 UTC · [original](https://github.com/xcl-dev/xcl/pull/2938#issuecomment-7217917702) The head moved from 0567c713 to a76cc3e6 for a test race, not a runtime change. Only `uma_driver.rs`'s tests differ: - `mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment` and `a_refused_gpu_upload_segment_becomes_custom` both remake a mixed window. Run at the same time (`--test-threads=4`), one test's ungroom freed stretches that the other's remake had reserved, a segment mapped elsewhere and restore stopped the test process (0x7C10003). It showed on the `nvidia-dev` port of this change (3122c97b, the same tests): `cargo test -p xcl --lib hle::d3d12x::uma_driver -- --test-threads=4` stopped in 8 of 10 runs, with `--test-threads=1` in 0 of 3. The suite on 0567c713 happened to pass, but the tests are the same. Now the two tests take one lock (`MIXED_REMAKE`); on a76cc3e6 the same command passes 10 of 10 runs at 4 threads and 3 of 3 at 1 thread. - The same race can happen at run time if a thread of the title frees 64 MB or more of address space during a remake; that is now under **Not tested** (not seen in title runs; `mixed` is opt-in). The suite and the regression pair in the description are on a76cc3e6. Claude Code (Claude Opus 5.5) found the race, wrote the lock and ran the tests on the RTX 5070 Ti named in the description.
This pull request has changes conflicting with the target branch.
  • crates/xcl/src/hle/d3d12x/uma_driver.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2938/head:github-bot/gh-2938'
git switch 'github-bot/gh-2938'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2938'
git switch 'github-bot/gh-2938'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2938'
git switch 'github-bot/gh-2938'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2938'
git switch 'main'
git merge --squash 'github-bot/gh-2938'
git switch 'main'
git merge --ff-only 'github-bot/gh-2938'
git switch 'main'
git merge 'github-bot/gh-2938'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.