diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index bd9f62ec0..faa1b347c 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1707,8 +1707,30 @@ The copies: (logged once otherwise). - Any **other address in the title's memory** gets a window: the 64 KiB-aligned pages it covers, clipped to the title's range, copied into the arena now and before every submission, through the same shadow refresh as slot 133 - (so dirty-page tracking for that refresh applies to both). Windows stay until the device goes, up to - `LEONIDA_TITLE_WINDOWS_MB` (64 MiB by default). A window that + (so dirty-page tracking for that refresh applies to both). A window never covers bytes an existing range already + serves: it stays inside the free span around the address (and a stream-pool extent inside the free span in both of + the pair's views), because a range entered over a live one replaces it whole, and the copy that range answered from + would be left reached by nothing. Windows stay while an address range still answers from them, up to + `LEONIDA_TITLE_WINDOWS_MB` (64 MiB by default). A window that no range answers from any more (a slot-133 buffer the + title placed over its pages, or a BVH input's exact copy, replaced its ranges) is **retired** after the next + submission's refresh: the alias table's listener records the removed ranges' copies, and a window none of its + ranges is left for loses its stream-pool extent and its bytes of the budget at once. Its memory is freed once every + `ExecuteCommandLists` replay in progress then has recorded its submissions, every command list whose recording + began before the retirement is gone (reset, released, or a held batch's or the async worker's copy of it run), and + the submissions recorded by then have completed: a list resolves its root views when they are recorded, so one + recorded before the retirement and executed, or executed again, after it still names the window + (`src/command_list_epochs.h`). Until then its copy stays a target of its pages' tracker, refreshed like the others, + and what the GPU wrote in it goes back to the title's pages: with its submissions' write-back, and once more when it + is freed (a range noted when a list was recorded can be copied back before a held batch has run). A retired copy goes + back only on the bytes no live copy over them changed, byte by byte (the window and the buffer that replaced it can + each have written their own bytes of one 256-byte piece), and every copy is compared with the title's bytes as + they were before any copy went back. The bytes a retired copy returns are also written into every other copy over + them that still held the title's older bytes, as the next refresh would: a window is freed after its submission's + refresh, and the range that replaced it reads its last bytes in that same submission. `d3d12_title_window_orphans` covers it, with a writing batch held on a fence + while the next submission's refresh retires its window. A window is + not retired when its pages are released or remapped: a retail run measured no release at all of the pages windows + cover (the title remaps its pool frames instead), and the tracker follows the pages. + A tracker the window shared with a copy still live keeps its extent (a retirement never splits one). A window that cannot fit between the title's address reservations can use a separate mapped buffer. The buffer's device address must fit as a positive 47-bit offset from the arena base. The same window cap and dirty-page refresh apply. `LEONIDA_STREAM_BUFFER_WINDOWS=0` requires the window to fit in the arena. @@ -1721,7 +1743,7 @@ The copies: title itself wrote in between keeps the title's newer bytes and its GPU result is dropped. The copy back asks the write watch first (the refresh's own asking comes after it, so a hot page's last answer is a submission old), passes over pages whose mapping changed, that a kernel write may be filling or that xmem maps at another address too, and - writes only the 256-byte pieces where the copy differs from the title's bytes: a read-only view writes nothing and + writes only the bytes where the copy differs from the title's (compared in 256-byte pieces): a read-only view writes nothing and its pages stay guarded. The copy runs under the tracker's lock and can still fault on a page another guard keeps read-only (the geometry watch, another view's shadow): the fault handler asks every tracker over the address, this one included, and on the thread whose copy faulted it does not take that lock again (an SRW lock is not @@ -1738,9 +1760,22 @@ The copies: loses the device. The refusal and the count of zero-size views are logged. - A **stream pool** (the title's CPU view paired with a 16-24 GiB GPU-only alias) is not windowed per request. The GPU-only pages are translated to the CPU view of the same frames (rule B in - that note), and **one mapping serves a page-aligned readable run** of the pool (at most 1 MiB, a geometry copy when - the cap allows, a window otherwise). Both addresses of the pair are entered in the table, so a V# naming either - reaches that one mapping instead of asking for a second one; `LEONIDA_GEOMETRY_MB` is the preferred backing. + that note), and **one mapping serves a page-aligned readable run** of the pool (at most 1 MiB, and never past the + next mapping in either view; a geometry copy when the cap allows, a window otherwise). A request whose byte a + mapping already holds in either view is served by it when the mapping holds all of the request's bytes, and the + other view is entered as far as that mapping reaches. A request never gets a mapping shorter than its bytes (a V#'s + size, 64 KiB for a root view): one that runs into the next mapping, or past the end of the one holding its first + byte, gets one mapping over itself and every window it reaches, each whole, in both views (`title_pool_cover`, + `TitleVaAliases::replace_twin`), and those windows are retired at the next submission. `replace_twin` checks, under + the lock it replaces them under, that every range it would erase is one of those windows: a slot-133 buffer is + entered without the window lock, so one placed in the span after the plan makes it refuse, the new window is dropped + and the request falls back as below. Only with a range in the way + that is not a window (a slot-133 buffer, a geometry copy) or that reaches past the pool in its view, or pages that are + not readable, does it get a zero-size + view: a refusal there would also have the root views a title rings through a pool read zeros where it served them + before. `vsharp_address` asks again, like `TitleVaAliases::resolve`, when the range holding a V#'s base ends before + the V# does. Both addresses of the pair are entered in the table, so a V# naming either reaches that one mapping instead of + asking for a second one; `LEONIDA_GEOMETRY_MB` is the preferred backing. Acceleration-structure destinations and scratch also resolve through the table, and a structure no window holds whole gets a copy of its whole range, so the BVH builder's commands are recorded. - `LEONIDA_GEOMETRY_MB` sets the device-local memory cap for streamed buffer views. The default is 0. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 7bcfa9ef6..e556ce905 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -3999,6 +3999,15 @@ if(TARGET Vulkan::Headers) # the title's pages at the next refresh, and the title's own newer words still win (#1537, WRITE_INVALID). add_test(NAME d3d12_title_window_write_back COMMAND d3d12_title_va_test --window-writeback) set_tests_properties(d3d12_title_window_write_back PROPERTIES SKIP_RETURN_CODE 77) + # No window nothing reaches: a stream-pool request just before an extent stops where it starts, and a window a + # slot-133 buffer replaced is retired at the next submission, its bytes returned and its memory freed. + add_test(NAME d3d12_title_window_orphans COMMAND d3d12_title_va_test --window-orphans) + set_tests_properties(d3d12_title_window_orphans PROPERTIES SKIP_RETURN_CODE 77) + # The same with no per-submission copy back: a retired window's GPU writes reach the title's pages only when it + # is freed, on the bytes no live copy changed (a buffer over the same 256-byte piece wrote the others). + add_test(NAME d3d12_title_window_orphans_free COMMAND d3d12_title_va_test --window-orphans) + set_tests_properties(d3d12_title_window_orphans_free PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_TITLE_WRITEBACK=0") # A write-back copy that faults on a page another guard (a geometry watch cell) keeps read-only: the fault # handler asks the tracker whose copy faulted too, which must not take its lock again on that thread (#2418). add_test(NAME d3d12_title_window_write_back_fault COMMAND d3d12_title_va_test --window-writeback-fault) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 3bad0b767..2c948ff3d 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -331,6 +331,12 @@ bool title_shadow_buffer(ID3D12Resource* resource); std::uint64_t title_host_imports(ID3D12Device* device); // VirtualQuery calls made by the title-buffer shadows in their latest refresh. For tests. std::uint64_t title_shadow_refresh_queries(ID3D12Device* device); +// The device's title windows now: how many and their bytes, how many were retired with their pages, and how many of +// those still wait for the GPU before their memory is freed. For tests. +struct TitleWindows { + std::uint64_t count = 0, bytes = 0, retired = 0, waiting = 0; +}; +TitleWindows title_windows(ID3D12Device* device); // The trackers behind the title-buffer shadows and title windows (copies whose pages overlap or touch share one). // For tests. std::uint64_t title_shadow_trackers(ID3D12Device* device); diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h index 02f9590ba..58649a29c 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h @@ -383,6 +383,18 @@ class GeometryViews { executing_.push_back(++execute_serial_); return execute_serial_; } + // The last replay begun, and the oldest still in progress (kAfterExecutes when none): what execute_end stamps by, + // for a copy the device retires the same way outside these views (a title window, DeviceState::retire_windows). + std::uint64_t execute_epoch() { + std::lock_guard lock(execute_mutex_); + return execute_serial_; + } + std::uint64_t oldest_execute() { + std::lock_guard lock(execute_mutex_); + std::uint64_t oldest = kAfterExecutes; + for (const auto s : executing_) oldest = (std::min)(oldest, s); + return oldest; + } // The replay that began with `serial` has recorded its submissions. Views retired while only replays now finished // were in progress get submitted() (the context's submitted_retire_ticket(), read here, after those replays // recorded theirs) as their retire ticket. Lock order: mutex_ -> execute_mutex_, as in retire_range. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e7980daee..f4d1dbef0 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -31,6 +31,7 @@ #include "d3d12_xs_native_pso.h" #include "dxgi_com.h" #include "../src/arena_size.h" +#include "../src/command_list_epochs.h" #include "../src/value_write_sink.h" #include "../src/address_guard.h" #include "../src/arena_blocks.h" @@ -415,7 +416,10 @@ class ShadowPages { // read-only binding's pages alone (guarded, so a write the title makes meanwhile faults and waits on the lock), // where opening them for a whole copy lost a write made between the opening and the copy; and of two copies of // the same bytes only the one that differs is written, where the last one won. - std::size_t write_back(std::uintptr_t from, std::uintptr_t to) { + // + // `only` (a retired window's copy, when it is freed): that copy alone goes back, where no live copy changed the + // bytes; the live copies' own results wait for their submissions' batches. + std::size_t write_back(std::uintptr_t from, std::uintptr_t to, const std::uint8_t* only = nullptr) { from = std::max(from, first_), to = std::min(to, last_); if (from >= to) return 0; AcquireSRWLockExclusive(&lock_); @@ -469,22 +473,68 @@ class ShadowPages { if (!held((at - first_) / kPage)) { const std::uintptr_t a = std::max(at, from), b = std::min(at + pages * kPage, to); bool opened = false; - for (const Target& t : targets_) { - const std::uintptr_t x = std::max(a, t.begin), y = std::min(b, t.end); - if (x >= y || !t.shadow) continue; - for (std::uintptr_t c = x; c < y;) { - const std::uintptr_t e = std::min(y, (c + kPiece) & ~(kPiece - 1)); - const std::uint8_t* copy = t.shadow + (c - t.begin); - if (std::memcmp(reinterpret_cast(c), copy, e - c) != 0) { - if (!opened) { - reopen_locked(at, at + pages * kPage); - opened = true; + Vector over; // the targets with bytes in [a, b) + for (const Target& t : targets_) + if (t.shadow && std::max(a, t.begin) < std::min(b, t.end)) over.push_back(&t); + // Piece by piece, against the title's bytes as they were before any copy went back here: a copy goes + // back on the bytes it holds differently from those, so one that still holds them is not written over + // another's result. A retired window's copy (retire_target) goes back only on bytes no live copy + // changed: what a submission wrote in it is older than what a live copy holds (the range that + // replaced it serves every submission recorded since). Byte by byte, as two copies can share a piece + // with disjoint bytes each. + for (std::uintptr_t c = a; c < b && !over.empty();) { + const std::uintptr_t e = std::min(b, (c + kPiece) & ~(kPiece - 1)); + std::uint8_t before[kPiece]; + bool live[kPiece]; // the bytes a live copy changed, once `saved` + bool saved = false; + for (int pass = 0; pass < 2; ++pass) + for (const Target* t : over) { + if (t->retired != (pass == 1) || (only && pass == 1 && t->shadow != only)) continue; + const std::uintptr_t x = std::max(c, t->begin), y = std::min(e, t->end); + if (x >= y) continue; + const std::uint8_t* copy = t->shadow + (x - t->begin); + const void* now = saved ? static_cast(before + (x - c)) + : reinterpret_cast(x); + if (std::memcmp(now, copy, y - x) == 0) continue; + if (!saved) { + std::memcpy(before, reinterpret_cast(c), e - c); + std::fill_n(live, e - c, false); + saved = true; + } + const auto goes = [&](std::uintptr_t v) { + return copy[v - x] != before[v - c] && !(pass == 1 && live[v - c]); + }; + for (std::uintptr_t i = x; i < y;) { + if (!goes(i)) { + ++i; + continue; + } + std::uintptr_t j = i + 1; + while (j < y && goes(j)) ++j; + if (pass == 0) std::fill(live + (i - c), live + (j - c), true); + if (pass == 1 || !only) { // `only`: the live copies' results wait for their batches + if (!opened) { + reopen_locked(at, at + pages * kPage); + opened = true; + } + std::memcpy(reinterpret_cast(i), copy + (i - x), j - i); + written += j - i; + } + // A retired copy's bytes are the title's now: the copies that held the older ones + // take them too, as the next refresh would, so one read before it (the range that + // replaced the window, when the window is freed after this submission's refresh) + // is not behind the title. A copy that changed a byte keeps its own. + if (pass == 1) + for (const Target* o : over) { + if (o == t) continue; + for (std::uintptr_t v = std::max(i, o->begin); v < std::min(j, o->end); ++v) + if (o->shadow[v - o->begin] == before[v - c]) + o->shadow[v - o->begin] = copy[v - x]; + } + i = j; } - std::memcpy(reinterpret_cast(c), copy, e - c); - written += e - c; } - c = e; - } + c = e; } } at += pages * kPage; @@ -853,6 +903,22 @@ class ShadowPages { } } + // Under shadow_mutex: `shadow` is a retired window's copy (retire_orphan_windows). It is still refreshed, so it + // never holds bytes older than the title's but what the GPU wrote in it, and what it holds goes back only where + // no live copy changed the bytes (write_back). False when it isn't one of this tracker's. + bool retire_target(const std::uint8_t* shadow) { + AcquireSRWLockExclusive(&lock_); + bool found = false; + for (Target& t : targets_) + if (t.shadow == shadow) t.retired = found = true; + ReleaseSRWLockExclusive(&lock_); + return found; + } + + bool has_target(const std::uint8_t* shadow) const { + return std::any_of(targets_.begin(), targets_.end(), [shadow](const Target& t) { return t.shadow == shadow; }); + } + // Under shadow_mutex: `shadow` is no longer a target. Pages no other target covers are made writable again and // passed over from now on. False when it isn't one of this tracker's. bool remove_target(const std::uint8_t* shadow) { @@ -1256,6 +1322,7 @@ class ShadowPages { struct Target { std::uintptr_t begin, end; // the title's bytes std::uint8_t* shadow; // where begin's byte goes + bool retired = false; // a window nothing answers from, kept until its submissions are copied back }; static Kind classify(const MEMORY_BASIC_INFORMATION& region) { @@ -3086,6 +3153,26 @@ struct DeviceState { for (std::size_t k = hits.size(); k-- > 1;) shadows.erase(shadows.begin() + std::ptrdiff_t(hits[k])); keep.fill(begin, end, shadow); } + void retire_shadow(const std::uint8_t* mapped) { + std::lock_guard lock(shadow_mutex); + for (const ShadowPagesPtr& s : shadows) + if (s->retire_target(mapped)) return; + } + // A retired window's memory is freed: what its copy holds that the title's pages do not, written by submissions + // that have all completed, goes back once more (where no live copy changed those bytes), then the copy leaves + // its tracker. + void free_retired_shadow(const std::uint8_t* mapped, std::uint64_t start, std::uint64_t size) { + std::lock_guard lock(shadow_mutex); + for (auto it = shadows.begin(); it != shadows.end(); ++it) { + ShadowPages& s = **it; + if (!s.has_target(mapped)) continue; + title_write_back_total += s.write_back(static_cast(start), + static_cast(start + size), mapped); + s.remove_target(mapped); + if (!s.targets()) shadows.erase(it); + return; + } + } void remove_shadow(const std::uint8_t* mapped) { std::lock_guard lock(shadow_mutex); for (auto it = shadows.begin(); it != shadows.end(); ++it) @@ -3217,13 +3304,17 @@ struct DeviceState { // Windows of the title's own memory in the GPU address arena (src/title_va_alias.h, docs/d3d12_vulkan.md // section 3.3 "Title-chosen addresses"): a root view or buffer V# that names the title's memory outside any // slot-133 buffer (a per-frame constant ring, #8862 section 3.5) gets a copy of the 64 KiB-aligned pages it - // covers, refreshed before every submission like a slot-133 shadow, and the address of that copy. Windows are - // kept until the device goes (the ring comes round to the same pages), up to LEONIDA_TITLE_WINDOWS_MB (64 MiB - // by default). A window that does not fit is not made: the range is backed by a geometry copy instead, or the - // view written with a zero-size range (src/title_window_plan.h). + // covers, refreshed before every submission like a slot-133 shadow, and the address of that copy. A window never + // covers bytes an existing range already serves (it stays inside the free span, in both views of a stream pool), + // and is kept while an address range still answers from it (the ring comes round to the same pages), up to + // LEONIDA_TITLE_WINDOWS_MB (64 MiB by default); one a newer range replaced everywhere is retired + // (retire_orphan_windows). A window that does not fit is not made: the range is backed by a geometry copy + // instead, or the view written with a zero-size range (src/title_window_plan.h). struct TitleWindow { std::uint64_t start; std::uint64_t shader_va; + std::uint64_t size; + std::uint8_t* mapped; // the copy, as the tracker of its pages writes it }; static constexpr std::uint64_t kTitleWindowAlign = 65536; static constexpr std::uint64_t kTitleWindowMax = 16ull << 20; // the most one address pulls in @@ -3252,9 +3343,10 @@ struct DeviceState { static constexpr std::size_t kTitleWriteBackBatches = 64; // pending batches before the oldest goes back unfenced static constexpr std::size_t kTitleWriteBackRanges = 8192; // ranges kept per submission static constexpr std::uint64_t kTitleWriteBackBytes = 64ull << 20; // bytes copied back per submission - // The stream pools' mappings (title_gpu_views): one per readable run of a pool. A window is kept for the device's - // life; a geometry copy goes when its view is retired (the pages were freed, unmapped or remapped: - // drain_geometry_releases), and the next request for those pages makes a new one. + // The stream pools' mappings (title_gpu_views): one per readable run of a pool that no other mapping serves yet. A + // window goes once no address answers from it (retire_orphan_windows); a geometry copy goes when its view is + // retired (the pages were freed, unmapped or remapped: drain_geometry_releases), and the next request for those + // pages makes a new one. struct PoolSpan { std::uint64_t source; // the readable side of the pair the copy is made from std::uint64_t twin; // the extent's address in the pair's other view (0 when there is none) @@ -3265,9 +3357,35 @@ struct DeviceState { std::vector pool_spans; std::atomic pool_span_count{0}; std::uint64_t pool_span_bytes = 0; - std::uint64_t pool_spans_retired = 0; // geometry-copy extents whose view was retired (forget_pool_span) + std::uint64_t pool_spans_retired = 0; // extents gone with their copy (forget_pool_span, retire_orphan_windows) std::uint64_t title_window_refusals = 0; // windows neither the budget nor the arena allowed std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) + std::uint64_t pool_covers = 0; // stream-pool requests given one mapping over windows they ran into + + // Title windows no address range answers from any more (retire_orphan_windows): the removed ranges' copies, as the + // alias table's listener records them, and the retired windows whose memory waits for the GPU: freed as a retired + // geometry view's is, once every replay in progress at the retirement has recorded its submissions (ticket + // kAfterExecutes until then, see stamp_retired_windows) and those have completed. A command list resolves its root + // views when they are recorded, so a list recorded before the retirement and executed (again) after it still + // names the window: the ticket is taken only once every list (and every copy a held batch or the async worker + // keeps) whose recording began before the retirement is gone (src/command_list_epochs.h). Its copy stays a target + // of its pages' tracker until then, still refreshed: what those submissions wrote in it goes back to the title's + // pages (write_back_titles, and once more when it is freed), not dropped with it. + struct RetiredWindow { + std::uint64_t start, shader_va, size, ticket, epoch; + std::uint8_t* mapped; + std::uint64_t lists; // the command-list epoch of the retirement + }; + static constexpr std::size_t kWindowAliasRemovals = 4096; // kept before every window is looked at instead + std::mutex window_alias_removal_mutex; // a leaf: taken in alias_changed, under the alias table's lock + std::vector> window_alias_removals; // (shader VA, bytes) + bool window_alias_removals_overflow = false; + std::atomic window_alias_removals_pending{false}; + std::mutex retired_window_mutex; // taken under title_window_mutex; only GeometryViews' execute_mutex_ under it + std::vector retired_windows; + std::atomic retired_window_count{0}; + std::atomic retired_windows_unstamped{false}; + std::uint64_t title_windows_retired = 0, title_window_bytes_retired = 0, window_retirements = 0; rt::d3d12::GeometryViews geometry; // A retired geometry view: its alias ranges go, and so does every answer made through it without one @@ -3311,6 +3429,135 @@ struct DeviceState { pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); ++pool_spans_retired; } + // After this submission's refresh (the windows' last copy is the one it made): a title window no address range + // answers from any more leaves the refresh. Its ranges went because a newer range was entered over them (a + // slot-133 buffer placed over the pages, a BVH input's exact copy, src/title_va_alias.h add), and a window nothing + // reaches is only cost: its tracker walks its pages at every refresh and its bytes count against + // LEONIDA_TITLE_WINDOWS_MB. Its stream-pool extent and its budget go at once; its copy leaves its tracker and its + // memory is freed later (retired_windows), and the retired windows due are freed here. Only windows whose copy a + // removed range answered from are looked at (alias_changed records those). + void retire_orphan_windows() { + if (!context || (!window_alias_removals_pending.load(std::memory_order_acquire) && + !retired_window_count.load(std::memory_order_acquire))) + return; + std::vector> removed; // (shader VA, bytes) + bool every = false; + { + std::lock_guard lock(window_alias_removal_mutex); + removed.swap(window_alias_removals); + every = window_alias_removals_overflow; + window_alias_removals_overflow = false; + window_alias_removals_pending.store(false, std::memory_order_release); + } + stamp_retired_windows(); // lists reset or released since the last replay + const std::uint64_t completed = context->completed_retire_ticket(); + std::lock_guard windows(title_window_mutex); + free_retired_windows(completed); + if (removed.empty() && !every) return; + std::sort(removed.begin(), removed.end()); + std::uint64_t longest = 0; + for (const auto& r : removed) longest = std::max(longest, r.second); + const auto touched = [&](const TitleWindow& window) { // a removed range answered from inside this copy + if (every) return true; + auto it = std::lower_bound(removed.begin(), removed.end(), + std::pair{window.shader_va + window.size, std::uint64_t(0)}); + while (it != removed.begin()) { + --it; + if (window.shader_va - std::min(window.shader_va, it->first) >= longest) break; + if (it->first + it->second > window.shader_va) return true; + } + return false; + }; + auto& aliases = leonida::title_va_aliases(); + std::vector gone; // shader VAs of the windows retired, sorted below + for (const TitleWindow& window : title_windows) + if (touched(window) && !aliases.answers_into(window.shader_va, window.size)) + gone.push_back(window.shader_va); + if (gone.empty()) return; + std::sort(gone.begin(), gone.end()); + const auto is_gone = [&](std::uint64_t va) { return std::binary_search(gone.begin(), gone.end(), va); }; + const std::size_t spans = pool_spans.size(); + std::erase_if(pool_spans, [&](const PoolSpan& span) { + if (span.geometry || !is_gone(span.shader_va)) return false; + pool_span_bytes -= span.size; + return true; + }); + pool_spans_retired += spans - pool_spans.size(); + pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); + std::vector retiring; + const std::uint64_t epoch = geometry.execute_epoch(); + const std::uint64_t lists = leonida::command_list_epochs::advance(); + std::uint64_t bytes = 0; + std::erase_if(title_windows, [&](const TitleWindow& window) { + if (!is_gone(window.shader_va)) return false; + retire_shadow(window.mapped); + retiring.push_back({window.start, window.shader_va, window.size, rt::d3d12::GeometryViews::kAfterExecutes, + epoch, window.mapped, lists}); + title_window_bytes -= window.size; + bytes += window.size; + return true; + }); + title_window_count.store(title_windows.size(), std::memory_order_relaxed); + { + std::lock_guard retired(retired_window_mutex); + retired_windows.insert(retired_windows.end(), retiring.begin(), retiring.end()); + retired_window_count.store(retired_windows.size(), std::memory_order_release); + retired_windows_unstamped.store(true, std::memory_order_release); + } + title_windows_retired += retiring.size(); + title_window_bytes_retired += bytes; + ++window_retirements; + if (window_retirements <= 4 || !(window_retirements & (window_retirements - 1))) + std::fprintf(stderr, "[rt] d3d12: %zu title windows (%llu KiB) no address answers from any more were " + "retired (%zu windows, %llu KiB left; %llu retired, %llu KiB returned so far)\n", + retiring.size(), static_cast(bytes >> 10), title_windows.size(), + static_cast(title_window_bytes >> 10), + static_cast(title_windows_retired), + static_cast(title_window_bytes_retired >> 10)); + } + // The memory of retired windows whose submissions have completed by `completed`; what their copies hold goes back + // once more first (free_retired_shadow). title_window_mutex held. + void free_retired_windows(std::uint64_t completed) { + std::vector due; + { + std::lock_guard retired(retired_window_mutex); + std::erase_if(retired_windows, [&](const RetiredWindow& window) { + if (window.ticket == rt::d3d12::GeometryViews::kAfterExecutes || window.ticket > completed) + return false; + due.push_back(window); + return true; + }); + retired_window_count.store(retired_windows.size(), std::memory_order_release); + } + for (const RetiredWindow& window : due) { + free_retired_shadow(window.mapped, window.start, window.size); + if (window.shader_va < arena.size) { + arena_release(window.shader_va, window.size, arena_buffer); + } else { + backing(arena.address + window.shader_va, window.size, window.start, false); + external_windows.free(*this, window.shader_va, window.size); + } + } + } + // A replay has recorded its submissions, or a refresh runs: retired windows that only replays now finished and + // only lists now gone may name get the submissions recorded so far as their ticket (GeometryViews::execute_end + // does the same for its views, by replays alone). + void stamp_retired_windows() { + if (!retired_windows_unstamped.load(std::memory_order_acquire)) return; + // Under the lock: a window retired by a replay begun after `oldest` was read must not be stamped here. + std::lock_guard retired(retired_window_mutex); + const std::uint64_t oldest = geometry.oldest_execute(); + // Before the ticket: a list released after this read has had its submissions counted in it. + const std::uint64_t oldest_list = leonida::command_list_epochs::oldest(); + const std::uint64_t ticket = context->submitted_retire_ticket(); + bool left = false; + for (RetiredWindow& window : retired_windows) { + if (window.ticket != rt::d3d12::GeometryViews::kAfterExecutes) continue; + if (window.epoch < oldest && window.lists <= oldest_list) window.ticket = ticket; + else left = true; + } + retired_windows_unstamped.store(left, std::memory_order_release); + } // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases). // A plain aggregate on purpose: a C++ thread_local with a destructor in gta6rt.exe adds TLS callbacks to the image // the loader's TLS index-0 move must not have (pe_loader.cpp reserve_tls_index0; VulkanContext::stage_xdxr_table @@ -3325,14 +3572,14 @@ struct DeviceState { thread_local GeometryExecuteSerials serials; return serials; } + // Kept with geometry copies off too: a retired title window waits for the same replays (stamp_retired_windows). void geometry_execute_begin() { - if (!geometry.cap()) return; auto& serials = geometry_execute_serials(); if (serials.count == GeometryExecuteSerials::kCapacity) { static std::atomic logged{false}; if (!logged.exchange(true)) - std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists nested more than %u deep; a geometry view retired " - "in the extra replay is not deferred to it\n", + std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists nested more than %u deep; a geometry view or " + "title window retired in the extra replay is not deferred to it\n", GeometryExecuteSerials::kCapacity); ++serials.skipped; return; @@ -3340,7 +3587,6 @@ struct DeviceState { serials.serials[serials.count++] = geometry.execute_begin(); } void geometry_execute_end() { - if (!geometry.cap()) return; auto& serials = geometry_execute_serials(); if (serials.skipped != 0) { --serials.skipped; @@ -3349,6 +3595,7 @@ struct DeviceState { if (serials.count == 0) return; const std::uint64_t serial = serials.serials[--serials.count]; geometry.execute_end(serial, [this] { return context->submitted_retire_ticket(); }); + stamp_retired_windows(); } static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { using Result = rt::d3d12::GeometryCopy; @@ -3426,9 +3673,11 @@ struct DeviceState { // A window for [start, start + size): an arena range or a block outside the arena, charged to // LEONIDA_TITLE_WINDOWS_MB and refreshed before every submission by the tracker of its pages. 0 when neither the - // budget nor the arena has room. title_window_mutex held. - std::uint64_t make_title_window(std::uint64_t start, std::uint64_t size) { - if (!leonida::title_window_fits(title_window_cap, title_window_bytes, size)) { + // budget nor the arena has room. `credit`: bytes of windows this one replaces, retired at the next submission + // (cover_pool_request), not counted against it. title_window_mutex held. + std::uint64_t make_title_window(std::uint64_t start, std::uint64_t size, std::uint64_t credit = 0) { + if (!leonida::title_window_fits(title_window_cap, title_window_bytes - std::min(credit, title_window_bytes), + size)) { ++title_window_refusals; log_once("title memory named by a shader address is past LEONIDA_TITLE_WINDOWS_MB, no window; MiB copied " "so far:", @@ -3451,7 +3700,7 @@ struct DeviceState { if (offset >= arena.size) backing(arena.address + offset, size, start, true); const auto* pages = reinterpret_cast(static_cast(start)); add_shadow(pages, mapped, std::size_t(size)); - title_windows.push_back({start, offset}); + title_windows.push_back({start, offset, size, mapped}); title_window_count.store(title_windows.size(), std::memory_order_relaxed); title_window_bytes += size; if (title_windows.size() <= 4 || !(title_windows.size() & (title_windows.size() - 1))) @@ -3461,6 +3710,24 @@ struct DeviceState { static_cast(title_window_bytes >> 10)); return offset; } + // Undoes make_title_window for a window no range was entered for (the table refused the mapping): nothing has + // answered from it, so no submission names it and its memory goes at once. title_window_mutex held. + void drop_title_window(std::uint64_t shader_va) { + const auto it = std::find_if(title_windows.begin(), title_windows.end(), + [&](const TitleWindow& window) { return window.shader_va == shader_va; }); + if (it == title_windows.end()) return; + const TitleWindow window = *it; + title_windows.erase(it); + title_window_count.store(title_windows.size(), std::memory_order_relaxed); + title_window_bytes -= window.size; + remove_shadow(window.mapped); + if (window.shader_va < arena.size) { + arena_release(window.shader_va, window.size, arena_buffer); + } else { + backing(arena.address + window.shader_va, window.size, window.start, false); + external_windows.free(*this, window.shader_va, window.size); + } + } // A binding of the title's memory reached for the coming submission: keep its range for the copy back after it. // Over-inclusive on purpose (a read-only view costs a copy, a write is never missed: a V# has no read/write bit). @@ -3559,78 +3826,137 @@ struct DeviceState { // held. bool resolve_pool_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { leonida::title_gpu_views::Range view{}; - if (!leonida::title_gpu_views::view_at(static_cast(va), - static_cast(std::max(bytes, 1)), view)) - return false; - const std::uint64_t offset = va >= view.gpu && va - view.gpu < view.size ? va - view.gpu : va - view.cpu; - // Rule B: the CPU view where the host reads the frames, the GPU-only pages only when that view has none. - const std::uint64_t source = leonida::title_gpu_views::to_host_view(static_cast(va), - static_cast( - std::max(bytes, 1))); - const std::uint64_t twin = leonida::title_gpu_views::other_view(static_cast(source)); - const std::uint64_t twin_view = twin ? twin : source; // the pair always has two addresses - if (!readable_page(source)) { + if (!leonida::title_gpu_views::view_at(static_cast(va), 1, view)) return false; + const auto want = std::max(bytes, 1); + const auto unbacked = [&] { out = 0; ++unbacked_requests; note_unbacked("stream pool", va, bytes); return true; - } + }; + const std::uint64_t offset = va >= view.gpu && va - view.gpu < view.size ? va - view.gpu : va - view.cpu; + if (want > view.size - offset) return unbacked(); + // Rule B: the CPU view where the host reads the frames, the GPU-only pages only when that view has none. + const std::uint64_t source = leonida::title_gpu_views::to_host_view(static_cast(va), want); + const std::uint64_t twin = leonida::title_gpu_views::other_view(static_cast(source)); + const std::uint64_t twin_view = twin ? twin : source; // the pair always has two addresses + auto& aliases = leonida::title_va_aliases(); + const auto other = source == va ? twin_view : source; + const auto max_size = std::min(view.size - offset, kPoolExtentMax); + const auto reuse = [&] { return aliases.reuse_pool_mapping(va, other, want, max_size, out); }; + if (reuse()) return true; + if (!readable_page(source)) return unbacked(); const std::uint64_t pool_end = (source >= view.gpu && source - view.gpu < view.size ? view.gpu : view.cpu) + view.size; const std::uint64_t run_end = readable_run_end(source & ~(kTitleWindowAlign - 1), std::min(pool_end, source + kPoolExtentMax)); + // Up to the next mapping in either view at most, never over it. leonida::TitleWindowRange extent{}; if (!leonida::title_pool_extent(source - offset, pool_end, source, run_end, kTitleWindowAlign, kPoolExtentMax, - extent)) { - out = 0; - ++unbacked_requests; - note_unbacked("stream pool", va, bytes); + extent)) + return unbacked(); + std::uint64_t source_lo, source_hi, twin_lo, twin_hi; + aliases.gap(source, source_lo, source_hi); + aliases.gap(twin_view, twin_lo, twin_hi); + // A request that runs past what would serve it, the mapping holding its first byte or the extent clipped + // at the next one, gets one mapping over itself and the windows it reaches (cover_pool_request) rather than + // a zero-size view; only a range that is not a window in the way (a slot-133 buffer, a geometry copy) still + // leaves it with none. + const std::uint64_t request_end = source + want; + if (!leonida::clip_title_pool_extent(extent, source, twin_view, source_lo, source_hi, twin_lo, twin_hi)) + return reuse() || cover_pool_request(source, twin_view, source, request_end, source - offset, pool_end, + out) || + unbacked(); + if (want > std::min(extent.size - (source - extent.start), run_end - source)) + return reuse() || + cover_pool_request(source, twin_view, extent.start, request_end, source - offset, pool_end, out) || + unbacked(); + const auto twin_start = twin_view - (source - extent.start); + std::uint64_t shader = 0; + if (geometry.cap() && watch_shadow_writes() && !context->knows_buffer_va(extent.start, extent.size)) + shader = geometry.resolve(*this, extent.start, extent.size, copy_geometry); + const bool geometry_copy = shader != 0; + if (!shader) shader = make_title_window(extent.start, extent.size); + if (!shader) return reuse() || unbacked(); + if (!aliases.add_twin(extent.start, twin_start, extent.size, shader)) { + if (!geometry_copy) drop_title_window(shader); + return reuse() || unbacked(); + } + pool_spans.push_back({extent.start, twin_start, shader, extent.size, geometry_copy}); + pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); + pool_span_bytes += extent.size; + if (pool_spans.size() <= 4 || !(pool_spans.size() & (pool_spans.size() - 1))) + std::fprintf(stderr, + "[rt] d3d12: a %llu KiB stream-pool extent is one %s mapping (alias 0x%llx and CPU view " + "0x%llx share shader VA 0x%llx; %zu extents, %llu KiB)\n", + static_cast(extent.size >> 10), + geometry_copy ? "geometry-copy" : "window", static_cast(twin_view), + static_cast(source), static_cast(shader), + pool_spans.size(), static_cast(pool_span_bytes >> 10)); + out = shader + (source - extent.start); + return true; + } + + // One mapping for a stream-pool request [source, end) that what would serve it stops short of: the extent from + // `start` clipped at the next mapping, or the mapping holding `source`, ends first (title_pool_cover). It covers + // the request and, whole, the windows it reaches in either view; the range entered over theirs replaces them + // (TitleVaAliases::replace_twin), and they are retired at the next submission like any window nothing answers + // from (retire_orphan_windows), what the GPU wrote in them copied back first. Their bytes are not charged twice + // meanwhile. False when another kind of range is in the way (a slot-133 buffer, a geometry copy), the pages are not + // all readable, or the mapping cannot be made. title_window_mutex held. + bool cover_pool_request(std::uint64_t source, std::uint64_t twin_view, std::uint64_t start, std::uint64_t end, + std::uint64_t pool_lo, std::uint64_t pool_end, std::uint64_t& out) { + std::vector replaced; // title_windows entries the ranges in the way answer from + const auto window_of = [&](std::uint64_t shader_va) { + std::size_t i = 0; + for (; i < title_windows.size(); ++i) + if (shader_va - title_windows[i].shader_va < title_windows[i].size) break; + return i; + }; + const auto owned = [&](std::uint64_t shader_va) { + const std::size_t i = window_of(shader_va); + if (i == title_windows.size()) return false; + if (std::find(replaced.begin(), replaced.end(), i) == replaced.end()) replaced.push_back(i); return true; - } - const std::uint64_t twin_start = twin_view - (source - extent.start); // the same pages in the other view + }; + // What replace_twin may erase: only those windows. A slot-133 buffer is entered without title_window_mutex, + // so one may have been placed over the cover's span (in either view) since it was planned. + const auto planned = [&](std::uint64_t shader_va) { + return std::find(replaced.begin(), replaced.end(), window_of(shader_va)) != replaced.end(); + }; auto& aliases = leonida::title_va_aliases(); - // A mapping that already holds the extent's start (a buffer made over these pages, or a window from another - // request) serves the request only as far as it reaches: claim that much, never bytes it does not cover. - std::uint64_t shader = 0, available = 0; - if (aliases.range_of(extent.start, shader, available) || - aliases.range_of(twin_start, shader, available)) { - if (available < extent.size) { - if (available <= source - extent.start) shader = 0; - else extent.size = available; - } - } - if (shader) { - // Both addresses must reach it. The address the mapping was found at keeps its own (possibly wider) - // range: adding a shorter one over it would drop bytes another view still uses. - if (aliases.shader_va(twin_start) == twin_start) aliases.add(twin_start, extent.size, shader); - if (aliases.shader_va(extent.start) == extent.start) aliases.add(extent.start, extent.size, shader); - } else { - bool geometry_copy = false; - if (geometry.cap() && watch_shadow_writes() && !context->knows_buffer_va(extent.start, extent.size)) { - shader = geometry.resolve(*this, extent.start, extent.size, copy_geometry); - geometry_copy = shader != 0; - } - if (!shader) shader = make_title_window(extent.start, extent.size); - if (!shader) { - out = 0; - ++unbacked_requests; - note_unbacked("stream pool", va, bytes); - return true; - } - aliases.add_twin(extent.start, twin_start, extent.size, shader); - pool_spans.push_back({extent.start, twin_start, shader, extent.size, geometry_copy}); - pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); - pool_span_bytes += extent.size; - if (pool_spans.size() <= 4 || !(pool_spans.size() & (pool_spans.size() - 1))) - std::fprintf(stderr, - "[rt] d3d12: a %llu KiB stream-pool extent is one %s mapping (alias 0x%llx and CPU view " - "0x%llx share shader VA 0x%llx; %zu extents, %llu KiB)\n", - static_cast(extent.size >> 10), - geometry_copy ? "geometry-copy" : "window", static_cast(twin_view), - static_cast(source), static_cast(shader), - pool_spans.size(), static_cast(pool_span_bytes >> 10)); + leonida::TitleWindowRange cover{}; + if (end > pool_end || + !leonida::title_pool_cover(aliases, pool_lo, pool_end, source, twin_view, start, end, kTitleWindowAlign, + kTitleWindowMax, owned, cover)) + return false; + const std::uint64_t cover_end = cover.start + cover.size; + if (readable_run_end(cover.start & ~(kTitleWindowAlign - 1), cover_end) < cover_end) return false; + std::uint64_t credit = 0; + for (const std::size_t i : replaced) credit += title_windows[i].size; + const std::uint64_t twin_start = twin_view - (source - cover.start); + std::uint64_t shader = 0; + if (geometry.cap() && watch_shadow_writes() && !context->knows_buffer_va(cover.start, cover.size)) + shader = geometry.resolve(*this, cover.start, cover.size, copy_geometry); + const bool geometry_copy = shader != 0; + if (!shader) shader = make_title_window(cover.start, cover.size, credit); + if (!shader) return false; + if (!aliases.replace_twin(cover.start, twin_start, cover.size, shader, planned)) { + if (!geometry_copy) drop_title_window(shader); + return false; } - out = shader + (source - extent.start); + pool_spans.push_back({cover.start, twin_start, shader, cover.size, geometry_copy}); + pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); + pool_span_bytes += cover.size; + ++pool_covers; + if (pool_covers <= 4 || !(pool_covers & (pool_covers - 1))) + std::fprintf(stderr, + "[rt] d3d12: a stream-pool request ran past the mapping that would serve it: one %llu KiB " + "%s covers it and the %zu window(s) it reached, retired at the next submission (%llu so " + "far)\n", + static_cast(cover.size >> 10), geometry_copy ? "geometry copy" : "window", + replaced.size(), static_cast(pool_covers)); + out = shader + (source - cover.start); return true; } @@ -3700,12 +4026,18 @@ struct DeviceState { } const std::uint64_t want = std::max(bytes, 1); std::lock_guard lock(title_window_mutex); - if (const std::uint64_t made = aliases.shader_va(va); made != va) { // another thread made it meanwhile + std::uint64_t made = 0, available = 0; + const bool has_mapping = aliases.range_of(va, made, available) && made != va; + if (has_mapping && available >= want) { out = made; return true; } // A stream pool's address: one mapping for its readable run, shared by both of its views. if (resolve_pool_memory(va, bytes, out)) return true; + if (has_mapping) { + out = made; + return true; + } if (readable_page(va)) { std::uint64_t lo = 0, hi = UINT64_MAX; aliases.gap(va, lo, hi); // never over a slot-133 buffer's range or another window @@ -4229,6 +4561,15 @@ struct DeviceState { // 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); + // A title window it answered from may be answered by nothing now (retire_orphan_windows). + if (self.title_window_count.load(std::memory_order_relaxed)) { + std::lock_guard lock(self.window_alias_removal_mutex); + if (self.window_alias_removals.size() < kWindowAliasRemovals) + self.window_alias_removals.push_back({shader_va, bytes}); + else + self.window_alias_removals_overflow = true; + self.window_alias_removals_pending.store(true, std::memory_order_release); + } } else { self.note_slot_change(leonida::SlotChange::source_added, title_va, bytes); } @@ -4294,6 +4635,11 @@ 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)) { + // A range that ends before the V# does: the resolver may give a stream pool's request one mapping for all + // of it (resolve_pool_memory), as TitleVaAliases::resolve asks it for a short range. + uint64_t whole{}; + if (to && room < bytes && make_window && resolve_title_memory(base, bytes, whole) && whole) + aliases.range_of(base, to, room); if (!to || room < bytes || !backed(to)) { if (refused) *refused = to; return path(1), 0; @@ -4591,12 +4937,14 @@ struct DeviceState { const auto geometry_spans = std::count_if(pool_spans.begin(), pool_spans.end(), [](const PoolSpan& span) { return span.geometry; }); std::fprintf(stderr, - "[rt] d3d12: title memory: %zu windows (%llu KiB of a %llu MiB budget, %llu refused), %zu " - "stream-pool extents (one mapping each, %llu KiB; %lld by geometry copy, %llu retired with " - "their copy), %llu addresses given a zero-size view\n", + "[rt] d3d12: title memory: %zu windows (%llu KiB of a %llu MiB budget, %llu refused, %llu " + "retired once nothing reached them), %zu stream-pool extents (one mapping each, %llu KiB; " + "%lld by geometry copy, %llu retired with their copy or window), %llu addresses given a " + "zero-size view\n", title_windows.size(), static_cast(title_window_bytes >> 10), static_cast(title_window_cap >> 20), - static_cast(title_window_refusals), pool_spans.size(), + static_cast(title_window_refusals), + static_cast(title_windows_retired), pool_spans.size(), static_cast(pool_span_bytes >> 10), static_cast(geometry_spans), static_cast(pool_spans_retired), static_cast(unbacked_requests)); @@ -14789,6 +15137,7 @@ class Device final } state_.drain_geometry_releases(); state_.refresh_shadows(full || per_frame < 2, full); + state_.retire_orphan_windows(); // LEONIDA_GEOMETRY_ASYNC=1 (for runs that only need the title to go on): the geometry copies are brought // up to date on a worker of ours, started here and not waited for, instead of on the title's GPU submit // thread (speed-27: 230-330 ms a refresh after the load, a VirtualQuery and VirtualProtect per written @@ -21425,6 +21774,19 @@ std::uint64_t title_host_imports(ID3D12Device* device) { return d ? d->state().host_imports.load(std::memory_order_relaxed) : 0; } +TitleWindows title_windows(ID3D12Device* device) { + TitleWindows windows; + auto* d = Device::from(device); + if (!d) return windows; + auto& state = d->state(); + std::lock_guard lock(state.title_window_mutex); + windows.count = state.title_windows.size(); + windows.bytes = state.title_window_bytes; + windows.retired = state.title_windows_retired; + std::lock_guard retired(state.retired_window_mutex); + windows.waiting = state.retired_windows.size(); + return windows; +} std::uint64_t title_shadow_trackers(ID3D12Device* device) { auto* d = Device::from(device); if (!d) return 0; diff --git a/runtime/src/buffer_va_index.h b/runtime/src/buffer_va_index.h index 3ab8edf82..2f7c1abb1 100644 --- a/runtime/src/buffer_va_index.h +++ b/runtime/src/buffer_va_index.h @@ -89,6 +89,14 @@ class BufferVaIndex { return find(va, hit, bytes) && bytes <= hit.size - (va - hit.start); } + // Whether any range overlaps [va, va + bytes) (bytes 0 counts as 1). + bool overlaps(std::uint64_t va, std::uint64_t bytes) const { + Hit hit{}; + if (find(va, hit)) return true; + const auto it = ranges_.lower_bound({va, Id{}}); + return it != ranges_.end() && it->first.first - va < (bytes ? bytes : 1); + } + std::size_t size() const { return ranges_.size(); } std::uint64_t longest() const { return longest_; } // f(first VA, bytes) for every range, in VA order. diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index d7d739640..8b79c987e 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -1,4 +1,5 @@ #pragma once +#include "command_list_epochs.h" #include "gpu_label_memory.h" // The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until @@ -983,6 +984,7 @@ class CommandList { commands_.clear(); active_.clear(); closed_ = false; + stamp_.restamp(); return true; } @@ -1026,6 +1028,7 @@ class CommandList { std::vector commands_; std::vector active_; // queries begun and not yet ended bool closed_ = false; + command_list_epochs::Stamp stamp_; // when this recording began: a copy the layer retires waits for it }; } // namespace leonida diff --git a/runtime/src/command_list_epochs.h b/runtime/src/command_list_epochs.h new file mode 100644 index 000000000..61c73565d --- /dev/null +++ b/runtime/src/command_list_epochs.h @@ -0,0 +1,69 @@ +#pragma once +// Which command lists recorded before a moment may still be replayed. A command list resolves the title addresses +// its root views name when they are recorded (d3d12_com.cpp GraphicsCommandList::address), so a copy the layer +// retires (a title window, DeviceState::retire_orphan_windows) may still be named by a list recorded before the +// retirement and executed, or executed again, after it; a held batch and the async worker keep copies of the lists +// too. Each list, and each copy of it, carries the epoch its recording began in (Stamp, a CommandList member): +// whatever was retired at epoch E is named by no list once the oldest live stamp is E or later. +#include +#include +#include +#include + +namespace leonida::command_list_epochs { + +struct Registry { + std::mutex mutex; + std::multiset live; // the stamps of every list and copy alive + std::atomic epoch{1}; +}; +inline Registry& registry() { + static Registry r; + return r; +} + +// A new epoch: lists whose recording began before it carry a smaller stamp. +inline std::uint64_t advance() { return registry().epoch.fetch_add(1, std::memory_order_acq_rel) + 1; } + +// The oldest stamp alive (UINT64_MAX with no list at all). +inline std::uint64_t oldest() { + Registry& r = registry(); + std::lock_guard lock(r.mutex); + return r.live.empty() ? UINT64_MAX : *r.live.begin(); +} + +class Stamp { +public: + Stamp() : epoch_(enter(registry().epoch.load(std::memory_order_acquire))) {} + Stamp(const Stamp& other) : epoch_(enter(other.epoch_)) {} + Stamp& operator=(const Stamp& other) { + if (this != &other) { + leave(epoch_); + epoch_ = enter(other.epoch_); + } + return *this; + } + ~Stamp() { leave(epoch_); } + // A new recording begins (CommandList::reset). + void restamp() { + leave(epoch_); + epoch_ = enter(registry().epoch.load(std::memory_order_acquire)); + } + std::uint64_t epoch() const { return epoch_; } + +private: + static std::uint64_t enter(std::uint64_t epoch) { + Registry& r = registry(); + std::lock_guard lock(r.mutex); + r.live.insert(epoch); + return epoch; + } + static void leave(std::uint64_t epoch) { + Registry& r = registry(); + std::lock_guard lock(r.mutex); + if (const auto it = r.live.find(epoch); it != r.live.end()) r.live.erase(it); + } + std::uint64_t epoch_; +}; + +} // namespace leonida::command_list_epochs diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index c49880d92..8ed315ecf 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -23,10 +23,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include @@ -65,9 +67,72 @@ class TitleVaAliases { // The two addresses of one stream-pool extent (a GPU-only alias and the CPU view of the same pages, gfxgeom // section 3): both name the same shader VA, so a title view carrying either resolves to the one mapping. bool add_twin(std::uint64_t va, std::uint64_t twin, std::uint64_t bytes, std::uint64_t shader_va) { - if (va == twin) return add(va, bytes, shader_va); - const bool first = add(va, bytes, shader_va); - return add(twin, bytes, shader_va) && first; + if (!bytes || va > UINT64_MAX - bytes || twin > UINT64_MAX - bytes) return false; + if (va != twin && va < twin + bytes && twin < va + bytes) return false; + std::unique_lock lock(mutex_); + if (overlaps(va, va + bytes) || (va != twin && overlaps(twin, twin + bytes))) return false; + decltype(ranges_) pending; + pending.try_emplace(va, Range{va + bytes, shader_va}); + pending.try_emplace(twin, Range{twin + bytes, shader_va}); + publish_pool_ranges(pending); + return true; + } + + // add_twin over live ranges: every range either address's bytes overlap is replaced whole (each is told as a + // removal), then both are entered under one lock. For a stream-pool request that runs into the windows next to it + // (title_pool_cover): the new range covers each of them whole, so none of their bytes is left unanswered. + // `replaces(shader_va)` names the ranges the caller planned to replace; one it does not (a slot-133 buffer + // entered since the plan, which takes no lock of the caller's) makes it false with nothing changed, checked + // under the same lock as the replacement. + template + bool replace_twin(std::uint64_t va, std::uint64_t twin, std::uint64_t bytes, std::uint64_t shader_va, + Replaces&& replaces) { + if (!bytes || va > UINT64_MAX - bytes || twin > UINT64_MAX - bytes) return false; + if (va != twin && va < twin + bytes && twin < va + bytes) return false; + std::unique_lock lock(mutex_); + const auto planned = [&](std::uint64_t begin, std::uint64_t end) { + auto it = ranges_.lower_bound(begin); + if (it != ranges_.begin() && std::prev(it)->second.end > begin) --it; + for (; it != ranges_.end() && it->first < end; ++it) + if (!replaces(it->second.shader_va)) return false; + return true; + }; + if (!planned(va, va + bytes) || (va != twin && !planned(twin, twin + bytes))) return false; + erase_overlapping(va, va + bytes); + if (va != twin) erase_overlapping(twin, twin + bytes); + decltype(ranges_) pending; + pending.try_emplace(va, Range{va + bytes, shader_va}); + pending.try_emplace(twin, Range{twin + bytes, shader_va}); + publish_pool_ranges(pending); + return true; + } + + bool reuse_pool_mapping(std::uint64_t va, std::uint64_t twin, std::uint64_t want, std::uint64_t max_size, + std::uint64_t& shader_va) { + if (!want) return false; + std::unique_lock lock(mutex_); + const auto next = ranges_.upper_bound(va); + if (next != ranges_.begin()) { + const auto existing = std::prev(next); + if (va < existing->second.end) { + if (want > existing->second.end - va) return false; + shader_va = existing->second.shader_va + (va - existing->first); + return true; + } + } + const auto other_next = ranges_.upper_bound(twin); + if (other_next == ranges_.begin()) return false; + const auto other = std::prev(other_next); + if (twin >= other->second.end) return false; + const auto end = next == ranges_.end() ? UINT64_MAX : next->first; + const auto bytes = std::min({max_size, other->second.end - twin, end - va}); + if (bytes < want) return false; + const auto shader = other->second.shader_va + (twin - other->first); + decltype(ranges_) pending; + pending.try_emplace(va, Range{va + bytes, shader}); + publish_pool_ranges(pending); + shader_va = shader; + return true; } // Forgets the range that starts at title_va, if it still maps to shader_va (a newer range at the same VA keeps @@ -92,6 +157,16 @@ class TitleVaAliases { 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_); + for (auto it = ranges_.lower_bound(title_va); it != ranges_.end() && it->first - title_va < bytes;) { + if (it->second.shader_va - shader_va != it->first - title_va) { + ++it; + continue; + } + by_shader_.erase(it->second.shader_va, it->first); + notify(Change::removed, it->first, it->second.end - it->first, it->second.shader_va); + it = ranges_.erase(it); + } + count_.store(ranges_.size(), std::memory_order_release); notify(Change::removed, title_va, bytes, shader_va); note_removed(shader_va, bytes); generation_.fetch_add(1, std::memory_order_release); @@ -135,6 +210,16 @@ class TitleVaAliases { out.reserve(ranges_.size()); for (const auto& [start, range] : ranges_) out.push_back({start, range.end, range.shader_va}); } + // The ranges that overlap [begin, end), in title-VA order. + void overlapping(std::uint64_t begin, std::uint64_t end, std::vector& out) const { + out.clear(); + if (begin >= end || !count_.load(std::memory_order_acquire)) return; + std::shared_lock lock(mutex_); + auto it = ranges_.lower_bound(begin); + if (it != ranges_.begin() && std::prev(it)->second.end > begin) --it; + for (; it != ranges_.end() && it->first < end; ++it) + out.push_back({it->first, it->second.end, it->second.shader_va}); + } // Whether `shader_va` lies in the copy of a range added so far: an address the layer itself wrote for the title // (a window, a geometry copy, a slot-133 shadow or import), which a later scan of the same descriptor sees again. @@ -146,6 +231,14 @@ class TitleVaAliases { return by_shader_.find(shader_va, hit); } + // Whether any range still answers from inside [shader_va, shader_va + bytes): a copy (a title window) that some + // address still reaches. A range entered over a live one replaces it whole (add), so a copy can be left with none. + bool answers_into(std::uint64_t shader_va, std::uint64_t bytes) const { + if (!count_.load(std::memory_order_acquire)) return false; + std::shared_lock lock(mutex_); + return by_shader_.overlaps(shader_va, bytes); + } + // Debug-only inverse lookup. V#s retain 48 bits, so an import below heap_base wraps. bool source_of_vsharp(std::uint64_t base, std::uint64_t& title, std::uint64_t& available) const { constexpr std::uint64_t mask = (1ull << 48) - 1; @@ -177,11 +270,12 @@ class TitleVaAliases { // read or write). Counted by kind: translated, or in the title's memory and left as it was. std::uint64_t resolve(std::uint64_t va, std::uint64_t bytes, Kind kind) { if (!va) return va; - std::uint64_t to = shader_va(va); - if (to != va) { + std::uint64_t mapped = va, available = 0; + const bool has_mapping = range_of(va, mapped, available) && mapped != va; + if (has_mapping && bytes <= available) { translated_[kind].fetch_add(1, std::memory_order_relaxed); note_reached(va, bytes); - return to; + return mapped; } Resolver resolver; void* context; @@ -190,9 +284,13 @@ class TitleVaAliases { resolver = resolver_; context = hook_context_; } - if (!resolver || !resolver(context, va, bytes, to)) return va; + std::uint64_t to = va; + if (!resolver || !resolver(context, va, bytes, to)) { + if (!has_mapping) return va; + to = mapped; + } (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed); - if (to != va) note_reached(va, bytes); + if (to && to != va) note_reached(va, bytes); return to; } @@ -423,6 +521,25 @@ class TitleVaAliases { std::uint64_t shader_va; // what the range's first byte becomes }; + void publish_pool_ranges(std::map& pending) { + try { + for (const auto& [base, range] : pending) by_shader_.insert(range.shader_va, range.end - base, base); + } catch (...) { + for (const auto& [base, range] : pending) by_shader_.erase(range.shader_va, base); + throw; + } + for (const auto& [base, range] : pending) notify(Change::added, base, range.end - base, range.shader_va); + ranges_.merge(pending); + count_.store(ranges_.size(), std::memory_order_release); + generation_.fetch_add(1, std::memory_order_release); + } + + bool overlaps(std::uint64_t begin, std::uint64_t end) const { + const auto next = ranges_.lower_bound(begin); + return (next != ranges_.end() && next->first < end) || + (next != ranges_.begin() && std::prev(next)->second.end > begin); + } + void erase_overlapping(std::uint64_t begin, std::uint64_t end) { auto it = ranges_.lower_bound(begin); if (it != ranges_.begin()) { diff --git a/runtime/src/title_window_plan.h b/runtime/src/title_window_plan.h index cd17bc596..46bcc97c4 100644 --- a/runtime/src/title_window_plan.h +++ b/runtime/src/title_window_plan.h @@ -9,8 +9,11 @@ // - a stream pool (the title's CPU view paired with a GPU-only alias, gfxgeom section 3) is one reservation of // 16-24 GiB, so it cannot be one allocation: one mapping serves a page-aligned readable run of it, and every // request inside that run reuses it instead of asking for a 128 KiB window each. +#include "title_va_alias.h" + #include #include +#include namespace leonida { @@ -63,4 +66,59 @@ inline bool title_pool_extent(std::uint64_t pool_lo, std::uint64_t pool_hi, std: return true; } +inline bool clip_title_pool_extent(TitleWindowRange& extent, std::uint64_t source, std::uint64_t twin, + std::uint64_t source_lo, std::uint64_t source_hi, + std::uint64_t twin_lo, std::uint64_t twin_hi) { + if (source < source_lo || source >= source_hi || twin < twin_lo || twin >= twin_hi || + source < extent.start || source - extent.start >= extent.size) + return false; + const auto prefix = source - extent.start; + const auto before = std::min({prefix, source - source_lo, twin - twin_lo}); + const auto after = std::min({extent.size - prefix, source_hi - source, twin_hi - twin}); + extent = {source - before, before + after}; + return true; +} + +// The one mapping a stream-pool request [va, end) gets when what would serve it stops short: the extent clipped to +// the free span (clip_title_pool_extent) ends at the next mapping, or `va` lies in a mapping that ends before `end`. +// It starts at `start` (that extent's start, or `va`) and covers the request and, whole, every range the result +// overlaps in either view (`twin`: va's byte in the pair's other view, `va` when there is none), page-aligned at its +// end. A range entered over it replaces those ranges whole (TitleVaAliases::replace_twin), so none of their bytes is +// left unanswered and no view reaches past the copy it was given. `owned(shader_va)` says the caller can retire the +// copy a range answers from (a title window); any other range in the way (a slot-133 buffer, a geometry copy) makes +// it false, as does a mapping past `most` bytes or outside [pool_lo, pool_hi) in its own view. The pool's other view +// is [twin_lo, twin_hi), `twin` being va's byte there; one that would not fit in 64 bits makes it false too, so no +// address is ever taken modulo 2^64. `out` is unchanged on false. +template +inline bool title_pool_cover(const TitleVaAliases& aliases, std::uint64_t pool_lo, std::uint64_t pool_hi, + std::uint64_t va, std::uint64_t twin, std::uint64_t start, std::uint64_t end, + std::uint64_t align, std::uint64_t most, Owned&& owned, TitleWindowRange& out) { + if (!align || (align & (align - 1)) != 0 || start > va || va >= end || start < pool_lo || end > pool_hi) + return false; + if (twin < va - pool_lo || pool_hi - va > UINT64_MAX - twin) return false; + const auto aligned_end = [&](std::uint64_t e) { + return e > pool_hi - (align - 1) ? pool_hi : (std::min)(pool_hi, (e + align - 1) & ~(align - 1)); + }; + // Each view's bounds: a range at x in the twin view is at x - twin_lo + pool_lo in va's. + const std::uint64_t base[2] = {pool_lo, twin - (va - pool_lo)}, top[2] = {pool_hi, twin + (pool_hi - va)}; + std::uint64_t lo = start, hi = aligned_end(end); + std::vector hits; + for (bool grew = true; grew;) { + grew = false; + for (int view = 0; view < (twin != va ? 2 : 1); ++view) { + aliases.overlapping(lo - pool_lo + base[view], hi - pool_lo + base[view], hits); + for (const TitleVaAliases::Mapping& m : hits) { + // Not ours, or not coverable: reaching past the pool in its own view. + if (!owned(m.shader_va) || m.title_va < base[view] || m.end > top[view]) return false; + const std::uint64_t b = m.title_va - base[view] + pool_lo, e = m.end - base[view] + pool_lo; + if (b < lo) lo = b, grew = true; + if (e > hi) hi = aligned_end(e), grew = true; + } + } + if (lo < pool_lo || hi > pool_hi || hi - lo > most) return false; + } + out = {lo, hi - lo}; + return true; +} + } // namespace leonida diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 51d529aba..b968b4ede 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -522,11 +522,12 @@ struct WriteBack { ID3D12Resource* out; ID3D12DescriptorHeap* heap; UINT64 gpu; + ID3D12CommandQueue* queue = nullptr; // the context's when null }; -// One submission that dispatches through a root UAV at `va` (and at `va2` too, when given) and waits for it. False -// on a failed call. -int submit_write(WriteBack& s, std::uint64_t va, std::uint64_t va2 = 0) { +// One submission that dispatches through a root UAV at `va` (and at `va2` too, when given) and waits for it. With +// `wait` false it is only executed (no signal: the caller knows when it is done). False on a failed call. +int submit_write(WriteBack& s, std::uint64_t va, std::uint64_t va2 = 0, bool wait = true) { EXPECT(s.allocator->Reset() == S_OK); EXPECT(s.list->Reset(s.allocator, s.c->pso) == S_OK); ID3D12DescriptorHeap* heaps[] = {s.heap}; @@ -550,9 +551,11 @@ int submit_write(WriteBack& s, std::uint64_t va, std::uint64_t va2 = 0) { s.list->ResourceBarrier(1, &to_copy); EXPECT(s.list->Close() == S_OK); ID3D12CommandList* lists[] = {s.list}; - s.c->queue->ExecuteCommandLists(1, lists); - EXPECT(rt::d3d12::last_execute_result(s.c->queue) == leonida::ReplayResult::success); - EXPECT(SUCCEEDED(s.c->queue->Signal(s.c->fence, ++s.c->fence_value))); + ID3D12CommandQueue* queue = s.queue ? s.queue : s.c->queue; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue) == leonida::ReplayResult::success); + if (!wait) return 0; + EXPECT(SUCCEEDED(queue->Signal(s.c->fence, ++s.c->fence_value))); s.c->fence->SetEventOnCompletion(s.c->fence_value, nullptr); // a null event waits, as D3D12 does return 0; } @@ -1105,6 +1108,18 @@ int check_stream_pool(Context& c, int& checks) { aliases.add_title_memory(gpu_va, pool_bytes); EXPECT(leonida::title_gpu_views::to_host_view(gpu_va + 0x2000, 0x100) == cpu_va + 0x2000); + constexpr UINT64 seam = pool_bytes / 2; + constexpr UINT64 existing = 0x100000; + const auto root = leonida::TitleVaAliases::root_view; + EXPECT(aliases.add(cpu_va + seam, 0x1000, existing)); + const auto ranges_at_seam = aliases.size(); + EXPECT(aliases.resolve(gpu_va + seam - 0x100, 0x200, root) == 0); + EXPECT(aliases.resolve(gpu_va + seam, 0x2000, root) == 0); + EXPECT(aliases.resolve(cpu_va + seam, 0x2000, root) == 0); + EXPECT(aliases.size() == ranges_at_seam); + EXPECT(aliases.shader_va(cpu_va + seam) == existing); + aliases.remove(cpu_va + seam, existing); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref heap; @@ -1126,6 +1141,8 @@ int check_stream_pool(Context& c, int& checks) { EXPECT(aliases.shader_va(gpu_va + 0x2000) == aliases.shader_va(cpu_va + 0x2000)); // Two ranges (the two views' addresses), each a page-aligned run of the pool: one mapping, not one per view. EXPECT(aliases.size() == ranges_before + 2); + EXPECT(aliases.resolve(gpu_va + pool_bytes - 0x100, 0x200, root) == 0); + EXPECT(aliases.size() == ranges_before + 2); std::printf("stream pool: GPU-only alias 0x%llx and CPU view 0x%llx share one %llu KiB mapping (V# base " "0x%llx); a second view naming the twin made no mapping\n", static_cast(gpu_va), static_cast(cpu_va), @@ -1141,6 +1158,358 @@ int check_stream_pool(Context& c, int& checks) { return 0; } +// One submission that reads 64 title words through a root view at `va`, 256 bytes past it, into an arena buffer +// (cs_user_data's mode 0xFFFFFFFD: the table entry is the buffer's raw VA), then copies them to a READBACK buffer. +// `matched`: how many are words[64 + i] + kRootAdd, the bytes at `va` as the title wrote them. +struct Reader { + Context* c; + ID3D12CommandAllocator* allocator; + ID3D12GraphicsCommandList* list; + ID3D12Resource* out; + ID3D12Resource* readback; + ID3D12DescriptorHeap* heap; + UINT64 gpu; +}; +int read_root(Reader& r, std::uint64_t va, const std::uint32_t* words, UINT& matched) { + EXPECT(r.allocator->Reset() == S_OK); + EXPECT(r.list->Reset(r.allocator, r.c->pso) == S_OK); + ID3D12DescriptorHeap* heaps[] = {r.heap}; + r.list->SetDescriptorHeaps(1, heaps); + r.list->SetComputeRootSignature(r.c->root); + r.list->SetComputeRoot32BitConstant(0, kRootAdd, 0); + r.list->SetComputeRoot32BitConstant(0, 0xFFFFFFFDu, 1); + r.list->SetComputeRootUnorderedAccessView(1, va); + r.list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{r.gpu}); + r.list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = r.out; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + r.list->ResourceBarrier(1, &barrier); + r.list->CopyBufferRegion(r.readback, 0, r.out, 0, kBytes); + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + r.list->ResourceBarrier(1, &barrier); + EXPECT(r.list->Close() == S_OK); + ID3D12CommandList* lists[] = {r.list}; + r.c->queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(r.c->queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(r.c->queue->Signal(r.c->fence, ++r.c->fence_value))); + EXPECT(SUCCEEDED(r.c->fence->SetEventOnCompletion(r.c->fence_value, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(r.readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + matched = 0; + for (UINT i = 0; i < kElements; ++i) matched += got[i] == words[64 + i] + kRootAdd; + r.readback->Unmap(0, nullptr); + return 0; +} + +// What the GPU wrote in a window goes back to the title's pages when the window is retired before that submission +// has run: its copy stays a target of its pages' tracker until the submissions that may name it have completed and +// been copied back, and goes back only where the live copy over the same pages changed nothing. The writing +// submission waits on a fence only the CPU signals, so it is still queued when the next one's refresh retires the +// window (the title placed a slot-133 buffer over its pages meanwhile). +int check_retired_window_write_back(Context& c) { + auto& aliases = leonida::title_va_aliases(); + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref out; + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.p)))); + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + Ref allocators[2]; + Ref lists[2]; + for (int i = 0; i < 2; ++i) { + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(&allocators[i].p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocators[i].p, c.pso, + IID_PPV_ARGS(&lists[i].p)))); + EXPECT(lists[i]->Close() == S_OK); + } + Ref gate, held_done; + EXPECT(SUCCEEDED(c.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate.p)))); + EXPECT(SUCCEEDED(c.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&held_done.p)))); + // The held submission's own queue: a queue holds what follows a Wait until it is signalled, so the next + // submission, whose refresh retires the window, runs on the context's. + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref gated; + EXPECT(SUCCEEDED(c.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&gated.p)))); + const UINT64 gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + WriteBack held{&c, allocators[0].p, lists[0].p, out.p, heap.p, gpu, gated.p}; + WriteBack next{&c, allocators[1].p, lists[1].p, out.p, heap.p, gpu}; + const std::uint64_t arena_va = out->GetGPUVirtualAddress(); // not the title's memory: nothing to copy back + // A reader through the buffer placed over the ring, with its own heap and output. + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto readback_desc = buffer_desc(kBytes); + Ref read_out, readback; + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&read_out.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + Ref read_heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&read_heap.p)))); + const std::uint64_t read_out_va = read_out->GetGPUVirtualAddress(); + std::memcpy(reinterpret_cast(reinterpret_cast(slot(read_heap.p, 9))(read_heap.p)), + &read_out_va, sizeof(read_out_va)); + Ref read_allocator; + Ref read_list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(&read_allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, read_allocator.p, c.pso, + IID_PPV_ARGS(&read_list.p)))); + EXPECT(read_list->Close() == S_OK); + Reader reader{&c, read_allocator.p, read_list.p, read_out.p, readback.p, read_heap.p, + reinterpret_cast(slot(read_heap.p, 10))(read_heap.p)}; + // Pages no range answers for yet: a range of a buffer the tests before this one placed can outlive the buffer at + // an address the ring might get again, so such pages are kept aside until the end. Write-combined, so the buffer + // placed over them is a copy refreshed before each submission on every driver (one that imports read-write pages + // would read the pages themselves). + constexpr UINT64 ring_bytes = 128 * 1024; + // The held submission's words: 256 bytes from here, through the window. Half of them share a 256-byte piece with + // the words a later submission writes through the buffer placed over the ring. + constexpr UINT64 held_at = 384; + std::vector taken; + std::uint32_t* ring = nullptr; + for (int tries = 0; tries < 32 && !ring; ++tries) { + void* pages = VirtualAlloc(nullptr, ring_bytes, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE | PAGE_WRITECOMBINE); + EXPECT(pages); + const auto at = reinterpret_cast(pages); + if (aliases.shader_va(at) == at && aliases.shader_va(at + ring_bytes - 1) == at + ring_bytes - 1) + ring = static_cast(pages); + else + taken.push_back(pages); + } + EXPECT(ring); + const auto ring_va = reinterpret_cast(ring); + for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0; + aliases.add_title_memory(ring_va, ring_bytes); + + // Held on the GPU: it writes the ring's window once the gate opens. + const auto empty = rt::d3d12::title_windows(c.inner); + EXPECT(SUCCEEDED(gated->Wait(gate.p, 1))); + EXPECT(submit_write(held, ring_va + held_at, 0, false) == 0); + EXPECT(SUCCEEDED(gated->Signal(held_done.p, 1))); + const std::uint64_t window = aliases.shader_va(ring_va); + const auto before = rt::d3d12::title_windows(c.inner); + EXPECT(window != ring_va && before.count == empty.count + 1); + Ref placed; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, ring, buffer_desc(ring_bytes), 0xFFFFFFFFu, + IID_PPV_ARGS(&placed.p)))); + EXPECT(!aliases.answers_into(window, 1)); + EXPECT(submit_write(next, arena_va, 0, false) == 0); // its refresh retires the window, its write still queued + const auto retired = rt::d3d12::title_windows(c.inner); + EXPECT(retired.retired == before.retired + 1 && retired.waiting >= 1); + EXPECT(held_done->GetCompletedValue() == 0); // the write has not run yet + // Another submission, completed: the window is still kept, because the held batch, recorded before its + // retirement, names it and has not run (its memory must not be handed out again meanwhile). + EXPECT(submit_write(next, arena_va) == 0); + const auto kept = rt::d3d12::title_windows(c.inner); + EXPECT(kept.waiting == retired.waiting); + EXPECT(SUCCEEDED(gate->Signal(1))); + EXPECT(SUCCEEDED(held_done->SetEventOnCompletion(1, nullptr))); + // A shader writes through the buffer the 256 bytes before the held words: the buffer's copy changed the first + // half of the 256-byte piece [256, 512) whose second half only the window wrote. Both go back, each its own bytes. + EXPECT(submit_write(next, ring_va + held_at - 256) == 0); + // The title resets the list it recorded (a list may be executed again until then); then the window goes, and + // what the held submission wrote in it reaches the title's pages first, and the copy of the buffer over them: the + // submission that frees it reads them through the buffer (256 bytes past ring + held_at - 256). + EXPECT(allocators[0]->Reset() == S_OK); + EXPECT(lists[0]->Reset(allocators[0].p, c.pso) == S_OK); + EXPECT(lists[0]->Close() == S_OK); + rt::d3d12::TitleWindows freed{}; + UINT seen = 0; + for (int i = 0; i < 8; ++i) { + EXPECT(read_root(reader, ring_va + held_at - 256, ring + (held_at - 256) / 4, seen) == 0); + freed = rt::d3d12::title_windows(c.inner); + if (!freed.waiting) break; + } + UINT written = 0; + for (UINT i = 0; i < kElements; ++i) written += ring[held_at / 4 + i] != 0; + std::printf("retired window write back: kept while a held batch named it (%llu waiting); %u of %u words the held " + "submission wrote reached the title's pages, %u read through the buffer by the submission that freed " + "the window; %llu retired windows wait for the GPU\n", + static_cast(kept.waiting), written, kElements, seen, + static_cast(freed.waiting)); + EXPECT(freed.waiting == 0); + EXPECT(written == kElements); + EXPECT(seen == kElements); + // The buffer's own words go back with its submission's batch (none with LEONIDA_TITLE_WRITEBACK=0). + const char* write_back = std::getenv("LEONIDA_TITLE_WRITEBACK"); + UINT buffer_words = 0; + for (UINT i = 0; i < kElements; ++i) buffer_words += ring[(held_at - 256) / 4 + i] != 0; + EXPECT(buffer_words == ((write_back && write_back[0] == '0') ? 0 : kElements)); + + placed.reset(); + aliases.remove_title_memory(ring_va); + VirtualFree(ring, 0, MEM_RELEASE); + for (void* pages : taken) VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + +// No window is left that nothing reaches (RT-TITLE-WINDOW-RETIRE). A range entered over a live one replaces it whole, +// so a mapping made over bytes another one serves left that one's copy answered by nothing, still refreshed and +// charged to LEONIDA_TITLE_WINDOWS_MB. First a stream pool: a request just before an extent the pool already has gets +// an extent that stops where that one starts, and both keep answering. Then a slot-133 buffer the title places over a +// window's pages: the window, now reached by nothing, is retired at the next submission, its bytes returned and its +// memory freed after the submission completes, and the GPU reads the title's bytes through the buffer. +int check_window_orphans(Context& c) { + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const auto readback_desc = buffer_desc(kBytes); + Ref out, readback; + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t out_va = out->GetGPUVirtualAddress(); + std::memcpy(reinterpret_cast(reinterpret_cast(slot(heap.p, 9))(heap.p)), &out_va, + sizeof(out_va)); + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, + IID_PPV_ARGS(&list.p)))); + EXPECT(list->Close() == S_OK); + Reader r{&c, allocator.p, list.p, out.p, readback.p, heap.p, + reinterpret_cast(slot(heap.p, 10))(heap.p)}; + auto& aliases = leonida::title_va_aliases(); + UINT matched = 0; + + // A 512 KiB stream pool: its CPU view committed, its GPU-only alias reserved. + constexpr UINT64 pool_bytes = 512 * 1024; + auto* pool = static_cast( + VirtualAlloc(nullptr, pool_bytes, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + void* gpu_alias = VirtualAlloc(nullptr, pool_bytes, MEM_TOP_DOWN | MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pool && gpu_alias); + const auto cpu_va = reinterpret_cast(pool), gpu_va = reinterpret_cast(gpu_alias); + EXPECT(!leonida::title_gpu_views::note_reservation(cpu_va, pool_bytes, false)); + EXPECT(leonida::title_gpu_views::note_reservation(gpu_va, pool_bytes, true)); + aliases.add_title_memory(cpu_va, pool_bytes); + aliases.add_title_memory(gpu_va, pool_bytes); + for (UINT i = 0; i < pool_bytes / 4; ++i) pool[i] = 0xD0000000u + i * 3u; + constexpr UINT64 later = 0x40000, earlier = 0x10000; // the second request lands 192 KiB before the first's extent + const auto before = rt::d3d12::title_windows(c.inner); + EXPECT(read_root(r, gpu_va + later, pool + later / 4, matched) == 0); + EXPECT(matched == kElements); + const std::uint64_t first = aliases.shader_va(cpu_va + later); + EXPECT(first != cpu_va + later && aliases.shader_va(gpu_va + later) == first); + EXPECT(read_root(r, gpu_va + earlier, pool + earlier / 4, matched) == 0); + EXPECT(matched == kElements); + const auto pooled = rt::d3d12::title_windows(c.inner); + std::printf("window orphans: two pool requests made %llu windows of %llu KiB; the first extent is answered at its " + "CPU view %s and its alias %s\n", + static_cast(pooled.count - before.count), + static_cast((pooled.bytes - before.bytes) >> 10), + aliases.shader_va(cpu_va + later) == first ? "yes" : "no", + aliases.shader_va(gpu_va + later) == first ? "yes" : "no"); + EXPECT(pooled.count == before.count + 2); + // [earlier, later) and [later, pool end): no byte twice. + EXPECT(pooled.bytes - before.bytes == pool_bytes - earlier); + EXPECT(aliases.shader_va(cpu_va + later) == first && aliases.shader_va(gpu_va + later) == first); + EXPECT(aliases.shader_va(gpu_va + earlier) == aliases.shader_va(cpu_va + earlier)); + // Both still read the title's bytes, the first through its own extent; and neither window is retired. + EXPECT(read_root(r, cpu_va + later, pool + later / 4, matched) == 0); + EXPECT(matched == kElements); + EXPECT(read_root(r, gpu_va + earlier, pool + earlier / 4, matched) == 0); + EXPECT(matched == kElements); + EXPECT(rt::d3d12::title_windows(c.inner).count == pooled.count); + + // A view whose bytes run from the second extent into the first gets one mapping for all of them, over both, never + // one that stops at the first one's start: a V# with too few bytes is refused, and a root view would reach past + // its copy into whatever the arena holds next. Both extents are retired at the next submission, and the GPU + // reads the title's bytes across the seam. + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const std::uint64_t cbv = reinterpret_cast(slot(heap.p, 9))(heap.p) + inc; + constexpr UINT64 seam = later - 0x8000, seam_bytes = 0x10000; // 32 KiB on each side of the first extent's start + const D3D12_CONSTANT_BUFFER_VIEW_DESC crossing{gpu_va + seam, UINT(seam_bytes)}; + c.device->CreateConstantBufferView(&crossing, D3D12_CPU_DESCRIPTOR_HANDLE{cbv}); + const std::uint64_t covered = aliases.shader_va(gpu_va + seam, seam_bytes); + const auto merged = rt::d3d12::title_windows(c.inner); + std::printf("window orphans: a 64 KiB view across the two extents' seam got V# base 0x%llx (%s), one mapping of " + "%llu KiB over both\n", + static_cast(vsharp_base(cbv)), + covered != gpu_va + seam ? "all its bytes in one copy" : "no copy holds them all", + static_cast((merged.bytes - pooled.bytes) >> 10)); + EXPECT(covered != gpu_va + seam && vsharp_base(cbv) == (covered & 0xFFFFFFFFFFFFull)); + EXPECT(aliases.shader_va(cpu_va + seam, seam_bytes) == covered); + EXPECT(merged.count == pooled.count + 1 && merged.bytes - pooled.bytes == pool_bytes - earlier); + EXPECT(aliases.shader_va(cpu_va + later) == covered + (later - seam)); + EXPECT(aliases.shader_va(gpu_va + earlier) == covered - (seam - earlier)); + EXPECT(read_root(r, gpu_va + later - 0x180, pool + (later - 0x180) / 4, matched) == 0); // 512 bytes over it + EXPECT(matched == kElements); + const auto settled = rt::d3d12::title_windows(c.inner); + EXPECT(settled.retired == merged.retired + 2 && settled.count == merged.count - 2); + EXPECT(settled.bytes == pooled.bytes); + EXPECT(read_root(r, cpu_va + earlier, pool + earlier / 4, matched) == 0); + EXPECT(matched == kElements); + + // A 128 KiB constant ring: a window for its first page, then a buffer the title places over the whole ring. + constexpr UINT64 ring_bytes = 128 * 1024; + auto* ring = static_cast( + VirtualAlloc(nullptr, ring_bytes, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(ring); + const auto ring_va = reinterpret_cast(ring); + aliases.add_title_memory(ring_va, ring_bytes); + for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0xE0000000u + i * 5u; + EXPECT(read_root(r, ring_va, ring, matched) == 0); + EXPECT(matched == kElements); + const auto windowed = rt::d3d12::title_windows(c.inner); + const std::uint64_t window = aliases.shader_va(ring_va); + EXPECT(windowed.count == settled.count + 1 && window != ring_va); + const std::uint64_t window_bytes = windowed.bytes - settled.bytes; + Ref placed; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, ring, buffer_desc(ring_bytes), 0xFFFFFFFFu, + IID_PPV_ARGS(&placed.p)))); + EXPECT(aliases.shader_va(ring_va) != window && aliases.shader_va(ring_va) != ring_va); + EXPECT(!aliases.answers_into(window, window_bytes)); // nothing reaches the window now + for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0xF0000000u + i * 7u; // new bytes, after the buffer exists + EXPECT(read_root(r, ring_va, ring, matched) == 0); // through the buffer; the window is retired after the refresh + const auto retired = rt::d3d12::title_windows(c.inner); + std::printf("window orphans: a buffer over the ring's window: %u/%u words read through it; %llu -> %llu windows, " + "%llu -> %llu KiB (%llu retired, %llu waiting for the GPU)\n", + matched, kElements, static_cast(windowed.count), + static_cast(retired.count), static_cast(windowed.bytes >> 10), + static_cast(retired.bytes >> 10), + static_cast(retired.retired - windowed.retired), + static_cast(retired.waiting)); + EXPECT(matched == kElements); + EXPECT(retired.count == windowed.count - 1 && retired.bytes == windowed.bytes - window_bytes); + EXPECT(retired.retired == windowed.retired + 1); + // Its memory goes once the submission that retired it has completed; the pool's windows stay. + EXPECT(read_root(r, ring_va, ring, matched) == 0); + EXPECT(matched == kElements); + const auto freed = rt::d3d12::title_windows(c.inner); + EXPECT(freed.waiting == 0 && freed.count == retired.count); + EXPECT(read_root(r, gpu_va + later, pool + later / 4, matched) == 0); + EXPECT(matched == kElements); + + placed.reset(); + aliases.remove_title_memory(ring_va); + aliases.remove_title_memory(gpu_va); + aliases.remove_title_memory(cpu_va); + remove_test_pair(gpu_va, cpu_va); + VirtualFree(ring, 0, MEM_RELEASE); + VirtualFree(gpu_alias, 0, MEM_RELEASE); + VirtualFree(pool, 0, MEM_RELEASE); + return 0; +} + // Four 4 MiB slabs fill the 16 MiB fixture budget. A final 1 MiB view still fits // immediately after the 3 MiB view in the second slab. int check_geometry_slab_tails(Context& c) { @@ -1370,6 +1739,7 @@ int main(int argc, char** argv) { const bool rebind = api_copy || mirror_off || second_device || (argc == 2 && std::strcmp(argv[1], "--rebound-tables") == 0); const bool window_cap = argc == 2 && std::strcmp(argv[1], "--window-cap") == 0; const bool window_write_back = argc == 2 && std::strcmp(argv[1], "--window-writeback") == 0; + const bool window_orphans = argc == 2 && std::strcmp(argv[1], "--window-orphans") == 0; const bool window_write_back_tile = argc == 2 && std::strcmp(argv[1], "--window-writeback-fault-tile") == 0; const bool window_write_back_fault = window_write_back_tile || (argc == 2 && std::strcmp(argv[1], "--window-writeback-fault") == 0); @@ -1526,6 +1896,16 @@ int main(int argc, char** argv) { "words won\n"); return 0; } + if (window_orphans) { + if (check_window_orphans(c)) return 1; + if (check_retired_window_write_back(c)) return 1; + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title window orphans: no window overlapped another; the one nothing reached was retired\n"); + return 0; + } if (geometry && check_declined_imports(c)) return 1; if (geometry && check_import_over_shadow(c)) return 1; if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index 6eadb4bea..7cc51cf92 100644 --- a/runtime/test/title_va_alias_test.cpp +++ b/runtime/test/title_va_alias_test.cpp @@ -138,6 +138,45 @@ int main() { EXPECT(!a.shader_side(arena) && a.shader_side(0xA0000ff) && !a.shader_side(0xA000100)); a.remove(title + 0x100, 0xA000000); EXPECT(a.size() == 0 && !a.shader_side(0xA000000)); + + constexpr std::uint64_t twin = title + 0x10000000; + EXPECT(a.add(twin + size, size, arena)); + first.clear(); + a.add_listener(&first, hear); + const auto pool_generation = a.generation(); + EXPECT(!a.add_twin(title, twin, size * 2, 0x5000000)); + EXPECT(a.generation() == pool_generation && !a.shader_side(0x5000000)); + EXPECT(a.size() == 1 && a.shader_va(title) == title && a.shader_va(twin) == twin); + EXPECT(a.shader_va(twin + size) == arena); + EXPECT(a.add_twin(title, twin, size, 0x5000000)); + EXPECT(a.generation() != pool_generation && a.shader_side(0x5000000)); + EXPECT(first.size() == 2); + EXPECT(first[0].change == Change::added && first[0].title_va == title && first[0].bytes == size); + EXPECT(first[1].change == Change::added && first[1].title_va == twin && first[1].bytes == size); + a.remove_listener(&first); + EXPECT(a.size() == 3 && a.shader_va(title) == 0x5000000 && a.shader_va(twin) == 0x5000000); + EXPECT(a.shader_va(twin + size) == arena); + + a.remove(title, 0x5000000); + EXPECT(a.add(title + size / 2, size, 0x7000000)); + EXPECT(!a.reuse_pool_mapping(title, twin, size, size, to)); + EXPECT(a.shader_va(title) == title); + EXPECT(a.reuse_pool_mapping(title, twin, size / 2, size, to) && to == 0x5000000); + EXPECT(!a.reuse_pool_mapping(title, twin, size / 2 + 1, size, to)); + EXPECT(a.range_of(title, to, room) && room == size / 2); + EXPECT(a.shader_va(title + size / 2) == 0x7000000); + EXPECT(a.reuse_pool_mapping(title + size / 2, twin + size / 2, size, size, to) && to == 0x7000000); + EXPECT(!a.add_twin(title + 4 * size, title + 5 * size, size * 2, arena)); + EXPECT(a.add(title + 4 * size, size, 0x8000000)); + EXPECT(a.add(twin + 5 * size - 16, 16, 0x9000000)); + EXPECT(a.reuse_pool_mapping(twin + 4 * size + 16, title + 4 * size + 16, size - 32, size, to) && to == 0x8000010); + a.remove(title + 4 * size, 0x8000000); + EXPECT(a.shader_side(0x8000010)); + a.forget_copy(twin + 4 * size, size, 0x8000000); + EXPECT(!a.shader_side(0x8000010)); + EXPECT(a.shader_va(twin + 4 * size + 16) == twin + 4 * size + 16); + EXPECT(a.shader_va(twin + 5 * size - 16) == 0x9000000); + std::printf("title_va_alias: translation inside a title-placed range, identity outside it and after release\n"); return 0; } diff --git a/runtime/test/title_window_plan_bounds_test.cpp b/runtime/test/title_window_plan_bounds_test.cpp index 93cf2bed4..52a9ea12d 100644 --- a/runtime/test/title_window_plan_bounds_test.cpp +++ b/runtime/test/title_window_plan_bounds_test.cpp @@ -83,6 +83,16 @@ int test_title_pool_extent_bounds() { EXPECT(leonida::title_pool_extent(pool_lo, pool_hi, pool_lo + 0x28000, pool_hi, kAlign, kMiB, second)); EXPECT(first.start == pool_lo + 0x20000 && first.size == 0xE0000); EXPECT(second.start == first.start && second.size == first.size); + + const auto source = pool_lo + 0x28000; + const auto twin = source + 2 * kMiB; + EXPECT(leonida::clip_title_pool_extent(first, source, twin, source - 0x4000, source + 0x60000, + twin - 0x10000, twin + 0x10000)); + EXPECT(first.start == source - 0x4000 && first.size == 0x14000); + EXPECT(!leonida::clip_title_pool_extent(second, source, twin, source + 1, pool_hi, + twin - 0x10000, twin + 0x10000)); + EXPECT(!leonida::clip_title_pool_extent(second, source, twin, pool_lo, pool_hi, twin, twin)); + EXPECT(second.start == pool_lo + 0x20000 && second.size == 0xE0000); return 0; } diff --git a/runtime/test/title_window_plan_test.cpp b/runtime/test/title_window_plan_test.cpp index 987ee6e35..1cef1757f 100644 --- a/runtime/test/title_window_plan_test.cpp +++ b/runtime/test/title_window_plan_test.cpp @@ -143,11 +143,99 @@ int check_stream_pool() { return 0; } +// A request whose bytes run into the next mapping gets one mapping for all of them, not a zero-size view: the +// extent made for it stops at that mapping (clip_title_pool_extent), and a view given less than its bytes would reach +// past its copy. The cover takes the windows it reaches whole, in either view, and nothing else. Made-up addresses: +// nothing is mapped here. +int check_pool_cover() { + constexpr std::uint64_t cpu = 0x7ff612340000ull, gpu = 0x5612340000ull, pool = 4 * kMiB; + const auto window = [](std::uint64_t shader_va) { return shader_va >= 0x100000 && shader_va < 0x800000; }; + leonida::TitleVaAliases table; + leonida::TitleWindowRange cover{}, unused{}; + // An extent 512 KiB in, 256 KiB long, at both of the pair's addresses. + EXPECT(table.add_twin(cpu + 0x80000, gpu + 0x80000, 0x40000, 0x100000)); + // A request 128 KiB before it for 192 KiB: from its own page, over the first extent, whole, in both views. + EXPECT(leonida::title_pool_cover(table, cpu, cpu + pool, cpu + 0x60000, gpu + 0x60000, cpu + 0x60000, + cpu + 0x90000, kAlign, kMiB, window, cover)); + EXPECT(cover.start == cpu + 0x60000 && cover.size == 0x60000); + // A request that starts inside the first extent and ends past it: the same, from the extent's start, and an end + // that is not page-aligned is rounded up. + EXPECT(leonida::title_pool_cover(table, cpu, cpu + pool, cpu + 0xB0000, gpu + 0xB0000, cpu + 0xB0000, + cpu + 0xD0010, kAlign, kMiB, window, cover)); + EXPECT(cover.start == cpu + 0x80000 && cover.size == 0x60000); + // add_twin refuses to enter it over the first extent; replace_twin replaces that one's ranges whole, and every + // byte they answered for is answered again. + EXPECT(!table.add_twin(cover.start, gpu + 0x80000, cover.size, 0x200000)); + // A buffer the title places in the cover's span in either view after the plan (slot 133 takes no lock of the + // planner's) is not erased with the windows: replace_twin refuses and leaves every range as it was. + for (const std::uint64_t placed : {cpu + 0xC0000, gpu + 0xC8000}) { + leonida::TitleVaAliases raced; + EXPECT(raced.add_twin(cpu + 0x80000, gpu + 0x80000, 0x40000, 0x100000)); + EXPECT(leonida::title_pool_cover(raced, cpu, cpu + pool, cpu + 0xB0000, gpu + 0xB0000, cpu + 0xB0000, + cpu + 0xD0010, kAlign, kMiB, window, cover)); + EXPECT(raced.add(placed, 0x4000, 0x900000)); + EXPECT(!raced.replace_twin(cover.start, gpu + 0x80000, cover.size, 0x200000, window)); + EXPECT(raced.size() == 3 && raced.shader_va(placed + 0x10) == 0x900010); + EXPECT(raced.shader_va(cpu + 0x80000) == 0x100000 && raced.shader_va(gpu + 0xBFFFF) == 0x13FFFF); + } + EXPECT(table.replace_twin(cover.start, gpu + 0x80000, cover.size, 0x200000, window)); + EXPECT(table.size() == 2); + EXPECT(table.shader_va(cpu + 0xBFFFF) == 0x23FFFF && table.shader_va(gpu + 0xD000F) == 0x25000F); + // Past `most`, or into a range that is not a window (a buffer placed in the GPU-only view), there is no cover. + EXPECT(!leonida::title_pool_cover(table, cpu, cpu + pool, cpu + 0x70000, gpu + 0x70000, cpu + 0x70000, + cpu + 0x90000, kAlign, 0x40000, window, unused)); + EXPECT(table.add(gpu + 0xE0000, 0x8000, 0x900000)); + EXPECT(!leonida::title_pool_cover(table, cpu, cpu + pool, cpu + 0xD8000, gpu + 0xD8000, cpu + 0xD8000, + cpu + 0xE4000, kAlign, kMiB, window, unused)); + std::printf("stream pool: a request crossing into the next extent gets one 384 KiB mapping over it, whole; none " + "over a buffer or past the cap\n"); + return 0; +} + +// The twin view is bounded like the pool's own, and never computed modulo 2^64. Made-up addresses. +int check_pool_cover_bounds() { + const auto window = [](std::uint64_t shader_va) { return shader_va >= 0x100000 && shader_va < 0x800000; }; + leonida::TitleWindowRange cover{}; + { + // Pool [0x100000, 0x500000), twin view [0x400000, 0x800000). A window at [0x200000, 0x440000) reaches the + // twin view from below it: covering it would erase it whole and leave [0x200000, 0x420000) unanswered. + leonida::TitleVaAliases table; + EXPECT(table.add(0x200000, 0x240000, 0x100000)); + EXPECT(!leonida::title_pool_cover(table, 0x100000, 0x500000, 0x120000, 0x420000, 0x120000, 0x130000, kAlign, + kMiB, window, cover)); + // And at the top: a window at [0x7F0000, 0x810000) runs past the twin view's end. + leonida::TitleVaAliases top; + EXPECT(top.add(0x7F0000, 0x20000, 0x100000)); + EXPECT(!leonida::title_pool_cover(top, 0x100000, 0x500000, 0x4E0000, 0x7E0000, 0x4E0000, 0x4F8000, kAlign, + kMiB, window, cover)); + } + { + // A twin view that would start below 0: the pool's first 3 MiB sit before address 0 there, so the request's + // span in it wraps. Refused, not looked up as an empty range past the window at [0, 0x20000). + leonida::TitleVaAliases table; + EXPECT(table.add(0, 0x20000, 0x100000)); + EXPECT(!leonida::title_pool_cover(table, 0x10000000, 0x10400000, 0x10300000, 0x100000, 0x10000000, + 0x10310000, kAlign, 4 * kMiB, window, cover)); + } + { + // One that would end past 2^64: the request's span there wraps, and a buffer in it (not a window) was missed. + leonida::TitleVaAliases table; + constexpr std::uint64_t twin = 0xFFFFFFFFFFF00000ull; + EXPECT(table.add(twin + 0x80000, 0x10000, 0x900000)); + EXPECT(!leonida::title_pool_cover(table, 0x100000, 0x500000, 0x100000, twin, 0x100000, 0x200000, kAlign, kMiB, + window, cover)); + } + std::printf("stream pool: no cover over a mapping past the twin view, nor over a twin view past 64 bits\n"); + return 0; +} + } // namespace int main() { if (check_window_budget()) return 1; if (check_stream_pool()) return 1; + if (check_pool_cover()) return 1; + if (check_pool_cover_bounds()) return 1; std::printf("title_window_plan: a refused window gives no raw base, and a stream pool's two views share one " "mapping\n"); return 0;