Skip to content

d3d12: a window's GPU writes go back to the title's pages (RT-TITLE-WINDOW-WRITE-BACK) - #2129

Merged
aslan2142 merged 4 commits into
ProjectLeonida:mainfrom
star41905453-coder:rt-title-window-write-back
Nov 26, 2026
Merged

aslan2142 merged 4 commits into
ProjectLeonida:mainfrom
star41905453-coder:rt-title-window-write-back

Conversation

@star41905453-coder

@star41905453-coder star41905453-coder commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes the world-start stop of #1537 (QemmHD's WRITE_INVALID, about 160 s into the load): a title window is a read-side mirror, so a UAV or raw write into one landed in the copy and the title never saw it.

What it does

  • Every title range a submission's bindings resolve to is kept (the resolve path, so root views, table V#s and created views are all covered — a V# has no read/write bit, so a read-only view costs a copy and a write is never missed).
  • A batch is fenced: it carries the retire ticket of the submission that will use it, and the ranges are copied back to the title's pages only once the context reports that ticket retired — at a later refresh, before that refresh's forward copy. A range another submission is still writing is never read half done.
  • A page the title wrote in between keeps the title's newer bytes and its GPU result is dropped (the tracker knows those pages: not guarded and not asked-about-and-clean, or not committed).
  • Caps: 8,192 ranges and 64 MiB per submission, refused ranges logged once. LEONIDA_TITLE_WRITEBACK=0 turns it off.

It also covers the slot-133 case: a placed buffer whose pages the driver will not import is a shadow too, and a write through it landed in the copy exactly the same way. The pages there are title memory, the buffer's alias resolves through the same noter and the tracker carries the range, so the mechanism needed nothing new — only proof, d3d12_placed_write_back.

Test — d3d12_title_window_write_back (new ctest entry, --window-writeback): a dispatch through a root UAV at the title's own pages. The pages stay untouched until the next submission, then hold exactly the words the shader wrote, across two submissions, and a title write survives the next forward copy. No game files.

Run — Linux, Wine 10, Mesa llvmpipe (no GPU on this box). The 21 failures of a full 448-test run are environmental and were confirmed by running the same list on unmodified main (9f9a7c5f3): every one fails there too, most with WARP reference unavailable, and the title tests pass there. Nothing in this diff causes a failure that main does not already have.

  • d3d12_title_va, d3d12_title_va_shadow, d3d12_geometry_views, d3d12_title_window_cap, d3d12_title_window_write_back, d3d12_placed_write_back: pass.
  • ctest -R 'write_back|title|shadow|alias|arena|stream': 20/20 pass.
  • Full suite: 448 run, 21 failed, 15 skipped — the same 21 fail on main (baseline above); 7 of them xmem/file_system/bcrypt_rng/root_sig are Wine gaps, the rest say WARP reference unavailable.
  • gta6rt --run of tiny_async through the rebuilt loader: PASS, exit 0.

What is still wanted: a retail --run past the cap on a GPU (the package is 208 GiB and this box has 36), with LEONIDA_DEVICE_FAULT=1 if it still dies.

Item: RT-TITLE-WINDOW-WRITE-BACK, claimed in #1608.

…INDOW-WRITE-BACK)

A window of the title's memory is a read-side mirror refreshed before every
submission, so a UAV or raw write into one landed in the copy and the title
never saw it. At the world start that is the WRITE_INVALID device loss of
ubiquitarianism#1537 (QemmHD, 160 s into the load, past the cap): the culling compute writes
through addresses that name title memory, and nothing ever reads the result
back into the pages.

The layer now keeps every title range a submission's bindings reach (the
resolve path, so root views, table V#s and created views alike) and copies
those ranges from the copy to the title's pages at the start of the next
refresh, before the forward copy. A page the title wrote in between takes the
title's newer bytes and its GPU result is dropped; the tracker already knows
those pages (guarded, hot and clean). Caps: 8,192 ranges and 64 MiB a
submission, logged once; LEONIDA_TITLE_WRITEBACK=0 turns it off.

Test: d3d12_title_window_write_back, a dispatch through a root UAV at the
title's pages: the written words reach the pages, hold across two
submissions, and a title write survives the next forward copy. No game files.

Item: RT-TITLE-WINDOW-WRITE-BACK (claimed in ubiquitarianism#1608)

Wine against llvmpipe.
@ecox982745

ecox982745 commented Nov 25, 2026 •

Copy link
Copy Markdown

Retested at fa3885a7f with the new retirement-ticket handling. On the RTX 4090, the stock test passed 6/6 and lower-address-first passed 6/6. Upper-address-first still failed 6/6. The lower window contained 0/64 written words and the upper one contained 64/64. Each set includes three runs with Vulkan validation and three without. Every submission in this test waits for its fence.

The patch below merges touching ranges under their lowest address and charges only newly covered bytes against the cap. Applied on top of this head, it passed all 18 GPU runs. Separately, I compiled the insertion code in a CPU harness with limits of five bytes and two ranges. Across all 46,656 ordered triples of nonempty intervals in an eight-byte space, the stored ranges and byte total matched a byte-set reference after every insertion, including refused insertions.

Tested patch for note_title_write (applies to fa3885a)
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -2418,27 +2418,30 @@
         if (!leonida::title_va_aliases().title_memory(va, lo, hi) || va >= hi) return;
         const std::uint64_t end = va + std::min(bytes, hi - va);
         std::lock_guard lock(title_write_back_mutex);
-        auto it = title_write_back.lower_bound(va);
-        if (it != title_write_back.begin()) {
-            auto previous = std::prev(it);
-            if (previous->second >= va) {
-                if (previous->second < end) previous->second = end;
-                return;
-            }
-        }
-        if (it != title_write_back.end() && it->first <= end) {
-            it->second = std::max(it->second, end);
-            return;
-        }
-        if (title_write_back.size() >= kTitleWriteBackRanges || title_write_back_bytes >= kTitleWriteBackBytes) {
+        auto first = title_write_back.lower_bound(va);
+        if (first != title_write_back.begin() && std::prev(first)->second >= va) --first;
+        if (first != title_write_back.end() && first->first <= va && first->second >= end) return;
+
+        std::uint64_t begin = va, merged_end = end, replaced_bytes = 0;
+        auto last = first;
+        while (last != title_write_back.end() && last->first <= merged_end) {
+            begin = std::min(begin, last->first);
+            merged_end = std::max(merged_end, last->second);
+            replaced_bytes += last->second - last->first;
+            ++last;
+        }
+        const std::uint64_t added_bytes = (merged_end - begin) - replaced_bytes;
+        if ((first == last && title_write_back.size() >= kTitleWriteBackRanges) ||
+            added_bytes > kTitleWriteBackBytes - title_write_back_bytes) {
             if (!title_write_back_refused++)
                 log_once("past LEONIDA_TITLE_WRITEBACK's caps: reached ranges are not copied back this submission; "
                          "ranges refused:",
                          1);
             return;
         }
-        title_write_back_bytes += end - va;
-        title_write_back.emplace(va, end);
+        auto kept = title_write_back.insert_or_assign(first, begin, merged_end);
+        title_write_back.erase(std::next(kept), last);
+        title_write_back_bytes += added_bytes;
     }
 
     // What the GPU wrote into those copies goes back to the title's pages, so a later read by the title or the next

Two adjacent windows lose the lower window's GPU writes when the command list binds the upper address first. I reproduced this at f55177efb on an RTX 4090, Windows 11, NVIDIA 616.64. Each submission waited for its fence before the next began.

I extended the PR's synthetic --window-writeback fixture locally. In one command list, dispatch the existing shader twice through its root UAV, once at the base of the fixture's zeroed 256 KiB buffer and once 64 KiB above it. Both dispatches write the same 64-word pattern. Submit that list, wait, then repeat to trigger write-back and inspect the original CPU pages. Changing only the dispatch order gave these results:

Runtime and dispatch order Lower window, nonzero words Upper window, nonzero words Runs
PR, lower first 64/64 64/64 3 plain and 3 with validation
PR, upper first 0/64 64/64 3 plain and 3 with validation
Local correction, either order 64/64 64/64 3 per order with validation

The cause is in DeviceState::note_title_write. When lower_bound(va) finds a touching successor, the branch extends its end and keeps its old start. With the upper window already recorded, the lower one disappears. Re-keying that entry to the lower start made all 64 corresponding word pairs equal in both orders. For the full fix, merge every interval the new binding touches and charge the byte cap for the additional covered bytes. The current extension branches return before updating the byte count.

The PR's unmodified five title-window and geometry CTests passed on this card, both plain and with Vulkan validation. This additional case checks writes to two adjacent windows. All inputs were synthetic.

AI-assisted with OpenAI Codex (gpt-6.2-astra).

…TITLE-WINDOW-WRITE-BACK)

The first cut copied the reached ranges back at the next refresh whether or not
the submission that wrote them had finished, so a range the GPU was still
filling could be read half done.

A batch is now kept with the retire ticket of the submission that will use it,
and the ranges are copied back only once the context reports that ticket done.
Anything not yet retired stays queued and is copied on a later refresh, still
before that refresh's forward copy, so the ordering that keeps the title's own
newer bytes is unchanged.

The test is unchanged and still passes: it asserts the pages are untouched
until the next submission and then hold exactly what the shader wrote.
@qhukz13

qhukz13 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Heads-up for whoever merges either: this PR and #2032 (TITLE-GPU-WRITE-BACK, BubsMcgee) implement the same thing, copying a shader's writes in a title window back to the title's pages. I reviewed #2032 earlier today (comment); reading this one against the three points there:

So this one covers what I raised there; the two authors may want to settle on one. ecox982745's upper-address-first ordering case above is still open here.

Native Windows run (the description has Wine/llvmpipe; ecox982745 ran an RTX 4090): GTX 1050 Ti, Windows 10 Pro 19045, NVIDIA 582.66, MSVC RelWithDebInfo, this head merged onto main c50ed94b3 (clean). d3d12_title_window_write_back, d3d12_title_va, d3d12_title_va_shadow, d3d12_title_window_cap, d3d12_api_descriptor_copy, d3d12_rebound_tables, d3d12_title_index_window, d3d12_title_vertex_window, xbox_geometry_upload_batch, d3d12_unmapped_vsharp: 10/10, 3 runs each, plain and with LEONIDA_VK_VALIDATION=1, no validation messages. I did not apply ecox982745's range-merge patch here.

AI-assisted (Claude Code).

…WRITE-BACK)

A slot-133 buffer the driver will not import is a shadow of the title's pages,
and the write through it landed in the copy exactly as a window's did. The
mechanism is already the same one - the pages are title memory, the alias of
the buffer resolves through the noter, and the tracker carries the range - but
nothing said so and nothing tested it.

d3d12_placed_write_back: a root UAV over a placed buffer. The pages keep the
title's words until the next submission, then hold the shader's; a write by the
title over the result survives the copy forward.
@ecox982745

Copy link
Copy Markdown

The new slot-133 test passes on my RTX 4090 at 990a9f931c391334d93674e2dabbe86e3d6d4aac. I extended it to two adjacent placed buffers. When the upper address was submitted first, the lower buffer received 0/64 expected words on all six runs. The range-merging patch from the window test applies cleanly to this head and fixes both orders.

Dispatch order PR head (lower / upper) With the range patch (lower / upper)
Lower address first 64/64 and 64/64 64/64 and 64/64
Upper address first 0/64 and 64/64 64/64 and 64/64

I created two separate 64 KiB slot-133 buffers over adjacent halves of one registered 128 KiB synthetic allocation. In one command list, each dispatch used its own root UAV and the fixture shader's existing root-read mode to write original_word[i + 64] + 7 into words 0–63. All CPU words still held their initial values after the first fence. The next submission triggered the copy back. In every run the other 32,640 words stayed unchanged. Each table cell represents three runs with Vulkan validation enabled and three with it disabled. Turning write-back off on the patched runtime returned 0/64 for both buffers in both orders.

One detail for the new stock test: its untouched == kElements assertion is skipped on this device. The host-import counter stayed flat across placement, and the shadow's shader address was inside the arena. The current guard requires an address at or above the arena size. The fixture can assert the timing directly when it disables host import, or use the import-count delta around placement to choose that assertion.

Windows 11, NVIDIA 616.64, synthetic GPU readback only. AI-assisted verification (OpenAI Codex).

…nced (RT-TITLE-WINDOW-WRITE-BACK)

A fenced batch waits for its submission's retire ticket. On a queue the layer
holds back (console ordering) the ticket is not ours, and in the worst case
nothing retires soon: the pending list would grow for the rest of the run.

Past 64 pending batches the oldest is now copied back without waiting, once
each, and the fact is logged once. Docs say so.
@Timon360SB

Copy link
Copy Markdown
Contributor

Testing Results — PR #2129

PR #2129 — title-window GPU write-back

Configuration

  • BASE: 9f9a7c5f30f8559c52675780cf84004571b8d6e5
  • HEAD: 990a9f931c391334d93674e2dabbe86e3d6d4aac
  • Date: 2026-11-26.
  • GPUs: NVIDIA GeForce RTX 5070 and RTX 2060 SUPER.
  • Build: Ninja, RelWithDebInfo, selected targets.
  • Repetitions: three with validation off and three with validation on.

Both revisions built successfully.

Results

GPU BASE HEAD FAIL SKIP
RTX 5070 24 PASS 66 PASS 0 0
RTX 2060 SUPER 24 PASS 66 PASS 0 0

180 actual test executions, 11 distinct test names. No checkpoint-restored results were counted.

The four shared tests passed on both revisions: d3d12_title_va, d3d12_title_va_shadow, d3d12_geometry_views, d3d12_title_window_cap.

Write-back checks

Both new fixtures passed 6/6 times on each GPU:

Fixture Observed result in every execution
d3d12_title_window_write_back 64/64 words nonzero after write-back; 64/64 stable across subsequent submissions; 64/64 CPU replacement words preserved
d3d12_placed_write_back 64/64 words changed and nonzero; 64/64 CPU replacement words preserved

No VUID messages were captured.

Coverage limits: the new fixtures ran only on HEAD. They do not check every word against an exact shader-output reference. The placed-buffer pre-write-back timing assertion did not execute on either GPU.

Testing used synthetic fixtures on physical GPUs. AI assisted log analysis and report preparation.

clquwu added a commit to clquwu/leonida-ultimate that referenced this pull request Nov 26, 2026
…pump coalescing & 16-bit/indirect completeness (Wave 29A)

Adapts and integrates:
- GPU-to-CPU title-window write-back with retire-ticket fencing, xmem dirty-stamp + byte-level CPU-write precedence, and LEONIDA_TITLE_WRITEBACK=0 kill switch (ubiquitarianism/leonida#2129, GPL-3.0).
- Slot-133 shadow GPU-write preservation via 256-byte piece sums (LEONIDA_SHADOW_KEEP, ubiquitarianism/leonida#2163, GPL-3.0), saved-snapshot advancement after partial merge (Marvisak/VIctory#3031, GPL-3.0), and read-only hash skip for foreign PAGE_READONLY pages (ubiquitarianism/leonida#1897, GPL-3.0).
- Held-batch fence-pump fix: snapshot has_shader_work / internal_staging on ExecuteCommandLists thread in VulkanQueue::Deferred and coalesce redundant back-to-back refresh_shadows() / refresh_console_heaps() inside a single QueueHolds::pump_ready() sweep when xmem epochs and shadow registry are unchanged.
- Transient dedicated command-pool renewal for long recordings above LEONIDA_CMD_POOL_RENEW (default 512, Rubenpannen/VIctory-RTX5070@5df4fb3, GPL-3.0).
- Complete 16-bit packed colour widening for B5G6R5_UNORM RT/UAV, B4G4R4A4_UNORM RT/UAV, and B5G5R5A1_UNORM RT/UAV (Marvisak/VIctory#2936, GPL-3.0; californiaAlmonds/OpenScarlett@ee7153c, MIT).
- Compound graphics ExecuteIndirect host-visible expansion, Tier 1.1 incrementing-constant stride fix, and D3D12 state-leakage binding reset (ubiquitarianism/leonida#1937, GPL-3.0).

AI-assisted; verified on NVIDIA GeForce RTX 3080 (Windows 11, VS 18 MSVC 19.51) with LEONIDA_VK_VALIDATION=1 (18/18 CTests passed, 0 validation errors).
@star41905453-coder
star41905453-coder force-pushed the rt-title-window-write-back branch from 298748a to 5fa864e Compare November 26, 2026 12:05
@aslan2142
aslan2142 merged commit dbe7cf3 into ProjectLeonida:main Nov 26, 2026
@aslan2142

Copy link
Copy Markdown
Collaborator

Thank you, @star41905453-coder. This went into main through #2350 (RT-LINUX-AMD-WORLD), merged at your head 5fa864e53 with your commits and authorship kept. The one conflict, in the title-window members, kept your write-back state as it is. The two-adjacent-buffers case reported above is still open; a follow-up is welcome. GitHub shows this PR as merged for that reason, so nothing needs closing.

AI-assisted (Claude Code, Claude Opus 5.5 and Claude Fable 5.2)

aslan2142 pushed a commit that referenced this pull request Nov 27, 2026
…n in the fault handler

ShadowPages::write_back copies a window's GPU writes back to the title's pages under the tracker's
SRW lock (#2129, and the 256-byte pieces of #2404). It reopens its own guard first, but the page can
still be read-only because of another guard (the geometry watch, another view's shadow). The copy
then faults, shadow_write_fault asks every tracker over the address, and this one's reopen() took
lock_ again on the thread that already held it. SRW locks are not recursive, so the title's
submitting thread hung for good: on an RTX 4070 Laptop (NVIDIA 621.40) the main loop froze at
209-309 s with no device loss, and the thread dumps showed the submitting thread inside
write_back -> (fault) -> shadow_write_fault -> reopen, waiting on the SRW lock, in four runs.

write_back records its thread in writer_ while it holds lock_; reopen() and reopen_range() skip
taking the lock on that thread (they run under it). Other threads still wait on the lock as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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