From 27c1673761cf479cf3e822f1353f20ad757bd2a3 Mon Sep 17 00:00:00 2001 From: Tyrannys <80750971+Tyrannys@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:34:01 -0600 Subject: [PATCH] d3d12: every title write-back range on one guarded page goes back (RT-TITLE-WRITEBACK-SAME-PAGE-RANGES) 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 --- runtime/CMakeLists.txt | 4 + runtime/shims/d3d12_vulkan_device.cpp | 132 +++++++++++++++++--------- runtime/test/d3d12_title_va_test.cpp | 102 +++++++++++++++++++- 3 files changed, 192 insertions(+), 46 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 46ea96aaf7..7e5f6a27fc 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3996,6 +3996,10 @@ if(TARGET Vulkan::Headers) # handler asks the tracker whose copy faulted too, which must not take its lock again on that thread (#2418). add_test(NAME d3d12_title_window_write_back_fault COMMAND d3d12_title_va_test --window-writeback-fault) set_tests_properties(d3d12_title_window_write_back_fault PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # Disjoint write-back ranges on one guarded page: every one of them reaches the page, not only the first + # (RT-TITLE-WRITEBACK-SAME-PAGE-RANGES). + add_test(NAME d3d12_title_window_write_back_ranges COMMAND d3d12_title_va_test --window-writeback-ranges) + set_tests_properties(d3d12_title_window_write_back_ranges PROPERTIES SKIP_RETURN_CODE 77) # The same return copy for a slot-133 buffer's shadow (the write-back of a compute result the title reads again). add_test(NAME d3d12_placed_write_back COMMAND d3d12_title_va_test --placed-writeback) set_tests_properties(d3d12_placed_write_back PROPERTIES SKIP_RETURN_CODE 77) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 031fa22e12..7cec9d39ab 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -404,9 +404,10 @@ class ShadowPages { ShadowPages(const ShadowPages&) = delete; ShadowPages& operator=(const ShadowPages&) = delete; - // What the GPU writes into the copies of [from, to) goes back to the title's pages. Returns the bytes written. - // Called before the next refresh, so a page the title writes again is copied forward over the result, as on a GPU - // that shares the memory. + // What the GPU writes into the copies of the ranges [first, second) goes back to the title's pages: `count` of + // them, sorted by start. Returns the bytes written, and in `reached` (when given) how many of the ranges wrote + // any. Called before the next refresh, so a page the title writes again is copied forward over the result, as on + // a GPU that shares the memory. // // Only the bytes a copy holds differently from the title's page go back, and only on a page known unchanged since // it was copied: guarded (read-only since that copy), or write-watched and found unwritten by an asking made here. @@ -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* 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 held_pages((hi - lo) / kPage); AcquireSRWLockExclusive(&lock_); // The copies below can fault on a page another guard (the geometry watch, another view's shadow) keeps // read-only. The fault handler asks this tracker too (reopen), and must not take lock_ again on this thread: @@ -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(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(c), copy, e - c) != 0) { + if (!opened) { + reopen_locked(at, at + pages * kPage); + opened = true; + } + std::memcpy(reinterpret_cast(c), copy, e - c); + written += e - c; } - std::memcpy(reinterpret_cast(c), copy, e - c); - written += e - c; + c = e; } - c = e; } } + at += pages * kPage; } - at += pages * kPage; + if (reached && written != range_written) ++*reached; } writer_.store(0, std::memory_order_relaxed); ReleaseSRWLockExclusive(&lock_); @@ -3524,14 +3561,21 @@ struct DeviceState { 1); } if (finished.empty()) return; + // Each shadow takes all the ranges over it in one call, in address order (batches can overlap), and decides + // which of its pages are held once for all of them (ShadowPages::write_back). + std::sort(finished.begin(), finished.end()); std::uint64_t written = 0, ranges = 0; - for (const auto& [begin, end] : finished) - for (const ShadowPagesPtr& s : shadows) - if (end > s->first() && begin < s->last()) { - const std::uint64_t bytes = s->write_back(begin, end); - written += bytes; - ranges += bytes != 0; - } + std::vector> over; + for (const ShadowPagesPtr& s : shadows) { + over.clear(); + for (const auto& [begin, end] : finished) + if (end > s->first() && begin < s->last()) + over.push_back({static_cast(begin), static_cast(end)}); + if (over.empty()) continue; + std::size_t reached = 0; + written += s->write_back(over.data(), over.size(), &reached); + ranges += reached; + } title_write_back_total += written; if (!written) return; if (++title_write_back_calls <= 4 || !(title_write_back_calls & (title_write_back_calls - 1))) diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 38a4a675c3..cd283f11bf 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -525,13 +525,13 @@ struct WriteBack { }; // One submission that dispatches through a root UAV at `va` and waits for it. False on a failed call. -int submit_write(WriteBack& s, std::uint64_t va) { +int submit_write(WriteBack& s, std::uint64_t va, std::uint32_t base = 0) { EXPECT(s.allocator->Reset() == S_OK); EXPECT(s.list->Reset(s.allocator, s.c->pso) == S_OK); ID3D12DescriptorHeap* heaps[] = {s.heap}; s.list->SetDescriptorHeaps(1, heaps); s.list->SetComputeRootSignature(s.c->root); - s.list->SetComputeRoot32BitConstant(0, 0, 0); + s.list->SetComputeRoot32BitConstant(0, base, 0); s.list->SetComputeRoot32BitConstant(0, 1, 1); // the step: a word the shader writes s.list->SetComputeRootUnorderedAccessView(1, va); s.list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{s.gpu}); @@ -700,6 +700,94 @@ int check_window_write_back(Context& c, bool geometry) { return 0; } +// Several disjoint write-back ranges on one guarded page (RT-TITLE-WRITEBACK-SAME-PAGE-RANGES, found by 73N1X in +// #1608). The ranges of a submission go back one by one; the first that differs used to reopen the page, and every +// later range on it then found the page neither guarded nor clean and was dropped as written by the title, though +// nothing but the write-back itself had written there. +// 1. a submission makes the ring's window, and a second one copies its words back and guards the pages; +// 2. a submission writes new words into the window through its arena address (nothing noted for it), while 16 +// four-byte ranges 16 bytes apart on the first page are noted as reached; +// 3. the next submission's refresh copies those ranges back: every one of them must reach the page, and the words +// between them must keep the title's. +int check_window_write_back_ranges(Context& c, bool geometry) { + if (geometry) { + std::fprintf(stderr, "SKIP: the geometry copy backs the ring, not a window\n"); + return 77; + } + constexpr UINT64 ring_bytes = 64 * 1024; + constexpr UINT kRanges = 16, kSpacing = 4; // in words: ranges at words 0, 4, 8, ..., 60 + auto* ring = static_cast( + VirtualAlloc(nullptr, ring_bytes, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(ring); + const auto ring_va = reinterpret_cast(ring); + for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0; + auto& aliases = leonida::title_va_aliases(); + aliases.add_title_memory(ring_va, ring_bytes); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref out, scratch; + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&scratch.p)))); + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, + IID_PPV_ARGS(&list.p)))); + EXPECT(list->Close() == S_OK); + WriteBack s{&c, allocator.p, list.p, out.p, heap.p, + reinterpret_cast(slot(heap.p, 10))(heap.p)}; + + // 1. The window, and its words back in the pages; then a submission that does not reach the ring guards them. + EXPECT(submit_write(s, ring_va) == 0); + const std::uint64_t window = aliases.shader_va(ring_va); + EXPECT(window != ring_va && window != 0); + EXPECT(submit_write(s, scratch->GetGPUVirtualAddress()) == 0); + EXPECT(submit_write(s, scratch->GetGPUVirtualAddress()) == 0); + const std::vector before(ring, ring + kElements); + UINT nonzero = 0; + for (std::uint32_t w : before) nonzero += w != 0; + EXPECT(nonzero > 0); // the first submission's words came back + MEMORY_BASIC_INFORMATION region{}; + EXPECT(VirtualQuery(ring, ®ion, sizeof(region)) && (region.Protect & 0xff) == PAGE_READONLY); + + // 2. New words in the window, written through its arena address (not a title address: nothing is noted), and the + // ranges the copy back should cover, noted for the same submission. + constexpr std::uint32_t kBase = 0x5A000000u; + for (UINT k = 0; k < kRanges; ++k) aliases.note_reached(ring_va + k * kSpacing * 4, 4); + EXPECT(submit_write(s, window, kBase) == 0); + for (UINT i = 0; i < kElements; ++i) EXPECT(ring[i] == before[i]); // not back before the next submission + + // 3. The next refresh copies the ranges back. + EXPECT(submit_write(s, scratch->GetGPUVirtualAddress()) == 0); + UINT reached = 0, kept = 0, wrong = 0; + for (UINT i = 0; i < kElements; ++i) { + if (i % kSpacing == 0) + reached += ring[i] != before[i]; + else + kept += ring[i] == before[i]; + wrong += ring[i] != before[i] && ring[i] != before[i] + kBase; + } + std::printf("write back ranges: %u/%u four-byte ranges on one guarded page reached it, %u/%u words between them " + "kept the title's, %u words neither\n", + reached, kRanges, kept, kElements - kRanges, wrong); + EXPECT(reached == kRanges); + EXPECT(kept == kElements - kRanges); + EXPECT(wrong == 0); + + aliases.remove_title_memory(ring_va); + VirtualFree(ring, 0, MEM_RELEASE); + return 0; +} + // A write-back whose copy faults (#2418). The copy runs under its tracker's lock and can land on a page another guard // keeps read-only: here a hot page (write-watched, so this tracker does not guard it) that a geometry watch cell has // made read-only, as a geometry view over the same pages does in the title. The copy faults, the handler reopens the @@ -1346,6 +1434,7 @@ int main(int argc, char** argv) { const bool window_write_back = argc == 2 && std::strcmp(argv[1], "--window-writeback") == 0; const bool window_write_back_fault = argc == 2 && std::strcmp(argv[1], "--window-writeback-fault") == 0; const bool placed_write_back = argc == 2 && std::strcmp(argv[1], "--placed-writeback") == 0; + const bool window_write_back_ranges = argc == 2 && std::strcmp(argv[1], "--window-writeback-ranges") == 0; const bool keep_refill = argc == 2 && std::strcmp(argv[1], "--shadow-keep-refill") == 0; if (window_cap) { const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); @@ -1488,6 +1577,15 @@ int main(int argc, char** argv) { "read-only returned, and the GPU's words reached the title's pages\n"); return 0; } + if (window_write_back_ranges) { + if (const int result = check_window_write_back_ranges(c, geometry)) return result; + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title window write back ranges: every range on one guarded page reached it\n"); + return 0; + } if (window_write_back) { if (check_window_write_back(c, geometry)) return 1; if (d.validation_errors()) {