diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 45d4b4be47..f5009730ea 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1722,7 +1722,11 @@ The copies: write watch first (the refresh's own asking comes after it, so a hot page's last answer is a submission old), passes over pages whose mapping changed, that a kernel write may be filling or that xmem maps at another address too, and writes only the 256-byte pieces where the copy differs from the title's bytes: a read-only view writes nothing and - its pages stay guarded. Up to 8,192 ranges and 64 MiB a submission (a V# has no read/write bit, so every view + its pages stay guarded. The copy runs under the tracker's lock and can still fault on a page another guard keeps + read-only (the geometry watch, another view's shadow): the fault handler asks every tracker over the address, this + one included, and on the thread whose copy faulted it does not take that lock again (an SRW lock is not + recursive; on 621.40 the title's submitting thread hung there for good, the main loop frozen with no device loss). + Up to 8,192 ranges and 64 MiB a submission (a V# has no read/write bit, so every view reached is compared; past the caps the ranges are left behind, logged once). `LEONIDA_TITLE_WRITEBACK=0` turns it off. A batch is fenced: it is kept with the ticket of the submission that will use it and copied back only when the context reports that ticket retired, so a range another submission is still writing is never read half done. A queue held deep (console ordering) can leave batches diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index f8edc3508e..a7b7907b64 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3936,6 +3936,10 @@ if(TARGET Vulkan::Headers) # the title's pages at the next refresh, and the title's own newer words still win (#1537, WRITE_INVALID). add_test(NAME d3d12_title_window_write_back COMMAND d3d12_title_va_test --window-writeback) set_tests_properties(d3d12_title_window_write_back PROPERTIES SKIP_RETURN_CODE 77) + # A write-back copy that faults on a page another guard (a geometry watch cell) keeps read-only: the fault + # 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) # 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 f2fa3a45c2..1c7e60d295 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -416,6 +416,10 @@ class ShadowPages { from = std::max(from, first_), to = std::min(to, last_); if (from >= to) return 0; 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: + // SRW locks are not recursive, and a title thread hung there for good (621.40, a submission's write-back). + writer_.store(GetCurrentThreadId(), std::memory_order_relaxed); // What changed since the last refresh, as refresh() learns it: mappings (the journal), kernel-write pins, and // the write watch. A journal that no longer reaches back makes nothing known: nothing goes back. std::uint64_t map_generation = leonida::title_memory_map::generation(); @@ -428,6 +432,7 @@ class ShadowPages { state_[i] |= kRequery; }); if (!known) { + writer_.store(0, std::memory_order_relaxed); ReleaseSRWLockExclusive(&lock_); return 0; } @@ -474,6 +479,7 @@ class ShadowPages { } at += pages * kPage; } + writer_.store(0, std::memory_order_relaxed); ReleaseSRWLockExclusive(&lock_); return written; } @@ -870,14 +876,15 @@ class ShadowPages { from = std::max(from & ~(kPage - 1), first_); to = std::min((to + kPage - 1) & ~(kPage - 1), last_); if (from >= to) return; - AcquireSRWLockExclusive(&lock_); + const bool held = writer_.load(std::memory_order_relaxed) == GetCurrentThreadId(); // see write_back + if (!held) AcquireSRWLockExclusive(&lock_); bool guarded = false; for (std::size_t i = (from - first_) / kPage, i1 = (to - first_) / kPage; i < i1; ++i) { state_[i] &= ~kClean; guarded |= (state_[i] & kProtected) != 0; } if (guarded) reopen_locked(from, to); - ReleaseSRWLockExclusive(&lock_); + if (!held) ReleaseSRWLockExclusive(&lock_); } // From the fault handler: a write to `address`, inside this range, faulted. True when the write can be retried: @@ -888,7 +895,9 @@ class ShadowPages { // write it should have retried, which ended the process (seen natively on Windows 11: threads writing one page // across a submission). bool reopen(std::uintptr_t address) { - AcquireSRWLockExclusive(&lock_); + // On the thread whose write_back faulted, lock_ is held already (see write_back). + const bool held = writer_.load(std::memory_order_relaxed) == GetCurrentThreadId(); + if (!held) AcquireSRWLockExclusive(&lock_); const std::size_t index = (address - first_) / kPage; bool retry = (state_[index] & kProtected) != 0; if (retry) { @@ -914,7 +923,7 @@ class ShadowPages { retry = VirtualQuery(reinterpret_cast(address), ®ion, sizeof(region)) && classify(region) == Kind::writable; } - ReleaseSRWLockExclusive(&lock_); + if (!held) ReleaseSRWLockExclusive(&lock_); return retry; } @@ -1404,6 +1413,7 @@ class ShadowPages { std::uintptr_t begin_ = 0, end_ = 0; // the targets' bytes: the first start and the furthest end std::uintptr_t first_ = 0, last_ = 0; // the pages covered SRWLOCK lock_ = SRWLOCK_INIT; // state_, cover_, the targets, and the protection of the pages + std::atomic writer_{0}; // the thread in write_back, which holds lock_ while it copies into the title Vector state_; // per 4 KiB page Vector cover_; // per 4 KiB page: the targets that read it Vector targets_; // by start diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 90eddc66a6..38a4a675c3 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -700,6 +700,122 @@ int check_window_write_back(Context& c, bool geometry) { 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 +// cell and asks every tracker over the address, the writing one too; that one used to take its own (non-recursive) +// lock again on the same thread and the submission never returned. A watchdog ends the process if it does not. +// 1. the ring is write-watched and the first submission makes its window: the tracker guards the pages; +// 2. the title writes the first page outside the words the shader writes: the fault makes its block hot (writable, +// asked about rather than guarded), and the next submission drops the GPU's words there (the page was written) +// and copies the page forward again; +// 3. a geometry cell over the ring's first 64 KiB makes the hot page read-only, unknown to the tracker; +// 4. the next submission's write-back faults on that page, and must return with the GPU's words in the pages. +int check_window_write_back_fault(Context& c) { + if (!leonida::title_write_watch::enabled()) { + std::fprintf(stderr, "SKIP: write watching is off (LEONIDA_WRITE_WATCH=0, Wine, or no host heap)\n"); + return 77; + } + constexpr UINT64 ring_bytes = 256 * 1024; + auto* ring = static_cast( + VirtualAlloc(nullptr, ring_bytes, MEM_TOP_DOWN | MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE)); + EXPECT(ring && VirtualAlloc(ring, ring_bytes, MEM_COMMIT, PAGE_READWRITE) == ring); + const auto ring_va = reinterpret_cast(ring); + EXPECT((ring_va & (leonida::geometry_writes::tile_size - 1)) == 0); // a reservation starts on 64 KiB + leonida::title_write_watch::add(ring_va, ring_bytes); // as xmem records it + auto& aliases = leonida::title_va_aliases(); + aliases.add_title_memory(ring_va, ring_bytes); + const auto protection = [](const void* p) { + MEMORY_BASIC_INFORMATION m{}; + return VirtualQuery(p, &m, sizeof m) ? m.Protect & 0xff : 0; + }; + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref out; + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.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)}; + + // Step 1. + EXPECT(submit_write(s, ring_va) == 0); + EXPECT(aliases.shader_va(ring_va) != ring_va); // a window was made for the title's pages + EXPECT(ring[0] == 0); // the copy took the write + const DWORD guarded = protection(ring); + EXPECT(guarded == PAGE_READONLY); // guarded until written + + // Step 2: word 1000 is on the first page, past the 64 words the shader writes. + const std::uint64_t faults_before = rt::d3d12::title_shadow_watch(c.inner).faults; + ring[1000] = 0x5EED0001u; + const std::uint64_t title_faults = rt::d3d12::title_shadow_watch(c.inner).faults - faults_before; + EXPECT(title_faults == 1); + EXPECT(rt::d3d12::title_shadow_watch(c.inner).watched_bytes > 0); // the window's pages are write-watched + EXPECT(submit_write(s, ring_va) == 0); + UINT dropped = 0; + for (UINT i = 0; i < kElements; ++i) dropped += ring[i] == 0; + EXPECT(dropped == kElements); // the title wrote that page since it was copied: the GPU's words were not taken + const DWORD hot = protection(ring); + EXPECT(hot == PAGE_READWRITE); // asked about, not guarded + EXPECT(rt::d3d12::title_shadow_watch(c.inner).hot_bytes > 0); + + // Step 3: what a geometry view over these pages arms (GeometryViews), standing in for the other guard. + const auto tile = std::uintptr_t(ring_va); + leonida::geometry_writes::Cell* cell = leonida::geometry_writes::acquire(tile); + EXPECT(cell && leonida::geometry_writes::arm(tile, *cell)); + const DWORD armed = protection(ring); + EXPECT(armed == PAGE_READONLY); + + // Step 4. + HANDLE done = CreateEventW(nullptr, TRUE, FALSE, nullptr); + EXPECT(done); + HANDLE watchdog = CreateThread( + nullptr, 0, + [](void* event) -> DWORD { + if (WaitForSingleObject(static_cast(event), 20000) == WAIT_OBJECT_0) return 0; + std::fprintf(stderr, "FAIL: the submission whose write-back faulted on a page another guard keeps " + "read-only did not return in 20 s (the fault handler waits on the tracker's lock its " + "own thread holds)\n"); + std::fflush(stderr); + TerminateProcess(GetCurrentProcess(), 3); + return 1; + }, + done, 0, nullptr); + EXPECT(watchdog); + const int submitted = submit_write(s, ring_va); + SetEvent(done); + WaitForSingleObject(watchdog, INFINITE); + CloseHandle(watchdog); + CloseHandle(done); + EXPECT(submitted == 0); + UINT nonzero = 0; + for (UINT i = 0; i < kElements; ++i) nonzero += ring[i] != 0; + std::printf("write back fault: protection 0x%lx guarded, 0x%lx hot after %llu title fault, 0x%lx under the " + "geometry cell; the faulting write-back returned and %u of %u words the shader wrote are in the " + "title's pages, the title's own word %s\n", + guarded, hot, static_cast(title_faults), armed, nonzero, kElements, + ring[1000] == 0x5EED0001u ? "kept" : "lost"); + EXPECT(nonzero > 0); + EXPECT(ring[1000] == 0x5EED0001u); + + leonida::geometry_writes::release(tile); + aliases.remove_title_memory(ring_va); + leonida::title_write_watch::remove(ring_va); + VirtualFree(ring, 0, MEM_RELEASE); + return 0; +} + void remove_test_pair(std::uintptr_t gpu, std::uintptr_t cpu) { auto& state = leonida::title_gpu_views::state(); std::unique_lock lock(state.mutex); @@ -1228,6 +1344,7 @@ int main(int argc, char** argv) { const bool rebind = api_copy || mirror_off || second_device || (argc == 2 && std::strcmp(argv[1], "--rebound-tables") == 0); const bool window_cap = argc == 2 && std::strcmp(argv[1], "--window-cap") == 0; 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 keep_refill = argc == 2 && std::strcmp(argv[1], "--shadow-keep-refill") == 0; if (window_cap) { @@ -1361,6 +1478,16 @@ int main(int argc, char** argv) { } return 0; } + if (window_write_back_fault) { + if (const int result = check_window_write_back_fault(c)) return result; + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title window write back fault: a write-back copy that faulted on a page another guard keeps " + "read-only returned, and the GPU's words reached the title's pages\n"); + return 0; + } if (window_write_back) { if (check_window_write_back(c, geometry)) return 1; if (d.validation_errors()) {