Skip to content

Memory: defer private physical-home GPU tiles on NVIDIA - #3123

Closed
Prime1997 wants to merge 1 commit into
xcl-dev:mainfrom
Prime1997:codex/nvidia-private-home-tiles-20261128
Closed

Prime1997 wants to merge 1 commit into
xcl-dev:mainfrom
Prime1997:codex/nvidia-private-home-tiles-20261128

Conversation

@Prime1997

@Prime1997 Prime1997 commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

NVIDIA adaptation of CallMeBrado’s #1916, reviewed at e2aa856010a637d33adc2cf8b49766da91574747. Physical-page storage writes can allocate sparse GPU tiles before a title exposes that home to the GPU. XCL_DEFER_PRIVATE_HOME_TILES=1 defers this duplicate backing and queues the existing bytes when the home is explicitly mapped.

This targets nvidia-dev directly; it does not replace the original main-targeted PR or import the separate physical-page release/alias-identity integration. Default remains off. This is not a global VRAM cap or a claim that the previous device removal is solved.

What is in it

  • Remember whether a physical home has ever been exposed; exposed homes retain normal recommit behavior.
  • Replay storage bytes after mapping/copying home, including after consumed write-watch state and with ordinary storage hints disabled.
  • Add a pure state fixture and a child-isolated GPU round-trip fixture.

Tested

  • Standalone PR head: 6330fba1f3d2cfcfebef82d3032b38639f0b175e.
  • Combined integration d54d80e1bc9d070cbec4a619abb5f4b89880b2f5 compiled with cargo build --locked --release -p xcl --target-dir <isolated-target>: exit 0, 229.200 seconds. This is compilation of the combined candidate, not a build or runtime validation of this standalone PR. Zero tests executed; no GPU checks or smoke run.
  • Independent source review and git diff --check only, at 6330fba1f3d2cfcfebef82d3032b38639f0b175e.
  • Based directly on NVIDIA 54225f5884a94cd23b7aab3f703a7c975070aa77; one commit, four files, 162 insertions / 28 deletions.

Regression run
Not run. No smoke blocks or runtime test results are claimed.

Not tested
Build, fixtures, full suite, real-title behavior, NVIDIA/AMD hardware and actual memory savings have not been validated at this standalone head. Keep as draft pending validation.

AI use
Codex (GPT-6) adapted the existing contribution, inspected local SDK contracts, wrote fixtures and performed independent source review. Original behavior/design credit belongs to CallMeBrado’s #1916.

Optional contributor/test coordination: https://discord.gg/6B4TykyC4W

NVIDIA adaptation of CallMeBrado's xcl-dev#1916 at e2aa856. Keep storage-only homes CPU-backed until explicitly mapped, then replay preserved bytes even when ordinary storage write hints are disabled.

Based directly on nvidia-dev 54225f5, without the separate physical-page liveness, alias-identity or owner-sampler integration. Preserves NVIDIA's existing free/title mapping behavior. Prepared from integration abc027544; source-reviewed independently. Added fixtures are unrun, no native or build results claimed.

Assisted-by: Codex (GPT-6)
@Prime1997

Copy link
Copy Markdown
Collaborator Author

Failed interactive integration result for d54d80e1bc9d070cbec4a619abb5f4b89880b2f5, containing this PR's change together with the other memory/removal repairs. This was not a standalone test of 6330fba1f3d2cfcfebef82d3032b38639f0b175e and does not establish which change caused or prevented a symptom.

  • RTX 3060 Ti 8 GiB, 32 GiB system RAM, release, about 402 seconds with 126 read-only monitoring samples. XCL ended the title itself with 0x887a0005 (DEVICE_REMOVED); no external stop or automated inputs.
  • Peak process commit: 22,994 MiB; peak resident process-tree RAM: 15.79 GiB. Peak DXGI local usage: 6,839 MiB; all 196 console memory lines were below their simultaneous local budget, with minimum headroom 218 MiB. Sampling cannot rule out a transient overrun.
  • Last positive presentation interval was observed around 173 seconds. Audio/diagnostic activity continued during the later rendering stall.
  • DRED state was UNKNOWN. Both page-fault output and breadcrumbs returned 0x887a0004 (unsupported), so there is no reliable GPU fault location. System commit still had 34,764 MiB headroom at removal; no out-of-memory result was established.

The private-home path was active, with capped CPU-backing samples reporting up to 2,007 MiB still private. Final sparse pools were 1,472 MiB capacity / 1,471 MiB mapped. These partial CPU snapshots are not measured VRAM savings or directly comparable totals. The mixed build and changed cache make this unsuitable as a controlled A/B measurement.

This run does not justify merge approval or a claim that RAM growth/device removal is fixed. Full standalone validation and matching main/head smoke reports remain outstanding. No builds or synthetic GPU tests ran during gameplay. Logs, hashes, counter samples and source/installed-data preservation checks are retained locally.

AI use: OpenAI Codex (GPT-6) launched the prepared candidate at the user's request, monitored existing logs and read-only counters, and prepared this report; a separate Codex agent reviewed the log evidence.

Optional contributor/test coordination: https://discord.gg/gK3y7WRRY

@Gevroska

Copy link
Copy Markdown

I tested standalone head 6330fba1 on Windows. The CPU test exposed_physical_home_is_never_made_private_again passed. The native D3D12 test private_physical_pages_reach_the_gpu_on_mapping ran without a skip and failed at the first copy_back byte comparison. All 65,536 bytes in the first tile were 0xDD, the fixture’s CPU overwrite pattern. The expected value was 0xA7. The assertion stopped the test before it checked the other two tiles. Failing assertion

The fixture enabled XCL_DEFER_PRIVATE_HOME_TILES=1 and XCL_SPARSE_LAZY=1, with XCL_DS_KNOWN_WRITES=0. After MapTitlePhysicalPages, mapped_ranges() covered the three-tile interval and the pending count was zero. The tracker includes lazy entries that can still be waiting for GPU backing, and a zero pending count is also possible if no copy was submitted. The byte mismatch is reproducible evidence from this run; which stage produced it remains open. Tracker semantics

This was a standalone fixture run on the Windows default D3D12 device. The log didn’t identify the adapter model. I didn’t run a retail title or establish a connection to the combined integration failure.

I used OpenAI Codex with GPT-6.2 Sol to run the tests and review the fixture. A separate GPT-6.2 Sol agent verified the saved results. GPT-6.2 Astra drafted this comment.

I reviewed and approved this comment before posting.

@kole07139

Copy link
Copy Markdown

Test report for head 6330fba1. It confirms @Gevroska's result on another NVIDIA card and suggests a cause.

  • Library tests: 1772 passed, 7 failed, 28 ignored. exposed_physical_home_is_never_made_private_again passes. private_physical_pages_reach_the_gpu_on_mapping fails 3 of 3 when run alone, at sparse.rs:5305: the first tile reads 0xdd (the fixture's CPU overwrite) where 0xa7 is expected. That is the same failure Gevroska saw.
  • A possible cause, from the code, not instrumented: on nvidia-dev, land_page (sparse.rs:1065) does not overwrite a 64-byte chunk that the CPU changed since it was last sent: "a chunk the CPU wrote since it was last sent keeps its (newer) bytes and goes up with the next look". The fixture writes 0xdd over the home with the CPU right before readback_after_execute, then expects the GPU's bytes in the same chunks. On this base the copy-back keeps the 0xdd chunks, whether or not the deferred bytes reached the GPU. So the test may need to check the GPU copy without a CPU write in between (or check that it is the newer CPU write that wins), rather than the deferral being wrong.

Tested: NVIDIA GeForce RTX 3070 8 GB (driver 617.42, wave32), Intel i9-9900K, 32 GB RAM, Windows 11 Pro N 26200, rustc 1.99.0, DXC 1.8.2502.11, debug. Each head was tested alone, with its own target directory, on its base nvidia-dev 54225f58. The library tests were run as cargo test -p xcl --lib --no-fail-fast -- --test-threads=4 --skip a_refused_gpu_upload_segment_becomes_custom. That one test is left out because the library test binary stops at its fail-stop (0x7C10003), as throny reported on #3041, with or without this PR; alone it passes. On the base the same command gives 1771 passed, 6 failed, 28 ignored. The 6 failures (placed_title_textures_share_vram_and_preserve_pixels, three stream_recheck_*, d32s8_targets_take_their_own_size_of_video_memory, gpu_retire_queue_holds_heap_until_blocked_queue_passes_mark) are the base's own and are not repeated below.

I also merged the four heads #3122–#3125 together on 54225f58 (only README.md conflicts, plus the two new tests of #3123 and #3125 at the same place in sparse.rs; both kept). On that tree cargo test --workspace --no-fail-fast -- --test-threads=4 gives: library binary stopped at the same fail-stop; the other test binaries 132 passed, 0 failed, 20 ignored. The library command above: 1779 passed, 9 failed, 28 ignored, that is the base's 6 plus the 3 named below.

Not tested: a title run or smoke run of this head, a release build, AMD and Intel GPUs.

AI use: Claude Code (Claude Opus 5.5) ran the merges, builds and tests, and wrote this report.

@KDenKC

KDenKC commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

@Prime1997 a whole-suite run of your head on an RTX 3090 against its base on the same machine: your new GPU test fails here; nothing else changes.

Tested: 6330fba1 and its base nvidia-dev 54225f58.

  • RTX 3090 24 GB, NVIDIA 621.24, i7-10700T x8 (a VM with the GPU passed through), Windows 11 26H2 (26300.9974), Rust 1.99.1 (stable-x86_64-pc-windows-msvc), debug, no XCL_* set.
  • cargo test --workspace --no-fail-fast -- --test-threads=4 --skip uma_driver::tests::a_refused_gpu_upload_segment_becomes_custom --skip uma_driver::tests::mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment --skip uma_driver::tests::failed_restore_stops_before_importing_an_unbacked_window (the three end the lib test binary on 621.24, at the base too): base 1,900 passed, 7 failed, 48 ignored; head 1,901 passed, 8 failed, 48 ignored.
  • New on the head: sparse::tests::private_physical_pages_reach_the_gpu_on_mapping.
    • In its child process: sparse.rs:5305, assertion left == right. The GPU read [221, 221, …] (0xDD) where the test expects [167, 167, …] (0xA7): it saw other bytes than the private page's.
    • Then the parent: sparse.rs:5263, output.status.success().
    • The same alone (--exact … --nocapture --test-threads=1): 0 passed, 1 failed.
  • exposed_physical_home_is_never_made_private_again passes. The other 7 failures are the base's own on this VM (see D3D12.X: retire idle NVIDIA command pools between presents #3122's report).

Not tested: a title run with XCL_DEFER_PRIVATE_HOME_TILES=1; a release build; other GPUs.

AI use: an agent swarm: Claude Fable 5.2, Claude Opus 5.5, GPT-6.2-Sol and Gemini 4 Neon.

@vasanex

vasanex commented Nov 29, 2026

Copy link
Copy Markdown

Test report for head 6330fba1 on a 10 GB card (RTX 3080), with deferral off vs on in one binary, plus a test-only fix for private_physical_pages_reach_the_gpu_on_mapping that makes it pass here. This is not a merge-check: no full suite, no merge onto current main.

1. Deferral at the front end (#3211 E). One release binary of 6330fba1, XCL_DEFER_PRIVATE_HOME_TILES unset vs 1, interleaved after one 420 s warm-up run; XCL_PREPARE=0, an empty data root, otherwise defaults; retail title in its front end, 150 s per run; values from XCL's own memory: lines (every 2 s).

Run Sparse pool (mapped) Peak local Peak non-local Peak commit Presents
off-2 896 (837) MB 6,247 MB 4,827 MB 17,044 MB 4,319
on-2 320 (314) MB 5,671 MB 4,790 MB 21,415 MB (18,673 at the end) 4,316
off-1 ¹ 960 (951) MB 6,254 MB 4,841 MB 17,454 MB 4,321
on-1 ¹ 320 (314) MB 5,671 MB 4,873 MB 16,394 MB 4,317

¹ pair 1 got a stray manual input (one button press each, at 82.7 s / 28.5 s); pair 2 had none. Both pairs agree on the pool and local video memory.

  • Sparse pool 896 → 320 MB, local video memory −576 MB at the same work (equal presents, no crash, no device removal). Same 320 MB as on the 5090 and the 5070 Ti in Memory: defer GPU tiles for private physical page storage #1916.
  • Process commit: no conclusion from two pairs (lower in pair 1, a transient peak in pair 2).

1b. Loading the save (A presses). Same binary, interleaved after a warm-up, a data root with a save, A pressed every 4 s, 600 s per run, XCL_PREPARE=0, no other switches (so no system-memory pools). Every run stops presenting while loading, at 70–88 s, with local video memory far over the 9.3 GB budget. At the last presenting point:

Run Local video memory Sparse pool Outcome
off-1 13,069 MB 2,176 MB device removed 0x887a0006 (hung) at 71.3 s
on-1 12,072 MB 320 MB no presents after 82 s
off-2 14,860 MB 3,072 MB no presents after 82 s
on-2 12,114 MB 320 MB no presents after 80 s; scene start at 282 s, still no presents

So while loading, deferral takes ~2.75 GB off local video memory (pool 3,072 → 320 MB) – far more than in the front end – but on 10 GB the title still does not reach a rendering world with either setting; both stay about 2.8 GB or more over budget. Peak commit is the same in both arms (38–40 GB in the runs that did not end early). One device removal, in an off run, under that overload; not enough to say more about it.

2. Why the GPU test fails, and a test-only fix (#3211 A). The test fails here as on the 3070 / 3090: sparse.rs:5305, first tile 0xDD instead of 0xA7. As @kole07139 suggested, it fails whatever the deferral does: the test reads the CPU home after readback_after_execute, and land_page (sparse.rs:1065-1080) only lands GPU bytes into a 64-byte chunk whose hash still equals the one last sent; the fixture's own 0xDD overwrite (5295) changes every chunk, so nothing lands and the home reads 0xDD (also with no upload at all, or with the tiles still lazy). The fixture comes from #1916, whose base copied back unconditionally, so the 0xDD check made sense there.

The change below reads the window natively after the test queue's fence (as #3211 A step 5 asks), and adds checks so that a pass means something: only the written pages are queued for their first upload, their tiles have video memory and were mapped by the refresh (not by the test's own flush), the unwritten middle tile stays lazy, and the CPU home keeps its bytes. window_bytes now uses the window that holds the address (its other callers use window 0, unchanged).

Test-only diff (crates/xcl/src/hle/d3d12x/sparse.rs, +31/−7)
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 0152f3bc..924ae4fe 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -5293,17 +5293,40 @@ mod tests {
             assert!(mapped_ranges().iter().any(|&(a, b)| a <= home && home + n * TILE <= b));
             assert_eq!(windows_sys::Win32::System::Memory::ResetWriteWatch(home as *const c_void, n * TILE), 0);
+            // (the written pages, and only they, wait for their first upload)
+            let queued = super::super::title_textures::known_in(home, n * TILE);
+            let covers = |at: usize| queued.iter().any(|&(a, len)| a <= at && at < a + len);
+            assert!(covers(home) && covers(home + 2 * TILE), "the written pages are queued for their first upload: {queued:x?}");
+            assert!(!covers(home + TILE), "the unwritten page is not queued: {queued:x?}");
             super::super::title_textures::refresh(queue.as_raw());
-            std::ptr::write_bytes(home as *mut u8, 0xdd, n * TILE);
-            readback_after_execute(&queue, &[(home, n * TILE)], &[]);
+            // What the GPU holds, read natively once the test queue (which waits for the uploads)
+            // is done; the CPU home is not what is checked: a copy back keeps a chunk the CPU
+            // wrote since it was sent (`land_page`), so it would show the CPU's bytes either way.
+            let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+            queue.Signal(&fence, 1).unwrap();
             let started = std::time::Instant::now();
-            while RB_PENDING.load(Ordering::Acquire) != 0 && started.elapsed().as_secs() < 5 {
-                settle_readbacks();
+            while fence.GetCompletedValue() < 1 && started.elapsed().as_secs() < 5 {
                 std::thread::yield_now();
             }
-            assert_eq!(RB_PENDING.load(Ordering::Acquire), 0, "copy back did not finish");
-            let result = std::slice::from_raw_parts(home as *const u8, n * TILE);
+            assert_eq!(fence.GetCompletedValue(), 1, "the test queue did not finish");
+            let result = {
+                let mut g = lock_for_submit();
+                let s = g.as_mut().expect("sparse state");
+                for (k, what) in [(0, "first"), (2, "last")] {
+                    let e = s.mapped.get(&(home + k * TILE)).unwrap_or_else(|| panic!("the {what} tile is not mapped"));
+                    assert!(e.pool != LAZY, "the {what} tile has no video memory");
+                    assert!(!s.pending.contains(&(home + k * TILE)), "the {what} tile's mapping was sent by the refresh");
+                }
+                if lazy_commits() {
+                    assert!(s.mapped.get(&(home + TILE)).is_some_and(|e| e.pool == LAZY), "the unwritten tile got no video memory");
+                }
+                assert_eq!(s.window_index(home), s.window_index(home + n * TILE - 1), "one window holds the pages");
+                window_bytes(s, home, n * TILE)
+            };
             assert_eq!(&result[..TILE], &first);
             assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0));
             assert_eq!(&result[2 * TILE..], &last);
+            let cpu = std::slice::from_raw_parts(home as *const u8, n * TILE);
+            assert_eq!(&cpu[..TILE], &first, "the CPU home keeps its bytes");
+            assert_eq!(&cpu[2 * TILE..], &last, "the CPU home keeps its bytes");
             assert_eq!(FreeTitlePhysicalPages(null, n, pages.as_mut_ptr()), 1);
         }
@@ -6522,5 +6545,6 @@ mod tests {
         s.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back).expect("readback buffer");
         let back = back.expect("readback buffer");
-        let (base, window) = (s.windows[0].0, s.windows[0].1.clone());
+        let wi = s.window_index(va).expect("an address in a window");
+        let (base, window) = (s.windows[wi].0, s.windows[wi].1.clone());
         let alloc: ID3D12CommandAllocator = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc");
         let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list");
  • With it: passes 3 of 3 (cargo test -p xcl --lib --release private_physical_pages_reach_the_gpu_on_mapping -- --exact …), no SKIPPED: the private pages' bytes (A7 / zeros / 38) are in video memory at the first mapping on this card.
  • Control: with title_textures::take_known made to drop the queued ranges (local, reverted), it fails (the first tile has no video memory). That shows a missing replay is caught; it fails at the video-memory check, one step before the byte comparison, so a wrong-bytes upload is not shown to be caught separately.
  • cargo test -p xcl --lib --release sparse:: -- --test-threads=4, twice: head 73 passed / 1 failed (this test) / 1 ignored; with the change 74 / 0 / 1. (One parallel run showed a_tile_decommitted_and_committed_again_keeps_its_video_memory failing once; it passes alone on both trees and did not repeat.)

This covers first exposure only. It does not touch the later-write discrepancy from the RTX 4060 report in #3211 (0x5b CPU / 0x00 GPU), which land_page cannot explain.

Tested: RTX 3080 10 GB, NVIDIA 621.40, Ryzen 9 7950X, 64 GB RAM, Windows 11 (26200), Rust 1.100.0, release.

Not tested: the full suite; a merge onto current main (the head is on nvidia-dev 54225f58); a rendering world (not reached on this base on 10 GB, see 1b); AMD; the later-write case; repeats beyond two pairs.

AI use: Claude Code (Claude Opus 5.5) ran the runs and the tests, wrote the test change and wrote this comment; two further Claude agents reviewed the test change.

@andrewDoing

Copy link
Copy Markdown
Contributor

I checked recommit after moving an already-exposed physical page away at 6330fba1 on RTX 5070, driver 616.92. Three fresh-process runs returned the new data from native GPU memory. This extends the RTX 3080 first-exposure check.

The local test used one 64 KiB physical page with XCL_DEFER_PRIVATE_HOME_TILES=1, XCL_SPARSE_LAZY=1, and XCL_DS_KNOWN_WRITES=0. It used the production physical-page APIs and texture refresh:

  1. Write the private page with byte pattern (17*i + 0xA7) mod 256. Refresh and verify the sparse mapped ranges remain unchanged. Map the page at its home, refresh, fence, and read the mapped window with a native CopyBufferRegion.
  2. Move that same page to a separate reserved CPU address. Verify with VirtualQuery that the original home is now reserved and that its address is absent from the sparse mapped ranges.
  3. Write through write_physical_pages while away, this time with (17*i + 0x5B) mod 256. Verify those bytes at the away address, map back to the original home, verify the CPU bytes, refresh, fence, and read the GPU window again.

All 65,536/65,536 native bytes matched the first pattern on initial exposure and the second pattern after recommit in each run. Every byte differs between the patterns. Before either GPU copy the fixture required a concrete pool tile, no pending mapping for that home, and a completed queue fence. It issued no copy while the page was away.

This covers a full-page storage write while mapped away, followed by a normal refresh on remapping home. It leaves open the separate later-write case on an already-mapped home, the behavior of submissions that skip a write-watch scan, and retail memory usage.

AI-assisted fixture and verification.

@thehollowedone

Copy link
Copy Markdown
Contributor

Independent Windows check of head 6330fba1 with current main fa204595. I merged the two in a disposable worktree without committing, then ran the focused native tests on an RTX 3080 Ti (driver 621.35), Ryzen 7 9800X3D, Windows 11 build 26300. cargo check -p xcl --all-targets passed on that combination.

The existing private_physical_pages_reach_the_gpu_on_mapping fixture failed on standalone PR head at its first-tile comparison (0 passed, 1 failed, 0 ignored, no skip). That result has already been independently reported above. On the current-main combination, its first tile passed but the middle-tile assertion failed: the middle remains LAZY and has no GPU backing, so readback_after_execute leaves the fixture's 0xdd CPU bytes there. With the middle expectation corrected to LAZY/0xdd, this test passed (1 passed, 0 failed, 0 ignored, no skip), including its populated last tile. This is a test-only correction in an uncommitted integration, not a standalone-head pass or a retail run.

I also reproduced a separate protection-state problem on that combination. commit_homes calls sparse::committed(home, len) for the entire ready range when any page is CpuOnly. That marks an already exposed neighboring home writable again, clearing a recorded read-only 4 KiB page. A child-isolated regression using AllocateTitlePhysicalPages, MapTitlePhysicalPages, XCL VirtualProtect, and a second map failed at exposing neighbor must retain prior protection (not_rw changed from set to zero; 0 passed, 1 failed, 0 ignored, no skip). The path matters because known_writable can then give an affirmative answer for a protected page. Registering only the newly exposed private runs would avoid this particular overwrite; the fix also needs to preserve protection on a private home that was already read-only or no-access before exposure, and avoid reading such a page during replay. I have not validated a complete fix for those cases.

Test-only candidate diff for the two reproduced boundaries
@@ existing private_physical_pages_reach_the_gpu_on_mapping
-assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0));
+assert_eq!(STATE.lock().unwrap().as_ref().unwrap().mapped[&(home + TILE)].pool, LAZY);
+assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0xdd));

@@ additional child-isolated regression, after exposing the first of two homes
+let protected = home + PAGE;
+let mut old = 0;
+assert_ne!(VirtualProtect(protected as *const c_void, PAGE, PAGE_READONLY, &mut old), 0);
+assert_ne!(STATE.lock().unwrap().as_ref().unwrap().mapped[&home].not_rw & (1 << 1), 0);
+assert_eq!(MapTitlePhysicalPages(null, 2, 0, 4, pages.as_mut_ptr()) as usize, home);
+assert_ne!(STATE.lock().unwrap().as_ref().unwrap().mapped[&home].not_rw & (1 << 1), 0);

Commands: cargo test -p xcl --lib hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping -- --exact --test-threads=1 --nocapture and the same command with exposing_a_private_neighbor_keeps_an_exposed_home_read_only as filter. The whole workspace suite, clean-commit paired smoke, other adapters, and a retail title were not run for this scratch combination. AI use: Codex (GPT-6.2 Sol) ran the checks and wrote this report; Codex (GPT-6.2 Astra) independently traced the protection and lazy-tile paths.

@vasanex

vasanex commented Nov 29, 2026

Copy link
Copy Markdown
merge-check
base: fa204595a488c60c6c5f905244f0172072c9c2a9
head: 6330fba1f3d2cfcfebef82d3032b38639f0b175e
merge: clean (clashes with #3124 and #3125 in README.md, with #3125 also in the sparse.rs test module)
build: cargo build --workspace -> ok
tests: not run alone; in a stack of 11 of your PRs on this base: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2650 passed, 1 failed, 49 ignored; SKIPPED: 27 lines; failing: private_physical_pages_reach_the_gpu_on_mapping (this PR's test; not on the base). Alone: hle::d3d12x::sparse:: hle::d3d12x::title_textures:: hle::kernelx:: 265 passed, 1 failed (the same test), 3 ignored.
review: on main the test fails at another assertion than on nvidia-dev: the first tile is right now (main's land_page takes a list's own GPU writes, #3149), the middle tile keeps the fixture's own 0xDD because a lazy tile gets no copy back (`result[TILE..2 * TILE]` all zero). So my earlier explanation holds on main for the middle tile. The test-only native-readback version from my earlier comment passes 3 of 3 on main + this PR as well. thehollowedone's report from today (issuecomment-7250516040) has the same middle-tile result and corrects the expectation to LAZY/0xdd instead; the native readback additionally checks the bytes on the GPU. Runtime part: with the switch off nothing changes (private_home is false). With it on, the protection-state regression thehollowedone reproduced is visible in the code: commit_homes calls sparse::committed(home, len) for the whole range as soon as one page is CpuOnly (kernelx.rs, `if !ready || has_private`), and committed is committed_with_protection(.., writable = true), so an already exposed neighbour that the title made read-only is recorded writable again. My read-through had missed that (it took homes to be read-write). Free/reuse of a page and lock order read through, nothing found. Description is stale (says nvidia-dev, "zero tests"). Same feature as #1916 (#1607 D156); this one is the one that merges on main.
performance: off by default. 60 s smoke of the merged tree (ed24537c), switch off: 1681 frames, peak commit 16823 MB, 0 removals, 0 crashes (base 1629-1689 frames, 16065-16596 MB). Switch on, measured at this head on its own base: see my earlier comment (sparse pool 896 -> 320 MB in the front end).
verdict: not yet: with the switch on, exposing a private page resets the recorded protection of exposed neighbours (thehollowedone's regression); its own GPU test fails on main too - fold in a corrected test; refresh the description
hardware / tool and model: RTX 3080 10 GB 621.40, Ryzen 9 7950X, Windows 11 26200 / Claude Code (Claude Opus 5.5, Claude Fable 5.2)

How this was run: the suite ran once on the 11 of your PRs that build on this base, merged together (#3047 #3048 #3049 #3091 #3092 #3103 #3104 #3105 #3107 #3123 #3125; a local tree, only #3125 needed a resolution in README and the sparse.rs test module); the base alone gave 2608 passed, 0 failed, 49 ignored with the same 27 SKIPPED lines (21 no wave64, 3 refused per-lane f16/f32 forms, 2 heap windows opt-in, 1 driver cache needs Developer Mode). This PR alone was merged onto the base, built (cargo build --workspace, then release), its modules' lib tests run (debug), and smoke-run once for 60 s (scripts/smoke.ps1, retail title, front end, XCL_PREPARE=0). The smoke numbers are for my local merged tree, not a clean-head block for the description.

AI use: Claude Code (Claude Opus 5.5 and Claude Fable 5.2) ran the builds, tests and title runs, reviewed the diff and wrote this; the code points cited were checked against the merged tree.

@lnqigr

lnqigr commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Independent RTX 4060 Laptop GPU check for #3211, on Windows 11 build 26300.9974, NVIDIA driver 610.88 and Rust 1.100.0.

Late CPU writes. On the exact parent 54225f5884a94cd23b7aab3f703a7c975070aa77 and PR head 6330fba1f3d2cfcfebef82d3032b38639f0b175e with deferral off and on, I ran three fresh processes per configuration and write route (CPU pointer and storage helper). All 18 passed, 0 failed, 0 ignored, 0 skipped. A separate native GPU readback after the production queue submission and fence matched all 65,536 bytes of the middle page in every run. The earlier CPU/GPU mismatch did not reproduce.

Read-only protection. I independently confirmed the reported protection regression on a local merge of 7a649b0e7341c1daf1bcf2f3101e9518a8a8c16f with 6330fba1f3d2cfcfebef82d3032b38639f0b175e. Clean main and the merge with deferral off each had 3 passed, 0 failed. With deferral on the merge had 0 passed, 3 failed. No skips or ignored tests in these runs. Windows retained PAGE_READONLY, while XCL's tracker reported the page writable after the neighbor was mapped.

Commands. Both fixtures were built in debug with cargo test --offline --locked -p xcl --lib --no-run -j 4. The late-write fixture ran in the resulting test binary with --exact hle::d3d12x::sparse::tests::qualifying_late_physical_write_reaches_native_gpu_memory --nocapture --test-threads=1. The protection check ran with cargo test --offline --locked -p xcl --lib -j 4 hle::d3d12x::sparse::tests::exposing_a_private_neighbor_keeps_an_exposed_home_read_only -- --exact --test-threads=1 --nocapture. Both used XCL_SPARSE_LAZY=1, XCL_DS_KNOWN_WRITES=0, and XCL_DEFER_PRIVATE_HOME_TILES=0/1 as applicable.

Not tested. No-access protection, the full workspace suite, retail smoke and AMD.

AI use. Codex (GPT-6) prepared the local fixtures, ran the tests and drafted this report.

@Prime1997 Are you already working on the protection fix? I can independently retest an updated head, or help prepare a patch if useful.

@Kalmarv

Kalmarv commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

merge-check
base: beeb81b (mergeable cleanly on current main)
head: 6330fba
merge: clean
build: cargo check -p xcl --all-targets -> ok
tests: non-GPU lib tests of touched modules (sparse 19 passed, title_textures 7 passed / 1 ignored, kernelx 52 passed / 1 ignored). Full workspace suite and hardware-sparse GPU test not run.
review: none blocking. Opt-in via XCL_DEFER_PRIVATE_HOME_TILES=1; per-page state is cleaned up on FreeTitlePhysicalPages and exposure is one-way.
performance: off by default. In a combined 600 s run with XCL_DEFER_PRIVATE_HOME_TILES=1 + XCL_TEXTURE_DROP_LEVELS=1 (#2968), local video memory dropped 2.3-2.6 GB (11.87-12.16 vs 14.19-14.76 GB), sparse tiles -1.5 GB, peak commit -3.0 GB (32,052 vs 35,016 MB), 0 removals, 0 crashes. Tested in a combined 600 s retail run on main beeb81b + 13 PRs (warm cache, defaults) vs baseline: presents/2 s 3.27 vs 3.29, peak commit 35,016 vs 35,767 MB, local video memory 14.19-14.76 vs 14.32-14.95 GB, 0 pipeline waits >= 1 s vs 5, 0 device removals, 0 crashes. Combined result across all 13 PRs, not isolated to this PR.
verdict: not yet: full workspace suite and hardware-sparse GPU test not run.
hardware / tool and model: NVIDIA GeForce RTX 5070 Ti, driver 32.0.16.1074, AMD Ryzen 9 9950X, Windows 11 Pro 26200 / Claude Code (claude-opus-5-5)

@github-actions github-actions Bot added area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH labels Nov 29, 2026
@github-actions github-actions Bot added area:memory Virtual/physical memory, arenas, VRAM budget, UMA gpu:nvidia Code is specific to NVIDIA / wave32 GPUs (scope tag; see needs:nvidia-test) needs-pr-check Failing the PR description check (CONTRIBUTING.md) labels Nov 29, 2026

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical review of current head 6330fba1. Blocking correctness evidence: the new native GPU round-trip test private_physical_pages_reach_the_gpu_on_mapping failed independently on multiple NVIDIA cards: the first tile returned the CPU overwrite pattern 0xDD instead of the expected earlier storage bytes 0xA7 (see test reports). The pure state test does not cover the write-watch/replay order that failed. Please resolve this at the exact standalone head and require that GPU fixture to pass with deferral on and off before promotion; the feature can otherwise expose stale/incorrect physical-home contents. No local GPU run.

@vasanex

vasanex commented Nov 29, 2026

Copy link
Copy Markdown

@bmjask one correction to the evidence, not to the conclusion that this is not ready.

The failing GPU test does not show stale physical-home contents. private_physical_pages_reach_the_gpu_on_mapping fails with deferral off as well as on, because of what the fixture reads, not because of what the GPU holds:

  • The test overwrites the CPU home with 0xDD and then reads that home after the copy back. land_page only lands GPU bytes into a 64-byte chunk whose hash still equals the one last sent; the fixture's own overwrite changes every chunk, so nothing lands and the home reads 0xDD. The fixture comes from Memory: defer GPU tiles for private physical page storage #1916, whose base copied back unconditionally. (Cause suggested by @kole07139; details in my report.)
  • On current main the first tile already reads right (main's land_page takes a list's own GPU writes, D3D12.X: a list's own GPU writes land in a sparse chunk the CPU changed #3149) and the test fails at the middle tile instead, which is lazy and gets no copy back – @thehollowedone has the same result (report).
  • A test-only version that reads the window natively after the queue's fence, and checks that only the written pages are queued and mapped, passes 3 of 3 here on the PR's base and on main + this PR (diff in my report). So on this card the bytes on the GPU are the expected ones with deferral on.

What does block it, in my reading: with the switch on, exposing a private page records already exposed neighbours as writable again (commit_homes → sparse::committed for the whole range), the regression @thehollowedone reproduced; plus the test needs to be replaced by one that passes for the right reason, and the description refreshed. That is what my merge-check says ("not yet").

So "require the GPU fixture to pass with deferral on and off" is right, but with the corrected fixture; the current one cannot pass on main either way.

Not tested for this reply: nothing new. The runs above are on an RTX 3080 10 GB (621.40), Ryzen 9 7950X, Windows 11 26200, heads as named in the linked comments. AI use: Claude Code (Claude Fable 5.2) wrote this from our earlier reports; read and posted by me.

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Review (head 6330fba, diff read, not a merge-check; draft, so not built or run):

  • Duplicate of Memory: defer GPU tiles for private physical page storage #1916 (CallMeBrado, open, not a draft, targets main, same XCL_DEFER_PRIVATE_HOME_TILES switch and design). Since Merge nvidia-dev into main (makes #2572 mergeable) #3203 put nvidia-dev into main, both target main, so a maintainer needs to pick one.
  • Nothing limits it to NVIDIA: it's switched only by the environment variable, so it applies to every vendor; the title, README and "targets nvidia-dev" no longer match a PR against main. The branch sits on 54225f5, before Merge nvidia-dev into main (makes #2572 mergeable) #3203 and four later kernelx commits; it merges cleanly onto d0832e6 but was never built there.
  • No test was executed, private_physical_pages_reach_the_gpu_on_mapping was never run, and there are no smoke runs.
  • Minor: home_pages[&at] (kernelx.rs ~2125) would panic if an address in the run were missing from the map; impossible today (homes are 64 KiB aligned), but .get() would be safer since the line also runs with the setting off.

Fine: with the setting off the calls are the same as main's. A home only becomes visible to the GPU through MapTitlePhysicalPages at its home, where the tiles are committed before the stored bytes are queued for upload after the copies home; exposure is sticky, freeing a page clears its entry, and the test covers writes an earlier write-watch look already consumed.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

@thehollowedone

thehollowedone commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Updated consolidated check for #3123 head 6330fba1, test-merged onto main d0832e6. The original report's read-only failure still reproduces. An expanded test found a second failure: when the neighboring home is reserved, commit_homes calls VirtualAlloc(MEM_COMMIT, PAGE_READWRITE) over the entire range, which changes the already exposed neighbor from PAGE_READONLY to PAGE_READWRITE in Windows. When both homes are already committed, Windows keeps the protection, but the following sparse::committed(home, len) clears its non-writable tracker bit. Both paths need correction.

The local candidate commits only the reserved subranges, queries the resulting protection runs, and publishes their actual writability. It also serializes sparse-overlapping VirtualProtect / own-process VirtualProtectEx with physical-page mapping through the existing AWAY lock, so a protection change cannot be overwritten by a stale query result. Non-sparse protection calls avoid that lock. It validates all query spans before updating the sparse tracker and decommits newly committed spans if validation fails.

Local verification — Windows 11 build 26300, RTX 3080 Ti / NVIDIA 621.40, Ryzen 7 9800X3D, rustc 1.99.1 MSVC, debug:

  • The earlier read-only GPU regression failed on the unchanged merged PR with deferral on: 0 passed, 1 failed, 0 ignored, no skip. An intermediate protection-only candidate passed the already-committed case but failed when the adjacent home was still reserved; Windows reported PAGE_READWRITE after that call. With the complete local candidate, the expanded child-isolated test passes six cases (read-only, no-access, guard × adjacent home reserved/already committed) with deferral on and off: each parent invocation 1 passed, 0 failed, 0 ignored, 0 skips. Windows protection and the sparse non-writable bit agree in every case.
  • cargo test --offline --locked -p xcl --lib hle::kernelx:: -- --test-threads=4: 67 passed, 0 failed, 1 ignored, 0 SKIPPED.
  • cargo test --offline --locked -p xcl --lib hle::d3d12x::sparse::tests:: -- --test-threads=4: 142 passed, 0 failed, 1 ignored, 0 SKIPPED. This includes the previously proposed native GPU-readback correction to the PR's private_physical_pages_reach_the_gpu_on_mapping fixture; without that test-only correction, the original CPU-home oracle still fails at the middle tile.
  • cargo build --offline --locked --workspace passed. git diff --check is clean.
Local candidate diff against the current-main PR merge
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 131f3a00..a8c68bff 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -8439,6 +8439,65 @@ fn forget_in(s: &mut State, res: usize) {
 mod tests {
     use super::*;
 
+    #[test]
+    fn private_neighbor_preserves_exposed_protection() {
+        const CHILD: &str = "XCL_TEST_PRIVATE_NEIGHBOR_PROTECTION";
+        if std::env::var_os(CHILD).is_none() {
+            for (write_private, protection) in [
+                ("0", "readonly"), ("1", "readonly"), ("0", "noaccess"), ("1", "noaccess"), ("0", "guard"), ("1", "guard"),
+            ] {
+                let output = std::process::Command::new(std::env::current_exe().unwrap())
+                    .args(["--exact", "hle::d3d12x::sparse::tests::private_neighbor_preserves_exposed_protection", "--nocapture"])
+                    .env(CHILD, "1")
+                    .env("XCL_TEST_PRIVATE_WRITE", write_private)
+                    .env("XCL_TEST_PROTECTION", protection)
+                    .env("XCL_DEFER_PRIVATE_HOME_TILES", std::env::var("XCL_TEST_DEFER_FLAG").unwrap_or_else(|_| "1".into()))
+                    .env("XCL_SPARSE_LAZY", "1")
+                    .output().unwrap();
+                print!("{}", String::from_utf8_lossy(&output.stdout));
+                eprint!("{}", String::from_utf8_lossy(&output.stderr));
+                assert!(output.status.success(), "private write={write_private}, protection={protection}");
+            }
+            return;
+        }
+        use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, VirtualProtect, write_physical_pages};
+        use windows_sys::Win32::System::Memory::{PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE};
+        unsafe {
+            let dev = test_device();
+            if software(&dev) { return crate::gpu::recomp::runner::skip_test("no hardware sparse adapter"); }
+            let Some(u) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no UMA"); };
+            if !u.has_sparse() { return crate::gpu::recomp::runner::skip_test("no sparse windows"); }
+            let windows = init(&dev);
+            if windows.is_empty() { return crate::gpu::recomp::runner::skip_test("no reserved sparse buffers"); }
+            for (_, raw, _) in windows { drop(ID3D12Resource::from_raw(raw as *mut c_void)); }
+            let mut pages = [0usize; 2];
+            let mut n = pages.len();
+            let null = std::ptr::null_mut();
+            assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1);
+            let home = MapTitlePhysicalPages(null, 1, 0, 4, pages.as_mut_ptr()) as usize;
+            assert_ne!(home, 0);
+            let mut old = 0;
+            let protection = match std::env::var("XCL_TEST_PROTECTION").as_deref() {
+                Ok("noaccess") => PAGE_NOACCESS,
+                Ok("guard") => PAGE_READWRITE | PAGE_GUARD,
+                _ => PAGE_READONLY,
+            };
+            assert_ne!(VirtualProtect((home + PAGE) as *const c_void, PAGE, protection, &mut old), 0);
+            let mask = 1 << 1;
+            assert_ne!(STATE.lock().unwrap().as_ref().unwrap().mapped[&home].not_rw & mask, 0);
+            if std::env::var("XCL_TEST_PRIVATE_WRITE").as_deref() == Ok("1") {
+                assert!(write_physical_pages(&pages[1..], 0, &[0x5a]));
+            }
+            assert_eq!(MapTitlePhysicalPages(null, n, 0, 4, pages.as_mut_ptr()) as usize, home);
+            let mut mbi: windows_sys::Win32::System::Memory::MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            assert_ne!(windows_sys::Win32::System::Memory::VirtualQuery((home + PAGE) as *const c_void, &mut mbi, std::mem::size_of_val(&mbi)), 0);
+            assert_eq!(mbi.Protect, protection, "Windows protection changed when exposing the neighbor");
+            assert_ne!(STATE.lock().unwrap().as_ref().unwrap().mapped[&home].not_rw & mask, 0,
+                "exposing the private neighbor must preserve the first page's protection state");
+            assert_eq!(FreeTitlePhysicalPages(null, n, pages.as_mut_ptr()), 1);
+        }
+    }
+
     /// Adapted from CallMeBrado's #1916: consumed CPU writes still reach first GPU exposure.
     #[test]
     fn private_physical_pages_reach_the_gpu_on_mapping() {
@@ -8483,19 +8542,38 @@ mod tests {
             assert_eq!(home, first_home as usize);
             assert!(mapped_ranges().iter().any(|&(a, b)| a <= home && home + n * TILE <= b));
             assert_eq!(windows_sys::Win32::System::Memory::ResetWriteWatch(home as *const c_void, n * TILE), 0);
+            let queued = super::super::title_textures::known_in(home, n * TILE);
+            let covers = |at: usize| queued.iter().any(|&(a, len)| a <= at && at < a + len);
+            assert!(covers(home) && covers(home + 2 * TILE), "written homes need an upload: {queued:x?}");
+            assert!(!covers(home + TILE), "unwritten home should not be queued: {queued:x?}");
             super::super::title_textures::refresh(queue.as_raw());
-            std::ptr::write_bytes(home as *mut u8, 0xdd, n * TILE);
-            readback_after_execute(&queue, &[(home, n * TILE)], &[]);
+            let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+            queue.Signal(&fence, 1).unwrap();
             let started = std::time::Instant::now();
-            while RB_PENDING.load(Ordering::Acquire) != 0 && started.elapsed().as_secs() < 5 {
-                settle_readbacks();
+            while fence.GetCompletedValue() < 1 && started.elapsed().as_secs() < 5 {
                 std::thread::yield_now();
             }
-            assert_eq!(RB_PENDING.load(Ordering::Acquire), 0, "copy back did not finish");
-            let result = std::slice::from_raw_parts(home as *const u8, n * TILE);
+            assert_eq!(fence.GetCompletedValue(), 1, "test queue did not finish");
+            let result = {
+                let mut g = lock_for_submit();
+                let s = g.as_mut().expect("sparse state");
+                for k in [0, 2] {
+                    let e = s.mapped.get(&(home + k * TILE)).expect("written home mapped");
+                    assert_ne!(e.pool, LAZY, "written home has video memory");
+                    assert!(!s.pending.contains(&(home + k * TILE)), "written home mapping was submitted");
+                }
+                if lazy_commits() {
+                    assert!(s.mapped.get(&(home + TILE)).is_some_and(|e| e.pool == LAZY), "unwritten home stays lazy");
+                }
+                assert_eq!(s.window_index(home), s.window_index(home + n * TILE - 1));
+                window_bytes(s, home, n * TILE)
+            };
             assert_eq!(&result[..TILE], &first);
             assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0));
             assert_eq!(&result[2 * TILE..], &last);
+            let cpu = std::slice::from_raw_parts(home as *const u8, n * TILE);
+            assert_eq!(&cpu[..TILE], &first);
+            assert_eq!(&cpu[2 * TILE..], &last);
             assert_eq!(FreeTitlePhysicalPages(null, n, pages.as_mut_ptr()), 1);
         }
     }
@@ -11351,7 +11429,8 @@ mod tests {
         let mut back: Option<ID3D12Resource> = None;
         s.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back).expect("readback buffer");
         let back = back.expect("readback buffer");
-        let (base, window) = (s.windows[0].0, s.windows[0].1.clone());
+        let wi = s.window_index(va).expect("address in a window");
+        let (base, window) = (s.windows[wi].0, s.windows[wi].1.clone());
         let alloc: ID3D12CommandAllocator = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc");
         let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list");
         list.CopyBufferRegion(&back, 0, &window, (va - base) as u64, len as u64);
diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs
index 0231cdbc..290d15f8 100644
--- a/crates/xcl/src/hle/kernelx.rs
+++ b/crates/xcl/src/hle/kernelx.rs
@@ -1333,6 +1333,7 @@ pub unsafe extern "system" fn VirtualAllocEx(proc_: HANDLE, addr: *const c_void,
 }
 
 pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL {
+    let _mapping = sparse_protection_overlap(addr, size).then(|| AWAY.lock().unwrap());
     let protection = sanitize_protect(p);
     let writable = read_write(protection);
     if !writable {
@@ -1346,8 +1347,9 @@ pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p
 }
 
 pub unsafe extern "system" fn VirtualProtectEx(proc_: HANDLE, addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL {
-    let protection = sanitize_protect(p);
     let own = own_process(proc_);
+    let _mapping = (own && sparse_protection_overlap(addr, size)).then(|| AWAY.lock().unwrap());
+    let protection = sanitize_protect(p);
     let writable = read_write(protection);
     if own && !writable {
         note_protection(addr, size, protection);
@@ -1359,6 +1361,17 @@ pub unsafe extern "system" fn VirtualProtectEx(proc_: HANDLE, addr: *const c_voi
     ok
 }
 
+fn sparse_protection_overlap(addr: *const c_void, size: usize) -> bool {
+    let start = addr as usize;
+    let end = start.saturating_add(size);
+    crate::gpu::uma::get().is_some_and(|u| {
+        (0..u.shader_windows()).any(|k| {
+            let (base, bytes) = u.window(k);
+            u.is_sparse_window(k) && start < base.saturating_add(bytes) && base < end
+        })
+    })
+}
+
 /// XALLOC_ATTRIBUTES bit fields.
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 pub struct XAllocAttrs {
@@ -2190,16 +2203,63 @@ unsafe fn commit_homes(home: usize, pages: &[usize], away: &mut Away) -> Option<
     let n = pages.len();
     let len = n * PHYS_PAGE;
     let ready = committed_range(home, len);
-    if !ready && mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() {
-        crate::xlog_warn!("physical pages: {n} at their home {home:#x} could not be committed");
-        return None;
+    let mut newly_committed = Vec::new();
+    if !ready {
+        let end = home + len;
+        let mut at = home;
+        while at < end {
+            let mut m: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            let queried = mem::VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m));
+            let stop = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end);
+            let valid = queried != 0 && stop > at;
+            let committed = if valid && m.State == mem::MEM_RESERVE {
+                !mem::VirtualAlloc(at as *const c_void, stop - at, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null()
+            } else {
+                valid && m.State == mem::MEM_COMMIT
+            };
+            if !committed {
+                for (start, bytes) in newly_committed {
+                    mem::VirtualFree(start as *mut c_void, bytes, mem::MEM_DECOMMIT);
+                }
+                crate::xlog_warn!("physical pages: {n} at their home {home:#x} could not be committed");
+                return None;
+            }
+            if m.State == mem::MEM_RESERVE {
+                newly_committed.push((at, stop - at));
+            }
+            at = stop;
+        }
     }
     let mut replay = Vec::new();
     if u.is_sparse(home) {
         let private = |p: &usize| away.sparse_homes.get(p) == Some(&SparseHome::CpuOnly);
         let has_private = defer_private_home_tiles() && pages.iter().any(private);
         if !ready || has_private {
-            crate::hle::d3d12x::sparse::committed(home, len);
+            let mut at = home;
+            let mut protections = Vec::new();
+            while at < home + len {
+                let mut m: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+                if mem::VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 {
+                    for (start, bytes) in newly_committed {
+                        mem::VirtualFree(start as *mut c_void, bytes, mem::MEM_DECOMMIT);
+                    }
+                    crate::xlog_warn!("physical pages: could not query home protection at {at:#x}");
+                    return None;
+                }
+                let stop = (m.BaseAddress as usize + m.RegionSize).min(home + len);
+                if stop <= at || m.State != mem::MEM_COMMIT {
+                    for (start, bytes) in newly_committed {
+                        mem::VirtualFree(start as *mut c_void, bytes, mem::MEM_DECOMMIT);
+                    }
+                    crate::xlog_warn!("physical pages: home {at:#x} was not committed after allocation");
+                    return None;
+                }
+                protections.push((at, stop - at, read_write(m.Protect)));
+                at = stop;
+            }
+            for (at, bytes, writable) in protections {
+                crate::hle::d3d12x::sparse::committed_with_protection(at, bytes, writable);
+            }
         }
         if has_private {
             let mut at = home;

This is a tested candidate for the PR author, not a merge check. The full workspace suite, paired smoke, and a title-level performance comparison were not run. The sparse-overlap lock order was source reviewed; the query/protection race has not had a deterministic interleaving test. Alternate protection APIs that bypass XCL's VirtualProtect wrappers are outside this candidate's coverage. #1916 still overlaps the feature and needs a maintainer choice.

AI use: OpenAI Codex (GPT-6.2 Sol) prepared the candidate, ran the tests, and drafted this update; a Codex specialist independently reviewed the lock and tracker lifecycle.

lucsoft added a commit to lucsoft/xcl that referenced this pull request Dec 1, 2026
private_physical_pages_reach_the_gpu_on_mapping came to amd-dev with
87e900b (the NVIDIA adaptation of xcl-dev#1916, xcl-dev#3123) unrun. Unlike xcl-dev#1916's
fixture it sets XCL_SPARSE_LAZY=1, so the untouched middle page is
committed as a LAZY tile with no video memory. A copy back skips such a
tile (nothing to copy, the window reads zeros there), which leaves the
fixture's own 0xdd CPU overwrite in place, and the zero check failed
every time.

Check what lazy commits promise instead: the middle tile has no video
memory and the CPU's bytes stay. Without lazy commits the old zero
check still applies. The written pages are checked as before. This
matches the diagnosis on xcl-dev#3123 (thehollowedone, vasanex).
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Test report (not a merge-check: draft, PR description red)
base: b2b1f10
head: 6330fba
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2903 passed, 2 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping
review: not repeated here; my review of this same head is at #3123 (comment), and its findings stand. This run adds what reading couldn't: whether the change merges, builds and passes the whole suite on current main.
performance: no smoke run.
assessment: its own new test fails on this NVIDIA card: hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping (it runs itself in a child process, so it counts as 2 failures: the child, and the parent that checks it). The child's output in the log doesn't include the assertion message, so I can't say which check fails, only that the private physical pages don't reach the GPU on mapping here (RTX 5070 Ti, driver 621.14, Windows), which is the case this PR is for. Running cargo test -p xcl --lib private_physical_pages_reach_the_gpu_on_mapping -- --nocapture on an NVIDIA card would show it. The rest of the suite passes, and the findings in my review stand
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

@throny

throny commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Closing as a duplicate of #1916: #1607 group D156, checked by oni-swr and Foniass, who both read the diffs and suggest keeping #1916. If something here is not in #1916, say so and reopen it, or ask and I will.

AI use: Claude Code (Claude Opus 5.5) ran the closing script.

@throny throny added the duplicate This issue or pull request already exists label Dec 1, 2026
@throny throny closed this Dec 1, 2026
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Note on this closure: #1916 does not yet carry everything here. On current main, unmap-only runs go through kernelx.rs commit_homes_ahead (kernelx.rs:2118, called at :2620), which commits homes ahead and skips home_again, so #1916's deferral never runs on that path. This PR's kernelx.rs hunk (private_home per page before sparse::committed) handles it. My D156 check missed this and is corrected. #1916's rebase should take over that hunk; otherwise this PR should be reopened to carry it.

AI use: Claude Code (Claude Opus 5.5).

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

Labels

area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH area:memory Virtual/physical memory, arenas, VRAM budget, UMA duplicate This issue or pull request already exists gpu:nvidia Code is specific to NVIDIA / wave32 GPUs (scope tag; see needs:nvidia-test) needs-pr-check Failing the PR description check (CONTRIBUTING.md)

Projects

None yet

Development

Successfully merging this pull request may close these issues.