diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index c2e36319e2..044c444ecc 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1680,6 +1680,18 @@ The copies: cannot fit between the title's address reservations can use a separate mapped buffer. The buffer's device address must fit as a positive 47-bit offset from the arena base. The same window cap and dirty-page refresh apply. `LEONIDA_STREAM_BUFFER_WINDOWS=0` requires the window to fit in the arena. +- **What the GPU wrote goes back.** The same return copy serves slot-133 shadows (a buffer the driver would not + import, a compute result the title reads again): the ranges are recorded through the alias of the buffer's pages and + the tracker there carries them back. `d3d12_placed_write_back` covers it. A copy is a read-side mirror, so a UAV or a raw write into a window would land in + the copy and the title would never see it ([#1537](https://github.com/ubiquitarianism/leonida/issues/1537), the + `WRITE_INVALID` stop at the world start). Every title range a submission's bindings reach is kept, and the next + refresh copies those ranges from the copy to the title's pages *before* it copies the pages forward, so a page the + title itself wrote in between keeps the title's newer bytes and its GPU result is dropped. Up to 8,192 ranges and + 64 MiB a submission (a V# has no read/write bit, so a read-only view costs a copy too; 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 + waiting: past 64 of them the oldest go back without their ticket, logged once. - A **window that is refused** (the budget is spent, the arena is full, or the pages are not committed yet) is backed by a persistent geometry copy of exactly the requested range (`LEONIDA_GEOMETRY_MB`) instead; when no copy can be made either, the view is written with **no base and no records** — loads return 0 and stores are dropped. A raw diff --git a/docs/linux_proton.md b/docs/linux_proton.md index de4760d70a..525fa8825a 100644 --- a/docs/linux_proton.md +++ b/docs/linux_proton.md @@ -150,6 +150,10 @@ Each item was a stop on at least one of the machines. Tests named in the pull re ## Where it stops +- **Writes into title memory.** A window is a read-side copy, so a UAV or raw write used to stop at the copy: the + missing return copy is the `WRITE_INVALID` device loss of #1537. The layer now copies the reached ranges back to + the title's pages at the next refresh, before the forward copy, and the title's own newer words win. Not yet + measured on a GPU with the world phase in front of it. - **Streamed memory that reaches its destination late or not at all.** The title calls queue slot 31 (`CopyPageMappingsBatchX`) about 300 times per boot. With #968 this branch maps each batch's pool pages at the destination and at the paired CPU view the layer reads (`docs/d3d12_vulkan.md`, section 4.9), so most streamed diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 66af48c7da..4d89d9b542 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3647,6 +3647,13 @@ if(TARGET Vulkan::Headers) # is written zero-size, and a dispatch through it reads zeros. add_test(NAME d3d12_title_window_cap COMMAND d3d12_title_va_test --window-cap) set_tests_properties(d3d12_title_window_cap PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_TITLE_WINDOWS_MB=0") + # A window is a read-side mirror refreshed before every submission: what a shader writes into it goes back to + # 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) + # 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) add_test(NAME d3d12_api_descriptor_copy COMMAND d3d12_title_va_test --api-descriptor-copy) set_tests_properties(d3d12_api_descriptor_copy PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") add_test(NAME d3d12_api_descriptor_copy_off COMMAND d3d12_title_va_test --api-descriptor-copy-off) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index c5f72eb272..72bf02bace 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -349,6 +349,43 @@ 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: the pages are made writable + // first (the tracker guards them) and every target is copied from its shadow. 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. + 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; + AcquireSRWLockExclusive(&lock_); + // 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. A guarded page (read-only since that copy) or one asked about and + // found unchanged takes the GPU's. + const auto held = [&](std::size_t i) { + const std::uint8_t s = state_[i]; + return (s & kZero) || (!(s & kProtected) && !(s & kClean)); + }; + 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); + reopen_locked(at, at + pages * kPage); + 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; + std::memcpy(reinterpret_cast(x), t.shadow + (x - t.begin), y - x); + written += y - x; + } + } + at += pages * kPage; + } + ReleaseSRWLockExclusive(&lock_); + return written; + } + // The bytes of all targets, and how many there are. std::size_t size() const { return target_bytes_; } std::size_t targets() const { return targets_.size(); } @@ -2125,6 +2162,7 @@ struct DeviceState { if (!pages) return; const leonida::submit_phases::Scope timed(leonida::submit_phases::shadows); std::lock_guard lock(shadow_mutex); + write_back_titles(); // what the last submission wrote in the copies, before the forward copy below if (shadows.empty()) return; const auto start = clock::now(); // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses, which no guard @@ -2230,6 +2268,21 @@ struct DeviceState { std::atomic title_window_count{0}; // title_windows.size(), read without the mutex std::uint64_t title_window_bytes = 0; std::uint64_t title_window_cap = 64ull << 20; + // What the GPU wrote into a copy of the title's memory goes back to the title's pages: the ranges reached since + // the last submission (title_va_alias.h note_reached), copied back at the next refresh before the forward copy. + // A window is a read-side mirror, so without this a UAV or a raw write lands in the copy and the title never sees + // it (#1537, the WRITE_INVALID stop at the world start). + std::mutex title_write_back_mutex; // its own: taken under shadow_mutex, never the other way round + std::map title_write_back; // start -> end, of the submission about to run + std::deque>> title_write_back_pending; // by ticket + std::uint64_t title_write_back_refused = 0; // ranges past the caps, logged once + std::uint64_t title_write_back_bytes = 0; // queued for this submission + std::uint64_t title_write_back_total = 0; // copied back, all submissions + std::uint64_t title_write_back_calls = 0; // log line count + std::uint64_t title_write_back_unfenced = 0; + static constexpr std::size_t kTitleWriteBackBatches = 64; // pending batches before the oldest goes back unfenced + static constexpr std::size_t kTitleWriteBackRanges = 8192; // ranges kept per submission + static constexpr std::uint64_t kTitleWriteBackBytes = 64ull << 20; // bytes copied back per submission // The stream pools' mappings (title_gpu_views): one per readable run of a pool, kept for the device's life. struct PoolSpan { std::uint64_t source; // the readable side of the pair the copy is made from @@ -2354,6 +2407,93 @@ struct DeviceState { return offset; } + // A binding of the title's memory reached for the coming submission: keep its range for the copy back after it. + // Over-inclusive on purpose (a read-only view costs a copy, a write is never missed: a V# has no read/write bit). + void note_title_write(std::uint64_t va, std::uint64_t bytes) { + static const bool on = [] { + char value[2] = {}; + std::size_t length = 0; + return getenv_s(&length, value, sizeof(value), "LEONIDA_TITLE_WRITEBACK") != 0 || value[0] != '0'; + }(); + if (!on || !va || !bytes) return; + std::uint64_t lo = 0, hi = 0; + if (!leonida::title_va_aliases().title_memory(va, lo, hi) || va >= hi) return; + const std::uint64_t end = va + std::min(bytes, hi - va); + std::lock_guard lock(title_write_back_mutex); + auto it = title_write_back.lower_bound(va); + if (it != title_write_back.begin()) { + auto previous = std::prev(it); + if (previous->second >= va) { + if (previous->second < end) previous->second = end; + return; + } + } + if (it != title_write_back.end() && it->first <= end) { + it->second = std::max(it->second, end); + return; + } + if (title_write_back.size() >= kTitleWriteBackRanges || title_write_back_bytes >= kTitleWriteBackBytes) { + if (!title_write_back_refused++) + log_once("past LEONIDA_TITLE_WRITEBACK's caps: reached ranges are not copied back this submission; " + "ranges refused:", + 1); + return; + } + title_write_back_bytes += end - va; + title_write_back.emplace(va, end); + } + + // What the GPU wrote into those copies goes back to the title's pages, so a later read by the title or the next + // forward copy sees it. Only once the submission that wrote them has completed: a batch carries the ticket of the + // submission after it (a submission's commands are recorded before it exists), and is copied back when the + // context reports that ticket done. Runs at the start of a refresh, under shadow_mutex and before the forward + // copies, so a page the title wrote again is copied forward over the result. + void write_back_titles() { + if (!&context) return; + const std::uint64_t done = context->completed_retire_ticket(); + std::vector> finished; // one entry per range, collected under the lock + { + std::lock_guard lock(title_write_back_mutex); + if (!title_write_back.empty()) { + // The ranges of the submission about to execute, which is the next ticket. + title_write_back_pending.push_back({context->submitted_retire_ticket() + 1, + std::move(title_write_back)}); + title_write_back.clear(); + title_write_back_bytes = 0; + } + bool forced = false; + while (!title_write_back_pending.empty() && + (title_write_back_pending.front().first <= done || + title_write_back_pending.size() > kTitleWriteBackBatches)) { + forced = forced || title_write_back_pending.front().first > done; + for (const auto& [begin, end] : title_write_back_pending.front().second) + finished.push_back({begin, end}); + title_write_back_pending.pop_front(); + } + // A queue held deep (console ordering) can leave batches waiting: the oldest go back anyway, once each. + if (forced && !title_write_back_unfenced++) + log_once("more than 64 title write-back batches wait on their submissions: the oldest are copied " + "back without their ticket; batches:", + 1); + } + if (finished.empty()) return; + 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; + } + title_write_back_total += written; + if (!written) return; + if (++title_write_back_calls <= 4 || !(title_write_back_calls & (title_write_back_calls - 1))) + std::fprintf(stderr, "[rt] d3d12: %llu KiB of the GPU's writes in %llu reached range(s) went back to the " + "title's pages (%llu KiB so far)\n", + static_cast(written >> 10), static_cast(ranges), + static_cast(title_write_back_total >> 10)); + } + // A stream pool's address (a CPU view paired with a GPU-only alias). Rule B // first: the CPU view is where the host reads the frames, so that is what the copy is made from; the GPU-only // pages are the same frames through the title's queue slot 31 and are read only when the CPU view is not @@ -10946,6 +11086,9 @@ class Device final [](void* device, std::uint64_t table, std::uint32_t descriptors) { static_cast(device)->scan_title_table(table, descriptors); }); + leonida::title_va_aliases().set_noter([](void* device, std::uint64_t va, std::uint64_t bytes) { + static_cast(device)->note_title_write(va, bytes); + }); state_.image_memory = std::make_unique( [device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) { VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; @@ -14913,7 +15056,7 @@ class Device final // imported, or a shadow copied from them before every submission) and kept until the device goes, up to // LEONIDA_TITLE_BUFFERS_MB (512 by default). void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { - if (!state_.context) return; + if (!&context()) return; static const bool check_size = [] { wchar_t flag[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_BUFFER_COVERAGE", flag, 2) == 1 && flag[0] == L'0'); diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index b3de5ce706..0d44050bb9 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -42,6 +42,9 @@ class TitleVaAliases { // memory (an arena VA, a buffer of the layer's). using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors); + // Every binding resolved to a copy of the title's memory: [va, va + bytes) as they are reached at (the device keeps + // them for the copy back after the submission, see DeviceState::write_back_titles). + using Noter = void (*)(void* context, std::uint64_t va, std::uint64_t bytes); // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. @@ -147,6 +150,7 @@ class TitleVaAliases { std::uint64_t to = shader_va(va); if (to != va) { translated_[kind].fetch_add(1, std::memory_order_relaxed); + note_reached(va, bytes); return to; } Resolver resolver; @@ -158,6 +162,7 @@ class TitleVaAliases { } if (!resolver || !resolver(context, va, bytes, to)) return va; (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed); + if (to != va) note_reached(va, bytes); return to; } @@ -167,6 +172,18 @@ class TitleVaAliases { if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); } + // [va, va + bytes) is reached as a copy of the title's memory: the device keeps it for the copy back. + void note_reached(std::uint64_t va, std::uint64_t bytes) { + Noter noter; + void* context; + { + std::lock_guard lock(hook_mutex_); + noter = noter_; + context = hook_context_; + } + if (noter) noter(context, va, bytes); + } + // Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares // for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps). void scan_table(std::uint64_t table_va, std::uint32_t descriptors) { @@ -307,10 +324,16 @@ class TitleVaAliases { hook_context_ = nullptr; resolver_ = nullptr; scanner_ = nullptr; + noter_ = nullptr; } // The resolver alone, for a device that scans its descriptor tables itself. void set_resolver(void* context, Resolver resolver) { set_hooks(context, resolver, nullptr); } void clear_resolver(void* context) { clear_hooks(context); } + // Set after set_hooks, so the hook (and its context) stays the device's: what reached a copy of the title's memory. + void set_noter(Noter noter) { + std::lock_guard lock(hook_mutex_); + noter_ = noter; + } std::size_t size() const { return count_.load(std::memory_order_acquire); } std::uint64_t invalidations() const { return invalidations_.load(std::memory_order_acquire); } @@ -344,6 +367,7 @@ class TitleVaAliases { BufferMaker maker_ = nullptr; Resolver resolver_ = nullptr; TableScanner scanner_ = nullptr; + Noter noter_ = nullptr; void* source_context_ = nullptr; DescriptorSource source_ = nullptr; std::atomic pulled_{0}; diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 81a3b2fe53..162af852fb 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -522,7 +522,194 @@ int check_window_overflow(Context& c) { VirtualFree(ring, 0, MEM_RELEASE); return 0; } -// These fixtures register their own pairs without XMem. Retire each before Wine can reuse either VA. +// What the GPU writes into a title window goes back to the title's pages (#1537, the WRITE_INVALID stop: a window is +// a read-side mirror, so a UAV write used to land in the copy and the title never saw it). The shader's write is read +// back through the pages themselves; then a write by the title must survive the next submission's forward copy. +struct WriteBack { + Context* c; + ID3D12CommandAllocator* allocator; + ID3D12GraphicsCommandList* list; + ID3D12Resource* out; + ID3D12DescriptorHeap* heap; + UINT64 gpu; +}; + +// 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) { + 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, 1, 1); // the step: a word the shader writes + s.list->SetComputeRootUnorderedAccessView(1, va); + s.list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{s.gpu}); + s.list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER to_copy{}; + to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_copy.Transition.pResource = s.out; + to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + s.list->ResourceBarrier(1, &to_copy); + EXPECT(s.list->Close() == S_OK); + ID3D12CommandList* lists[] = {s.list}; + s.c->queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(s.c->queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(s.c->queue->Signal(s.c->fence, ++s.c->fence_value))); + s.c->fence->SetEventOnCompletion(s.c->fence_value, nullptr); // a null event waits, as D3D12 does + return 0; +} + +// The same gap on a buffer the title places at its own address (slot 133, the retail case for a compute result it +// reads back): the pages are not imported here, so the buffer is a shadow, and the write of a root UAV over the +// title's VA must reach the pages at the next submission - and the title's own newer words must still win. +int check_placed_write_back(Context& c, bool geometry) { + void* pages = VirtualAlloc(nullptr, kPages, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages); + const auto title_va = reinterpret_cast(pages); + auto* words = static_cast(pages); + for (UINT i = 0; i < kPages / 4; ++i) words[i] = 0xA0000000u + i * 3u; // never zero, unlike the shader's rows + auto& aliases = leonida::title_va_aliases(); + aliases.add_title_memory(title_va, kPages); // what the xmem shims do for the title's allocations + const D3D12_RESOURCE_DESC desc = buffer_desc(kPages); + Ref placed; + EXPECT(SUCCEEDED( + rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&placed.p)))); + EXPECT(placed->GetGPUVirtualAddress() == title_va); + EXPECT(aliases.shader_va(title_va) != title_va); // there is a copy to be reached through + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const auto readback_desc = buffer_desc(kBytes); + Ref out, readback; + 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(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.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)}; + + const std::vector before(words, words + kElements); + EXPECT(submit_write(s, title_va) == 0); + UINT untouched = 0; + for (UINT i = 0; i < kElements; ++i) untouched += words[i] == before[i]; + // An imported buffer is the same memory and needs no copy; only a shadow owes the pages the GPU's words. + const bool shadow = !geometry && aliases.shader_va(title_va) >= c.arena; + if (shadow) { + std::printf("placed buffer write back: %u/%u words still held the title's before the next submission\n", + untouched, kElements); + EXPECT(untouched == kElements); + } + + EXPECT(submit_write(s, title_va) == 0); + std::vector written(words, words + kElements); + UINT reached = 0, changed = 0, nonzero = 0; + for (UINT i = 0; i < kElements; ++i) { + reached += written[i] == (0xA0000000u + i * 3u); + changed += written[i] != before[i]; + nonzero += written[i] != 0; + } + std::printf("placed buffer write back: %u/%u words reached the pages (%u changed, %u nonzero)\n", kElements - reached, + kElements, changed, nonzero); + EXPECT(changed == kElements && nonzero > 0); + (void)reached; + + // The title writes its own words over the result: the next submission copies them forward and they stay. + for (UINT i = 0; i < kElements; ++i) words[i] = 0xB16B00B5u; + EXPECT(submit_write(s, title_va) == 0); + UINT kept = 0; + for (UINT i = 0; i < kElements; ++i) kept += words[i] == 0xB16B00B5u; + std::printf("placed buffer write back: the title's own words survived %u/%u\n", kept, kElements); + EXPECT(kept == kElements); + + placed.reset(); // the shadow goes, the pages stay writable + aliases.remove_title_memory(title_va); + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + +int check_window_write_back(Context& c, bool geometry) { + constexpr UINT64 ring_bytes = 256 * 1024; + 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}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const auto readback_desc = buffer_desc(kBytes); + Ref out, readback; + 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(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.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); // Reset needs it closed, as the title leaves it + WriteBack s{&c, allocator.p, list.p, out.p, heap.p, + reinterpret_cast(slot(heap.p, 10))(heap.p)}; + + // The shader writes the range the root UAV names, which is the title's own pages here, far past the arena: the + // resolve already has to make a window for them before the submission. + EXPECT(aliases.shader_va(ring_va) == ring_va); + EXPECT(submit_write(s, ring_va) == 0); + EXPECT(aliases.shader_va(ring_va) != ring_va); // a window was made for the title's pages + if (!geometry) EXPECT(ring[0] == 0); // the copy took the write: the pages get it only after the next submission + + // The next submission's refresh copies the GPU's writes back, before it copies the pages forward. + EXPECT(submit_write(s, ring_va) == 0); + const std::vector written(ring, ring + kElements); + UINT nonzero = 0; + for (std::uint32_t w : written) nonzero += w != 0; + std::printf("write back: %u of %u words the shader wrote are in the title's pages\n", nonzero, kElements); + EXPECT(nonzero > 0); + + // The same submission again: the pages keep what they hold, the values do not drift. + EXPECT(submit_write(s, ring_va) == 0); + UINT stable = 0; + for (UINT i = 0; i < kElements; ++i) stable += ring[i] == written[i]; + std::printf("write back: the pages kept those words across two submissions %u/%u\n", stable, kElements); + EXPECT(stable == kElements); + + // A write by the title after a submission is copied forward over the result again, not overwritten by it. + for (UINT i = 0; i < kElements; ++i) ring[i] = 0xB16B00B5u; + EXPECT(submit_write(s, ring_va) == 0); + UINT kept = 0; + for (UINT i = 0; i < kElements; ++i) kept += ring[i] == 0xB16B00B5u; + std::printf("write back: the title's own words survived the next submission %u/%u\n", kept, kElements); + EXPECT(kept == kElements); + + aliases.remove_title_memory(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); @@ -995,6 +1182,8 @@ int main(int argc, char** argv) { const bool api_copy = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy") == 0); 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 placed_write_back = argc == 2 && std::strcmp(argv[1], "--placed-writeback") == 0; if (window_cap) { const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); if (!cap || std::strcmp(cap, "0")) { @@ -1109,6 +1298,25 @@ int main(int argc, char** argv) { std::printf("title memory past the window cap: the views were zero-size and the shader read zeros\n"); return 0; } + if (placed_write_back) { + if (check_placed_write_back(c, geometry)) return 1; + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title-placed buffer write back: the GPU's writes 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()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title window write back: the GPU's writes reached the title's pages and the title's own " + "words won\n"); + return 0; + } if (geometry && check_declined_imports(c)) return 1; if (geometry && check_import_over_shadow(c)) return 1; if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1;