From f52796172d221875aa5758ea45a7623122885d93 Mon Sep 17 00:00:00 2001 From: Dimitar Pavlov <360593571+azsekazvamdimitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:05:34 +0200 Subject: [PATCH] d3d12: slot-133 shadows pass over the title's reserved pages until the journal names them (RT-SHADOW-RESERVATION-SKIP) Under Wine most of the shadow walk after the story load is VirtualQuery of reserved pages: the stream pools' unmapped 64 KiB slots inside xmem's physical-page windows, 450-7,500 queries a refresh, 1.5 us each when quiet and 15-70 us under Wine's virtual-memory lock while the title maps memory. xmem now records the title's placeholders and windows in leonida::title_reservations and forgets them on every release. The walk marks a page there that VirtualQuery found reserved and private as settled and passes over it until the title memory journal names it, a release moves the registry's generation, or a full walk runs. Aliased, pinned and write-watched pages never settle. First world minute on an RTX 3090 (GE-Proton): VirtualQuery calls a refresh 443-1,616 -> 70-136, walk 16.5-40.4 -> 10.2-21.4 ms. AI-assisted. Tested: shadow tests under WineHQ 11.22 and GE-Proton11-14, also with LEONIDA_SHADOW_FULL_WALK=1; RTX 3090, NVIDIA 590.48.01. --- runtime/README.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 55 +++++++++++---- runtime/shims/xmem.cpp | 15 +++- runtime/src/title_page_watch.h | 83 ++++++++++++++++++++++- runtime/test/d3d12_existing_heap_test.cpp | 57 ++++++++++++++++ 5 files changed, 195 insertions(+), 17 deletions(-) diff --git a/runtime/README.md b/runtime/README.md index ab8451e6ff..07e89747cc 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -347,7 +347,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TEXTURE_SWEEP_BUDGET_US` | `400` | Microseconds a pass may spend on residency checks and uploads between textures. | | `LEONIDA_TITLE_BUFFERS_MB` | `512` | The most memory, in MiB, of buffers made over the title's own memory for vertex and index views that name it. | | `LEONIDA_TITLE_BUFFER_COVERAGE` | on | Such a view counts as covered only when a known buffer spans all its bytes. `0` asks for the first byte only. | -| `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. | +| `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh: as before unchanged generations were skipped, and as before the pages reserved in the title's xmem reservations were passed over. | | `LEONIDA_STRICT_REPLAY` | unset | *Diagnostic.* `1` makes a draw or dispatch with an unresolvable resource fail its command list (`src/vulkan_replay.h`); by default it is dropped and logged. | | `LEONIDA_VOLUME_MIPS` | on | The XG layout of a 3D texture with mips or a block format is computed (`shims/xg_xs_layout.h`). `0` refuses it. | | `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`). **Since RT-BOOT-COMBINED `0` also needs `LEONIDA_TITLE_WATCHDOG_KICK`**: the watchdog's addresses are no longer built in. With `0` and no `LEONIDA_TITLE_WATCHDOG_KICK`, the loader says once that the watchdog stays armed. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 37d1d007ee..f342453e7b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -323,7 +323,8 @@ void copy_run(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, boo // - pages this tracker made read-only weren't written: skipped; // - other readable pages (read-only or copy-on-write pages of the title's own, pages another tracker protected) // can't be watched: copied every time, as before; -// - pages not committed, or not readable, are zero in the copies (written once); +// - pages not committed, or not readable, are zero in the copies (written once); one that is reserved in the +// title's xmem reservations (title_reservations) is not asked about again until the journal names it; // - pages xmem reports mapped at another address too (title_page_watch.h): a write through the other address // doesn't fault here, so their 64 KiB blocks are guarded at every address by the geometry watch's cells // (update_aliased) and copied when a cell's version moved. Without the other addresses (no xmem), or while a @@ -527,6 +528,7 @@ class ShadowPages { zeroed_.clear(); copy_bytes_ = {}; std::uint64_t queries = 0; + const std::uint64_t reservations = leonida::title_reservations::generation(); // LEONIDA_SHADOW_FULL_WALK=1 queries every page at every refresh, as before the generation skip. static const bool always_full_walk = [] { char value[8] = {}; @@ -550,6 +552,11 @@ class ShadowPages { full_walk = true; refresh_walked_all_ = full_walk; refresh_protects_ = alias_arms_; + if (reservations != reservation_generation_) { // one released since: its pages are asked about again + reservation_generation_ = reservations; + for (std::uint8_t& s : state_) + if ((s & (kZero | kHot)) == kZero) s &= std::uint8_t(~kClean); + } if (pinned_) { for (std::uint8_t& s : state_) s &= ~kPinned; pinned_ = false; @@ -577,9 +584,15 @@ class ShadowPages { // Wine (NtQueryVirtualMemory waits for Wine's virtual-memory lock, which the mapping threads hold), a // fifth of the submitting thread's time. So are aliased pages whose cells no write reached (aliased_clean): // a mapping, commitment or protection change over a cell moves its version too. + // A page reserved in the title's xmem reservations is passed over at every refresh (kZero | kClean): only + // xmem's and the title's memory calls change it, and the journal names each of them. After the story load + // the walk made 450-7,500 queries a refresh of such pages, one for each of the stream pools' unmapped + // 64 KiB slots, 1.5 us each when nothing else mapped memory and 15-70 us under that lock while the title's + // mapping threads were busy: most of a walk of 100-330 ms a submission (RTX 3090, Wine 11). const auto skip = [&](std::size_t i) { const std::uint8_t s = state_[i]; - return unchanged(s) || ((s & ~(kZero | kProtected)) == kAliased && aliased_clean(i)) || + return unchanged(s) || s == (kZero | kClean) || + ((s & ~(kZero | kProtected)) == kAliased && aliased_clean(i)) || (!copy_aliased_ && (s == kAliased || s == kZero || s == (kZero | kAliased))); }; if (!full_walk && skip(i0)) { @@ -604,20 +617,34 @@ class ShadowPages { break; } const bool streaming = (region.Protect & PAGE_WRITECOMBINE) != 0; + if (kind != Kind::zero) + for (std::size_t i = i0; i < i1; ++i) + if (state_[i] & kZero) state_[i] &= std::uint8_t(~kClean); // committed or mapped now switch (kind) { - case Kind::zero: + case Kind::zero: { + // Reserved, private, and inside the title's xmem reservations: passed over until the journal names it + // (see skip above). Aliased, pinned and write-watched pages are left out: a first touch through a + // physical page's other address is journaled for that address alone, and a pin or a write watch is + // the business of the passes before the walk. + const bool settled = region.State == MEM_RESERVE && region.Type == MEM_PRIVATE && + leonida::title_reservations::contains(at, next); for (std::size_t i = i0; i < i1; ++i) { - if (state_[i] & kZero) continue; - const auto [offset, bytes] = span_of(i, i + 1); - zero_targets(offset, bytes); - leonida::shadow_keep::forget(sums_.data(), first_, begin_ + offset, begin_ + offset + bytes); - if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset) - zeroed_.back().bytes += bytes; - else - zeroed_.push_back({offset, bytes, false}); - state_[i] = std::uint8_t(kZero | (state_[i] & (kAliased | kPinned | kWatched))); + if (!(state_[i] & kZero)) { + const auto [offset, bytes] = span_of(i, i + 1); + zero_targets(offset, bytes); + leonida::shadow_keep::forget(sums_.data(), first_, begin_ + offset, begin_ + offset + bytes); + if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset) + zeroed_.back().bytes += bytes; + else + zeroed_.push_back({offset, bytes, false}); + state_[i] = std::uint8_t(kZero | (state_[i] & (kAliased | kPinned | kWatched))); + } + const bool alone = (state_[i] & ~(kClean | kRequery)) == kZero; + state_[i] = settled && alone ? std::uint8_t(state_[i] | kClean) + : std::uint8_t(state_[i] & ~kClean); } break; + } case Kind::writable: case Kind::read_only: for (std::size_t i = i0; i < i1;) { @@ -934,7 +961,8 @@ class ShadowPages { kAliased = 4, // xmem maps its physical page at another address too kPinned = 8, // a kernel write into it may be in flight (leonida::kernel_writes) kWatched = 16, // in a write-watched reservation (leonida::title_write_watch) - kClean = 32, // hot, and not written since it was copied after an asking + kClean = 32, // hot, and not written since it was copied after an asking; on a zero page: reserved in + // the title's xmem reservations, passed over until the journal names it kHot = 64, // write-watched and asked about at every refresh, never guarded kRequery = 128, // its mapping, commitment or protection changed (title_memory_map): queried at the next walk }; @@ -1427,6 +1455,7 @@ class ShadowPages { Vector clean_; Vector rearm_; std::uint64_t alias_arms_ = 0; // arm() calls of the last update_aliased() + std::uint64_t reservation_generation_ = ~std::uint64_t(0); // the xmem reservations its zero pages were settled under std::uint64_t map_generation_ = ~std::uint64_t(0); bool pinned_ = false; // some page has kPinned Vector jobs_; // refresh() only, which DeviceState::shadow_mutex serializes diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index fca6f6f474..35ecc69fd6 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -906,11 +906,16 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON // the host is part way through changing. const FaultLockExclusive view_lock; if (!isolate_placeholder(address, size)) return nullptr; - if (window) + if (window) { replace_window(g_fault_windows, reinterpret_cast(address), size, host_prot, true); - else + leonida::title_reservations::add(reinterpret_cast(address), size); + } else { replaced = placeholder_api().virtual_alloc2(GetCurrentProcess(), address, size, host_type | MEM_RESERVE, host_prot, nullptr, 0); + // Ordinary memory now, which the title commits with VirtualAlloc: not a reservation of xmem's. + leonida::title_reservations::forget(reinterpret_cast(address), + reinterpret_cast(address) + size); + } } if (!window) return replaced; // A reserve-only replacement stays a placeholder: the physical pages are mapped into it. @@ -925,6 +930,7 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON { const FaultLockExclusive faults; replace_window(g_fault_windows, reinterpret_cast(result), size, host_prot, false); + leonida::title_reservations::add(reinterpret_cast(result), size); } // Diagnostic (temporary): the windows a fault can be inside. std::fprintf(stderr, "[rt] xmem: window reserve %p size %llu protect 0x%lx\n", result, @@ -936,6 +942,7 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON const FaultLockExclusive lock; forget_range(g_title_placeholders, base, base + size); // a release the table missed g_title_placeholders[base] = Window{size, host_prot}; + leonida::title_reservations::add(base, size); } std::fprintf(stderr, "[rt] xmem: placeholder reserve %p size %llu\n", result, static_cast(size)); @@ -1694,6 +1701,7 @@ bool install_physical_page_fault_handler() { placeholder_api(); leonida::host_heap::handle(); leonida::geometry_writes::state(); + leonida::title_reservations::state(); char flag[4]{}; g_pool_zero_pages = GetEnvironmentVariableA("LEONIDA_POOL_ZERO_PAGES", flag, sizeof(flag)) == 1 && flag[0] == '1'; return AddVectoredExceptionHandler(1, &physical_page_fault) != nullptr; @@ -2276,6 +2284,9 @@ BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) { } else { result = VirtualFree(address, size, free_type); } + // Every release, also of a reservation xmem's tables missed, before the journal names its pages: the host can + // reserve the space again for memory the shadows would otherwise take as settled. + if (result && releases && release_end > start) leonida::title_reservations::forget(start, release_end); // A release of size 0 frees the whole reservation, whose extent is not known here: a change anywhere. if (result && size) leonida::title_memory_map::changed(address, size); else if (result) leonida::title_memory_map::changed(); diff --git a/runtime/src/title_page_watch.h b/runtime/src/title_page_watch.h index 44a19cb1bf..3153c0d044 100644 --- a/runtime/src/title_page_watch.h +++ b/runtime/src/title_page_watch.h @@ -39,7 +39,9 @@ // faulting page. // // Successful title memory map changes also invalidate the shadows' cached protection state. The shadows' own -// protection changes stay local to their trackers. +// protection changes stay local to their trackers. A reserved page of the title's placeholders and physical-page +// windows (title_reservations, below) changes only through such a change, so a shadow doesn't ask about it again +// until one names it. // // The shadows themselves are brought up to date in one place, DeviceState::refresh_shadows in // d3d12_vulkan_device.cpp, which VulkanQueue::execute_now calls (VulkanContext::set_before_execute) before every @@ -720,6 +722,85 @@ std::uint64_t ask(std::uint64_t reader, const Runs& runs, Dirty&& dirty, Refused } // namespace leonida::title_write_watch +// 7. The title's xmem reservations (title_reservations): its placeholders and physical-page windows, from the +// reservation to its release. Nothing but xmem and the title's own memory calls changes their pages, and those +// record every change in title_memory_map (a placeholder refuses a plain commit, and the title doesn't commit +// inside a window with VirtualAlloc: see the windows in xmem.cpp). A shadow takes a page there that is reserved +// and not mapped as zero until the journal names it, instead of asking VirtualQuery at every submission: under +// Wine a query waits for the virtual-memory lock, and the world's thousands of 64 KiB placeholders made the +// queries most of a refresh. +namespace leonida::title_reservations { + +// Allocates from host_heap, as title_write_watch does: the D3D12 layer asks under a tracker's lock. +struct State { + std::shared_mutex mutex; // ranges + host_heap::map ranges; // base -> end; apart, never touching + std::atomic count{0}; // ranges.size(), read without the lock + std::atomic generation{1}; // moved whenever a range was released or dropped +}; + +inline State& state() { + static State s; + return s; +} + +// xmem: [base, base + size) was reserved as a placeholder or a physical-page window of the title's. Inside one range +// already, it is part of that reservation (a window replacing part of a placeholder). A range it only overlaps was +// released without xmem seeing it, and goes whole, as xmem's tables drop it: nothing outside the new reservation is +// known to be one of the title's any more. +inline void add(std::uintptr_t base, std::uintptr_t size) { + if (!size) return; + State& s = state(); + const std::uintptr_t end = base + size; + std::unique_lock lock(s.mutex); + auto it = s.ranges.upper_bound(base); + if (it != s.ranges.begin() && std::prev(it)->second > base) --it; + if (it != s.ranges.end() && it->first <= base && it->second >= end) return; // inside one range already + bool erased = false; + while (it != s.ranges.end() && it->first < end) { + it = s.ranges.erase(it); + erased = true; + } + s.ranges.emplace(base, end); + s.count.store(s.ranges.size(), std::memory_order_release); + if (erased) s.generation.fetch_add(1, std::memory_order_release); +} + +// xmem: [start, end) was released. +inline void forget(std::uintptr_t start, std::uintptr_t end) { + State& s = state(); + if (start >= end || !s.count.load(std::memory_order_acquire)) return; + std::unique_lock lock(s.mutex); + auto it = s.ranges.lower_bound(start); + if (it != s.ranges.begin() && std::prev(it)->second > start) --it; + bool erased = false; + while (it != s.ranges.end() && it->first < end) { + const std::uintptr_t base = it->first, until = it->second; + it = s.ranges.erase(it); + erased = true; + if (base < start) s.ranges.emplace(base, start); + if (until > end) it = s.ranges.emplace(end, until).first; + } + if (!erased) return; + s.count.store(s.ranges.size(), std::memory_order_release); + s.generation.fetch_add(1, std::memory_order_release); +} + +// Moved whenever a reservation was released: what a shadow keeps of the reserved pages starts again. (A reservation +// made covers pages no shadow had settled: they were in no range until then, or in one released since.) +inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); } + +// Whether [begin, end) is inside one of the title's xmem reservations. +inline bool contains(std::uintptr_t begin, std::uintptr_t end) { + State& s = state(); + if (!s.count.load(std::memory_order_acquire)) return false; + std::shared_lock lock(s.mutex); + auto it = s.ranges.upper_bound(begin); + return it != s.ranges.begin() && (--it)->second >= end; +} + +} // namespace leonida::title_reservations + namespace leonida::kernel_writes { // The layer's side: makes every watched page in [begin, end) writable. Set once the first shadow exists. diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 69c3a6607a..4e2ef827dd 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -870,6 +870,62 @@ int check_commit_changes(ID3D12Device* device) { return failures; } +// A reserved range that xmem registered as one of the title's reservations (leonida::title_reservations: what +// XMemVirtualAlloc makes of a physical-page window), with a shadow over it. Its pages are zero in the copies, and a +// refresh stops asking about them. A page the title commits there, which its VirtualAlloc shim journals, arrives at +// the next submission, and so does its decommit. A range xmem lets go is asked about again, as any reserved page is. +int check_reserved_pages(ID3D12Device* device) { + const char* who = "vulkan slot-133 reserved pages"; + constexpr SIZE_T size = 4 * 0x10000; + auto* pages = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(pages != nullptr); + const auto base = reinterpret_cast(pages); + leonida::title_reservations::add(base, size); + int failures = 0; + { + Ref buffer; + buffer.p = place_shadow(device, pages, size); + EXPECT(buffer.p != nullptr); + GpuReader reader; + if (reader.init(device, size)) return 1; + std::vector want(size, 0), got; + wchar_t flag[2]{}; + const bool full_walk = GetEnvironmentVariableW(L"LEONIDA_SHADOW_FULL_WALK", flag, 2) == 1 && flag[0] == L'1'; + // Two submissions: the first asks about the range, the next one only on a full walk. + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(first_difference(got, want) == -1); + EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == (full_walk ? 1u : 0u)); + // Committed and written. + std::uint8_t* later = pages + 2 * 0x10000; + EXPECT(VirtualAlloc(later, 0x1000, MEM_COMMIT, PAGE_READWRITE) == later); + leonida::title_memory_map::changed(); // as the title's VirtualAlloc shim does + for (UINT64 i = 0; i < 0x1000; ++i) want[2 * 0x10000 + i] = later[i] = pattern_byte(i, 43); + EXPECT(reader.read(buffer.p, got) == 0); + long long wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: page committed in a reservation: first wrong byte at %lld\n", who, wrong); + EXPECT(wrong == -1); + // Decommitted: zeros again, the rest as it was. + EXPECT(VirtualFree(later, 0x1000, MEM_DECOMMIT)); + leonida::title_memory_map::changed(); // as the title's VirtualFree shim does + std::fill(want.begin() + 2 * 0x10000, want.begin() + 2 * 0x10000 + 0x1000, std::uint8_t(0)); + EXPECT(reader.read(buffer.p, got) == 0); + wrong = first_difference(got, want); + if (wrong >= 0) std::fprintf(stderr, "%s: page decommitted in a reservation: first wrong byte at %lld\n", who, wrong); + EXPECT(wrong == -1); + // Let go by xmem: asked about again. + leonida::title_reservations::forget(base, base + size); + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(reader.read(buffer.p, got) == 0); + EXPECT(rt::d3d12::title_shadow_refresh_queries(device) >= 1u); + EXPECT(first_difference(got, want) == -1); + } + std::printf("%s: the reserved pages of a registered reservation are not asked about again; a committed one arrives\n", + who); + VirtualFree(pages, 0, MEM_RELEASE); + return failures; +} + // The negative control, and the case it stands for. One pagefile-backed section (SEC_RESERVE, half committed, as xmem // backs physical pages) is mapped at two addresses, A and B; the shadow is placed at A. A write through B doesn't fault // at A, so without a mark the page it changed is not copied: the GPU still reads the old bytes. That shows the test @@ -2254,6 +2310,7 @@ int check_written_pages_all(ID3D12Device* device) { } } failures += check_commit_changes(device); + failures += check_reserved_pages(device); failures += check_concurrent_writes(device, false); if (leonida::title_write_watch::enabled()) failures += check_concurrent_writes(device, true); failures += check_aliased_write(device);