Skip to content

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

Closed
maxxgabriel wants to merge 19 commits into
ProjectLeonida:mainfrom
maxxgabriel:d3d-546-page-mapping
Closed

maxxgabriel wants to merge 19 commits into
ProjectLeonida: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
Collaborator

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.

@searyecheesepeaceful

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.

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

@maxxgabriel

maxxgabriel commented Nov 23, 2026 •

Copy link
Copy Markdown
Author

Updated to c5116ef, merged #5378 in, no force push.

@Etoile-Bleu thanks for the call site write-up, the 64 KiB unit matches. Now that #6919 is merged, I'll make this the gpu half under that store instead of keeping a second one.

49/49 targeted tests pass on my 1660 SUPER (610.88). Full suite is running.

@cynbun

cynbun commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested c5116ef08 on Linux + Wine 11.20 (RTX 5080, NVIDIA 615.78.08), with my own copy of the retail 1.0.2.1 exe: pass — both new tests pass on the GPU under Wine, write-fault dirty tracking included, and there is no ctest regression against main. The retail exe behaves exactly as on main, which is expected: nothing calls this code from the xmem.dll exports yet.

Setup. The head merged alone onto main fd335571a (clean merge). Depends on: #5378: its head d87b8010a is already an ancestor of this branch, so nothing else was merged. clang-cl 23.1.3 + xwin (MSVC 14.44 STL, SDK 10.0.26100) cross build, Ninja, RelWithDebInfo, -DLEONIDA_SDL3_FETCH=ON -DLEONIDA_VULKAN_HEADERS_FETCH=ON. The same flags for the main baseline build. Vulkan through winevulkan on the host NVIDIA driver.

Tests

  • vk_xbox_paging_test.exe: PASS, exit 0, 0 FAIL lines. Mapper summary: 188 calls, 187 submits, 20150 binds, 71088 pages. Queued-work gap: 0.006 ms without a remap, 1.343 ms with a 64-page scattered remap (median of 9). The remap call returned in 0.113 ms while W1 was still running. Trim and destroy (cleared, and with a page still mapped) leave 0 bytes reserved.
  • vk_xbox_physical_test.exe: PASS, exit 0, 0 FAIL lines. The double mapping, the CPU→arena readback match and the GPU fill → CPU view all hold. First write to a clean page (fault + unprotect): 20.7 µs. 256 dirty pages (16 MiB) upload in 24.7 ms (0.68 GB/s), 2.9 ms with one changed word per page, 12.9 ms rewritten whole. So the read-only protection and the vectored handler behind the dirty tracking work under Wine.
  • ctest -C RelWithDebInfo --output-on-failure -j1 --timeout 300: 253/269 pass, 16 fail (vk_xbox_paging and vk_xbox_physical pass). All 16 also fail on main here: gameinput_host, device_proxy, device_proxy_trace, file_system, run_tiny_game_abort_exit_codes, and ten d3d12_* tests plus dxgi_swapchain. I didn't look into why they fail under Wine; the PR doesn't touch them. main's full run had two more failures, vk_pipeline_check_cli and a timeout in xdxr_build_check, and both pass here. Neither is touched by this PR, and both pass when run alone on main: vk_pipeline_check_cli passed 1 of 3 runs alone, because its 5 s execute_process limit is shorter than a cold Wine start.

Retail exe (LEONIDA_D3D12=vulkan, --overlay to a scratch folder outside the package, network off via a separate network namespace, fresh --trace, --trace-d3d12), main fd335571a vs main + this PR:

  • --dry-run: identical. 5 modules, shim=54, 29 unimplemented, the same list, including all seven xmem.dll imports (XMemAllocatePhysicalPages, XMemMapPhysicalPages[Scatter], XMemFreePhysicalPages and the rest). The PR leaves the exports unwired, as its description says.
  • --init: exit 0, 4 TLS callbacks, 4/4 DllMain ok, on both.
  • --run: the same stop on both: 2 TLS callbacks, 4/4 DllMain ok, then a null read (0xC0000005) in gta6rt's own host_module_name (library_loader.cpp) on the game thread, before any unimplemented import or D3D12 call. That is the known Wine form of the /GA TLS index 0 problem (Coordinating who works on what (38) (moved to #6750) #6603, fixed by Loader: the mapped game executable owns module TLS index 0 (RT-259) #4313, which conflicts with main), so the boot doesn't get near the physical-page calls (stop 6 of docs/retail_boot_chain.md) either way.

Not tested: native Windows/MSVC, a Vulkan validation-layer run, and wiring the exports to this store. #6919, merged after my main base, serves those exports with its own CPU-only store, so the retail exe only exercises this code once it sits under that store, as your last comment plans. My dry-run numbers are against fd335571a, before #6919.

AI-assisted (Claude Code).

cc @shayderrr

@Numbers-iwnl

Copy link
Copy Markdown

Boot-chain measurement for this PR on RDNA4/Windows, alone and combined with #7524.

Machine: Windows 11 26300, RX 9070 XT (RDNA4, gfx1201), AMD 32.0.32029.2010 (26.11.2). MSVC 19.44 build, Ninja, RelWithDebInfo, own 1.0.2.1 copy + retail executable, gta6rt --run <exe> --game-dir <copy> --trace.

tree result
main@867d922 0xc0000005 read TLS index 0 at game_scarlett_master.exe+0x104075 (#8452 / #7968)
#5381 alone (c5116ef08) 5 modules mapped, 29 unimplemented imports, trace ends after the two game_scarlett_master.exe TLS callbacks (+0x55dd4f4, +0x55e2ebc); process dies before a physical-page call or an exception record is written
#7524 alone (c38194af8) clears TLS: xgameruntime InitializeApiImplEx2(10002, 7901), DStorageGetFactory, IDStorageFactoryX::OpenFile, then XMemAllocatePhysicalPages (0x280) at game_scarlett_master.exe+0x5eb27ac and 0x80000003 at +0x5eb27be (stop 6)
#7524 + #5381 not mergeable as heads: git merge pr5381 into pr7524 conflicts in runtime/shims/xmem.cpp and runtime/test/xmem_test.cpp

Net: this PR does not move the front on its own — the wall in front of physical pages is still the TLS stop — and the two boot PRs do not compose without a rebase, so the pair that would plausibly clear stop 6 cannot be measured from the current heads.

AI-assisted — agent: yes.

@Numbers-iwnl

Copy link
Copy Markdown

Detail on the merge conflict reported above, since it decides whether the pair can be measured at all.

runtime/shims/xmem.cpp conflicts in the XMemAlloc / XMemFree hunk and in the note_attributes signature:

So the two branches rewrite the same four lines with different allocators. Taking this PR's side as-is drops #7524's tracked-alloc guard; taking #7524's side drops the kNoSize bookkeeping. Either way the file needs a rebase of #5381 onto #7524 (or #7524 onto main first) before a combined boot run means anything.

runtime/test/xmem_test.cpp conflicts for the same reason: the test asserts the old allocator's behaviour.

AI-assisted — agent: yes.

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.