d3d12: every title write-back range on one guarded page goes back (RT-TITLE-WRITEBACK-SAME-PAGE-RANGES) #2470

Open
github-bot wants to merge 2 commits from github-bot/gh-2470 into main AGit
Owner

@⁠Tyrannys on GitHub · 2026-11-27 14:43 UTC · original
Tyrannys:rt-title-writeback-same-page-ranges → main · +203 −54 · 3 files · 2 commits · open

Claimed in the coordination issue as: RT-TITLE-WRITEBACK-SAME-PAGE-RANGES (#1608). Found by @⁠73N1X (their finding in #1608, 2026-11-27 11:40).

Depends on: none (builds on #2468, now merged; upstream/main merged in)

What and why

DeviceState::write_back_titles handed each finished range to ShadowPages::write_back on its own. When the first range that differs is on a guarded page, write_back reopens that page, and reopen_locked clears kProtected. Every later disjoint range on that page then fails the held() check (not protected, not clean) and is dropped as if the title had written the page. But only the write-back itself wrote there, so the GPU's later words on that page never reach the title, and the next forward copy writes the title's older bytes over them in the shadow. CPU code that reads GPU results back (the write-back case) sees stale words.

Fix:

  • ShadowPages::write_back takes all of one tracker's finished ranges in one call (const std::pair<uintptr_t, uintptr_t>*, count, optional reached count). It decides which pages are held once for every page the ranges cover, after the journal, pin and write-watch checks and before the first copy. Then it copies range by range as before.
  • write_back_titles sorts the finished ranges (batches can overlap) and gives each shadow the ranges over it in one call. The log line's range count now comes from reached.
  • The per-page decisions are allocated before lock_ is taken. A thread that faults on a guarded page waits on lock_ in reopen(), and it may hold the heap lock while it waits.

How it relates to the other work on this path:

  • #2468 (OreoFR, RT-WRITEBACK-TILE-REOPEN, merged) took held once per page before the copies of one range. This PR now builds on it: the same snapshot, in #2468's held_pages_ member, covers all of a tracker's ranges, and #2468's tile test stays.
  • #2352 merges touching ranges in note_title_write. This PR does not touch that function and is about disjoint ranges.
  • #2461 changes the batch-draining loop in write_back_titles. This PR changes only the loop after it (the per-range calls). The two edit neighbouring lines, so a textual conflict is possible, but no logic is shared.
  • RT-WRITEBACK-FAULT-RELOCK (OreoFR, #2418 is merged): the writer_ handling is unchanged.

Known limit, unchanged by this PR: a page opened by the write-back stays writable by the title until the next refresh guards it again. Before this PR that was already true for the pieces of a single range after the first.

Tested

New test d3d12_title_window_write_back_ranges (d3d12_title_va_test --window-writeback-ranges). It makes a title window and lets a submission that does not reach the ring guard the pages. Then the GPU writes new words into the window through its arena address, so nothing is noted for that write. Before that submission, the test notes 16 four-byte ranges 16 bytes apart on the first page. The next refresh copies them back.

  • base ec91d695c: fails 3/3. 1/16 four-byte ranges on one guarded page reached it, 48/48 words between them kept the title's
  • with the fix: passes 3/3. 16/16 ranges reach the page, the 48 words between them keep the title's, and no word has any other value.

Write-back, shadow and title-memory tests (-R "write_back|writeback|shadow|title_memory|title_va|title_window|placed"): 19/19 pass, including d3d12_title_window_write_back_fault (#2418), d3d12_placed_write_back and d3d12_shadow_keep_refill(_off).

Full suite (ctest -C Release -j 4): 498/502. The four failures:

  • big_compile_gate timed out under -j 4 and passes alone.
  • xs_proxy_mock failed under -j 4 and passes alone.
  • xbox_present (present_planes) and d3d12_set_descriptor_heaps (recorded_commands) also fail on the base with the original d3d12_vulkan_device.cpp, so they are not from this change.

No game files or shaders were needed.

GPUs tested: profile M: NVIDIA GeForce RTX 4070 SUPER, 12 GB, desktop, driver 621.01, Windows 11

AI-assisted: yes (Claude Code)

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • 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. (n/a)

🤖 Generated with Claude Code

**@⁠Tyrannys** on GitHub · 2026-11-27 14:43 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2470) `Tyrannys:rt-title-writeback-same-page-ranges` → `main` · +203 −54 · 3 files · 2 commits · open Claimed in the coordination issue as: RT-TITLE-WRITEBACK-SAME-PAGE-RANGES (https://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608). Found by @⁠73N1X (their finding in #1608, 2026-11-27 11:40). Depends on: none (builds on #2468, now merged; `upstream/main` merged in) ### What and why `DeviceState::write_back_titles` handed each finished range to `ShadowPages::write_back` on its own. When the first range that differs is on a guarded page, `write_back` reopens that page, and `reopen_locked` clears `kProtected`. Every later disjoint range on that page then fails the `held()` check (not protected, not clean) and is dropped as if the title had written the page. But only the write-back itself wrote there, so the GPU's later words on that page never reach the title, and the next forward copy writes the title's older bytes over them in the shadow. CPU code that reads GPU results back (the write-back case) sees stale words. Fix: - `ShadowPages::write_back` takes all of one tracker's finished ranges in one call (`const std::pair<uintptr_t, uintptr_t>*`, count, optional `reached` count). It decides which pages are held once for every page the ranges cover, after the journal, pin and write-watch checks and before the first copy. Then it copies range by range as before. - `write_back_titles` sorts the finished ranges (batches can overlap) and gives each shadow the ranges over it in one call. The log line's range count now comes from `reached`. - The per-page decisions are allocated before `lock_` is taken. A thread that faults on a guarded page waits on `lock_` in `reopen()`, and it may hold the heap lock while it waits. How it relates to the other work on this path: - **#2468** (OreoFR, RT-WRITEBACK-TILE-REOPEN, merged) took `held` once per page before the copies of one range. This PR now builds on it: the same snapshot, in #2468's `held_pages_` member, covers all of a tracker's ranges, and #2468's tile test stays. - **#2352** merges touching ranges in `note_title_write`. This PR does not touch that function and is about disjoint ranges. - **#2461** changes the batch-draining loop in `write_back_titles`. This PR changes only the loop after it (the per-range calls). The two edit neighbouring lines, so a textual conflict is possible, but no logic is shared. - **RT-WRITEBACK-FAULT-RELOCK** (OreoFR, #2418 is merged): the `writer_` handling is unchanged. Known limit, unchanged by this PR: a page opened by the write-back stays writable by the title until the next refresh guards it again. Before this PR that was already true for the pieces of a single range after the first. ### Tested New test `d3d12_title_window_write_back_ranges` (`d3d12_title_va_test --window-writeback-ranges`). It makes a title window and lets a submission that does not reach the ring guard the pages. Then the GPU writes new words into the window through its arena address, so nothing is noted for that write. Before that submission, the test notes 16 four-byte ranges 16 bytes apart on the first page. The next refresh copies them back. - base `ec91d695c`: fails 3/3. `1/16 four-byte ranges on one guarded page reached it, 48/48 words between them kept the title's` - with the fix: passes 3/3. 16/16 ranges reach the page, the 48 words between them keep the title's, and no word has any other value. Write-back, shadow and title-memory tests (`-R "write_back|writeback|shadow|title_memory|title_va|title_window|placed"`): 19/19 pass, including `d3d12_title_window_write_back_fault` (#2418), `d3d12_placed_write_back` and `d3d12_shadow_keep_refill(_off)`. Full suite (`ctest -C Release -j 4`): 498/502. The four failures: - `big_compile_gate` timed out under `-j 4` and passes alone. - `xs_proxy_mock` failed under `-j 4` and passes alone. - `xbox_present` (`present_planes`) and `d3d12_set_descriptor_heaps` (`recorded_commands`) also fail on the base with the original `d3d12_vulkan_device.cpp`, so they are not from this change. No game files or shaders were needed. GPUs tested: profile M: NVIDIA GeForce RTX 4070 SUPER, 12 GB, desktop, driver 621.01, Windows 11 AI-assisted: yes (Claude Code) ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] 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. (n/a) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
DeviceState::write_back_titles handed each finished range to
ShadowPages::write_back on its own. The first range that differed reopened
its guarded page (kProtected cleared), and every later disjoint range on that
page then read as written by the title and was dropped, though only the
write-back itself had written there.

Each shadow now takes all of its finished ranges in one call, sorted by
address, and decides which pages are held once for all of them, before the
first copy. The per-page decisions are allocated before the tracker's lock is
taken.

New test d3d12_title_window_write_back_ranges: 16 four-byte ranges 16 bytes
apart on one guarded page of a title window. On main 1/16 reach the page
(3/3 runs); with the fix 16/16, and the words between them keep the title's.

Found by 73N1X in #1608.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-27 14:46:04 +00:00
Author
Owner

@⁠lixonik on GitHub · 2026-11-27 15:20 UTC · original · reviewed

Reviewed and tested at 27c167376 (merged cleanly onto main ec91d695c).

Batching all finished ranges per tracker into one ShadowPages::write_back() call and snapshotting held_pages once before the first copy cleanly fixes the multi-range-on-one-guarded-page drop, and passes all write-back GPU tests on RTX 5070.

Two coordination / optimization notes:

  • Overlap with #2468: snapshotting held_pages across all ranges in one call also addresses #2468's same-tile reopen bug (including #2468's noted multi-range-in-one-tile limit). Both PRs touch the same lines in runtime/CMakeLists.txt, runtime/shims/d3d12_vulkan_device.cpp, and runtime/test/d3d12_title_va_test.cpp; if #2470 lands, pulling in #2468's host_heap held_pages_ member and --window-writeback-fault-tile test covers both issues cleanly.
  • Two minor perf notes inline on held_pages allocation and repeated reopen_locked() calls for ranges sharing a page.

Verified locally on Windows 11 (MSVC 19.44.35230.0, Ninja Release, NVIDIA GeForce RTX 5070, driver 610.88, Vulkan 1.4.341; note VK_LAYER_KHRONOS_validation is not installed locally so Vulkan validation layers did not run):

  • d3d12_title_window_write_back, d3d12_title_window_write_back_fault, d3d12_title_window_write_back_ranges (16/16 four-byte ranges reached the guarded page, 48/48 surrounding words kept), d3d12_placed_write_back: 4/4 passed
  • scripts/check_no_game_data.py and git diff --check: clean

AI-assisted.

**@⁠lixonik** on GitHub · 2026-11-27 15:20 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2470#pullrequestreview-6090272733) · **reviewed** Reviewed and tested at `27c167376` (merged cleanly onto `main` `ec91d695c`). Batching all finished ranges per tracker into one `ShadowPages::write_back()` call and snapshotting `held_pages` once before the first copy cleanly fixes the multi-range-on-one-guarded-page drop, and passes all write-back GPU tests on RTX 5070. Two coordination / optimization notes: - **Overlap with `#2468`**: snapshotting `held_pages` across all ranges in one call also addresses `#2468`'s same-tile reopen bug (including `#2468`'s noted multi-range-in-one-tile limit). Both PRs touch the same lines in `runtime/CMakeLists.txt`, `runtime/shims/d3d12_vulkan_device.cpp`, and `runtime/test/d3d12_title_va_test.cpp`; if `#2470` lands, pulling in `#2468`'s `host_heap` `held_pages_` member and `--window-writeback-fault-tile` test covers both issues cleanly. - Two minor perf notes inline on `held_pages` allocation and repeated `reopen_locked()` calls for ranges sharing a page. Verified locally on Windows 11 (MSVC 19.44.35230.0, Ninja Release, NVIDIA GeForce RTX 5070, driver 610.88, Vulkan 1.4.341; note `VK_LAYER_KHRONOS_validation` is not installed locally so Vulkan validation layers did not run): - `d3d12_title_window_write_back`, `d3d12_title_window_write_back_fault`, `d3d12_title_window_write_back_ranges` (16/16 four-byte ranges reached the guarded page, 48/48 surrounding words kept), `d3d12_placed_write_back`: 4/4 passed - `scripts/check_no_game_data.py` and `git diff --check`: clean AI-assisted.
@ -421,0 +436,4 @@
if (lo >= hi) return 0;
// Allocated before lock_ is taken: a thread that faults on a guarded page waits on lock_ in reopen(), and may
// hold the heap's lock while it does.
std::vector<std::uint8_t> held_pages((hi - lo) / kPage);
Author
Owner

@⁠lixonik on GitHub · 2026-11-27 15:20 UTC · original

Good that held_pages is allocated before AcquireSRWLockExclusive(&lock_) and destroyed after ReleaseSRWLockExclusive(&lock_) on every return path, avoiding the fault-handler process-heap deadlock. Keeping it as a reusable Vector<std::uint8_t> (leonida::host_heap) member on ShadowPages (as in #2468) would also avoid per-call process-heap allocations when two ranges touch opposite ends of a large tracker.

**@⁠lixonik** on GitHub · 2026-11-27 15:20 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2470#discussion_r4721091784) Good that `held_pages` is allocated before `AcquireSRWLockExclusive(&lock_)` and destroyed after `ReleaseSRWLockExclusive(&lock_)` on every return path, avoiding the fault-handler process-heap deadlock. Keeping it as a reusable `Vector<std::uint8_t>` (`leonida::host_heap`) member on `ShadowPages` (as in `#2468`) would also avoid per-call process-heap allocations when two ranges touch opposite ends of a large tracker.
@ -475,0 +505,4 @@
const std::uint8_t* copy = t.shadow + (c - t.begin);
if (std::memcmp(reinterpret_cast<const void*>(c), copy, e - c) != 0) {
if (!opened) {
reopen_locked(at, at + pages * kPage);
Author
Owner

@⁠lixonik on GitHub · 2026-11-27 15:20 UTC · original

Minor: bool opened is reset per range r, so when many disjoint ranges share one guarded page (e.g. 130 four-byte ranges on one page), range 0 clears kProtected and ranges 1..129 still enter reopen_locked(at, at + pages * kPage) and issue a VirtualQuery each time. Skipping reopen_locked when no page in [at, at + pages * kPage) still has kProtected set avoids the redundant VirtualQuery calls.

**@⁠lixonik** on GitHub · 2026-11-27 15:20 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2470#discussion_r4721091793) Minor: `bool opened` is reset per range `r`, so when many disjoint ranges share one guarded page (e.g. 130 four-byte ranges on one page), range 0 clears `kProtected` and ranges 1..129 still enter `reopen_locked(at, at + pages * kPage)` and issue a `VirtualQuery` each time. Skipping `reopen_locked` when no page in `[at, at + pages * kPage)` still has `kProtected` set avoids the redundant `VirtualQuery` calls.
Author
Owner

@⁠djrolfes on GitHub · 2026-11-27 15:26 UTC · original

Independent Linux/Wine + NVIDIA check at head 27c167376 (merged cleanly onto origin/main ec91d695c in a local integration stack alongside #2467, #2463, #2469, #2461, #2126, #2091, and two local V# patches).

  • Environment: Linux 7.2.15, wine-11.22, clang-cl + xwin cross-build, NVIDIA GeForce RTX 3070 Ti 8 GB, driver 620.73.04, Ryzen 7 5800X, 32 GB RAM. No game files.
  • CTest:
    • d3d12_title_window_write_back_ranges: passed (6.06 s) — 16/16 four-byte ranges on one guarded page reached it, 48/48 words between them kept the title's, 0 words neither.
    • d3d12_title_va, d3d12_title_va_shadow, d3d12_title_window_cap, d3d12_title_window_write_back: all passed (~6.0 s each).
    • d3d12_title_window_write_back_fault: skipped as expected under Wine (write watching is off).
  • Code review: allocating held_pages before taking lock_ and computing page hold state once across all sorted ranges per shadow cleanly avoids both the same-page reopen drop and the lock-inversion hazard.

AI-assisted.

**@⁠djrolfes** on GitHub · 2026-11-27 15:26 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2470#issuecomment-7222061018) Independent Linux/Wine + NVIDIA check at head `27c167376` (merged cleanly onto `origin/main` `ec91d695c` in a local integration stack alongside `#2467`, `#2463`, `#2469`, `#2461`, `#2126`, `#2091`, and two local V# patches). - **Environment:** Linux `7.2.15`, `wine-11.22`, `clang-cl` + `xwin` cross-build, NVIDIA GeForce RTX 3070 Ti 8 GB, driver `620.73.04`, Ryzen 7 5800X, 32 GB RAM. No game files. - **CTest:** - `d3d12_title_window_write_back_ranges`: **passed** (`6.06 s`) — `16/16 four-byte ranges on one guarded page reached it, 48/48 words between them kept the title's, 0 words neither`. - `d3d12_title_va`, `d3d12_title_va_shadow`, `d3d12_title_window_cap`, `d3d12_title_window_write_back`: all **passed** (`~6.0 s` each). - `d3d12_title_window_write_back_fault`: skipped as expected under Wine (`write watching is off`). - **Code review:** allocating `held_pages` before taking `lock_` and computing page hold state once across all sorted ranges per shadow cleanly avoids both the same-page reopen drop and the lock-inversion hazard. AI-assisted.
#2468 (RT-WRITEBACK-TILE-REOPEN) took write_back's per-page held decision
before the copies for one range. This branch takes it for all of a tracker's
ranges in one call, so the two are now one snapshot over every range, kept in
#2468's host-heap member held_pages_ (sized before lock_ is taken). Both tests
stay: d3d12_title_window_write_back_fault_tile and
d3d12_title_window_write_back_ranges; submit_write takes both va2 and base.

Also from lixonik's review: a run whose pages an earlier range already
reopened (none still kProtected) skips reopen_locked and its VirtualQuery.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Author
Owner

@⁠Tyrannys on GitHub · 2026-11-27 16:08 UTC · original
On runtime/shims/d3d12_vulkan_device.cpp line 439 (outdated):

@@ -415,9 +416,27 @@ class ShadowPages {
     // read-only binding's pages alone (guarded, so a write the title makes meanwhile faults and waits on the lock),
     // where opening them for a whole copy lost a write made between the opening and the copy; and of two copies of
     // the same bytes only the one that differs is written, where the last one won.
-    std::size_t write_back(std::uintptr_t from, std::uintptr_t to) {
-        from = std::max(from, first_), to = std::min(to, last_);
-        if (from >= to) return 0;
+    //
+    // All the finished ranges over this tracker come in one call, and which pages are held is decided once for all of
+    // them, before the first copy. One call per range made the first range that differed reopen its page (kProtected
+    // gone), and every later range on that page then read as written by the title and was dropped, though only this
+    // write-back had written there (73N1X, #1608: of 130 four-byte ranges 256 bytes apart, 9 went back). A page
+    // opened here is open to the title until the next refresh guards it again, as it was for the pieces of one range
+    // after the first.
+    std::size_t write_back(const std::pair<std::uintptr_t, std::uintptr_t>* ranges, std::size_t count,
+                           std::size_t* reached = nullptr) {
+        if (reached) *reached = 0;
+        std::uintptr_t lo = last_, hi = first_;  // the pages the ranges cover
+        for (std::size_t r = 0; r < count; ++r) {
+            const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_);
+            if (from >= to) continue;
+            lo = std::min(lo, from & ~(kPage - 1));
+            hi = std::max(hi, (to + kPage - 1) & ~(kPage - 1));
+        }
+        if (lo >= hi) return 0;
+        // Allocated before lock_ is taken: a thread that faults on a guarded page waits on lock_ in reopen(), and may
+        // hold the heap's lock while it does.
+        std::vector<std::uint8_t> held_pages((hi - lo) / kPage);

Thanks, done in d7b81dd43. The merge with main brought in #2468's held_pages_ (a leonida::host_heap Vector member), and this branch now uses it for the snapshot over all ranges. I size it before lock_ is taken (only write_back uses it, and one write_back runs at a time under shadow_mutex), so the lock-ordering point still holds and the capacity is reused between calls. AI-assisted (Claude Code).

**@⁠Tyrannys** on GitHub · 2026-11-27 16:08 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2470#discussion_r4721526760) On `runtime/shims/d3d12_vulkan_device.cpp` line 439 (outdated): ```diff @@ -415,9 +416,27 @@ class ShadowPages { // read-only binding's pages alone (guarded, so a write the title makes meanwhile faults and waits on the lock), // where opening them for a whole copy lost a write made between the opening and the copy; and of two copies of // the same bytes only the one that differs is written, where the last one won. - std::size_t write_back(std::uintptr_t from, std::uintptr_t to) { - from = std::max(from, first_), to = std::min(to, last_); - if (from >= to) return 0; + // + // All the finished ranges over this tracker come in one call, and which pages are held is decided once for all of + // them, before the first copy. One call per range made the first range that differed reopen its page (kProtected + // gone), and every later range on that page then read as written by the title and was dropped, though only this + // write-back had written there (73N1X, #1608: of 130 four-byte ranges 256 bytes apart, 9 went back). A page + // opened here is open to the title until the next refresh guards it again, as it was for the pieces of one range + // after the first. + std::size_t write_back(const std::pair<std::uintptr_t, std::uintptr_t>* ranges, std::size_t count, + std::size_t* reached = nullptr) { + if (reached) *reached = 0; + std::uintptr_t lo = last_, hi = first_; // the pages the ranges cover + for (std::size_t r = 0; r < count; ++r) { + const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); + if (from >= to) continue; + lo = std::min(lo, from & ~(kPage - 1)); + hi = std::max(hi, (to + kPage - 1) & ~(kPage - 1)); + } + if (lo >= hi) return 0; + // Allocated before lock_ is taken: a thread that faults on a guarded page waits on lock_ in reopen(), and may + // hold the heap's lock while it does. + std::vector<std::uint8_t> held_pages((hi - lo) / kPage); ``` Thanks, done in d7b81dd43. The merge with main brought in #2468's `held_pages_` (a `leonida::host_heap` Vector member), and this branch now uses it for the snapshot over all ranges. I size it before `lock_` is taken (only `write_back` uses it, and one `write_back` runs at a time under `shadow_mutex`), so the lock-ordering point still holds and the capacity is reused between calls. AI-assisted (Claude Code).
Author
Owner

@⁠Tyrannys on GitHub · 2026-11-27 16:08 UTC · original
On runtime/shims/d3d12_vulkan_device.cpp line 508 (outdated):

@@ -439,48 +458,66 @@ class ShadowPages {
             ReleaseSRWLockExclusive(&lock_);
             return 0;
         }
-        leonida::kernel_writes::for_each_pin(from, to, [&](std::uintptr_t a, std::uintptr_t b) {
-            for (std::uintptr_t p = std::max(a, from) & ~(kPage - 1); p < std::min(b, to); p += kPage)
-                state_[(p - first_) / kPage] |= kPinned;
-            pinned_ = true;
-        });
+        for (std::size_t r = 0; r < count; ++r) {
+            const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_);
+            if (from >= to) continue;
+            leonida::kernel_writes::for_each_pin(from, to, [&](std::uintptr_t a, std::uintptr_t b) {
+                for (std::uintptr_t p = std::max(a, from) & ~(kPage - 1); p < std::min(b, to); p += kPage)
+                    state_[(p - first_) / kPage] |= kPinned;
+                pinned_ = true;
+            });
+        }
         ask_written_locked();
         // A page the title wrote since it was last copied holds the newer bytes already: its GPU result is dropped and
         // the refresh's own copy carries the title's. So is a page whose mapping changed, one a kernel write may be
         // filling, and one xmem maps at another address too (a write there is seen by no guard and no watch here).
-        const auto held = [&](std::size_t i) {
-            const std::uint8_t s = state_[i];
-            return (s & (kZero | kRequery | kPinned | kAliased)) || (!(s & kProtected) && !(s & kClean));
-        };
+        const std::size_t p0 = (lo - first_) / kPage;
+        for (std::size_t r = 0; r < count; ++r) {
+            const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_);
+            if (from >= to) continue;
+            for (std::size_t i = (from - first_) / kPage, i1 = (to - first_ + kPage - 1) / kPage; i < i1; ++i) {
+                const std::uint8_t s = state_[i];
+                held_pages[i - p0] =
+                    (s & (kZero | kRequery | kPinned | kAliased)) || (!(s & kProtected) && !(s & kClean));
+            }
+        }
+        const auto held = [&](std::size_t i) { return held_pages[i - p0] != 0; };
         constexpr std::uintptr_t kPiece = 256;  // compared and copied in pieces this size
         std::size_t written = 0;
-        for (std::uintptr_t at = from & ~(kPage - 1); at < ((to + kPage - 1) & ~(kPage - 1));) {
-            std::size_t pages = 0;
-            while (at + (pages + 1) * kPage <= ((to + kPage - 1) & ~(kPage - 1)) &&
-                   held((at - first_) / kPage + pages) == held((at - first_) / kPage))
-                ++pages;
-            if (!held((at - first_) / kPage)) {
-                const std::uintptr_t a = std::max(at, from), b = std::min(at + pages * kPage, to);
-                bool opened = false;
-                for (const Target& t : targets_) {
-                    const std::uintptr_t x = std::max(a, t.begin), y = std::min(b, t.end);
-                    if (x >= y || !t.shadow) continue;
-                    for (std::uintptr_t c = x; c < y;) {
-                        const std::uintptr_t e = std::min(y, (c + kPiece) & ~(kPiece - 1));
-                        const std::uint8_t* copy = t.shadow + (c - t.begin);
-                        if (std::memcmp(reinterpret_cast<const void*>(c), copy, e - c) != 0) {
-                            if (!opened) {
-                                reopen_locked(at, at + pages * kPage);
-                                opened = true;
+        for (std::size_t r = 0; r < count; ++r) {
+            const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_);
+            if (from >= to) continue;
+            const std::size_t range_written = written;
+            const std::uintptr_t end = (to + kPage - 1) & ~(kPage - 1);
+            for (std::uintptr_t at = from & ~(kPage - 1); at < end;) {
+                std::size_t pages = 0;
+                while (at + (pages + 1) * kPage <= end &&
+                       held((at - first_) / kPage + pages) == held((at - first_) / kPage))
+                    ++pages;
+                if (!held((at - first_) / kPage)) {
+                    const std::uintptr_t a = std::max(at, from), b = std::min(at + pages * kPage, to);
+                    bool opened = false;
+                    for (const Target& t : targets_) {
+                        const std::uintptr_t x = std::max(a, t.begin), y = std::min(b, t.end);
+                        if (x >= y || !t.shadow) continue;
+                        for (std::uintptr_t c = x; c < y;) {
+                            const std::uintptr_t e = std::min(y, (c + kPiece) & ~(kPiece - 1));
+                            const std::uint8_t* copy = t.shadow + (c - t.begin);
+                            if (std::memcmp(reinterpret_cast<const void*>(c), copy, e - c) != 0) {
+                                if (!opened) {
+                                    reopen_locked(at, at + pages * kPage);

Good catch, thanks. Done in d7b81dd43: before calling reopen_locked for a run, write_back now checks whether any page in [at, at + pages * kPage) still has kProtected, and skips the call (and its VirtualQuery) when an earlier range already reopened them. reopen_locked only touches pages of ours, so the result is the same. d3d12_title_window_write_back_ranges and the #2468 tile test still pass. AI-assisted (Claude Code).

**@⁠Tyrannys** on GitHub · 2026-11-27 16:08 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2470#discussion_r4721527089) On `runtime/shims/d3d12_vulkan_device.cpp` line 508 (outdated): ```diff @@ -439,48 +458,66 @@ class ShadowPages { ReleaseSRWLockExclusive(&lock_); return 0; } - leonida::kernel_writes::for_each_pin(from, to, [&](std::uintptr_t a, std::uintptr_t b) { - for (std::uintptr_t p = std::max(a, from) & ~(kPage - 1); p < std::min(b, to); p += kPage) - state_[(p - first_) / kPage] |= kPinned; - pinned_ = true; - }); + for (std::size_t r = 0; r < count; ++r) { + const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); + if (from >= to) continue; + leonida::kernel_writes::for_each_pin(from, to, [&](std::uintptr_t a, std::uintptr_t b) { + for (std::uintptr_t p = std::max(a, from) & ~(kPage - 1); p < std::min(b, to); p += kPage) + state_[(p - first_) / kPage] |= kPinned; + pinned_ = true; + }); + } ask_written_locked(); // A page the title wrote since it was last copied holds the newer bytes already: its GPU result is dropped and // the refresh's own copy carries the title's. So is a page whose mapping changed, one a kernel write may be // filling, and one xmem maps at another address too (a write there is seen by no guard and no watch here). - const auto held = [&](std::size_t i) { - const std::uint8_t s = state_[i]; - return (s & (kZero | kRequery | kPinned | kAliased)) || (!(s & kProtected) && !(s & kClean)); - }; + const std::size_t p0 = (lo - first_) / kPage; + for (std::size_t r = 0; r < count; ++r) { + const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); + if (from >= to) continue; + for (std::size_t i = (from - first_) / kPage, i1 = (to - first_ + kPage - 1) / kPage; i < i1; ++i) { + const std::uint8_t s = state_[i]; + held_pages[i - p0] = + (s & (kZero | kRequery | kPinned | kAliased)) || (!(s & kProtected) && !(s & kClean)); + } + } + const auto held = [&](std::size_t i) { return held_pages[i - p0] != 0; }; constexpr std::uintptr_t kPiece = 256; // compared and copied in pieces this size std::size_t written = 0; - for (std::uintptr_t at = from & ~(kPage - 1); at < ((to + kPage - 1) & ~(kPage - 1));) { - std::size_t pages = 0; - while (at + (pages + 1) * kPage <= ((to + kPage - 1) & ~(kPage - 1)) && - held((at - first_) / kPage + pages) == held((at - first_) / kPage)) - ++pages; - if (!held((at - first_) / kPage)) { - const std::uintptr_t a = std::max(at, from), b = std::min(at + pages * kPage, to); - bool opened = false; - for (const Target& t : targets_) { - const std::uintptr_t x = std::max(a, t.begin), y = std::min(b, t.end); - if (x >= y || !t.shadow) continue; - for (std::uintptr_t c = x; c < y;) { - const std::uintptr_t e = std::min(y, (c + kPiece) & ~(kPiece - 1)); - const std::uint8_t* copy = t.shadow + (c - t.begin); - if (std::memcmp(reinterpret_cast<const void*>(c), copy, e - c) != 0) { - if (!opened) { - reopen_locked(at, at + pages * kPage); - opened = true; + for (std::size_t r = 0; r < count; ++r) { + const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); + if (from >= to) continue; + const std::size_t range_written = written; + const std::uintptr_t end = (to + kPage - 1) & ~(kPage - 1); + for (std::uintptr_t at = from & ~(kPage - 1); at < end;) { + std::size_t pages = 0; + while (at + (pages + 1) * kPage <= end && + held((at - first_) / kPage + pages) == held((at - first_) / kPage)) + ++pages; + if (!held((at - first_) / kPage)) { + const std::uintptr_t a = std::max(at, from), b = std::min(at + pages * kPage, to); + bool opened = false; + for (const Target& t : targets_) { + const std::uintptr_t x = std::max(a, t.begin), y = std::min(b, t.end); + if (x >= y || !t.shadow) continue; + for (std::uintptr_t c = x; c < y;) { + const std::uintptr_t e = std::min(y, (c + kPiece) & ~(kPiece - 1)); + const std::uint8_t* copy = t.shadow + (c - t.begin); + if (std::memcmp(reinterpret_cast<const void*>(c), copy, e - c) != 0) { + if (!opened) { + reopen_locked(at, at + pages * kPage); ``` Good catch, thanks. Done in d7b81dd43: before calling `reopen_locked` for a run, `write_back` now checks whether any page in `[at, at + pages * kPage)` still has `kProtected`, and skips the call (and its `VirtualQuery`) when an earlier range already reopened them. `reopen_locked` only touches pages of ours, so the result is the same. `d3d12_title_window_write_back_ranges` and the #2468 tile test still pass. AI-assisted (Claude Code).
Author
Owner

@⁠Tyrannys on GitHub · 2026-11-27 16:08 UTC · original

Merged upstream/main (no rebase) in d7b81dd43. Main now has #2468, so the conflict is resolved.

Thanks @⁠lixonik for the review and the RTX 5070 run, and @⁠djrolfes for the Linux/Wine check.

How this PR relates to #2468 (OreoFR, RT-WRITEBACK-TILE-REOPEN, now merged):

  • #2468 found and fixed the first half of this: it decided held once per page before the copies, so that a faulting copy's tile reopen on the same thread no longer dropped the later runs of that range. Credit for that snapshot, the held_pages_ member and the --window-writeback-fault-tile test goes to OreoFR (and to DadaCap, whose review found it).
  • This PR widens the same snapshot from one range to all of a tracker's finished ranges in one call. That is what 73N1X's case needs: several disjoint ranges on one guarded page, each handed to write_back alone before.
  • Since #2468 landed first, this PR now builds on it instead of replacing it. One snapshot, kept in #2468's member, covers both cases, and both regression tests stay: d3d12_title_window_write_back_fault_tile and d3d12_title_window_write_back_ranges.

Also from lixonik's notes: a run whose pages an earlier range already reopened skips reopen_locked (no VirtualQuery).

Re-tested after the merge on RTX 4070 SUPER, driver 621.01, Windows 11. ctest -R "write_back|writeback|shadow|title_memory|title_va|title_window|placed": 20/20 pass, including both tests above. AI-assisted (Claude Code).

**@⁠Tyrannys** on GitHub · 2026-11-27 16:08 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2470#issuecomment-7222910113) Merged `upstream/main` (no rebase) in d7b81dd43. Main now has #2468, so the conflict is resolved. Thanks @⁠lixonik for the review and the RTX 5070 run, and @⁠djrolfes for the Linux/Wine check. **How this PR relates to #2468 (OreoFR, RT-WRITEBACK-TILE-REOPEN, now merged):** - #2468 found and fixed the first half of this: it decided `held` once per page before the copies, so that a faulting copy's tile reopen on the same thread no longer dropped the later runs of that range. Credit for that snapshot, the `held_pages_` member and the `--window-writeback-fault-tile` test goes to OreoFR (and to DadaCap, whose review found it). - This PR widens the same snapshot from one range to all of a tracker's finished ranges in one call. That is what 73N1X's case needs: several disjoint ranges on one guarded page, each handed to `write_back` alone before. - Since #2468 landed first, this PR now builds on it instead of replacing it. One snapshot, kept in #2468's member, covers both cases, and both regression tests stay: `d3d12_title_window_write_back_fault_tile` and `d3d12_title_window_write_back_ranges`. Also from lixonik's notes: a run whose pages an earlier range already reopened skips `reopen_locked` (no `VirtualQuery`). Re-tested after the merge on RTX 4070 SUPER, driver 621.01, Windows 11. `ctest -R "write_back|writeback|shadow|title_memory|title_va|title_window|placed"`: 20/20 pass, including both tests above. AI-assisted (Claude Code).
This pull request can be merged automatically.
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2470/head:github-bot/gh-2470'
git switch 'github-bot/gh-2470'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2470'
git switch 'github-bot/gh-2470'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2470'
git switch 'github-bot/gh-2470'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2470'
git switch 'main'
git merge --squash 'github-bot/gh-2470'
git switch 'main'
git merge --ff-only 'github-bot/gh-2470'
git switch 'main'
git merge 'github-bot/gh-2470'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.