diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 375278169a..22515184a0 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 be7e48c858..f037b2326c 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 5822dba8f8..7f02f41e05 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 76e946b47b..3bad0b7671 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 fdec0348e3..70ac61e52c 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 ebfab4b74e..ab8797ef65 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h @@ -411,10 +411,10 @@ class GeometryViews { // 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 0b9b211dbb..96b6fd9958 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 d6d6f408c4..ff2f9b4094 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 d9251c5f0e..6e0017f2ba 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 7eae03aa52..0000000000 --- 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 dfb0ae5b52..7283eccd81 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 48618170e5..0000000000 --- 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 3e8f3793ff..0000000000 --- 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 d1e9a07d88..773360dd52 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 d5e866a767..79f6554128 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();