From 84db5cd02736759eab9ffb4deedc98c52027c050 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Thu, 26 Nov 2026 14:47:29 -0500 Subject: [PATCH] d3d12: console heap slots record what their V#s resolved to; a release re-fixes only the slots naming it (RT-VSHARP-SLOT-RECORDS) After any arena release, title-window or geometry block destroyed, or alias change, the next submission walked every live V# slot of the console heap (about 580,000 in world runs), reading each from the copy in ReBAR VRAM: 1.1-1.5 s a walk whatever the scene, about 2.9 s of a 4.6 s frame. It existed only because nothing recorded which slot resolved into which backing. Each V# half of a console resource heap's copy now has a record in host RAM (src/console_heap_slot_records.h): the title's base and span, the device address its copy names, and whether it resolved or waits. Two indexes (by base, by target; per power-of-two span class and 64 KiB-or-larger granule) find the halves near a range. fix_console_slot, the only writer of a slot's copy, writes them; a zeroed range, a deferred slot and a rewritten slot drop theirs; a destroyed heap takes them with it. Releases (backing(), title_block_gone), alias ranges removed or replaced (TitleVaAliases tells its listeners as it happens, forget_copy included) and additions (backings, alias ranges, title memory) go on an unbounded per-device list. refresh_console_heaps takes it whole; every heap re-fixes exactly the slots it touches: a release or removal every half naming the range, an addition the waiting halves over it. A new heap log line gives the changes, slots looked at, slots fixed again and ms per submission. Removed: the live_vsharps walk and its bitset (console_heap_vsharp_slots.h and its test), the release generation checks (released_backings, TitleVaAliases::invalidations), LEONIDA_CONSOLE_RELEASE_FILTER, the 4,096-entry DescriptorRangeChanges ring with its full-sweep overflow and changed_ranges(), the empty-slot probe and retry_unmapped_slots (unreachable: nothing set its flag). LEONIDA_CONSOLE_GPU_FILTER now defaults to unset instead of the removed variable's value. The T# retries (retry_console_slots) stay. Tests: console_heap_slot_records_test (portable): releasing a buffer 10 of 60,010 slots name looks at 10 entries and fixes 10 slots; an alias moved, removed and added back; overwritten and zeroed slots; partial overlap; two slots on one backing; a buffer back; a refused alias copy backed later; a large span; a destroyed heap; and 400 random rounds compared with a full re-resolution of every slot. d3d12_unmapped_vsharp_test now expects all 128 waiting slots restored at the first submission after their alias comes (was: 16 by the probe in 64 submissions), none after it goes, and the slots naming a released buffer null. title_va_alias_test and geometry_views_test check the listener in place of the ring. Linux ctest 113/113; Windows suite under Wine (clang-cl, iGPU, RADV) equal to main 2d43417d4 test by test. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 14 +- docs/running.md | 2 +- runtime/CMakeLists.txt | 8 +- runtime/README.md | 3 +- runtime/shims/d3d12_vulkan_device.cpp | 375 ++++++++---------- runtime/src/console_heap_slot_records.h | 227 +++++++++++ runtime/src/console_heap_vsharp_slots.h | 115 ------ runtime/src/descriptor_range_changes.h | 46 --- runtime/src/title_va_alias.h | 47 ++- .../test/console_heap_slot_records_test.cpp | 347 ++++++++++++++++ .../test/console_heap_vsharp_slots_test.cpp | 334 ---------------- runtime/test/d3d12_unmapped_vsharp_test.cpp | 78 +++- runtime/test/geometry_views_test.cpp | 26 +- runtime/test/title_va_alias_test.cpp | 57 ++- 14 files changed, 909 insertions(+), 770 deletions(-) create mode 100644 runtime/src/console_heap_slot_records.h delete mode 100644 runtime/src/console_heap_vsharp_slots.h delete mode 100644 runtime/src/descriptor_range_changes.h create mode 100644 runtime/test/console_heap_slot_records_test.cpp delete mode 100644 runtime/test/console_heap_vsharp_slots_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 23b758897d..f727021287 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2081,8 +2081,18 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all heap pointers read by the mesh and pixel stages after a rebind. `d3d12_mesh_test` checks the recorded dwords for a vertex draw, a resource-only rebind, a signature ending at s30 and one on the s0 layout. Set `LEONIDA_GRAPHICS_DIRECT_HEAPS=0` to restore the previous draw arguments. - Missing console V# backing leaves a settled zero descriptor. Every 32 submissions a heap probes up to - eight of these slots in round-robin order, including independent UAV-counter failures. + Missing console V# backing leaves a zero descriptor in the copy. Each V# half of a console resource heap's copy + (the buffer V# and the UAV counter) has a record in host RAM of what it resolved to: the title's base and span, + the device address its copy names, and whether it resolved or waits (`src/console_heap_slot_records.h`, written + only by `fix_console_slot`). Two indexes find the halves near a range, by base and by target, per power-of-two + span class and 64 KiB-or-larger granule. Releases (a backing, a title-window or geometry block), alias ranges + removed or replaced (`TitleVaAliases` tells its listeners as it happens, `forget_copy` included) and additions + (a backing, an alias range, title memory) go on an unbounded per-device list; at the next submission each heap + fixes again exactly the slots whose records a change touches: a release or removal every half naming it, an + addition the waiting halves over it. Nothing walks the heap or reads the copy for this. A zeroed range, a slot + the title rewrote and a heap destroyed drop their records. `console_heap_slot_records_test` checks that a release + of a buffer 10 of 60,010 slots name looks at those 10, and compares the copy with a full re-resolution through + random writes, releases, additions and alias changes. Console resource heap copies and shader-visible CBV/SRV/UAV heaps with at least 65,536 slots request 64 MiB of zeroed padding after their last descriptor. `LEONIDA_HEAP_GUARD_MB` sets the padding in MiB (0 disables it). When arena space is tight, allocation can fall back to the heap alone. Only indices diff --git a/docs/running.md b/docs/running.md index 77887d23d3..161e3153dc 100644 --- a/docs/running.md +++ b/docs/running.md @@ -69,7 +69,7 @@ reasons behind each step: [linux_proton.md](linux_proton.md#amd-on-linux-what-go | `LEONIDA_TITLE_WATCHDOG=0`, `LEONIDA_TITLE_WATCHDOG_KICK=,` | the title's hang watchdog ([above](#settings-every-platform-needs)) | | `LEONIDA_DEVICE_TYPE=6`, `LEONIDA_MAP_READBACK=1`, `LEONIDA_FRAME_PACING=1`, `LEONIDA_PRESENT_NO_TEAR=1` | taken over from the NVIDIA report below; their effect on AMD was not measured one by one | | `LEONIDA_ARENA_MB=4095`, `LEONIDA_TITLE_WINDOWS_MB=4096`, `LEONIDA_GEOMETRY_MB=6144` | room for the title's buffers in the world | - | `LEONIDA_CONSOLE_RELEASE_FILTER=1`, `LEONIDA_SHADOW_ALIAS_MS=5000`, `LEONIDA_CONSOLE_FIX_US=0` | carried from earlier boot runs; their effect here was not measured one by one | + | `LEONIDA_SHADOW_ALIAS_MS=5000`, `LEONIDA_CONSOLE_FIX_US=0` | carried from earlier boot runs; their effect here was not measured one by one | | `LEONIDA_DEVICE_FAULT=1` | a device-loss report if the GPU hangs | | `LEONIDA_KEYBOARD_PAD=always` | the keyboard as the pad | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 566a8a0730..93993e88bb 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -4700,12 +4700,12 @@ if(TARGET Vulkan::Headers) target_compile_options(title_window_plan_bounds_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME title_window_plan_bounds COMMAND title_window_plan_bounds_test) - # Host-RAM bitset of live console resource-heap V# slots (src/console_heap_vsharp_slots.h). - add_executable(console_heap_vsharp_slots_test test/console_heap_vsharp_slots_test.cpp) + # What each console resource-heap V# resolved to, and the slots a change touches (src/console_heap_slot_records.h). + add_executable(console_heap_slot_records_test test/console_heap_slot_records_test.cpp) if(WIN32 AND MSVC) - target_compile_options(console_heap_vsharp_slots_test PRIVATE /W4 /permissive- /utf-8) + target_compile_options(console_heap_slot_records_test PRIVATE /W4 /permissive- /utf-8) endif() - add_test(NAME console_heap_vsharp_slots COMMAND console_heap_vsharp_slots_test) + add_test(NAME console_heap_slot_records COMMAND console_heap_slot_records_test) # A slot-133 shadow keeps a GPU write until the title's bytes under it change (src/shadow_keep.h). add_executable(shadow_keep_test test/shadow_keep_test.cpp) if(WIN32 AND MSVC) diff --git a/runtime/README.md b/runtime/README.md index 1158c15424..97df9a749a 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -425,8 +425,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_CONSOLE_HEAP_ARENA` | unset | With `LEONIDA_CONSOLE_HEAP_GPU=1`, `1` puts a console heap's GPU copy and its guard in the arena (device-local where the device has ReBAR) instead of an import of host memory. No room in the arena: the import. | | `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_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_CONSOLE_GPU_FILTER` | unset | 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_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. | | `LEONIDA_SHADOW_JOIN` | unset | `1`: pieces of one shadow copy job that continue where the one before ended, in the pages and in the copy, are one copy (one GPU region); one the GPU refuses is copied by the CPU whole. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index b03081c7ed..4baf8f01c0 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -68,7 +68,7 @@ #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" #include "../src/title_va_alias.h" -#include "../src/console_heap_vsharp_slots.h" +#include "../src/console_heap_slot_records.h" #include "../src/title_window_plan.h" #include "../src/vulkan_present.h" #include "../src/vulkan_device_filter.h" @@ -3841,36 +3841,67 @@ struct DeviceState { } // Indexed by actual Vulkan address, never by a placed buffer's CPU address. - static bool filter_heap_releases() { - static const bool on = [] { - const auto* v = std::getenv("LEONIDA_CONSOLE_RELEASE_FILTER"); - return v && std::strcmp(v, "1") == 0; - }(); - return on; - } - leonida::DescriptorRangeChanges backing_changes; - std::atomic released_backings{}; std::atomic backing_generation{}; // every add and release std::mutex backing_mutex; leonida::BufferVaIndex gpu_backings; + + // What changed for the console heaps' slot records (ConsoleHeap::records) since the last submission: backings and + // copies released or added, alias ranges removed or added, title memory added. Unbounded: every change is applied + // at the next refresh_console_heaps, which takes the whole list. Written from any thread, under the lock of what + // changed (backing_mutex, the alias table's); slot_change_mutex is taken last and nothing is taken under it. + // Nothing is kept before a console resource heap with a CPU copy exists (no slot has a record then). + std::mutex slot_change_mutex; + std::vector slot_changes; + std::atomic slot_records_live{false}; + void note_slot_change(leonida::SlotChange::Kind kind, std::uint64_t lo, std::uint64_t bytes) { + if (!bytes || !slot_records_live.load(std::memory_order_acquire)) return; + const std::uint64_t hi = lo + bytes < lo ? UINT64_MAX : lo + bytes; + std::lock_guard lock(slot_change_mutex); + slot_changes.push_back({kind, lo, hi}); + } + // A device range [address, address + bytes) as the V# bases that name it directly: arena offsets in the V#'s 48 + // bits (a buffer below the arena, as sign-extended offsets, vsharp_address). Nothing for a range no V# reaches. + void note_slot_source_added(VkDeviceAddress address, std::uint64_t bytes) { + constexpr std::uint64_t mask = (1ull << 48) - 1; + const std::uint64_t offset = address - arena.address; + if (offset <= mask) note_slot_change(leonida::SlotChange::source_added, offset, bytes); + else if (offset >= ~(mask >> 1)) note_slot_change(leonida::SlotChange::source_added, offset & mask, bytes); + } + // The alias table's changes (TitleVaAliases::add_listener), under its lock. + static void alias_changed(void* device, leonida::TitleVaAliases::Change change, std::uint64_t title_va, + std::uint64_t bytes, std::uint64_t shader_va) { + auto& self = *static_cast(device); + using Change = leonida::TitleVaAliases::Change; + if (change == Change::removed) { + // What resolved through the range (by its base), and what names its copy (by the copy's address). + self.note_slot_change(leonida::SlotChange::source_gone, title_va, bytes); + self.note_slot_change(leonida::SlotChange::target_gone, self.arena.address + shader_va, bytes); + } else { + self.note_slot_change(leonida::SlotChange::source_added, title_va, bytes); + } + } + // A title-window or geometry-copy block was destroyed (TitleBufferWindows::destroy_block; its GPU work completed): // as for a released backing, the backed table cuts it and the key entries and heap slots answering into it go at // the next refresh, so no table names the freed memory. void title_block_gone(VkDeviceAddress address, VkDeviceSize bytes) { std::lock_guard lock(backing_mutex); - if (filter_heap_releases()) backing_changes.record(address, bytes); backing_generation.fetch_add(1, std::memory_order_relaxed); - released_backings.fetch_add(1, std::memory_order_release); + note_slot_change(leonida::SlotChange::target_gone, address, bytes); if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); } void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) { std::lock_guard lock(backing_mutex); - if (filter_heap_releases()) backing_changes.record(address, bytes); backing_generation.fetch_add(1, std::memory_order_relaxed); - if (add) gpu_backings.insert(address, bytes, id); - else { + if (add) { + gpu_backings.insert(address, bytes, id); + // A V# that named this range before it was backed, directly or through an alias, can resolve now. + note_slot_change(leonida::SlotChange::target_added, address, bytes); + note_slot_source_added(address, bytes); + } else { gpu_backings.erase(address, id); - released_backings.fetch_add(1, std::memory_order_release); + // The heap slots whose copy names it are fixed again at the next refresh. + note_slot_change(leonida::SlotChange::target_gone, address, bytes); // LEONIDA_CONSOLE_HEAP_GPU: the key entries answering into it go at the next refresh. if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); } @@ -3879,8 +3910,11 @@ struct DeviceState { enum class VsharpPath { table, shadow, scratch }; enum class VsharpResult { unchanged, rebased, empty }; + // `refused` (when given): for an answer of 0, the copy an alias range named that was not backed (0: none), so the + // console heap's slot record is found again when a backing is added there. uint64_t vsharp_address(uint64_t base, uint64_t bytes, leonida::TitleVaAliases::Kind kind = leonida::TitleVaAliases::created_view, - bool make_window = true, bool try_geometry = false) { + bool make_window = true, bool try_geometry = false, uint64_t* refused = nullptr) { + if (refused) *refused = 0; if (!base || !bytes) return 0; auto& aliases = leonida::title_va_aliases(); constexpr uint64_t mask = (1ull << 48) - 1; @@ -3907,7 +3941,10 @@ struct DeviceState { const auto path = [this](unsigned p) { vsharp_paths[p].fetch_add(1, std::memory_order_relaxed); }; uint64_t to{}, room{}; if (aliases.range_of(base, to, room)) { - if (!to || room < bytes || !backed(to)) return path(1), 0; + if (!to || room < bytes || !backed(to)) { + if (refused) *refused = to; + return path(1), 0; + } aliases.note_translation(kind); return path(0), to; } @@ -3927,6 +3964,7 @@ struct DeviceState { uint64_t mapped{}; if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to)) return path(4), to; + if (refused) *refused = to; } return path(5), 0; } @@ -3973,7 +4011,12 @@ struct DeviceState { } } - VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) { + // What fix_vsharp resolved a V# to, for a console heap's slot record (ConsoleHeapSlotRecords::set). + struct VsharpRecord { + leonida::ConsoleHeapSlotRecords::State state = leonida::ConsoleHeapSlotRecords::none; + uint64_t base = 0, span = 0, target = 0; + }; + VsharpResult fix_vsharp(uint32_t* w, VsharpPath path, VsharpRecord* record = nullptr) { if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer const uint64_t base = uint64_t(w[0]) | (uint64_t(w[1] & 0xffff) << 32); const uint32_t stride = (w[1] >> 16) & 0x3fffu; @@ -3982,8 +4025,16 @@ struct DeviceState { leonida::gfx10::Buffer desc{}; const bool copy_geometry = leonida::gfx10::decode(words, desc) && (path != VsharpPath::scratch || span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words)); + uint64_t refused = 0; const auto to = vsharp_address(base, span, leonida::TitleVaAliases::table_view, - path != VsharpPath::scratch, copy_geometry); + path != VsharpPath::scratch, copy_geometry, &refused); + if (record) { + // The copy's device address (mod 2^64: a buffer below the arena has a negative offset). + record->state = to ? leonida::ConsoleHeapSlotRecords::resolved : leonida::ConsoleHeapSlotRecords::waiting; + record->base = base; + record->span = span; + record->target = to ? arena.address + to : refused ? arena.address + refused : 0; + } if (!to) { static std::atomic_flag noted[3]{}; if (!noted[unsigned(path)].test_and_set(std::memory_order_relaxed)) { @@ -4209,7 +4260,7 @@ struct DeviceState { backing(arena.address + offset, bytes, offset, false); arena.in_use -= bytes; arena.use_in_use[use] -= bytes; - // A heap copy re-fixes its slots when a backing has gone (released_backings): the range is no view's. + // A heap copy re-fixes the slots that named a backing that has gone (slot_changes): the range is no view's. backing(arena.address + offset, bytes, offset, false); } if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) { @@ -4271,25 +4322,17 @@ struct DeviceState { VkDeviceMemory memory = VK_NULL_HANDLE; std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives std::size_t scan_at = 0; // the next slot the T# scan reads - uint64_t checked_generation{}, alias_generation{}, backing_cursor{}, alias_cursor{}; - uint64_t release_sweeps{}, release_candidates{}, release_fixes{}, release_rebases{}, release_full{}; // copy bool identity = false; ShadowPagesPtr pages; std::vector mirror; // the title's bytes as the tracker last copied them std::vector made; // the title's bytes each arena slot was last made from std::vector retry; // per slot: not settled yet (fix_console_slot), in `retries` - leonida::ConsoleHeapVsharpSlots live_vsharps; // slots whose GPU copy holds a live buffer V# + // A resource heap's V# halves: what each resolved to (fix_console_slot), so a change of the address space + // re-fixes the slots it touches (apply_slot_changes), and a V# whose buffer comes later is fixed when it does. + leonida::ConsoleHeapSlotRecords records; std::vector retries; - std::set empty_slots; - std::uint32_t next_empty = 0; std::size_t retry_at = 0; // where retry_console_slots goes on - // V#s naming an address nothing backs that is not the title's memory: null in the copy, and looked at again a - // few times (kUnmappedTries, at most kUnmappedRetrySlots a submission) in case their buffer is made after the - // descriptor. - std::vector unmapped_tries; // per slot: 0, or the looks so far (it is in `unmapped`) - std::vector unmapped; - std::size_t unmapped_at = 0; // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line std::chrono::steady_clock::time_point fix_start{}; bool fix_over = false; @@ -4304,10 +4347,11 @@ struct DeviceState { double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts // Changed slots by class (before the fix budget), since the last log line: all-zero, V# pair, T#, other // words; V# halves whose 16 bytes were seen before (a direct-mapped memo of 65536 keys, so a lower bound of - // how often an exact-key translation would be found again); rescans after a backing release and their cost. + // how often an exact-key translation would be found again); the slot records' work: changes applied, index + // entries looked at, slots fixed again, and its time. std::uint64_t changed[4] = {}, vsharp_halves = 0, vsharp_repeats = 0; - std::uint64_t rescans = 0, rescanned = 0; - double rescan_ms = 0; + std::uint64_t record_changes = 0, record_looked = 0, record_refixed = 0; + double record_ms = 0; std::vector> seen_keys; // LEONIDA_CONSOLE_HEAP_GPU (DeviceState::attach_console_heap_gpu): the translation pass's index of this heap // (-1: fixed on the CPU), the import of `input` the pass reads, the slots holding a V# pair (translated again @@ -4383,38 +4427,31 @@ struct DeviceState { return true; } - // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above. True when it is settled: not a - // T# whose texture is still to come, nor a V# into the title's memory that got no copy. `unmapped` (when given) is - // set for a V# written null because its base is neither the title's memory nor anything of the device's: settled, - // but its buffer may still be made (the round-robin probe in refresh_console_heap). A sampler heap holds S#s: - // copied as written. - bool fix_console_slot(ConsoleHeap& heap, std::size_t slot, bool* unmapped = nullptr) { + // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above, and the only writer of a + // resource heap's slot records. True when it is settled: not a T# whose texture is still to come. A sampler heap + // holds S#s: copied as written. + bool fix_console_slot(ConsoleHeap& heap, std::size_t slot) { std::uint32_t w[kDescriptorSize / 4]; std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); - bool settled = true, empty = false; - if (unmapped) *unmapped = false; + bool settled = true, vsharp = false; + VsharpRecord halves[2]; const VsharpPath path = heap.scratch ? VsharpPath::scratch : VsharpPath::shadow; if (!heap.resource_heap || !(w[0] | w[1] | w[2] | w[3])) { // A sampler heap holds S#s (copied as written); an all-zero slot stays null. } else if (!(w[3] >> 30)) { // A buffer V#: rewritten to the address its bytes are backed at (fix_vsharp: the console shadow, or the - // console scratch an imported heap rewrites). A base nothing backs is written with no base and no records, - // settled, and left for the bounded round-robin probe in refresh_console_heap in case its buffer is made - // after the descriptor. - const VsharpResult result = fix_vsharp(w, path); + // console scratch an imported heap rewrites). A base nothing backs is written with no base and no records + // and recorded as waiting: a backing, alias range or title memory added over it fixes the slot again + // (apply_slot_changes). + vsharp = true; + const VsharpResult result = fix_vsharp(w, path, &halves[0]); if (result == VsharpResult::rebased) ++heap.vsharps; - if (result == VsharpResult::empty) { - // Only the GPU copy changes; the title's bytes (heap.previous) stay as written. - ++heap.unbacked; - empty = true; - } + // Only the GPU copy changes; the title's bytes (heap.previous) stay as written. + if (result == VsharpResult::empty) ++heap.unbacked; // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it at // heap_base + a raw title address loses the device just as one through the buffer V# does. A counter with - // no backing is nulled and left to retry_console_slots. - if (fix_vsharp(w + 4, path) == VsharpResult::empty) { - ++heap.unbacked; - empty = true; - } + // no backing is nulled and waits as the buffer V# does. + if (fix_vsharp(w + 4, path, &halves[1]) == VsharpResult::empty) ++heap.unbacked; } else { leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); @@ -4433,15 +4470,20 @@ struct DeviceState { // Neither a buffer V# (TYPE is not 0) nor a T# the layer can decode: data the title keeps in the slot. // No image is found by these words (the bindless lookup misses, as for a null T#), but a shader that // takes the slot as a V# (an index from data, or one past what the title filled) adds heap_base to - // words that name nothing: in the GPU copy the slot is null, and left to retry_console_slots. + // words that name nothing: in the GPU copy the slot is null. ++heap.images[unsigned(TitleImage::not_tsharp)]; std::memset(w, 0, 16); } } - if (empty) heap.empty_slots.insert(std::uint32_t(slot)); - else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot)); std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); - heap.live_vsharps.set(slot, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); + if (heap.resource_heap) { + if (vsharp) + for (unsigned half = 0; half < 2; ++half) + heap.records.set(slot, half, halves[half].state, halves[half].base, halves[half].span, + halves[half].target); + else + heap.records.clear(slot); + } return settled; } @@ -4496,7 +4538,6 @@ struct DeviceState { const std::size_t slot = at / kDescriptorSize; if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); - if (heap.unmapped_tries[slot]) heap.unmapped_tries[slot] = 1; // new words: their looks start over note_changed_slot(heap, heap.previous + at); if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) @@ -4509,7 +4550,7 @@ struct DeviceState { const bool is_buffer_vsharp = !(w3 >> 30); if (heap.fix_over && !is_buffer_vsharp) { std::memset(heap.copy + at, 0, kDescriptorSize); - heap.live_vsharps.clear(slot); + heap.records.clear(slot); ++heap.deferred_fixes; if (!heap.retry[slot]) { heap.retry[slot] = 1; @@ -4517,49 +4558,34 @@ struct DeviceState { } continue; } - bool unmapped = false; - if (fix_console_slot(heap, slot, &unmapped)) { + if (fix_console_slot(heap, slot)) { heap.retry[slot] = 0; } else if (!heap.retry[slot]) { heap.retry[slot] = 1; heap.retries.push_back(std::uint32_t(slot)); } - if (unmapped && !heap.unmapped_tries[slot]) { - heap.unmapped_tries[slot] = 1; - heap.unmapped.push_back(std::uint32_t(slot)); - } - } - } - - // The V#s fix_console_slot wrote null because nothing backs their base: looked at again, round robin, at most - // kUnmappedRetrySlots a submission, each kUnmappedTries times at most. A descriptor the title wrote before making - // its buffer (or a buffer another thread registers just after) then gets its base back; one that stays unmapped - // drops out of the list, so data the title keeps in its heap does not cost a lookup at every submission. - static constexpr std::size_t kUnmappedRetrySlots = 2048; - static constexpr std::uint8_t kUnmappedTries = 4; - void retry_unmapped_slots(ConsoleHeap& heap) { - std::size_t i = heap.unmapped_at; - // Each entry once a submission at most: the looks are a submission apart. - const std::size_t visits = std::min(kUnmappedRetrySlots, heap.unmapped.size()); - for (std::size_t visited = 0; visited < visits && !heap.unmapped.empty(); ++visited) { - if (i >= heap.unmapped.size()) i = 0; - const std::uint32_t slot = heap.unmapped[i]; - // Zeroed since (unmapped_tries reset), reachable now, or out of looks: out of the list. - bool done = !heap.unmapped_tries[slot]; - if (!done) { - bool unmapped = false; - fix_console_slot(heap, slot, &unmapped); - done = !unmapped || ++heap.unmapped_tries[slot] > kUnmappedTries; - } - if (done) { - heap.unmapped_tries[slot] = 0; - heap.unmapped[i] = heap.unmapped.back(); - heap.unmapped.pop_back(); - } else { - ++i; - } } - heap.unmapped_at = i; + } + + // The changes since the last submission (slot_changes), applied to a resource heap's copy: each slot whose record + // a change touches is fixed again - a V# whose backing, copy or alias range went, so the copy never names freed + // memory, and a waiting V# over which a backing, alias range or title memory was added. Only the slots near the + // changed ranges are looked at (ConsoleHeapSlotRecords::touched); nothing reads the copy. + std::vector slot_change_scratch; // console_heap_mutex + void apply_slot_changes(ConsoleHeap& heap, const std::vector& changes) { + if (!heap.resource_heap || changes.empty()) return; + const auto start = std::chrono::steady_clock::now(); + const std::uint64_t looked = heap.records.looked_at(); + heap.records.touched(changes.data(), changes.size(), slot_change_scratch); + heap.record_changes += changes.size(); + heap.record_looked += heap.records.looked_at() - looked; + heap.record_refixed += slot_change_scratch.size(); + for (const std::uint32_t slot : slot_change_scratch) + if (!fix_console_slot(heap, slot) && !heap.retry[slot]) { + heap.retry[slot] = 1; + heap.retries.push_back(slot); + } + heap.record_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. Round robin, for at @@ -4601,7 +4627,9 @@ struct DeviceState { unbound_tsharp_tracker().note(heap.console_va, offset, words, why); } - void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held + // `changes`: what changed since the last submission (refresh_console_heaps took it from slot_changes), or null for + // a heap's first refresh, which has no records yet. + void refresh_console_heap(ConsoleHeap& heap, const std::vector* changes) { // console_heap_mutex held if (heap.imported) return; // directly imported sampler heap if (heap.gpu >= 0) return refresh_console_heap_gpu(heap); using clock = std::chrono::steady_clock; @@ -4615,90 +4643,20 @@ struct DeviceState { std::memset(heap.previous + offset, 0, bytes); const auto first = std::uint32_t(offset / kDescriptorSize); const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); - heap.empty_slots.erase(heap.empty_slots.lower_bound(first), heap.empty_slots.lower_bound(end)); - for (auto slot = first; slot < end; ++slot) { - heap.retry[slot] = 0; - heap.unmapped_tries[slot] = 0; - } - heap.live_vsharps.clear_range(first, end); + for (auto slot = first; slot < end; ++slot) heap.retry[slot] = 0; + if (heap.resource_heap) heap.records.clear_range(first, end); }); const auto t1 = clock::now(); heap.fix_start = t1; heap.fix_over = false; heap.fix_count = 0; heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { fix_console_slots(heap, offset, bytes); }); - const auto generation = released_backings.load(std::memory_order_acquire); - const auto alias_generation = leonida::title_va_aliases().invalidations(); - if (heap.resource_heap && (generation != heap.checked_generation || alias_generation != heap.alias_generation)) { - heap.alias_generation = alias_generation; - heap.checked_generation = generation; - leonida::DescriptorRanges backing, aliases; - bool filtered = filter_heap_releases(); - if (filtered) { - { - std::lock_guard lock(backing_mutex); - filtered = backing_changes.read(heap.backing_cursor, backing); - } - filtered &= leonida::title_va_aliases().changed_ranges(heap.alias_cursor, aliases); - backing.merge(); - aliases.merge(); - } - ++heap.release_sweeps; - heap.release_full += !filtered; - const auto bda = [&](uint64_t base) { - if (signed_vsharp_offsets() && (base & (1ull << 47))) base |= ~((1ull << 48)-1); - return arena.address + base; - }; - const auto affected = [&](const uint32_t* src, const uint32_t* dst) { - if ((src[3] >> 30) || !src[2]) return false; - const uint64_t base = uint64_t(src[0]) | (uint64_t(src[1] & 0xffff) << 32); - const uint64_t fixed = uint64_t(dst[0]) | (uint64_t(dst[1] & 0xffff) << 32); - const auto stride = (src[1] >> 16) & 0x3fff; - const uint64_t bytes = uint64_t(src[2]) * (stride ? stride : 1); - return aliases.overlaps(base, 1) || backing.overlaps(bda(base), bytes) || - (dst[2] && backing.overlaps(bda(fixed), bytes)); - }; - const auto before = heap.vsharps; - ++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). - 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(heap.copy + at); - if (!affected(src, dst) && !affected(src + 4, dst + 4)) return; - } - ++heap.release_fixes; - ++heap.rescanned; - if (!fix_console_slot(heap, slot) && !heap.retry[slot]) { - heap.retry[slot] = 1; - heap.retries.push_back(uint32_t(slot)); - } - }); - heap.release_rebases += heap.vsharps - before; - heap.rescan_ms += ms(rescan_start, clock::now()); - } + // Even an unchanged title slot may name a buffer released since the last submission: the slots the changes + // touch are fixed again, found by their records. + if (changes) apply_slot_changes(heap, *changes); const auto t2 = clock::now(); - // A settled zero can acquire GPU backing without a CPU map event. Probe at most eight in - // round-robin order every 32 submissions. Keep texture and copy-budget retries independent. - if ((heap.refreshes & 31) == 31 && !heap.empty_slots.empty()) { - auto it = heap.empty_slots.lower_bound(heap.next_empty); - const auto count = (std::min)(std::size_t{8}, heap.empty_slots.size()); - for (std::size_t n = 0; n < count && !heap.empty_slots.empty(); ++n) { - if (it == heap.empty_slots.end()) it = heap.empty_slots.begin(); - const auto slot = *it++; - heap.next_empty = slot + 1; - if (!heap.retry[slot]) { - fix_console_slot(heap, slot); - ++heap.retried; - } - } - } + // T#s whose texture is not there yet, and slots the fix budget deferred. if (!heap.retries.empty()) retry_console_slots(heap); - if (!heap.unmapped.empty()) retry_unmapped_slots(heap); const auto t3 = clock::now(); heap.pages_ms += ms(t0, t1); heap.fix_ms += ms(t1, t2); @@ -4718,9 +4676,16 @@ struct DeviceState { if (on) state.console_heap_gpu_end(); } } gpu_end{*this, heap_pass}; + // Every change since the last submission, for every heap; one made from now on (by another thread, or by a + // fix below making a window) is applied at the next submission. + std::vector changes; + { + std::lock_guard taken(slot_change_mutex); + changes.swap(slot_changes); + } for (const auto& heap : console_heaps) { const auto start = std::chrono::steady_clock::now(); - refresh_console_heap(*heap); + refresh_console_heap(*heap, &changes); heap->ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); ++heap->refreshes; // A line at the first and 64th submission, then every 10 s (a crawl logs as often as a fast run). @@ -4735,7 +4700,7 @@ struct DeviceState { "in %.3f ms on average (pages %.3f, fixing copied slots %.3f, %llu left to retries past the " "budget, retrying %.3f: %.1f slots a " "submission, %zu waiting), %llu write faults; %llu title V#s rebased, %llu with no copy given " - "no records (%zu naming nothing waiting for another look), T#s %llu known, %llu bound, %llu " + "no records (%zu V# halves waiting for a backing), T#s %llu known, %llu bound, %llu " "naming no texture, %llu refused, %llu words that are no V# or T# (data, null in the copy)\n", static_cast(heap->console_va), heap->imported ? "imported" : "copy", static_cast(heap->refreshes), "copied", @@ -4745,41 +4710,41 @@ struct DeviceState { double(heap->retried) / count, heap->retries.size(), static_cast(heap->pages ? heap->pages->faults() : 0), static_cast(heap->vsharps), - static_cast(heap->unbacked), heap->empty_slots.size(), + static_cast(heap->unbacked), heap->records.waiting_count(), static_cast(heap->images[unsigned(TitleImage::known)]), static_cast(heap->images[unsigned(TitleImage::bound)]), static_cast(heap->images[unsigned(TitleImage::unknown)]), static_cast(heap->images[unsigned(TitleImage::refused)]), static_cast(heap->images[unsigned(TitleImage::not_tsharp)])); - if (heap->release_sweeps && filter_heap_releases()) - std::fprintf(stderr, "[rt] CPU release filter: %llu sweeps, %llu live slots, %llu fixes, %llu rebases, %llu full fallbacks\n", - (unsigned long long)heap->release_sweeps, (unsigned long long)heap->release_candidates, - (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->resource_heap) { std::uint64_t paths[kVsharpPathCount]; for (unsigned i = 0; i < kVsharpPathCount; ++i) paths[i] = vsharp_paths[i].exchange(0, std::memory_order_relaxed); std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx changed slots per submission: %.1f zero, %.1f " - "V# pairs, %.1f T#s, %.1f other; V# halves %.1f, %.1f%% seen before; rescans %llu (%.1f " - "V# slots and %.3f ms each); V# resolutions since the last line: alias %llu, alias " - "refused %llu, arena %llu, geometry %llu, window %llu, none %llu\n", + "V# pairs, %.1f T#s, %.1f other; V# halves %.1f, %.1f%% seen before; V# resolutions since " + "the last line: alias %llu, alias refused %llu, arena %llu, geometry %llu, window %llu, " + "none %llu\n", static_cast(heap->console_va), double(heap->changed[0]) / count, double(heap->changed[1]) / count, double(heap->changed[2]) / count, double(heap->changed[3]) / count, double(heap->vsharp_halves) / count, heap->vsharp_halves ? 100.0 * double(heap->vsharp_repeats) / double(heap->vsharp_halves) : 0.0, - static_cast(heap->rescans), - heap->rescans ? double(heap->rescanned) / double(heap->rescans) : 0.0, - heap->rescans ? heap->rescan_ms / double(heap->rescans) : 0.0, static_cast(paths[0]), static_cast(paths[1]), static_cast(paths[2]), static_cast(paths[3]), static_cast(paths[4]), static_cast(paths[5])); + // What releases, alias changes and additions cost: per submission, the changes taken, the record + // entries looked at to find their slots, and the slots fixed again (apply_slot_changes). + std::fprintf(stderr, + "[rt] d3d12: console descriptor heap 0x%llx slot records per submission: %.1f changes, " + "%.1f slots looked at, %.1f fixed again, %.3f ms; %zu V# halves recorded\n", + static_cast(heap->console_va), double(heap->record_changes) / count, + double(heap->record_looked) / count, double(heap->record_refixed) / count, + heap->record_ms / count, heap->records.recorded()); for (auto& n : heap->changed) n = 0; - heap->vsharp_halves = heap->vsharp_repeats = heap->rescans = heap->rescanned = 0; - heap->rescan_ms = 0; + heap->vsharp_halves = heap->vsharp_repeats = 0; + heap->record_changes = heap->record_looked = heap->record_refixed = 0; + heap->record_ms = 0; } if (heap->gpu >= 0) log_console_heap_gpu(*heap, count); std::string refused_breakdown; @@ -4984,8 +4949,11 @@ struct DeviceState { heap->previous = heap->made.data(); } heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0); - heap->live_vsharps.reset(std::size_t(bytes / kDescriptorSize)); - heap->unmapped_tries.assign(std::size_t(bytes / kDescriptorSize), 0); + if (resource_heap) { + heap->records.reset(std::size_t(bytes / kDescriptorSize)); + // Changes are kept from now on, before the first refresh writes a record. + slot_records_live.store(true, std::memory_order_release); + } heap->pages = make_shadow_pages(reinterpret_cast(static_cast(console_va)), heap->input, std::size_t(bytes)); } @@ -4999,7 +4967,7 @@ struct DeviceState { { std::lock_guard lock(console_heap_mutex); if (heap->gpu >= 0) gpu_heaps[std::size_t(heap->gpu)] = heap.get(); - if (!imported) refresh_console_heap(*heap); + if (!imported) refresh_console_heap(*heap, nullptr); if (heap->copy) { std::unique_lock ranges(console_copy_ranges_mutex); console_copy_ranges.emplace_back(heap->console_va, heap->bytes); @@ -5144,17 +5112,15 @@ struct DeviceState { std::vector gpu_queue_scratch; bool gpu_rescan = false, gpu_rescan_after_resolve = false; std::chrono::steady_clock::time_point gpu_rescan_asked{}; - // LEONIDA_CONSOLE_GPU_FILTER=1 (default: LEONIDA_CONSOLE_RELEASE_FILTER's value): a release, an alias range that - // went or a word answered since asks for a rescan of the slots it touches (the release filter's interval rule, - // 8a22e92c8) instead of every V# slot: the GPU passes over the rest on its device-local metadata. + // LEONIDA_CONSOLE_GPU_FILTER=1 (default off): a release, an alias range that went or a word answered since asks + // for a rescan of the slots it touches (an interval rule, 8a22e92c8) instead of every V# slot: the GPU passes over + // the rest on its device-local metadata. // gpu_filter_shader: shader-VA spans (released backings, alias copies that went); gpu_filter_title: title VAs // (words backed since). Overflows and key resets still rescan everything. static bool gpu_filter_enabled() { static const bool on = [] { char text[8] = {}; - if (GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_FILTER", text, sizeof(text)) && text[0]) - return text[0] == '1'; - return GetEnvironmentVariableA("LEONIDA_CONSOLE_RELEASE_FILTER", text, sizeof(text)) && text[0] == '1'; + return GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_FILTER", text, sizeof(text)) && text[0] == '1'; }(); return on; } @@ -14367,6 +14333,8 @@ class Device final leonida::title_va_aliases().set_noter([](void* device, std::uint64_t va, std::uint64_t bytes) { static_cast(device)->note_title_write(va, bytes); }); + // Every device, hooks or not: its console heaps' slot records follow the alias table's changes. + leonida::title_va_aliases().add_listener(&state_, &DeviceState::alias_changed); state_.image_memory = std::make_unique( [device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) { VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; @@ -15075,6 +15043,7 @@ class Device final compiler_use_.release(); } leonida::title_va_aliases().clear_hooks(&state_); + leonida::title_va_aliases().remove_listener(&state_); { std::lock_guard lock(state_.title_window_mutex); for (const auto& window : state_.title_windows) diff --git a/runtime/src/console_heap_slot_records.h b/runtime/src/console_heap_slot_records.h new file mode 100644 index 0000000000..4ab3c3b9d9 --- /dev/null +++ b/runtime/src/console_heap_slot_records.h @@ -0,0 +1,227 @@ +#pragma once +// What each buffer V# of a console resource heap's GPU copy resolved to (docs/d3d12_vulkan.md section 3.4), kept in +// host RAM so that a change of the address space re-fixes exactly the slots it touches. +// +// A slot of the copy is the title's descriptor with its V# bases rewritten (DeviceState::fix_console_slot). What a +// base became depends on things that change after the slot was written: a buffer or window released, an alias range +// removed, a geometry copy retired, or (for a base nothing backed yet) a buffer, alias or title memory added. Without +// a record of which slot resolved into which range, a change could only be applied by walking every live slot. Here +// each V# half (the buffer V# and the UAV counter V# of a slot) records: +// - base and span: the bytes the title's V# names, [base, base + span) (the base is the V#'s 48 bits); +// - target: the device address its GPU copy names, [target, target + span); for a half that resolved to nothing, +// the device address of a copy that was found but refused (not backed yet), or 0; +// - state: resolved, waiting (written with no base and no records until something backs it) or none. +// Two indexes find the halves a change touches: by base ("source") and by target. Each holds a half once, under the +// power-of-two class of its span and the granule of its start (a granule is at least 64 KiB and at least the class), +// so a range [lo, hi) is answered by visiting, per class in use, the granules from lo - 2^class to hi: the cost is the +// halves near the range, never the heap. An entry is checked against the record when visited (a half that moved +// leaves a stale entry behind; a bucket drops its stale entries whenever it has doubled since it was last cleaned). +// Portable, standard library only: console_heap_slot_records_test exercises it without a GPU. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// One change since the last submission, as a range; hi is exclusive and greater than lo. +struct SlotChange { + enum Kind : std::uint8_t { + target_gone, // device addresses: a backing released, a copy's block destroyed, an alias range's copy gone + source_gone, // V# bases: an alias range removed or replaced, or a copy that answered for it gone + target_added, // device addresses: a backing added (a refused alias target may be backed now) + source_added, // V# bases: an alias range or title memory added, or a backing added at those arena offsets + }; + Kind kind; + std::uint64_t lo, hi; +}; + +class ConsoleHeapSlotRecords { +public: + enum State : std::uint8_t { none = 0, resolved = 1, waiting = 2 }; + + void reset(std::size_t slots) { + slots_ = slots; + // calloc: the pages of slots never written are never touched (the retail heap uses a tenth of its slots). + halves_.reset(slots ? static_cast(std::calloc(slots * 2, sizeof(Half))) : nullptr); + if (slots && !halves_) slots_ = 0; + for (auto& index : indexes_) index = Index{}; + recorded_ = waiting_ = 0; + looked_at_ = 0; + } + std::size_t slots() const { return slots_; } + std::size_t recorded() const { return recorded_; } // halves in state resolved or waiting + std::size_t waiting_count() const { return waiting_; } // halves in state waiting + std::uint64_t looked_at() const { return looked_at_; } // index entries visited by touched(), all calls + + // Half `half` (0: the buffer V#, 1: the UAV counter V#) of `slot` now names [base, base + span) and resolved as + // `state` says, its copy at `target` (see above). span 0 counts as 1. + void set(std::size_t slot, unsigned half, State state, std::uint64_t base, std::uint64_t span, + std::uint64_t target) { + if (slot >= slots_ || half > 1) return; + if (state == none) base = span = target = 0; + if (!span) span = 1; + if (span > kMaxSpan) span = kMaxSpan; + const std::size_t key = slot * 2 + half; + Half& h = halves_[key]; + const Half old = h; + count(old.state(), -1); + h.base = base; + h.target = target; + h.span_state = span | (std::uint64_t(state) << 56); + count(state, +1); + if (state == none) return; // entries left behind are stale now + const auto add = [&](int which, std::uint64_t start, std::uint64_t old_start) { + const unsigned c = span_class(span); + const std::uint64_t granule = start >> granule_shift(c); + // Unchanged key: the entry already there stands for it. + if (old.state() != none && (which == kSource || old.target) && span_class(old.span()) == c && + (old_start >> granule_shift(c)) == granule) + return; + push(which, c, granule, std::uint32_t(key)); + }; + add(kSource, base, old.base); + if (target) add(kTarget, target, old.target); + } + + void clear(std::size_t slot) { + set(slot, 0, none, 0, 0, 0); + set(slot, 1, none, 0, 0, 0); + } + void clear_range(std::size_t first, std::size_t end) { + end = (std::min)(end, slots_); + for (std::size_t slot = first; slot < end; ++slot) + for (unsigned half = 0; half < 2; ++half) + if (halves_[slot * 2 + half].state() != none) set(slot, half, none, 0, 0, 0); + } + + State state(std::size_t slot, unsigned half) const { + return slot < slots_ && half < 2 ? halves_[slot * 2 + half].state() : none; + } + std::uint64_t target(std::size_t slot, unsigned half) const { + return slot < slots_ && half < 2 ? halves_[slot * 2 + half].target : 0; + } + + // The slots `changes` touch, each once, ascending, appended to `out` (cleared first): + // target_gone: halves whose [target, target + span) overlaps the range (whatever their state); + // source_gone: halves whose [base, base + span) overlaps it; + // target_added, source_added: the same, waiting halves only (a resolved one stays valid until something goes). + void touched(const SlotChange* changes, std::size_t count, std::vector& out) { + out.clear(); + for (std::size_t i = 0; i < count; ++i) { + const SlotChange& change = changes[i]; + if (change.hi <= change.lo) continue; + const bool target = change.kind == SlotChange::target_gone || change.kind == SlotChange::target_added; + const bool waiting_only = change.kind == SlotChange::target_added || change.kind == SlotChange::source_added; + find(target ? kTarget : kSource, change.lo, change.hi, waiting_only, out); + } + std::sort(out.begin(), out.end()); + out.erase(std::unique(out.begin(), out.end()), out.end()); + } + +private: + static constexpr int kSource = 0, kTarget = 1; + static constexpr std::uint64_t kMaxSpan = (std::uint64_t(1) << 56) - 1; + static constexpr unsigned kMinGranule = 16; // 64 KiB + static constexpr unsigned kClasses = 57; + + struct Half { + std::uint64_t base, target, span_state; + std::uint64_t span() const { return span_state & kMaxSpan; } + State state() const { return State(span_state >> 56); } + }; + struct Free { + void operator()(Half* p) const { std::free(p); } + }; + struct Bucket { + std::vector keys; + std::size_t clean = 0; // its size when it was last cleaned + }; + struct Index { + std::array, kClasses> classes; + std::uint64_t used = 0; // a bit per class that ever held an entry + }; + + // The smallest c with span <= 2^c. + static unsigned span_class(std::uint64_t span) { + return span <= 1 ? 0u : unsigned(64 - std::countl_zero(span - 1)); + } + static unsigned granule_shift(unsigned c) { return c < kMinGranule ? kMinGranule : c; } + + void count(State state, int delta) { + if (state != none) recorded_ += std::size_t(std::ptrdiff_t(delta)); + if (state == waiting) waiting_ += std::size_t(std::ptrdiff_t(delta)); + } + + // Whether index `which` still holds `key` under (c, granule). + bool current(int which, std::uint32_t key, unsigned c, std::uint64_t granule) const { + const Half& h = halves_[key]; + if (h.state() == none || span_class(h.span()) != c) return false; + if (which == kTarget && !h.target) return false; + return ((which == kSource ? h.base : h.target) >> granule_shift(c)) == granule; + } + + void push(int which, unsigned c, std::uint64_t granule, std::uint32_t key) { + Index& index = indexes_[which]; + index.used |= std::uint64_t(1) << c; + Bucket& bucket = index.classes[c][granule]; + bucket.keys.push_back(key); + if (bucket.keys.size() < 32 || bucket.keys.size() < 2 * bucket.clean) return; + auto& keys = bucket.keys; + keys.erase(std::remove_if(keys.begin(), keys.end(), + [&](std::uint32_t k) { return !current(which, k, c, granule); }), + keys.end()); + std::sort(keys.begin(), keys.end()); + keys.erase(std::unique(keys.begin(), keys.end()), keys.end()); + bucket.clean = keys.size(); + } + + void find(int which, std::uint64_t lo, std::uint64_t hi, bool waiting_only, std::vector& out) { + Index& index = indexes_[which]; + for (std::uint64_t used = index.used; used; used &= used - 1) { + const unsigned c = unsigned(std::countr_zero(used)); + auto& buckets = index.classes[c]; + if (buckets.empty()) continue; + const unsigned shift = granule_shift(c); + // A half of this class overlaps [lo, hi) only if it starts in (lo - 2^c, hi). + const std::uint64_t reach = std::uint64_t(1) << c; + const std::uint64_t first = (lo >= reach ? lo - reach + 1 : 0) >> shift; + const std::uint64_t last = (hi - 1) >> shift; + const auto visit = [&](std::uint64_t granule, const Bucket& bucket) { + for (const std::uint32_t key : bucket.keys) { + ++looked_at_; + if (!current(which, key, c, granule)) continue; + const Half& h = halves_[key]; + if (waiting_only && h.state() != waiting) continue; + const std::uint64_t start = which == kSource ? h.base : h.target; + const std::uint64_t span = h.span(); + const std::uint64_t end = start + span < start ? UINT64_MAX : start + span; + if (start < hi && end > lo) out.push_back(key >> 1); + } + }; + if (last - first >= buckets.size()) { + for (const auto& [granule, bucket] : buckets) + if (granule >= first && granule <= last) visit(granule, bucket); + } else { + for (std::uint64_t granule = first;; ++granule) { + const auto it = buckets.find(granule); + if (it != buckets.end()) visit(granule, it->second); + if (granule == last) break; + } + } + } + } + + std::size_t slots_ = 0; + std::unique_ptr halves_; + std::array indexes_; + std::size_t recorded_ = 0, waiting_ = 0; + std::uint64_t looked_at_ = 0; +}; + +} // namespace leonida diff --git a/runtime/src/console_heap_vsharp_slots.h b/runtime/src/console_heap_vsharp_slots.h deleted file mode 100644 index 0b0830053b..0000000000 --- a/runtime/src/console_heap_vsharp_slots.h +++ /dev/null @@ -1,115 +0,0 @@ -#pragma once -// Host-RAM bitset of console resource-heap slots whose GPU copy (`heap.copy`) currently holds a live buffer V# -// (`!(w[3] >> 30) && (w[2] || w[6])`). -// -// When a buffer backing or title VA alias is released, `refresh_console_heap` must re-run `fix_console_slot` on every -// slot that might still point at the released allocation. Scanning `heap.copy` linearly reads every 32-byte slot of -// the heap (4-5.5+ MiB): when `heap.copy` sits in `arena.mapped` (uncached write-combined GPU memory), each release -// triggers ~180k uncached PCIe reads. Tracking the live V# slots in host RAM keeps invalidation scans strictly in CPU -// cache (zero reads from `heap.copy`) and skips empty and T# slots 64 at a time. - -#include -#include -#include -#include -#include - -namespace leonida { - -class ConsoleHeapVsharpSlots { -public: - // Matches the descriptor predicate for a non-empty buffer V# (primary or counter half) in a 32-byte slot. - static constexpr bool is_live_vsharp(const std::uint32_t* w) noexcept { - return !(w[3] >> 30) && (w[2] || w[6]); - } - - void reset(std::size_t slot_count) { - slot_count_ = slot_count; - live_count_ = 0; - words_.assign((slot_count + 63) / 64, 0); - } - - void set(std::size_t slot, bool live) noexcept { - if (slot >= slot_count_) return; - std::uint64_t& word = words_[slot >> 6]; - const std::uint64_t mask = std::uint64_t{1} << (slot & 63); - const bool was = (word & mask) != 0; - if (live == was) return; - if (live) { - word |= mask; - ++live_count_; - } else { - word &= ~mask; - --live_count_; - } - } - - void clear(std::size_t slot) noexcept { set(slot, false); } - - // Clears every slot in [first, end), clamping to slot_count(). - void clear_range(std::size_t first, std::size_t end) noexcept { - if (first >= end || first >= slot_count_ || live_count_ == 0) return; - end = (std::min)(end, slot_count_); - std::size_t w = first >> 6; - const std::size_t last_w = (end - 1) >> 6; - const unsigned first_bit = static_cast(first & 63); - const unsigned end_bit = static_cast(end & 63); - const std::uint64_t head_mask = ~std::uint64_t{0} << first_bit; - const std::uint64_t tail_mask = end_bit ? ((std::uint64_t{1} << end_bit) - 1) : ~std::uint64_t{0}; - if (w == last_w) { - const std::uint64_t mask = head_mask & tail_mask; - const std::uint64_t cleared = words_[w] & mask; - if (cleared) { - words_[w] &= ~mask; - live_count_ -= static_cast(std::popcount(cleared)); - } - return; - } - if (const std::uint64_t cleared = words_[w] & head_mask) { - words_[w] &= ~head_mask; - live_count_ -= static_cast(std::popcount(cleared)); - } - for (++w; w < last_w; ++w) { - if (const std::uint64_t cleared = words_[w]) { - words_[w] = 0; - live_count_ -= static_cast(std::popcount(cleared)); - } - } - if (const std::uint64_t cleared = words_[last_w] & tail_mask) { - words_[last_w] &= ~tail_mask; - live_count_ -= static_cast(std::popcount(cleared)); - } - } - - // Calls fn(slot) in ascending slot order for every set bit present when its 64-slot word is entered. - // Safe if fn mutates the bit for `slot` (e.g., fix_console_slot clearing an invalidated V#). - template - void for_each(F&& fn) const { - if (live_count_ == 0) return; - for (std::size_t w = 0; w < words_.size(); ++w) { - std::uint64_t bits = words_[w]; - if (!bits) continue; - const std::size_t base = w << 6; - while (bits) { - const unsigned bit = static_cast(std::countr_zero(bits)); - bits &= bits - 1; - fn(base + bit); - } - } - } - - bool test(std::size_t slot) const noexcept { - return slot < slot_count_ && ((words_[slot >> 6] >> (slot & 63)) & 1u) != 0; - } - - std::size_t slot_count() const noexcept { return slot_count_; } - std::size_t live_count() const noexcept { return live_count_; } - bool empty() const noexcept { return live_count_ == 0; } - -private: - std::size_t slot_count_ = 0; - std::size_t live_count_ = 0; - std::vector words_; -}; - -} // namespace leonida diff --git a/runtime/src/descriptor_range_changes.h b/runtime/src/descriptor_range_changes.h deleted file mode 100644 index 5a4d7717f2..0000000000 --- a/runtime/src/descriptor_range_changes.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace leonida { -// A separate cursor per console heap. The owning backing/alias registry locks record() and read(). -struct DescriptorRanges { - struct Range { uint64_t first, last; }; // inclusive, including UINT64_MAX - std::vector ranges; - void merge() { - std::sort(ranges.begin(), ranges.end(), [](auto a, auto b) { return a.first < b.first; }); - size_t n = 0; - for (auto r : ranges) { - if (n && r.first <= ranges[n-1].last) - ranges[n-1].last = (std::max)(ranges[n-1].last, r.last); - else ranges[n++] = r; - } - ranges.resize(n); - } - bool overlaps(uint64_t base, uint64_t bytes) const { - if (!bytes) return false; - auto it = std::lower_bound(ranges.begin(), ranges.end(), base, - [](auto r, uint64_t v) { return r.last < v; }); - return it != ranges.end() && (it->first <= base || it->first - base < bytes); - } -}; -class DescriptorRangeChanges { - std::array ring_{}; - uint64_t serial_{}; -public: - void record(uint64_t start, uint64_t bytes) { - if (bytes) { - ring_[serial_++ % ring_.size()] = {start, start + (std::min)(UINT64_MAX-start, bytes-1)}; - } - } - bool read(uint64_t& cursor, DescriptorRanges& out) const { - const auto previous = cursor; - cursor = serial_; - if (serial_ - previous > ring_.size()) return false; - for (auto i = previous; i != serial_; ++i) out.ranges.push_back(ring_[i % ring_.size()]); - return true; - } -}; -} diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 66a7f58947..c49880d923 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -16,7 +16,6 @@ // that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the // buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was // added to it, so it is tested without a GPU (title_va_alias_test). -#include "descriptor_range_changes.h" #include #include "buffer_va_index.h" @@ -55,7 +54,7 @@ class TitleVaAliases { if (!bytes || title_va > UINT64_MAX - bytes) return false; std::unique_lock lock(mutex_); erase_overlapping(title_va, title_va + bytes); - changes_.record(title_va, bytes); + notify(Change::added, title_va, bytes, shader_va); ranges_[title_va] = {title_va + bytes, shader_va}; by_shader_.insert(shader_va, bytes, title_va); count_.store(ranges_.size(), std::memory_order_release); @@ -77,11 +76,10 @@ class TitleVaAliases { std::unique_lock lock(mutex_); const auto it = ranges_.find(title_va); if (it != ranges_.end() && it->second.shader_va == shader_va) { - changes_.record(it->first, it->second.end - it->first); + notify(Change::removed, it->first, it->second.end - it->first, shader_va); by_shader_.erase(shader_va, title_va); note_removed(it->second.shader_va, it->second.end - it->first); ranges_.erase(it); - invalidations_.fetch_add(1, std::memory_order_release); generation_.fetch_add(1, std::memory_order_release); } count_.store(ranges_.size(), std::memory_order_release); @@ -89,14 +87,13 @@ class TitleVaAliases { // A copy that answered for [title_va, title_va + bytes) at shader_va went, whether or not it had a range here (a // geometry copy that vsharp_address or a placed view reached through GeometryViews directly has none): what was - // translated through it is stale. Recorded as a removal would be: the console heaps translate the slots in the - // range again (invalidations, changed_ranges), and the GPU key table drops answers into shader_va (take_removed). + // translated through it is stale. Told as a removal is: the console heaps fix the slots that resolved through + // either side of it again (the listeners), and the GPU key table drops answers into shader_va (take_removed). void forget_copy(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) { if (!bytes) return; std::unique_lock lock(mutex_); - changes_.record(title_va, bytes); + notify(Change::removed, title_va, bytes, shader_va); note_removed(shader_va, bytes); - invalidations_.fetch_add(1, std::memory_order_release); generation_.fetch_add(1, std::memory_order_release); } @@ -259,6 +256,7 @@ class TitleVaAliases { } memory_[begin] = end; memory_generation_.fetch_add(1, std::memory_order_release); + notify(Change::memory_added, base, bytes, 0); } void remove_title_memory(std::uint64_t base) { std::unique_lock lock(memory_mutex_); @@ -373,10 +371,23 @@ class TitleVaAliases { } std::size_t size() const { return count_.load(std::memory_order_acquire); } - std::uint64_t invalidations() const { return invalidations_.load(std::memory_order_acquire); } - bool changed_ranges(uint64_t& cursor, DescriptorRanges& ranges) const { - std::shared_lock lock(mutex_); - return changes_.read(cursor, ranges); + + // What changed, told as it happens to every listener (a device whose console heaps record what each descriptor + // resolved to, src/console_heap_slot_records.h): [title_va, title_va + bytes) reached at shader_va was added, or + // was removed or replaced (remove, an overlapping add, forget_copy: what resolved through it is stale), or title + // memory was added (shader_va 0: a copy may now be made for an address that had none). Called with the table's + // lock held, so a listener only records and never calls back into the table. remove_listener returns once no call + // to that listener is in progress. + enum class Change : unsigned { added, removed, memory_added }; + using Listener = void (*)(void* context, Change change, std::uint64_t title_va, std::uint64_t bytes, + std::uint64_t shader_va); + void add_listener(void* context, Listener listener) { + std::unique_lock lock(listener_mutex_); + listeners_.emplace_back(context, listener); + } + void remove_listener(void* context) { + std::unique_lock lock(listener_mutex_); + std::erase_if(listeners_, [context](const auto& l) { return l.first == context; }); } // Bumped by every add and every removal: a copy of mappings() is current while it has not moved. std::uint64_t generation() const { return generation_.load(std::memory_order_acquire); } @@ -418,9 +429,8 @@ class TitleVaAliases { auto previous = std::prev(it); if (previous->second.end > begin) it = previous; } - if (it != ranges_.end() && it->first < end) invalidations_.fetch_add(1, std::memory_order_release); while (it != ranges_.end() && it->first < end) { - changes_.record(it->first, it->second.end - it->first); + notify(Change::removed, it->first, it->second.end - it->first, it->second.shader_va); by_shader_.erase(it->second.shader_va, it->first); note_removed(it->second.shader_va, it->second.end - it->first); it = ranges_.erase(it); @@ -432,12 +442,17 @@ class TitleVaAliases { if (record_removals_.load(std::memory_order_relaxed)) removed_.push_back({shader_va, bytes}); } - DescriptorRangeChanges changes_; + void notify(Change change, std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) const { + std::shared_lock lock(listener_mutex_); + for (const auto& [context, listener] : listeners_) listener(context, change, title_va, bytes, shader_va); + } + + mutable std::shared_mutex listener_mutex_; // taken inside mutex_ and memory_mutex_, never the other way + std::vector> listeners_; mutable std::shared_mutex mutex_; std::map ranges_; // by title VA BufferVaIndex by_shader_; // the same ranges by shader VA (id: the title VA); copies may overlap std::atomic count_{0}; - std::atomic invalidations_{}; std::atomic generation_{}; std::atomic record_removals_{false}; std::vector> removed_; // (shader VA, bytes), when recorded diff --git a/runtime/test/console_heap_slot_records_test.cpp b/runtime/test/console_heap_slot_records_test.cpp new file mode 100644 index 0000000000..c5fcfbe9ab --- /dev/null +++ b/runtime/test/console_heap_slot_records_test.cpp @@ -0,0 +1,347 @@ +// leonida::ConsoleHeapSlotRecords (src/console_heap_slot_records.h): a change of the address space finds exactly the +// console-heap slots whose V#s it touches, without walking the heap. Portable, CPU only, no game data. +// +// A small model stands in for the device: backings (device ranges), alias ranges (title VA -> arena offset) and a +// resolver that follows DeviceState::vsharp_address's order (an alias first, refused when its copy is not backed; then +// the base as an arena offset). fix() is fix_console_slot: it resolves both halves of a slot, writes the "copy" and the +// records. apply() is apply_slot_changes: the slots touched() names are fixed again. After every step the copy is +// compared with a full re-resolution of every slot: a slot left naming a range that went (a GPU page fault in the +// runtime) or a waiting slot left null after its buffer came fails the comparison. +#include "../src/console_heap_slot_records.h" + +#include +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using leonida::ConsoleHeapSlotRecords; +using leonida::SlotChange; + +constexpr std::uint64_t kArena = 0x7f0000000000ull; // the arena's device address +constexpr std::uint64_t kMask = (1ull << 48) - 1; + +struct HalfWords { + std::uint64_t base = 0, span = 0; // span 0: no V# in this half +}; + +struct Model { + using Words = HalfWords; + struct Alias { + std::uint64_t end, shader; + }; + std::vector> slots; + std::vector> copy; // the device address each half names, 0: null + std::map backings; // device start -> end + std::map aliases; // title VA -> range + ConsoleHeapSlotRecords records; + std::vector changes; + std::uint64_t fixes = 0; + + explicit Model(std::size_t n) : slots(n), copy(n, {0, 0}) { records.reset(n); } + + bool backed(std::uint64_t address, std::uint64_t span) const { + auto it = backings.upper_bound(address); + if (it == backings.begin()) return false; + --it; + return address >= it->first && address + span <= it->second; + } + // As vsharp_address: 0 when nothing backs it, with `refused` an alias copy that is not backed. + std::uint64_t resolve(std::uint64_t base, std::uint64_t span, std::uint64_t& refused) const { + refused = 0; + auto it = aliases.upper_bound(base); + if (it != aliases.begin() && base < std::prev(it)->second.end) { + --it; + const std::uint64_t to = kArena + it->second.shader + (base - it->first); + if (base + span > it->second.end || !backed(to, span)) { + refused = to; + return 0; + } + return to; + } + if (base < (1ull << 40) && backed(kArena + base, span)) return kArena + base; + return 0; + } + void fix(std::size_t slot) { + ++fixes; + for (unsigned half = 0; half < 2; ++half) { + const Words& w = slots[slot][half]; + if (!w.span) { + records.set(slot, half, ConsoleHeapSlotRecords::none, 0, 0, 0); + copy[slot][half] = 0; + continue; + } + std::uint64_t refused = 0; + const std::uint64_t to = resolve(w.base, w.span, refused); + records.set(slot, half, to ? ConsoleHeapSlotRecords::resolved : ConsoleHeapSlotRecords::waiting, w.base, + w.span, to ? to : refused); + copy[slot][half] = to; + } + } + void write(std::size_t slot, Words a, Words b = Words{}) { + slots[slot] = {a, b}; + fix(slot); + } + void zero(std::size_t slot) { + slots[slot] = {}; + copy[slot] = {0, 0}; + records.clear(slot); + } + // The changes the device notes (DeviceState::backing, alias_changed). + void add_backing(std::uint64_t offset, std::uint64_t bytes) { + backings[kArena + offset] = kArena + offset + bytes; + changes.push_back({SlotChange::target_added, kArena + offset, kArena + offset + bytes}); + changes.push_back({SlotChange::source_added, offset & kMask, (offset & kMask) + bytes}); + } + void release_backing(std::uint64_t offset) { + const auto it = backings.find(kArena + offset); + changes.push_back({SlotChange::target_gone, it->first, it->second}); + backings.erase(it); + } + void add_alias(std::uint64_t title, std::uint64_t bytes, std::uint64_t shader) { + for (auto it = aliases.begin(); it != aliases.end();) { + if (it->first < title + bytes && it->second.end > title) { + remove_change(it->first, it->second); + it = aliases.erase(it); + } else { + ++it; + } + } + aliases[title] = {title + bytes, shader}; + changes.push_back({SlotChange::source_added, title, title + bytes}); + } + void remove_alias(std::uint64_t title) { + const auto it = aliases.find(title); + remove_change(it->first, it->second); + aliases.erase(it); + } + void remove_change(std::uint64_t title, const Alias& a) { + changes.push_back({SlotChange::source_gone, title, a.end}); + changes.push_back({SlotChange::target_gone, kArena + a.shader, kArena + a.shader + (a.end - title)}); + } + // apply_slot_changes: the slots looked at (index entries) and fixed again. + std::uint64_t looked = 0; + std::vector touched; + void apply() { + const std::uint64_t before = records.looked_at(); + records.touched(changes.data(), changes.size(), touched); + looked = records.looked_at() - before; + changes.clear(); + for (const std::uint32_t slot : touched) fix(slot); + } + // Every slot as a full re-resolution would leave it: the copy the walk this replaced would have produced. + bool consistent() const { + for (std::size_t slot = 0; slot < slots.size(); ++slot) + for (unsigned half = 0; half < 2; ++half) { + const Words& w = slots[slot][half]; + std::uint64_t refused = 0; + const std::uint64_t want = w.span ? resolve(w.base, w.span, refused) : 0; + if (copy[slot][half] != want) { + std::fprintf(stderr, "slot %zu half %u names 0x%llx, a full re-resolution gives 0x%llx\n", slot, half, + static_cast(copy[slot][half]), + static_cast(want)); + return false; + } + } + return true; + } +}; + +// The design's case: 60,010 live slots, 10 of them name buffer B. Releasing B looks at those 10 and fixes only them; +// the walk this replaced looked at all 60,010. +int release_looks_at_its_slots_only() { + constexpr std::size_t kSlots = 65536; + Model m(kSlots); + constexpr std::uint64_t a = 0x100000, b = 0x900000; + m.add_backing(a, 0x10000); + m.add_backing(b, 0x10000); + m.changes.clear(); + for (std::size_t slot = 0; slot < 60000; ++slot) m.write(slot, {a + (slot % 64) * 0x100, 0x100}); + for (std::size_t slot = 60000; slot < 60010; ++slot) m.write(slot, {b + (slot - 60000) * 0x100, 0x100}); + EXPECT(m.records.recorded() == 60010 && m.records.waiting_count() == 0 && m.consistent()); + m.fixes = 0; + m.release_backing(b); + m.apply(); + const std::uint64_t looked = m.looked; + EXPECT(looked <= 10); + EXPECT(m.touched.size() == 10 && m.touched.front() == 60000 && m.touched.back() == 60009); + EXPECT(m.fixes == 10 && m.records.waiting_count() == 10 && m.consistent()); + // Nothing changed: nothing looked at. + m.apply(); + EXPECT(m.looked == 0 && m.touched.empty()); + std::printf("release: 60,010 live slots, 10 name the buffer: %llu looked at, 10 fixed again\n", + static_cast(looked)); + return 0; +} + +// An alias range removed, replaced and added again; a slot overwritten or zeroed after it was recorded; a release that +// only partly overlaps a slot's range; two slots naming one backing; a buffer that comes back. +int cases() { + Model m(4096); + constexpr std::uint64_t title = 0x200000000000ull, copy_at = 0x400000, other_copy = 0x800000, c = 0x1000000; + m.add_backing(copy_at, 0x20000); + m.add_backing(other_copy, 0x20000); + m.add_backing(c, 0x10000); + m.add_alias(title, 0x20000, copy_at); + m.apply(); + for (std::size_t slot = 0; slot < 8; ++slot) m.write(slot, {title + slot * 0x1000, 0x800}); + EXPECT(m.copy[3][0] == kArena + copy_at + 0x3000 && m.consistent()); + + // Alias change: the range moves to another copy; every slot through it follows, nothing else is fixed. + m.write(100, {c, 0x100}); + m.add_alias(title, 0x20000, other_copy); + m.apply(); + EXPECT(m.touched.size() == 8 && m.copy[3][0] == kArena + other_copy + 0x3000 && m.consistent()); + // Removed: they wait (null in the copy); added again: they are fixed when it comes. + m.remove_alias(title); + m.apply(); + EXPECT(m.touched.size() == 8 && m.copy[3][0] == 0 && m.records.waiting_count() == 8 && m.consistent()); + m.add_alias(title, 0x20000, copy_at); + m.apply(); + EXPECT(m.touched.size() == 8 && m.records.waiting_count() == 0 && m.consistent()); + + // A slot overwritten after it was recorded (it names C now), and one zeroed: a release of their old copy does not + // touch them; the zeroed one keeps no record. + m.write(5, {c + 0x200, 0x100}); + m.zero(6); + m.release_backing(copy_at); + m.apply(); + EXPECT(m.touched.size() == 6); // slots 0-4 and 7 + for (const std::uint32_t slot : m.touched) EXPECT(slot != 5 && slot != 6 && slot != 100); + EXPECT(m.copy[5][0] == kArena + c + 0x200 && m.records.state(6, 0) == ConsoleHeapSlotRecords::none); + EXPECT(m.consistent()); + + // Partial overlap: a release that covers only the tail of a slot's range touches it; one that ends right before + // its range does not. The two slots naming the same bytes are both fixed. + m.add_backing(0x2000000, 0x1000); + m.add_backing(0x2001000, 0x3000); + m.apply(); + m.write(200, {0x2001800, 0x400}); + m.write(201, {0x2001800, 0x400}); + m.write(202, {0x2000000, 0x1000}); // ends where the second backing starts + EXPECT(m.copy[200][0] == kArena + 0x2001800 && m.copy[202][0] == kArena + 0x2000000); + m.release_backing(0x2001000); + m.apply(); + EXPECT(m.touched.size() == 2 && m.touched[0] == 200 && m.touched[1] == 201); + EXPECT(m.copy[200][0] == 0 && m.copy[201][0] == 0 && m.copy[202][0] != 0 && m.consistent()); + // The buffer comes back: the waiting slots are fixed again by the addition, not by a probe. + m.add_backing(0x2001000, 0x3000); + m.apply(); + EXPECT(m.touched.size() == 2 && m.copy[200][0] == kArena + 0x2001800 && m.copy[201][0] == kArena + 0x2001800); + EXPECT(m.consistent()); + + // The counter half on its own, and a refused alias copy: waiting on the copy's address, fixed when it is backed. + constexpr std::uint64_t title2 = 0x300000000000ull, unbacked = 0x3000000; + m.add_alias(title2, 0x10000, unbacked); + m.apply(); + m.write(300, {c, 0x40}, {title2 + 0x40, 4}); + EXPECT(m.copy[300][0] == kArena + c && m.copy[300][1] == 0 && m.records.state(300, 1) == ConsoleHeapSlotRecords::waiting); + m.add_backing(unbacked, 0x10000); + m.apply(); + EXPECT(m.copy[300][1] == kArena + unbacked + 0x40 && m.consistent()); + + // A large range in a granule before the release: found through its span class. + m.add_backing(0x10000000, 0x400000); + m.apply(); + m.write(400, {0x10000000, 0x400000}); + m.release_backing(0x10000000); + m.apply(); + EXPECT(m.touched.size() == 1 && m.touched[0] == 400 && m.copy[400][0] == 0 && m.consistent()); + + // The heap destroyed (its records with it): a new heap of the same size starts with none. + m.records.reset(4096); + m.release_backing(c); + m.apply(); + EXPECT(m.touched.empty() && m.records.recorded() == 0); + std::printf("cases: alias moved, removed and added again; overwritten and zeroed slots; partial overlap; two slots " + "on one backing; a buffer back; a refused alias copy backed later; a large range; a destroyed heap\n"); + return 0; +} + +// Random writes, zeroes, releases, additions and alias changes; after each round of changes the copy must equal a full +// re-resolution, and the entries looked at must stay near what the changes touch. +int differential() { + std::mt19937_64 rng(0x5107); + constexpr std::size_t kSlots = 3000; + Model m(kSlots); + constexpr std::uint64_t kGranule = 0x10000; + std::vector titles; + for (int i = 0; i < 6; ++i) titles.push_back(0x100000000000ull + std::uint64_t(i) * 0x100000); + const auto pick = [&](std::uint64_t n) { return std::uint64_t(rng() % n); }; + std::uint64_t looked = 0, touched = 0; + for (int round = 0; round < 400; ++round) { + for (int op = 0; op < 20; ++op) { + const auto slot = std::size_t(pick(kSlots)); + switch (pick(9)) { + case 0: case 1: case 2: { // a V# into an arena offset, one through an alias, or a counter half too + const auto span = 1 + pick(pick(4) ? 0x2000 : 0x80000); + Model::Words a{pick(2) ? pick(64) * kGranule / 2 + pick(0x800) : titles[pick(6)] + pick(0x80000), span}; + Model::Words b{}; + if (!pick(4)) b = {pick(64) * kGranule / 2, 4}; + m.write(slot, a, b); + break; + } + case 3: m.zero(slot); break; + case 4: { + const auto at = pick(64) * kGranule / 2; + const auto it = m.backings.find(kArena + at); + if (it == m.backings.end()) { + // Not over another backing. + const auto bytes = (1 + pick(8)) * kGranule / 4; + bool free = true; + for (const auto& [lo, hi] : m.backings) free &= !(lo < kArena + at + bytes && hi > kArena + at); + if (free) m.add_backing(at, bytes); + } else { + m.release_backing(at); + } + break; + } + case 5: case 6: { + const auto title = titles[pick(6)] + pick(4) * 0x20000; + m.add_alias(title, (1 + pick(4)) * 0x8000, pick(64) * kGranule / 2); + break; + } + case 7: + if (!m.aliases.empty()) { + auto it = m.aliases.begin(); + std::advance(it, std::ptrdiff_t(pick(m.aliases.size()))); + m.remove_alias(it->first); + } + break; + default: m.fix(slot); break; + } + } + m.apply(); + looked += m.looked; + touched += m.touched.size(); + if (!m.consistent()) { + std::fprintf(stderr, "round %d\n", round); + return 1; + } + } + EXPECT(m.records.recorded() > 0); + // The model's address space is a few MiB, so most changes touch most of it: this case checks results, not cost. + std::printf("differential: 400 rounds, copy equal to a full re-resolution after each; %llu entries looked at, " + "%llu slots fixed again, %zu halves recorded at the end\n", + static_cast(looked), static_cast(touched), + m.records.recorded()); + return 0; +} + +} // namespace + +int main() { + if (release_looks_at_its_slots_only()) return 1; + if (cases()) return 1; + if (differential()) return 1; + std::printf("console_heap_slot_records_test: ok\n"); + return 0; +} diff --git a/runtime/test/console_heap_vsharp_slots_test.cpp b/runtime/test/console_heap_vsharp_slots_test.cpp deleted file mode 100644 index aa56b4fdd3..0000000000 --- a/runtime/test/console_heap_vsharp_slots_test.cpp +++ /dev/null @@ -1,334 +0,0 @@ -// Portable CPU-only unit test for leonida::ConsoleHeapVsharpSlots (runtime/src/console_heap_vsharp_slots.h). -// Verifies bit-for-bit equivalence with a linear scan of 32-byte descriptor slots, boundary handling, range clears, -// callback-time bit clearing (as in refresh_console_heap invalidation passes), and a 5.5 MiB heap stress check. -#include "../src/console_heap_vsharp_slots.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::ConsoleHeapVsharpSlots; - -std::vector collect(const ConsoleHeapVsharpSlots& slots) { - std::vector out; - slots.for_each([&](std::size_t slot) { out.push_back(slot); }); - return out; -} - -int test_predicate_exactness() { - // Primary buffer V#: top 2 bits of w[3] are 0, w[2] (num_records) != 0. - std::uint32_t primary[8] = {0x1000, 0x20, 64, 0x3fffffffu, 0, 0, 0, 0}; - EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(primary)); - - // Counter-only buffer V#: w[2] == 0, w[6] != 0, top 2 bits of w[3] == 0. - std::uint32_t counter[8] = {0, 0, 0, 0, 0x2000, 0, 16, 0}; - EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(counter)); - - // Empty / zeroed V#: w[2] == 0 and w[6] == 0. - std::uint32_t empty[8] = {0x1000, 0, 0, 0x00010000u, 0x2000, 0, 0, 0}; - EXPECT(!ConsoleHeapVsharpSlots::is_live_vsharp(empty)); - - // Image T# (w[3] >> 30 != 0): must NOT be treated as a buffer V# even if w[2]/w[6] are non-zero. - for (std::uint32_t hi : {1u, 2u, 3u}) { - std::uint32_t tsharp[8] = {0x1000, 0, 128, (hi << 30) | 0x55u, 0, 0, 64, 0}; - EXPECT(!ConsoleHeapVsharpSlots::is_live_vsharp(tsharp)); - } - - // not_tsharp zeroes lower 16 bytes (w[0..3] = 0) while leaving upper 16 bytes (w[4..7]): - // if w[6] is non-zero, predicate matches the legacy `!(w[3] >> 30) && (w[2] || w[6])` check. - std::uint32_t not_tsharp_with_hi[8] = {0, 0, 0, 0, 0, 0, 1, 0}; - EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(not_tsharp_with_hi)); - return 0; -} - -int test_boundaries_and_ranges() { - // Zero-size heap. - ConsoleHeapVsharpSlots zero; - zero.reset(0); - EXPECT(zero.empty() && zero.slot_count() == 0 && zero.live_count() == 0); - zero.set(0, true); - zero.clear(0); - zero.clear_range(0, 10); - EXPECT(zero.empty() && !zero.test(0) && collect(zero).empty()); - - // Word boundary sizes: 1, 63, 64, 65, 128, 129, 257. - for (std::size_t n : {std::size_t(1), std::size_t(63), std::size_t(64), std::size_t(65), std::size_t(128), - std::size_t(129), std::size_t(257)}) { - ConsoleHeapVsharpSlots s; - s.reset(n); - EXPECT(s.slot_count() == n && s.empty()); - // Out-of-range writes are ignored. - s.set(n, true); - s.set(n + 100, true); - EXPECT(s.empty() && !s.test(n)); - - // Set every slot, check idempotency and exact ordering. - for (std::size_t i = 0; i < n; ++i) s.set(i, true); - s.set(0, true); - s.set(n - 1, true); - EXPECT(s.live_count() == n); - const auto all = collect(s); - EXPECT(all.size() == n); - for (std::size_t i = 0; i < n; ++i) EXPECT(all[i] == i && s.test(i)); - - // Inverted / empty / past-end clear_range is a no-op. - s.clear_range(5, 5); - s.clear_range(10, 2); - s.clear_range(n, n + 64); - EXPECT(s.live_count() == n); - - // Partial single-word and multi-word clear_range. - if (n >= 129) { - s.clear_range(3, 19); // within word 0 - s.clear_range(60, 128); // spans word 0 tail + all of word 1 - EXPECT(s.live_count() == n - 16 - 68); - EXPECT(s.test(2) && !s.test(3) && !s.test(18) && s.test(19)); - EXPECT(s.test(59) && !s.test(60) && !s.test(127) && s.test(128)); - } - - // Clear past end clamps cleanly. - s.clear_range(0, n + 500); - EXPECT(s.empty() && s.live_count() == 0 && collect(s).empty()); - } - return 0; -} - -int test_in_place_invalidation_mutation() { - // Mirrors refresh_console_heap: for_each visits each live V# slot and calls fix_console_slot, which may clear - // that slot's bit when its backing buffer was released. - ConsoleHeapVsharpSlots s; - s.reset(260); - const std::vector initial = {0, 1, 62, 63, 64, 65, 127, 128, 191, 255, 259}; - for (std::size_t slot : initial) s.set(slot, true); - EXPECT(s.live_count() == initial.size()); - - std::vector visited; - s.for_each([&](std::size_t slot) { - visited.push_back(slot); - // Simulate releasing every even-numbered slot during the invalidation pass. - if ((slot & 1u) == 0) s.set(slot, false); - }); - EXPECT(visited == initial); - - std::vector remaining; - for (std::size_t slot : initial) - if ((slot & 1u) != 0) remaining.push_back(slot); - EXPECT(s.live_count() == remaining.size()); - EXPECT(collect(s) == remaining); - - // Clear the remaining slots and confirm empty fast path visits nothing. - s.for_each([&](std::size_t slot) { s.clear(slot); }); - EXPECT(s.empty() && collect(s).empty()); - return 0; -} - -int test_differential_equivalence_against_linear_copy() { - // Differential model: maintain a synthetic 32-byte-per-slot `heap.copy` buffer alongside ConsoleHeapVsharpSlots - // across thousands of random writes, deferred zeroes, page-range zeroes, and invalidation passes. - constexpr std::size_t kSlots = 1029; - std::vector> gpu_copy(kSlots); - for (auto& slot : gpu_copy) slot.fill(0); - - ConsoleHeapVsharpSlots tracked; - tracked.reset(kSlots); - - auto linear_scan = [&] { - std::vector expected; - for (std::size_t i = 0; i < kSlots; ++i) - if (ConsoleHeapVsharpSlots::is_live_vsharp(gpu_copy[i].data())) expected.push_back(i); - return expected; - }; - - std::uint64_t rng = 0x9e3779b97f4a7c15ull; - auto next_u32 = [&]() -> std::uint32_t { - rng ^= rng >> 12; - rng ^= rng << 25; - rng ^= rng >> 27; - return static_cast((rng * 0x2545f4914f6cdd1dull) >> 32); - }; - - for (unsigned step = 0; step < 4000; ++step) { - const unsigned op = next_u32() % 10; - if (op < 6) { - // Simulate fix_console_slot writing a descriptor to heap.copy. - const std::size_t slot = next_u32() % kSlots; - std::array w{}; - const unsigned kind = next_u32() % 5; - if (kind == 0) { - // Live primary V# - w[0] = next_u32(); - w[2] = (next_u32() % 256) + 1; - w[3] = next_u32() & 0x3fffffffu; - } else if (kind == 1) { - // Live counter V# only - w[6] = (next_u32() % 64) + 1; - } else if (kind == 2) { - // Empty V# (zero records) - w[0] = 0; - w[2] = 0; - w[3] = next_u32() & 0x3fffffffu; - w[6] = 0; - } else if (kind == 3) { - // Image T# - w[2] = 128; - w[3] = (2u << 30) | (next_u32() & 0x3fffffffu); - w[6] = 32; - } else { - // not_tsharp (lower 16B zeroed, upper 16B arbitrary) - w[4] = next_u32(); - w[6] = (next_u32() & 1u) ? 7u : 0u; - } - gpu_copy[slot] = w; - tracked.set(slot, ConsoleHeapVsharpSlots::is_live_vsharp(w.data())); - } else if (op < 8) { - // Simulate fix_console_slots deferred zeroing. - const std::size_t slot = next_u32() % kSlots; - gpu_copy[slot].fill(0); - tracked.clear(slot); - } else if (op == 8) { - // Simulate for_each_zeroed (both page-aligned 128-slot and arbitrary sub-ranges). - const std::size_t first = next_u32() % (kSlots + 16); - const std::size_t len = (next_u32() % 200); - const std::size_t end = first + len; - for (std::size_t i = first; i < end && i < kSlots; ++i) gpu_copy[i].fill(0); - tracked.clear_range(first, end); - } else { - // Simulate refresh_console_heap invalidation pass clearing a subset of visited slots. - const std::vector expected = linear_scan(); - std::vector got; - tracked.for_each([&](std::size_t slot) { - got.push_back(slot); - if ((slot % 3) == 0) { - gpu_copy[slot].fill(0); - tracked.set(slot, false); - } - }); - EXPECT(got == expected); - } - - if ((step & 63) == 63) { - const std::vector expected = linear_scan(); - EXPECT(tracked.live_count() == expected.size()); - EXPECT(collect(tracked) == expected); - } - } - EXPECT(collect(tracked) == linear_scan()); - return 0; -} - -int test_retail_sized_heap_sparse_scan() { - // 5.5 MiB resource heap = 180,224 32-byte slots (matching retail console descriptor heap). - constexpr std::size_t kRetailSlots = (5632u * 1024u) / 32u; - ConsoleHeapVsharpSlots tracked; - tracked.reset(kRetailSlots); - - const std::vector hot = {0, 63, 64, 4095, 4096, 65536, 131072, kRetailSlots - 1}; - for (std::size_t slot : hot) tracked.set(slot, true); - EXPECT(tracked.live_count() == hot.size()); - EXPECT(collect(tracked) == hot); - - // Zero a 4 KiB page (128 slots) containing slots 4096..4223. - tracked.clear_range(4096, 4096 + 128); - EXPECT(!tracked.test(4096) && tracked.test(4095)); - EXPECT(tracked.live_count() == hot.size() - 1); - return 0; -} - -int test_console_fix_budget_buffer_vsharp_non_deferral() { - // Verifies that under fix_console_slots budget expiry (fix_over == true), buffer V# descriptors - // (!(w[3] >> 30)) are never deferred/nulled, while image T# descriptors ((w[3] >> 30) != 0) are deferred. - constexpr std::size_t kSlots = 16; - std::vector> gpu_copy(kSlots); - for (auto& slot : gpu_copy) slot.fill(0); - - ConsoleHeapVsharpSlots tracked; - tracked.reset(kSlots); - - // Populate slots with alternating buffer V# and image T# descriptors: - // Even slots: live buffer V#s - // Odd slots: image T#s - for (std::size_t i = 0; i < kSlots; ++i) { - std::array w{}; - if ((i & 1u) == 0) { - // Buffer V#: w[3] >> 30 == 0, num_records != 0 - w[0] = static_cast(0x1000 + i * 0x100); - w[1] = 0x20; - w[2] = 256; - w[3] = 0x00010000u; // w[3] >> 30 == 0 - } else { - // Image T#: w[3] >> 30 != 0 - w[0] = static_cast(0x5000 + i * 0x100); - w[2] = 128; - w[3] = (2u << 30) | 0x1234u; // w[3] >> 30 == 2 - } - gpu_copy[i] = w; - tracked.set(i, ConsoleHeapVsharpSlots::is_live_vsharp(w.data())); - } - - // Now simulate fix_console_slots when budget is expired (fix_over == true): - // Buffer V#s must be fixed in-place and never nulled/deferred; only image T#s are deferred. - std::size_t deferred_fixes = 0; - std::vector retries; - const bool fix_over = true; - - for (std::size_t slot = 0; slot < kSlots; ++slot) { - const std::array& input = gpu_copy[slot]; - const std::uint32_t w3 = input[3]; - const bool is_buffer_vsharp = !(w3 >> 30); - - if (fix_over && !is_buffer_vsharp) { - // Image T#: deferred past budget - gpu_copy[slot].fill(0); - tracked.clear(slot); - ++deferred_fixes; - retries.push_back(static_cast(slot)); - continue; - } - - // Buffer V#: fixed immediately, not deferred - tracked.set(slot, ConsoleHeapVsharpSlots::is_live_vsharp(input.data())); - } - - // All odd slots (image T#s) must have been deferred (nulled) - EXPECT(deferred_fixes == kSlots / 2); - EXPECT(retries.size() == kSlots / 2); - for (std::size_t slot : retries) { - EXPECT((slot & 1u) == 1u); - EXPECT(!tracked.test(slot)); - EXPECT(gpu_copy[slot][0] == 0 && gpu_copy[slot][2] == 0); - } - - // All even slots (buffer V#s) must have been preserved and remain live - for (std::size_t i = 0; i < kSlots; i += 2) { - EXPECT(tracked.test(i)); - EXPECT(gpu_copy[i][2] == 256); - EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(gpu_copy[i].data())); - } - EXPECT(tracked.live_count() == kSlots / 2); - return 0; -} - -} // namespace - -int main() { - if (test_predicate_exactness()) return 1; - if (test_boundaries_and_ranges()) return 1; - if (test_in_place_invalidation_mutation()) return 1; - if (test_differential_equivalence_against_linear_copy()) return 1; - if (test_retail_sized_heap_sparse_scan()) return 1; - if (test_console_fix_budget_buffer_vsharp_non_deferral()) return 1; - std::printf("console_heap_vsharp_slots_test: ok\n"); - return 0; -} diff --git a/runtime/test/d3d12_unmapped_vsharp_test.cpp b/runtime/test/d3d12_unmapped_vsharp_test.cpp index 2e072ce407..1cb0b7c232 100644 --- a/runtime/test/d3d12_unmapped_vsharp_test.cpp +++ b/runtime/test/d3d12_unmapped_vsharp_test.cpp @@ -232,8 +232,9 @@ int check_console_heap(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fe EXPECT(!(copy[3][0] | copy[3][1] | copy[3][2] | copy[3][3])); // the data slot's descriptor half is null for (int i = 0; i < 4; ++i) EXPECT(!std::memcmp(title + i * kDescriptor, before[i], kDescriptor)); - // 128 cold descriptors share one absent range. Publishing its alias leaves the title bytes - // unchanged. Only the bounded round-robin probes should discover it in the first 64 submits. + // 128 descriptors wait on one absent range; the title's bytes never change. Publishing its alias fixes every one + // of them at the next submission (the heap's slot records: an addition over a waiting V#), not one round-robin + // probe at a time. Ref allocator; Ref list; EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); @@ -241,23 +242,70 @@ int check_console_heap(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fe IID_PPV_ARGS(&list.p)))); EXPECT(SUCCEEDED(list->Close())); ID3D12CommandList* lists[] = {list.p}; - for (unsigned pass = 0; pass < 64; ++pass) { - if (pass == 1) leonida::title_va_aliases().add(unmapped, kViewBytes, b.arena_va); + const auto submit = [&] { queue->ExecuteCommandLists(1, lists); - EXPECT(SUCCEEDED(queue->Signal(fence, ++fence_value))); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr))); - } + return SUCCEEDED(queue->Signal(fence, ++fence_value)) && + SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr)); + }; + const auto count_restored = [&](unsigned& restored) { + restored = 0; + for (unsigned slot = 0; slot < 131; ++slot) { + if (slot > 0 && slot < 4) continue; + std::uint32_t words[8]; + if (!rt::d3d12::read_arena(device, shader_va + slot * kDescriptor, words, sizeof(words))) return false; + if (base_of(words) == b.arena_va && words[2]) ++restored; + else if (!zero_size(words)) return false; + } + return true; + }; unsigned restored = 0; - for (unsigned slot = 0; slot < 131; ++slot) { - if (slot > 0 && slot < 4) continue; + EXPECT(submit()); + EXPECT(count_restored(restored) && restored == 0); + leonida::title_va_aliases().add(unmapped, kViewBytes, b.arena_va); + EXPECT(submit()); + EXPECT(count_restored(restored) && restored == 128); + std::printf("128 waiting zero descriptors, all restored at the first submission after their alias came\n"); + // The alias goes: at the next submission none of them names its copy any more. + leonida::title_va_aliases().remove(unmapped, b.arena_va); + EXPECT(submit()); + EXPECT(count_restored(restored) && restored == 0); + + // A released buffer: the slots that named it are null at the next submission, the others keep their V#s. The + // title's bytes stay as written (each slot is rewritten through its page, as the title does, so the heap's write + // tracking sees it). + { + Ref gone; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto gone_desc = buffer_desc(64 * 1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &gone_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&gone.p)))); + const std::uint64_t gone_va = gone->GetGPUVirtualAddress(); + for (int i = 140; i < 150; ++i) put(i, raw_vsharp(gone_va + std::uint64_t(i - 140) * kViewBytes)); + for (int i = 150; i < 160; ++i) put(i, raw_vsharp(b.arena_va)); + EXPECT(submit()); std::uint32_t words[8]; - EXPECT(rt::d3d12::read_arena(device, shader_va + slot * kDescriptor, words, sizeof(words))); - if (base_of(words) == b.arena_va && words[2]) ++restored; - else EXPECT(zero_size(words)); + for (unsigned slot = 140; slot < 160; ++slot) { + EXPECT(rt::d3d12::read_arena(device, shader_va + slot * kDescriptor, words, sizeof(words))); + EXPECT(words[2] && base_of(words) == (slot < 150 ? gone_va + (slot - 140) * kViewBytes : b.arena_va)); + } + gone.reset(); + // The arena range goes once the device has retired the buffer: a few submissions at most. + bool nulled = false; + for (int pass = 0; pass < 8 && !nulled; ++pass) { + EXPECT(submit()); + nulled = true; + for (unsigned slot = 140; slot < 150; ++slot) { + EXPECT(rt::d3d12::read_arena(device, shader_va + slot * kDescriptor, words, sizeof(words))); + nulled &= zero_size(words); + } + } + EXPECT(nulled); + for (unsigned slot = 150; slot < 160; ++slot) { + EXPECT(rt::d3d12::read_arena(device, shader_va + slot * kDescriptor, words, sizeof(words))); + EXPECT(words[2] && base_of(words) == b.arena_va); + } + std::printf("released buffer: the 10 slots that named it are null at the next submissions, 10 others kept\n"); } - EXPECT(restored == 16); - std::printf("128 settled zero descriptors, %u restored in 64 submissions\n", restored); - leonida::title_va_aliases().remove(unmapped, b.arena_va); // The null guard: past the heap's last slot, up to kHeapIndexReach from its start, every byte reads 0. constexpr std::uint64_t reach = 64ull << 20; diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp index 773360dd52..37a1bd391d 100644 --- a/runtime/test/geometry_views_test.cpp +++ b/runtime/test/geometry_views_test.cpp @@ -468,12 +468,17 @@ int main() { const std::uint64_t own = fly.execute_begin(); leonida::TitleVaAliases aliases; aliases.record_removals(true); - std::uint64_t cursor = 0; - { - leonida::DescriptorRanges skip; - aliases.changed_ranges(cursor, skip); - } - const std::uint64_t invalidations = aliases.invalidations(); + // What the console heaps' slot records are told (TitleVaAliases::add_listener). + struct Heard { + bool removed; + std::uint64_t title_va, bytes, shader_va; + }; + std::vector heard; + aliases.add_listener(&heard, [](void* to, leonida::TitleVaAliases::Change change, std::uint64_t va, + std::uint64_t bytes, std::uint64_t shader_va) { + static_cast*>(to)->push_back( + {change == leonida::TitleVaAliases::Change::removed, va, bytes, shader_va}); + }); leonida::geometry_writes::note_released(flybase, flybase + kView); fly.drain_released(device, rt::d3d12::GeometryViews::kAfterExecutes, submitted, [&](std::uintptr_t source, std::size_t size, VkDeviceSize va) { @@ -483,13 +488,12 @@ int main() { fly.bytes() == kView && g_gone_blocks == gone, "a view retired in before_execute_ is not reaped there, though the GPU is idle"); - leonida::DescriptorRanges changed; - const bool read = aliases.changed_ranges(cursor, changed); - changed.merge(); std::vector> removed; aliases.take_removed(removed); - check(read && aliases.invalidations() != invalidations && changed.overlaps(flybase, kView) && - removed.size() == 1 && removed[0].first == va_f && removed[0].second == kView, + aliases.remove_listener(&heard); + check(heard.size() == 1 && heard[0].removed && heard[0].title_va == flybase && heard[0].bytes == kView && + heard[0].shader_va == va_f && removed.size() == 1 && removed[0].first == va_f && + removed[0].second == kView, "the retirement invalidates the heap slots and key answers made through the view without an alias"); submitted = 8; // this replay's submission diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index f2f8693915..6eadb4beaf 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp @@ -85,29 +85,44 @@ int main() { a.remove(title, arena); a.remove(title + 0x40000, 0x7000000); EXPECT(a.size() == 0); - // Replacing part of an alias removes the entire old interval. Other heaps read independently. - std::uint64_t cursor = 0; - leonida::DescriptorRanges past; - EXPECT(a.changed_ranges(cursor, past)); - auto second = cursor; + // Every listener is told each change as it happens (the console heaps' slot records): an add, the whole old + // interval when part of it is replaced, a removal, a copy forgotten and title memory added. None is dropped, however + // many come (the 4,096-entry ring this replaced fell back to a full sweep), and a removed listener hears nothing. + struct Heard { + leonida::TitleVaAliases::Change change; + std::uint64_t title_va, bytes, shader_va; + }; + std::vector first, second; + const auto hear = [](void* to, leonida::TitleVaAliases::Change change, std::uint64_t va, std::uint64_t bytes, + std::uint64_t shader_va) { + static_cast*>(to)->push_back({change, va, bytes, shader_va}); + }; + using Change = leonida::TitleVaAliases::Change; + a.add_listener(&first, hear); + a.add_listener(&second, hear); EXPECT(a.add(title, size, arena)); - EXPECT(a.add(title+16, 32, arena+4096)); - for (auto* reader : {&cursor, &second}) { - leonida::DescriptorRanges delta; - EXPECT(a.changed_ranges(*reader, delta)); - delta.merge(); - EXPECT(delta.overlaps(title+size-1, 1) && delta.overlaps(title-16, 17)); - EXPECT(!delta.overlaps(title+size, 1) && !delta.overlaps(title-16, 16)); + EXPECT(a.add(title + 16, 32, arena + 4096)); + for (const auto* heard : {&first, &second}) { + EXPECT(heard->size() == 3); + EXPECT((*heard)[0].change == Change::added && (*heard)[0].title_va == title && (*heard)[0].bytes == size); + EXPECT((*heard)[1].change == Change::removed && (*heard)[1].title_va == title && (*heard)[1].bytes == size && + (*heard)[1].shader_va == arena); + EXPECT((*heard)[2].change == Change::added && (*heard)[2].title_va == title + 16 && + (*heard)[2].bytes == 32 && (*heard)[2].shader_va == arena + 4096); } - leonida::DescriptorRangeChanges backing; - for (unsigned i = 0; i < 4097; ++i) backing.record(UINT64_MAX-3, 4); - cursor = 0; - EXPECT(!backing.read(cursor, past)); - backing.record(UINT64_MAX-3, 4); - leonida::DescriptorRanges last; - EXPECT(backing.read(cursor,last)); - last.merge(); - EXPECT(last.overlaps(UINT64_MAX,1) && !last.overlaps(0,1)); + a.remove_listener(&second); + a.remove(title + 16, arena + 4096); + a.forget_copy(title + 0x1000, 0x100, 0x5000000); + a.add_title_memory(0x30000000000ull, 0x2000); + EXPECT(second.size() == 3 && first.size() == 6); + EXPECT(first[3].change == Change::removed && first[3].title_va == title + 16 && first[3].shader_va == arena + 4096); + EXPECT(first[4].change == Change::removed && first[4].title_va == title + 0x1000 && first[4].bytes == 0x100 && + first[4].shader_va == 0x5000000); + EXPECT(first[5].change == Change::memory_added && first[5].title_va == 0x30000000000ull && first[5].bytes == 0x2000); + a.remove_title_memory(0x30000000000ull); + for (unsigned i = 0; i < 5000; ++i) a.forget_copy(title, 4, arena); + EXPECT(first.size() == 5006); + a.remove_listener(&first); // shader_side: whether an address is one the layer wrote for the title (inside some range's copy), so a scan that // sees an already rewritten V# again leaves it alone rather than taking it for an unmapped address. EXPECT(!a.shader_side(arena));