From ca00cc0e0338d27ff018f94d9a7e6e3da58abe7d Mon Sep 17 00:00:00 2001 From: kurrutako Date: Wed, 25 Nov 2026 18:02:47 +0100 Subject: xmem: a slot-31 copy leaves the title's own mappings at the paired CPU range copy_page_mappings (queue slot 31, CopyPageMappingsBatchX) mirrors every page it maps or unmaps at a GPU-only destination onto the paired CPU range (title_gpu_views::to_cpu). It did so even where the title had mapped that CPU page itself with XMemMapPhysicalPages or XMemMapPhysicalPagesScatter: a copy replaced the title's page, and an unmap (kind 2) left the title's CPU page reserved. The title's next read of it faulted, and the run ended. The console's CopyPageMappingsBatchX edits only the GPU-only range's page table, so a CPU page holding a mapping of the title's (physical, scatter or a slot-31 copy onto that address) is now left as it is. Pages the mirror made itself, zero plants and pages with no mapping still follow the GPU-only range, so the D3D12 layer's reads at the CPU view keep working. Each page kept is counted and the first ones are logged. The unmaps these paths make are now labelled in the read-fault report (CopyPageMappingsBatchX unmap / paired CPU page / remap / hole, XMemMapPhysicalPagesScatter unmap / remap) instead of the default "unmap". xmem_test: test_copy_page_mappings_cpu_view now checks that a copy onto, and an unmap of, a GPU-only page whose paired CPU page the title mapped keep the title's bytes at the CPU page. Both checks fail on the old code. Co-Authored-By: Claude Opus 5.5 --- runtime/test/xmem_test.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'runtime/test/xmem_test.cpp') diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 991388c7f..58143ae49 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -741,7 +741,19 @@ void test_copy_page_mappings_cpu_view(const PhysicalApi& api) { check(readable(other) && page_holds(other, 0x7300u), "a GPU-only source page unmapped there is looked up at its CPU range"); - // A null source unmaps both ranges. + // A CPU page the title mapped itself is the title's: a copy onto its GPU-only page, or an unmap of it, changes the + // GPU-only page alone (the console's CopyPageMappingsBatchX edits only that range's page table). + check(copy(gpu + 2 * kPage64k, pool + kPage64k, 1, false), "a copy onto a GPU-only page whose CPU page is the title's"); + check(readable(gpu + 2 * kPage64k) && page_holds(gpu + 2 * kPage64k, 0x7301u), + "the GPU-only page shows the copied pool page"); + check(readable(cpu + 2 * kPage64k) && page_holds(cpu + 2 * kPage64k, 0x7300u), + "the title's own mapping at the paired CPU page is kept, not replaced by the copy"); + check(copy(gpu + 2 * kPage64k, nullptr, 1, false), "a null source unmaps a GPU-only page whose CPU page is the title's"); + check(!readable(gpu + 2 * kPage64k), "the GPU-only page is unmapped"); + check(readable(cpu + 2 * kPage64k) && page_holds(cpu + 2 * kPage64k, 0x7300u), + "the title's own mapping at the paired CPU page survives the unmap"); + + // A null source unmaps both ranges where the CPU pages are the copy's own. check(copy(gpu, nullptr, kPool, false), "a null source unmaps the GPU-only range"); check(!readable(gpu) && !readable(cpu) && !readable(cpu + kPage64k), "the paired CPU range is unmapped with it"); -- cgit v1.2.3 From d088ea79b8394c04a46ec19efb2922a7cd3faae3 Mon Sep 17 00:00:00 2001 From: Zack Date: Thu, 26 Nov 2026 02:02:47 -0800 Subject: Sync title texture readability with map journal between refresh passes Between periodic refresh_title_textures passes, synchronous slot-70 view creation and the async fill worker checked TextureReadability with a constant generation, missing title_memory_map range changes since the last pass. Track the map generation on TextureReadability and consult title_memory_map::changes_since outside refresh passes so unmapped or decommitted pages defer before hashing and newly mapped pages publish immediately without waiting for a submission. Also mark mix_words and hash_bytes LEONIDA_GUARDED_NO_BUILTIN using an unaligned 64-bit load so clang-cl cannot emit CRT memcpy calls inside the __try frame, and classify non-title read faults over unmapped title pages in xmem::physical_page_fault as FaultExit::passed_guarded. --- runtime/shims/d3d12_vulkan_device.cpp | 18 ++-- runtime/shims/xmem.cpp | 8 +- runtime/shims/xmem.h | 2 +- runtime/src/title_texture_memory.h | 28 +++++- runtime/test/d3d12_existing_heap_test.cpp | 137 ++++++++++++++++++++++++++++++ runtime/test/title_memory_map_test.cpp | 45 +++++++++- runtime/test/xmem_test.cpp | 32 +++++++ 7 files changed, 258 insertions(+), 12 deletions(-) (limited to 'runtime/test/xmem_test.cpp') diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1fb36401e..3be1d88c0 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -225,18 +225,24 @@ bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, // (streaming, file reads, XG copies) or whole planes (video), never a few bytes inside a page. The same sampling as // OpenScarlett's texture hash before submission (src/gpu/d3d12_xs/device_x.cpp, f8e24d4, MIT), with more samples. // False when a page faults (the title unmapped it). No C++ objects here: it is a __try frame. -inline std::uint64_t mix_words(std::uint64_t h, const std::uint8_t* at, std::size_t n) { +#pragma pack(push, 1) +struct UnalignedWord64 { + std::uint64_t value; +}; +#pragma pack(pop) + +LEONIDA_GUARDED_NO_BUILTIN inline std::uint64_t mix_words(std::uint64_t h, const std::uint8_t* at, std::size_t n) { for (std::size_t i = 0; i + 8 <= n; i += 8) { - std::uint64_t w; - std::memcpy(&w, at + i, 8); + const std::uint64_t w = reinterpret_cast(at + i)->value; h = (h ^ w) * 0x100000001b3ull; h ^= h >> 29; } return h; } // The reads of hash_guarded, in a frame of its own: an inline load inside the __try is not covered by clang-cl -// without /EHa (src/guarded_copy.h). -__declspec(noinline) std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes, bool every_byte) { +// without /EHa, and a CRT memcpy call is not covered under Wine (src/guarded_copy.h). +__declspec(noinline) LEONIDA_GUARDED_NO_BUILTIN std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes, + bool every_byte) { std::uint64_t h = 0x9e3779b97f4a7c15ull ^ bytes; if (bytes <= (256u << 10) || every_byte) { h = mix_words(h, p, bytes & ~std::size_t(7)); @@ -15508,6 +15514,8 @@ private: const bool guard = check_pages_before_read(); if (!guard && !t.memory.pending()) return true; const bool mapped = t.mapped && refresh_mapped_pages(); + if (!title_pass_ && guard && !mapped) + t.memory.sync_map(title_map_generation_, static_cast(t.cpu), t.layout.layout.size); const auto commit = mapped ? leonida::kernel_writes::state().committer.load(std::memory_order_acquire) : nullptr; const bool waited = t.memory.pending(); // The answer is kept (generation 0) until a map change over the texture, a write into it or the periodic diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 384f7bd27..964cc9216 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -1575,7 +1575,7 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { MEMORY_BASIC_INFORMATION seen{}; // the page as the decision saw it char read_note[1024]; DWORD read_note_size = 0; - bool plant_read = false, promote = false; + bool plant_read = false, promote = false, from_title = false; bool queried = false; { const FaultLockShared lock; @@ -1594,7 +1594,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { if (where != kNoReservation || access == 1) queried = VirtualQuery(reinterpret_cast(accessed), &seen, sizeof(seen)) != 0; const auto pc = reinterpret_cast(record->ExceptionAddress); - if (access == 0 && result == PageCommit::not_ours && title_code(pc)) { + from_title = access == 0 && result == PageCommit::not_ours && title_code(pc); + if (from_title) { if (!queried) queried = VirtualQuery(reinterpret_cast(accessed), &seen, sizeof(seen)) != 0; read_note_size = describe_read(read_note, pc, accessed, seen); plant_read = where == kInWindow && g_pool_zero_pages; @@ -1670,7 +1671,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { exit = FaultExit::committed; } else if (answered) { exit = FaultExit::answered; - } else if (result == PageCommit::committed_before && !escalated) { + } else if ((result == PageCommit::committed_before && !escalated) || + (title_page && access == 0 && result == PageCommit::not_ours && !from_title)) { exit = FaultExit::passed_guarded; // a guard's (the D3D12 layer's), routine: not noted } else if (title_page || reserved_write) { note_fault(kRefused, accessed, access, result, where, seen); diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index 96fb89e7e..6e0017f2b 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -55,7 +55,7 @@ enum class FaultExit : int { answered, // a mapped page committed, or found committed and allowed (another thread's map or commit) planted, // a window page the title never mapped, backed by a zero page committed, // a section page in the title's reservation with no view of xmem's, committed - passed_guarded, // a committed page of xmem's views whose protection refuses the access: its guard's to answer + passed_guarded, // a committed page whose protection refuses the access, or a host guarded read of an unmapped page passed_foreign, // memory that is not the title's reservation and not only reserved: someone else's fault left_to_title, // the title's reservation, or a write into memory that is only reserved: noted (FaultNote) count diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h index a97e5bed6..ff9f004e0 100644 --- a/runtime/src/title_texture_memory.h +++ b/runtime/src/title_texture_memory.h @@ -1,14 +1,17 @@ #pragma once #include +#include #include #include #include +#include "title_page_watch.h" + namespace leonida { // Keep negative probes until the title changes the map or a writer reports this footprint. With cache_success, -// positive ones too: a caller that is told of every map change over the footprint (retry) and reads it under a guard -// (a page gone since faults into a defer) need not walk the pages before every read. +// positive ones too: a caller that is told of every map change over the footprint (retry or sync_map) and reads it +// under a guard (a page gone since faults into a defer) need not walk the pages before every read. class TextureReadability { public: template @@ -16,16 +19,37 @@ public: if (cache_failure && pending_ && !retry_ && generation_ == generation) return false; if (cache_success && probed_ && !pending_ && !retry_ && generation_ == generation) return true; generation_ = generation; // snapshot before the probe so a concurrent map change is noticed + map_generation_ = title_memory_map::generation(); retry_ = false; probed_ = true; pending_ = !probe(); return !pending_; } + // Between refresh passes, check whether the map journal recorded a change over [cpu, cpu + size) since both + // this texture's last probe and the last pass's sweep. + void sync_map(std::uint64_t pass_generation, std::uintptr_t cpu, std::uint64_t size) { + if (!probed_ || retry_) return; + const std::uint64_t since = (std::max)(map_generation_, pass_generation); + if (title_memory_map::generation() == since) return; + const std::uintptr_t end = size > (std::numeric_limits::max)() - cpu + ? (std::numeric_limits::max)() + : cpu + static_cast(size); + std::uint64_t now = 0; + bool overlapped = false; + if (!title_memory_map::changes_since( + since, now, cpu, end, [&](std::uintptr_t, std::uintptr_t) { overlapped = true; }) || + overlapped) { + retry_ = true; + } else { + map_generation_ = now; + } + } void defer() { pending_ = true; } // mapping disappeared between the probe and the read void retry() { retry_ = true; } bool pending() const { return pending_; } private: std::uint64_t generation_ = 0; + std::uint64_t map_generation_ = 0; bool pending_ = false, retry_ = false, probed_ = false; }; diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 25fa1f654..546c76055 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1359,6 +1359,141 @@ int check_pending_stream_views(ID3D12Device* device) { return 0; } +namespace { +std::atomic g_view_av_thread{0}; +std::atomic g_view_avs{0}; + +LONG CALLBACK count_view_av(PEXCEPTION_POINTERS info) { + if (info && info->ExceptionRecord && info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && + GetCurrentThreadId() == g_view_av_thread.load(std::memory_order_relaxed)) { + g_view_avs.fetch_add(1, std::memory_order_relaxed); + } + return EXCEPTION_CONTINUE_SEARCH; +} +} // namespace + +// Map changes reported to title_memory_map between submissions must both retire a cached readable answer before a +// synchronous slot-70 view hashes decommitted pages, and wake a pending slot-70 view without waiting for a submission. +int check_placed_view_map_changes(ID3D12Device* device) { + const char* who = "slot-70 view map changes"; + if (!rt::d3d12::bindless_set_layout(device)) return 0; + GpuReader gpu; + EXPECT(!gpu.init(device, 4096)); + auto env_is = [](const char* name, const char* want) { + char buf[16]{}; + const DWORD n = GetEnvironmentVariableA(name, buf, sizeof(buf)); + return n > 0 && n < sizeof(buf) && std::strcmp(buf, want) == 0; + }; + auto index = [&](const leonida::gfx10::ImageWords& descriptor) { + std::uint32_t key[8]; + std::memcpy(key, descriptor.data(), sizeof(key)); + return rt::d3d12::bindless_hash_lookup(device, key); + }; + + // 1. Committed >256 KiB texture -> decommit interior 64 KiB + map::changed -> synchronous view takes zero AVs. + { + constexpr SIZE_T bytes = 512 * 1024; + auto* pages = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(pages); + std::memset(pages, 0x5a, bytes); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 512; + desc.Height = 1024; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = desc.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + leonida::gfx10::ImageWords slot{}; + auto write_view = [&](UINT mapping) { + srv.Shader4ComponentMapping = mapping; + std::array resource{}; + std::array words{}; + std::memcpy(resource.data(), &desc, sizeof(desc)); + std::memcpy(words.data(), &srv, sizeof(srv)); + return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), + reinterpret_cast(pages), + {reinterpret_cast(slot.data())}); + }; + EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING)); + EXPECT(index(slot) != 0); + + EXPECT(VirtualFree(pages + 65536, 65536, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(pages + 65536, 65536); + + g_view_avs.store(0, std::memory_order_relaxed); + g_view_av_thread.store(GetCurrentThreadId(), std::memory_order_relaxed); + PVOID veh = AddVectoredExceptionHandler(1, &count_view_av); + EXPECT(veh != nullptr); + const bool wrote_after_unmap = write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0)); + RemoveVectoredExceptionHandler(veh); + g_view_av_thread.store(0, std::memory_order_relaxed); + EXPECT(wrote_after_unmap); + EXPECT(g_view_avs.load(std::memory_order_relaxed) == 0); + + EXPECT(VirtualAlloc(pages + 65536, 65536, MEM_COMMIT, PAGE_READWRITE) == pages + 65536); + leonida::title_memory_map::changed(pages + 65536, 65536); + Ref placement; + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK); + placement.p->Release(); + placement.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + } + + // 2. Reserved texture -> commit + map::changed (no texel write note, no submission) -> synchronous view publishes. + { + constexpr SIZE_T bytes = 65536; + void* pages = VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pages); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 32; + desc.Height = 8; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = desc.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + leonida::gfx10::ImageWords first{}, second{}; + auto write_view = [&](UINT mapping, leonida::gfx10::ImageWords& out) { + srv.Shader4ComponentMapping = mapping; + std::array resource{}; + std::array words{}; + std::memcpy(resource.data(), &desc, sizeof(desc)); + std::memcpy(words.data(), &srv, sizeof(srv)); + return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), + reinterpret_cast(pages), + {reinterpret_cast(out.data())}); + }; + EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, first)); + if (!env_is("LEONIDA_TITLE_IMAGE_DEFER", "0")) EXPECT(!index(first)); + + EXPECT(VirtualAlloc(pages, bytes, MEM_COMMIT, PAGE_READWRITE) == pages); + std::memset(pages, 0x33, bytes); + leonida::title_memory_map::changed(pages, bytes); + + EXPECT(write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0), second)); + if (!env_is("LEONIDA_TITLE_FILL_ASYNC", "1")) EXPECT(index(first) && index(second)); + + Ref placement; + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK); + placement.p->Release(); + placement.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + } + return 0; +} + // A persistent Map can become readable without notifying xmem or calling Map a second time. int check_mapped_plane(ID3D12Device* device) { const char* who = "persistent slot-133 plane"; @@ -2089,6 +2224,7 @@ int main(int argc, char** argv) { if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p); if (vk.host_image_copy) { failures += check_pending_stream_views(ours.p); + failures += check_placed_view_map_changes(ours.p); failures += check_shared_bc_placements(ours.p); failures += check_mapped_plane(ours.p); failures += check_mapped_bc_array(ours.p); @@ -2099,6 +2235,7 @@ int main(int argc, char** argv) { no_host_copy.host_image_copy = false; Ref staged; if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; + failures += check_placed_view_map_changes(staged.p); failures += check_mapped_plane(staged.p); failures += check_mapped_bc_array(staged.p); } diff --git a/runtime/test/title_memory_map_test.cpp b/runtime/test/title_memory_map_test.cpp index ba5a518a1..ff226d648 100644 --- a/runtime/test/title_memory_map_test.cpp +++ b/runtime/test/title_memory_map_test.cpp @@ -7,7 +7,8 @@ // 3. a reader further behind than the journal holds is told so (it then looks at everything); // 4. a change with no range overlaps every reader; // 5. TextureReadability keeps a positive answer, when asked to, until a retry; -// 6. a pass over 20,000 waiting textures probes only those under the one mapped block. +// 6. a pass over 20,000 waiting textures probes only those under the one mapped block; +// 7. between passes, sync_map retries only when a map change overlaps the texture's footprint. #include #include @@ -142,6 +143,48 @@ int main() { check(pass() == 4 && probes == 0, "a pass with no change probes nothing"); } + // 7. Synchronous view checks between passes (sync_map): unrelated map changes cost no probe, an overlapping unmap + // defers without reading, and an overlapping map wakes a waiting texture before the next pass. + { + constexpr std::uintptr_t cpu = kBase + 0x20000000; + constexpr std::uint64_t size = 512 * 1024; + const std::uint64_t pass_generation = map::generation(); + bool mapped = true; + unsigned probes = 0; + leonida::TextureReadability r; + const auto probe = [&] { + ++probes; + return mapped; + }; + check(r.check(0, true, probe, true) && probes == 1 && !r.pending(), + "sync_map: initial probe caches a readable answer"); + for (std::uintptr_t i = 0; i < 32; ++i) + map::changed(cpu + size + i * 0x10000, cpu + size + (i + 1) * 0x10000); + r.sync_map(pass_generation, cpu, size); + check(r.check(0, true, probe, true) && probes == 1, + "sync_map: map changes outside the footprint keep the cached answer"); + r.sync_map(pass_generation, cpu, size); + check(r.check(0, true, probe, true) && probes == 1, + "sync_map: a second check at the same generation does nothing"); + + mapped = false; + map::changed(cpu + 0x10000, cpu + 0x20000); + r.sync_map(pass_generation, cpu, size); + check(!r.check(0, true, probe, true) && r.pending() && probes == 2, + "sync_map: an overlapping unmap between passes reprobes and defers"); + + map::changed(cpu - 0x10000, cpu); + r.sync_map(pass_generation, cpu, size); + check(!r.check(0, true, probe, true) && r.pending() && probes == 2, + "sync_map: an adjacent non-overlapping change leaves a pending texture waiting"); + + mapped = true; + map::changed(cpu, cpu + size); + r.sync_map(pass_generation, cpu, size); + check(r.check(0, true, probe, true) && !r.pending() && probes == 3, + "sync_map: an overlapping map between passes wakes a pending texture at once"); + } + std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 991388c7f..fca830bf0 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -1544,6 +1544,38 @@ void test_physical_pages_commit_on_touch(const PhysicalApi& api) { check(read_ok, "ReadFile fills a page that commit_physical_range committed"); check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap"); + { + // A host guarded read (outside the title image at 0x140000000) of an unmapped window page exits as + // passed_guarded without counting as left_to_title; a title read still counts as left_to_title. + void* const stub_page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + const uint8_t mov_eax_rcx_ret[] = {0x8b, 0x01, 0xc3}; + DWORD stub_old = 0; + bool stub_ready = false; + if (stub_page) { + std::memcpy(stub_page, mov_eax_rcx_ret, sizeof(mov_eax_rcx_ret)); + stub_ready = VirtualProtect(stub_page, 4096, PAGE_EXECUTE_READ, &stub_old) != FALSE; + FlushInstructionCache(GetCurrentProcess(), stub_page, sizeof(mov_eax_rcx_ret)); + } + const auto host_read_faults = [&](const void* p) { + __try { + reinterpret_cast(stub_page)(p); + return false; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER + : EXCEPTION_CONTINUE_SEARCH) { + return true; + } + }; + const uint64_t guarded_before = rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded); + const uint64_t left_before = rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title); + check(stub_ready && host_read_faults(second) && + rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded) == guarded_before + 1 && + rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before, + "a host guarded read of an unmapped window page exits as passed_guarded"); + check(access_faults(reinterpret_cast(second), false) && + rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before + 1, + "a title read of an unmapped window page still exits as left_to_title"); + if (stub_page) VirtualFree(stub_page, 0, MEM_RELEASE); + } check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); } -- cgit v1.2.3 From 36771ec53dc3769a75be6b0b878b9868e9648fdb Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 23:33:21 -0500 Subject: d3d12: geometry copies in system memory, and retired when the title remaps their pages Geometry copies held 4.4-6 GB of VRAM in world runs and were never evicted: a view retired only when its range was freed, decommitted or unmapped, and the title streams by remapping the frames of its pools. - LEONIDA_GEOMETRY_HOST (unset by default): 1 puts the copies in system memory outside VRAM, write-back where the device offers a cached host type; 2 write-combined. The memory type is picked among the host-visible types that are not device-local (memory_type_order alone would give the BAR first); a device with none keeps its types. Logged once and in the geometry buffers line. - LEONIDA_GEOMETRY_REMAP_RELEASE (on by default, 0 off): XMemMapPhysicalPages with pages, the scatter call and CopyPageMappingsBatchX report the pages whose frame changed (or went) as released (xmem's RemapReleases, collected under the fault lock, reported after it), so GeometryViews retires the copies over them through #2094's drain_released and kAfterExecutes reaping. A page mapped again to its own frame is no change. - A retired view is copied once more from its pages when they are readable: a list recorded before a remap that took the view's address reads the new bytes, as the refresh this replaces would have given it. - A stream-pool extent backed by a retired copy leaves pool_spans (it was kept for the device's life). - A full release queue joins touching ranges before it collapses into one covering range. Tests: geometry_views_test cases 14-16, xmem_test test_remap_releases. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 16 +++++ runtime/README.md | 2 + runtime/shims/d3d12_geometry_views.h | 60 ++++++++++++---- runtime/shims/d3d12_title_buffer_windows.h | 57 ++++++++++++++- runtime/shims/d3d12_vulkan_device.cpp | 33 +++++++-- runtime/shims/xmem.cpp | 55 +++++++++++++++ runtime/src/title_geometry_watch.h | 18 ++++- runtime/test/geometry_views_test.cpp | 110 ++++++++++++++++++++++++++++- runtime/test/xmem_test.cpp | 74 +++++++++++++++++++ 9 files changed, 399 insertions(+), 26 deletions(-) (limited to 'runtime/test/xmem_test.cpp') diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 35dbd0f62..35a71003f 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1719,6 +1719,22 @@ The copies: encoding reuses only an independently established geometry view. An explicit table or placed SRV can establish that view. The Vulkan memory probe reports populated views, payload and reserved bytes, upload totals, cap refusals and allocation failures. + - **Where the copies live**: device-local memory through the BAR by default. `LEONIDA_GEOMETRY_HOST=1` puts them + in system memory outside VRAM (write-back where the device offers a cached host type, `=2` write-combined), + as VIctory keeps its copies of title memory (approach only). In a world run on the RX 7900 XTX the copies held + 4.4-6 GB of VRAM. The cost moves to the bus: the GPU reads every vertex and index of a copy from system memory, + so a geometry-heavy pass can take longer; measure frame time with and without it before making it a default. + - **When a copy goes**: a view is retired when its title range is freed, decommitted or unmapped, and also when a + remap gives one of its pages another frame or none (`XMemMapPhysicalPages` with pages, the scatter call, + `CopyPageMappingsBatchX`; xmem's `RemapReleases`, `LEONIDA_GEOMETRY_REMAP_RELEASE=0` turns it off): the title + streams by remapping its pools' frames, and before this the copies of what those pages held stayed for the + device's life (`evicted 0` in every world run). A page mapped again to the frame it had is no change. A retired + view leaves the lookups at once, its alias ranges and translated heap slots are invalidated, its stream-pool + extent is forgotten, and its memory is freed only after every ExecuteCommandLists replay in progress at the + retirement has recorded its submissions and those have completed (`kAfterExecutes`). Before it leaves the + refresh it is copied once more from its pages if they are readable: a list recorded before a remap that took the + view's address (a root view) reads the new bytes, as on the console. The next view of the range makes a new copy. + `geometry_views_test` cases 14-16 and `xmem_test` (`test_remap_releases`) cover this without a GPU. - **Which pages changed** since the last refresh: where xmem reserved the title's memory with `MEM_WRITE_WATCH` (`XMemVirtualAlloc`'s ordinary regions and the title's `VirtualAlloc` reservations, not placeholders or physical-page windows), the kernel says (`GetWriteWatch` with reset, its answers kept for every copy over the page: diff --git a/runtime/README.md b/runtime/README.md index e0b4b9d17..bfaf82d0c 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -382,6 +382,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. | | `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. | | `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. | +| `LEONIDA_GEOMETRY_HOST` | unset | Where the geometry copies (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) live. Unset or `0`: device-local memory through the BAR while the driver gives it (several GB of VRAM in a world run). `1`: system memory outside VRAM, write-back where the device offers a cached host type; `2`: system memory, write-combined. The GPU then reads every vertex and index of a copy over the bus, which can cost frame time in geometry-heavy passes. A device whose host-visible memory is all device-local (an integrated GPU) keeps its types. The choice is logged once and in the `geometry buffers` line. | +| `LEONIDA_GEOMETRY_REMAP_RELEASE` | on | A remap of physical pages (`XMemMapPhysicalPages`, the scatter call, `CopyPageMappingsBatchX`) that gives a page another frame, or none, retires the geometry copies over it, as freeing or unmapping it does: the title streams by remapping its pools' frames, and the copies of what they held were kept for the device's life. A retired copy is copied once more from the new pages if they are readable, then freed once every submission that may name it has finished. A page mapped again to the frame it had is no change. `0` turns it off. | | `LEONIDA_TITLE_FILL_ASYNC` | unset | Trades correctness for speed. `1` stops device slot 70 views from hashing and filling the texture they name on the title's thread: a texture never filled or known stale is queued for a worker thread that fills one texture at a time. Until then a shader samples the image as it is, empty or a frame behind. | | `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. | | `LEONIDA_TITLE_EVERY_BUDGET_US` | `0` | Microseconds one pass over the textures filled from the title's memory may spend on the textures it visits every pass (mapped by the title, or known stale), resuming where the last pass stopped; the texture that crosses the limit is finished. A mapped texture never filled yet is visited first whatever the limit. `0` visits all of them every pass. It limits the synchronous pass only: with `LEONIDA_TEXTURE_REFRESH_ASYNC=1` the pass runs on the refresh worker, and the limit does not apply. | diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h index feb4ff52e..ebfab4b74 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h @@ -9,13 +9,14 @@ #include #include #include +#include #include #include #include namespace rt::d3d12 { -// One persistent device-local copy for each geometry extent. The console heap retains its original indices. +// One persistent copy for each geometry extent, in device-local memory (or system memory: LEONIDA_GEOMETRY_HOST). The console heap retains its original indices. // Every CPU mapping of a source tile is watched; a physical remap changes which aliases must be watched. // Views whose title range is released are retired immediately and their backing storage is reclaimed once // in-flight GPU submissions up to their retire ticket have completed; previously cap-refused ranges retry @@ -30,6 +31,7 @@ class GeometryViews { struct NoopRetire { void operator()(Address, std::size_t, VkDeviceSize) const noexcept {} }; + struct NoCopy {}; struct View { Address source{}; std::size_t size{}; @@ -121,7 +123,7 @@ class GeometryViews { std::atomic free_generation_{0}; std::uint64_t serial_{}, bytes_{}, cap_refusals_{}, allocation_failures_{}, ready_{}, uploads_{}, uploaded_{}; std::uint64_t submissions_{}, dirty_refreshes_{}, refilled_{}, tile_fills_{}; - std::uint64_t evicted_{}, reaped_{}, retries_succeeded_{}; + std::uint64_t evicted_{}, reaped_{}, retries_succeeded_{}, final_copies_{}; std::unordered_map tile_reads_; // refresh(): offset in tile_scratch_, SIZE_MAX unreadable // refresh() scratch: per view, whether it waits on a tile (pinned), is filled whole, was touched, was counted; // and the tiles found written, in address order. @@ -213,6 +215,7 @@ class GeometryViews { public: explicit GeometryViews(std::uint64_t cap_override = 0) : cap_override_(cap_override) { + pool_.set_system_memory(system_memory_setting()); leonida::geometry_writes::subscribe(releases_); } ~GeometryViews() { leonida::geometry_writes::unsubscribe(releases_); } @@ -231,6 +234,16 @@ public: std::uint64_t effective_cap() const { return cap_override_ ? cap_override_ : cap(); } + // LEONIDA_GEOMETRY_HOST: where the copies live. Unset or 0: device-local memory (the BAR) while the driver gives it; + // 1: system memory, write-back (cached) where the device offers it; 2: system memory, write-combined. The GPU then + // reads the copies over the bus (VRAM saved, each read of a vertex or index slower). + static int system_memory_setting() { + const char* v = std::getenv("LEONIDA_GEOMETRY_HOST"); + if (!v || !*v || *v == '0') return TitleBufferWindows::kDeviceLocal; + return *v == '2' ? TitleBufferWindows::kSystemUncached : TitleBufferWindows::kSystemCached; + } + int system_memory() const { return pool_.system_memory(); } + bool has_released() const { return leonida::geometry_writes::has_released(releases_); } bool has_retired() const { return retired_count_.load(std::memory_order_acquire) != 0; } bool has_pending_reclaim() const { return has_released() || has_retired(); } @@ -258,6 +271,10 @@ public: std::lock_guard lock(mutex_); return evicted_; } + std::uint64_t final_copies() const { + std::lock_guard lock(mutex_); + return final_copies_; + } std::uint64_t reaped() const { std::lock_guard lock(mutex_); return reaped_; @@ -393,9 +410,14 @@ public: // Retires every live view overlapping [begin, end), unlinking it from lookup/refresh/watch immediately and // deferring its backing storage reclamation until GPU submissions through `retire_ticket` have completed // (kAfterExecutes: through the submissions of every replay in progress now, see execute_end). - template + // With `final_copy` (a refresh's copy), a ready view whose title range is readable now is copied from it once more + // before it leaves the refresh: a range the title remapped holds new bytes, and a list recorded before the remap + // that took the view's address (a root view) and runs in a submission the view waits for reads those, as it would + // have read them in the console's memory, and as the refresh this retirement replaces would have copied them. + // Freed or unmapped memory is not readable, so such a view keeps what it held. + template std::size_t retire_range(Address begin, Address end, std::uint64_t retire_ticket = 0, - OnRetire&& on_retire = {}) { + OnRetire&& on_retire = {}, Copy&& final_copy = {}) { if (end <= begin) return 0; struct CallbackItem { Address source; @@ -425,6 +447,13 @@ public: const std::size_t first_retired = retired_.size(); for (const auto id : ids) { View& v = views_[id]; + if constexpr (!std::is_same_v, NoCopy>) { + if (v.ready && final_copy(v.dst, reinterpret_cast(v.source), v.size) == + GeometryCopy::copied) { + ++final_copies_; + uploaded_ += v.size; + } + } detach_tiles_locked(id, v.source, v.size); if (v.ready) { --ready_; @@ -495,21 +524,21 @@ public: return freed; } - // Drains released title ranges recorded by xmem (retiring matching views at `retire_ticket`) and reaps retired - // views whose GPU work completed by `completed_ticket`. - template + // Drains released title ranges recorded by xmem (retiring matching views at `retire_ticket`, with `final_copy` as + // retire_range takes it) and reaps retired views whose GPU work completed by `completed_ticket`. + template void drain_released(Device& device, std::uint64_t retire_ticket, std::uint64_t completed_ticket, - OnRetire&& on_retire = {}) { + OnRetire&& on_retire = {}, Copy&& final_copy = {}) { std::vector> ranges; leonida::geometry_writes::take_released(releases_, ranges); for (const auto& [begin, end] : ranges) { - retire_range(begin, end, retire_ticket, on_retire); + retire_range(begin, end, retire_ticket, on_retire, final_copy); leonida::title_gpu_views::Range pair{}; if (end > begin && leonida::title_gpu_views::view_at(begin, 1, pair) && begin >= pair.gpu && begin - pair.gpu < pair.size) { const Address offset = begin - pair.gpu; const Address span = (std::min)(end - begin, pair.size - offset); - retire_range(pair.cpu + offset, pair.cpu + offset + span, retire_ticket, on_retire); + retire_range(pair.cpu + offset, pair.cpu + offset + span, retire_ticket, on_retire, final_copy); } } reap(device, completed_ticket); @@ -666,14 +695,17 @@ public: if (!effective_cap()) return; std::lock_guard lock(mutex_); std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, " - "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu), " - "allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, reserved %llu bytes\n", + "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu, copied at " + "retirement %llu), allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, " + "reserved %llu bytes (%s)\n", keys_.size() + refused_.size(), live_views_, (unsigned long long)bytes_, (unsigned long long)ready_, (unsigned long long)(effective_cap() >> 20), (unsigned long long)cap_refusals_, (unsigned long long)retries_succeeded_, (unsigned long long)evicted_, - (unsigned long long)reaped_, retired_.size(), (unsigned long long)allocation_failures_, + (unsigned long long)reaped_, retired_.size(), (unsigned long long)final_copies_, + (unsigned long long)allocation_failures_, (unsigned long long)uploads_, (unsigned long long)uploaded_, tiles_.size(), - static_cast(pool_.reserved())); + static_cast(pool_.reserved()), + pool_.system_memory() ? "system memory" : "device-local"); std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by " "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n", static_cast(dirty_refreshes_), static_cast(submissions_), diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h index 06927cb4b..c85809e8e 100644 --- a/runtime/shims/d3d12_title_buffer_windows.h +++ b/runtime/shims/d3d12_title_buffer_windows.h @@ -38,6 +38,10 @@ class TitleBufferWindows { std::chrono::steady_clock::time_point failed_at_{}; bool failed_ = false; bool local_refused_ = false; // device-local blocks refused once: host memory from then on + // SystemMemory: where a device_local allocation goes instead (set_system_memory; GeometryViews from + // LEONIDA_GEOMETRY_HOST). + int system_memory_ = 0; + bool system_memory_logged_ = false; std::uint64_t quick_refusals_ = 0; // The blocks' (device address, capacity), readable without the owner's lock: published in order, a slot never // reused before release(). A destroyed block's slot keeps its other fields and only its address goes to 0 (the @@ -73,7 +77,38 @@ class TitleBufferWindows { blocks_.erase(it); } + // The memory types a system-memory block may take: host-visible ones outside device-local memory (the GPU reads + // them over the bus), the write-back (cached) ones only when `cached`, else the write-combined ones only. None of + // them: every type `bits` allows (an integrated GPU, whose memory is all device-local). + template + static std::uint32_t system_memory_types(const Device& d, std::uint32_t bits, bool cached) { + if constexpr (requires { d.memory.memoryTypes[0].propertyFlags; d.memory.memoryTypeCount; }) { + std::uint32_t host = 0, wanted = 0; + for (std::uint32_t i = 0; i < d.memory.memoryTypeCount && i < 32; ++i) { + if (!(bits & (1u << i))) continue; + const VkMemoryPropertyFlags f = d.memory.memoryTypes[i].propertyFlags; + if ((f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) || !(f & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) || + !(f & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) + continue; + host |= 1u << i; + if (bool(f & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) == cached) wanted |= 1u << i; + } + return wanted ? wanted : host ? host : bits; + } else { + (void)d; + (void)cached; + return bits; + } + } + public: + // Where blocks asked for as device_local go: kDeviceLocal (Resizable BAR while the driver gives it, the default), + // kSystemCached (host memory outside VRAM, write-back where the device offers it: what VIctory gives its copies + // of title memory) or kSystemUncached (host memory outside VRAM, write-combined). The GPU reads the system-memory + // kinds over the bus. Set before the first allocation. + static constexpr int kDeviceLocal = 0, kSystemCached = 1, kSystemUncached = 2; + void set_system_memory(int kind) { system_memory_ = kind; } + int system_memory() const { return system_memory_; } VkDeviceSize reserved() const { return reserved_; } // f(device address, capacity) for each live block; from any thread. template @@ -186,10 +221,26 @@ public: // story load the driver refused every 4 MiB device-local, host-visible block with a device address // (VK_ERROR_OUT_OF_HOST_MEMORY, speed-8/-9) while host memory still served: once that happens, later blocks // go straight to host memory instead of through DeviceState::allocate's sleeping retries first. + // A device_local request under set_system_memory takes system memory instead, out of the types that are not + // device-local (memory_type_order would otherwise give the first host-visible type, which can be the BAR). VkMemoryPropertyFlags chosen = 0; - const bool want_local = device_local && !local_refused_; - b.memory = d.allocate(req, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &chosen, true); + const bool system = device_local && system_memory_ != kDeviceLocal; + const bool want_local = device_local && !local_refused_ && !system; + VkMemoryRequirements types = req; + if (system) types.memoryTypeBits = system_memory_types(d, req.memoryTypeBits, system_memory_ == kSystemCached); + b.memory = d.allocate(types, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT + : system && system_memory_ == kSystemCached ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT + : 0, + &chosen, true); + if (b.memory && system && !system_memory_logged_) { + system_memory_logged_ = true; + std::fprintf(stderr, "[rt] d3d12: title buffer copies in system memory (LEONIDA_GEOMETRY_HOST): memory " + "flags 0x%x (%s, %s)\n", + unsigned(chosen), + (chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ? "device-local: no other type" : "not VRAM", + (chosen & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) ? "write-back" : "write-combined"); + } if (b.memory && want_local && !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { local_refused_ = true; std::fprintf(stderr, "[rt] d3d12: title buffer windows: device-local memory refused a %llu KiB block; " diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 2c7dea49c..32b8c00ba 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2569,7 +2569,9 @@ 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; - // The stream pools' mappings (title_gpu_views): one per readable run of a pool, kept for the device's life. + // The stream pools' mappings (title_gpu_views): one per readable run of a pool. A window is kept for the device's + // life; a geometry copy goes when its view is retired (the pages were freed, unmapped or remapped: + // drain_geometry_releases), and the next request for those pages makes a new one. struct PoolSpan { std::uint64_t source; // the readable side of the pair the copy is made from std::uint64_t twin; // the extent's address in the pair's other view (0 when there is none) @@ -2580,6 +2582,7 @@ struct DeviceState { std::vector pool_spans; std::atomic pool_span_count{0}; std::uint64_t pool_span_bytes = 0; + std::uint64_t pool_spans_retired = 0; // geometry-copy extents whose view was retired (forget_pool_span) std::uint64_t title_window_refusals = 0; // windows neither the budget nor the arena allowed std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) @@ -2601,11 +2604,29 @@ struct DeviceState { // another queue's replay that translated its slots before this retirement may still name it. A ticket read here // would be one short of this submission, which records its own only after before_execute_ (and with an idle GPU // the view would be reaped in this very call). + // A retired view's last copy is made here from the title's pages as they are now (GeometryViews::retire_range): a + // range the title remapped (xmem's RemapReleases) holds its new bytes, which the refresh below would have copied. + // A stream-pool extent it backed leaves pool_spans: the next request for those pages makes a new mapping. void drain_geometry_releases() { if (!context || !geometry.has_pending_reclaim()) return; const std::uint64_t completed_ticket = geometry.has_retired() ? context->completed_retire_ticket() : 0; - geometry.drain_released(*this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket, - forget_geometry_alias); + geometry.drain_released( + *this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket, + [this](std::uintptr_t source, std::size_t size, VkDeviceSize va) { + forget_geometry_alias(source, size, va); + forget_pool_span(va); + }, + copy_geometry); + } + void forget_pool_span(VkDeviceSize va) { + std::lock_guard windows(title_window_mutex); + const auto it = std::find_if(pool_spans.begin(), pool_spans.end(), + [&](const PoolSpan& span) { return span.geometry && span.shader_va == va; }); + if (it == pool_spans.end()) return; + pool_span_bytes -= it->size; + pool_spans.erase(it); + pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); + ++pool_spans_retired; } // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases). static std::vector& geometry_execute_serials() { @@ -3726,13 +3747,13 @@ struct DeviceState { [](const PoolSpan& span) { return span.geometry; }); std::fprintf(stderr, "[rt] d3d12: title memory: %zu windows (%llu KiB of a %llu MiB budget, %llu refused), %zu " - "stream-pool extents (one mapping each, %llu KiB; %lld by geometry copy), %llu addresses " - "given a zero-size view\n", + "stream-pool extents (one mapping each, %llu KiB; %lld by geometry copy, %llu retired with " + "their copy), %llu addresses given a zero-size view\n", title_windows.size(), static_cast(title_window_bytes >> 10), static_cast(title_window_cap >> 20), static_cast(title_window_refusals), pool_spans.size(), static_cast(pool_span_bytes >> 10), - static_cast(geometry_spans), + static_cast(geometry_spans), static_cast(pool_spans_retired), static_cast(unbacked_requests)); } } diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 384f7bd27..f3863e2c9 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -1032,12 +1032,62 @@ constexpr size_t kUnmapRecords = 1024; UnmapRecord g_unmaps[kUnmapRecords]; uint64_t g_unmap_count = 0; thread_local const char* t_unmap_cause = "unmap"; + +// A remap of physical pages (XMemMapPhysicalPages with pages, the scatter call, CopyPageMappingsBatchX): the pages +// whose frame it took away. unmap_range_locked records each page that held a frame while one is installed (under the +// fault lock: host_heap only, nothing else); when it goes, with g_phys_mutex still held and the fault lock not, every +// page now mapped to another frame than it had (or to none) is reported as released, in runs, so the geometry copies +// over it are retired as over freed or unmapped memory (geometry_writes::note_released, GeometryViews::drain_released): +// the title streams by remapping the frames of its pools, and the copies of what those pages held before were kept +// for the device's life. A page mapped again to the frame it had is no change. LEONIDA_GEOMETRY_REMAP_RELEASE=0: off. +bool remap_releases_enabled() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_GEOMETRY_REMAP_RELEASE"); + return !v || std::strcmp(v, "0") != 0; + }(); + return on; +} +struct RemapReleases; +thread_local RemapReleases* t_remap_releases = nullptr; +struct RemapReleases { + leonida::host_heap::vector> pages; // address, the frame it had + bool active = false; + RemapReleases() { + if (!t_remap_releases && remap_releases_enabled()) { + t_remap_releases = this; + active = true; + } + } + RemapReleases(const RemapReleases&) = delete; + RemapReleases& operator=(const RemapReleases&) = delete; + ~RemapReleases(); // g_phys_mutex held, the fault lock not +}; struct UnmapCause { const char* was; explicit UnmapCause(const char* cause) : was(std::exchange(t_unmap_cause, cause)) {} ~UnmapCause() { t_unmap_cause = was; } }; +RemapReleases::~RemapReleases() { + if (!active) return; + t_remap_releases = nullptr; + if (pages.empty()) return; + std::sort(pages.begin(), pages.end()); + uintptr_t run_begin = 0, run_end = 0; + for (const auto& [at, frame] : pages) { + const auto now = g_mapped.find(at); + if (now != g_mapped.end() && now->second == frame) continue; // the frame it had: no change + if (run_end == at && run_end > run_begin) { + run_end = at + kPhysicalPageSize; + continue; + } + if (run_end > run_begin) leonida::geometry_writes::note_released(run_begin, run_end); + run_begin = at; + run_end = at + kPhysicalPageSize; + } + if (run_end > run_begin) leonida::geometry_writes::note_released(run_begin, run_end); +} + // With g_fault_lock held exclusively. Unmaps every page in [start, end); the addresses become placeholders again. A // view that reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so // neighbours keep their pages. @@ -1064,6 +1114,7 @@ bool unmap_range_locked(uintptr_t start, uintptr_t end) { // The pages of [start, end) this view held are unmapped now; the ones outside it are mapped again below. for (uintptr_t at = (std::max)(base, start); at < (std::min)(view_end, end); at += kPhysicalPageSize) { if (const auto mapped = g_mapped.find(at); mapped != g_mapped.end()) { + if (t_remap_releases) t_remap_releases->pages.emplace_back(at, mapped->second); note_mapping(mapped->second, at, false); g_mapped.erase(mapped); } @@ -1834,6 +1885,7 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint } drain_fault_notes(); const std::lock_guard lock(g_phys_mutex); + RemapReleases remap_releases; // reported as it goes: after the fault lock, with g_phys_mutex const uintptr_t end = start + page_count * kPhysicalPageSize; const UnmapCause cause(page_array ? "XMemMapPhysicalPages (remap)" : "XMemMapPhysicalPages (unmap)"); if (!page_array) { @@ -1957,6 +2009,7 @@ BOOL scatter_refused(ScatterFailure reason, uintptr_t address, DWORD error) { BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_count, const uint64_t* page_array) { drain_fault_notes(); const std::lock_guard lock(g_phys_mutex); + RemapReleases remap_releases; if (page_count && !addresses) { return scatter_refused(ScatterFailure::missing_addresses, 0, ERROR_INVALID_PARAMETER); } @@ -2005,6 +2058,7 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b return false; } const std::lock_guard lock(g_phys_mutex); + RemapReleases remap_releases; // The destination is usually a GPU-only reservation, which the D3D12 layer reads at its paired CPU view // (title_gpu_views::to_cpu); that view gets the same pages, or it would stay reserved and never readable. const uintptr_t cpu_to = leonida::title_gpu_views::to_cpu(to, pages * kPhysicalPageSize); @@ -2399,6 +2453,7 @@ bool copy_page_mappings(std::uint32_t count, const PageBatch* batches, std::uint std::vector frames; drain_fault_notes(); const std::lock_guard lock(g_phys_mutex); + RemapReleases remap_releases; try { for (uint32_t b = 0; b < count; ++b) { const auto& batch = batches[b]; diff --git a/runtime/src/title_geometry_watch.h b/runtime/src/title_geometry_watch.h index ca600fb9b..dfb0ae5b5 100644 --- a/runtime/src/title_geometry_watch.h +++ b/runtime/src/title_geometry_watch.h @@ -1,6 +1,7 @@ #pragma once #include "title_page_watch.h" +#include #include #include #include @@ -72,7 +73,22 @@ inline void note_released(std::uintptr_t begin, std::uintptr_t end) { std::lock_guard subscribers_lock(s.subscribers_mutex); for (ReleaseQueue* q : s.subscribers) { std::lock_guard lock(q->mutex); - if (q->ranges.size() < 65536) { + bool room = q->ranges.size() < 65536; + if (!room) { + // Full: first the ranges that overlap or touch become one (remaps report page runs, often neighbours), and + // only when that leaves it more than half full does it all become one covering range. + std::sort(q->ranges.begin(), q->ranges.end()); + std::size_t kept = 0; + for (std::size_t i = 1; i < q->ranges.size(); ++i) { + if (q->ranges[i].first <= q->ranges[kept].second) + q->ranges[kept].second = (std::max)(q->ranges[kept].second, q->ranges[i].second); + else + q->ranges[++kept] = q->ranges[i]; + } + q->ranges.resize(kept + 1); + room = q->ranges.size() <= 32768; + } + if (room) { q->ranges.emplace_back(begin, end); } else { std::uintptr_t merged_lo = begin; diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp index caac93dc0..d1e9a07d8 100644 --- a/runtime/test/geometry_views_test.cpp +++ b/runtime/test/geometry_views_test.cpp @@ -16,7 +16,10 @@ // 13. a submission's sequence on an idle GPU (completed == submitted): a view retired by the drain in before_execute_ // (kAfterExecutes) is freed only after every replay begun before the retirement recorded its submissions and those // completed (a ticket read in the drain reaps it at once); its answers made without an alias are invalidated -// (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device. +// (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device; +// 14. LEONIDA_GEOMETRY_HOST picks a system-memory type (write-back for 1, write-combined for 2), never the BAR; +// 15. a retired view is copied once more from its pages when they are readable (a remap), not when they are not; +// 16. a full release queue joins touching ranges before it collapses to one covering range. #include #include @@ -61,7 +64,7 @@ VKAPI_ATTR void VKAPI_CALL requirements(VkDevice, VkBuffer buffer, VkMemoryRequi *out = {}; out->size = reinterpret_cast(buffer)->size; out->alignment = 65536; - out->memoryTypeBits = 1; + out->memoryTypeBits = 0xf; // the four types of test 14's device } VKAPI_ATTR VkResult VKAPI_CALL bind(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) { reinterpret_cast(buffer)->memory = memory; @@ -510,6 +513,109 @@ int main() { } VirtualFree(fly_title, 0, MEM_RELEASE); + // 14. LEONIDA_GEOMETRY_HOST: the copies' memory type. A discrete GPU's types: 0 VRAM, 1 VRAM through the BAR, + // 2 system memory write-combined, 3 system memory write-back. 1 takes type 3 (write-back preferred), 2 type 2, + // unset any host-visible type with device-local preferred (the BAR); a device whose host-visible types are all + // device-local (an integrated GPU) keeps them all. + { + struct TypedDevice : FakeDevice { + VkPhysicalDeviceMemoryProperties memory{}; + std::uint32_t bits = 0; + VkMemoryPropertyFlags preferred = 0; + VkDeviceMemory allocate(const VkMemoryRequirements& r, VkMemoryPropertyFlags required, + VkMemoryPropertyFlags wanted, VkMemoryPropertyFlags* chosen, bool address) { + bits = r.memoryTypeBits; + preferred = wanted; + return FakeDevice::allocate(r, required, wanted, chosen, address); + } + }; + constexpr VkMemoryPropertyFlags kLocal = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + kHost = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + kCached = VK_MEMORY_PROPERTY_HOST_CACHED_BIT; + TypedDevice discrete; + discrete.memory.memoryTypeCount = 4; + const VkMemoryPropertyFlags discrete_types[4] = {kLocal, kLocal | kHost, kHost, kHost | kCached}; + for (int i = 0; i < 4; ++i) discrete.memory.memoryTypes[i].propertyFlags = discrete_types[i]; + TypedDevice integrated; + integrated.memory.memoryTypeCount = 2; + integrated.memory.memoryTypes[0].propertyFlags = kLocal; + integrated.memory.memoryTypes[1].propertyFlags = kLocal | kHost | kCached; + auto* host_title = + static_cast(VirtualAlloc(nullptr, kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!host_title) return 1; + const auto hbase = reinterpret_cast(host_title); + const auto made_with = [&](TypedDevice& dev, const char* setting) { + _putenv_s("LEONIDA_GEOMETRY_HOST", setting); + dev.bits = ~0u; + dev.preferred = 0; + rt::d3d12::GeometryViews v; + const bool made = v.resolve(dev, hbase, kView, copy) != 0; + const int kind = v.system_memory(); + v.release(dev); + return made ? kind : -1; + }; + check(made_with(discrete, "1") == rt::d3d12::TitleBufferWindows::kSystemCached && discrete.bits == 1u << 3 && + discrete.preferred == kCached, + "LEONIDA_GEOMETRY_HOST=1 puts the copies in write-back system memory, never the BAR"); + check(made_with(discrete, "2") == rt::d3d12::TitleBufferWindows::kSystemUncached && discrete.bits == 1u << 2 && + discrete.preferred == 0, + "LEONIDA_GEOMETRY_HOST=2 puts them in write-combined system memory"); + check(made_with(discrete, "") == rt::d3d12::TitleBufferWindows::kDeviceLocal && discrete.bits == 0xfu && + discrete.preferred == kLocal, + "unset, every type the buffer allows is tried, device-local first"); + check(made_with(integrated, "1") == rt::d3d12::TitleBufferWindows::kSystemCached && integrated.bits == 0xfu, + "on a device with no host type outside device-local memory, the types are left as they are"); + _putenv_s("LEONIDA_GEOMETRY_HOST", ""); + check(g_live_buffers == 0, "the memory-type views free their blocks"); + + // 15. A retired view is copied once more from the title's pages when they are readable (a remap gave them new + // bytes), and keeps what it held when they are not (freed or unmapped). + rt::d3d12::GeometryViews last; + std::memset(host_title, 0x11, kView); + const std::uint64_t va_l = last.resolve(device, hbase, kView, copy); + std::uint64_t host_l = 0, bytes_l = 0; + check(va_l && last.lookup(device.arena.address + va_l, host_l, bytes_l), "a view to retire"); + auto* held = reinterpret_cast(host_l); + // The remapped pages' bytes: the watched tiles are opened first (no fault handler here). + leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open); + std::memset(host_title, 0x22, kView); + g_copies.clear(); + check(last.retire_range(hbase, hbase + kView, 1, [](std::uintptr_t, std::size_t, VkDeviceSize) {}, copy) == 1 && + held[0] == 0x22 && held[kView - 1] == 0x22 && last.final_copies() == 1 && g_copies.size() == 1, + "a retired view whose pages are readable is copied from them once more"); + const std::uint64_t va_l2 = last.resolve(device, hbase, kView, copy); + std::uint64_t host_l2 = 0; + check(va_l2 && last.lookup(device.arena.address + va_l2, host_l2, bytes_l), "and made again"); + auto* held2 = reinterpret_cast(host_l2); + leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open); + std::memset(host_title, 0x33, kView); + const auto unreadable = [](std::uint8_t*, const std::uint8_t*, std::size_t) { + return rt::d3d12::GeometryCopy::unreadable; + }; + check(last.retire_range(hbase, hbase + kView, 2, [](std::uintptr_t, std::size_t, VkDeviceSize) {}, + unreadable) == 1 && + held2[0] == 0x22 && last.final_copies() == 1, + "one whose pages are not readable keeps what it held"); + check(last.reap(device, 2) == 2 && last.bytes() == 0, "both are freed at their tickets"); + last.release(device); + + // 16. A full release queue first joins ranges that touch (remaps report page runs): 65536 neighbouring ranges + // and one apart from them are two ranges, not one covering everything between them. + rt::d3d12::GeometryViews coalesce; + check(coalesce.resolve(device, hbase, kView, copy) != 0, "a view to watch the pages"); + for (std::size_t i = 0; i < 65536; ++i) + leonida::geometry_writes::note_released(hbase + i * 8, hbase + i * 8 + 8); + leonida::geometry_writes::note_released(hbase + kView - 4096, hbase + kView); + std::vector> joined; + leonida::geometry_writes::take_released(coalesce.release_queue(), joined); + check(joined.size() == 2 && joined[0] == std::make_pair(hbase, hbase + 65536 * 8) && + joined[1] == std::make_pair(hbase + kView - 4096, hbase + kView), + "65536 touching ranges become one, and a range apart from them stays apart"); + coalesce.release(device); + VirtualFree(host_title, 0, MEM_RELEASE); + } + std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 991388c7f..c65ac257a 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -31,6 +31,7 @@ #include "startup_trace.h" #include "xmem.h" #include "../src/title_page_watch.h" +#include "../src/title_geometry_watch.h" // The process heap as test_heap_lock_faults needs it (the same gate as d3d12_existing_heap_test's): an allocation that // waits while a thread holds the heap's lock. The NT heap's low-fragmentation front end serves most small sizes @@ -429,6 +430,78 @@ struct PhysicalApi { XMemMapPhysicalPagesScatterFn scatter; }; +// A remap that gives watched pages another frame reports them released (geometry_writes::note_released), so the +// geometry copies of what they held are retired; a page mapped again to the frame it had is no change. Through +// XMemMapPhysicalPages, the scatter call and CopyPageMappingsBatchX. +void test_remap_releases(const PhysicalApi& api) { + namespace watch = leonida::geometry_writes; + constexpr uint64_t kPages = 3; + auto* const window = static_cast(api.virtual_alloc( + nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); + uint64_t pages[4]{}; + uint64_t count = 4; + if (!window || api.allocate(0x280, &count, pages) != TRUE || count != 4) { + check(false, "remap releases: a window and four physical pages"); + return; + } + const auto base = reinterpret_cast(window); + watch::ReleaseQueue queue; + watch::subscribe(queue); + for (uint64_t i = 0; i < kPages; ++i) watch::acquire(base + i * kPage64k); // as a geometry copy over the pages + std::vector> released; + const auto take = [&] { + watch::take_released(queue, released); + return released; + }; + const auto covers = [&](uintptr_t from, uintptr_t to) { + for (const auto& [lo, hi] : released) + if (lo <= from && hi >= to) return true; + return false; + }; + const auto any_overlap = [&](uintptr_t from, uintptr_t to) { + for (const auto& [lo, hi] : released) + if (lo < to && hi > from) return true; + return false; + }; + + const uint64_t first[kPages] = {pages[0], pages[1], pages[2]}; + check(api.map(window, kPages, first) == window && take().empty(), + "remap releases: a first mapping of unmapped pages releases nothing"); + check(api.map(window + kPage64k, 1, &pages[1]) == window + kPage64k && take().empty(), + "remap releases: a page mapped again to the frame it has is no change"); + check(api.map(window + kPage64k, 1, &pages[3]) == window + kPage64k && !take().empty() && + covers(base + kPage64k, base + 2 * kPage64k) && !any_overlap(base, base + kPage64k) && + !any_overlap(base + 2 * kPage64k, base + 3 * kPage64k), + "remap releases: a page given another frame is released, its neighbours are not"); + const uint64_t rotated[kPages] = {pages[2], pages[0], pages[1]}; + check(api.map(window, kPages, rotated) == window && !take().empty() && covers(base, base + 3 * kPage64k), + "remap releases: a run given other frames is released whole"); + const uint64_t partly[kPages] = {pages[2], pages[3], pages[1]}; + check(api.map(window, kPages, partly) == window && !take().empty() && + covers(base + kPage64k, base + 2 * kPage64k) && !any_overlap(base, base + kPage64k) && + !any_overlap(base + 2 * kPage64k, base + 3 * kPage64k), + "remap releases: of a remapped run, only the page whose frame changed is released"); + void* const last = window + 2 * kPage64k; + check(api.scatter(&last, 1, &pages[0]) == TRUE && !take().empty() && + covers(base + 2 * kPage64k, base + 3 * kPage64k) && !any_overlap(base, base + 2 * kPage64k), + "remap releases: the scatter call releases the page it gives another frame"); + check(api.scatter(&last, 1, &pages[0]) == TRUE && take().empty(), + "remap releases: the scatter call with the frame the page has releases nothing"); + // CopyPageMappingsBatchX: page 0 gets the frame at page 1 (kind 0 from a pool at the window itself). + const rt::xmem::PageRange range{0, 1, 1}; + const rt::xmem::PageBatch batch{base, 1, &range}; + check(rt::xmem::copy_page_mappings(1, &batch, base, kPages, 0) && !take().empty() && + covers(base, base + kPage64k) && !any_overlap(base + kPage64k, base + 3 * kPage64k), + "remap releases: CopyPageMappingsBatchX releases the page it gives another frame"); + + check(api.map(window, kPages, nullptr) == window && !take().empty() && covers(base, base + 3 * kPage64k), + "remap releases: unmapping releases the range"); + for (uint64_t i = 0; i < kPages; ++i) watch::release(base + i * kPage64k); + watch::unsubscribe(queue); + api.free_pages(4, pages); + VirtualFree(window, 0, MEM_RELEASE); +} + // Physical pages in a 64 KiB-page window, as the measured callers use them: reserve a window, allocate pages, map them, // remap them elsewhere and in another order, unmap, free. void test_physical_pages(const PhysicalApi& api) { @@ -2655,6 +2728,7 @@ int main(int argc, char** argv) { // Keep the direct SEC_RESERVE control ahead of the first physical allocation, which installs xmem's VEH. g_section_write_control = measure_section_write_control(); test_physical_pages(physical); + test_remap_releases(physical); if (argc == 2 && std::strcmp(argv[1], "--file-pools") == 0) { test_placeholders(physical); print_result(); -- cgit v1.2.3 From 1f7cbeff9a0461c037287e83297e9add75d2646a Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Thu, 26 Nov 2026 09:57:50 -0500 Subject: xmem: a remap retires geometry copies only with LEONIDA_GEOMETRY_REMAP_RELEASE=1 Since #2350 a remap of physical pages that gives a page another frame retired the geometry copies over it, on by default. In the first world run of that main on an RX 7900 XTX (RADV) the copies were retired by the thousand (evicted 15010 in about 40 s) and the run ended in a GPUVM page fault (TCP read) and a lost device; the same build settings without it ran eight minutes with evicted 0 and no fault. A remap leaves the address valid on the console, so the title keeps using what names it, and not everything that names a copy's address is rewritten when the copy goes: - a root view is resolved while its list is recorded (d3d12_com.cpp, GraphicsCommandList::address); a list recorded before the retirement and executed in an ExecuteCommandLists begun after it is not among the replays the retirement waits for (kAfterExecutes covers only those in progress), so it reads the freed copy; - a placed buffer view written outside a console heap carries the copy's address for as long as the descriptor lives. The remap release is now off unless the variable is 1, read at every remap; the copies follow the new pages through the refresh, as before #2350. Freeing, decommitting and unmapping still retire copies. Tests: xmem_test test_remap_releases checks that a remap releases nothing by default and with 0, then the existing checks with 1. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 17 ++++++++++++----- runtime/README.md | 2 +- runtime/shims/xmem.cpp | 14 ++++++++------ runtime/test/xmem_test.cpp | 17 +++++++++++++++++ 4 files changed, 38 insertions(+), 12 deletions(-) (limited to 'runtime/test/xmem_test.cpp') diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 98cf32aad..c40224693 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1737,11 +1737,18 @@ The copies: as VIctory keeps its copies of title memory (approach only). In a world run on the RX 7900 XTX the copies held 4.4-6 GB of VRAM. The cost moves to the bus: the GPU reads every vertex and index of a copy from system memory, so a geometry-heavy pass can take longer; measure frame time with and without it before making it a default. - - **When a copy goes**: a view is retired when its title range is freed, decommitted or unmapped, and also when a - remap gives one of its pages another frame or none (`XMemMapPhysicalPages` with pages, the scatter call, - `CopyPageMappingsBatchX`; xmem's `RemapReleases`, `LEONIDA_GEOMETRY_REMAP_RELEASE=0` turns it off): the title - streams by remapping its pools' frames, and before this the copies of what those pages held stayed for the - device's life (`evicted 0` in every world run). A page mapped again to the frame it had is no change. A retired + - **When a copy goes**: a view is retired when its title range is freed, decommitted or unmapped. With + `LEONIDA_GEOMETRY_REMAP_RELEASE=1` (off by default) also when a remap gives one of its pages another frame or + none (`XMemMapPhysicalPages` with pages, the scatter call, `CopyPageMappingsBatchX`; xmem's `RemapReleases`): + the title streams by remapping its pools' frames, and otherwise the copies of what those pages held stay for the + device's life (`evicted 0` in every world run). It is off because a remap leaves the address valid on the + console, and not everything that names a copy's address is rewritten when the copy goes: a root view is + resolved while its list is recorded (`d3d12_com.cpp`, `GraphicsCommandList::address`), so a list recorded before the + retirement and executed after it reads the freed copy, and so does a placed buffer view written outside a + console heap. On by default, it retired 15 010 copies in 40 s of a world run on the + RX 7900 XTX (RADV) and ended it in a GPUVM page fault and a lost device; the same run without it went eight + minutes with no fault. Making it safe needs a copy kept until nothing recorded or written can still name it. + A page mapped again to the frame it had is no change. A retired view leaves the lookups at once, its alias ranges and translated heap slots are invalidated, its stream-pool extent is forgotten, and its memory is freed only after every ExecuteCommandLists replay in progress at the retirement has recorded its submissions and those have completed (`kAfterExecutes`). Before it leaves the diff --git a/runtime/README.md b/runtime/README.md index 84190039c..76df56ff4 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -383,7 +383,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. | | `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. | | `LEONIDA_GEOMETRY_HOST` | unset | Where the geometry copies (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) live. Unset or `0`: device-local memory through the BAR while the driver gives it (several GB of VRAM in a world run). `1`: system memory outside VRAM, write-back where the device offers a cached host type; `2`: system memory, write-combined. The GPU then reads every vertex and index of a copy over the bus, which can cost frame time in geometry-heavy passes. A device whose host-visible memory is all device-local (an integrated GPU) keeps its types. The choice is logged once and in the `geometry buffers` line. | -| `LEONIDA_GEOMETRY_REMAP_RELEASE` | on | A remap of physical pages (`XMemMapPhysicalPages`, the scatter call, `CopyPageMappingsBatchX`) that gives a page another frame, or none, retires the geometry copies over it, as freeing or unmapping it does: the title streams by remapping its pools' frames, and the copies of what they held were kept for the device's life. A retired copy is copied once more from the new pages if they are readable, then freed once every submission that may name it has finished. A page mapped again to the frame it had is no change. `0` turns it off. | +| `LEONIDA_GEOMETRY_REMAP_RELEASE` | unset | Experimental, unsafe in world runs. `1`: a remap of physical pages (`XMemMapPhysicalPages`, the scatter call, `CopyPageMappingsBatchX`) that gives a page another frame, or none, retires the geometry copies over it, as freeing or unmapping it does, so the copies of what the title's stream pools held do not stay for the device's life. A retired copy is copied once more from the new pages if they are readable, then freed once the submissions in progress at the retirement have finished. A remap leaves the address valid, though, and a root view resolved while a list was recorded (executed after the retirement) or a placed buffer view written outside a console heap still names the freed copy: on by default it ended a world run on an RX 7900 XTX in a GPUVM page fault and a lost device. Unset or any other value: a remap retires nothing, and the copies follow the new pages through the refresh. | | `LEONIDA_TITLE_FILL_ASYNC` | unset | Trades correctness for speed. `1` stops device slot 70 views from hashing and filling the texture they name on the title's thread: a texture never filled or known stale is queued for a worker thread that fills one texture at a time. Until then a shader samples the image as it is, empty or a frame behind. | | `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. | | `LEONIDA_TITLE_EVERY_BUDGET_US` | `0` | Microseconds one pass over the textures filled from the title's memory may spend on the textures it visits every pass (mapped by the title, or known stale), resuming where the last pass stopped; the texture that crosses the limit is finished. A mapped texture never filled yet is visited first whatever the limit. `0` visits all of them every pass. It limits the synchronous pass only: with `LEONIDA_TEXTURE_REFRESH_ASYNC=1` the pass runs on the refresh worker, and the limit does not apply. | diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index cbd857fce..0d982be4b 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -1039,13 +1039,15 @@ thread_local const char* t_unmap_cause = "unmap"; // page now mapped to another frame than it had (or to none) is reported as released, in runs, so the geometry copies // over it are retired as over freed or unmapped memory (geometry_writes::note_released, GeometryViews::drain_released): // the title streams by remapping the frames of its pools, and the copies of what those pages held before were kept -// for the device's life. A page mapped again to the frame it had is no change. LEONIDA_GEOMETRY_REMAP_RELEASE=0: off. +// for the device's life. A page mapped again to the frame it had is no change. +// Off unless LEONIDA_GEOMETRY_REMAP_RELEASE=1: a remap keeps the address valid on the console, so the title goes on +// using what names it, and some of what names a copy's address is never rewritten when the copy is retired (a root +// view a list resolved while it was recorded, executed after the retirement; a placed buffer view written outside a +// console heap). On by default, it freed copies under such views: a GPUVM page fault and a lost device about 40 s +// into the world on an RX 7900 XTX. Read at every remap, so a test can switch it. bool remap_releases_enabled() { - static const bool on = [] { - const char* v = std::getenv("LEONIDA_GEOMETRY_REMAP_RELEASE"); - return !v || std::strcmp(v, "0") != 0; - }(); - return on; + char value[2]{}; + return GetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", value, sizeof(value)) == 1 && value[0] == '1'; } struct RemapReleases; thread_local RemapReleases* t_remap_releases = nullptr; diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index adc24cca3..61e8732e1 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -464,7 +464,22 @@ void test_remap_releases(const PhysicalApi& api) { return false; }; + // Off by default: a remap keeps the address valid, and a root view recorded before it (or a placed buffer view) + // names the copy's address after it, so a copy freed then is read by the GPU (a page fault and a lost device). + char previous[8]{}; + const DWORD had = GetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", previous, sizeof(previous)); + SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", nullptr); const uint64_t first[kPages] = {pages[0], pages[1], pages[2]}; + const uint64_t other[kPages] = {pages[3], pages[2], pages[1]}; + check(api.map(window, kPages, first) == window && api.map(window, kPages, other) == window && take().empty(), + "remap releases: off by default, a remap releases nothing"); + SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", "0"); + check(api.map(window, kPages, first) == window && take().empty(), + "remap releases: LEONIDA_GEOMETRY_REMAP_RELEASE=0 releases nothing"); + check(api.map(window, kPages, nullptr) == window && !take().empty() && covers(base, base + 3 * kPage64k), + "remap releases: unmapping releases the range whatever the setting"); + SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", "1"); + check(api.map(window, kPages, first) == window && take().empty(), "remap releases: a first mapping of unmapped pages releases nothing"); check(api.map(window + kPage64k, 1, &pages[1]) == window + kPage64k && take().empty(), @@ -496,6 +511,8 @@ void test_remap_releases(const PhysicalApi& api) { check(api.map(window, kPages, nullptr) == window && !take().empty() && covers(base, base + 3 * kPage64k), "remap releases: unmapping releases the range"); + SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", + had > 0 && had < sizeof(previous) ? previous : nullptr); for (uint64_t i = 0; i < kPages; ++i) watch::release(base + i * kPage64k); watch::unsubscribe(queue); api.free_pages(4, pages); -- cgit v1.2.3 From 4a6a8a633e71ceb5af7afbaadcf9ad2e4ba9a377 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Thu, 26 Nov 2026 10:05:43 -0500 Subject: xmem: read LEONIDA_GEOMETRY_REMAP_RELEASE once, with a test seam to read it again GetEnvironmentVariableA at every remap ran under g_phys_mutex in every scatter call; with it, xmem_test's split race ("the reader of the views' last pages never faults or misreads") failed in two full Wine runs in a row, where main passed it twice. The value is cached as before #2350's default changed; rt::xmem::reload_remap_release_setting lets test_remap_releases switch it. Two full runs since: no change against main. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/xmem.cpp | 14 +++++++++++--- runtime/shims/xmem.h | 2 ++ runtime/test/xmem_test.cpp | 4 ++++ 3 files changed, 17 insertions(+), 3 deletions(-) (limited to 'runtime/test/xmem_test.cpp') diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 0d982be4b..d6d6f408c 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -1044,10 +1044,16 @@ thread_local const char* t_unmap_cause = "unmap"; // using what names it, and some of what names a copy's address is never rewritten when the copy is retired (a root // view a list resolved while it was recorded, executed after the retirement; a placed buffer view written outside a // console heap). On by default, it freed copies under such views: a GPUVM page fault and a lost device about 40 s -// into the world on an RX 7900 XTX. Read at every remap, so a test can switch it. +// into the world on an RX 7900 XTX. Read once; rt::xmem::reload_remap_release_setting reads it again (for a test). +std::atomic g_remap_releases{-1}; bool remap_releases_enabled() { - char value[2]{}; - return GetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", value, sizeof(value)) == 1 && value[0] == '1'; + int on = g_remap_releases.load(std::memory_order_relaxed); + if (on < 0) { + char value[2]{}; + on = GetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", value, sizeof(value)) == 1 && value[0] == '1'; + g_remap_releases.store(on, std::memory_order_relaxed); + } + return on != 0; } struct RemapReleases; thread_local RemapReleases* t_remap_releases = nullptr; @@ -2423,6 +2429,8 @@ bool host_page(std::uintptr_t address, HostPage& out) { namespace rt::xmem { +void reload_remap_release_setting() { g_remap_releases.store(-1, std::memory_order_relaxed); } + void note_stream_reservation(uintptr_t base, size_t size, uintptr_t caller_rva) { if (caller_rva != 0x1e1d00f && caller_rva != 0x1e1d03e) return; const std::lock_guard physical(g_phys_mutex); diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index 6e0017f2b..d9251c5f0 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -29,6 +29,8 @@ bool copy_page_mappings(std::uint32_t count, const PageBatch* batches, std::uint std::uint32_t pool_pages, std::uint32_t flags); void geometry_aliases(std::uintptr_t va, std::vector& addresses); +// Test seam: LEONIDA_GEOMETRY_REMAP_RELEASE is read again at the next remap. +void reload_remap_release_setting(); bool commit_physical_range(const void* address, std::size_t size); // A lifetime-pinned alias of a contiguous range of the title's writable mapped physical pages. std::shared_ptr pin_mapped_data(const void* address, std::size_t size); diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 61e8732e1..d5e866a76 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -469,16 +469,19 @@ void test_remap_releases(const PhysicalApi& api) { char previous[8]{}; const DWORD had = GetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", previous, sizeof(previous)); SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", nullptr); + rt::xmem::reload_remap_release_setting(); const uint64_t first[kPages] = {pages[0], pages[1], pages[2]}; const uint64_t other[kPages] = {pages[3], pages[2], pages[1]}; check(api.map(window, kPages, first) == window && api.map(window, kPages, other) == window && take().empty(), "remap releases: off by default, a remap releases nothing"); SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", "0"); + rt::xmem::reload_remap_release_setting(); check(api.map(window, kPages, first) == window && take().empty(), "remap releases: LEONIDA_GEOMETRY_REMAP_RELEASE=0 releases nothing"); check(api.map(window, kPages, nullptr) == window && !take().empty() && covers(base, base + 3 * kPage64k), "remap releases: unmapping releases the range whatever the setting"); SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", "1"); + rt::xmem::reload_remap_release_setting(); check(api.map(window, kPages, first) == window && take().empty(), "remap releases: a first mapping of unmapped pages releases nothing"); @@ -513,6 +516,7 @@ void test_remap_releases(const PhysicalApi& api) { "remap releases: unmapping releases the range"); SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", had > 0 && had < sizeof(previous) ? previous : nullptr); + rt::xmem::reload_remap_release_setting(); for (uint64_t i = 0; i < kPages; ++i) watch::release(base + i * kPage64k); watch::unsubscribe(queue); api.free_pages(4, pages); -- cgit v1.2.3 From b0767fd6574e5ec7af617e27c87a3401176154b8 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Thu, 26 Nov 2026 10:43:18 -0500 Subject: d3d12, xmem: remove remap release and the console heap mirror Both came in with #2350 as additions on top of stopgap mechanisms, broke world runs (remap release: a GPUVM page fault and a lost device; the mirror: a GPU hang) and were made opt-in by #2356. They go completely; with both variables unset, main behaves as before. Remap release (LEONIDA_GEOMETRY_REMAP_RELEASE, from 36771ec53): - xmem.cpp: RemapReleases, remap_releases_enabled() and the page recording in unmap_range_locked; the four call sites (XMemMapPhysicalPages, the scatter call, both copy_page_mappings). - xmem.h/xmem.cpp: the test seam rt::xmem::reload_remap_release_setting(). - xmem_test: test_remap_releases (and the title_geometry_watch.h include only it used). - README row, the docs/d3d12_vulkan.md paragraph; comments that named it. Console heap mirror (LEONIDA_HEAP_MIRROR, LEONIDA_HEAP_MIRROR_CHECK, from 746059011): - src/console_heap_copy.h goes. ConsoleHeap::copy is a plain std::uint8_t* again, written with memcpy/memset as before the mirror, including the zeroing site that #2350's merge of #2162 resolved as heap.copy.zero(); the compute-input probe reads it directly again. Without the mirror, view() was the copy itself, so nothing changes. - heap_mirror_enabled(), heap_mirror_check_enabled(), check_console_heap_mirror(), the per-heap check counters and log line, and the test API console_heap_mirror_mismatches() (d3d12_com.h). - Tests console_heap_copy, d3d12_console_heap_mirror, _off and _default with their CMake entries; README rows and the docs/d3d12_vulkan.md sentences. Kept, because other paths use them or main's behaviour with the variable unset depends on them: - LEONIDA_GEOMETRY_HOST and its DeviceState memory-type assert (dc9ef1a0b). - The final copy at retirement (GeometryViews::retire_range's final_copy, "copied at retirement" in the geometry buffers line): XMemFree of a title heap block (free_title_block) reports a release while the block's memory stays committed and readable, so that copy is still made without remap release. Comments now say that instead of naming remaps; geometry_views_test case 15 stays. - forget_pool_span and "retired with their copy" in the title memory line: any retirement (free, decommit, unmap) feeds it. - The release queue's joining of touching ranges (title_geometry_watch.h): unmaps report page runs too; geometry_views_test case 16 stays. - LEONIDA_CONSOLE_RELEASE_FILTER, which predates the mirror; its sweep reads the copy again. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 26 +-- runtime/CMakeLists.txt | 22 --- runtime/README.md | 3 - runtime/shims/d3d12_com.h | 4 - runtime/shims/d3d12_compute_input_probe.h | 6 +- runtime/shims/d3d12_geometry_views.h | 8 +- runtime/shims/d3d12_vulkan_device.cpp | 104 ++---------- runtime/shims/xmem.cpp | 64 ------- runtime/shims/xmem.h | 2 - runtime/src/console_heap_copy.h | 98 ----------- runtime/src/title_geometry_watch.h | 2 +- runtime/test/console_heap_copy_test.cpp | 168 ------------------ runtime/test/d3d12_console_heap_mirror_test.cpp | 216 ------------------------ runtime/test/geometry_views_test.cpp | 10 +- runtime/test/xmem_test.cpp | 95 ----------- 15 files changed, 32 insertions(+), 796 deletions(-) delete mode 100644 runtime/src/console_heap_copy.h delete mode 100644 runtime/test/console_heap_copy_test.cpp delete mode 100644 runtime/test/d3d12_console_heap_mirror_test.cpp (limited to 'runtime/test/xmem_test.cpp') diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 375278169..22515184a 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1737,24 +1737,14 @@ The copies: as VIctory keeps its copies of title memory (approach only). In a world run on the RX 7900 XTX the copies held 4.4-6 GB of VRAM. The cost moves to the bus: the GPU reads every vertex and index of a copy from system memory, so a geometry-heavy pass can take longer; measure frame time with and without it before making it a default. - - **When a copy goes**: a view is retired when its title range is freed, decommitted or unmapped. With - `LEONIDA_GEOMETRY_REMAP_RELEASE=1` (off by default) also when a remap gives one of its pages another frame or - none (`XMemMapPhysicalPages` with pages, the scatter call, `CopyPageMappingsBatchX`; xmem's `RemapReleases`): - the title streams by remapping its pools' frames, and otherwise the copies of what those pages held stay for the - device's life (`evicted 0` in every world run). It is off because a remap leaves the address valid on the - console, and not everything that names a copy's address is rewritten when the copy goes: a root view is - resolved while its list is recorded (`d3d12_com.cpp`, `GraphicsCommandList::address`), so a list recorded before the - retirement and executed after it reads the freed copy, and so does a placed buffer view written outside a - console heap. On by default, it retired 15 010 copies in 40 s of a world run on the - RX 7900 XTX (RADV) and ended it in a GPUVM page fault and a lost device; the same run without it went eight - minutes with no fault. Making it safe needs a copy kept until nothing recorded or written can still name it. - A page mapped again to the frame it had is no change. A retired + - **When a copy goes**: a view is retired when its title range is freed, decommitted or unmapped. A remap of + physical pages retires nothing: the copies follow the new pages through the refresh. A retired view leaves the lookups at once, its alias ranges and translated heap slots are invalidated, its stream-pool extent is forgotten, and its memory is freed only after every ExecuteCommandLists replay in progress at the retirement has recorded its submissions and those have completed (`kAfterExecutes`). Before it leaves the - refresh it is copied once more from its pages if they are readable: a list recorded before a remap that took the - view's address (a root view) reads the new bytes, as on the console. The next view of the range makes a new copy. - `geometry_views_test` cases 14-16 and `xmem_test` (`test_remap_releases`) cover this without a GPU. + refresh it is copied once more from its pages if they are still readable (a heap block freed in memory that + stays committed). The next view of the range makes a new copy. + `geometry_views_test` cases 14-16 cover this without a GPU. - **Which pages changed** since the last refresh: where xmem reserved the title's memory with `MEM_WRITE_WATCH` (`XMemVirtualAlloc`'s ordinary regions and the title's `VirtualAlloc` reservations, not placeholders or physical-page windows), the kernel says (`GetWriteWatch` with reset, its answers kept for every copy over the page: @@ -2062,11 +2052,7 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all arguments for direct and indirect compute dispatches with an inline signature. Bound console descriptor heap base addresses are remapped through `console_descriptor_table_va` so that user SGPRs receive the arena copy's shader virtual address (where GPU descriptor reads land, preventing `READ_INVALID` device loss during world - load), while unshadowed host heaps remain unchanged. The CPU reads that copy too (the release sweep of - `LEONIDA_CONSOLE_RELEASE_FILTER=1`), uncached across PCIe when it is in ReBAR memory. `LEONIDA_HEAP_MIRROR=1` - gives those reads a host-RAM mirror of the copy (`src/console_heap_copy.h`). It is off by default: with it, a - world run on the RX 7900 XTX (RADV) hung in a library compute program about a minute in and lost the device, - and without it the same run went on for more than five minutes. Why is not known yet. An unbound heap contributes + load), while unshadowed host heaps remain unchanged. An unbound heap contributes zero, and rebinding affects later commands. A heap that cannot fit in the inline user data is reported once, and a signature whose compute arguments spill gets nothing written (logged once). Set `LEONIDA_COMPUTE_DIRECT_HEAPS=0` to restore the previous compute arguments. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index be7e48c85..f037b2326 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3732,22 +3732,6 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_unmapped_vsharp_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_unmapped_vsharp COMMAND d3d12_unmapped_vsharp_test) set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_CONSOLE_FIX_US=0") - # The host-RAM mirror of a console heap's GPU copy (src/console_heap_copy.h) agrees with the copy through the first - # refresh, title writes and a filtered release sweep; run again without the mirror, where the copy must not change. - add_executable(d3d12_console_heap_mirror_test test/d3d12_console_heap_mirror_test.cpp shims/d3d12_xs_device.cpp) - target_link_libraries(d3d12_console_heap_mirror_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_console_heap_mirror_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) - target_compile_options(d3d12_console_heap_mirror_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_console_heap_mirror COMMAND d3d12_console_heap_mirror_test) - set_tests_properties(d3d12_console_heap_mirror PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT - "LEONIDA_CONSOLE_FIX_US=0;LEONIDA_CONSOLE_RELEASE_FILTER=1;LEONIDA_HEAP_MIRROR=1;LEONIDA_HEAP_MIRROR_CHECK=1") - add_test(NAME d3d12_console_heap_mirror_off COMMAND d3d12_console_heap_mirror_test) - set_tests_properties(d3d12_console_heap_mirror_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT - "LEONIDA_CONSOLE_FIX_US=0;LEONIDA_CONSOLE_RELEASE_FILTER=1;LEONIDA_HEAP_MIRROR=0") - # The default: no mirror unless LEONIDA_HEAP_MIRROR=1. - add_test(NAME d3d12_console_heap_mirror_default COMMAND d3d12_console_heap_mirror_test) - set_tests_properties(d3d12_console_heap_mirror_default PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT - "LEONIDA_CONSOLE_FIX_US=0;LEONIDA_CONSOLE_RELEASE_FILTER=1") add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -4700,12 +4684,6 @@ if(TARGET Vulkan::Headers) target_compile_options(console_heap_vsharp_slots_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME console_heap_vsharp_slots COMMAND console_heap_vsharp_slots_test) - # Host-RAM mirror of a console resource heap's GPU copy (src/console_heap_copy.h). - add_executable(console_heap_copy_test test/console_heap_copy_test.cpp) - if(WIN32 AND MSVC) - target_compile_options(console_heap_copy_test PRIVATE /W4 /permissive- /utf-8) - endif() - add_test(NAME console_heap_copy COMMAND console_heap_copy_test) # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp) target_link_libraries(vk_host_texture_order_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) diff --git a/runtime/README.md b/runtime/README.md index 5822dba8f..7f02f41e0 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -383,7 +383,6 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. | | `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. | | `LEONIDA_GEOMETRY_HOST` | unset | Where the geometry copies (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) live. Unset or `0`: device-local memory through the BAR while the driver gives it (several GB of VRAM in a world run). `1`: system memory outside VRAM, write-back where the device offers a cached host type; `2`: system memory, write-combined. The GPU then reads every vertex and index of a copy over the bus, which can cost frame time in geometry-heavy passes. A device whose host-visible memory is all device-local (an integrated GPU) keeps its types. The choice is logged once and in the `geometry buffers` line. | -| `LEONIDA_GEOMETRY_REMAP_RELEASE` | unset | Experimental, unsafe in world runs. `1`: a remap of physical pages (`XMemMapPhysicalPages`, the scatter call, `CopyPageMappingsBatchX`) that gives a page another frame, or none, retires the geometry copies over it, as freeing or unmapping it does, so the copies of what the title's stream pools held do not stay for the device's life. A retired copy is copied once more from the new pages if they are readable, then freed once the submissions in progress at the retirement have finished. A remap leaves the address valid, though, and a root view resolved while a list was recorded (executed after the retirement) or a placed buffer view written outside a console heap still names the freed copy: on by default it ended a world run on an RX 7900 XTX in a GPUVM page fault and a lost device. Unset or any other value: a remap retires nothing, and the copies follow the new pages through the refresh. | | `LEONIDA_TITLE_FILL_ASYNC` | unset | Trades correctness for speed. `1` stops device slot 70 views from hashing and filling the texture they name on the title's thread: a texture never filled or known stale is queued for a worker thread that fills one texture at a time. Until then a shader samples the image as it is, empty or a frame behind. | | `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. | | `LEONIDA_TITLE_EVERY_BUDGET_US` | `0` | Microseconds one pass over the textures filled from the title's memory may spend on the textures it visits every pass (mapped by the title, or known stale), resuming where the last pass stopped; the texture that crosses the limit is finished. A mapped texture never filled yet is visited first whatever the limit. `0` visits all of them every pass. It limits the synchronous pass only: with `LEONIDA_TEXTURE_REFRESH_ASYNC=1` the pass runs on the refresh worker, and the limit does not apply. | @@ -425,8 +424,6 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_CONSOLE_GPU_TSHARPS` | on | With `LEONIDA_CONSOLE_HEAP_GPU=1`, the T#s of changed slots are registered by the resolver thread and the refresh only decodes them. `0` registers them on the submitting thread, under the fix budget. | | `LEONIDA_CONSOLE_GPU_RETRY_MS` | `2000` | With `LEONIDA_CONSOLE_HEAP_GPU=1`, how often V# words that got no backing are asked for again, on a timer that bounds the cost per submission. | | `LEONIDA_CONSOLE_GPU_FILTER` | `LEONIDA_CONSOLE_RELEASE_FILTER`'s value | With `LEONIDA_CONSOLE_HEAP_GPU=1`, `1`: a released backing, an alias range that went or a word answered since asks for a rescan of only the slots it touches, not of every V# slot. Overflows and key resets still rescan everything. | -| `LEONIDA_HEAP_MIRROR` | unset | Experimental. `1`: a host-RAM mirror of a console resource heap's copy in the arena (`src/console_heap_copy.h`), so the CPU reads of the copy (the `LEONIDA_CONSOLE_RELEASE_FILTER` sweep) come from host RAM, not uncached device memory across PCIe. Off by default: with it, a world run on an RX 7900 XTX hung in a compute program about a minute in and lost the device; without it the same run went on for more than five minutes. Unset or any other value: no mirror, and the sweep reads the copy. A copy in an import of host memory, and one the `LEONIDA_CONSOLE_HEAP_GPU` pass writes, never has one. | -| `LEONIDA_HEAP_MIRROR_CHECK` | unset | `1`: at every release sweep the mirror is compared with the copy (a read of the whole copy); the first differing slots are logged, and the heap log line counts the checks and differing slots. | | `LEONIDA_CONSOLE_RELEASE_FILTER` | unset | `1`: when a backing is released, only the console-heap slots whose V#s point into it are fixed again (by actual Vulkan address), instead of every V# slot of the heap. The heap log line counts the sweeps, live slots, fixes and full fallbacks. | | `LEONIDA_SHADOW_GPU` | unset | `1`: aliased pages of the slot-133 shadows are copied on the GPU at the start of a submission, from an import of the mapped title section (`VK_EXT_external_memory_host`, per 2 MiB window, kept while xmem's map journal shows no change over it). Destinations outside the arena and pages that do not import are copied by the CPU as before. | | `LEONIDA_SHADOW_GPU_MB` | `1024` | With `LEONIDA_SHADOW_GPU=1`, the MiB of title memory imported for those copies at most. | diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 76e946b47..3bad0b767 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -390,10 +390,6 @@ std::uint64_t device_arena_size(ID3D12Device* device); // Copies `bytes` of the device's GPU address arena at console VA `va` (what shaders read there: a heap's GPU copy, // the null slots after it) into `out`. False without an arena or when the range is not inside it. For tests. bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes); -// The slots whose host-RAM mirror differs from the GPU copy of the console descriptor heap at `console_va` -// (src/console_heap_copy.h), compared now: 0 when they agree, -1 when there is no such heap or it has no mirror. -// For tests. -long long console_heap_mirror_mismatches(ID3D12Device* device, std::uint64_t console_va); // The blocks of device memory that textures share (src/image_memory.h): how many, their bytes, and the textures in // them. For tests. diff --git a/runtime/shims/d3d12_compute_input_probe.h b/runtime/shims/d3d12_compute_input_probe.h index fdec0348e..70ac61e52 100644 --- a/runtime/shims/d3d12_compute_input_probe.h +++ b/runtime/shims/d3d12_compute_input_probe.h @@ -195,7 +195,7 @@ bool gpu_words_now(State& state, std::uint64_t at, std::array& for (const auto& heap : state.console_heaps) { const auto delta = at - heap->shader_va; if (heap->copy && delta <= heap->bytes && sizeof(out) <= heap->bytes - delta) { - std::memcpy(out.data(), heap->copy.gpu() + delta, sizeof(out)); + std::memcpy(out.data(), heap->copy + delta, sizeof(out)); return true; } } @@ -249,7 +249,7 @@ void recheck(State& state) { if (!lock.owns_lock()) std::fputs("[rt] compute-input: after loss, console heaps locked\n", stderr); else for (const auto& heap : state.console_heaps) - if (heap->copy) scan("console", heap->shader_va, heap->copy.gpu(), heap->bytes); + if (heap->copy) scan("console", heap->shader_va, heap->copy, heap->bytes); } { std::unique_lock lock(state.visible_heap_mutex, std::try_to_lock); @@ -294,7 +294,7 @@ Backing descriptor(State& state, std::uint64_t seq, std::size_t list, std::size_ for (const auto& heap : state.console_heaps) { const auto delta = at - heap->shader_va; if (heap->copy && delta <= heap->bytes && sizeof(gpu) <= heap->bytes - delta) { - std::memcpy(gpu.data(), heap->copy.view() + delta, sizeof(gpu)); + std::memcpy(gpu.data(), heap->copy + delta, sizeof(gpu)); have_gpu = true; break; } diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h index ebfab4b74..ab8797ef6 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h @@ -411,10 +411,10 @@ public: // deferring its backing storage reclamation until GPU submissions through `retire_ticket` have completed // (kAfterExecutes: through the submissions of every replay in progress now, see execute_end). // With `final_copy` (a refresh's copy), a ready view whose title range is readable now is copied from it once more - // before it leaves the refresh: a range the title remapped holds new bytes, and a list recorded before the remap - // that took the view's address (a root view) and runs in a submission the view waits for reads those, as it would - // have read them in the console's memory, and as the refresh this retirement replaces would have copied them. - // Freed or unmapped memory is not readable, so such a view keeps what it held. + // before it leaves the refresh: a released range that is still readable (a heap block freed in memory that stays + // committed) may hold new bytes, and a list recorded before the release that runs in a submission the view waits + // for reads those, as it would have read them in the console's memory. Decommitted or unmapped memory is not + // readable, so such a view keeps what it held. template std::size_t retire_range(Address begin, Address end, std::uint64_t retire_ticket = 0, OnRetire&& on_retire = {}, Copy&& final_copy = {}) { diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0b9b211db..96b6fd995 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -67,7 +67,6 @@ #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" #include "../src/title_va_alias.h" -#include "../src/console_heap_copy.h" #include "../src/console_heap_vsharp_slots.h" #include "../src/title_window_plan.h" #include "../src/vulkan_present.h" @@ -2862,8 +2861,8 @@ struct DeviceState { // another queue's replay that translated its slots before this retirement may still name it. A ticket read here // would be one short of this submission, which records its own only after before_execute_ (and with an idle GPU // the view would be reaped in this very call). - // A retired view's last copy is made here from the title's pages as they are now (GeometryViews::retire_range): a - // range the title remapped (xmem's RemapReleases) holds its new bytes, which the refresh below would have copied. + // A retired view's last copy is made here from the title's pages as they are now, when they are still readable + // (GeometryViews::retire_range). // A stream-pool extent it backed leaves pool_spans: the next request for those pages makes a new mapping. void drain_geometry_releases() { if (!context || !geometry.has_pending_reclaim()) return; @@ -4188,10 +4187,7 @@ struct DeviceState { VkDeviceSize guard = 0; // null bytes after the GPU copy (heap_guard_bytes/heap_guard_for), its allocation bool resource_heap = false; // a CBV/SRV/UAV heap; a sampler heap's S#s are copied as written bool imported = false; - // The translated copy shaders read, and its host-RAM mirror (src/console_heap_copy.h): written only through - // copy.write()/copy.zero(), read on the CPU only through copy.view(). - leonida::ConsoleHeapCopy copy; - std::uint64_t mirror_checks = 0, mirror_mismatches = 0; // LEONIDA_HEAP_MIRROR_CHECK, since the last log line + std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap // Keep large scratch allocations out of the low addresses the title can use for its heap. std::unique_ptr scratch; std::uint8_t* input{}; @@ -4370,7 +4366,7 @@ struct DeviceState { } if (empty) heap.empty_slots.insert(std::uint32_t(slot)); else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot)); - heap.copy.write(slot * kDescriptorSize, w, kDescriptorSize); + std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); heap.live_vsharps.set(slot, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); return settled; } @@ -4418,7 +4414,7 @@ struct DeviceState { }(); const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); if (!heap.resource_heap) { - heap.copy.write(offset, heap.input + offset, end - offset); + std::memcpy(heap.copy + offset, heap.input + offset, end - offset); return; } for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; @@ -4438,7 +4434,7 @@ struct DeviceState { std::memcpy(&w3, heap.previous + at + 12, sizeof(w3)); const bool is_buffer_vsharp = !(w3 >> 30); if (heap.fix_over && !is_buffer_vsharp) { - heap.copy.zero(at, kDescriptorSize); + std::memset(heap.copy + at, 0, kDescriptorSize); heap.live_vsharps.clear(slot); ++heap.deferred_fixes; if (!heap.retry[slot]) { @@ -4531,60 +4527,6 @@ struct DeviceState { unbound_tsharp_tracker().note(heap.console_va, offset, words, why); } - // LEONIDA_HEAP_MIRROR=1: a host-RAM mirror of a console heap's copy in the arena (src/console_heap_copy.h), which - // the release sweep reads instead of the copy. Off by default: on, a world run on the RX 7900 XTX hung in a - // compute program about a minute in and lost the device; off, the same run went past five minutes. - static bool heap_mirror_enabled() { - static const bool on = [] { - char value[4] = {}; - return GetEnvironmentVariableA("LEONIDA_HEAP_MIRROR", value, sizeof(value)) == 1 && value[0] == '1'; - }(); - return on; - } - // LEONIDA_HEAP_MIRROR_CHECK=1: the mirror compared with the copy at every release sweep (it reads the whole copy, - // so it costs what the mirror saves), the first slots that differ logged. - static bool heap_mirror_check_enabled() { - static const bool on = [] { - char value[4] = {}; - return GetEnvironmentVariableA("LEONIDA_HEAP_MIRROR_CHECK", value, sizeof(value)) == 1 && value[0] == '1'; - }(); - return on; - } - // The slots whose mirror differs from the copy (0: none, or no mirror); the first few logged, for the first - // sweeps that find any. - std::size_t check_console_heap_mirror(ConsoleHeap& heap) { // console_heap_mutex held - if (!heap.copy.mirrored()) return 0; - constexpr std::size_t kShown = 8; - std::vector slots; - const std::size_t count = heap.copy.mismatches(kDescriptorSize, kShown, slots); - ++heap.mirror_checks; - heap.mirror_mismatches += count; - static std::atomic reports{0}; - if (count && reports.fetch_add(1, std::memory_order_relaxed) < 16) { - std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAP_MIRROR_CHECK: console descriptor heap 0x%llx: %zu slots of " - "the host mirror differ from the copy\n", - static_cast(heap.console_va), count); - for (const std::size_t slot : slots) { - std::uint32_t mirror[8], copy[8]; - std::memcpy(mirror, heap.copy.view() + slot * kDescriptorSize, sizeof(mirror)); - std::memcpy(copy, heap.copy.gpu() + slot * kDescriptorSize, sizeof(copy)); - std::fprintf(stderr, "[rt] d3d12: slot %zu: mirror %08x %08x %08x %08x %08x %08x %08x %08x, copy %08x " - "%08x %08x %08x %08x %08x %08x %08x\n", - slot, mirror[0], mirror[1], mirror[2], mirror[3], mirror[4], mirror[5], mirror[6], mirror[7], - copy[0], copy[1], copy[2], copy[3], copy[4], copy[5], copy[6], copy[7]); - } - } - return count; - } - // Tests: the mirror of the console heap at `console_va` compared with its copy now. -1: no such heap, or no mirror. - long long console_heap_mirror_mismatches(std::uint64_t console_va) { - std::lock_guard lock(console_heap_mutex); - for (const auto& heap : console_heaps) - if (heap->console_va == console_va) - return heap->copy.mirrored() ? static_cast(check_console_heap_mirror(*heap)) : -1; - return -1; - } - void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held if (heap.imported) return; // directly imported sampler heap if (heap.gpu >= 0) return refresh_console_heap_gpu(heap); @@ -4595,7 +4537,7 @@ struct DeviceState { const auto t0 = clock::now(); heap.copied += heap.pages->refresh(); heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { - heap.copy.zero(offset, bytes); + std::memset(heap.copy + offset, 0, bytes); std::memset(heap.previous + offset, 0, bytes); const auto first = std::uint32_t(offset / kDescriptorSize); const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); @@ -4646,16 +4588,13 @@ struct DeviceState { ++heap.rescans; const auto rescan_start = clock::now(); // Even an unchanged title slot may name a buffer released since the last submission. - // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM), - // and read the copy's words from its host-RAM mirror. - if (heap_mirror_check_enabled()) check_console_heap_mirror(heap); - const std::uint8_t* const translated = heap.copy.view(); + // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM). heap.live_vsharps.for_each([&](std::size_t slot) { ++heap.release_candidates; if (filtered) { const auto at = slot * kDescriptorSize; const auto* src = reinterpret_cast(heap.previous + at); - const auto* dst = reinterpret_cast(translated + at); + const auto* dst = reinterpret_cast(heap.copy + at); if (!affected(src, dst) && !affected(src + 4, dst + 4)) return; } ++heap.release_fixes; @@ -4744,13 +4683,6 @@ struct DeviceState { (unsigned long long)heap->release_fixes, (unsigned long long)heap->release_rebases, (unsigned long long)heap->release_full); heap->release_sweeps = heap->release_candidates = heap->release_fixes = heap->release_rebases = heap->release_full = 0; - if (heap_mirror_check_enabled() && heap->copy.mirrored()) - std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAP_MIRROR_CHECK: console descriptor heap 0x%llx: %llu " - "checks, %llu slots differing in all\n", - static_cast(heap->console_va), - static_cast(heap->mirror_checks), - static_cast(heap->mirror_mismatches)); - heap->mirror_checks = heap->mirror_mismatches = 0; if (heap->resource_heap) { std::uint64_t paths[kVsharpPathCount]; for (unsigned i = 0; i < kVsharpPathCount; ++i) @@ -4908,7 +4840,7 @@ struct DeviceState { heap->input = heap->scratch.get(); heap->previous = heap->scratch.get() + bytes; heap->shader_va = offset; - heap->copy.attach(arena.mapped + offset, std::size_t(bytes), heap_mirror_enabled()); + heap->copy = arena.mapped + offset; heap->guard = guard; heap->imported = false; in_arena = true; @@ -4931,7 +4863,7 @@ struct DeviceState { if (heap->scratch) { auto* backing = heap->scratch.get(); if (import_console_heap(*heap, reinterpret_cast(backing), bytes + guard)) { - heap->copy.attach(backing, std::size_t(bytes), false); // host RAM already: no mirror + heap->copy = backing; heap->guard = guard; } heap->input = backing + bytes + guard; @@ -4968,10 +4900,9 @@ struct DeviceState { "a heap index past it reads the arena's next bytes; guard MiB", int(guard >> 20)); heap->shader_va = offset; - // A sampler heap's copy is read by no CPU sweep: no mirror. - heap->copy.attach(arena.mapped + offset, std::size_t(bytes), resource_heap && heap_mirror_enabled()); + heap->copy = arena.mapped + offset; } - heap->copy.zero(0, std::size_t(bytes + heap->guard)); + std::memset(heap->copy, 0, std::size_t(bytes + heap->guard)); if (!heap->input) { heap->mirror.assign(std::size_t(bytes), 0); heap->made.assign(std::size_t(bytes), 0); @@ -5513,7 +5444,6 @@ struct DeviceState { return; } heap.gpu = index; - heap.copy.drop_mirror(); // the pass writes the copy from now on; the CPU neither writes nor reads it heap.vsharp_bits.assign((heap.bytes / kDescriptorSize + 63) / 64, 0); std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx (%llu slots) is " "translated by the pass (heap %d)\n", @@ -21068,14 +20998,6 @@ bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t b return true; } -long long console_heap_mirror_mismatches(ID3D12Device* device, std::uint64_t console_va) { - if (!device) return -1; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - if (!real) real = device; - Device* d = Device::from(real); - return d ? d->state().console_heap_mirror_mismatches(console_va) : -1; -} - namespace { const leonida::BindlessSet* bindless_of(ID3D12Device* device) { if (!device) return nullptr; diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index d6d6f408c..ff2f9b409 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -1033,69 +1033,12 @@ UnmapRecord g_unmaps[kUnmapRecords]; uint64_t g_unmap_count = 0; thread_local const char* t_unmap_cause = "unmap"; -// A remap of physical pages (XMemMapPhysicalPages with pages, the scatter call, CopyPageMappingsBatchX): the pages -// whose frame it took away. unmap_range_locked records each page that held a frame while one is installed (under the -// fault lock: host_heap only, nothing else); when it goes, with g_phys_mutex still held and the fault lock not, every -// page now mapped to another frame than it had (or to none) is reported as released, in runs, so the geometry copies -// over it are retired as over freed or unmapped memory (geometry_writes::note_released, GeometryViews::drain_released): -// the title streams by remapping the frames of its pools, and the copies of what those pages held before were kept -// for the device's life. A page mapped again to the frame it had is no change. -// Off unless LEONIDA_GEOMETRY_REMAP_RELEASE=1: a remap keeps the address valid on the console, so the title goes on -// using what names it, and some of what names a copy's address is never rewritten when the copy is retired (a root -// view a list resolved while it was recorded, executed after the retirement; a placed buffer view written outside a -// console heap). On by default, it freed copies under such views: a GPUVM page fault and a lost device about 40 s -// into the world on an RX 7900 XTX. Read once; rt::xmem::reload_remap_release_setting reads it again (for a test). -std::atomic g_remap_releases{-1}; -bool remap_releases_enabled() { - int on = g_remap_releases.load(std::memory_order_relaxed); - if (on < 0) { - char value[2]{}; - on = GetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", value, sizeof(value)) == 1 && value[0] == '1'; - g_remap_releases.store(on, std::memory_order_relaxed); - } - return on != 0; -} -struct RemapReleases; -thread_local RemapReleases* t_remap_releases = nullptr; -struct RemapReleases { - leonida::host_heap::vector> pages; // address, the frame it had - bool active = false; - RemapReleases() { - if (!t_remap_releases && remap_releases_enabled()) { - t_remap_releases = this; - active = true; - } - } - RemapReleases(const RemapReleases&) = delete; - RemapReleases& operator=(const RemapReleases&) = delete; - ~RemapReleases(); // g_phys_mutex held, the fault lock not -}; struct UnmapCause { const char* was; explicit UnmapCause(const char* cause) : was(std::exchange(t_unmap_cause, cause)) {} ~UnmapCause() { t_unmap_cause = was; } }; -RemapReleases::~RemapReleases() { - if (!active) return; - t_remap_releases = nullptr; - if (pages.empty()) return; - std::sort(pages.begin(), pages.end()); - uintptr_t run_begin = 0, run_end = 0; - for (const auto& [at, frame] : pages) { - const auto now = g_mapped.find(at); - if (now != g_mapped.end() && now->second == frame) continue; // the frame it had: no change - if (run_end == at && run_end > run_begin) { - run_end = at + kPhysicalPageSize; - continue; - } - if (run_end > run_begin) leonida::geometry_writes::note_released(run_begin, run_end); - run_begin = at; - run_end = at + kPhysicalPageSize; - } - if (run_end > run_begin) leonida::geometry_writes::note_released(run_begin, run_end); -} - // With g_fault_lock held exclusively. Unmaps every page in [start, end); the addresses become placeholders again. A // view that reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so // neighbours keep their pages. @@ -1122,7 +1065,6 @@ bool unmap_range_locked(uintptr_t start, uintptr_t end) { // The pages of [start, end) this view held are unmapped now; the ones outside it are mapped again below. for (uintptr_t at = (std::max)(base, start); at < (std::min)(view_end, end); at += kPhysicalPageSize) { if (const auto mapped = g_mapped.find(at); mapped != g_mapped.end()) { - if (t_remap_releases) t_remap_releases->pages.emplace_back(at, mapped->second); note_mapping(mapped->second, at, false); g_mapped.erase(mapped); } @@ -1895,7 +1837,6 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint } drain_fault_notes(); const std::lock_guard lock(g_phys_mutex); - RemapReleases remap_releases; // reported as it goes: after the fault lock, with g_phys_mutex const uintptr_t end = start + page_count * kPhysicalPageSize; const UnmapCause cause(page_array ? "XMemMapPhysicalPages (remap)" : "XMemMapPhysicalPages (unmap)"); if (!page_array) { @@ -2019,7 +1960,6 @@ BOOL scatter_refused(ScatterFailure reason, uintptr_t address, DWORD error) { BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_count, const uint64_t* page_array) { drain_fault_notes(); const std::lock_guard lock(g_phys_mutex); - RemapReleases remap_releases; if (page_count && !addresses) { return scatter_refused(ScatterFailure::missing_addresses, 0, ERROR_INVALID_PARAMETER); } @@ -2097,7 +2037,6 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b return false; } const std::lock_guard lock(g_phys_mutex); - RemapReleases remap_releases; // The destination is usually a GPU-only reservation, which the D3D12 layer reads at its paired CPU view // (title_gpu_views::to_cpu); that view gets the same pages, or it would stay reserved and never readable. const uintptr_t cpu_to = leonida::title_gpu_views::to_cpu(to, pages * kPhysicalPageSize); @@ -2429,8 +2368,6 @@ bool host_page(std::uintptr_t address, HostPage& out) { namespace rt::xmem { -void reload_remap_release_setting() { g_remap_releases.store(-1, std::memory_order_relaxed); } - void note_stream_reservation(uintptr_t base, size_t size, uintptr_t caller_rva) { if (caller_rva != 0x1e1d00f && caller_rva != 0x1e1d03e) return; const std::lock_guard physical(g_phys_mutex); @@ -2503,7 +2440,6 @@ bool copy_page_mappings(std::uint32_t count, const PageBatch* batches, std::uint std::vector frames; drain_fault_notes(); const std::lock_guard lock(g_phys_mutex); - RemapReleases remap_releases; try { for (uint32_t b = 0; b < count; ++b) { const auto& batch = batches[b]; diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index d9251c5f0..6e0017f2b 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -29,8 +29,6 @@ bool copy_page_mappings(std::uint32_t count, const PageBatch* batches, std::uint std::uint32_t pool_pages, std::uint32_t flags); void geometry_aliases(std::uintptr_t va, std::vector& addresses); -// Test seam: LEONIDA_GEOMETRY_REMAP_RELEASE is read again at the next remap. -void reload_remap_release_setting(); bool commit_physical_range(const void* address, std::size_t size); // A lifetime-pinned alias of a contiguous range of the title's writable mapped physical pages. std::shared_ptr pin_mapped_data(const void* address, std::size_t size); diff --git a/runtime/src/console_heap_copy.h b/runtime/src/console_heap_copy.h deleted file mode 100644 index 7eae03aa5..000000000 --- a/runtime/src/console_heap_copy.h +++ /dev/null @@ -1,98 +0,0 @@ -#pragma once -// A console resource heap's translated copy (DeviceState::ConsoleHeap::copy): the bytes shaders read, and a host-RAM -// mirror of them that the CPU reads instead. -// -// The copy lies in the GPU address arena when the import of host memory is not used (arena.mapped + offset), and the -// arena prefers DEVICE_LOCAL | HOST_VISIBLE memory (ReBAR): a CPU read of it is an uncached read across PCIe. The -// release sweep of refresh_console_heap with LEONIDA_CONSOLE_RELEASE_FILTER=1 reads words 0-2 of both V# halves of -// every live V# slot (about 470k in a game run) to decide whether the slot needs fixing, and that read cost -// 0.9-1.0 s a sweep. Every CPU write goes through write() and zero(), which write both the copy and the mirror, so -// view() (the mirror, or the copy when there is none) holds what the GPU reads. -// -// The mirror is made only with LEONIDA_HEAP_MIRROR=1 (off by default: a world run with it hung the GPU). Even then, -// no mirror when the copy is already host RAM (the import of the heap's own scratch), or -// once the copy is written by the GPU pass (LEONIDA_CONSOLE_HEAP_GPU: drop_mirror(); the CPU neither writes nor reads -// the copy then). The mirror covers the heap's bytes only, not the null guard after them (written once, at creation). -// -// LEONIDA_HEAP_MIRROR_CHECK=1: refresh_console_heap compares the mirror with the copy at every release sweep -// (mismatches()) and logs the first slots that differ. - -#include -#include -#include -#include -#include - -namespace leonida { - -class ConsoleHeapCopy { -public: - // `gpu`: the copy shaders read; `bytes`: the heap's bytes (the mirror's size, when `mirrored`). - void attach(std::uint8_t* gpu, std::size_t bytes, bool mirrored) { - gpu_ = gpu; - bytes_ = bytes; - mirror_.clear(); - mirror_.shrink_to_fit(); - if (gpu && mirrored) mirror_.assign(bytes, 0); - } - // The mirror goes; view() is the copy from now on. - void drop_mirror() { - mirror_.clear(); - mirror_.shrink_to_fit(); - } - - explicit operator bool() const noexcept { return gpu_ != nullptr; } - std::uint8_t* gpu() const noexcept { return gpu_; } - bool mirrored() const noexcept { return !mirror_.empty(); } - std::size_t bytes() const noexcept { return bytes_; } - - // What the CPU reads: the mirror, or the copy itself. - const std::uint8_t* view() const noexcept { return mirror_.empty() ? gpu_ : mirror_.data(); } - - // [at, at + n) of the copy, and of the mirror where it reaches. - void write(std::size_t at, const void* bytes, std::size_t n) { - std::memcpy(gpu_ + at, bytes, n); - if (const std::size_t m = mirror_span(at, n)) std::memcpy(mirror_.data() + at, bytes, m); - } - void zero(std::size_t at, std::size_t n) { - std::memset(gpu_ + at, 0, n); - if (const std::size_t m = mirror_span(at, n)) std::memset(mirror_.data() + at, 0, m); - } - - // LEONIDA_HEAP_MIRROR_CHECK: the slots of `slot_bytes` whose mirror bytes differ from the copy's, at most `limit` - // of them in `out` (in ascending order); returns how many slots differ in all. 0 without a mirror. - std::size_t mismatches(std::size_t slot_bytes, std::size_t limit, std::vector& out) const { - out.clear(); - if (mirror_.empty() || !slot_bytes) return 0; - // Read the copy in large blocks: one pass over device memory, compared in host RAM. - constexpr std::size_t kBlock = std::size_t(1) << 16; - std::vector block; - std::size_t count = 0; - const std::size_t step = std::max(slot_bytes, kBlock / slot_bytes * slot_bytes); - for (std::size_t at = 0; at < bytes_; at += step) { - const std::size_t n = std::min(step, bytes_ - at); - block.resize(n); - std::memcpy(block.data(), gpu_ + at, n); - if (!std::memcmp(block.data(), mirror_.data() + at, n)) continue; - for (std::size_t s = 0; s < n; s += slot_bytes) { - const std::size_t k = std::min(slot_bytes, n - s); - if (!std::memcmp(block.data() + s, mirror_.data() + at + s, k)) continue; - if (out.size() < limit) out.push_back((at + s) / slot_bytes); - ++count; - } - } - return count; - } - -private: - std::size_t mirror_span(std::size_t at, std::size_t n) const noexcept { - if (mirror_.empty() || at >= mirror_.size()) return 0; - return std::min(n, mirror_.size() - at); - } - - std::uint8_t* gpu_ = nullptr; - std::size_t bytes_ = 0; - std::vector mirror_; -}; - -} // namespace leonida diff --git a/runtime/src/title_geometry_watch.h b/runtime/src/title_geometry_watch.h index dfb0ae5b5..7283eccd8 100644 --- a/runtime/src/title_geometry_watch.h +++ b/runtime/src/title_geometry_watch.h @@ -75,7 +75,7 @@ inline void note_released(std::uintptr_t begin, std::uintptr_t end) { std::lock_guard lock(q->mutex); bool room = q->ranges.size() < 65536; if (!room) { - // Full: first the ranges that overlap or touch become one (remaps report page runs, often neighbours), and + // Full: first the ranges that overlap or touch become one (unmaps report page runs, often neighbours), and // only when that leaves it more than half full does it all become one covering range. std::sort(q->ranges.begin(), q->ranges.end()); std::size_t kept = 0; diff --git a/runtime/test/console_heap_copy_test.cpp b/runtime/test/console_heap_copy_test.cpp deleted file mode 100644 index 48618170e..000000000 --- a/runtime/test/console_heap_copy_test.cpp +++ /dev/null @@ -1,168 +0,0 @@ -// Portable CPU-only unit test for leonida::ConsoleHeapCopy (runtime/src/console_heap_copy.h): the host-RAM mirror of a -// console heap's translated copy. A plain buffer stands in for the copy in the GPU address arena. Checks that every -// write and zero reaches both, that the null guard past the heap stays out of the mirror, that mismatches() finds a -// write that bypassed the helpers (the LEONIDA_HEAP_MIRROR_CHECK case), and that without a mirror view() is the copy. -// Then times a filtered release sweep over a large heap reading the mirror (the work refresh_console_heap does per -// rescan with LEONIDA_CONSOLE_RELEASE_FILTER=1), for reference; no game data. -#include "../src/console_heap_copy.h" -#include "../src/console_heap_vsharp_slots.h" -#include "../src/descriptor_range_changes.h" - -#include -#include -#include -#include -#include - -#define EXPECT(condition) \ - do { \ - if (!(condition)) { \ - std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ - return 1; \ - } \ - } while (0) - -namespace { - -using leonida::ConsoleHeapCopy; -constexpr std::size_t kSlot = 32; - -int test_writes_reach_both() { - constexpr std::size_t slots = 256, bytes = slots * kSlot, guard = 4096; - std::vector gpu(bytes + guard, 0xCD); - ConsoleHeapCopy copy; - EXPECT(!copy); - copy.attach(gpu.data(), bytes, true); - EXPECT(copy && copy.mirrored() && copy.gpu() == gpu.data() && copy.bytes() == bytes); - EXPECT(copy.view() != gpu.data()); - // Creation: the copy and its guard zeroed; the mirror covers the heap only. - copy.zero(0, bytes + guard); - for (const auto b : gpu) EXPECT(b == 0); - std::vector differ; - EXPECT(copy.mismatches(kSlot, 8, differ) == 0 && differ.empty()); - - std::uint32_t w[8] = {0x1000, 0x20, 64, 0x3fffu, 0, 0, 0, 0}; - for (std::size_t s = 0; s < slots; s += 3) { - w[0] = std::uint32_t(0x1000 + s * 0x40); - copy.write(s * kSlot, w, sizeof(w)); - } - copy.zero(9 * kSlot, kSlot); - copy.zero(64 * kSlot, 32 * kSlot); // a zeroed range of slots - // A sampler heap's whole range copied at once. - std::vector run(5 * kSlot + 7, 0x5A); - copy.write(200 * kSlot + 3, run.data(), run.size()); - EXPECT(std::memcmp(copy.view(), gpu.data(), bytes) == 0); - EXPECT(copy.mismatches(kSlot, 8, differ) == 0); - // Past the heap: the copy's guard only, nothing out of the mirror's bounds. - copy.zero(bytes - kSlot, kSlot + guard); - std::uint32_t tail[8]; - std::memcpy(tail, copy.view() + bytes - kSlot, sizeof(tail)); - for (const auto t : tail) EXPECT(t == 0); - EXPECT(copy.mismatches(kSlot, 8, differ) == 0); - std::puts("writes and zeros reach the copy and the mirror; the guard stays out of the mirror"); - return 0; -} - -int test_mismatch_found() { - constexpr std::size_t slots = 8192, bytes = slots * kSlot; // 256 KiB: more than one compare block - std::vector gpu(bytes, 0); - ConsoleHeapCopy copy; - copy.attach(gpu.data(), bytes, true); - // Writes that bypass the helpers (a missed write site, or the GPU writing the copy). - gpu[5 * kSlot + 4] = 1; - gpu[4000 * kSlot] = 2; - gpu[4001 * kSlot + 31] = 3; - gpu[8191 * kSlot + 16] = 4; - std::vector differ; - EXPECT(copy.mismatches(kSlot, 3, differ) == 4); - EXPECT(differ.size() == 3 && differ[0] == 5 && differ[1] == 4000 && differ[2] == 4001); - EXPECT(copy.mismatches(kSlot, 8, differ) == 4 && differ.size() == 4 && differ[3] == 8191); - std::puts("mismatches() finds writes that bypassed the mirror, in slot order"); - return 0; -} - -int test_without_mirror() { - constexpr std::size_t bytes = 64 * kSlot; - std::vector gpu(bytes, 0); - ConsoleHeapCopy copy; - copy.attach(gpu.data(), bytes, false); // the copy is host RAM already - EXPECT(!copy.mirrored() && copy.view() == gpu.data()); - const std::uint32_t w[8] = {1, 2, 3, 4, 5, 6, 7, 8}; - copy.write(3 * kSlot, w, sizeof(w)); - EXPECT(!std::memcmp(gpu.data() + 3 * kSlot, w, sizeof(w))); - std::vector differ; - EXPECT(copy.mismatches(kSlot, 8, differ) == 0); - - copy.attach(gpu.data(), bytes, true); - EXPECT(copy.mirrored()); - copy.drop_mirror(); // the GPU pass writes the copy from now on - EXPECT(!copy.mirrored() && copy.view() == gpu.data()); - std::puts("without a mirror view() is the copy"); - return 0; -} - -// The filtered release sweep of refresh_console_heap over a heap of 576k slots (18 MiB) with 470k live V# slots, one -// released range touching about 2%: the time per sweep with its words read from host RAM. -int bench_filtered_sweep() { - constexpr std::size_t slots = 576 * 1024, bytes = slots * kSlot; - std::vector previous(bytes, 0), gpu(bytes, 0); - ConsoleHeapCopy copy; - copy.attach(gpu.data(), bytes, true); - leonida::ConsoleHeapVsharpSlots live; - live.reset(slots); - constexpr std::uint64_t kBuffers = 4096, kBufferBytes = 1 << 20, kArena = 1ull << 32; - for (std::size_t s = 0; s < slots; ++s) { - if (s % 11 == 10) continue; // T#s and empty slots - const std::uint64_t base = 0x100000 + (s * 2654435761u % kBuffers) * kBufferBytes + (s % 64) * 256; - std::uint32_t w[8] = {std::uint32_t(base), std::uint32_t(base >> 32) & 0xffffu, 256, 0x00027fac, 0, 0, 0, 0}; - std::memcpy(previous.data() + s * kSlot, w, sizeof(w)); - copy.write(s * kSlot, w, sizeof(w)); - live.set(s, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); - } - leonida::DescriptorRanges backing, aliases; - for (std::uint64_t b = 0; b < kBuffers; b += 50) // about 2% of the buffers released - backing.ranges.push_back({kArena + 0x100000 + b * kBufferBytes, kArena + 0x100000 + (b + 1) * kBufferBytes - 1}); - backing.merge(); - const auto bda = [&](std::uint64_t base) { return kArena + base; }; - const auto affected = [&](const std::uint32_t* src, const std::uint32_t* dst) { - if ((src[3] >> 30) || !src[2]) return false; - const std::uint64_t base = std::uint64_t(src[0]) | (std::uint64_t(src[1] & 0xffff) << 32); - const std::uint64_t fixed = std::uint64_t(dst[0]) | (std::uint64_t(dst[1] & 0xffff) << 32); - const auto stride = (src[1] >> 16) & 0x3fff; - const std::uint64_t n = std::uint64_t(src[2]) * (stride ? stride : 1); - return aliases.overlaps(base, 1) || backing.overlaps(bda(base), n) || (dst[2] && backing.overlaps(bda(fixed), n)); - }; - constexpr int kRuns = 9; - double best = 1e30, first = 0; - std::size_t hits = 0; - for (int run = 0; run < kRuns; ++run) { - hits = 0; - const auto start = std::chrono::steady_clock::now(); - const std::uint8_t* const translated = copy.view(); - live.for_each([&](std::size_t slot) { - const auto at = slot * kSlot; - const auto* src = reinterpret_cast(previous.data() + at); - const auto* dst = reinterpret_cast(translated + at); - if (affected(src, dst) || affected(src + 4, dst + 4)) ++hits; - }); - const double took = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); - if (!run) first = took; - best = std::min(best, took); - } - EXPECT(hits > 0 && hits < live.live_count() / 10); - std::printf("filtered sweep over %zu live slots of %zu MiB, %zu affected: %.2f ms (best of %d, first %.2f), words " - "from the host mirror\n", - live.live_count(), bytes >> 20, hits, best, kRuns, first); - return 0; -} - -} // namespace - -int main() { - if (test_writes_reach_both()) return 1; - if (test_mismatch_found()) return 1; - if (test_without_mirror()) return 1; - if (bench_filtered_sweep()) return 1; - std::puts("ok"); - return 0; -} diff --git a/runtime/test/d3d12_console_heap_mirror_test.cpp b/runtime/test/d3d12_console_heap_mirror_test.cpp deleted file mode 100644 index 3e8f3793f..000000000 --- a/runtime/test/d3d12_console_heap_mirror_test.cpp +++ /dev/null @@ -1,216 +0,0 @@ -// The host-RAM mirror of a console descriptor heap's GPU copy (src/console_heap_copy.h) through a heap's life, with -// LEONIDA_CONSOLE_RELEASE_FILTER=1 (the release sweep reads the mirror to pick the slots to fix): the first refresh, -// slots the title rewrites and zeroes after it, and a released buffer whose V#s the sweep must find and null. After -// each step the GPU copy holds what it should and the mirror agrees with it byte for byte. Run three times by ctest: -// with LEONIDA_HEAP_MIRROR=1 (the mirror), with 0 and with the variable unset (no mirror, the default; the sweep reads -// the copy), where the copy must come out the same. Nothing dispatches through a descriptor. No game data. -#include "vk_test_device.h" -#include "../shims/d3d12_com.h" -#include "../src/gfx10_descriptors.h" - -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -template -struct Ref { - T* p = nullptr; - ~Ref() { reset(); } - void reset() { - if (p) p->Release(); - p = nullptr; - } - T* operator->() const { return p; } -}; - -constexpr UINT kDescriptor = 32; -constexpr UINT kViewBytes = 256; -constexpr UINT kBufferBytes = 64 * 1024; - -D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = bytes; - desc.Height = 1; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - return desc; -} - -leonida::gfx10::BufferWords raw_vsharp(std::uint64_t address) { - leonida::gfx10::Buffer b{}; - b.address = address; - b.num_records = kViewBytes; - b.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); - b.oob_select = leonida::gfx10::OobSelect::raw; - return leonida::gfx10::encode(b); -} - -std::uint64_t base_of(const std::uint32_t* w) { return std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); } -bool zero_size(const std::uint32_t* w) { return base_of(w) == 0 && w[2] == 0; } - -struct Heap { - static constexpr UINT slots = 4096; - static constexpr std::uint64_t bytes = std::uint64_t(slots) * kDescriptor; -}; - -// What a slot of the copy is expected to hold: the buffer it names, or nothing. -enum class Want { a, b, none, zero }; - -int check(ID3D12Device* device, std::uint64_t shader_va, std::uint64_t title, const Want* want, std::uint64_t a_va, - std::uint64_t b_va, bool mirrored, const char* step) { - static std::uint32_t copy[Heap::slots][kDescriptor / 4]; - EXPECT(rt::d3d12::read_arena(device, shader_va, copy, sizeof(copy))); - for (UINT s = 0; s < Heap::slots; ++s) { - const std::uint32_t* w = copy[s]; - bool ok = true; - switch (want[s]) { - case Want::a: ok = base_of(w) >= a_va && base_of(w) < a_va + kBufferBytes && w[2] == kViewBytes; break; - case Want::b: ok = base_of(w) >= b_va && base_of(w) < b_va + kBufferBytes && w[2] == kViewBytes; break; - case Want::none: ok = zero_size(w); break; - case Want::zero: for (int i = 0; i < 8; ++i) ok = ok && !w[i]; break; - } - if (!ok) { - std::fprintf(stderr, "%s: slot %u holds %08x %08x %08x %08x, wanted %d\n", step, s, w[0], w[1], w[2], w[3], - int(want[s])); - return 1; - } - } - const long long differ = rt::d3d12::console_heap_mirror_mismatches(device, title); - if (mirrored) EXPECT(differ == 0); - else EXPECT(differ == -1); - std::printf("%s: copy as expected, %s\n", step, mirrored ? "mirror agrees with it" : "no mirror"); - return 0; -} - -int run(ID3D12Device* device, bool mirrored) { - const D3D12_COMMAND_QUEUE_DESC queue_desc{}; - Ref queue; - Ref fence; - EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - UINT64 fence_value = 0; - Ref allocator; - Ref list; - EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - EXPECT(SUCCEEDED(list->Close())); - ID3D12CommandList* lists[] = {list.p}; - const auto submit = [&]() -> int { // every submission refreshes the console heaps first - queue->ExecuteCommandLists(1, lists); - EXPECT(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr))); - return 0; - }; - - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const auto desc = buffer_desc(kBufferBytes); - Ref a, b; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&a.p)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&b.p)))); - const std::uint64_t a_va = a->GetGPUVirtualAddress(), b_va = b->GetGPUVirtualAddress(); - EXPECT(a_va && b_va); - - auto* title = static_cast(VirtualAlloc(nullptr, Heap::bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - EXPECT(title); - static Want want[Heap::slots]; - const auto put = [&](UINT slot, std::uint64_t va, Want w) { - const auto words = raw_vsharp(va); - std::memcpy(title + slot * kDescriptor, words.data(), sizeof(words)); - want[slot] = w; - }; - for (UINT s = 0; s < Heap::slots; ++s) want[s] = Want::zero; - // Before the heap exists: slots 0-1023 name A, 1024-2047 B, the rest empty but for one data slot. - for (UINT s = 0; s < 1024; ++s) put(s, a_va + (s % 256) * kViewBytes, Want::a); - for (UINT s = 1024; s < 2048; ++s) put(s, b_va + (s % 256) * kViewBytes, Want::b); - const std::uint32_t data[8] = {0x12345000u, 0x00007777u, 0x00000400u, 0x40000000u, 1, 2, 3, 4}; - std::memcpy(title + 3000 * kDescriptor, data, sizeof(data)); - want[3000] = Want::none; // its descriptor half null in the copy (fix_console_slot) - - const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, Heap::slots, - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - Ref heap; - const auto title_va = reinterpret_cast(title); - EXPECT(SUCCEEDED(rt::d3d12::create_console_descriptor_heap(device, &heap_desc, title_va, Heap::bytes, - IID_PPV_ARGS(&heap.p)))); - D3D12_DESCRIPTOR_HEAP_DESC got{}; - D3D12_GPU_VIRTUAL_ADDRESS shader_va = 0; - EXPECT(rt::d3d12::descriptor_heap_info(heap.p, got, shader_va)); - if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "first refresh")) return 1; - - // The title rewrites slots after the heap is made (the write watch finds them): a slot of B now names A, new V#s - // past what it filled, and a page of A's slots zeroed (128 slots). - put(1500, a_va + 0x400, Want::a); - for (UINT s = 2048; s < 2112; ++s) put(s, b_va + (s % 256) * kViewBytes, Want::b); - std::memset(title + 128 * kDescriptor, 0, 4096); - for (UINT s = 128; s < 256; ++s) want[s] = Want::zero; - if (submit()) return 1; - if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "title writes")) return 1; - - // A goes: the release sweep (filtered: only the V#s naming A) nulls the slots that name it, and only those. Its - // memory is given back once its GPU work retires, so a few submissions may pass first. - a.reset(); - for (UINT s = 0; s < Heap::slots; ++s) - if (want[s] == Want::a) want[s] = Want::none; - bool nulled = false; - for (int pass = 0; pass < 32 && !nulled; ++pass) { - if (submit()) return 1; - std::uint32_t w[8]; - EXPECT(rt::d3d12::read_arena(device, shader_va + 1500 * kDescriptor, w, sizeof(w))); - nulled = zero_size(w); - } - EXPECT(nulled); - if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "A released")) return 1; - - heap.reset(); - VirtualFree(title, 0, MEM_RELEASE); - return 0; -} - -} // namespace - -int main() { - char value[4] = {}; - // Only LEONIDA_HEAP_MIRROR=1 mirrors: unset (the default) and 0 must leave the heap without one. - const bool mirrored = GetEnvironmentVariableA("LEONIDA_HEAP_MIRROR", value, sizeof(value)) == 1 && value[0] == '1'; - vktest::Device d; - const auto status = d.initialize(); - if (status == vktest::DeviceStatus::unavailable) { - std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); - return 77; - } - EXPECT(status == vktest::DeviceStatus::ready); - { - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.buffer_device_address = true; - info.subgroup = d.subgroup; - Ref device; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); - EXPECT(rt::d3d12::device_arena_size(device.p) > 0); - if (run(device.p, mirrored)) return 1; - } - if (d.validation_errors()) { - std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); - return 1; - } - std::puts("ok"); - return 0; -} diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp index d1e9a07d8..773360dd5 100644 --- a/runtime/test/geometry_views_test.cpp +++ b/runtime/test/geometry_views_test.cpp @@ -18,7 +18,7 @@ // completed (a ticket read in the drain reaps it at once); its answers made without an alias are invalidated // (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device; // 14. LEONIDA_GEOMETRY_HOST picks a system-memory type (write-back for 1, write-combined for 2), never the BAR; -// 15. a retired view is copied once more from its pages when they are readable (a remap), not when they are not; +// 15. a retired view is copied once more from its pages when they are readable, not when they are not; // 16. a full release queue joins touching ranges before it collapses to one covering range. #include @@ -569,15 +569,15 @@ int main() { _putenv_s("LEONIDA_GEOMETRY_HOST", ""); check(g_live_buffers == 0, "the memory-type views free their blocks"); - // 15. A retired view is copied once more from the title's pages when they are readable (a remap gave them new - // bytes), and keeps what it held when they are not (freed or unmapped). + // 15. A retired view is copied once more from the title's pages when they are readable (they hold new bytes), + // and keeps what it held when they are not (decommitted or unmapped). rt::d3d12::GeometryViews last; std::memset(host_title, 0x11, kView); const std::uint64_t va_l = last.resolve(device, hbase, kView, copy); std::uint64_t host_l = 0, bytes_l = 0; check(va_l && last.lookup(device.arena.address + va_l, host_l, bytes_l), "a view to retire"); auto* held = reinterpret_cast(host_l); - // The remapped pages' bytes: the watched tiles are opened first (no fault handler here). + // The pages' new bytes: the watched tiles are opened first (no fault handler here). leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open); std::memset(host_title, 0x22, kView); g_copies.clear(); @@ -600,7 +600,7 @@ int main() { check(last.reap(device, 2) == 2 && last.bytes() == 0, "both are freed at their tickets"); last.release(device); - // 16. A full release queue first joins ranges that touch (remaps report page runs): 65536 neighbouring ranges + // 16. A full release queue first joins ranges that touch (unmaps report page runs): 65536 neighbouring ranges // and one apart from them are two ranges, not one covering everything between them. rt::d3d12::GeometryViews coalesce; check(coalesce.resolve(device, hbase, kView, copy) != 0, "a view to watch the pages"); diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index d5e866a76..79f655412 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -31,7 +31,6 @@ #include "startup_trace.h" #include "xmem.h" #include "../src/title_page_watch.h" -#include "../src/title_geometry_watch.h" // The process heap as test_heap_lock_faults needs it (the same gate as d3d12_existing_heap_test's): an allocation that // waits while a thread holds the heap's lock. The NT heap's low-fragmentation front end serves most small sizes @@ -430,99 +429,6 @@ struct PhysicalApi { XMemMapPhysicalPagesScatterFn scatter; }; -// A remap that gives watched pages another frame reports them released (geometry_writes::note_released), so the -// geometry copies of what they held are retired; a page mapped again to the frame it had is no change. Through -// XMemMapPhysicalPages, the scatter call and CopyPageMappingsBatchX. -void test_remap_releases(const PhysicalApi& api) { - namespace watch = leonida::geometry_writes; - constexpr uint64_t kPages = 3; - auto* const window = static_cast(api.virtual_alloc( - nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); - uint64_t pages[4]{}; - uint64_t count = 4; - if (!window || api.allocate(0x280, &count, pages) != TRUE || count != 4) { - check(false, "remap releases: a window and four physical pages"); - return; - } - const auto base = reinterpret_cast(window); - watch::ReleaseQueue queue; - watch::subscribe(queue); - for (uint64_t i = 0; i < kPages; ++i) watch::acquire(base + i * kPage64k); // as a geometry copy over the pages - std::vector> released; - const auto take = [&] { - watch::take_released(queue, released); - return released; - }; - const auto covers = [&](uintptr_t from, uintptr_t to) { - for (const auto& [lo, hi] : released) - if (lo <= from && hi >= to) return true; - return false; - }; - const auto any_overlap = [&](uintptr_t from, uintptr_t to) { - for (const auto& [lo, hi] : released) - if (lo < to && hi > from) return true; - return false; - }; - - // Off by default: a remap keeps the address valid, and a root view recorded before it (or a placed buffer view) - // names the copy's address after it, so a copy freed then is read by the GPU (a page fault and a lost device). - char previous[8]{}; - const DWORD had = GetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", previous, sizeof(previous)); - SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", nullptr); - rt::xmem::reload_remap_release_setting(); - const uint64_t first[kPages] = {pages[0], pages[1], pages[2]}; - const uint64_t other[kPages] = {pages[3], pages[2], pages[1]}; - check(api.map(window, kPages, first) == window && api.map(window, kPages, other) == window && take().empty(), - "remap releases: off by default, a remap releases nothing"); - SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", "0"); - rt::xmem::reload_remap_release_setting(); - check(api.map(window, kPages, first) == window && take().empty(), - "remap releases: LEONIDA_GEOMETRY_REMAP_RELEASE=0 releases nothing"); - check(api.map(window, kPages, nullptr) == window && !take().empty() && covers(base, base + 3 * kPage64k), - "remap releases: unmapping releases the range whatever the setting"); - SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", "1"); - rt::xmem::reload_remap_release_setting(); - - check(api.map(window, kPages, first) == window && take().empty(), - "remap releases: a first mapping of unmapped pages releases nothing"); - check(api.map(window + kPage64k, 1, &pages[1]) == window + kPage64k && take().empty(), - "remap releases: a page mapped again to the frame it has is no change"); - check(api.map(window + kPage64k, 1, &pages[3]) == window + kPage64k && !take().empty() && - covers(base + kPage64k, base + 2 * kPage64k) && !any_overlap(base, base + kPage64k) && - !any_overlap(base + 2 * kPage64k, base + 3 * kPage64k), - "remap releases: a page given another frame is released, its neighbours are not"); - const uint64_t rotated[kPages] = {pages[2], pages[0], pages[1]}; - check(api.map(window, kPages, rotated) == window && !take().empty() && covers(base, base + 3 * kPage64k), - "remap releases: a run given other frames is released whole"); - const uint64_t partly[kPages] = {pages[2], pages[3], pages[1]}; - check(api.map(window, kPages, partly) == window && !take().empty() && - covers(base + kPage64k, base + 2 * kPage64k) && !any_overlap(base, base + kPage64k) && - !any_overlap(base + 2 * kPage64k, base + 3 * kPage64k), - "remap releases: of a remapped run, only the page whose frame changed is released"); - void* const last = window + 2 * kPage64k; - check(api.scatter(&last, 1, &pages[0]) == TRUE && !take().empty() && - covers(base + 2 * kPage64k, base + 3 * kPage64k) && !any_overlap(base, base + 2 * kPage64k), - "remap releases: the scatter call releases the page it gives another frame"); - check(api.scatter(&last, 1, &pages[0]) == TRUE && take().empty(), - "remap releases: the scatter call with the frame the page has releases nothing"); - // CopyPageMappingsBatchX: page 0 gets the frame at page 1 (kind 0 from a pool at the window itself). - const rt::xmem::PageRange range{0, 1, 1}; - const rt::xmem::PageBatch batch{base, 1, &range}; - check(rt::xmem::copy_page_mappings(1, &batch, base, kPages, 0) && !take().empty() && - covers(base, base + kPage64k) && !any_overlap(base + kPage64k, base + 3 * kPage64k), - "remap releases: CopyPageMappingsBatchX releases the page it gives another frame"); - - check(api.map(window, kPages, nullptr) == window && !take().empty() && covers(base, base + 3 * kPage64k), - "remap releases: unmapping releases the range"); - SetEnvironmentVariableA("LEONIDA_GEOMETRY_REMAP_RELEASE", - had > 0 && had < sizeof(previous) ? previous : nullptr); - rt::xmem::reload_remap_release_setting(); - for (uint64_t i = 0; i < kPages; ++i) watch::release(base + i * kPage64k); - watch::unsubscribe(queue); - api.free_pages(4, pages); - VirtualFree(window, 0, MEM_RELEASE); -} - // Physical pages in a 64 KiB-page window, as the measured callers use them: reserve a window, allocate pages, map them, // remap them elsewhere and in another order, unmap, free. void test_physical_pages(const PhysicalApi& api) { @@ -2793,7 +2699,6 @@ int main(int argc, char** argv) { // Keep the direct SEC_RESERVE control ahead of the first physical allocation, which installs xmem's VEH. g_section_write_control = measure_section_write_control(); test_physical_pages(physical); - test_remap_releases(physical); if (argc == 2 && std::strcmp(argv[1], "--file-pools") == 0) { test_placeholders(physical); print_result(); -- cgit v1.2.3