Skip to content

hle/xmem: prefer mappable 128 GiB GPU directory range for graphics reservations (D3D12-XMEM-GRAPHICS-37BIT) - #2856

Open
djrolfes wants to merge 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/xmem-128gib-gpu-dir
Open

djrolfes wants to merge 1 commit into
ProjectLeonida:mainfrom
djrolfes:djrolfes/xmem-128gib-gpu-dir

Conversation

@djrolfes

@djrolfes djrolfes commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: D3D12-XMEM-GRAPHICS-37BIT (claim comment; coordinated with zmasi's queued D3D12-RT-FG-ARENA-VA-STORM in #2570#issuecomment-7237954231)

What and why

Prefer the GPU's mappable raw-address page directory range ([4 GiB, 128 GiB - 64 KiB), i.e. [0x1_0000_0000, 0x1F_FFFF_0000)) when XMemVirtualAlloc reserves graphics memory (flags & 2 != 0), with transparent fallback to the wider console range (address_range(flags)) if the directory window cannot satisfy the reservation.

  • Why: On main, XMemVirtualAlloc constrains GRAPHICS reservations only to the full console range ([4 GiB, 1 TiB) or up to 46-bit when the bit-12 field is set). Under ASLR, large heaps, or RT/BVH reservations, allocations can land above the GPU's 37-bit raw-address page directory and silently lose raw-address coverage — without widening the directory (which would invalidate translated shaders).
  • Sentinel-page invariant: The GPU's 64 KiB-page directory has MEMORY_PAGES = 1 << 21 entries (128 GiB), and reserves the final entry MEMORY_PAGES - 1 (0x1F_FFFF, [0x1F_FFFF_0000, 0x20_0000_0000)) as the permanently empty out-of-range sentinel (leonida-gpu/src/memory.rs:295,354,627, leonida-shader/src/emit/lower.rs:4781). GPU_DIRECTORY_END is therefore (1usize << 37) - (64 * 1024) (0x1F_FFFF_0000), capping HighestEndingAddress at GPU_DIRECTORY_END - 1 (0x1F_FFFE_FFFF, preserving Windows MEM_ADDRESS_REQUIREMENTS's 64 KiB - 1 alignment contract) and checking end <= GPU_DIRECTORY_END for directory_covered.
  • Fallback & logging: CPU-only reservations (flags & 2 == 0) and 32-bit reservations (ADDRESS_32BIT) keep their existing ranges unchanged. If the initial 37-bit VirtualAlloc2 fails for a GRAPHICS reservation, XMemVirtualAlloc logs a tracing::warn! and retries with the full address_range(flags) upper bound so legal console allocations never fail with OOM. Successful graphics reservations log at tracing::debug! so default logs stay quiet.
  • Evidence classification: READ IN CODE (d3d12/crates/leonida-hle/src/modules/xmem.rs, d3d12/crates/leonida-gpu/src/memory.rs:295, d3d12/crates/leonida-shader/src/emit/lower.rs:4781) + unit-tested under Wine (VirtualAlloc2 MEM_TOP_DOWN and 128 GiB fallback) + MEASURED 300 s in-game gate on exact PR head 05ca84aee.

Tested

  • python3 -I scripts/check_no_game_data.py d3d12/crates/leonida-hle/src/modules/xmem.rs → exit 0.
  • Cross-compiled leonida-hle test binary (x86_64-pc-windows-msvc) and ran under Wine:
    • RED on origin/main (501b3e6c5) (only the new tests applied, no production change):
      running 2 tests
      test modules::xmem::tests::graphics_reservation_falls_back_when_the_directory_range_is_too_small ... ok
      test modules::xmem::tests::graphics_reservations_prefer_the_gpu_directory ... FAILED
      # field 0: graphics reservation 0xffffff0000 exceeded GPU directory
      test result: FAILED. 1 passed; 1 failed; 0 ignored
      
    • GREEN on PR head 05ca84aee (rebased onto cd73ddab7):
      running 26 tests (modules::xmem::tests)
      test modules::xmem::tests::graphics_reservation_falls_back_when_the_directory_range_is_too_small ... ok
      test modules::xmem::tests::graphics_reservations_prefer_the_gpu_directory ... ok
      ...
      test result: ok. 25 passed; 0 failed; 1 ignored; 0 measured; 218 filtered out
      
  • 300 s in-game gate (docs/game_gate.md) on exact PR head 05ca84aee (leonida.exe --profile play --features mimalloc,dlss,diagnostics, Series S + DLSS Quality 1280×720 → 1920×1080):
    • Verdict: PASS
    • In-world duration: 310.19 s (world_at_s = 77.33 s, >= 300 s required)
    • Frames (world + 60 s to stop): 2,935 presented frames (3,031 total world presents), 15.06 median FPS, 116.67 ms p95 frame time (15.43 end-window median FPS, 4,356 median draws/frame)
    • Longest present gap in world: 3.723 s (<= 10.0 s required)
    • Peak VRAM: 6,707 MiB (<= 7,400 MiB guard)
    • Stability: 0 device losses, 0 crashes/faults, 0 panics, 0 kernel NVRM: Xid errors

GPUs tested: NVIDIA GeForce RTX 3070 Ti 8 GB, driver 620.73.04, Arch Linux (Wine 11.22 + VKD3D-Proton 3.2.0).

AI-assisted: yes (initial prototype by GPT-6.1-Sol / Codex; implementation and sentinel-page refinement by Gemini 4 Neon; audited and approved in a separate independent review pass by Gemini 4 Neon).

Checklist

  • Based on current main (cd73ddab7) and merges cleanly.
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (check_no_game_data.py clean).
  • A new translator rule is in the contract table of docs/design.md (n/a — HLE memory reservation change, no translator rule).
  • Independent fresh reviewer agent audit completed (APPROVED).
  • 300 s in-game gate completed and PASSED on exact PR head (05ca84aee).

@fiestorra

Copy link
Copy Markdown
Contributor

Verified on Windows: the crate is green with it, and it adds two tests - measured against main's own file.

main 3393ceec9, cherry-picked (one commit), cargo 1.98.1:

cargo test -p leonida-hle
  with this pull request:            ok. 243 passed; 0 failed; 2 ignored
  with xmem.rs from main:            ok. 241 passed; 0 failed; 2 ignored

That is an existence control, not a mutation one - I did not remove the preference to watch a specific test fail, because the two that come with it are the ones that would.

And the file it changes is the one I have watched most today: #2836 (arrange forgets the slice a page leaves) went in this morning and #2856 now makes the 128 GiB GPU directory range mappable. The 241 existing tests absorbed both.

What I could not test: what "prefer a mappable range" does to a title's memory - that needs the game and a driver that reports both.

AI-assisted: yes - DeepSeek v4.1 (flash), both arms on the machine above.

Written with an AI assistant.

@MoonEyes

MoonEyes commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Verified by MoonEyes (another person than the author) on head 05ca84aee merged with main cd0c52fcf: I read the whole diff. cargo test -p leonida-hle: 245 passed, 0 failed. With highest.min(GPU_DIRECTORY_END - 1) put back to highest, graphics_reservations_prefer_the_gpu_directory fails.

In-game run with the six others of a batch on main 21e6bbf4b: RTX 4060 8 GB, NVIDIA 610.88, Windows 11 26300, -SeriesS -FrameGen 2, about 860 s in the world, then a second one of about 440 s, 0 device lost, 0 panic; pictures of the same scene compared with main, same. Black surfaces in early cutscenes while the PC's memory is full are there on plain main too. No "37-bit reservation refused" line in either run.

AI-assisted (Claude Code).

@merzleckeier

Copy link
Copy Markdown
Contributor

I ran a forced 128 GiB fallback check with 05ca84a merged into edf7d01 (Win64 MSVC target, Rust 1.98.1, Wine 11.22). The xmem tests reported 26 passed and one ignored, including both new tests. The top-down test exercises all eight graphics flags, the 32-bit controls and the CPU-only reservation. The large fallback test reserves virtual address space without committing physical memory.

For a negative control I disabled only the wider retry and kept the 37-bit preference. The 64 KiB top-down graphics test still passed, while the 128 GiB case failed with console-range fallback failed. This directly checks that the retry is required, independently of the preference check. MEASURED with synthetic VA reservations. AI-assisted (Codex).

@lixonik

lixonik commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

RUN (independent native Windows 10 unit + in-world verification, #2856 head 05ca84aee merged onto main 0ff8a532f):

  • Unit tests (cargo test --locked -p leonida-hle --lib xmem): 26 passed, 0 failed, 1 ignored (0.56 s).
  • In-world D3D12 gate (Series S, -NoFrameGen, diagnostics,dlss,mimalloc, 268.4 s runtime after precompile):
    • Reached play cleanly (48 frame lines, 10 in-world samples >= 1000 draws/frame, 2,543 median / 4,216 max draws/frame, median 16.1 fps / 62.0 ms, 0.0 ms GPU wait).
    • 0 ERROR lines, 0 device-lost events across 27,874 log lines.
  • GPUs tested: NVIDIA GeForce RTX 5070 12 GB (driver 621.40, Windows 10 Pro 22H2 build 19045, Ryzen 9 5950X 16C/32T).

MEASURED. AI-assisted: Antigravity.

@KelboLive KelboLive left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The claim verifies in code: MEMORY_PAGES = 1<<21 64 KiB pages (emit/shader.rs:127, memory.rs:82), the last directory entry is permanently empty (memory.rs:295, :627; lower.rs:4781), so [4 GiB, 128 GiB−64 KiB) is exactly pages 0x1_0000..=0x1F_FFFE. A native-Windows probe confirms VirtualAlloc2 accepts HighestEndingAddress = 0x1F_FFFE_FFFF and returns exactly 0x1F_FFFE_0000, so the cap is inclusive and not silently rejected. Merge-tree with current main is clean and the merged suite is 245/0/2 serially.

Blocker: the two new tests destroy each other under the default parallel harness. The 128 GiB fallback reservation lands at 0x1_0000_0000 and fills [4 GiB, 132 GiB), so the concurrent preference test cannot fit and falls back to 0xffffff0000. Measured 8/30 failures on the head and 6/20 after merging main — CI's plain cargo test will be red roughly a quarter of the time. Please serialize the pair (shared Mutex) or make the big reservation start above GPU_DIRECTORY_END.

Two smaller things:

  • The fallback keeps the caller's floor, so an out-of-directory 128 GiB reservation squats on the entire mappable window (the probe shows exactly that). Raising LowestStartingAddress to GPU_DIRECTORY_END on retry would preserve the window for later graphics allocations.
  • directory_covered (xmem.rs:213) omits at >= 4 GiB, so a 32-bit graphics reservation logs true even though memory.rs:295 rejects pages below 0x1_0000.

Mutation check: reverting the widened fallback_highest correctly fails graphics_reservation_falls_back_when_the_directory_range_is_too_small, so that guard is covered.

Not verifiable here: the 300 s in-game gate, VRAM/FPS, and real raw-address coverage — no game data. The end-to-end path (commit + write-watch + shader lookup) is only inferable from code.

@imShangLi

Copy link
Copy Markdown
Contributor

VERIFY-2856 — Linux, Fedora 45, Rust 1.98.1 (the pinned toolchain), Wine 11.21, no GPU device, no game files

Verdict: PASS. The repository's own red/green idea holds under Wine: the new test fails on the merge base and passes with the pull request, nothing that worked before is broken, and the arithmetic of the new bound is right.

Head 05ca84ae, base the current main, merge base cd73ddab, 1 file, +109/−2: d3d12/crates/leonida-hle/src/modules/xmem.rs.

1. What it changes

XMemVirtualAlloc asked the Windows loader for the console's address range (up to 40 or 47 bits). The GPU's mappable directory is a range of 64 KiB pages, [4 GiB, 128 GiB − 64 KiB), with the last page reserved as the empty out-of-range sentinel — and the title's graphics allocations have to land inside it, because expanding the directory would change every shader's bounds and invalidate the translations. The change caps a graphics reservation at that directory and falls back to the console's wider range when the reservation is refused:

const GPU_DIRECTORY_END: usize = (1usize << 37) - (64 * 1024);

fn graphics_address_range(flags: u64) -> (usize, usize) {
    let (lowest, highest) = address_range(flags);
    (lowest, if flags & 2 != 0 { highest.min(GPU_DIRECTORY_END - 1) } else { highest })
}

flags & 2 is the graphics bit (GRAPHICS = 3, so the graphics flag has it set; the CPU-only case passes 1), and address_range gives the console's 40 or 47-bit range otherwise.

2. The bound is the sentinel's, and the arithmetic is right

GPU_DIRECTORY_END = (1 << 37) − 64 KiB = 137 438 887 936 = 0x1F_FFFF_0000 — the address the code comment names as the sentinel page's start, and the page [0x1F_FFFF_0000, 0x20_0000_0000) stays out of reach, because the reservation's ending address is capped at GPU_DIRECTORY_END − 1 = 0x1F_FFFE_FFFF, the last address inside the directory.

For every one of the eight field values the code has (flags >> 12 & 7 gives 0..=7, so the console range is 47 down to 40 bits), highest.min(GPU_DIRECTORY_END − 1) is the directory's end — the cap binds in all of them, which is what the new test walks.

3. The fallback is a retry, not a silent widening

let (_, fallback_highest) = address_range(flags);
if at.is_null() && constrained && highest < fallback_highest {
    tracing::warn!(size, %error, "XMemVirtualAlloc: 37-bit reservation refused; retrying console range ...");
    requirements.HighestEndingAddress = fallback_highest as *mut c_void;
    ...
    at = unsafe { VirtualAlloc2(GetCurrentProcess(), base, size, kind, protect, &mut parameter, 1) };
}

The retry restores the console's own limit (normally 40 bits) and says so in the log, so a crowded low address range cannot turn a legal console allocation into an OOM, and the loss of raw-address GPU coverage is visible rather than hidden. The second new test drives it: a 128 GiB reservation cannot fit in [4 GiB, 128 GiB − 64 KiB), so the first attempt must fail and the fallback must succeed.

4. Red and green, run under Wine

leonida-hle does not build on Linux (upstream: "The crates are Windows-only today … Linux follows #2577"), so I cross-compiled it for x86_64-pc-windows-gnu and ran the tests under Wine 11.21:

the merge base with only this pull request's tests 245 tests
the pull request's head 245 tests
red → green modules::xmem::tests::a_title_thread_goes_on_using_the_rest_of_a_view — fails on the base, passes with the pull request
regressions 0
failing on both sides 3 (see below)

The three that fail on both sides are:

  • modules::net::tests::only_loopback_is_reachable — "ws2_32.dll lacks WSAConnectByList": Wine's ws2_32 has no such API. Not this change.

  • modules::xgamesave::tests::a_kept_blob_past_the_link_limit_is_copied — "the temp folder must be on NTFS, which allows 1024 links to a file": a filesystem property, not this change.

  • modules::xmem::tests::graphics_reservations_prefer_the_gpu_directory — this pull request's own second test, and the reason is the environment: the assertion that fails is the last one,

    assert!(
        cpu_addr >= 1usize << 37 && cpu_addr.checked_add(size).is_some_and(|end| end <= 1usize << 40),
        "CPU-only top-down reservation {cpu_addr:#x} did not retain the 40-bit console range"
    );

    a CPU-only top-down reservation that has to land in the 40-bit range (above 128 GiB). Wine's address space is not laid out that way. Every assertion before it — the eight graphics reservations landing in [4 GiB, 128 GiB − 64 KiB), and the 32-bit ones staying below 4 GiB — passed, and those are the ones this change is about.

5. What I did not check

  • Whether the title's own allocations fit the directory. The change caps where a graphics reservation may land; whether the title's allocation pattern fits inside [4 GiB, 128 GiB − 64 KiB) is a property of the game and of the run, and needs the game files and a GPU.
  • The leonida_gpu::title_memory_freed bookkeeping the new test uses — that is the GPU crate's, and it is exercised by the leonida-gpu tests, not by this one.
  • Windows and MSVC. Everything above is Linux with Wine 11.21 (staging) and no GPU device. Wine's VirtualAlloc2 is not Microsoft's, and the one assertion that fails is exactly the kind that depends on it.
  • The D3D12 side. The GPU's directory end and the sentinel page are named in leonida-gpu/src/memory.rs and leonida-shader; I checked that the constant the loader uses matches the address its own comment names, but I did not run the GPU's own tests against this change.

AI-assisted: MiniMax M3.1 Flash.

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.

7 participants