Skip to content

d3d12: a slot-133 shadow buffer is re-copied only where the title wrote since the last submission - #9045

Open
Etr0p wants to merge 20 commits into
ItsNotRexed:mainfrom
Etr0p:shadow-dirty-copy
Open

Etr0p wants to merge 20 commits into
ItsNotRexed:mainfrom
Etr0p:shadow-dirty-copy

Conversation

@Etr0p

@Etr0p Etr0p commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue: #8683 (comment)

Depends on: #8225 (and through it #7218). This branch is #8225's head 14dc9af52 plus one commit, 76d9b4b93.

What and why

#8225 gives a slot-133 buffer whose pages the driver won't import a shadow at the title's VA, and re-copies every live shadow in full before each ExecuteCommandLists. Its own description names the follow-up: copy only the dirty pages (#5381's tracking) or only what the submitted lists reference. On my machine the import is refused for the retail 174 MiB range (write-combined and uncommitted pages), so that full copy runs on every submission, and the frame loop drops to about 53 presents per second.

With this change, a shadow is re-copied only where the title wrote since the last submission.

Mechanism, and why this one

  • Why not GetWriteWatch: it only works on memory allocated with MEM_WRITE_WATCH. The title's slot-133 pages are xmem's physical pages, mapped as views of a pagefile-backed section (MapViewOfFile3), so a write watch can't be put on them.

  • Write faults through page protection, as in runtime: the CPU half of Xbox physical pages, with write-fault dirty tracking #5381: each shadow (ShadowPages) keeps the title's read-write pages read-only between submissions. The cache attribute is kept: write-combined pages become PAGE_READONLY | PAGE_WRITECOMBINE. A write faults, and a vectored handler, first in the chain (so a startup trace doesn't log these faults), makes the 64 KiB around the fault writable again and lets the write go on.

  • Before each submission (DeviceState::refresh_shadows, the same entry point as d3d12: a slot-133 buffer whose pages can't be imported is a shadow at the title's VA, re-copied before each submit #8225, called from VulkanQueue::execute_now), a VirtualQuery walk decides page by page:

    • read-write pages were written, newly committed or newly mapped: they are protected first, then copied. A write that lands in between faults again, so it reaches the next submission at the latest;
    • pages this shadow protected weren't written, so they are skipped;
    • pages that aren't committed are zeroed once.

    The walk reads the real protection every time, so a page the title decommits, recommits, or xmem remaps is seen as it is now. It doesn't trust a stale bit.

  • Writes a fault can't see, handled so the GPU still gets every write:

    • Aliases: xmem can map one physical page at several VAs. A write through another VA doesn't fault here. xmem now reports each page mapped at more than one address (runtime/src/title_page_watch.h), and a shadow copies those pages at every submission.
    • Kernel writes: a read-only page makes ReadFile fail with ERROR_NOACCESS instead of faulting into a user-mode handler. The title's ReadFile, ReadFileEx and ReadFileScatter now go through file shims that pin and open the destination first. The pin lasts until the call returns, or, for an overlapped read, until its OVERLAPPED says it completed. A read that still fails with ERROR_NOACCESS is retried once after opening the destination again. The helper is public: leonida::kernel_writes::read_file, or begin_write / end_write.
    • Pages that can't be watched are copied at every submission, as before: VirtualProtect refuses them, they are copy-on-write or the title's own read-only pages, or the handler couldn't be installed. Nothing is turned off: the fallback is d3d12: a slot-133 buffer whose pages can't be imported is a shadow at the title's VA, re-copied before each submit #8225's full copy.
  • Also changed: a copy that faults mid-run (a page decommitted after the VirtualQuery) is redone page by page, so only the decommitted page reads as zeros. This is @SkillIssueXO's fix from the d3d12: a slot-133 buffer whose pages can't be imported is a shadow at the title's VA, re-copied before each submit #8225 review. The whole-range zeroing it replaces could zero a run under in-flight readers.

  • Logging: the first refresh and then every 4096th are logged with the bytes copied per submission, the time, and the write faults.

  • Unchanged: the import path, textures, and the one-way rule (GPU writes to a shadow are not copied back).

Integration note for #7180 (DirectStorage)

dstorage.cpp reads straight into the request's destination with ReadFile (read_file_range). It should call this helper (leonida::kernel_writes::read_file instead of ::ReadFile). Otherwise a request whose destination is a watched shadow page fails with E_DSTORAGE_ACCESS_VIOLATION. This PR doesn't depend on #7180. In my retail integration below, I made that one-line change locally: 0 DirectStorage entry failures before and 0 after. A user-mode copy into title memory (the zlib path, guarded_move) needs nothing, because it faults like the title's own writes.

Tested

Windows 11 26200, MSVC 14.44, Ninja RelWithDebInfo, Vulkan SDK 1.4.363.0.

d3d12_existing_heap_test with LEONIDA_VK_VALIDATION=1, 0 validation errors, on two devices:

  • RTX 5070 Ti Laptop, NVIDIA 621.24: 4 runs, all pass.
  • Radeon 610M (RDNA2), AMD 26.11.2: pass.

Each new case compares a GPU copy of the whole buffer, byte for byte, with what the CPU wrote:

  • Rewrites: a pattern, then one rewritten 4 KiB page plus the last byte, then a submission with nothing written, then a write from another thread. Covered on a half-committed range, a half-committed write-combined range, a write-combined range, and one placed 64 bytes into its page. Between submissions the pages read back as PAGE_READONLY (0x2), or 0x402 when write-combined, so the tracking is really engaged.
  • Commit changes: a page committed after the shadow exists, then written; the first 64 KiB decommitted (reads zeros); a page recommitted and written.
  • Negative control: a section is mapped at two VAs, with the shadow at the first. A page written through the second view does not arrive without the alias mark: the first stale byte is in that page. With the mark, it arrives, and so does a later write.
  • Kernel writes: a plain ReadFile into a watched page fails with ERROR_NOACCESS (998), which is the control. Through the shims' path, a synchronous read and an overlapped read on an asynchronous handle both succeed and reach the GPU, and no pin is left behind.
  • Released buffer: once a buffer is released, its pages are read-write again, and a write doesn't fault.
  • d3d12: a slot-133 buffer whose pages can't be imported is a shadow at the title's VA, re-copied before each submit #8225's existing cases still pass.

xmem_test (173 checks), xs_proxy_mock_test and file_system_test (446 checks) pass.

Retail measurement (counts and times only)

RTX 5070 Ti Laptop, NVIDIA 621.24, my own copy of Xbox 1.0.2.1. A local boot stack with #8225: the import of the 174 MiB slot-133 range is refused there, so it is a shadow. 120 s per run, same stack, with and without this commit. The before run's full copy logs the same statistics line through a local instrumentation commit.

Before (#8225, full copy) After (this PR)
Bytes copied per submission 178 582 KiB 64.2 KiB
Copy time per submission (avg of 4096) 8.6 ms 1.25 ms (including the VirtualQuery walk)
Write faults — about 1 per submission
PresentX per second (from the 1 000th present on) 53.4 193.3
PresentX in 120 s 5 000 19 000
ExecuteCommandLists in 120 s 10 650 38 443
PresentX failed 0 0
DirectStorage entries failed 0 0
Title ReadFile failed, at the 53 248th call 52 579 52 566

Not tested: Wine, a GPU without Resizable BAR, the other slot-133 paths of #8304.

AI-assisted: yes (Claude Code).

🤖 Generated with Claude Code

Pipodi and others added 20 commits November 23, 2026 16:30
…e PC vtable refuse with E_NOTIMPL

The retail title calls device slot 133, past the 128-entry table; the call read an empty entry and jumped to 0.
Every slot beyond the PC device's vtable now reaches the generic thunk. Mock test covers slot 133.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ory (VK_EXT_external_memory_host)

The retail executable opens the 64 KiB graphics region it has just committed with XMemVirtualAlloc
through device slot 48 right after its first queue and fence; the layer answered E_NOTIMPL and the
title asserted.

The call now answers as the host runtime does on an RTX 4090 and WARP (six cases measured in
d3d12_existing_heap_test): the base of a VirtualAlloc allocation committed read-write over its whole
size opens a heap of that size, 64 KiB aligned, CUSTOM / WRITE_BACK / L0, SHARED |
SHARED_CROSS_ADAPTER | ALLOW_SHADER_ATOMICS; an inner address, a partial or reserve-only commit
and a read-only range are E_INVALIDARG. The backing is the range itself, imported with
VK_EXT_external_memory_host, which the device and the test device enable when present.
CheckFeatureSupport(EXISTING_HEAPS) follows the extension. Placed resources in such a heap are
refused (E_NOTIMPL, logged) until the placed path addresses memory outside the arena.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… an uncached one is refused

Measured on the RTX 4090 and WARP: PAGE_READWRITE | PAGE_WRITECOMBINE is accepted with
CPUPageProperty WRITE_COMBINE, PAGE_READWRITE | PAGE_NOCACHE is E_INVALIDARG. Two new cases in
d3d12_existing_heap_test; 8 of 8 match both host devices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…he title's own pages

Xbox device slot 133 is (va, desc, state, clear, riid, out): the title places a buffer at the VA of a
physical-page range it has just mapped (docs/retail_boot_chain.md 3.4, ItsNotRexed#6915). The proxy now hands it to
a handler the Vulkan layer registers (set_placed_at_va_handler), which imports [va, va + width) with
VK_EXT_external_memory_host and binds a VkBuffer to it: the CPU's writes there are the GPU's reads with no
copy, and the resource's console VA is the title's VA, so views and immediate writes the title names by
that VA resolve to it through the buffer VA index. The Xbox flag bits above the PC ones are dropped and
the layout made ROW_MAJOR, as slot 76 does; textures are E_NOTIMPL, a misaligned VA E_INVALIDARG, and
with no handler (a PC device) the slot refuses with E_NOTIMPL as ItsNotRexed#6953's table does.

Not decided here: a shader that adds heap_base to the title's VA (its own V#s) does not reach these
pages; that needs the single address space of docs/d3d12_vulkan.md 3.3.

d3d12_existing_heap_test: on a VirtualAlloc range and on a view of a pagefile-backed section (the form
xmem's physical pages take), the buffer's GPU VA is the address and a GPU copy to a READBACK buffer reads
a pattern the CPU wrote after creation; Vulkan validation clean on an RTX 4090.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ler registered by every Vulkan device

The PC flag mask was a D3D12_RESOURCE_FLAGS constant past the SDK's last enumerator, which clang-cl with
SDK 10.0.26100 refuses as a constant expression; it is an integer now, cast after the AND. The slot-133
handler was registered in create_vulkan_device only, so the standalone device gta6rt --run creates never
served the slot; the Device constructor registers it now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts:
#	runtime/shims/d3d12_xs_device.cpp
… found in review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… not import the title's pages

RADV under Wine refuses to import a view of a pagefile-backed section (E_OUTOFMEMORY on an RX 9070 XT,
found in review), which is the form xmem's physical pages take, so the retail boot stopped at the first
174 MiB placement. An import failure other than a misaligned VA now gives an ordinary DEFAULT buffer of
the same description, as ItsNotRexed#6915's stand-in did, logged once: the boot goes on, and the title's writes at
that VA don't reach it on such a driver.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…commit re-added it, found in review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ge check, immediate free, proxy test

- A write-combined (or uncached) page in the range is not imported: an RTX 5090 imported such a range
  and read wrong bytes back (found in review). It takes the ordinary-buffer fallback.
- The whole range must be committed, walked with VirtualQuery across allocations (the retail buffer
  spans three mapped windows); otherwise E_INVALIDARG instead of undefined behaviour in Vulkan.
- The imported memory is freed as soon as the submitted work has retired (wait_retire_ticket), not
  after the next submission: VK_EXT_external_memory_host needs the caller's pages to outlive it, and a
  title may free them right after releasing the resource.
- The PC flag mask is 0x5ff: 0x200, which the host refuses, is dropped. Slot 133 is listed in
  device_slot_overridden.
- xs_proxy_mock_test registers a handler and checks slot 133's argument positions, the flag mask
  (0x20204 -> 0x4), the ROW_MAJOR rewrite and the iid; d3d12_existing_heap_test checks the
  write-combined fallback and the partly committed refusal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ich varies from run to run

The host runtime answers 64 KiB on some runs and 4 MiB on others for the same allocation (RX 9070 XT,
RTX 5090, WARP; found in review), which made the test fail about 1 run in 40. The layer's Alignment
must still be 64 KiB for an opened heap, and the host's either of the two values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s at the offset; uncommitted pages fall back

The title places small buffers inside a page too: a 16-byte UAV at a 64-byte-aligned address on an
RTX 5090 (found in review), which the import refused with E_INVALIDARG, halting the boot. The import now
starts at the page holding the address and the buffer is bound at the offset; an offset off the
buffer's alignment takes the ordinary-buffer fallback. A range not fully committed (xmem commits on
first touch) also falls back instead of failing. Only a null address or a zero width are E_INVALIDARG.

d3d12_existing_heap_test: a buffer 64 bytes into a page reads back the CPU's writes at its own VA; a
1-byte offset and a partly committed range fall back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ad of E_NOTIMPL

The retail title places textures at slot 133 too, and asserted on the E_NOTIMPL (found in review). A
texture now gets an ordinary committed DEFAULT texture of the same description, as slot 76 gives one,
logged once; it is not on the title's pages. The proxy rewrites a texture's Xbox layout word to
UNKNOWN (a buffer's to ROW_MAJOR), as slot 76 does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Wine can report a requested write-combined allocation as ordinary read/write memory. Check the observed protection and retain the fallback expectation when a cache modifier is present; otherwise verify the read/write import. Add PAGE_NOCACHE to keep the unsafe-protection guard covered under Wine.

Claim: ItsNotRexed#7913 (comment)

Depends on: ItsNotRexed#7218

AI-assisted: Codex
…e starts in the matching state

The title's third word at slot 133 is a D3D12_BARRIER_LAYOUT, not a resource state (measured by
@dracbat on a retail boot: 0x6 SHADER_RESOURCE for its RT/DS textures, 0x3 UNORDERED_ACCESS for its
RT+UAV ones, 0xFFFFFFFF UNDEFINED for the 182 MiB buffer), as PC CreatePlacedResource2 takes it. The
proxy passes it to the handler, and a texture's ordinary committed fallback starts in the equivalent
legacy state (UNDEFINED and unlisted values give COMMON; a state the description refuses retries with
COMMON, so the title always gets its resource). Buffers are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…the title's VA

When VK_EXT_external_memory_host refuses the title's pages (write-combined or uncached pages, pages not committed yet, no extension, or the driver's import budget: about 64 MiB on an RTX 3070 Ti), the fallback was an ordinary DEFAULT buffer with neither the title's VA nor its data, so the title's descriptors resolved to nothing (slot 70 wrote a null SRV) and UI draws sampled nothing.

The fallback is now a host-visible buffer (VRAM through Resizable BAR where upload buffers use it) whose console VA is the title's address, filled from the title's pages at creation and again before every submission of command lists (VulkanContext::set_before_execute, called from VulkanQueue::execute_now). Only committed, readable pages are read; the rest is zero. GPU writes to the shadow are not copied back.

The first per-submission copy of each buffer size is timed and logged. Write-combined pages are read with MOVNTDQA: memcpy read 64 MiB of them in 253 ms on a Core i9-13900K, MOVNTDQA in 13 to 17 ms.

Tests: write-combined, uncached, 64 MiB write-combined and half-committed ranges in d3d12_existing_heap_test, two patterns over two submissions each, 0 validation errors on an RTX 4090.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Clang's baseline x64 target cannot inline _mm_stream_load_si128 into copy_guarded. Give only that function the target feature the existing intrinsic requires; keep the MSVC path and global build flags unchanged.

Depends on: ItsNotRexed#8225. Claimed in ItsNotRexed#8186, comment7110252121. AI-assisted: yes (Codex).
…te since the last submission

ItsNotRexed#8225 re-copies every live shadow in full before each ExecuteCommandLists: 174 MiB on retail, about 20 ms per
submission. Now each shadow (ShadowPages) keeps the title's read-write pages read-only between submissions, cache
attribute kept (PAGE_READONLY | PAGE_WRITECOMBINE for write-combined pages). A write faults; a vectored handler,
first in the chain, makes the 64 KiB around it writable again and lets the write go on. Before each submission a
VirtualQuery walk copies the pages that are read-write again (written, newly committed, or newly mapped), protects
them first, and skips the ones still protected. Pages not committed are zeroed once.

What a write fault can't see is handled so the GPU still gets every write:
- a physical page xmem maps at more than one address: xmem reports it (title_page_watch.h) and the shadow copies it
  at every submission;
- kernel writes, which fail with ERROR_NOACCESS on a read-only page instead of faulting: the title's ReadFile,
  ReadFileEx and ReadFileScatter go through new file shims that pin and open the destination first (until the call
  returns, or until the OVERLAPPED completes) and retry once on ERROR_NOACCESS;
- pages that can't be protected (VirtualProtect refuses, copy-on-write or the title's own read-only pages, or no
  handler) are copied at every submission, as before.
A run of pages that faults during the copy is redone page by page, so only a decommitted page reads as zeros.

Tests (d3d12_existing_heap_test): a pattern, then one rewritten page, an unchanged submission and a write from
another thread, on half-committed, write-combined and offset ranges; pages committed, decommitted and recommitted
under a live shadow; a write through a second view of the page, which does not arrive without the alias mark (the
negative control) and arrives with it; a plain ReadFile into a watched page fails with ERROR_NOACCESS (control) and
succeeds, synchronous and overlapped, through the shims' path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

Independent Linux CPU review

What changed: d3d12 slot-133 shadow buffer is re-copied only where the title wrote since the last submission (large runtime touch across shims + title_page_watch).

Checked: diff review / stat (~1.9k lines; no local runtime build). Substantial surface — watch for merge conflicts with other d3d12/xmem PRs.

Looks careful; no game files.

Cryptoteep added a commit to Cryptoteep/Leonida that referenced this pull request Nov 23, 2026
…gainst main

Update docs/retail_boot_chain.md "What clears it" column against current main:
- Stops 1, 2, 6, 10, 11 landed on main (ItsNotRexed#6919, 042c5f3: physical pages,
  2 MiB pages, and placeholder reservations).
- Stop 3 landed on main (e417570: XErrorReport in runtime/shims/xgameruntime.cpp).
- Replace closed unmerged PR ItsNotRexed#4313 (Stop 4) with tracking open PRs ItsNotRexed#8379, ItsNotRexed#7524.
- Replace closed unmerged PR ItsNotRexed#4348 (Stop 5) with active takeover PR ItsNotRexed#8461, ItsNotRexed#7784.
- Link open tracking PRs for Stops 7, 9, 12 (ItsNotRexed#8851, ItsNotRexed#9061, ItsNotRexed#2490, ItsNotRexed#9045, ItsNotRexed#8414).

Addresses agulerman's finding in ItsNotRexed#8868.
@smowlyy

smowlyy commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Verified head 76d9b4b93 merged onto main (867d922f0) on native Windows 11 (10.0.26300.9974, MSVC 19.44, RelWithDebInfo, Vulkan SDK 1.4.363.0) across both GPUs with LEONIDA_VK_VALIDATION=1:

  • python -I scripts/check_no_game_data.py on all 11 changed files: clean (exit 0)
  • cmake --build runtime/build --target d3d12_existing_heap_test xs_proxy_mock_test --parallel: built cleanly
  • .\runtime\build\xs_proxy_mock_test.exe: passed (xs_proxy_mock_test: PASS (9 allocations refused on purpose))
  • LEONIDA_VK_VALIDATION=1 .\runtime\build\d3d12_existing_heap_test.exe on NVIDIA GeForce RTX 5060 Ti (driver 610.88, Vulkan 1.4.341): passed, 0 validation errors (all slot-133 written-pages, aliased-page, kernel-write, and 8/8 host parity checks matched)
  • LEONIDA_VK_VALIDATION=1 LEONIDA_VK_DEVICE=Radeon .\runtime\build\d3d12_existing_heap_test.exe on AMD Radeon(TM) Graphics (driver 24.10.24, Vulkan 1.3.280): passed, 0 validation errors (all slot-133 written-pages, aliased-page, kernel-write, and 8/8 host + WARP parity checks matched)

AI-assisted.

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.

6 participants