Skip to content

runtime: the CPU half of Xbox physical pages, with write-fault dirty tracking - #5381

Open
maxxgabriel wants to merge 16 commits into
ItsNotRexed:mainfrom
maxxgabriel:d3d-546-page-mapping
Open

maxxgabriel wants to merge 16 commits into
ItsNotRexed:mainfrom
maxxgabriel:d3d-546-page-mapping

Conversation

@maxxgabriel

Copy link
Copy Markdown

Claimed in the coordination issue as: D3D-546 (#313)

Depends on: #5378 (this branch includes its commit; the diff of its own is the second commit)

What and why

On the console the CPU and GPU address the same physical page. Here the GPU side has to be device-local, so runtime/src/xbox_physical.h gives each page two halves and keeps them coherent:

  • CPU half (PhysicalPageStore): a 64 KiB slot of one pagefile-backed section. Views are placed at the title's VAs over placeholders (VirtualAlloc2 with MEM_RESERVE_PLACEHOLDER, MapViewOfFile3 with MEM_REPLACE_PLACEHOLDER), so one page can be mapped at several VAs.
  • GPU half (PhysicalGpu): a PagePool page, allocated on first use.
  • CPU to GPU: clean pages are read-only. The first write faults; a vectored handler marks the page dirty and opens that view. take_dirty() write-protects dirty pages again, and record_upload copies them ahead of the title's commands.
  • GPU to CPU: on request only, with record_readback then finish_readback.

This is the mechanism XMemAllocatePhysicalPages and XMemMapPhysicalPages[Scatter] map onto; they get wired once a call site shows their arguments.

Details worth a look:

  • A slot whose neighbours were already split off is a placeholder of its own, and splitting it again fails. split() checks that with VirtualQuery.
  • map() and the record calls check the whole call before changing anything, so a bad page index or an exhausted pool leaves nothing half-applied.
  • The GPU halves go back to the pool when PhysicalGpu is destroyed.
  • The staging buffer is used from offset 0, so a command buffer holds one upload or readback at a time (documented; a per-frame ring comes with the device proxy wiring).

Measured on a GTX 1660 SUPER (median of 8):

Operation Cost
First write to a clean page 3.5 µs
take_dirty of 256 pages 0.24 ms
Upload of 256 pages (16 MiB) 9.3 ms (about 1.8 GB/s)

Tested

  • vk_xbox_physical_test (Windows only): PASS, and 0 errors under LEONIDA_VK_VALIDATION=1. Covers a page mapped at two VAs, CPU writes read back through the arena, and a GPU fill read through a CPU view.
  • vk_xbox_paging_test: still PASS.

NVIDIA GeForce GTX 1660 SUPER, driver 610.88, Windows 11, MSVC 14.51, Vulkan SDK 1.4.363.1.

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (No translator change.)

@SirKingg

Copy link
Copy Markdown
Contributor

AI-assisted independent GPU check of head 22afe9c5daa64ac6709e31a6a9378e47ec52e054 on Windows 11 Pro build 26300, NVIDIA RTX 4070 Ti, driver 610.88, MSVC 19.44, Vulkan SDK 1.4.363.0. Synthetic data only; no game files or XMem physical shims.

With LEONIDA_VK_VALIDATION=1, locally adapted vk_xbox_physical and vk_xbox_paging both passed with zero validation errors:

  • Physical: four CPU-written 64 KiB pages were uploaded and all bytes read back via the sparse GPU arena matched; a GPU fill of one page was read back to its CPU view and all bytes matched, without marking it dirty.
  • Paging: five remaps read the expected first and last words in order while the arena device address stayed fixed; GPU writes through one sparse alias were read via another; the bounded contiguous/scattered bind checks passed.
  • vk_sync_validation_selftest passed: the intentional missing-barrier control produced one synchronization error and the barrier control produced zero.

Scope: the local test copies disabled the timing/benchmark blocks (including the paging queued-work timing check); the paging test substituted a bounded four-page scattered-bind check, and the physical test added CPU assertions without changing the GPU upload/readback path. No performance claim, unbounded stress, or end-to-end title integration is covered. The separate Windows CPU mapping/dirty-rearm review is claimed by Hiiva; this is not a full PhysicalPageStore review.

@Hiiva Hiiva 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.

Independent Windows CPU review of 22afe9c5daa64ac6709e31a6a9378e47ec52e054.

The standalone probe includes the unmodified runtime/src/xbox_physical.h. Its 41 positive checks pass: aligned aliases share bytes, a first write marks the physical page, take_dirty() protects both views again, another alias write is tracked, invalid/unallocated page indices and oversized batches leave existing mappings unchanged, aligned remap/unmap preserves the other alias, and destruction releases the reservations. A separate ignored copy with only the take_dirty() re-protection call omitted fails the re-protection assertion, so this check exercises the new behavior.

One nonblocking boundary observation at runtime/src/xbox_physical.h:114: map(base + offset, {replacement}) accepts offsets 1, 4096, and 65535 and changes the preceding 64 KiB slot. This occurs with both a fresh placeholder and an existing mapping. The native MapViewOfFile3 controls reject those starts (1132, 487, 1132), preserve the placeholder, and subsequently accept the aligned mapping. The helper's integer slot calculation explains the observed rounding.

I am not treating that comparison as a blocking Xbox or game defect. The helper has no explicit invalid-start rejection promise, its current test callers supply aligned addresses, and the XMem/device wiring is deliberately deferred. Making the aligned-address boundary explicit before adding callers would avoid relying on accidental rounding.

Scope: original synthetic pagefile sections and placeholder reservations only, no game files or GPU execution. This does not replace the PR's GPU coherence/validation test. Windows 11 x64 build 26200, MSVC 19.44.35228, Windows SDK 10.0.26100.0; Vulkan headers 1.4.363.0 were used to compile the header, with no Vulkan calls. AI-assisted: yes.

@maxxgabriel
maxxgabriel requested a review from Hiiva November 23, 2026 11:12
@timbot103

Copy link
Copy Markdown

Tested 4b1252c natively on Windows 11 Pro 26200 (MSVC 14.44.35207, Vulkan SDK 1.4.363.0), merged onto main 3faac55, on an NVIDIA RTX 5080 (616.64) and an AMD Radeon Graphics RDNA2 iGPU (25.10.30.02). Pass on both.

  • vk_xbox_physical_test: PASS. Double mapping, CPU writes through the arena, and the GPU fill read through the CPU view (0x5a) all checked out. Uploading 256 dirty pages (16 MiB) took about 5-6 ms on the 5080 and about 8-9 ms on the iGPU. With LEONIDA_VK_VALIDATION=1: PASS, validation errors 0.
  • vk_xbox_paging_test: PASS, also under validation with 0 errors.
  • vk_queue_test, d3d12_sparse_queue_family_test and d3d12_vulkan_device_test: PASS.

No game files. AI-assisted (Claude Code).

@Kam471 Kam471 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.

Reviewed head 4b1252c5ef.

Stack: contains #5378's tip 6571ec5533 plus 3 commits (correctly rebased; git merge-base --is-ancestor pr/5378 pr/5381 is true).

Build: vcvars64 + Ninja + Vulkan 1.4.363, then
cmake --build build --target vk_xbox_paging_test vk_xbox_physical_test

  • .\build\vk_xbox_physical_test.exe -> PASS: one page at two VAs; CPU writes P0..P3 visible through arena VA 0x300000000 after one upload; GPU fill -> readback P2 = 0x5a; first write fault 2.51 us; take_dirty 256 pages 0.161 ms; 16 MiB upload 8.34 ms.
  • .\build\vk_xbox_paging_test.exe -> PASS (181 calls, 20144 binds), the #5378 suites still green on top.

Inert: xbox_physical.h is included only by xbox_paging.h; no src caller; CMake adds test executables only. Dirty tracking is exercised by the test rather than claimed.

Verdict: LGTM, merge after #5378.

@AwkGrep256

Copy link
Copy Markdown
Contributor

Ran an automated multi-agent review (Claude Code ultrareview) on this PR's current head. It found 17 candidates and refuted most of them; 10 were confirmed. All are graded nit, but only because nothing calls xbox_physical.h / PageMapper yet (docs/xbox_paging.md lists the wiring under "Not done"). They become real bugs once XMemAllocatePhysicalPages / XMemMapPhysicalPages are wired, so they seem worth settling before that.

Correctness

  1. GPU halves start with undefined contents (runtime/src/xbox_physical.h:304-310). gpu_page() takes a PagePool page (never zeroed, and reused as it is) and never fills it from the CPU half. A page the CPU hasn't written isn't dirty, so it's never uploaded. The GPU then reads garbage where the console reads zeros, and a readback copies that garbage over the zeroed CPU half. Fix: initialize a new GPU half from the CPU half, for example by marking the page dirty.
  2. A readback discards un-uploaded CPU writes (:355-358). finish_readback memcpy's GPU data over every requested page without checking dirty_. Fix: upload dirty pages before reading them back, or refuse or merge readback of dirty pages.
  3. A failed upload loses CPU writes (:148-154). take_dirty() clears the dirty bits and re-protects the pages before record_upload runs. If that fails (pool exhausted, staging allocation), the pages look clean and are never retried. Fix: re-mark them dirty on failure, or commit the clear only on success.
  4. No barrier before the upload copies (:319-323). There's only the TRANSFER→ALL_COMMANDS barrier after them, so an upload can overwrite a page that earlier GPU work on the queue still reads (WAR/WAW). The test doesn't see it because it waits on every submit. record_readback already has the matching "before" barrier.
  5. Kernel-mode writes into a clean view fail (:214-225). Dirty tracking relies on PAGE_READONLY plus a user-mode vectored handler, so ReadFile, overlapped I/O or recv into a mapped physical page fail (ERROR_NOACCESS) instead of marking it dirty. Streaming file data straight into physical memory is a common Xbox pattern. MEM_WRITE_WATCH / GetWriteWatch would avoid this.
  6. bind_sparse_ordered skips the queue's Wait-before-Signal hold (runtime/src/vulkan_backend.h:1678-1685). It submits at once while must_hold() is true, so a remap can run ahead of ExecuteCommandLists work that's still held, and it takes pending waits with it. The existing update_tiles / copy_tile_mappings path has the same gap.

Lifetime

  1. ~PhysicalGpu releases pages that may still be mapped or in use (xbox_physical.h:294-298). release_locked only clears chunk.used, so the next allocate can hand out a page the arena still maps, and the two GPU addresses alias.
  2. PagePool bind tickets from different queues are compared (xbox_paging.h:135-148). note_mapped folds every ticket into one last_bind with std::max, but each VulkanQueue has its own timeline. If binds come through more than one queue, trim() can vkFreeMemory a chunk that a pending bind still references, or never free it. Fix: track the ticket per queue, or assert a single bind queue per pool.

Performance

  1. One vkCmdCopyBuffer per page in record_upload (:321-325) and record_readback (:343-346). Grouping the regions per chunk buffer gives one call per buffer, instead of 256 commands for the PR's own 256-page measurement.
  2. take_dirty() scans all of capacity_ with an acq_rel exchange per slot, under the unique lock that blocks fault handlers (:149-158). That's O(capacity) per frame rather than O(dirty pages). A dirty list or bitset maintained in on_write_fault, or a relaxed load before the exchange, fixes it.

I didn't run anything for these; they come from the review's code read. AI-assisted (Claude Code).

@tedin7

tedin7 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

finding for #5381 (D3D-546), from a check of how Leonida keeps CPU and GPU copies of shared pages in sync. It's a design note, not a full review.

With per-page dirty tracking, record_upload copies a whole 64 KiB page from the CPU copy to the GPU copy whenever the CPU wrote anything on that page. Nothing records pages the GPU has written. So:

  1. The GPU writes a texture (or buffer) that lives on page P, for example with a copy into it.
  2. The CPU writes an unrelated object that shares page P.
  3. On the next upload, P is dirty, and the stale CPU copy of the texture's bytes overwrites what the GPU wrote.

A test that would catch it:

  • GPU-copy a known pattern into a resource on page P.
  • CPU-write a neighbouring allocation on P, then run the upload path.
  • Read back the resource: it must still hold the GPU pattern.
  • Control: a later CPU write into the resource itself must still reach the GPU after the next upload.

Possible fixes: track GPU-written ranges per page and either read them back before the upload (merge) or upload only the CPU-dirty byte ranges instead of whole pages.

It isn't reachable on main today, since nothing there tracks CPU-dirty pages, and #5381 notes it isn't wired to D3D12 yet. It matters once it is. AI-assisted.

@gertify

gertify commented Nov 23, 2026

Copy link
Copy Markdown

Tested 02392f1 on Intel UHD Graphics 770, driver 32.0.101.7088, with LEONIDA_VK_VALIDATION=1 and the Khronos validation layer inserted by the loader, and on NVIDIA GeForce RTX 4080, driver 617.42, without validation: vk_xbox_physical_test and vk_xbox_paging_test exit 0 and print PASS on both. The UHD 770 run prints "device: Intel(R) UHD Graphics 770 (validation on)" and "validation errors: 0". On the RTX 4080, vk_xbox_physical_test logs "CPU writes to P0..P3 read back through arena VA 0x300000000 after one upload: match" and "GPU fill of arena page -> readback -> CPU view of P2 reads 0x5a". vk_xbox_physical_test prints only PASS on success, so its other checks are not itemised.

AI-assisted.

@aidity

aidity commented Nov 23, 2026

Copy link
Copy Markdown

Windows x64 / Radeon RX 580 / driver 31.0.21924.61 validation: this PR's exact head 9b11bcc built with MSVC 14.44 and passed vk_xbox_physical_test on physical hardware. Shared CPU aliases, dirty tracking, CPU-to-GPU upload and GPU-to-CPU readback passed.

I also integrated the backing locally with main 1cc6e3c plus startup reservation/large-page work. That required adapting the sparse-bind queue path to retain the newer wait pins, resource types and cancellation behavior. The integrated runtime built, xmem_test passed 170 checks, and vk_xbox_paging_test plus vk_xbox_physical_test both passed. The integration branch is https://github.com/aidity/Leonida/tree/integration/physical-pages-current for comparison; it is not a competing implementation of this PR.

Measured integrated upload of 256 dirty pages (16 MiB) was about 18 ms on this GPU. The title-facing committed graphics-allocation wiring is still absent, so this does not claim the game's startup pool is supported or that gameplay works.

No game inputs or trace files are attached. AI-assisted with Codex.

@Etoile-Bleu

Copy link
Copy Markdown
Contributor

Call-site evidence for the wiring this PR leaves open ("they get wired once a call site shows their arguments"), from the retail game_scarlett_master.exe (1.0.2.1, SHA-256 e95020b2fa4a721db3df59fdecf75621730ac559d8835252f6c3b658d5a08993). Static, nothing executed; the full write-up is #6843 (docs/xmem_exe_calls.md, counts and constants only):

  • 21 call sites: XMemMapPhysicalPages 12, XMemAllocatePhysicalPages 4, XMemFreePhysicalPages 3, XMemMapPhysicalPagesScatter 2.
  • Shapes, inferred from the argument registers (Win32 AWE-like): Allocate(flags, ULONG_PTR* pages in/out, ULONG_PTR* pageArray); Map(void* va, pages, const ULONG_PTR* pageArray) where a null pageArray unmaps (4 sites) and one site maps a single page through a one-element array; Free(pages by value, ULONG_PTR* pageArray) (least certain, 2 of 3 sites read); Scatter(void** vas, pages, const ULONG_PTR* pageArray).
  • Page unit looks like 64 KiB: the unmap code shifts byte sizes right by 16 before passing page counts, and the reservations in front of the map calls use the 64 KiB page mode (0x20402000). That matches your 64 KiB slots.
  • Allocate's first word takes 0x180, 0x280 (2 sites) and 0x380. Its meaning is unmeasured. One site compares the returned count with the wanted one, so a partial allocation is possible.
  • The first function that uses them reserves its range with XMemVirtualAlloc(..., 0x20402000, attributes 0x23, protect 0x2004) between the allocate and the map. All 23 XMemVirtualAlloc sites pass a nonzero attribute word, which xmem.cpp refuses today, so the map calls are not reached until that is relaxed (xmem: support the two 64 KiB VA reservation forms reached at startup #6709 / Runtime: support the observed committed 64 KiB CPU XMem allocation #6814 / RT-217: Handle console allocation flags on Windows #3390 are on it).

I'm not writing a second store. Once this PR lands I can do the thin xmem.cpp layer that maps these four exports onto PhysicalPageStore, if you have not started it: say so here.

@aidity

aidity commented Nov 23, 2026

Copy link
Copy Markdown

Follow-up validation: the 2/4 MiB reserve-alignment change is at aidity@aa03123b6 (layered on our integration branch). It adds an optional alignment argument to PhysicalPageStore::reserve, validates power-of-two/aligned fixed addresses, and supplies VirtualAlloc2 address requirements for anonymous coarse-aligned windows. Default 64 KiB behavior is preserved. The test covers 2/4 MiB reserve addresses, mapping/writing a page, dirty tracking and invalid alignment requests. Both vk_xbox_physical and vk_xbox_paging pass on RX 580, driver 31.0.21924.61, Windows/MSVC, alongside the XMem and loader integration checks. Please consider folding the alignment argument into this PR; it is needed by the console's coarse-page requests. No duplicate PR opened.

@Jadiac5

Jadiac5 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 9b11bcc on Windows 11, AMD Radeon RX 9070 XT (RDNA4), driver 32.0.32029.2010: pass

  • Built vk_xbox_paging_test and vk_xbox_physical_test from the head (MSVC 19.44, Ninja, RelWithDebInfo, Vulkan SDK 1.4.363.1). 4/4 build steps, no error.
  • vk_xbox_paging_test.exe: PASS, exit 0, 0 FAIL lines. Mapper summary: 188 calls, 187 submits, 20150 binds, 71088 pages. Queued-work test: 0.009 ms gap without a remap, 1.513 ms with a 64-page scattered remap, remap call returned in 0.068 ms while W1 still ran.
  • vk_xbox_physical_test.exe: PASS, exit 0, 0 FAIL lines. 256-page (16 MiB) upload 16.872 ms (0.99 GB/s) in the first run, 6.382 ms rewritten whole, 1.663 ms with one changed word per page. The 16.872 ms figure was taken while other jobs used the GPU.
  • The earlier runs on this head are on other GPUs (Radeon RX 580, Intel UHD 770). This is the first RDNA4 run.
  • No negative control: all 9 files are new or add to vulkan_backend.h; there is no merge-base version of the code under test to revert to.
  • The PR is CONFLICTING with main. The tests were run on the head as it is, not on a merge result.
  • Not done: not run against the retail executable. The neighbouring vk_* tests were not built from this head. No Vulkan validation layer run.

AI-assisted (Claude Code).

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.