Skip to content

D3D12.X: UMA windows in a driver heap on NVIDIA, 4.9x FPS (0.62 -> 3.03) - #2844

Merged
Prime1997 merged 2 commits into
xcl-dev:mainfrom
Kalmarv:pr/uma-driver-window
Nov 27, 2026
Merged

Prime1997 merged 2 commits into
xcl-dev:mainfrom
Kalmarv:pr/uma-driver-window

Conversation

@Kalmarv

@Kalmarv Kalmarv commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #751; only the top commit belongs here (#751 fixes the detile crash that otherwise ends every world run before a two-minute window). Part of #2688.

Result: 3.03 FPS instead of 0.62 in the world (4.9x), RTX 5070 Ti, title ea3b5e4d, same 2-minute window, no device removal or crash. The GPU time of a replayed world frame drops 8.7x (1,427 ms -> 165 ms), the hot compute programs 18-39x each.

On NVIDIA the coherent UMA window is the bottleneck: the title's GPU code reads and writes it through a heap opened with OpenExistingHeapFromAddress, and the GPU's loads and atomics on those imported pages are an order of magnitude slower than on a driver heap in the same host memory. This PR puts the window in a driver CUSTOM write-back L0 heap mapped at the window's own address, so the title keeps its pointers.

How it was found: locum

locum (MIT) is a standalone D3D12 capture and replay tool: a wrapper DLL records every call, resource and descriptor of a frame, and locum-cli replays that frame offline, optionally with one thing changed, timing every draw and dispatch on the GPU (locum-cli verify --times). It is only used as an external tool here; no code of it is in XCL. Live, the title is too slow and noisy to tell causes apart (shader form, tile remaps, video memory over budget, paging and sync stalls all looked plausible). With locum:

  1. One world frame was captured under XCL and replayed on its own, window 3 in a driver CUSTOM L0 heap: draws 1-1704 took 164.6 ms of GPU time, against seconds per frame live. So the translated shaders were not the problem, and the same work could run fast.
  2. The replay was run again changing only how window 3 is made, as XCL makes it (VirtualAlloc + OpenExistingHeapFromAddress): 1,427.3 ms, 8.7x, reproducing the live per-op times. b78fa10b 19.7 -> 350.6 ms (18x), 24de2aef's three dispatches 10.2 -> 393.6 ms (39x), 1b5466f2 1.4 -> 246.5 ms. Same capture, same replay code, one queue, no tile remaps: the cost is in how the window's memory is made, not in the live run. (Both replays ran at the same low clocks, since a replay feeds the GPU slowly: the ratio is the result, not the absolute times.)
  3. That gave a one-line hypothesis, checked in two minutes by the probe below and then fixed here.

Evidence beyond the replay

  • A standalone probe on the same card (one 1024x64x16 dispatch per memory home, ns per loop iteration, atomics / load):

    boxes VRAM imported (OpenExistingHeapFromAddress) CUSTOM L0 write-back
    1 0.457 / 0.003 573 / 0.032 44.7 / 0.003
    256 0.187 / 0.003 97 / 0.081 14.7 / 0.004
    65536 0.043 / 0.018 13.6 / 3.44 14.9 / 1.70

    Write watch is not the cause (imported without it: same rows), and neither are the cross-adapter flags (a DEFAULT heap with SHARED_CROSS_ADAPTER runs at CUSTOM L0 speed). Plain stores at 256-4096 boxes are the one row where the driver heap is slower (4-7x); the frame totals above include that.

What is in it

  • hle/d3d12x/uma_driver.rs (new): 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. If the mapping lands anywhere else, or any step fails, the window is made again at its address with its pages and imported as before (logged as coherent window N stays imported: ...). If the snapshot of the written pages fails, the window is not released at all (found in review by @thehollowedone, with their test failed_write_watch_does_not_release_the_original_window).
  • hle/d3d12x/mod.rs, real.rs, host.rs: the backend, and with it the window and any remap, is made once in host_main before load_main, before a title DLL's TLS callbacks or DllMain can hold a window pointer; a backend first made later, and real::init(), only import. Otherwise a title write between the snapshot and the release could be lost. If the window cannot be made again at its address after the release, XCL logs it and ends the process (0x7C10003) rather than run the title on an unbacked window. Both found in review by @thehollowedone (review), with their candidates and tests applied as posted: the order check in the e2e test test_title_runs_and_game_folder_is_untouched, and failed_restore_stops_before_importing_an_unbacked_window.
  • hle/d3d12x/real.rs: buffers placed in a driver window drop ALLOW_CROSS_ADAPTER.
  • gpu/uma.rs: which windows are driver heaps.
  • hle/d3d12x/title_textures.rs: under Wine, read_committed_into goes region by region instead of one whole-range ReadProcessMemory (from D3D12.X: title texture reads outside the coherent window use the safe copy #751's commit below), which under Wine read through guard and no-access pages and failed title_bytes_leave_guard_pages_alone on Wine/NVIDIA (found by @SlopTart, traced by @thehollowedone, their candidate applied). Native Windows keeps the one copy.
  • The heap is made with D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH. On the RTX 5070 Ti GetWriteWatch reads the mapped window (4 KiB pages reported, reset, reported again after a new write; all 16,386 written pages of the 4 GiB window found once), so the window stays in watch_regions and the title's CPU writes reach its textures as with the import. A driver that refuses the flag, or a mapping GetWriteWatch cannot read, keeps the import. (A first form without write watch left CPU rewrites of title textures in the window off the GPU: placed_title_textures_share_vram_and_preserve_pixels row 6 failed in the full parallel suite, where another test had made the window a driver heap.)
  • Scope: on by default for an NVIDIA adapter (vendor 0x10DE) outside Wine (util::under_wine); AMD, Intel and Wine keep the import unchanged. XCL_UMA_DRIVER=0 turns it off, XCL_UMA_DRIVER=1 turns it on anywhere. Unit tests driver_windows_by_default_on_nvidia_outside_wine, failed_write_watch_does_not_release_the_original_window and failed_restore_stops_before_importing_an_unbacked_window.

Tested

  • RTX 5070 Ti (16 GB), driver 610.74, Ryzen 9 9950X, 31 GB RAM, Windows 11 Pro 26200, Rust 1.99.0, release.

  • On this head f2248f0, debug: cargo test -p xcl --lib hle::d3d12x::title_textures::tests:: -- --test-threads=1: 21 passed, 0 failed; cargo test -p xcl --lib hle::d3d12x::uma_driver::tests:: -- --test-threads=1: 3 passed, 0 failed. It differs from 50ae2eb only in the under-Wine branch above, so the full suite below is from 50ae2eb.

  • On 50ae2eb, debug: cargo test --workspace --no-fail-fast -- --test-threads=4: 1448 passed, 3 failed, 47 ignored, the same 144 SKIPPED. The failed ones: the two link_tests below (as on main), and list_x::tests::a_dispatch_with_a_pipeline_still_building_waits_at_the_submit once, in a suite run beside other jobs; it passed alone 3 of 3 and in cargo test -p xcl --lib list_x (40 passed, 0 failed). This PR does not touch list_x. cargo test -p xcl --lib hle::d3d12x::uma_driver::tests:: -- --test-threads=1: 3 passed, 0 failed; cargo test -p xcl --test e2e test_title_runs_and_game_folder_is_untouched: 1 passed, 0 failed.

  • On the previous head fc007a9: cargo test --workspace -- --test-threads=4: 1448 passed, 2 failed, 47 ignored; 144 SKIPPED (119 validator 1.7 < 1.8, validation step only; 21 no wave64; 3 refused f16 forms V_MUL_F16 / V_PK_MUL_F16 / V_CVT_F16_F32, gpu: direct RDNA2 -> DXIL backend (no HLSL / DXC), behind XCL_DIRECT_DXIL #1426 semantics; 1 no heap windows). The failed ones are link_tests::gpu_linked_memory_accessors and link_tests::linked_programs_keep_their_declarations (DXC: "attribute WaveSize only valid on entry point function"); they fail the same way on main 8b957be (cargo test -p xcl --lib link_tests: 0 passed, 2 failed).

  • Title ea3b5e4d, one paired run each (main and the previous head fc007a9), 480 s, the GPU alone (no build or other job on the machine). Both arms start from snapshots of one cache made by a single xcl shaders shaders.rpf --precompile --pipelines on main's translator (this PR changes no shader code; the precompile: 20,748 compiled, 14,842 already cached, 0 errors, 2,689 pipelines made, 0 refused), and neither arm wrote a new loose DXIL cache entry or driver PSO file in play (it still wrote translation records, which can hold DXIL from direct translation: main 866, this PR 868); the startup preparation still rescans the pack on every launch. Env for both: 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_DXIL_CACHE=<snapshot> XCL_DXC_DIR=<DXC 1.9.2609> XCL_PRESS_AT=14:A,18:A,... (A every 4 s from 14 s). Each arm is scored over 120 s from 10 s after its world starts (the first 2 s with 5,000+ dispatches), FPS as presents over the measured time of the activity intervals: main's world from 108 s, scored 117.7-238.7 s (121.0 s measured); this PR's from 106 s, scored 116.1-236.1 s (120.1 s measured).

    main 8b957be this PR fc007a9
    FPS mean 0.62 3.03
    worst interval (FPS) 0.0 0.5
    committed MB, start -> end (peak, slope) 33,286 -> 37,529 (peak 37,529, +2140 MB/min) 34,216 -> 39,213 (peak 39,213, +2540 MB/min)
    video memory local / non-local peak (budget 15,227 MB local) 17,863 / 5,792 MB 18,638 / 6,207 MB
    device removals / crashes 0 / 0 0 / 0
    log line – the coherent window at 0x... (4095 MB) is a driver CUSTOM write-back L0 heap mapped at its address, write-watched

    On 50ae2eb, 480 s, the same env and cache snapshot, in the queue's title lane beside other jobs (not timed, so not in the table): 2,937 frames shown (fc007a9: 2,841), 0 device removals, 0 crashes, peak commit 39,371 MB; the window became the driver heap before the title loaded (0 pages kept). On this head f2248f0, the same: 2,939 frames, 0 device removals, 0 crashes, peak commit 39,360 MB (block below). A first run on this head stopped presenting at ~591 s (about 470 s into play): Write64 Signal ... would close a GPU cycle lines, then no submits, and the device was found removed when the run ended (0x887a0006, no DRED page fault). On Windows this head runs the same code as 50ae2eb, whose run had 4 of those lines and no removal; the rerun had none. One hang in the three runs of this PR's two latest heads, cause not known.

    A second PR run, on 25dfc2c, an earlier form of this PR whose window was not write-watched and which instead hashed all ~500 MB of the title's textures in it at every look (16-19 ms a look): 1.22 FPS (world from 148 s, scored 158.0-278.1 s; device removals / crashes 0 / 0).

Regression run

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
xcl-smoke v1
commit: f2248f0689ba10123f48f0ed33ef249b05f0a8e4
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 480
exit: 0x0
frames shown: 2939 (PresentX 2939)
presents per 2 s (last 3): 8 8 7
device removals: 0
crashes: 0
peak commit: 39360 MB

Not tested

  • AMD, Intel and Wine: off there by design (the probe and replay above are NVIDIA only); XCL_UMA_DRIVER=1 on them is untested. The under-Wine read change is not run under Wine here.
  • Other NVIDIA cards and drivers, and other titles.
  • The fallback when the mapping lands elsewhere: no test, and not reached in these runs (the mapping landed at the window's address every time). Testers reached it: the synthetic e2e title on an RTX 3080 Ti, and a 512 MB window on an RTX 4070 Ti (nvidia-dev port), which ran to its 900 s cap.
  • A driver that refuses write watch on a CUSTOM heap (the import is kept): not reached here.
  • One run per arm, not the four [OFFICIAL] Swarm: RAM and VRAM use down, towards stable 30 FPS on AMD and NVIDIA #2688 asks for crash and removal counts.
  • The process-ending path after a failed restore: only the forced child-process test; not reached in a title run.
  • Known limit, found by a teammate on the stacked mixed window (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): once the heap is mapped at the window's address, Unmap and dropping it do not give the address back (VirtualQuery still shows it committed seconds later). So if GetWriteWatch cannot read a mapping that landed at the right address, the restore cannot succeed, and the process stops with 0x7C10003 instead of keeping the import. The doc comment's "the window is the title's memory again" holds for the other failures. Not reached in any run here, as the heap is made with D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH.
  • What the frames show: these runs saved no frames; FPS counts presents, not their content. Two testers report full-screen green flashes with the driver heap and none without it (RTX 4090, RTX 3070); not reproduced here, where this tree draws the world grey. Open.
  • failed_restore_stops_before_importing_an_unbacked_window exits 1 instead of 0x7C10003 on Wine/NVIDIA (@SlopTart); the child's output is not known yet.

AI use

  • Claude Code (Claude Opus 5.5) wrote the code, the gate's unit test and this description, and ran the tests and the paired runs. The capture/replay comparison and the probe were run by other AI agents on the same machine (Claude Code with Claude Opus 5.5 and Claude Fable 5.1; Codex, model not recorded). The fix to the snapshot failure path, the remap-before-guest-code change, the failed-restore exit, the under-Wine read change and their tests are @thehollowedone's review suggestions (Codex, GPT-6.2 Sol), applied as posted.

🤖 Generated with Claude Code

… copy

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 (xcl-dev#602). That bypasses the ReadProcessMemory copy of
read_committed (xcl-dev#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).
@thehollowedone

Copy link
Copy Markdown
Contributor

Focused review of #2844 at 25dfc2c: the fallback can lose bytes when the page snapshot fails. In uma_driver::written_pages, a nonzero GetWriteWatch result exits the loop but returns the empty or partial Vec as success. remake then releases the original window and restores only that Vec. Microsoft defines nonzero as failure; the original mapping should stay intact on this path.

I forced this path with a synthetic 64 KiB VirtualAlloc block lacking MEM_WRITE_WATCH. On the unmodified PR head, cargo test --offline --locked -p xcl --lib failed_write_watch_does_not_release_the_original_window -- --test-threads=1 --nocapture failed: after remake, the bytes no longer matched the original 0x5a pattern (0 passed, 1 failed, 0 ignored). With the candidate change, written_pages returns an error and remake exits before VirtualFree; cargo test --offline --locked -p xcl --lib hle::d3d12x::uma_driver::tests:: -- --test-threads=1 --nocapture passed (2 passed, 0 failed, 0 ignored). cargo build --offline --locked --workspace also passed. Hardware: Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti 621.35; no GPU skip in these two tests.

This is a forced failure-path test, not an observed GetWriteWatch failure on the retail window. I did not run a title or the full workspace suite for this local suggestion. open_uma already logs a failed remake and uses the original imported window, so propagating the error preserves that fallback.

Candidate diff and regression test
diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs
index 213b76b9..5afeed28 100644
--- a/crates/xcl/src/hle/d3d12x/uma_driver.rs
+++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs
@@ -51,15 +51,16 @@ fn vendor(device: &ID3D12Device) -> Option<u32> {
 }
 
 /// The written pages of `[base, base + size)` that hold anything but zeros, with their bytes.
-unsafe fn written_pages(base: usize, size: usize) -> Vec<(usize, Vec<u8>)> {
+unsafe fn written_pages(base: usize, size: usize) -> Result<Vec<(usize, Vec<u8>)>, String> {
     let mut out = Vec::new();
     let mut buf: Vec<*mut c_void> = vec![std::ptr::null_mut(); 1 << 16];
     let end = base + size;
     let mut at = base;
     while at < end {
         let (mut n, mut page) = (buf.len(), 0u32);
-        if GetWriteWatch(0, at as *const c_void, end - at, buf.as_mut_ptr(), &mut n, &mut page) != 0 {
-            break;
+        let status = GetWriteWatch(0, at as *const c_void, end - at, buf.as_mut_ptr(), &mut n, &mut page);
+        if status != 0 {
+            return Err(format!("GetWriteWatch at {at:#x} failed ({status})"));
         }
         for &p in &buf[..n] {
             let s = std::slice::from_raw_parts(p as *const u8, page as usize);
@@ -72,7 +73,7 @@ unsafe fn written_pages(base: usize, size: usize) -> Vec<(usize, Vec<u8>)> {
         }
         at = buf[n - 1] as usize + page as usize;
     }
-    out
+    Ok(out)
 }
 
 /// Reserves every free stretch of 1 GiB or more (but its first 256 MiB, room for the driver's own
@@ -116,7 +117,7 @@ unsafe fn ungroom(got: Vec<usize>) {
 /// good. On failure the window is the title's memory again, its pages as they were.
 pub(super) unsafe fn remake(device: &ID3D12Device, base: usize, size: usize) -> Result<(ID3D12Heap, ID3D12Resource), String> {
     let t0 = std::time::Instant::now();
-    let pages = written_pages(base, size);
+    let pages = written_pages(base, size)?;
     let kept: usize = pages.iter().map(|p| p.1.len()).sum();
     if VirtualFree(base as *mut c_void, 0, MEM_RELEASE) == 0 {
         return Err(format!("VirtualFree of the window at {base:#x} failed"));
@@ -207,4 +208,29 @@ mod tests {
         assert!(decide(Some("custom"), || true, || Some(0x1002)));
         assert!(decide(Some(" 1 "), || false, || None));
     }
+
+    #[test]
+    fn failed_write_watch_does_not_release_the_original_window() {
+        use super::*;
+        use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
+        const SIZE: usize = 1 << 16;
+        unsafe {
+            let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize;
+            assert_ne!(base, 0);
+            std::ptr::write_bytes(base as *mut u8, 0x5a, SIZE);
+            let mut dev = None;
+            if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
+                VirtualFree(base as *mut c_void, 0, MEM_RELEASE);
+                return crate::gpu::recomp::runner::skip_test("no D3D12 device");
+            }
+            // A regular VirtualAlloc block lacks MEM_WRITE_WATCH, forcing GetWriteWatch to fail.
+            assert!(remake(&dev.unwrap(), base, SIZE).is_err());
+            let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            assert_ne!(VirtualQuery(base as *const c_void, &mut info, std::mem::size_of_val(&info)), 0);
+            assert_eq!(info.AllocationBase as usize, base);
+            assert_eq!(info.State, MEM_COMMIT);
+            assert!(std::slice::from_raw_parts(base as *const u8, SIZE).iter().all(|&b| b == 0x5a));
+            assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
+        }
+    }
 }

AI use: Codex (GPT-6.2 Sol) traced the page-snapshot and fallback paths, wrote and ran the local candidate and test, and drafted this review. I checked the source path, diff, and test output.

@Kalmarv

Kalmarv commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, confirmed and applied as posted in fc007a9 (squashed into the PR commit, with your test and credit in the commit message): written_pages returns an error and remake leaves the window untouched. cargo test --workspace -- --test-threads=4 on fc007a9, RTX 5070 Ti: failed_write_watch_does_not_release_the_original_window passes.

The same push also changes one other thing: the driver heap is now created with D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH and kept only if GetWriteWatch reads its mapping, so the window stays write-watched like the import (otherwise the import is kept). The earlier head left the window out of write watch, which missed CPU rewrites of title textures there.

AI use: Claude Code (Claude Opus 5.5) checked the finding, applied the diff and wrote this reply.

@Kalmarv Kalmarv changed the title D3D12.X: coherent UMA windows in a driver heap at the title's address on NVIDIA D3D12.X: UMA windows in a driver heap on NVIDIA, 4.9x FPS (0.62 -> 3.03) Nov 26, 2026
@Kalmarv
Kalmarv marked this pull request as ready for review November 26, 2026 18:57
@thehollowedone

Copy link
Copy Markdown
Contributor

Independent Windows/NVIDIA check of #2844 at fc007a9. On Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti / 621.35, Rust 1.99.1 MSVC and DXC 1.8.2502.11:

  • cargo build --offline --locked --workspace passed.
  • cargo test --offline --locked -p xcl --lib hle::d3d12x::uma_driver::tests -- --test-threads=1 --nocapture: 2 passed, 0 failed, 0 ignored.
  • cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4 --nocapture: 1,450 passed, 0 failed, 47 ignored. The log contains 25 SKIPPED GPU notices (21 no wave64, 3 refused per-lane f16 forms, 1 no heap windows); these are not coverage. I set XCL_DXIL_CACHE to writable scratch for this run.
  • The workspace log has 13 driver CUSTOM write-back L0 mapping messages and 4 stays imported fallback messages, each followed by an UMA import check: ok. These are log occurrences across test processes, not a measure of title performance. The synthetic test_title_runs_and_game_folder_is_untouched e2e test passed 1/0/0 but took the fallback: Map returned a different address. This machine exercised both paths.

Two lifecycle points remain after reading the current code. I did not trigger either failure; these are execution paths to cover before treating the remap as safe for concurrent title code:

  1. kernelx::VirtualAlloc can return a coherent-window pointer before the first D3D device. backend() initializes the device lazily. remake snapshots written pages, releases the VA, maps the new heap, then restores the snapshot. A title worker holding the earlier pointer can read/write during that gap; a write after the snapshot can be lost. Could the transition happen before any pointer is exposed, or be guarded by a guest-thread safe point? A synthetic regression should keep a pre-device allocation active on another guest thread while device creation begins, and verify its bytes remain accessible and unchanged.
  2. If a post-release failure calls restore and VirtualAlloc(base, size, ...) cannot reacquire the entire original range, it returns an ordinary Err. open_uma then tries to import that address and returns after an error, while real::init continues with the device. The coherent window may no longer be backed, yet the runtime can keep serving its pointers. Please distinguish failed rollback from an ordinary fallback and stop device initialization/guest execution on that path. A fault-injection regression could force a post-release address collision and verify the runtime does not continue with an unbacked window.

I did not run a retail title or measure FPS on this card. AMD/Intel and post-reset write-watch behavior on this card remain untested here. AI use: Codex (GPT-6.2 Sol) reviewed the current source and ran the tests; I checked each point and the output before posting.

@thehollowedone

Copy link
Copy Markdown
Contributor

Follow-up to my RTX 3080 Ti report on head fc007a9: I checked post-reset write-watch behavior on this card with a local synthetic test. It mapped the 512 MB coherent window as the driver CUSTOM write-back L0 heap at its original address, reset GetWriteWatch, wrote one 4 KiB page, confirmed that page appeared, reset again and confirmed an empty result, then wrote a different page and confirmed that only the new page appeared. cargo test --offline --locked -p xcl --lib local_probe_driver_heap_tracks_writes_after_reset -- --test-threads=1 --nocapture: 1 passed, 0 failed, 0 ignored, 0 skipped. RTX 3080 Ti / 621.35, Windows 11 build 26300; no retail title involved.

This verifies the write-watch reset path on this NVIDIA driver. It does not resolve the two remap lifecycle concerns in my prior comment. The probe was local-only and has been removed from the worktree. AI use: Codex (GPT-6.2 Sol) wrote and ran the probe; I checked its assertions and result.

@thehollowedone

Copy link
Copy Markdown
Contributor

Follow-up to my lifecycle review on head fc007a9: I reproduced a lost write at the snapshot boundary with a local synthetic test on Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti / 621.35.

The test writes 0x5a into a 64 KiB write-watched window, lets written_pages snapshot it, writes 0xa5 while the original mapping is still valid, then lets the existing remake continue. cargo test --offline --locked -p xcl --lib write_after_snapshot_survives_remake -- --test-threads=1 --nocapture failed on two runs (0 passed, 1 failed, 0 ignored, 0 skipped each): the committed window contained 0x5a afterward. This machine took the imported fallback (remade=false); that fallback also restores the stale snapshot. The callback only makes the timing deterministic. It does not establish how often a title thread hits this interval.

A bounded resolution would complete backend initialization and any remap before load_main can run title DLL callbacks, then prohibit a driver remap during later lazy initialization so an already-published guest pointer remains on its original mapping. Please test both the early path and the late import path with an active pre-device allocation. The separate failed-rollback path from my earlier review still needs a terminal outcome if the original VA cannot be restored. I have not implemented or benchmarked that lifecycle change.

Local failing regression diff (test instrumentation only)
diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs
index 8b0dab98..fb34ee0a 100644
--- a/crates/xcl/src/hle/d3d12x/uma_driver.rs
+++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs
@@ -118,8 +118,18 @@ unsafe fn ungroom(got: Vec<usize>) {
 /// of it, mapped for good. On failure the window is the title's memory again, its pages as they
 /// were.
 pub(super) unsafe fn remake(device: &ID3D12Device, base: usize, size: usize) -> Result<(ID3D12Heap, ID3D12Resource), String> {
+    remake_with_after_snapshot(device, base, size, || {})
+}
+
+unsafe fn remake_with_after_snapshot(
+    device: &ID3D12Device,
+    base: usize,
+    size: usize,
+    after_snapshot: impl FnOnce(),
+) -> Result<(ID3D12Heap, ID3D12Resource), String> {
     let t0 = std::time::Instant::now();
     let pages = written_pages(base, size)?;
+    after_snapshot();
     let kept: usize = pages.iter().map(|p| p.1.len()).sum();
     if VirtualFree(base as *mut c_void, 0, MEM_RELEASE) == 0 {
         return Err(format!("VirtualFree of the window at {base:#x} failed"));
@@ -246,4 +256,35 @@ mod tests {
             assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
         }
     }
+
+    #[test]
+    fn write_after_snapshot_survives_remake() {
+        use super::*;
+        use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
+        const SIZE: usize = 1 << 16;
+        unsafe {
+            let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize;
+            assert_ne!(base, 0);
+            (base as *mut u8).write(0x5a);
+            let mut dev = None;
+            if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
+                VirtualFree(base as *mut c_void, 0, MEM_RELEASE);
+                return crate::gpu::recomp::runner::skip_test("no D3D12 device");
+            }
+            let result = remake_with_after_snapshot(&dev.unwrap(), base, SIZE, || (base as *mut u8).write(0xa5));
+            let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            assert_ne!(VirtualQuery(base as *const c_void, &mut info, std::mem::size_of_val(&info)), 0);
+            let committed = info.State == MEM_COMMIT;
+            let byte = if committed { Some((base as *const u8).read()) } else { None };
+            let remade = result.is_ok();
+            if let Ok((heap, buf)) = result {
+                buf.Unmap(0, None);
+                drop((buf, heap));
+            } else if committed {
+                assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
+            }
+            assert!(committed, "the original window is no longer committed");
+            assert_eq!(byte, Some(0xa5), "write made while the original window was still mapped; remade={remade}");
+        }
+    }
 }

The test was local only; no retail title, private game data or FPS measurement was used. AI use: Codex (GPT-6.2 Sol) traced the current source, wrote and ran the test, and drafted this report. I checked the source path, diff and failures before posting.

@thehollowedone

Copy link
Copy Markdown
Contributor

Candidate for the snapshot-boundary failure on #2844 head fc007a9. I checked the startup path: load_main can execute a dependent DLL's TLS callbacks and DllMain before the subsequent report initializes D3D12. The local candidate initializes the shared backend once before load_main; ordinary/later backend calls and direct real::init() use the import path, so they cannot destructively remap a window after guest code may hold a pointer. The run-seconds worker starts after this preparation so it cannot win the backend initializer. Null graphics still returns before device creation.

A new assertion in the existing synthetic title e2e test checks backend initialization precedes the dependent DLL's DllMain. On unmodified fc007a9, cargo test --offline --locked -p xcl --test e2e test_title_runs_and_game_folder_is_untouched -- --test-threads=1 --nocapture failed (0 passed, 1 failed, 0 ignored): backend initialized after title DLL code. With this local candidate, the same command passed (1/0/0). cargo build --offline --locked --workspace passed, and cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4 --nocapture passed across 38 targets: 1,450 passed, 0 failed, 47 ignored; 25 GPU SKIPPED notices are not coverage. RTX 3080 Ti / 621.35, Ryzen 7 9800X3D, Windows 11 build 26300, Rust 1.99.1 MSVC.

The synthetic title attempted early remap but this driver's mapping landed elsewhere, so it used the imported fallback. This run proves startup ordering and fallback, not successful CUSTOM mapping or a retail FPS effect. I did not run matched clean-tree retail smoke, AMD or Intel. The separate failed-rollback path in my earlier review remains unresolved; if the old VA cannot be reacquired, initialization must stop rather than continue with an unbacked window.

Local candidate diff
diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs
index 4666c0e7..b7c2e38c 100644
--- a/crates/xcl/src/hle/d3d12x/mod.rs
+++ b/crates/xcl/src/hle/d3d12x/mod.rs
@@ -73,15 +73,16 @@ pub enum Backend {
 }
 
 /// Decided once: the real backend unless disabled or the driver refuses.
-pub fn backend() -> Backend {
-    static B: OnceLock<Backend> = OnceLock::new();
-    *B.get_or_init(|| {
+static BACKEND: OnceLock<Backend> = OnceLock::new();
+
+fn backend_with_remap(allow_driver_remap: bool) -> Backend {
+    *BACKEND.get_or_init(|| {
         let cfg = crate::state::config();
         if cfg.graphics.eq_ignore_ascii_case("null") {
             crate::xlog_info!("D3D12.X: backend 'null' (from the config)");
             return Backend::Null;
         }
-        match real::init() {
+        match real::init_with_remap(allow_driver_remap) {
             Ok(desc) => {
                 crate::xlog_info!("D3D12.X: backend 'real' – {desc}");
                 Backend::Real
@@ -94,6 +95,14 @@ pub fn backend() -> Backend {
     })
 }
 
+pub fn backend() -> Backend {
+    backend_with_remap(false)
+}
+
+pub(crate) fn backend_before_guest() -> Backend {
+    backend_with_remap(true)
+}
+
 /// Call a function of the system d3d12.dll by name.
 unsafe fn sys(name: &str) -> Option<usize> {
     crate::resolver::system_proc("d3d12.dll", &crate::pe::ImportName::Name { hint: 0, name: name.into() })
diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs
index 8ab89e34..19eedfe6 100644
--- a/crates/xcl/src/hle/d3d12x/real.rs
+++ b/crates/xcl/src/hle/d3d12x/real.rs
@@ -298,14 +298,14 @@ unsafe fn check_uma_import(device: &ID3D12Device, u: &crate::gpu::uma::Uma, bufs
     Ok(format!("ok, {} window(s), {} µs", probes.len(), t0.elapsed().as_micros()))
 }
 
-unsafe fn open_uma(device: &ID3D12Device) {
+unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) {
     let Some(u) = crate::gpu::uma::get() else {
         *UMA_ERROR.lock().unwrap() = "no UMA region".into();
         return;
     };
     let open = |k: usize| -> Result<(usize, u64, usize), String> {
         let (base, size) = u.window(k);
-        if super::uma_driver::wanted(device) {
+        if allow_driver_remap && super::uma_driver::wanted(device) {
             match super::uma_driver::remake(device, base, size) {
                 Ok((heap, buf)) => {
                     u.set_driver_window(k);
@@ -478,6 +478,10 @@ fn graphics_wave32(device: *mut c_void) -> bool {
 /// by default the high-performance GPU → WARP); once – later calls
 /// return the existing device's adapter.
 pub fn init() -> Result<String, String> {
+    init_with_remap(false)
+}
+
+pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result<String, String> {
     if !device_raw().is_null() {
         return Ok(ADAPTER.lock().map(|a| a.clone()).unwrap_or_default());
     }
@@ -554,7 +558,7 @@ pub fn init() -> Result<String, String> {
                 let _ = q.RegisterMessageCallback(Some(debug_message), D3D12_MESSAGE_CALLBACK_FLAG_NONE, std::ptr::null_mut(), &mut cookie);
             }
         }
-        open_uma(&device);
+        open_uma(&device, allow_driver_remap);
         super::device_x::probe_dynamic_depth_bias(&device);
         let raw = device.into_raw(); // one reference kept for the process lifetime
         adopt(raw, Kind::Device);
diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs
index a9412c65..1f5d3f49 100644
--- a/crates/xcl/src/host.rs
+++ b/crates/xcl/src/host.rs
@@ -107,18 +107,6 @@ pub fn host_main(boot_path: &Path) -> i32 {
             }
         });
     }
-    // `XCL_RUN_SECONDS=n`: the title ends itself after n seconds – the GPU drained, the log and
-    // report written (a process killed from outside with GPU work in flight can hang in the driver)
-    if let Some(secs) = std::env::var("XCL_RUN_SECONDS").ok().and_then(|v| v.parse::<u64>().ok()) {
-        std::thread::spawn(move || {
-            std::thread::sleep(std::time::Duration::from_secs(secs));
-            let (shown, presented) = crate::hle::d3d12x::present::counters();
-            crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({shown} frames shown, {presented} PresentX calls)");
-            crate::report::write_final(None);
-            crate::log::flush();
-            crate::hle::d3d12x::real::end_title(0);
-        });
-    }
     crate::stubs::init_db(&boot.config.stub_returns);
     crate::hle::init(&boot.config);
     crate::hle::kernelx::fine_timer();
@@ -144,8 +132,22 @@ pub fn host_main(boot_path: &Path) -> i32 {
     }
     crate::eh::install_crash_handler();
     crate::eh::start_probes();
+    crate::hle::d3d12x::backend_before_guest();
     HOST_MODE.store(true, Ordering::Release);
 
+    // `XCL_RUN_SECONDS=n`: the title ends itself after n seconds – the GPU drained, the log and
+    // report written (a process killed from outside with GPU work in flight can hang in the driver)
+    if let Some(secs) = std::env::var("XCL_RUN_SECONDS").ok().and_then(|v| v.parse::<u64>().ok()) {
+        std::thread::spawn(move || {
+            std::thread::sleep(std::time::Duration::from_secs(secs));
+            let (shown, presented) = crate::hle::d3d12x::present::counters();
+            crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({shown} frames shown, {presented} PresentX calls)");
+            crate::report::write_final(None);
+            crate::log::flush();
+            crate::hle::d3d12x::real::end_title(0);
+        });
+    }
+
     let main = match crate::loader::load_main(&boot.exe_path) {
         Ok(m) => m,
         Err(e) => {
diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs
index 4f238248..8e7109f6 100644
--- a/crates/xcl/tests/e2e.rs
+++ b/crates/xcl/tests/e2e.rs
@@ -161,6 +161,9 @@ fn test_title_runs_and_game_folder_is_untouched() {
     assert!(out.status.success(), "exit code {:?}", out.status.code());
 
     let log = std::fs::read_to_string(data.join("XCL.TestTitle/logs/xcl.log")).unwrap();
+    let backend_init = log.find("D3D12.X: backend '").expect("backend initialized");
+    let dll_init = log.find("DllMain(").expect("dependent DLL initialized");
+    assert!(backend_init < dll_init, "D3D12 backend initialized after title DLL code ran");
     let window = |tag| log.lines().find_map(|line| line.split_once(tag).map(|(_, hwnd)| hwnd)).unwrap();
     assert_eq!(window("Shader preparation window "), window("present: swap chain window "));
 

AI use: Codex (GPT-6.2 Sol) traced the current code, wrote and ran the local candidate and tests, and drafted this report. Codex (GPT-6.2 Astra) provided a read-only architecture check. I independently checked every point and the output before posting.

@thehollowedone

Copy link
Copy Markdown
Contributor

Follow-up on the second #2844 lifecycle point, checked on head fc007a9. I forced the post-release rollback collision in a child test process: after the original 64 KiB write-watched window was released, the test reserved its exact address and made heap creation fail. On the unchanged recovery path, remake returned an ordinary error and the child continued with that address no longer backed by the original window. The parent regression failed (0 passed, 1 failed, 0 ignored); the child exited normally and printed continued after failed restore.

In the local candidate below, an unsuccessful exact-address restoration logs the cause, flushes, and terminates the process with 0x7C10003. It cannot reach open_uma's import fallback or guest execution with a lost window. I used TerminateProcess for this unrecoverable path because Microsoft documents that it does not invoke guest DLL detach handlers; an ordinary report write here would also reenter the backend initializer through real::stats. Recoverable failures still restore the original bytes and use the import path.

On Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti / 621.35, Rust 1.99.1 MSVC:

  • cargo test --offline --locked -p xcl --lib failed_restore_stops_before_importing_an_unbacked_window -- --test-threads=1 --nocapture: 1 passed, 0 failed, 0 ignored after the candidate; the child exited with the expected code and never printed the continuation marker.
  • cargo test --offline --locked -p xcl --lib hle::d3d12x::uma_driver::tests:: -- --test-threads=1 --nocapture: 3 passed, 0 failed, 0 ignored; this includes the existing write-watch fallback regression.
  • cargo build --offline --locked --workspace passed. cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4 --nocapture: 1,451 passed, 0 failed, 47 ignored across 38 targets, with 25 GPU SKIPPED notices (not coverage).

This is a forced failure-path test, not evidence that an address collision occurred in a retail run. No title or paired clean-tree smoke was run for this local candidate; the separate pre-guest remap timing candidate remains in my earlier comment.

Local candidate diff and child-process regression
diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs
index 8b0dab98..e68ac4d9 100644
--- a/crates/xcl/src/hle/d3d12x/uma_driver.rs
+++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs
@@ -118,6 +118,15 @@ unsafe fn ungroom(got: Vec<usize>) {
 /// of it, mapped for good. On failure the window is the title's memory again, its pages as they
 /// were.
 pub(super) unsafe fn remake(device: &ID3D12Device, base: usize, size: usize) -> Result<(ID3D12Heap, ID3D12Resource), String> {
+    remake_with_after_release(device, base, size, || Ok(()))
+}
+
+unsafe fn remake_with_after_release(
+    device: &ID3D12Device,
+    base: usize,
+    size: usize,
+    after_release: impl FnOnce() -> Result<(), String>,
+) -> Result<(ID3D12Heap, ID3D12Resource), String> {
     let t0 = std::time::Instant::now();
     let pages = written_pages(base, size)?;
     let kept: usize = pages.iter().map(|p| p.1.len()).sum();
@@ -127,7 +136,16 @@ pub(super) unsafe fn remake(device: &ID3D12Device, base: usize, size: usize) ->
     let restore = |why: String| -> String {
         let p = VirtualAlloc(base as *const c_void, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE);
         if p as usize != base {
-            return format!("{why}; and the window could not be made again at {base:#x} (got {p:?})");
+            let os_error = windows_sys::Win32::Foundation::GetLastError();
+            crate::xlog_error!(
+                "D3D12.X: coherent window could not be restored at {base:#x} ({size} bytes, got {p:?}, Windows error {os_error}) after {why}; stopping before guest memory is used"
+            );
+            crate::log::flush();
+            windows_sys::Win32::System::Threading::TerminateProcess(
+                windows_sys::Win32::System::Threading::GetCurrentProcess(),
+                0x7C1_0003,
+            );
+            std::process::abort();
         }
         for (a, bytes) in &pages {
             std::ptr::copy_nonoverlapping(bytes.as_ptr(), *a as *mut u8, bytes.len());
@@ -137,6 +155,7 @@ pub(super) unsafe fn remake(device: &ID3D12Device, base: usize, size: usize) ->
     let groomed = groom(base, size);
     let reservations = groomed.len();
     let made = (|| -> Result<(ID3D12Heap, ID3D12Resource, usize), String> {
+        after_release()?;
         let properties = D3D12_HEAP_PROPERTIES {
             Type: D3D12_HEAP_TYPE_CUSTOM,
             CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
@@ -246,4 +265,41 @@ mod tests {
             assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
         }
     }
+
+    #[test]
+    fn failed_restore_stops_before_importing_an_unbacked_window() {
+        use super::*;
+        use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
+        const SIZE: usize = 1 << 16;
+        const CODE: i32 = 0x7C1_0003;
+        if std::env::var_os("XCL_TEST_RESTORE_COLLISION").is_some() {
+            unsafe {
+                let mut dev = None;
+                D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).unwrap();
+                let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize;
+                assert_ne!(base, 0);
+                (base as *mut u8).write(0x5a);
+                let result = remake_with_after_release(&dev.unwrap(), base, SIZE, || {
+                    let occupied = VirtualAlloc(base as *const c_void, SIZE, MEM_RESERVE, PAGE_NOACCESS);
+                    assert_eq!(occupied as usize, base);
+                    Err("synthetic post-release failure".into())
+                });
+                eprintln!("continued after failed restore: {result:?}");
+            }
+            return;
+        }
+        let mut dev: Option<ID3D12Device> = None;
+        if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev) }.is_err() {
+            return crate::gpu::recomp::runner::skip_test("no D3D12 device");
+        }
+        let output = std::process::Command::new(std::env::current_exe().unwrap())
+            .args(["--exact", "hle::d3d12x::uma_driver::tests::failed_restore_stops_before_importing_an_unbacked_window", "--nocapture"])
+            .env("XCL_TEST_RESTORE_COLLISION", "1")
+            .output()
+            .unwrap();
+        let transcript = format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
+        assert_eq!(output.status.code(), Some(CODE), "{transcript}");
+        assert!(transcript.contains("coherent window could not be restored"), "{transcript}");
+        assert!(!transcript.contains("continued after failed restore"), "{transcript}");
+    }
 }

AI use: Codex (GPT-6.2 Sol) traced the recovery path, wrote and ran the candidate and tests, and drafted this report. I checked the code and outputs before posting.

@S1m0ne1997

Copy link
Copy Markdown

Tested — RTX 4090, one pair in the world: GPU time of the console's work per frame 5,080 ms → 91 ms, 0.27 → 2.66 fps.

world, from 10 s after it starts =0 =1
time measured (about) 270 s 370 s
presents/s 0.27 2.66
console GPU time per frame (timestamps, queues may overlap) 5,080 ms 91 ms
device removals 0 0
process commit, last line 36.4 GB 43.4 GB
video memory local, last line 17.1 GB 20.2 GB
program, ms per call =0 =1
1b5466f261a70cde 1,081 1.4
b78fa10b425b8e54 413 23
3429c04607b00016 374 0.7
9dc85ad397cbaffe 247 below the 15 heaviest
19a1c1ba0b567618 228 below the 15 heaviest
56446569eccb04f0 223 2.4
67657769b50d2f8b 200 0.9
24de2aef6c31d55e 125 0.26

Seen: green flashes over the whole picture with =1. The =0 run showed only grey frames and some text, so this pair cannot tell whether the PR causes them.

Not tested: the test suite and smoke.ps1 on this head, a run without the driver profile, repeated pairs, AMD, Intel.

AI use: Claude Code (Claude Sonnet 5.5) built the tree, read the logs and wrote this report; I played the runs.

@Kalmarv
Kalmarv force-pushed the pr/uma-driver-window branch from fc007a9 to 50ae2eb Compare November 26, 2026 20:37
@Kalmarv

Kalmarv commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

@thehollowedone thank you, both lifecycle points confirmed and taken as posted, squashed into the PR commit in 50ae2eb with credit in its message:

  • Remap only before guest code: the backend (and with it the window and any driver remap) is made once in host_main before load_main; a backend first made later, and real::init(), only import. Your e2e assertion (D3D12.X: backend ' before the dependent DLL's DllMain() is in test_title_runs_and_game_folder_is_untouched. Since gpu::uma::get() creates the window on first use, the early init also makes the window itself before any guest pointer exists, so the snapshot taken there holds nothing the title wrote.
  • Failed rollback: if the window cannot be made again at its address after the release, XCL logs it, flushes and ends the process (0x7C10003); failed_restore_stops_before_importing_an_unbacked_window is in uma_driver::tests.

Tested on 50ae2eb, RTX 5070 Ti, Windows 11, Rust stable MSVC:

  • cargo test -p xcl --lib hle::d3d12x::uma_driver::tests:: -- --test-threads=1: 3 passed, 0 failed, 0 ignored
  • cargo test -p xcl --test e2e test_title_runs_and_game_folder_is_untouched -- --test-threads=1: 1 passed, 0 failed
  • cargo test --workspace --no-fail-fast -- --test-threads=4: 1448 passed, 3 failed, 47 ignored: the two link_tests that fail the same way on main here, and one list_x test that failed once beside other jobs and passed alone 3 of 3 (details in the description)
  • title ea3b5e4d, 480 s, same env and cache snapshot as the earlier runs: 2,937 frames (fc007a9: 2,841), 0 device removals, 0 crashes. The window became the driver heap before the title loaded, with 0 pages kept. Block in the description.

AI use: Claude Code, Claude Opus 5.5 checked both candidates against the code, applied them, ran the tests and the title run, and wrote this reply.

@thehollowedone

Copy link
Copy Markdown
Contributor

Independent Windows/NVIDIA recheck of #2844 at 50ae2eb, after the startup-ordering and failed-restore changes.

On Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti / 621.35, Rust 1.99.1 MSVC, DXC 1.8.2502.11:

  • cargo test --offline --locked -p xcl --lib hle::d3d12x::uma_driver::tests:: -- --test-threads=1 --nocapture: 3 passed, 0 failed, 0 ignored, 0 skipped. This includes the failed write-watch and post-release restore-collision regressions.
  • cargo test --offline --locked -p xcl --test e2e test_title_runs_and_game_folder_is_untouched -- --test-threads=1 --nocapture: 1 passed, 0 failed, 0 ignored. Its backend-before-DllMain assertion passed.
  • cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4 --nocapture: 1,451 passed, 0 failed, 47 ignored across 38 test targets. The log has 25 SKIPPED GPU notices (21 no native wave64, 3 refused per-lane f16 forms, 1 no heap windows); these are not coverage. XCL_DXIL_CACHE pointed to fresh writable scratch under target.

The full-suite synthetic title log shows one successful pre-guest remap: a 512 MB coherent window became a driver CUSTOM write-back L0 heap at its original address, remained write-watched, kept 0 pages, and passed the UMA import check. The backend log precedes the dependent DLL's DllMain. This exercises the successful remap path on this GPU; the forced child-process regression exercises the failed-restore path separately.

I checked the current diff and test output. No retail title, visual output, FPS comparison, or AMD/Intel run was performed here. AI use: Codex (GPT-6.2 Sol) inspected the revision, ran the tests, and drafted this report.

@SlopTart

Copy link
Copy Markdown

Linux (Wine) dual-lane run at head 50ae2eb8 - your AMD Wine lane is spotless, and two of your own new tests fail deterministically on real NVIDIA hardware under Wine. That's the vendor combo no Windows tester covers, and it's exactly where the UMA driver-heap path lives.

  • Rig: Ryzen 9 9900X, 96 GB DDR5, RX 7900 XT (Mesa 26.2.5 RADV), Arch, wine-11.0 Proton build + vkd3d-proton
  • Boxb: i5-10600K, 16 GB DDR4, GTX 1070 (550.163.01), Debian 13, stock wine-10.0 + vkd3d-proton, xvfb

Suite: cargo test --release --locked -p xcl --lib --target x86_64-pc-windows-gnu -- --test-threads=2 --skip gpu:: vs today's fresh main baseline (rig 606/2, boxb 605/3).

AMD Wine lane: 611/2. Their 5 new tests all green, red set identical to base. Clean PR on RADV.

NVIDIA Wine lane: 608/5. Base three plus two failures introduced here, both reproducible in isolation 3/3 with --exact:

  1. uma_driver::tests::failed_restore_stops_before_importing_an_unbacked_window (your new test):
panicked at crates/xcl/src/hle/d3d12x/uma_driver.rs:301:9:
assertion `left == right` failed:
  left: Some(1)
 right: Some(130088963)   (0x7c10003)
  1. title_textures::tests::title_bytes_leave_guard_pages_alone (new in this PR):
panicked at crates/xcl/src/hle/d3d12x/title_textures.rs:2785:17:
guard and no-access pages read as zeros

Both tests are new in this PR (they don't exist at main 8b957bec, so no base comparison is possible - the failures arrived with it). Both pass on the AMD/RADV lane, and the Windows/NVIDIA full-suite report on this same commit (RTX 3080 Ti, comment above) is fully green including the failed-restore regressions. So the failure axis is not "NVIDIA", it is NVIDIA-under-Wine: Pascal + 550-branch driver + stock wine-10 + vkd3d-proton is the only stack in this thread where these two assertions fire. The guard-page one suggests guard/no-access page semantics differ under this stack (reads not zeroing as expected), the uma one lands on a mismatched value where Some(1) was expected against 0x7c10003.

Caveats: we measure suite-level behavior only - the headline 4.9x FPS number is an in-game result we cannot reproduce here. Single suite run plus the solo confirmations above; nothing else moved in the red set.

AI use: Hermes agent (local Qwen-class) ran the tests and drafted this; I checked it before posting.

@VolenNakov

Copy link
Copy Markdown

Tested on a slower CPU: RTX 4060 Ti 16 GB with an i7-8700. #2844 halved the GPU's busy time in the world, but the present rate did not move, because this machine is held by the write-watch looks. One run per arm, head fc007a9 (before 50ae2eb).

Setup

run 72 (without) run 73 (with fc007a9)
world presents/s (300-frame lines) 1.1–1.2 1.1–1.2
GPU busy in the world (nvidia-smi every 5 s, 200–880 s) 49 % mean, ≥ 95 % in 26 of 107 samples 26 % mean, ≥ 95 % in 0 of 107
sparse windows timing: write-watch, cumulative at ~790 s 606 s 617 s
peak commit / video memory 30.9 / 13.1 GB 30.8 / 13.2 GB
errors / removals / wait timeouts 0 / 0 / 0 0 / 0 / 0

Not tested: 50ae2eb; more than one run per arm; with hot looks (XCL_WATCH_HOT, not on main).

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

@thehollowedone

Copy link
Copy Markdown
Contributor

Follow-up to the Wine/NVIDIA failures on head 50ae2eb. I traced both new failures against this PR's parent.

The guard-page test reaches a new fast path in read_committed_into: a successful whole-range ReadProcessMemory returns before VirtualQuery can mask guard and no-access pages. The parent queried protections first. The Wine result is consistent with that bypass, although the report does not show Wine's ReadProcessMemory return/count or VirtualQuery protections, so the exact API behavior remains to be measured. A narrow candidate retains the native Windows fast path and the previous query-first behavior under Wine:

Candidate diff against 50ae2eb
--- a/crates/xcl/src/hle/d3d12x/title_textures.rs
+++ b/crates/xcl/src/hle/d3d12x/title_textures.rs
@@ -1405,8 +1405,16 @@ unsafe fn read_committed_into(at: usize, out: &mut [u8]) {
-    // `ReadProcessMemory` refuses a range with a page that is not committed, no-access or a guard
-    // page (and leaves the guard in place: `title_bytes_leave_guard_pages_alone`).
+    // On native Windows, `ReadProcessMemory` refuses a range with a page that is not committed,
+    // no-access or guarded (and leaves the guard in place).
+    if len == 0 {
+        return;
+    }
+    // Under Wine, retain the original query-first path so protection checks cannot be
+    // bypassed by a successful whole-range read.
     let mut read = 0usize;
-    if len == 0 || ReadProcessMemory(GetCurrentProcess(), at as *const c_void, out.as_mut_ptr() as *mut c_void, len, &mut read) != 0 {
+    if !crate::util::under_wine()
+        && ReadProcessMemory(GetCurrentProcess(), at as *const c_void, out.as_mut_ptr() as *mut c_void, len, &mut read) != 0
+    {
         return;
     }

On Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti / 621.35, cargo test --offline --locked -p xcl --lib hle::d3d12x::title_textures::tests:: -- --test-threads=1 reported 21 passed, 0 failed, 0 ignored, with zero GPU skip notices, on this local candidate. Not tested: Wine/NVIDIA, the full workspace, or a title run. A Wine rerun of title_bytes_leave_guard_pages_alone and title_bytes_survive_concurrent_decommit, plus the API return/count and page protections, would establish whether this fixes the reported failure without weakening the test.

For failed_restore_stops_before_importing_an_unbacked_window, exit status 1 alone does not show whether the child terminated safely or panicked first. Please include the child's captured stdout/stderr (transcript in the parent test) before changing the expected code. The test should still require the restore error and reject continued after failed restore.

AI use: Codex (GPT-6.2 Sol) traced the code, prepared the candidate, ran the Windows tests, and drafted this report.

@joeypercia

Copy link
Copy Markdown
Contributor

@Kalmarv a port of this PR to nvidia-dev (eae01502), and what it did on a 12 GB card. Branch: joeypercia/xcl d3d12x-uma-driver-nvdev, one commit 20e128ac, your authorship, for you to take or leave. On nvidia-dev the driver heap is tried at the top of open_uma's per-window loop, before its import / video-memory shadow, and not with XCL_UMA_SHADOW=1; a shadowed or driver-heap window gets no ALLOW_CROSS_ADAPTER. cargo check --tests is clean; I have not run the suite on it.

Runs: RTX 4070 Ti 12 GB, driver 621.40, 2 GiB shader heap (#2590), Series S profile, XCL_UMA_WINDOWS=16 XCL_HEAP_WINDOWS=1 XCL_DIRECT_DXIL=1 XCL_TWO_PASS_MB=3072, the tree of #2867 with 3292b096 reverted (that commit crashes this setup), 900 s runs, warm caches.

coherent window XCL_UMA_DRIVER window became a driver heap end world presents/s
968 MB, XCL_COHERENT_HEAPS=sparse:1024 on yes (94 ms) device removed at 110 s (DRED page fault) –
same on yes 900 s cap 0.91
same 0 – 900 s cap 1.08
512 MB, default heaps on no: Map gave 0x14b070000, not the window's 0x1300000000, and it stayed imported as designed 900 s cap 1.36
4095 MB (XCL_COHERENT_MB=4095), default heaps on yes (245 ms) the title writes to a bad address at 184.5 s –
same on yes the title writes to a bad address at 155.1 s –
same 0 – device removed at 150.4 s (DRED page fault) –
  • With the big heaps moved out of the window (sparse:1024), there was no gain on this card: 0.91 against 1.08 presents/s on the same build. That fits the window holding little of the hot work then.
  • The layout where your PR should help most (heaps in a 4 GB window) does not survive the world load on this tree with or without the driver heap, so these runs cannot say whether it helps here.
  • The fallback works: on the 512 MB window the driver's mapping landed elsewhere, and the window stayed imported.

Not tested: the suite on the port; the 4 GB layout on a tree where it survives; a second card.

AI use: Claude Code (Claude Opus 5.5) ported the commit, ran the runs on the hardware above and wrote this.

@kole07139

Copy link
Copy Markdown

8 GB card (RTX 3070, Ampere) on an Intel i9-9900K: with this PR the title presents 2.5–3.2x as often in its world (0.74 and 0.93 presents/s against 0.29 with XCL_UMA_DRIVER=0 on the same exe, and 0.24 / 0.27 on the tree without the PR). No device removal or crash in any run. The green flashes @S1m0ne1997 saw follow the PR here: they were on screen in both runs with it and absent in the run without. No 8 GB card or Ampere run was in this thread yet.

Setup

Results (the world from the first ListX #101, about 100 s, to 420 s)

run 50ae2eb XCL_UMA_DRIVER world presents/s GPU busy in the world (nvidia-smi every 2 s) peak commit / local VRAM removals / crashes
K1 no – 0.24 – 33.4 / 12.5 GB 0 / 0
K2 no – 0.27 – 33.7 / 12.4 GB 0 / 0
H1 yes default 0.74 43 % mean, ≥ 95 % in 43 of 137 samples 37.4 / 13.9 GB 0 / 0
H2 yes 0 0.29 90 % mean, ≥ 95 % in 123 of 139 33.5 / 12.7 GB 0 / 0
H3 yes default 0.93 41 % mean, ≥ 95 % in 29 of 137 36.8 / 14.3 GB 0 / 0

Presents per 30 s in the world:

s 120 150 180 210 240 270 300 330 360 390
H1 (on) 37 34 32 22 6 37 33 0 0 8
H2 (=0) 8 7 2 7 7 8 9 10 8 7
H3 (on) 41 33 27 20 30 29 16 14 28 25
  • Without the PR the GPU is saturated in the world; with it, it is idle more than half the time. Same picture as @VolenNakov's 4060 Ti, but on this CPU the present rate does move.
  • H1's gap at 330–390 s is not this PR: three compute whole forms (0.82–0.90 MB DXIL, records cef865388bce9c18, 216494e34b60ed7c, fbf6fb1ab17fe036) were built cold one after another on a title thread, 20–24 s each, with no driver blob in the cache.
  • GetWriteWatch costs more with the PR because frames come faster: sparse windows timing: write-watch reached 56 s by 138 s (H1) and 51 s by 136 s (H3), against 56 s by 302 s (H2). That is the next limit here, as D3D12.X: the write-watch look scans 1.5 GiB before every submit while 4 pages are written (measurement and plan) #582 / D3D12.X: omit VRAM-only sparse tiles and GPU-written textures from write-watch ranges #2754 say.
  • What was on screen (watched by me, not measured): all three runs reach the same point of the prologue cutscene (the same subtitles), a dark city skyline with point lights. H1 and H3 run visibly smoother, with full-screen green flashes alternating with the normal picture; H2 has no green flashes.

Not tested: this PR on main alone (my tree has the stack above); joeypercia's nvidia-dev port; more than one run without the PR on this exe; the test suite on this tree; AMD; Wine.

AI use: Claude Code (Claude Opus 5.5) built the tree, ran the runs on my machine, read the logs and wrote this; I watched the runs and checked the report.

@afpruivo

Copy link
Copy Markdown

RTX 3090 24 GB at 50ae2eb8: 2.03–2.19 fps with the driver heap against 1.49–1.51 without it, same exe, runs in the order A B B A (plus one A rerun). GPU busy per frame drops from ~670 ms to ~200 ms, but a frame still takes ~500 ms with the GPU idle most of it, so on this machine too the frames are then held outside the GPU, as @VolenNakov found.

Setup

run arm world start frames in ~60 s fps frame time median (p90) GPU busy median CPU wait median
2 B 133 s 128 2.19 472 ms (606) 191 ms 9.3 ms
3 B 117 s 118 2.03 545 ms (636) 203 ms 9.6 ms
4 A 112 s 85 1.51 640 ms (1,191) 665 ms 9.2 ms
1 (rerun) A 120 s 85 1.49 658 ms (1,177) 686 ms 9.4 ms
  • The first A run does not count: its world started at 217 s, after the capture window, so PresentMon recorded the menus. It was rerun as the last row.
  • No device removal in any run. Each built 212–216 compute pipelines after its world start.
  • Without the PR the frames are GPU-bound (GPU busy ≈ frame time). With it, GPU busy is about 40 % of the frame time. I did not time the write-watch scans here, so I can't confirm that they are the rest.

For comparison, not the same tree: on nvidia-dev af2cecc4 + #2551 on the same machine, #2009's XCL_COHERENT_HEAPS=sparse:2048 (the 2199 MB heap in video memory) gave 3.03 fps against 1.37, still GPU-bound at ~320 ms (#2009 comment). This PR gets less on this card but spends no video memory. The two change different things and could be combined; I have not tried that.

Tests at 50ae2eb8: cargo test --release -p xcl --lib -- uma_driver gpu::uma: 15 passed, 0 failed, 0 ignored. The whole suite was not run on this head.

Not tested: the write-watch time with the PR; this PR on nvidia-dev (@joeypercia's port); together with sparse:2048; video memory and commit use; AMD.

AI use: Claude Code (Claude Opus 5.5) ran the runs and tests on my machine, read the PresentMon captures and the logs, and drafted this. Checked by me before posting.

@Kalmarv
Kalmarv force-pushed the pr/uma-driver-window branch from 50ae2eb to 342bf7d Compare November 26, 2026 22:56
… on NVIDIA

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]>
@thehollowedone

Copy link
Copy Markdown
Contributor

Independent Windows/NVIDIA recheck of #2844 at head f2248f0, after the Wine guard-page change. Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti / driver 621.35, Rust 1.99.1 MSVC.

cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4: 1,451 passed, 0 failed, 47 ignored across 38 targets. The log has 25 SKIPPED GPU notices; those are not coverage. The three uma_driver tests, title_bytes_leave_guard_pages_alone, and the synthetic title e2e test all passed. I used a fresh writable XCL_DXIL_CACHE under target and no XCL_SAMPLE_* variables were set.

This confirms the current head on native Windows. It does not resolve the NVIDIA-under-Wine report: the new query-first Wine path still needs a Wine rerun, and the failed-restore child test's exit code 1 still needs its captured transcript to locate the failure. The PR's Regression run block currently names prior head 50ae2eb; a smoke block from this head is still required by the repository's merge rules. No retail title was run for this check.

AI use: Codex (GPT-6.2 Sol) ran and checked the suite and drafted this report; Codex (GPT-6.2 Sol) independently reviewed the Wine failure and current code.

rootw0rm pushed a commit to rootw0rm/xcl that referenced this pull request Nov 26, 2026
rootw0rm pushed a commit to rootw0rm/xcl that referenced this pull request Nov 26, 2026
@Kalmarv

Kalmarv commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks all. On the points since 50ae2eb, now at f2248f0:

  • title_bytes_leave_guard_pages_alone on Wine/NVIDIA (@SlopTart; traced by @thehollowedone): @thehollowedone's candidate, same logic: under Wine read_committed_into skips the whole-range ReadProcessMemory and goes region by region as before; native Windows keeps the one-copy path. It is folded into this PR's commit, because it changes a line D3D12.X: title texture reads outside the coherent window use the safe copy #751's commit added, and that commit stays as D3D12.X: title texture reads outside the coherent window use the safe copy #751 has it. On Windows, cargo test -p xcl --lib hle::d3d12x::title_textures::tests:: -- --test-threads=1 gives 21 passed, 0 failed, and uma_driver::tests:: 3 passed, 0 failed. Not tested under Wine: a rerun of that test on the Wine/NVIDIA lane would settle it.
  • failed_restore_stops_before_importing_an_unbacked_window exits 1 on Wine/NVIDIA: I agree with @thehollowedone. The assertion prints the child's output after the two codes. @SlopTart, could you post it? It shows whether the child reached the restore error or failed before that, for example at D3D12CreateDevice or at the exact-address VirtualAlloc. The expected code stays as it is until then. The driver heap is off under Wine by default, so a title under Wine does not reach this path.
  • Green flashes (@S1m0ne1997, @kole07139): they show up in both reports with the driver heap and in neither without it, so I treat them as this PR's until shown otherwise. Our runs of ea3b5e4d cannot show them: this tree draws the world grey. About 100 frames are dumped per run, and none of the late ones is green; the intro's few green frames at 24-35 s also appear with XCL_UMA_DRIVER=0. Full-screen green is what a YUV-to-RGB pass gives when its planes read as zero (about RGB 0,135,0). My first candidate is a video frame read live from the window before its decoder has filled it; that is not tested. Could one of you run a flashing stretch with XCL_FRAME_DUMP=10 and post the present: frame N raw texels (most common) lines, or one screenshot of a flash? A flat colour near 0xff008700 would point at the video path.
  • i7-8700 (@VolenNakov) and i9-9900K (@kole07139): thank you. Both show the GPU freed and the write-watch look (D3D12.X: the write-watch look scans 1.5 GiB before every submit while 4 pages are written (measurement and plan) #582) as the next limit on the CPU side, so this PR alone moves the present rate only where the look is cheap.
  • nvidia-dev port (@joeypercia): thank you for the port and the runs. The 512 MB window that stayed imported is the first title run of the fallback (Map gave ..., not the window's ...), and it ran to the 900 s cap. The 4095 MB layout fails with and without the driver heap on that tree, so I cannot tell the PR's share there; nvidia-dev is not a branch I can test against.

The regression run on f2248f0 is in the description. Same 480 s, env and cache snapshot as before, in the queue's title lane beside other jobs: 2,939 frames, 0 device removals, 0 crashes. A first run on this head stopped presenting at ~591 s and the device was found removed when it ended, after would close a GPU cycle lines. On Windows this head runs the same code as 50ae2eb, whose run passed, and the rerun passed. That is one hang in the three runs of the two latest heads, and its cause is not known. It is in the description too.

AI use: Claude Code, Claude Opus 5.5 applied the change, ran the tests and the title run, and wrote this reply.

Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 27, 2026
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
xcl-dev#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]>
Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 27, 2026
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 xcl-dev#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]>
Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 27, 2026
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
xcl-dev#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]>
Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 27, 2026
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 xcl-dev#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]>
Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 27, 2026
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 xcl-dev#2844's head.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 27, 2026
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).
- An adapter without GPU_UPLOAD heaps (D3D12_OPTIONS16; Resizable BAR off)
  gets the single CUSTOM heap: this is asked before the window is released.
  A GPU_UPLOAD segment refused anyway becomes a write-watched CUSTOM
  segment, because the segments mapped before it cannot be given back: a
  dropped segment's pages stay with the driver (VirtualQuery still shows
  them committed seconds later, and a new heap of that size maps there
  again), so the window could not be reserved again (Windows error 487).
- 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 xcl-dev#2844's head.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Royalflamejlh

Copy link
Copy Markdown
Contributor

On Linux + NVIDIA under Wine 11.21, XCL_UMA_DRIVER=custom did not place the heap at the window in 2 of 2 runs, and both then hit our limit (34 GiB of memory, 8 GiB of swap) before the world load, at 46.8 and 52.9 s. Our tree without f2248f06 ran its 110 s run to the end, peaking at 29.7 GiB (1 run).

Setup: RTX 4060 Ti 16 GB, NVIDIA 615.71.09, Wine 11.21 Staging, vkd3d-proton v3.1-90-g30b0eb9b with local patches; f2248f06 cherry-picked onto the tree of our #2753 comment with #2753 in (7202055600: main b49be18 + twelve PRs, #751 among them); the switch set by hand (decide keeps it off under Wine).

[   19.479] D3D12.X: coherent window 3 stays imported: Map gave 0x7f2e50000000, not the window's 0xb00000000 (129 reservations)
[   14.825] D3D12.X: coherent window 3 stays imported: Map gave 0x7fd5a8c00000, not the window's 0xb00000000 (129 reservations)
  • At the kills the process had 33.3 and 33.6 GiB resident and its 8 GiB of swap full.
  • The remake ran from 0.4 s to the fallback line at 19.5 and 14.8 s; the title first presented at 23.3 and 19.0 s, against 3.7 s without the commit. On Windows the remake took 0.4–1.2 s (kole07139's log above).
  • A reading of Wine's source, not a run: in Wine 11.21 and 11.22, create_view writes one protection byte per 4 KiB page of every new range, reserved or not, and releasing a range frees none (alloc_pages_vprot, set_page_vprot, dlls/ntdll/unix/virtual.c). Over the 128 TiB groom can reserve, that is up to 32 GiB. Wine's development tree stopped this for reserved-only ranges on 2026-11-18 (571d2d4de7). Should custom be ignored under Wine until a release has it?
  • Kalmarv's two Wine tests passed here, debug, 3 of 3 each: title_bytes_leave_guard_pages_alone, and failed_restore_stops_before_importing_an_unbacked_window, whose child printed coherent window could not be restored … stopping before guest memory is used and exited with the expected 0x7C10003. SlopTart's stack differs (wine-10.0, GTX 1070, driver 550, release), so this does not show why it exits 1 there.

Not tested: this tree without the switch; the two tests at the earlier head 50ae2eb or on that stack; Wine's development tree; Windows.

AI use: Claude Code (Claude Opus 5.5) picked the commit onto our tree, ran the two tests, read the runs and Wine's source, and wrote this.

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

Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 27, 2026
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).
- An adapter without GPU_UPLOAD heaps (D3D12_OPTIONS16; Resizable BAR off)
  gets the single CUSTOM heap: this is asked before the window is released.
  A GPU_UPLOAD segment refused anyway becomes a write-watched CUSTOM
  segment, because the segments mapped before it cannot be given back: a
  dropped segment's pages stay with the driver (VirtualQuery still shows
  them committed seconds later, and a new heap of that size maps there
  again), so the window could not be reserved again (Windows error 487).
- A console buffer XCL places in the window whose first fit crosses two
  segments (no one heap holds it) goes to the next fit; the crossing block
  is given back instead of staying charged (alloc_in_one_heap).
- 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 xcl-dev#2844's head.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 27, 2026
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. A
pending read is over when a look sees its OVERLAPPED done, or when the
title uses that OVERLAPPED for its next read. 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
xcl-dev#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]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Kalmarv added a commit to Kalmarv/xcl that referenced this pull request Nov 27, 2026
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 xcl-dev#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]>
@Prime1997
Prime1997 merged commit fa671a2 into xcl-dev:main Nov 27, 2026
3 of 4 checks passed
@3L1A5-1

3L1A5-1 commented Nov 27, 2026

Copy link
Copy Markdown

Compatibility data point: the CUSTOM heap takes effect on a Turing card without Resizable BAR (RTX 2060 SUPER 8 GB), and a 300 s scripted run had no device removal or crash.

AI use: run by a Claude Code agent (Claude Sonnet 5.5), note by Claude Code (Claude Opus 5.5).

@SlopTart

Copy link
Copy Markdown

Regression check on merged #2844: failed_restore_stops_before_importing_an_unbacked_window is red on our NVIDIA+Wine lane in current main - deterministic, same assertion as before the squash.

Main fa671a2f (post-merge), both Wine lanes:

  • Boxb (i5-10600K, GTX 1070, 550.163.01, Debian 13, wine-10.0, xvfb): 609/4 = exactly the standing baseline three plus your new test. Panic unchanged from our run at 50ae2eb: uma_driver.rs:301:9, left: Some(1), right: Some(130088963) (= 0x7c10003). Solo at the merged sha: 3/3 FAILED (7.24 / 5.93 / 7.23 s, same assertion) - deterministic on NVIDIA-under-Wine.
  • Rig (Ryzen 9 9900X, RX 7900 XT, Mesa 26.2.5 RADV, Arch, wine-11.0 Proton): flaky on the AMD lane, not a hard red: 1 of 4 solo runs FAILED at a different, earlier assertion (uma_driver.rs:284:21, left: 0, right: 20381696, 17.75 s), the other 3 passed but slow (36.6 / 44.8 / 68.5 s). The 68 s run explains the "running for over 60 seconds" harness warning in one of our earlier suite runs - that is slowness on this lane, not a hang; green in the suite run proper.

Good news: your second test from yesterday's runs, title_bytes_leave_guard_pages_alone, is green on both lanes now at fa671a2f - something in the merge wave fixed whatever made it fail at 50ae2eb.

Context for the axis: at merge time the Windows+NVIDIA full suite was all-green (RTX 3080 Ti report on this thread); the deterministic red is the NVIDIA-under-Wine corner, while AMD+Wine is only intermittently red (and at a different assertion).

Suite cmd: cargo test --release --locked -p xcl --lib --target x86_64-pc-windows-gnu -- --test-threads=2 --skip gpu::, same-day baselines: boxb standing three, rig standing two.

AI use: Hermes agent (local Qwen-class) ran the tests and drafted this; I checked it before posting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.