Skip to content

D3D12.X: leave no free granule next to the driver heap's hole, and no one-granule remake - #2991

Open
Prime1997 wants to merge 2 commits into
xcl-dev:mainfrom
Prime1997:contrib/uma-groom-boundaries
Open

Prime1997 wants to merge 2 commits into
xcl-dev:mainfrom
Prime1997:contrib/uma-groom-boundaries

Conversation

@Prime1997

Copy link
Copy Markdown
Collaborator

Requested by Prime · project thread

Two boundary cases of #2977's grooming, reported on that PR after it merged (thanks to the reviewer who followed up):

  • In the free stretch that holds the window's hole, the left reservation started at the stretch's base plus the margin. When the stretch begins less than the margin below the hole, the granules between them stay free, and with the hole they make room for a window-sized mapping that starts before the window's address. That stretch is now reserved right up to the hole and from its end; its margin stays at its start only where the part before the hole is longer than the margin.
  • A window of one 64 KiB granule has no margin (half of it rounds to zero granules), so grooming reserved every other free stretch and left the driver no room for its own mappings. Such a window is not remade now and stays the title's memory.

What is in it

  • crates/xcl/src/hle/d3d12x/uma_driver.rs: groom reserves the hole's own stretch up to the hole; groom_margin; remake refuses a one-granule window before releasing it.
  • Test grooming_leaves_no_free_granule_next_to_the_hole (in a process of its own, as the other grooming test): one free granule below a 512 MB hole; a window-sized reservation after grooming lands at the hole. With the old pieces it landed one granule low (0x7ff490740000 for a hole at 0x7ff490750000, checked by running the test against the old code).
  • Test a_one_granule_window_is_left_as_it_is; the two restore tests (failed_write_watch_does_not_release_the_original_window, failed_restore_stops_before_importing_an_unbacked_window) use two granules, since one is not remade now and their failure paths would not be reached.

Tested

  • NVIDIA GeForce RTX 3060 Ti 8 GB (driver 32.0.16.1714), Intel Core i5-10400, Windows 11 26200, rustc 1.100.0; debug tests, release smoke.
  • cargo test --locked --workspace --no-fail-fast -- --test-threads=4 with XCL_DXC_DIR set to DXC 1.9.2609.5: 1457 passed, 3 failed, 47 ignored. The 3 failures are tests that fail on main 623d02e4 itself (1455 passed, 3 failed, 47 ignored there, same command): test_title_draws_with_a_root_signature_under_the_debug_layer, test_title_runs_and_game_folder_is_untouched, test_title_runs_under_the_debug_layer_with_dred.
  • SKIPPED on this adapter: 27 (no wave64: 21, per-lane f16 form refused: 3, no dxc.exe: 1, cannot disable the driver cache (Windows Developer Mode is required): The application requested an operation that depend: 1, no heap windows: 1).

Regression run
A commit of main (b49be183, the last one before the shader preparation of #2555, which prepares every record before the title and does not fit a 60 s run):

xcl-smoke v1
commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7
gpu: NVIDIA GeForce RTX 3060 Ti
title: 419239bf
seconds: 60
exit: 0x0
frames shown: 363 (PresentX 363)
presents per 2 s (last 3): 16 17 16
device removals: 0
crashes: 0
peak commit: 15320 MB

This PR's head (with XCL_PREPARE=0, the switch of #2976):

xcl-smoke v1
commit: a497d8fc0649785bd8a77d9947383a85828a55f8
gpu: NVIDIA GeForce RTX 3060 Ti
title: 419239bf
seconds: 60
exit: 0x0
frames shown: 319 (PresentX 319)
presents per 2 s (last 3): 13 13 13
device removals: 0
crashes: 0
peak commit: 15055 MB

Not tested

  • Either case in a title run: neither was seen in a retail title; the coherent window is 512 MB or more there.
  • AMD (the remake is for NVIDIA), Wine.

AI use
Claude Code (Claude Opus 5.5) wrote the code, ran the suite and the regression runs on the hardware above, and wrote this description; Prime asked for it and owns the account. We coordinate the 8 GB work on the XCL Discord too: https://discord.gg/6B4TykyC4W

🤖 Generated with Claude Code

… one-granule remake

Two boundary cases of the grooming xcl-dev#2977 changed (reported on that PR after it merged):

- In the free stretch that holds the window's hole, the left reservation started at the
  stretch's base plus the margin. When the stretch began less than the margin before the hole,
  the granules between its base and the hole stayed free, and with the hole they made room for a
  window-sized mapping one granule before the window's address. Reproduced: with one free
  granule below a 512 MB hole, a window-sized reservation after grooming landed at hole - 64 KiB.
  The stretch that holds the hole is now reserved right up to it and from its end (the margin
  stays at the stretch's start only where the part before the hole is longer).
- A window of one 64 KiB granule has no margin (half of it rounds to zero granules), so grooming
  reserved every other free stretch and left the driver no room. Such a window is not remade
  now (it stays the title's memory); the two restore tests use two granules for that reason.

Tests: grooming_leaves_no_free_granule_next_to_the_hole (fails with the old pieces: the
reservation lands one granule low), a_one_granule_window_is_left_as_it_is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Prime1997 Prime1997 self-assigned this Nov 27, 2026
@Prime1997

Copy link
Copy Markdown
Collaborator Author

@thehollowedone Pushed this for you.

Plz review.

@thehollowedone

Copy link
Copy Markdown
Contributor

Independent RTX 3080 Ti check of #2991 head a497d8fc against its current-main parent 623d02e4. I reviewed the UMA change and found no runtime blocker. This is the same two boundary fixes as my #2977 follow-up, so I am not opening a duplicate PR.

Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti (621.35), Rust 1.99.1 MSVC, DXC 1.8.2502.11. On the clean PR head, cargo build --offline --locked -j 4 --workspace passed; cargo test --offline --locked -j 4 --workspace --no-fail-fast -- --test-threads=4 ran all 38 test binaries: 1,460 passed, 0 failed, 47 ignored, 25 GPU skip notices. XCL_DXIL_CACHE pointed to a writable temporary directory for this suite. cargo test --offline --locked -j 4 -p xcl --lib hle::d3d12x::uma_driver::tests -- --test-threads=1: 6 passed, 0 failed, 0 ignored, no skips.

I also ran scripts/smoke.ps1 for 60 seconds on clean release builds of the same title, GPU and settings, with XCL_PREPARE=0 on both. These are the script's generated blocks:

main 623d02e4

xcl-smoke v1
commit: 623d02e465a17497a757a4ce867f482b0a6c8f3b
gpu: NVIDIA GeForce RTX 3080 Ti
title: 9cc6a39e
seconds: 60
exit: 0x0
frames shown: 1330 (PresentX 1330)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14961 MB

#2991 a497d8fc

xcl-smoke v1
commit: a497d8fc0649785bd8a77d9947383a85828a55f8
gpu: NVIDIA GeForce RTX 3080 Ti
title: 9cc6a39e
seconds: 60
exit: 0x0
frames shown: 1317 (PresentX 1317)
presents per 2 s (last 3): 60 59 61
device removals: 0
crashes: 0
peak commit: 15003 MB

The head showed 99.0% of main's frames and 100.3% of its peak commit, within the PR limits. The blocks do not establish that either rare boundary case occurred in the title run or which screen it reached. Existing shader caches were retained; this is not a controlled cold shader timing result.

One non-blocking test improvement: grooming_leaves_no_free_granule_next_to_the_hole currently asks VirtualAlloc(NULL, LEN) where Windows chose to place the allocation. It can pass even if the wrong address is still available. I tested the more direct assertion below on the exact PR head: 1 passed, 0 failed, 0 ignored, no skip. It requires the allocation one granule before the hole to fail and the intended hole to succeed. The distinctive child exit code also prevents --exact matching zero tests from looking like success.

Test-only diff for the address invariant
diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs
@@ -388,15 +388,17 @@ mod tests {
                 assert_eq!(guard, all);
                 let hole = all + 2 * G;
                 let got = groom(hole, LEN);
-                let p = reserve(0, LEN, 0);
+                let wrong = reserve(hole - G, LEN, 0);
+                assert_eq!(wrong, 0, "a window-sized mapping still fits before the hole");
+                let right = reserve(hole, LEN, 0);
+                assert_eq!(right, hole, "the intended hole is blocked");
                 ungroom(got);
-                for a in [p, guard] {
+                for a in [right, guard] {
                     if a != 0 {
                         VirtualFree(a as *mut c_void, 0, MEM_RELEASE);
                     }
                 }
-                println!("window reservation at {p:#x}, hole {hole:#x}");
-                std::process::exit(if p == hole { 0 } else { 1 });
+                std::process::exit(77);
             }
         }
@@ -405,7 +407,7 @@ mod tests {
             .output()
             .unwrap();
         let transcript = format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
-        assert_eq!(output.status.code(), Some(0), "{transcript}");
+        assert_eq!(output.status.code(), Some(77), "{transcript}");
     }

AI use: Codex (GPT-6.2 Sol) reviewed the diff, ran the builds, tests and smoke pair, and drafted this report. Codex (GPT-6.2 Astra) independently reviewed the low-level boundary logic.

@LocranKing

Copy link
Copy Markdown

Tested PR #2991 (a497d8fc) on Windows 11 (Ryzen 5 5500, 32 GB RAM, NVIDIA GeForce RTX 3060 Ti 8 GB, driver 32.0.16.2140).

Unit tests (uma_driver)

Ran cargo test --locked -p xcl --lib -- uma_driver -- --test-threads=1 --nocapture on a497d8fc:

  • 6 passed, 0 failed:
    • driver_windows_by_default_on_nvidia_outside_wine — ok
    • a_one_granule_window_is_left_as_it_is — ok
    • failed_write_watch_does_not_release_the_original_window — ok
    • failed_restore_stops_before_importing_an_unbacked_window — ok
    • grooming_leaves_a_window_under_1_gib_only_its_hole — ok
    • grooming_leaves_no_free_granule_next_to_the_hole — ok

Smoke check (180 s, lockhart, XCL_PREPARE=0, XCL_DIRECT_DXIL=all)

  • #2991 (a497d8fc): Remapped the coherent window cleanly (D3D12.X: the coherent window at 0x700000000 (512 MB) is a driver CUSTOM write-back L0 heap mapped at its address, write-watched (135 reservations, 0 pages kept, 0 KB, 53 ms)), exit: 0x0, 0 crashes, 0 device removals, 1240 frames (PresentX 1240), peak commit 26954 MB, local 13864 MB, non-local 1852 MB (vs origin/main 06f90c19: 1236 frames, exit: 0x0, peak commit 27336 MB, local 14032 MB). Both reached loading (0 crashes on uma_driver startup) under default main texture settings.

@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 a497d8fc. I found no runtime blocker in the two UMA grooming boundary changes: both close holes that can let a window-sized mapping collide with the driver's reserved range. The branch now conflicts with current main, so the critical next step is a rebase that preserves the updated range arithmetic, followed by tests at both sides of the hole and the one-granule remake case. Existing Windows tests on an earlier main were green, but they do not validate the conflicted merge result. No local Windows run.

@Prime1997
Prime1997 marked this pull request as ready for review November 30, 2026 02:04
@github-actions github-actions Bot added area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:memory Virtual/physical memory, arenas, VRAM budget, UMA gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks) needs-pr-check Failing the PR description check (CONTRIBUTING.md) labels Nov 30, 2026
@saintwolf

Copy link
Copy Markdown
Contributor

Reviewed and tested current head 700087f3 (after the main merge).

Blocking finding from the merge commit (700087f3)

  1. groom_with ignores its headroom parameter — breaks mixed-segment UMA grooming (crates/xcl/src/hle/d3d12x/uma_driver.rs:125-145):
    • The merge resolution reintroduced let (least, margin) = (len.min(1 << 30), groom_margin(len)); inside groom_with and used margin instead of the headroom argument (also introducing two compiler warnings: unused variable: headroom at line 125 and unused variable: least at line 127).
    • remake_mixed on main calls groom_with(base, size, min_seg, (16 << 20).min(min_seg / 4)). For a 512 MiB window with a 64 MiB min_seg, remake_mixed expects headroom = 16 MiB, but groom_with now overrides it with groom_margin(512 MiB) = 256 MiB, leaving 256 MiB unreserved at the start of every stretch (and reserving nothing in stretches between 64 MiB and 256 MiB), which breaks remake_mixed's placement guarantee.
    • Fix: Remove let (least, margin) = ...;, use headroom directly in groom_with, and have groom(hole, len) call groom_with(hole, len, len.min(1 << 30), groom_margin(len)).
  2. Unchecked b + margin regression: main used ((base + 0xFFFF) & !0xFFFF).saturating_add(headroom); 700087f3 reverted that to unchecked b + margin. Restoring saturating_add(headroom) avoids overflow edge cases.

Non-blocking notes

  • Consider rebasing cleanly onto main instead of keeping the 700087f3 merge commit.
  • @thehollowedone's earlier suggestion on grooming_leaves_no_free_granule_next_to_the_hole (directly asserting reserve(hole - G, LEN) == 0 and reserve(hole, LEN) == hole with a non-zero child exit code) is still worth folding in.

Tested locally (700087f3)

  • Windows 11 (build 26300), NVIDIA GeForce RTX 4070 SUPER (driver 32.0.16.2140), AMD Ryzen 7 7800X3D, rustc 1.100.0.
  • cargo test -p xcl --lib hle::d3d12x::uma_driver::tests -- --test-threads=1 --nocapture: 10 passed, 0 failed (with the two new unused_variables warnings in uma_driver.rs:125,127).

AI use

  • Antigravity (Gemini 4 Neon) assisted with code review and drafting; all builds and tests were executed locally on the hardware above.

@thehollowedone

Copy link
Copy Markdown
Contributor

Agreed with Saintwolf’s current-head review. It identifies two regressions in merge commit 700087f: groom_with ignores its caller-provided headroom, and the checked start-address calculation was replaced with unchecked addition.

I prepared and locally tested this candidate against 700087f. It restores the per-stretch headroom contract and saturating address calculation, with a regression covering a 512 MiB window, 64 MiB mixed segments, and 16 MiB headroom.

Candidate patch
diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs
--- a/crates/xcl/src/hle/d3d12x/uma_driver.rs
+++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs
@@ -118,13 +118,12 @@ unsafe fn written_pages(base: usize, size: usize) -> Result<Vec<(usize, Vec<u8>)>
 /// stretch that holds the hole nothing next to it is left free: a free granule there and the hole
 /// make room for a window-sized mapping that starts before the window's address.
 unsafe fn groom(hole: usize, len: usize) -> Vec<usize> {
-    groom_with(hole, len, len.min(1 << 30), (256usize << 20).min(len / 2) & !0xFFFF)
+    groom_with(hole, len, len.min(1 << 30), groom_margin(len))
 }
 
 /// `groom` for stretches of `min_region` or more, leaving `headroom` at the start of each.
 unsafe fn groom_with(hole: usize, len: usize, min_region: usize, headroom: usize) -> Vec<usize> {
     let (top, mut a, mut got) = (0x7FFF_FFFE_0000usize, 0x1_0000usize, Vec::new());
-    let (least, margin) = (len.min(1 << 30), groom_margin(len));
     while a < top {
         let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
         if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of::<MEMORY_BASIC_INFORMATION>()) == 0 {
@@ -136,11 +135,12 @@ unsafe fn groom_with(hole: usize, len: usize, min_region: usize, headroom: usize
             continue;
         }
         let b = (base + 0xFFFF) & !0xFFFF;
+        let start = b.saturating_add(headroom);
         let pieces = if b <= hole && hole + len <= end {
             // (the margin at the stretch's start, only where the part before the hole is longer)
-            [(if hole - b > margin { b + margin } else { b }, hole), (hole + len, end)]
+            [(if start < hole { start } else { b }, hole), (hole + len, end)]
         } else {
-            [(b + margin, end), (0, 0)]
+            [(start, end), (0, 0)]
         };
         for (s, e) in pieces {
             let mut s = s;
@@ -746,6 +746,43 @@ mod tests {
         assert!(build_segments(256 << 20, &[(0, 128 << 20), (64 << 20, 64 << 20)]).is_err());
     }
 
+    #[test]
+    fn mixed_grooming_preserves_headroom_and_blocks_other_segment_placements() {
+        use super::*;
+        const SEG: usize = 64 << 20;
+        const LEN: usize = 512 << 20;
+        const ROOM: usize = 16 << 20;
+        if std::env::var_os("XCL_TEST_GROOM_MIXED").is_some() {
+            unsafe {
+                let reserve = |at: usize, n| VirtualAlloc(at as *const c_void, n, MEM_RESERVE, PAGE_NOACCESS) as usize;
+                let all = reserve(0, TILE + SEG + LEN);
+                assert_ne!(all, 0);
+                assert_ne!(VirtualFree(all as *mut c_void, 0, MEM_RELEASE), 0);
+                let stretch = all + TILE;
+                let hole = stretch + SEG;
+                assert_eq!(reserve(all, TILE), all);
+                assert_eq!(reserve(hole, SEG), hole);
+                assert_eq!(reserve(hole + SEG, LEN - SEG), hole + SEG);
+                let got = groom_with(hole, LEN, SEG, ROOM);
+                assert_ne!(VirtualFree(hole as *mut c_void, 0, MEM_RELEASE), 0);
+                assert_eq!(reserve(stretch, SEG), 0, "a segment still fits outside the window");
+                assert_eq!(reserve(hole - TILE, SEG), 0, "a segment fits across the boundary");
+                assert_eq!(reserve(stretch, ROOM), stretch, "driver headroom is blocked");
+                assert_eq!(reserve(stretch + ROOM, TILE), 0, "too much headroom was left");
+                assert_eq!(reserve(hole, SEG), hole, "the released segment is blocked");
+                ungroom(got);
+                std::process::exit(77);
+            }
+        }
+        let output = std::process::Command::new(std::env::current_exe().unwrap())
+            .args(["--exact", "hle::d3d12x::uma_driver::tests::mixed_grooming_preserves_headroom_and_blocks_other_segment_placements", "--nocapture"])
+            .env("XCL_TEST_GROOM_MIXED", "1")
+            .output()
+            .unwrap();
+        let transcript = format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
+        assert_eq!(output.status.code(), Some(77), "{transcript}");
+    }
+
     /// A mixed window keeps the title's bytes in every segment, and the GPU reads the CPU's later

Focused verification on the exact head: cargo test --offline --locked -j 4 -p xcl --lib hle::d3d12x::uma_driver::tests -- --test-threads=1 --nocapture — 11 passed, 0 failed, 0 ignored, 0 skipped. The workspace suite and retail smoke were not run on this candidate; this is a focused proposed fix, not a merge-readiness report.

AI use: Codex (GPT-6.2 Sol) prepared the candidate and ran the focused test.

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Review (head 700087f, diff read, not a merge-check: Build and test and PR description fail, so not built or run here):

  • The merge of main breaks XCL_UMA_DRIVER=mixed. groom_with (uma_driver.rs ~125-143) now ignores its headroom argument and uses groom_margin(len) for the whole window, and least is unused (CI warns about both). remake_mixed (~483) passes 16 MiB of headroom and now gets up to 256 MiB, so a segment can be mapped outside the window: CI fails mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment and a_refused_gpu_upload_segment_becomes_custom with "Map gave 0x1783ca00000, wanted 0x17840b10000", both green on main. Use headroom for stretches that don't hold the hole, or give the mixed caller its own margin. The original commit a497d8f had no groom_with; the merge applied the new margin to the mixed caller too.
  • The doc comment on groom_with still describes headroom. The smoke block names a497d8f, not the head (why PR description fails), and the suite results predate the merge.

Fine: reserving the hole's stretch right up to the hole while keeping the margin only when the part before it is longer, refusing a one-granule window before it's released, and the subprocess test for that edge case.

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

@Foniass

Foniass commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Test report (not a merge-check: PR description red)
base: b2b1f10
head: 700087f
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2902 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::uma_driver::tests::a_refused_gpu_upload_segment_becomes_custom, hle::d3d12x::uma_driver::tests::mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment
review: not repeated here; my review of this same head is at #2991 (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: 2 tests failed in this run: uma_driver::tests::a_refused_gpu_upload_segment_becomes_custom (uma_driver.rs ~830) and mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment (~776), both "remake_mixed: segment 0 (64 MB CUSTOM): Map gave

, wanted ". Correction to an earlier version of this comment: the same failure also hit #3377 and, once, #3318 (which doesn't touch heaps), and two full runs of main passed, so it is intermittent on this machine and not clearly caused by this PR. A few local runs of cargo test -p xcl --lib uma_driver on this head would settle 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.

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:memory Virtual/physical memory, arenas, VRAM budget, UMA gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks) needs-pr-check Failing the PR description check (CONTRIBUTING.md)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants