diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index bd9f62ec04..e843d8debc 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. @@ -3513,7 +3548,8 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv the driver's), as on D3D12. - GPU-writable slot-133 images on a default heap bind memory when replay, presentation or creation of a shader view first needs their Vulkan image. D3D12 placement and logical attachment views can precede that bind. - A CPU-fillable, typed BC texture can initially sample an immutable zero image of the same format, extent, + A CPU-fillable, typed BC texture (filled by host copies or the staged upload) can initially sample + an immutable zero image of the same format, extent, layer count and mip count. A CPU upload or explicit GPU command gives the placement private backing and republishes its existing descriptor keys. The cache holds at most 256 MiB. `LEONIDA_PLACED_IMAGE_DEFER=0` restores eager binding. @@ -3521,6 +3557,15 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv complete CPU read. Copies of descriptors written earlier resolve to the fallback until that upload succeeds. `LEONIDA_TITLE_IMAGE_DEFER=0` allocates these textures eagerly. The memory probe reports the live unbound image count and its Vulkan memory requirements in MiB. +- With `LEONIDA_TITLE_PARTIAL_MIPS=1`, such a texture can be filled before all its pages are readable. The XG + layout of a 2D texture of one slice stores its mips from the smallest to the largest, so the mips from `m` on are + the first `mip_chain_bytes(layout, m)` bytes from its base (`xg_xs_layout.h`; checked in `xg_xs_test` for tiled, + tail and linear layouts). The probe (`texture_memory_readable_bytes`) returns how many bytes from the base are + readable and `first_mip_within` the first mip those hold. When the last slot-70 view starts at that mip or later, + the mips from there on are filled and only the descriptor keys of views that start there or later are published. + The others stay on the fallback (`PendingImage::first_mip`) until a later fill has their mips. The image still has + memory for every mip: `LEONIDA_TITLE_PARTIAL_MIPS_MB` (2048) limits the image memory of the textures filled in + part. Arrays, cubes and volumes are filled whole or not at all. - Small optimal Vulkan images synthesized for slot-70 texture views share memory pages. Each slice meets the image's size, alignment and memory type requirements. The GPU retirement queue destroys the image before its slice can be reused. Large images, dedicated-only images, and failed pool allocations use individual memory @@ -3566,6 +3611,14 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv without host-transfer usage before it is bound, and takes the staging path. `d3d12_vulkan_device_test` and `d3d12_subresource_copy_test` force this branch on any GPU with `VulkanDeviceInfo::force_host_transfer_retry` (their third CPU-copy path; the second compares it with the host runtime). + - `LEONIDA_HOST_IMAGE_COPY` chooses whether the device enables the extension at all (`src/host_image_copy_policy.h`, + tested by `host_image_copy_policy_test`): `1` wherever the device has it, `0` never, and `auto`, the default, as + `1` except on NVIDIA (`vendorID` `0x10DE`), where it is off. On an RTX 4070 SUPER (Windows 11) a real boot lost + the device with `WRITE_INVALID` in 7 of 7 runs that used host image copies and in 0 of 2 that did not; why is + still under investigation. Off, the extension is neither enabled nor chained, no texture gets host-transfer + usage, and every copy takes the staging path, as on a device without the extension. Device creation logs one + line, `[rt] d3d12: host image copy: on (available)` or `off (...)` with the reason. Results with + `LEONIDA_HOST_IMAGE_COPY=1` on other NVIDIA GPUs and drivers are welcome in an issue. - 96-bit textures (`R32G32B32_FLOAT`/`_UINT`/`_SINT`/`_TYPELESS`, D3D-62) are `R32G32B32A32` images (`ResourceBinding::rgb96`), on every GPU. Most GPUs have no optimal-tiling RGB32 image (an RX 9070 XT reports no optimal features for `R32G32B32_SFLOAT`), and one that has would not avoid the repack: D3D12 places diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 5c07100bf4..3c0112060b 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -939,6 +939,12 @@ if(BUILD_TESTING) add_executable(vulkan_device_filter_test test/vulkan_device_filter_test.cpp) target_include_directories(vulkan_device_filter_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) add_test(NAME vulkan_device_filter COMMAND vulkan_device_filter_test) + # LEONIDA_HOST_IMAGE_COPY's choice (runtime/src/host_image_copy_policy.h): pure stdlib, no Vulkan instance. + add_executable(host_image_copy_policy_test test/host_image_copy_policy_test.cpp) + target_include_directories(host_image_copy_policy_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + add_test(NAME host_image_copy_policy COMMAND host_image_copy_policy_test) + add_executable(title_texture_refresh_test test/title_texture_refresh_test.cpp) + add_test(NAME title_texture_refresh COMMAND title_texture_refresh_test) add_executable(vk_presenter_capture_colour_test test/vk_presenter_capture_colour_test.cpp) add_test(NAME vk_presenter_capture_colour COMMAND vk_presenter_capture_colour_test) if(TARGET gta6rt) @@ -2985,6 +2991,13 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_fence_timing_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_fence_timing COMMAND d3d12_fence_timing_test) set_tests_properties(d3d12_fence_timing PROPERTIES SKIP_RETURN_CODE 77) + # CPU subresource copies through the staging queue wait for their own submission, not the direct queue (D9). + add_executable(d3d12_staged_copy_wait_test test/d3d12_staged_copy_wait_test.cpp) + target_link_libraries(d3d12_staged_copy_wait_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_staged_copy_wait_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_staged_copy_wait_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_staged_copy_wait COMMAND d3d12_staged_copy_wait_test) + set_tests_properties(d3d12_staged_copy_wait PROPERTIES SKIP_RETURN_CODE 77) # Fence events the host runtime sets or refuses (released fences, no fences), compared with the host devices. add_executable(d3d12_fence_events_test test/d3d12_fence_events_test.cpp) target_link_libraries(d3d12_fence_events_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) @@ -3993,6 +4006,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/README.md b/runtime/README.md index 90c040c05c..cdce0a811d 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -340,6 +340,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_CONSOLE_FORMATS` | on | Texture descriptions the console accepts and a PC GPU may not (an R9G9B9E5 render target, an sRGB RGBA8 or BGRA8 texture with unordered access) get a host format that can do the job. `0` refuses them, as a PC D3D12 runtime does. | | `LEONIDA_CONSOLE_HEAP_SHADOW` | on | A console descriptor heap has a copy in the descriptor arena that the shaders read. `0` keeps its bytes in the title's memory only (the comparison for a run that misbehaves with the copy). | | `LEONIDA_IMPORT_BELOW_ARENA` | unset | `1` keeps a host-memory import that the driver put below the GPU address arena. By default such an import is not used and the shadow buffer in the arena answers, because a V# cannot name an address below the arena. | +| `LEONIDA_HOST_IMAGE_COPY` | `auto` | Whether `WriteToSubresource`/`ReadFromSubresource` copy on the CPU with `VK_EXT_host_image_copy`. `auto` (unset, or any text other than `0` and `1`) uses it where the device has it, except on NVIDIA (vendor `0x10DE`), where a real boot lost the device; `1` uses it wherever the device has it; `0` never enables the extension, so every CPU texture copy takes the staging submit. Device creation logs one `[rt] d3d12: host image copy:` line with the choice and why (`docs/d3d12_vulkan.md`). | | `LEONIDA_ORDER_TEXTURE_UPLOADS` | on | A title texture in a host-transfer image is filled through the ordered host copy (`write_host_texture`). `0` fills it with `WriteToSubresource`. | | `LEONIDA_PLACED_IMAGE_KEYS` | on | A texture the title placed at its own address (device slot 133) and that the GPU writes keeps its own image address as its T# key. `0` re-keys it to the title address, like a texture the GPU does not write. | | `LEONIDA_PLACED_TEXTURE_UAV` | on | Device slot 71 writes an unordered-access view of a texture in the title's placed memory. `0` writes a null descriptor. | @@ -397,6 +398,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. | | `LEONIDA_TITLE_EVERY_BUDGET_US` | `0` | Microseconds one pass over the textures filled from the title's memory may spend on the textures it visits every pass (mapped by the title, or known stale), resuming where the last pass stopped; the texture that crosses the limit is finished. A mapped texture never filled yet is visited first whatever the limit. `0` visits all of them every pass. It limits the synchronous pass only: with `LEONIDA_TEXTURE_REFRESH_ASYNC=1` the pass runs on the refresh worker, and the limit does not apply. | | `LEONIDA_TITLE_TEXTURE_FILL_MS` | `8` | Milliseconds one pass over the textures filled from the title's memory may spend filling; a texture already started is finished. `0` removes the time limit and leaves `LEONIDA_TITLE_TEXTURE_FILL_MB` to bound the pass. | +| `LEONIDA_TITLE_PARTIAL_MIPS` | unset | `1`: a 2D texture of one slice the title keeps in its own memory, whose larger mips are not readable, is filled from the first mip that is when its last slot-70 view starts there or later. Views that start above keep the fallback until a later fill has their mips. Unset, a texture waits for all its mips. | +| `LEONIDA_TITLE_PARTIAL_MIPS_MB` | `2048` | With `LEONIDA_TITLE_PARTIAL_MIPS=1`, the image memory the textures filled in part may hold, in MiB: each has memory for all its mips. A texture past it keeps the fallback. | | `LEONIDA_MAP_READBACK` | unset | `1` writes the GPU's texels of a small render or unordered-access target the title placed into the title's pages when the title maps it, so a CPU read of the target sees what the GPU rendered (the title reads its exposure statistics that way). Only a single-row, single-mip, single-layer, single-sample 2D target of at most 4 KiB a row; the copy waits for the GPU's work already submitted, and a page that is not writable is left as it is. Unset, the title reads its own pages, which the GPU never writes. | | `LEONIDA_SLOT133_IMPORT` | on | *Diagnostic.* `0` imports no title-placed buffer (device slot 133) as host memory: each takes the shadow-buffer fallback, so no GPU store can reach the title's memory through an import. | | `LEONIDA_ARENA_NULL_MB` | `0` | `n` (MiB) keeps the first `n` MiB of the descriptor arena, at `heap_base + 0`, zeroed and never allocated, and moves the zero page and the quad indices above it. A translated shader whose address arithmetic starts from a null base then reads or writes there instead of in a title buffer or the shared zero page. Ignored when it would take half of the arena or more; the device logs the region it made. | diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 3bad0b7671..2c948ff3d3 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 02f9590bac..58649a29c2 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_title_image_upload.h b/runtime/shims/d3d12_title_image_upload.h index a0be8360dc..6d5674c0ea 100644 --- a/runtime/shims/d3d12_title_image_upload.h +++ b/runtime/shims/d3d12_title_image_upload.h @@ -35,20 +35,21 @@ class TitleImageUpload { ready_ = VK_NULL_HANDLE; } + // Uploads the mips from `from` on; `tiled` then needs only mip_chain_bytes(layout, from) bytes. template bool write(Device& d, leonida::ResourceId id, const leonida::ResourceBinding& image, const xg_xs::Texture& layout, const std::uint8_t* tiled, std::vector& columns, - bool inspect, bool& nonzero) { + bool inspect, bool& nonzero, unsigned from = 0) { const auto block = leonida::copy_block_format(image, VK_IMAGE_ASPECT_COLOR_BIT); const auto mips = layout.layout.mips; const auto layers = layout.array; - if (!block.bytes || block.bytes != layout.format.bytes || !mips || mips > image.mip_levels || + if (!block.bytes || block.bytes != layout.format.bytes || from >= mips || mips > image.mip_levels || !layers || layers > image.array_layers) return false; regions_.clear(); VkDeviceSize bytes = 0; for (unsigned layer = 0; layer < layers; ++layer) { - for (unsigned level = 0; level < mips; ++level) { + for (unsigned level = from; level < mips; ++level) { const auto& mip = layout.layout.plane[0].mips[level]; VkBufferImageCopy copy{}; copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, layer, 1}; @@ -81,7 +82,7 @@ class TitleImageUpload { [](std::uint8_t c) { return c != 0; }); } - const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, layers}; + const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, from, mips - from, 0, layers}; const auto result = d.context->write_staged_title_image(id, range, [&](const leonida::ReplayFunctions& replay, const leonida::LayoutPieces& pieces) { auto& vk = d.context->vk; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e7980daeed..748d6144a5 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" @@ -75,6 +76,7 @@ #include "../src/title_window_plan.h" #include "../src/vulkan_present.h" #include "../src/vulkan_device_filter.h" +#include "../src/host_image_copy_policy.h" #include "../src/vulkan13_features.h" #include "../src/vulkan_index_view.h" #include "d3d12_compute_input_probe.h" @@ -415,7 +417,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 +474,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 +904,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 +1323,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 +3154,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 +3305,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 +3344,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 +3358,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 +3430,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 +3573,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 +3588,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 +3596,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 +3674,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 +3701,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 +3711,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 +3827,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 +4027,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 +4562,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); } @@ -4262,6 +4604,26 @@ struct DeviceState { enum class VsharpPath { table, shadow, scratch }; enum class VsharpResult { unchanged, rebased, empty }; + // What fix_vsharp resolved a V# to, for a console heap's slot record (ConsoleHeapSlotRecords::set). + struct VsharpRecord { + leonida::ConsoleHeapSlotRecords::State state = leonida::ConsoleHeapSlotRecords::none; + uint64_t base = 0, span = 0, target = 0; + }; + // A buffer V#'s words, and what fix_vsharp made of them (ConsoleHeap::answers). + struct VsharpWords { + std::uint64_t low = 0, high = 0; + bool operator==(const VsharpWords&) const = default; + }; + struct VsharpWordsHash { + std::size_t operator()(const VsharpWords& words) const noexcept { + return std::hash{}(words.low ^ (words.high * 0x9e3779b97f4a7c15ull)); + } + }; + struct VsharpAnswer { + std::uint32_t words[3]; + VsharpResult result; + VsharpRecord record; + }; // `refused` (when given): for an answer of 0, the copy an alias range named that was not backed (0: none), so the // console heap's slot record is found again when a backing is added there. @@ -4294,6 +4656,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; @@ -4364,11 +4731,6 @@ struct DeviceState { } } - // What fix_vsharp resolved a V# to, for a console heap's slot record (ConsoleHeapSlotRecords::set). - struct VsharpRecord { - leonida::ConsoleHeapSlotRecords::State state = leonida::ConsoleHeapSlotRecords::none; - uint64_t base = 0, span = 0, target = 0; - }; VsharpResult fix_vsharp(uint32_t* w, VsharpPath path, VsharpRecord* record = nullptr) { if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer const uint64_t base = uint64_t(w[0]) | (uint64_t(w[1] & 0xffff) << 32); @@ -4406,12 +4768,14 @@ struct DeviceState { return VsharpResult::rebased; } - // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to - // the device's VkQueue and waited for. Created on first use. rt::d3d12::TitleImageUpload title_upload; // accessed with title_upload_mutex held std::mutex title_upload_mutex; // after title_texture_mutex when both are taken (the fill worker takes it alone) + // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to a + // VkQueue the game's first queues do not use and waited for (review D9): the copy family's for colour textures, + // the graphics family's for the rest (staged_copy). Created on first use. std::mutex staging_mutex; std::unique_ptr staging_queue; + std::unique_ptr staging_copy_queue; // The GPU address arena (docs/d3d12_vulkan.md section 3.3): one host-visible, device-addressable VkBuffer that // stands in for the console's GPU address space. A console VA is an offset in it, and heap_base (push-constant @@ -4591,12 +4955,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)); @@ -4686,6 +5052,9 @@ struct DeviceState { leonida::ConsoleHeapSlotRecords records; std::vector retries; std::size_t retry_at = 0; // where retry_console_slots goes on + // fix_vsharp's answers during one pass over the heap's slots (fix_heap_vsharp), cleared after it. + std::unordered_map answers; + bool answering = false; // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line std::chrono::steady_clock::time_point fix_start{}; bool fix_over = false; @@ -4694,7 +5063,7 @@ struct DeviceState { std::uint64_t refreshes = 0, logged = 0; std::chrono::steady_clock::time_point log_time{}; // Since the last log line. - std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0; + std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0, reused = 0; std::uint64_t images[5] = {}; // by TitleImage std::map refused_reasons; double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts @@ -4780,6 +5149,23 @@ struct DeviceState { return true; } + // fix_vsharp, asked once for each distinct V# in a pass over a heap's slots (heap.answering). The title writes the + // same words into thousands of slots, many of them data that reads as a V# into title memory with no copy, and + // each such answer costs VirtualQuery calls: under Wine a third of the submitting thread's time in the world. + VsharpResult fix_heap_vsharp(ConsoleHeap& heap, std::uint32_t* w, VsharpPath path, VsharpRecord* record) { + if (!heap.answering || (w[3] >> 30) || !w[2]) return fix_vsharp(w, path, record); + const VsharpWords key{w[0] | std::uint64_t(w[1]) << 32, w[2] | std::uint64_t(w[3]) << 32}; + if (const auto it = heap.answers.find(key); it != heap.answers.end()) { + std::memcpy(w, it->second.words, sizeof(it->second.words)); + *record = it->second.record; + ++heap.reused; + return it->second.result; + } + const VsharpResult result = fix_vsharp(w, path, record); + heap.answers.emplace(key, VsharpAnswer{{w[0], w[1], w[2]}, result, *record}); + return result; + } + // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above, and the only writer of a // resource heap's slot records. True when it is settled: not a T# whose texture is still to come. A sampler heap // holds S#s: copied as written. @@ -4797,14 +5183,14 @@ struct DeviceState { // and recorded as waiting: a backing, alias range or title memory added over it fixes the slot again // (apply_slot_changes). vsharp = true; - const VsharpResult result = fix_vsharp(w, path, &halves[0]); + const VsharpResult result = fix_heap_vsharp(heap, w, path, &halves[0]); if (result == VsharpResult::rebased) ++heap.vsharps; // Only the GPU copy changes; the title's bytes (heap.previous) stay as written. if (result == VsharpResult::empty) ++heap.unbacked; // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it at // heap_base + a raw title address loses the device just as one through the buffer V# does. A counter with // no backing is nulled and waits as the buffer V# does. - if (fix_vsharp(w + 4, path, &halves[1]) == VsharpResult::empty) ++heap.unbacked; + if (fix_heap_vsharp(heap, w + 4, path, &halves[1]) == VsharpResult::empty) ++heap.unbacked; } else { leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); @@ -5003,10 +5389,14 @@ struct DeviceState { heap.fix_start = t1; heap.fix_over = false; heap.fix_count = 0; + heap.answering = true; heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { fix_console_slots(heap, offset, bytes); }); + heap.answers.clear(); // the changes below can release what an answer of the pass above named // Even an unchanged title slot may name a buffer released since the last submission: the slots the changes // touch are fixed again, found by their records. if (changes) apply_slot_changes(heap, *changes); + heap.answering = false; + heap.answers.clear(); const auto t2 = clock::now(); // T#s whose texture is not there yet, and slots the fix budget deferred. if (!heap.retries.empty()) retry_console_slots(heap); @@ -5053,8 +5443,9 @@ struct DeviceState { "in %.3f ms on average (pages %.3f, fixing copied slots %.3f, %llu left to retries past the " "budget, retrying %.3f: %.1f slots a " "submission, %zu waiting), %llu write faults; %llu title V#s rebased, %llu with no copy given " - "no records (%zu V# halves waiting for a backing), T#s %llu known, %llu bound, %llu " - "naming no texture, %llu refused, %llu words that are no V# or T# (data, null in the copy)\n", + "no records (%zu V# halves waiting for a backing), %llu answered by an earlier slot of the pass, " + "T#s %llu known, %llu bound, %llu naming no texture, %llu refused, %llu words that are no " + "V# or T# (data, null in the copy)\n", static_cast(heap->console_va), heap->imported ? "imported" : "copy", static_cast(heap->refreshes), "copied", double(heap->copied) / 1024.0 / count, @@ -5064,6 +5455,7 @@ struct DeviceState { static_cast(heap->pages ? heap->pages->faults() : 0), static_cast(heap->vsharps), static_cast(heap->unbacked), heap->records.waiting_count(), + static_cast(heap->reused), static_cast(heap->images[unsigned(TitleImage::known)]), static_cast(heap->images[unsigned(TitleImage::bound)]), static_cast(heap->images[unsigned(TitleImage::unknown)]), @@ -5107,7 +5499,7 @@ struct DeviceState { std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx unbound T#s by reason: %s\n", static_cast(heap->console_va), refused_breakdown.c_str()); heap->refused_reasons.clear(); - heap->copied = heap->vsharps = heap->unbacked = heap->retried = heap->deferred_fixes = 0; + heap->copied = heap->vsharps = heap->unbacked = heap->retried = heap->reused = heap->deferred_fixes = 0; for (auto& n : heap->images) n = 0; heap->ms = heap->pages_ms = heap->fix_ms = heap->retry_ms = 0; if (start - arena_log_time >= std::chrono::seconds(60)) { @@ -7324,8 +7716,10 @@ struct DeviceState { std::map image_entries; // A pending stream has a console descriptor immediately. Keep its keys (including aliases) // until the first complete upload. A shader hash miss selects the existing fallback image. + // Once the smaller mips are filled (publish_streamed_texture), only the views that start above first_mip wait. struct PendingImage { VkImage zero = VK_NULL_HANDLE; + std::uint32_t first_mip = UINT32_MAX; std::map keys; }; std::unordered_map pending_image_keys; @@ -7452,7 +7846,7 @@ struct DeviceState { namespace g = leonida::gfx10; if (!bindless) return false; auto pending = pending_image_keys.find(vk_image); - if (pending != pending_image_keys.end()) { + if (pending != pending_image_keys.end() && image.first_mip < pending->second.first_mip) { pending->second.keys.try_emplace(words, image); if (!pending->second.zero) return true; vk_image = pending->second.zero; @@ -7513,7 +7907,8 @@ struct DeviceState { if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type)); return false; } - if (const auto pending = pending_image_keys.find(vk_image); pending != pending_image_keys.end()) { + if (const auto pending = pending_image_keys.find(vk_image); + pending != pending_image_keys.end() && image.first_mip < pending->second.first_mip) { pending->second.keys.try_emplace(words, image); if (!pending->second.zero) return true; vk_image = pending->second.zero; @@ -8625,9 +9020,9 @@ class Resource final bool replay_seen() const { return replay_seen_.load(std::memory_order_relaxed); } bool staged_title() const { return staged_title_; } bool upload_staged_title(const rt::xg_xs::Texture& layout, const std::uint8_t* tiled, - std::vector& columns, bool inspect, bool& nonzero) { + std::vector& columns, bool inspect, bool& nonzero, unsigned from) { std::lock_guard lock(device_.title_upload_mutex); - return device_.title_upload.write(device_, id(), binding_, layout, tiled, columns, inspect, nonzero); + return device_.title_upload.write(device_, id(), binding_, layout, tiled, columns, inspect, nonzero, from); } // Map and the destructor notify the registry for a slot-133 placement. void mark_title_texture() { title_texture_ = true; } @@ -9295,9 +9690,17 @@ class Resource final const char* value = std::getenv("LEONIDA_PLACED_IMAGE_DEFER"); return !value || std::strcmp(value, "0"); }(); + // A device without host copies has no other way to fill a title image: a refresh before a submission may not + // use a staged copy through the queue (host_copy_now). Its linear movie planes are staged too. + const bool no_host_copy = !device_.copy_memory_to_image && cpu_visible() && samples == 1 && + !format.d24_as_float && !format.rgb96; // Private BC copies start with the exact same zero blocks as the shared image. The host // transition and clear complete before a private view is published, including during command prepare. - if (defer_placed && origin == TitleImageOrigin::placed && host_transfer_ && device_.bindless && + // Without host copies the staged upload fills the private image, and the first shader submission clears what + // it has not filled. + const bool can_fill = host_transfer_ || (no_host_copy && stage_title && allow_staged_title && + device_.image_requirements); + if (defer_placed && origin == TitleImageOrigin::placed && can_fill && device_.bindless && desc_.Flags == D3D12_RESOURCE_FLAG_NONE && desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc_.SampleDesc.Count == 1 && asked_castable.empty() && !format.typeless && leonida::block_format(format.format, format.aspects).block > 1) { @@ -9306,11 +9709,7 @@ class Resource final shared_zero_ = device_.zero_sampled_image(desc_, format, footprint.size); } std::uint32_t plain_bits = 0; - // A device without host copies has no other way to fill a title image: a refresh before a submission may not - // use a staged copy through the queue (host_copy_now). Its linear movie planes are staged too. - const bool no_host_copy = !device_.copy_memory_to_image && cpu_visible() && samples == 1 && - !format.d24_as_float && !format.rgb96; - if (stage_title && !shared_zero_ && allow_staged_title && origin != TitleImageOrigin::ordinary && + if (stage_title && (!shared_zero_ || no_host_copy) && allow_staged_title && origin != TitleImageOrigin::ordinary && (no_host_copy || (!linear_placement && host_transfer_)) && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT && device_.image_requirements) { for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount; ++i) { @@ -9336,6 +9735,7 @@ class Resource final image_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; staged_title_ = false; + shared_zero_ = VK_NULL_HANDLE; log_once("no room for a staged title image; retrying host-copyable backing, format", int(info.format)); return create_texture(format, asked_castable, origin, false); }; @@ -9521,7 +9921,7 @@ class Resource final return deferred_stream_ ? S_OK : register_bound_texture(); } - // Called with title_texture_mutex held, after a guarded read of the complete console texture. + // Called with title_texture_mutex held, after a guarded read of the console texture (its smaller mips at least). bool back_streamed_texture() { if (!deferred_bytes_) return true; if (!image_backing_bytes_) { @@ -9536,19 +9936,32 @@ class Resource final return true; } - void publish_streamed_texture() { + // The mips from `from` on are filled: the views that start there or later get their T#s, the others wait on. + void publish_streamed_texture(unsigned from = 0) { if (!deferred_stream_) return; std::lock_guard lock(device_.descriptor_mutex); - auto pending = device_.pending_image_keys.extract(image_); + DeviceState::PendingImage ready; + if (const auto pending = device_.pending_image_keys.find(image_); pending != device_.pending_image_keys.end()) { + ready = pending->second; + std::erase_if(ready.keys, [&](const auto& key) { return key.second.first_mip < from; }); + if (from) { + pending->second.first_mip = from; + std::erase_if(pending->second.keys, [&](const auto& key) { return key.second.first_mip >= from; }); + } else { + device_.pending_image_keys.erase(pending); + } + } const auto owner = device_.images_by_address.find(image_address_); - if (!pending.empty() && owner != device_.images_by_address.end() && owner->second == this) { - if (pending.mapped().zero) device_.forget_image_views_locked(image_address_); - for (const auto& [words, image] : pending.mapped().keys) + if (owner != device_.images_by_address.end() && owner->second == this) { + if (ready.zero) device_.forget_image_views_locked(image_address_); + for (const auto& [words, image] : ready.keys) device_.bind_image_locked(words, image, image_, format_, aspects_, false, has_view_format_list(), uint_backed_); } - deferred_stream_ = false; + if (!from) deferred_stream_ = false; } + // Some view still waits, or would wait, for mips not filled yet. + bool deferred_stream() const { return deferred_stream_; } VkDeviceSize unbound_bytes() const { return image_backing_bytes() ? 0 : deferred_bytes_; } @@ -9562,6 +9975,7 @@ class Resource final } if (shared_zero_) { if (host_transfer_ && !host_initialize()) return false; + if (!host_transfer_) device_.context->note_shader_image(id()); // zeros until something fills it publish_streamed_texture(); } return true; @@ -10223,15 +10637,34 @@ class Resource final leonida::ReplayResult result = leonida::ReplayResult::unsupported; { std::lock_guard lock(device_.staging_mutex); - if (!device_.staging_queue) { - device_.staging_queue = std::make_unique(*device_.context, device_.info.queue, - device_.info.queue_family); - device_.staging_queue->make_synchronous(); // waited for at once (idle below) + // Review D9: a VkQueue the game's direct queue is not on. CreateCommandQueue hands each family's VkQueues + // out from the first, so the last one. A colour copy goes to the copy family, whose engine runs beside + // queued graphics work (a second graphics VkQueue may be time-sliced behind it, as on NVIDIA); a depth + // or stencil copy may convert D24, and an rgb96 one is repacked, by a compute shader, so they stay on + // the graphics family. + const bool copy_family = + !device_.info.copy_queues.empty() && aspects_ == VK_IMAGE_ASPECT_COLOR_BIT && !rgb96_; + auto& staging_queue = copy_family ? device_.staging_copy_queue : device_.staging_queue; + if (!staging_queue) { + if (copy_family) { + staging_queue = std::make_unique( + *device_.context, device_.info.copy_queues.back(), device_.info.copy_family, + leonida::VulkanQueue::QueueKind::copy); + } else { + const auto& queues = device_.info.command_queues; + const VkQueue own = queues.size() > 1 ? queues.back() : device_.info.queue; + staging_queue = std::make_unique(*device_.context, own, + device_.info.queue_family); + } + staging_queue->make_synchronous(); // submitted inline, then waited for (wait_submitted below) } - if (device_.staging_queue->ok()) { + if (staging_queue->ok()) { const leonida::CommandList* lists[] = {&list}; - result = device_.staging_queue->execute(lists); - if (result == leonida::ReplayResult::success && !device_.staging_queue->idle()) + result = staging_queue->execute(lists); + // Only this copy's own submission (review D9: was vkQueueWaitIdle under the submit lock). Other + // queues need no wait: D3D12 asks the application to have seen the texture's GPU work complete before + // a CPU copy, and that host wait, then this submission, orders it before the copy. + if (result == leonida::ReplayResult::success && !staging_queue->wait_submitted()) result = leonida::ReplayResult::unsupported; } } @@ -10304,7 +10737,7 @@ class Resource final std::unique_ptr deferred_attachment_; std::atomic replay_seen_{false}; bool staged_title_ = false; - std::atomic deferred_stream_{false}; // keys stay unpublished until the whole first upload succeeds + std::atomic deferred_stream_{false}; // keys stay unpublished until the mips they name are uploaded VkDeviceSize deferred_bytes_ = 0; std::uint32_t deferred_types_ = 0; bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT @@ -10316,10 +10749,11 @@ class Resource final std::shared_ptr heap_range_; }; -// One immutable, host-zeroed BC image per exact view shape. It has the right sampled format, extent, +// One immutable, zeroed BC image per exact view shape (zeroed on the host, or by the first shader submission). It has +// the right sampled format, extent, // mip count and zero-block decoding even before the title first supplies data or copies into the placement. VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Format& format, VkDeviceSize bytes) { - if (!host_transfer_format(format.format)) return VK_NULL_HANDLE; + if (copy_memory_to_image && !host_transfer_format(format.format)) return VK_NULL_HANDLE; const ZeroShape key{d.Format, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels}; std::lock_guard lock(zero_image_mutex); if (auto it = zero_images.find(key); it != zero_images.end()) return it->second ? it->second->image() : VK_NULL_HANDLE; @@ -10328,12 +10762,13 @@ VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Form if (used >= limit || bytes > limit - used) return VK_NULL_HANDLE; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; auto* zero = new Resource(*this, d, heap, D3D12_HEAP_FLAG_NONE); - if (FAILED(zero->create_texture(format)) || !zero->host_initialized_image() || + if (FAILED(zero->create_texture(format)) || (copy_memory_to_image && !zero->host_initialized_image()) || zero->image_backing_bytes() > limit - used) { zero->Release(); zero_images.emplace(key, nullptr); return VK_NULL_HANDLE; } + if (!zero->host_initialized_image()) context->note_shader_image(zero->id()); // cleared before a shader reads it zero_images.emplace(key, zero); zero_image_bytes.fetch_add(zero->image_backing_bytes(), std::memory_order_relaxed); return zero->image(); @@ -13907,6 +14342,11 @@ struct TitleTexture { bool full_hashed = false; bool every_byte() const { return mapped && (async_texture_refresh() || layout.layout.size <= (4u << 20)); } std::uint64_t fills = 0; + unsigned view_mip = 0; // first mip of the last slot-70 view + // The last probe: the first mip readable with every smaller one (the mip count: none; only a 2D texture of one + // slice has other values than 0 and the mip count). memory.pending(): above fill_limit, no use yet. + unsigned readable_from = 0; + unsigned filled_from = 0; // fills > 0: the image holds the mips from here on }; // The layout of a slot-133 texture as the title's own XG computer for its shape says (title_xg_layouts): how the title @@ -14789,6 +15229,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 @@ -15610,7 +16051,8 @@ class Device final std::lock_guard upload(state_.title_upload_mutex); state_.title_upload.release(state_); } - state_.staging_queue.reset(); // it uses the context + state_.staging_queue.reset(); // they use the context + state_.staging_copy_queue.reset(); if (state_.context && state_.bindless) { // Every texture is gone by now (each held this device), and its views with it; samplers remain. std::lock_guard lock(state_.descriptor_mutex); @@ -15978,13 +16420,16 @@ class Device final : leonida::title_texture_snapshot(state_.title_textures); if (async) title_slice_ = entries.size() == 128 ? entries.back().first + 1 : 0; title_pass_ = true; + title_partial_bytes_ = 0; + for (const auto& entry : entries) + if (entry.second->fills && entry.second->filled_from) title_partial_bytes_ += entry.second->backing_bytes; std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0; const auto visit = [&](TitleTexture& t) { // A slot-133 texture's guessed layout (no slot-70 view yet) is only used once the title maps it. if (t.gpu_written || !t.layout_known || !t.resource || ((t.layout_guessed || t.layout_from_xg) && !t.mapped && !t.stale)) return; - const std::uint64_t span = t.layout.layout.size; + std::uint64_t span = fill_bytes(t); const bool always = t.mapped && refresh_mapped_pages(); // Out of this pass's fill budget (bytes or time): a texture known to need a fill (stale) waits for the // next pass unprobed and unhashed; hashing it now would only find it changed again (measured: 10,000 @@ -15998,13 +16443,24 @@ class Device final } std::uint64_t hash = 0; if (!title_texture_readable(t)) return; + span = fill_bytes(t); // the probe may have found more mips, or fewer const bool full_mapped = async && always; checked += full_mapped ? span : hashed_bytes(span); ++stats.checked; const auto* bytes = reinterpret_cast(static_cast(t.cpu)); const auto timed_hash = [&](std::uint64_t& out, bool all = false) { const auto start = clock::now(); - const bool ok = hash_guarded(bytes, std::size_t(span), out, all); + // Every byte of write-combined memory goes through a streaming copy (copy_guarded): ordinary loads + // from it are not cached, and hashing a 4 MiB mapped texture in place took 36 ms on average and up to + // 78 ms each sixth pass, one to two frames of a title that paces itself for 30 Hz. + bool ok; + if (all && title_memory_write_combined(t.cpu)) { + title_tiled_.resize(std::size_t(span)); + ok = copy_guarded(title_tiled_.data(), bytes, std::size_t(span), true) && + hash_guarded(title_tiled_.data(), std::size_t(span), out, true); + } else { + ok = hash_guarded(bytes, std::size_t(span), out, all); + } stats.hash_ns += std::chrono::duration_cast(clock::now() - start).count(); return ok; }; @@ -16021,7 +16477,7 @@ class Device final stats.hash_ns += std::chrono::duration_cast(clock::now() - start).count(); const auto it = state_.title_textures.find(address); if (it == state_.title_textures.end() || it->second.get() != &t || !t.resource || - !t.layout_known || t.layout.layout.size != span || t.fills != fills) return; + !t.layout_known || fill_bytes(t) != span || t.fills != fills) return; ++stats.mapped_checks; if (!ok) { t.memory.defer(); @@ -16080,9 +16536,15 @@ class Device final if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) { stats.written_ranges += written.size(); leonida::merge_title_writes(written); - const auto invalidate = [&](TitleTexture& t, bool write) { + const auto invalidate = [&](TitleTexture& t, bool write, bool remapped) { if (t.gpu_written || !t.layout_known) return; t.memory.retry(); + // Pages that came without a noted write: a texture not filled, or not all of it, is filled in this + // pass's round of stale ones; the sweep reached it many passes later. + if (partial_mips() && remapped && !t.stale && t.resource && !t.layout_guessed && + !t.layout_from_xg && (!t.fills || t.filled_from) && title_texture_readable(t) && + (!t.fills || t.readable_from < t.filled_from)) + t.stale = true; if (write) t.stale = true; if (overflow) t.hashed = false; }; @@ -16092,15 +16554,15 @@ class Device final auto& t = *ptr; const auto end = t.cpu + t.layout.layout.size; const bool write = leonida::title_write_overlaps(written, t.cpu, end); - if (write || map_all || overflow || leonida::title_write_overlaps(title_map_changes_, t.cpu, end)) - invalidate(t, write); + const bool remapped = leonida::title_write_overlaps(title_map_changes_, t.cpu, end); + if (write || map_all || overflow || remapped) invalidate(t, write, remapped || map_all); } } else { const auto apply = [&](const auto& ranges, bool write) { for (const auto& [from, to] : ranges) state_.texture_ranges.overlapping(from, to, [&](auto key) { auto& t = *state_.title_textures.at(key); - invalidate(t, write); + invalidate(t, write, !write); if (t.stale) queue_title_fill(key); }); }; @@ -16214,6 +16676,9 @@ class Device final std::uint64_t views = 0, null_views = 0, of_slot133 = 0, of_cache = 0, made = 0, retired = 0, registered = 0, refusals = 0, written_ranges = 0, unmaps = 0, unreadable = 0, pending_views = 0; std::uint64_t fills = 0, fill_bytes = 0, fill_failures = 0; + // Fills of some mips only; textures whose first fill was one; those that got larger mips later; first fills + // refused by LEONIDA_TITLE_PARTIAL_MIPS_MB. + std::uint64_t partial_fills = 0, partial_textures = 0, partial_upgrades = 0, partial_refused = 0; std::uint64_t staged_fills = 0, staged_ns = 0; // refresh_title_textures, since the last log line std::uint64_t passes = 0, checked = 0, hashed = 0, changed = 0, deferred = 0, filled_bytes = 0, @@ -16343,6 +16808,7 @@ class Device final Resource* r = nullptr; rt::xg_xs::Texture layout{}; std::uint64_t cpu = 0, fills = 0; + unsigned from = 0; bool every_byte = false; { std::lock_guard lock(state_.title_texture_mutex); @@ -16359,6 +16825,7 @@ class Device final layout = t.layout; cpu = t.cpu; fills = t.fills; + from = fill_from(t); every_byte = t.every_byte(); } else { filled = fill_title_texture(t, true) != 0; @@ -16368,7 +16835,7 @@ class Device final } } if (r) { - filled = fill_unlocked(address, *r, layout, cpu, fills, every_byte, f); + filled = fill_unlocked(address, *r, layout, cpu, fills, from, every_byte, f); r->Release(); } std::size_t left = 0; @@ -16392,8 +16859,8 @@ class Device final // The fill worker's fill of a staged texture: copy, hash and upload without the registry lock, then the result // under it, if the registry still names `r` at `address` and nobody filled it meanwhile. bool fill_unlocked(std::uint64_t address, Resource& r, const rt::xg_xs::Texture& layout, std::uint64_t cpu, - std::uint64_t fills, bool every_byte, TitleFiller& f) { - const std::uint64_t span = layout.layout.size; + std::uint64_t fills, unsigned from, bool every_byte, TitleFiller& f) { + const std::uint64_t span = rt::xg_xs::mip_chain_bytes(layout, from); f.tiled.resize(std::size_t(span)); const bool copied = copy_guarded(f.tiled.data(), reinterpret_cast(cpu), std::size_t(span), title_memory_write_combined(cpu)); @@ -16404,7 +16871,7 @@ class Device final hash_guarded(f.tiled.data(), f.tiled.size(), hash); full_hashed = every_byte && hash_guarded(f.tiled.data(), f.tiled.size(), full, true); const auto start = std::chrono::steady_clock::now(); - ok = r.upload_staged_title(layout, f.tiled.data(), f.columns, false, nonzero); + ok = r.upload_staged_title(layout, f.tiled.data(), f.columns, false, nonzero, from); staged_ns = std::chrono::duration_cast(std::chrono::steady_clock::now() - start) .count(); } @@ -16427,7 +16894,7 @@ class Device final } ++title_stats_.staged_fills; if (t.fills != fills) return true; // another fill recorded itself in between: its hash is as good - if (t.owned && !t.fills) r.publish_streamed_texture(); + note_filled_from(t, from); t.hash = hash; t.hashed = true; t.full_hash = full; @@ -16484,6 +16951,7 @@ class Device final std::chrono::steady_clock::time_point title_retry_all_{}; // likewise leonida::TitleWriteRanges title_map_changes_; // likewise, scratch VkDeviceSize retired_backing_ = 0; + VkDeviceSize title_partial_bytes_ = 0; // likewise: image memory of the textures filled in part, as of this pass std::vector> retired_title_textures_; // likewise std::vector title_tiled_, title_linear_; // scratch, under title_texture_mutex std::vector title_columns_; @@ -16549,6 +17017,7 @@ class Device final return written; }; auto& textures = state_.title_textures; + const unsigned view_mip = srv.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D ? srv.Texture2D.MostDetailedMip : 0; const auto it = textures.find(address); // An entry without a resource is one destroyed inside the registry, waiting for drain_titles_gone. TitleTexture* t = it == textures.end() || !it->second->resource ? nullptr : it->second.get(); @@ -16596,12 +17065,16 @@ class Device final retire_title_texture(*t); state_.texture_ranges.erase(address); textures.erase(address); - t = make_title_texture(d, words, srv, address, same_shape ? formats : std::vector{}); + t = make_title_texture(d, words, srv, address, view_mip, same_shape ? formats : std::vector{}); } else if (t) { ++title_stats_.of_cache; + if (t->view_mip != view_mip) { + t->view_mip = view_mip; + if (!t->fills) t->memory.retry(); // what is readable may do for this view + } refresh_title_texture(*t); } else { - t = make_title_texture(d, words, srv, address, {}); + t = make_title_texture(d, words, srv, address, view_mip, {}); } return t && write(*t); } @@ -16615,7 +17088,7 @@ class Device final TitleTexture* make_title_texture(const rt::xg_xs::ResourceDesc& d, const std::array& words, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, std::uint64_t address, - std::vector formats) { + unsigned view_mip, std::vector formats) { namespace xg = rt::xg_xs; if (d.flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) @@ -16625,11 +17098,10 @@ class Device final auto entry = std::make_shared(); const char* why = nullptr; if (!title_layout(d, entry->layout, why)) return refuse_title_view(why, d, address), nullptr; - const std::uint64_t span = entry->layout.layout.size; entry->cpu = leonida::title_gpu_views::to_cpu(address); // A streamed texture can have views before its pages arrive. Keep the descriptor stable across its first fill. entry->memory.check(0, check_pages_before_read(), - [&] { return probe_title_memory(entry->cpu, span, false); }); + [&] { return probe_title_texture(*entry, false); }); title_stats_.unreadable += entry->memory.pending(); // The image takes the view's format too when the element is the same size (five-star-recomp does the same); // views in other formats of the same description add theirs (place_title_view). @@ -16687,16 +17159,20 @@ class Device final entry->set_resource(r); entry->owned = true; entry->formats = std::move(formats); + entry->view_mip = view_mip; + if (entry->memory.pending() && entry->readable_from <= fill_limit(*entry)) + entry->memory.retry(); // some mips do for this view + const bool readable = title_texture_readable(*entry); if (title_fill_async()) { entry->stale = true; // filled by the fill worker (queued below, once it is in the registry) - } else if (!entry->memory.pending()) { + } else if (readable) { fill_title_texture(*entry, true); } ++title_stats_.made; TitleTexture* t = entry.get(); state_.index_texture(*entry); state_.title_textures[address] = std::move(entry); - if (title_fill_async() && !t->memory.pending()) queue_title_fill(address); + if (title_fill_async() && readable) queue_title_fill(address); return t; } @@ -16711,6 +17187,49 @@ class Device final ++title_stats_.retired; } + // LEONIDA_TITLE_PARTIAL_MIPS=1 (off by default). A slot-70 2D texture whose larger mips are not readable is filled from the + // first mip that is, with every smaller one, when its last view starts there or later. The T#s of views that start + // above stay on the fallback (PendingImage::first_mip), so no shader samples a mip that was not filled. Larger + // mips come with a later fill; one whose filled mips are gone keeps them. + // shortcut: the image has memory for every mip, LEONIDA_TITLE_PARTIAL_MIPS_MB in all; make it without the missing + // mips when that limit is what keeps textures on the fallback. + static bool partial_mips() { + static const bool enabled = [] { + const char* v = std::getenv("LEONIDA_TITLE_PARTIAL_MIPS"); + return v && std::strcmp(v, "1") == 0; + }(); + return enabled; + } + static VkDeviceSize partial_mips_budget() { + static const VkDeviceSize bytes = [] { + const char* v = std::getenv("LEONIDA_TITLE_PARTIAL_MIPS_MB"); + return VkDeviceSize(v && *v ? std::strtoull(v, nullptr, 10) : 2048) << 20; + }(); + return bytes; + } + // Only an image whose T#s are published with its fills (deferred_stream) may hold a part of its mips. + static bool partial_texture(const TitleTexture& t) { + return partial_mips() && t.owned && t.resource && t.resource->deferred_stream() && + t.layout.layout.dimension == rt::xg_xs::kTexture2D && t.layout.array == 1; + } + // The largest first mip a fill may start at: what is filled already is never left half old. + static unsigned fill_limit(const TitleTexture& t) { + if (!partial_texture(t)) return 0; + return t.fills ? t.filled_from : std::min(t.view_mip, t.layout.layout.mips - 1); + } + static unsigned fill_from(const TitleTexture& t) { return std::min(t.readable_from, fill_limit(t)); } + static std::uint64_t fill_bytes(const TitleTexture& t) { return rt::xg_xs::mip_chain_bytes(t.layout, fill_from(t)); } + + // After an upload of the mips from `from` on, before ++t.fills. + void note_filled_from(TitleTexture& t, unsigned from) { + if (t.owned && (!t.fills || from < t.filled_from)) t.resource->publish_streamed_texture(from); + title_stats_.partial_fills += from != 0; + title_stats_.partial_textures += from && !t.fills; + title_stats_.partial_upgrades += t.fills && from < t.filled_from; + if (from && !t.fills) title_partial_bytes_ += t.backing_bytes; + t.filled_from = from; + } + static bool texture_probe() { static const bool enabled = [] { const char* v = std::getenv("LEONIDA_TEXTURE_PROBE"); @@ -16735,11 +17254,13 @@ class Device final return enabled; } - // texture_memory_readable, timed and counted (TitleTextureStats::probes). - bool probe_title_memory(std::uint64_t cpu, std::uint64_t span, bool waited, - leonida::TexturePageCommitter commit = nullptr) { + // texture_memory_readable_bytes, timed and counted (TitleTextureStats::probes). + // True when a fill can use what is readable; t.readable_from says what that is. + bool probe_title_texture(TitleTexture& t, bool waited, leonida::TexturePageCommitter commit = nullptr) { const auto start = std::chrono::steady_clock::now(); - const bool readable = leonida::texture_memory_readable(cpu, span, commit); + t.readable_from = rt::xg_xs::first_mip_within( + t.layout, leonida::texture_memory_readable_bytes(std::uintptr_t(t.cpu), t.layout.layout.size, commit)); + const bool readable = t.readable_from <= fill_limit(t); const std::size_t where = title_pass_ ? 0 : 1; TitleTextureStats& s = title_stats_; s.probe_ns[where] += std::chrono::duration_cast( @@ -16762,7 +17283,7 @@ class Device final // The answer is kept (generation 0) until a map change over the texture, a write into it or the periodic // retry of refresh_title_textures asks again. return t.memory.check(0, guard && !mapped, - [&] { return probe_title_memory(t.cpu, t.layout.layout.size, waited, commit); }, + [&] { return probe_title_texture(t, waited, commit); }, guard && !mapped); } @@ -16789,14 +17310,15 @@ class Device final std::uint64_t hash = 0; if (!title_texture_readable(t)) return; if (!hash_guarded(reinterpret_cast(static_cast(t.cpu)), - std::size_t(t.layout.layout.size), hash)) { + std::size_t(fill_bytes(t)), hash)) { t.memory.defer(); return; } if (!t.hashed || hash != t.hash || t.stale) fill_title_texture(t, true); } - // Snapshot the whole footprint before uploading any subresource. A concurrent unmap defers the fill. + // Snapshot the footprint (that of the mips the fill is for) before uploading any subresource. A concurrent unmap + // defers the fill. // Private title staging bypasses the D3D12 submit callbacks. Generic staged copies require an outer fill. std::uint64_t fill_title_texture(TitleTexture& t, bool staged) { const rt::xg_xs::Texture& layout = t.layout; @@ -16807,8 +17329,14 @@ class Device final t.stale = true; return 0; } - const std::uint64_t span = layout.layout.size; if (!title_texture_readable(t)) return 0; + const unsigned from = fill_from(t); + const std::uint64_t span = fill_bytes(t); + if (from && t.unbound_bytes && title_partial_bytes_ + t.unbound_bytes > partial_mips_budget()) { + ++title_stats_.partial_refused; + t.stale = false; // the sweep and its views ask again + return 0; + } title_tiled_.resize(std::size_t(span)); if (!copy_guarded(title_tiled_.data(), reinterpret_cast(t.cpu), std::size_t(span), title_memory_write_combined(t.cpu))) { @@ -16840,14 +17368,14 @@ class Device final bool ok = true; if (t.resource->staged_title()) { const auto start = std::chrono::steady_clock::now(); - ok = t.resource->upload_staged_title(layout, title_tiled_.data(), title_columns_, trace_pool, nonzero); + ok = t.resource->upload_staged_title(layout, title_tiled_.data(), title_columns_, trace_pool, nonzero, from); title_stats_.staged_ns += std::chrono::duration_cast( std::chrono::steady_clock::now() - start).count(); if (ok) ++title_stats_.staged_fills; if (!ok) log_once("staged title texture upload failed, format", int(t.resource->format())); } else { for (std::uint32_t slice = 0; slice < slices && ok; ++slice) { - for (std::uint32_t level = 0; level < mips && ok; ++level) { + for (std::uint32_t level = from; level < mips && ok; ++level) { const auto& mip = layout.layout.plane[0].mips[level]; const std::uint32_t row_pitch = mip.width_elements * layout.format.bytes; const std::uint32_t slice_pitch = row_pitch * mip.height_elements; @@ -16875,7 +17403,7 @@ class Device final std::fprintf(stderr, "[rt] ds-pool-fill cpu=%llx size=%llu staged=%d nonzero=%d\n", static_cast(t.cpu), static_cast(span), int(staged), int(nonzero)); - if (t.owned && !t.fills) t.resource->publish_streamed_texture(); + note_filled_from(t, from); t.hash = hash; t.hashed = true; t.stale = false; @@ -16970,6 +17498,24 @@ class Device final static_cast(s.registered), mapped, filled, static_cast(s.fills), double(s.fill_bytes) / 1048576.0, static_cast(s.fill_failures)); + if (s.partial_fills || s.partial_refused) { + std::size_t now = 0; + VkDeviceSize held = 0, used = 0; + for (const auto& [address, t] : state_.title_textures) + if (t->fills && t->filled_from) { + ++now; + held += t->backing_bytes; + used += rt::xg_xs::mip_chain_bytes(t->layout, t->filled_from); + } + std::fprintf(stderr, "[rt] d3d12: title textures filled in part: %zu now (%.1f MiB of image memory, %.1f MiB " + "filled), %llu in all, %llu partial fills, %llu got larger mips later, %llu refused by " + "LEONIDA_TITLE_PARTIAL_MIPS_MB\n", + now, double(held) / 1048576.0, double(used) / 1048576.0, + static_cast(s.partial_textures), + static_cast(s.partial_fills), + static_cast(s.partial_upgrades), + static_cast(s.partial_refused)); + } const auto host = state_.context->host_texture_stats(); std::fprintf(stderr, "[rt] d3d12: ordered title host copies %llu, GPU waits %llu; " "slot-70 views awaiting readable memory: %llu\n", @@ -21425,6 +21971,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; @@ -22348,13 +22907,17 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin vkGetPhysicalDeviceFeatures2(info.physical, &query); } const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME; - info.host_image_copy = has_host_image_copy && host_copy.hostImageCopy; + // LEONIDA_HOST_IMAGE_COPY (src/host_image_copy_policy.h). Off, the extension is neither enabled nor chained, so no + // image gets host-transfer usage and every CPU texture copy takes the staging submit, as on a device without it. + const leonida::HostImageCopyChoice host_copy_choice = leonida::host_image_copy_choice( + std::getenv("LEONIDA_HOST_IMAGE_COPY"), has_host_image_copy && host_copy.hostImageCopy, chosen.vendorID); + info.host_image_copy = host_copy_choice.use; if (info.host_image_copy) { host_copy.pNext = *v13.next(); // after the conditional rendering features, if any *v13.next() = &host_copy; - } else { - std::fprintf(stderr, "[rt] d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n"); } + std::fprintf(stderr, "[rt] d3d12: host image copy: %s (%s)%s\n", info.host_image_copy ? "on" : "off", + host_copy_choice.reason, info.host_image_copy ? "" : "; CPU texture copies use a staging submit"); const auto has_device_extension = [&](const char* name) { return std::any_of(extensions.begin(), extensions.end(), diff --git a/runtime/shims/xg_xs_layout.h b/runtime/shims/xg_xs_layout.h index 939c9e892d..b2b58576cd 100644 --- a/runtime/shims/xg_xs_layout.h +++ b/runtime/shims/xg_xs_layout.h @@ -281,6 +281,22 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) { return true; } +// The bytes from the texture's base that hold the mips from `first` on (the whole texture for 0). Only a 2D texture of +// one slice stores its chain from the smallest mips to the largest, so only there is a part of it a prefix. +inline uint64_t mip_chain_bytes(const Texture& t, unsigned first) { + const auto& plane = t.layout.plane[0]; + if (!first || first >= t.layout.mips || t.layout.dimension != kTexture2D || t.array != 1) return t.layout.size; + if (first >= plane.standard_mips) return t.layout.alignment; // the tail is one block + return plane.mips[first].offset + plane.mips[first].size; +} + +// The first mip that is held, with every smaller one, by the `bytes` readable bytes from the texture's base; the mip +// count when not even the smallest is. +inline unsigned first_mip_within(const Texture& t, uint64_t bytes) { + for (unsigned m = 0; m < t.layout.mips; ++m) + if (mip_chain_bytes(t, m) <= bytes) return m; + return t.layout.mips; +} // These RB+ equation rows come directly from AMD addrlib. The other two // non-XOR modes already have equations in Leonida's GFX10 detiler. diff --git a/runtime/src/buffer_va_index.h b/runtime/src/buffer_va_index.h index 3ab8edf82c..2f7c1abb1a 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 d7d7396408..8b79c987e9 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 0000000000..61c73565db --- /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/host_image_copy_policy.h b/runtime/src/host_image_copy_policy.h new file mode 100644 index 0000000000..a67be2a885 --- /dev/null +++ b/runtime/src/host_image_copy_policy.h @@ -0,0 +1,33 @@ +// LEONIDA_HOST_IMAGE_COPY: whether the Vulkan D3D12 layer (shims/d3d12_vulkan_device.cpp) enables +// VK_EXT_host_image_copy for WriteToSubresource/ReadFromSubresource. Pure stdlib, so the choice is tested without a +// GPU (test/host_image_copy_policy_test.cpp). +// +// 0 never: the extension is not enabled and every CPU texture copy takes the staging submit. +// 1 whenever the device has the extension and its hostImageCopy feature. +// auto (unset, empty or any other text) as 1, except on NVIDIA, where it is off: a real boot on an RTX 4070 SUPER +// lost the device (WRITE_INVALID) in 7 of 7 runs with host image copies and in 0 of 2 without them. The +// cause is not known yet (docs/d3d12_vulkan.md). +#pragma once + +#include +#include + +namespace leonida { + +constexpr std::uint32_t kNvidiaVendorId = 0x10DE; // VkPhysicalDeviceProperties::vendorID + +struct HostImageCopyChoice { + bool use; + const char* reason; // static text for the device-creation log line +}; + +// `setting` is the variable's text (null when unset); `available` is the extension with its hostImageCopy feature. +inline HostImageCopyChoice host_image_copy_choice(const char* setting, bool available, std::uint32_t vendor_id) { + if (setting && std::strcmp(setting, "0") == 0) return {false, "LEONIDA_HOST_IMAGE_COPY=0"}; + if (!available) return {false, "not available"}; + if (setting && std::strcmp(setting, "1") == 0) return {true, "LEONIDA_HOST_IMAGE_COPY=1"}; + if (vendor_id == kNvidiaVendorId) return {false, "auto: NVIDIA"}; + return {true, "available"}; +} + +} // namespace leonida diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h index ff9f004e07..d2c512cecc 100644 --- a/runtime/src/title_texture_memory.h +++ b/runtime/src/title_texture_memory.h @@ -55,32 +55,38 @@ class TextureReadability { using TexturePageCommitter = bool (*)(const void*, std::size_t); -// Check the whole footprint. A committed first page says nothing about a streamed mip farther on. -inline bool texture_memory_readable(std::uintptr_t base, std::uint64_t size, TexturePageCommitter commit = nullptr) { - if (!base || !size || size > (std::numeric_limits::max)() - base) return false; +// How many of the bytes from `base` are readable, up to the first page that is not (at most `size`). +inline std::uint64_t texture_memory_readable_bytes(std::uintptr_t base, std::uint64_t size, + TexturePageCommitter commit = nullptr) { + if (!base || !size || size > (std::numeric_limits::max)() - base) return 0; const auto end = base + size; for (auto at = base; at < end;) { MEMORY_BASIC_INFORMATION region{}; const auto* address = reinterpret_cast(at); - if (!VirtualQuery(address, ®ion, sizeof(region))) return false; + if (!VirtualQuery(address, ®ion, sizeof(region))) return at - base; // A persistent Map can name an xmem section whose physical pages commit on first touch. // Only xmem may commit them. A bare reservation or an inaccessible page must still defer. if (commit && region.State == MEM_RESERVE && region.Type == MEM_MAPPED) { - if (!commit(address, end - at) || !VirtualQuery(address, ®ion, sizeof(region))) return false; + if (!commit(address, end - at) || !VirtualQuery(address, ®ion, sizeof(region))) return at - base; } - if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return false; + if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return at - base; switch (region.Protect & 0xff) { case PAGE_READONLY: case PAGE_READWRITE: case PAGE_WRITECOPY: case PAGE_EXECUTE_READ: case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: break; - default: return false; + default: return at - base; } const auto start = reinterpret_cast(region.BaseAddress); - if (at < start || at - start >= region.RegionSize) return false; + if (at < start || at - start >= region.RegionSize) return at - base; const auto available = region.RegionSize - (at - start); - if (available >= end - at) return true; + if (available >= end - at) return size; at += available; } - return true; + return size; +} + +// Check the whole footprint. A committed first page says nothing about a streamed mip farther on. +inline bool texture_memory_readable(std::uintptr_t base, std::uint64_t size, TexturePageCommitter commit = nullptr) { + return size && texture_memory_readable_bytes(base, size, commit) == size; } } // namespace leonida diff --git a/runtime/src/title_texture_refresh.h b/runtime/src/title_texture_refresh.h index feb8a0cc27..b39defdcda 100644 --- a/runtime/src/title_texture_refresh.h +++ b/runtime/src/title_texture_refresh.h @@ -54,7 +54,12 @@ class TitleTextureRangeIndex { // Sorted, disjoint half-open intervals let each texture find its first possible writer by end address. inline void merge_title_writes(TitleWriteRanges& writes) { - std::sort(writes.begin(), writes.end()); + if (writes.empty()) return; + if (writes.size() == 1) { + if (writes[0].first >= writes[0].second) writes.clear(); + return; + } + if (!std::is_sorted(writes.begin(), writes.end())) std::sort(writes.begin(), writes.end()); std::size_t count = 0; for (const auto [begin, end] : writes) { if (begin >= end) continue; @@ -67,9 +72,12 @@ inline void merge_title_writes(TitleWriteRanges& writes) { } inline bool title_write_overlaps(const TitleWriteRanges& writes, std::uintptr_t begin, std::uintptr_t end) { + if (begin >= end || writes.empty()) return false; + if (end <= writes.front().first || begin >= writes.back().second) return false; + if (writes.size() == 1) return true; const auto it = std::upper_bound(writes.begin(), writes.end(), begin, [](auto address, const auto& range) { return address < range.second; }); - return begin < end && it != writes.end() && it->first < end; + return it != writes.end() && it->first < end; } // The registry's entries as one pass will visit them, in placement order. A pass cannot walk the registry itself: a @@ -100,7 +108,7 @@ void poll_title_textures(const std::vector& entries, std::uint64_t& curso if (index == entries.size()) index = 0; // the cursor is past the last address: resume at the first for (auto left = entries.size(); left; --left) { const auto& [address, texture] = entries[index]; - cursor = address + 1; + cursor = address == UINT64_MAX ? 0u : address + 1u; if (!texture->mapped && !texture->stale) visit(*texture); if (exhausted()) break; // advance at least one registry entry even if a deadline already passed index = index + 1 == entries.size() ? 0 : index + 1; diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index c49880d923..8ed315ecf1 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 cd17bc5961..46bcc97c41 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/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 18bcc07baa..858ba46bec 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -2908,6 +2908,31 @@ class VulkanQueue : private QueueHolds::Holder { return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS; } + // Waits on the CPU until what this queue has submitted so far is done: its own timeline, without the device's + // submit lock, so other queues keep submitting, and without waiting for anything submitted after (review D9; + // idle() waits for the whole VkQueue, which D3D12 queues may share, and blocks every submission meanwhile). + bool wait_submitted() { + std::uint64_t value = 0; + { + std::lock_guard state(state_mutex_); + value = submitted_; + } + if (!value) return true; + VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; + wait.semaphoreCount = 1; + wait.pSemaphores = &progress_; + wait.pValues = &value; + constexpr std::uint64_t slice_ns = 100'000'000; // 100 ms + for (;;) { // bounded slices: a lost device wakes the wait + if (context_.is_device_lost()) return false; + const VkResult res = context_.vk.vkWaitSemaphores(context_.device(), &wait, slice_ns); + if (res == VK_SUCCESS) return true; + if (res == VK_TIMEOUT) continue; + if (res == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); + return false; + } + } + private: // Completed stages, reused by later ARRAY_OF_POINTERS builds. Only execute_now() touches the pool, and it holds // state_mutex_ (including the deferred/held release paths), so no extra lock is needed. @@ -4418,8 +4443,7 @@ class VulkanQueue : private QueueHolds::Holder { semaphores = sparse_waits; values = sparse_values; } - const std::vector stages(semaphores.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - VkResult res = VK_SUCCESS; + const std::vector stages(semaphores.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); VkResult res = VK_SUCCESS; { std::lock_guard lock(context_.submit_mutex()); VkSemaphore signals[2]{progress_, VK_NULL_HANDLE}; diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 69c3a6607a..1d940a7e48 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1398,7 +1398,7 @@ int check_placed_target_backing(ID3D12Device* device) { // Two sampled BC placements have distinct T#s. A CPU write to the first and a GPU copy into // the second must each promote only their destination and keep previously copied descriptors usable. -int check_shared_bc_placements(ID3D12Device* device) { +int check_shared_bc_placements(ID3D12Device* device, bool must_share = false) { const char* who = "shared slot-133 BC images"; if (!rt::d3d12::bindless_set_layout(device)) return 0; constexpr UINT width = 32, height = 32, pitch = width / 4 * 8; @@ -1421,6 +1421,8 @@ int check_shared_bc_placements(ID3D12Device* device) { const auto second = rt::d3d12::bindless_hash_lookup(device, bv); EXPECT(first && second && first != second); const bool shared = !rt::d3d12::vulkan_memory_flags(a.p); + const char* defer = std::getenv("LEONIDA_PLACED_IMAGE_DEFER"); + EXPECT(shared || !must_share || (defer && !std::strcmp(defer, "0"))); EXPECT(bool(rt::d3d12::vulkan_memory_flags(b.p)) == !shared); std::array pattern{}, result{}; for (std::size_t i = 0; i < pattern.size(); ++i) pattern[i] = std::uint8_t(i * 13 + 71); @@ -2264,6 +2266,54 @@ int check_written_pages_all(ID3D12Device* device) { return failures; } +// A mapped plane above 256 KiB is hashed by samples every pass and every byte each sixth one. A byte the samples do +// not cover must still reach the GPU, from ordinary pages and from write-combined ones (the title's graphics +// memory), whose every-byte hash reads through a streaming copy. +int check_mapped_plane_byte(ID3D12Device* device, DWORD modifier) { + const char* who = modifier ? "persistent write-combined plane, one byte" : "persistent plane, one byte"; + constexpr UINT width = 1024, height = 512, size = width * height; + auto* pages = static_cast( + VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | modifier)); + EXPECT(pages); + GpuReader gpu; + EXPECT(!gpu.init(device, size)); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.SampleDesc.Count = desc.DepthOrArraySize = desc.MipLevels = 1; + leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), height, 1, 1, width}, 1); + Ref texture; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK); + void* mapped = nullptr; + EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == pages); + std::memset(pages, 0x40, size); + ID3D12CommandList* lists[]{gpu.list.p}; + std::vector pixels(size); + std::ptrdiff_t changed = 0; + for (unsigned pass = 0; pass < 14 && changed != 1; ++pass) { + // 1,000 bytes into a page: the sampled hash reads the first 64 bytes of a page and 64 from its middle. + if (pass == 1) pages[5 * 4096 + 1000] = 0x41; + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, pass + 1), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(pass + 1, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + EXPECT_HR(texture->ReadFromSubresource(pixels.data(), width, size, 0, nullptr), S_OK); + changed = std::count(pixels.begin(), pixels.end(), std::uint8_t(0x41)); + EXPECT(std::count(pixels.begin(), pixels.end(), std::uint8_t(0x40)) == std::ptrdiff_t(size) - changed); + if (!pass) EXPECT(!changed); + } + EXPECT(changed == 1); + texture->Unmap(0, nullptr); + texture.p->Release(); + texture.p = nullptr; + VirtualFree(pages, 0, MEM_RELEASE); + std::printf("%s: seen on the GPU\n", who); + return 0; +} + // Replace mapped bytes twice, including compressed edge blocks, mip tails and array slices. int check_mapped_bc_array(ID3D12Device* device) { const char* who = "persistent BC1 array"; @@ -2391,6 +2441,8 @@ int main(int argc, char** argv) { failures += check_placed_view_map_changes(ours.p); failures += check_shared_bc_placements(ours.p); failures += check_mapped_plane(ours.p); + for (const DWORD modifier : {DWORD(0), DWORD(PAGE_WRITECOMBINE)}) + failures += check_mapped_plane_byte(ours.p, modifier); failures += check_mapped_bc_array(ours.p); } { @@ -2400,6 +2452,7 @@ int main(int argc, char** argv) { Ref staged; if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; failures += check_placed_view_map_changes(staged.p); + failures += check_shared_bc_placements(staged.p, true); failures += check_mapped_plane(staged.p); failures += check_mapped_bc_array(staged.p); } diff --git a/runtime/test/d3d12_staged_copy_wait_test.cpp b/runtime/test/d3d12_staged_copy_wait_test.cpp new file mode 100644 index 0000000000..a4c54b32ad --- /dev/null +++ b/runtime/test/d3d12_staged_copy_wait_test.cpp @@ -0,0 +1,167 @@ +// Review D9: WriteToSubresource / ReadFromSubresource on a texture the host cannot copy (no +// VK_EXT_host_image_copy, or not in GENERAL) replay a CopyTextureRegion on a staging queue and wait for it. That wait +// was vkQueueWaitIdle on the device's first VkQueue, which the first D3D12 direct queue also uses, held under the +// device's submit lock: every such CPU copy waited for all the game work queued on that queue, and no queue could +// submit meanwhile. The staging copy now waits only for its own submission, on a VkQueue the game's first queues +// are not on: the copy family's for a colour texture (a second graphics VkQueue did not help on NVIDIA, which runs +// it behind the busy one: 32 ms either way). +// +// The standalone device queues about 30 ms of buffer copies on a direct queue, then writes and reads back a 64x64 +// colour texture in COPY_DEST (so through the staging copy). Where there is a copy family, the write must not take +// as long as the queued work (it did: 31.8 ms of 32.1); the bytes must round-trip either way. Prints both times. +// Skips (77) without a Vulkan GPU. No shaders or game data. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +double ms_since(std::chrono::steady_clock::time_point start) { + return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); +} + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + if (device_status != vktest::DeviceStatus::ready) return 1; + std::uint32_t family_count = 0; + const auto families_of = d.instance_fn( + "vkGetPhysicalDeviceQueueFamilyProperties"); + families_of(d.physical, &family_count, nullptr); + std::vector families(family_count); + families_of(d.physical, &family_count, families.data()); + // A family the standalone device makes D3D12 COPY queues in: transfer without graphics, copying whole texels. + bool copy_family = false; + for (const auto& f : families) + copy_family |= (f.queueFlags & VK_QUEUE_TRANSFER_BIT) && !(f.queueFlags & VK_QUEUE_GRAPHICS_BIT) && + f.minImageTransferGranularity.width == 1 && f.minImageTransferGranularity.height == 1 && + f.minImageTransferGranularity.depth == 1; + + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p)))); + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + Ref allocator; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + Ref list; + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + Ref fence; + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + const D3D12_HEAP_PROPERTIES gpu{D3D12_HEAP_TYPE_DEFAULT}; + constexpr UINT64 kBufferBytes = 96ull << 20; // two fit the GPU address arena (256 MiB) + D3D12_RESOURCE_DESC buffer_desc{}; + buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer_desc.Width = kBufferBytes; + buffer_desc.Height = 1; + buffer_desc.DepthOrArraySize = 1; + buffer_desc.MipLevels = 1; + buffer_desc.SampleDesc.Count = 1; + buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref a, b; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&gpu, D3D12_HEAP_FLAG_NONE, &buffer_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&a.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&gpu, D3D12_HEAP_FLAG_NONE, &buffer_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&b.p)))); + D3D12_RESOURCE_DESC texture_desc{}; + texture_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture_desc.Width = 64; + texture_desc.Height = 64; + texture_desc.DepthOrArraySize = 1; + texture_desc.MipLevels = 1; + texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture_desc.SampleDesc.Count = 1; + Ref texture; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&gpu, D3D12_HEAP_FLAG_NONE, &texture_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&texture.p)))); + std::vector texels(64 * 64 * 4), back(texels.size()); + for (std::size_t i = 0; i < texels.size(); ++i) texels[i] = std::uint8_t(i * 31 + 7); + // The first copy makes the staging queue; not timed. + EXPECT(SUCCEEDED(texture->WriteToSubresource(0, nullptr, texels.data(), 256, 0))); + // A first submission on the direct queue zero-fills the new buffers, which every other queue's next submission + // waits for (as it should): done before the timed part. + list->CopyBufferRegion(b.p, 0, a.p, 0, 256); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + EXPECT(SUCCEEDED(texture->WriteToSubresource(0, nullptr, texels.data(), 256, 0))); // after that wait, untimed + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + + // Work for the direct queue: 64 copies of 96 MiB, back and forth, each buffer moved between COPY_SOURCE and + // COPY_DEST in between as D3D12 asks. + const auto transition = [](ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = resource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = before; + barrier.Transition.StateAfter = after; + return barrier; + }; + constexpr auto kSource = D3D12_RESOURCE_STATE_COPY_SOURCE, kDest = D3D12_RESOURCE_STATE_COPY_DEST; + const D3D12_RESOURCE_BARRIER start_states[] = {transition(a.p, D3D12_RESOURCE_STATE_COMMON, kSource), + transition(b.p, D3D12_RESOURCE_STATE_COMMON, kDest)}; + list->ResourceBarrier(2, start_states); + for (int i = 0; i < 64; ++i) { + ID3D12Resource* from = i % 2 ? b.p : a.p; + ID3D12Resource* to = i % 2 ? a.p : b.p; + list->CopyBufferRegion(to, 0, from, 0, kBufferBytes); + const D3D12_RESOURCE_BARRIER swap[] = {transition(from, kSource, kDest), transition(to, kDest, kSource)}; + list->ResourceBarrier(2, swap); + } + EXPECT(SUCCEEDED(list->Close())); + const auto start = std::chrono::steady_clock::now(); + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 2))); + + for (std::size_t i = 0; i < texels.size(); ++i) texels[i] = std::uint8_t(i * 13 + 5); + const auto write_start = std::chrono::steady_clock::now(); + EXPECT(SUCCEEDED(texture->WriteToSubresource(0, nullptr, texels.data(), 256, 0))); + const double write_ms = ms_since(write_start); + const bool busy_after_write = fence->GetCompletedValue() < 2; + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(2, nullptr))); + const double work_ms = ms_since(start); + EXPECT(SUCCEEDED(texture->ReadFromSubresource(back.data(), 256, 0, 0, nullptr))); + EXPECT(std::memcmp(back.data(), texels.data(), texels.size()) == 0); + + std::printf("staged 64x64 WriteToSubresource with the direct queue busy: %.2f ms; the queued copies: %.2f ms; " + "direct queue still busy after the write: %s; copy family: %s\n", + write_ms, work_ms, busy_after_write ? "yes" : "no", copy_family ? "yes" : "no"); + if (copy_family && work_ms >= 10.0) { + EXPECT(busy_after_write); + EXPECT(write_ms < work_ms / 2); + } else { + std::printf("no copy family, or too little queued work to tell: the times are not compared\n"); + } + std::printf("d3d12_staged_copy_wait_test: OK\n"); + return 0; +} diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 51d529abab..b968b4edeb 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/d3d12_unmapped_vsharp_test.cpp b/runtime/test/d3d12_unmapped_vsharp_test.cpp index 1cb0b7c232..01347710e2 100644 --- a/runtime/test/d3d12_unmapped_vsharp_test.cpp +++ b/runtime/test/d3d12_unmapped_vsharp_test.cpp @@ -264,7 +264,15 @@ int check_console_heap(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fe leonida::title_va_aliases().add(unmapped, kViewBytes, b.arena_va); EXPECT(submit()); EXPECT(count_restored(restored) && restored == 128); - std::printf("128 waiting zero descriptors, all restored at the first submission after their alias came\n"); + // A slot written now with the words the first refresh had no copy for: the refresh that copies the write asks + // for them again rather than reuse that answer (fix_vsharp's answers last one pass over the heap). + put(140, raw_vsharp(unmapped)); + EXPECT(submit()); + std::uint32_t rewritten[8]; + EXPECT(rt::d3d12::read_arena(device, shader_va + 140 * kDescriptor, rewritten, sizeof(rewritten))); + EXPECT(base_of(rewritten) == b.arena_va && rewritten[2]); + std::printf("128 waiting zero descriptors, all restored at the first submission after their alias came, a " + "rewritten one at once\n"); // The alias goes: at the next submission none of them names its copy any more. leonida::title_va_aliases().remove(unmapped, b.arena_va); EXPECT(submit()); diff --git a/runtime/test/host_image_copy_policy_test.cpp b/runtime/test/host_image_copy_policy_test.cpp new file mode 100644 index 0000000000..eaf288ba31 --- /dev/null +++ b/runtime/test/host_image_copy_policy_test.cpp @@ -0,0 +1,62 @@ +// Unit tests for LEONIDA_HOST_IMAGE_COPY (runtime/src/host_image_copy_policy.h). No Vulkan instance and no GPU: the +// choice is a pure function of the variable's text, the extension's availability and the vendor. +#include "host_image_copy_policy.h" + +#include +#include +#include +#include + +namespace { + +int failures = 0; + +void expect(const char* setting, bool available, std::uint32_t vendor, bool use, const char* reason) { + const leonida::HostImageCopyChoice got = leonida::host_image_copy_choice(setting, available, vendor); + if (got.use == use && got.reason && std::strcmp(got.reason, reason) == 0) return; + std::fprintf(stderr, "FAIL setting=%s available=%d vendor=0x%04X: got %s (%s), want %s (%s)\n", + setting ? setting : "(unset)", available ? 1 : 0, static_cast(vendor), + got.use ? "on" : "off", got.reason ? got.reason : "(null)", use ? "on" : "off", reason); + ++failures; +} + +} // namespace + +int main() { + constexpr std::uint32_t nvidia = 0x10DE, amd = 0x1002, intel = 0x8086; + static_assert(leonida::kNvidiaVendorId == nvidia, "NVIDIA's PCI vendor id"); + + // auto (unset, empty, the word itself): on where available, except on NVIDIA. + for (const char* automatic : {static_cast(nullptr), "", "auto"}) { + expect(automatic, true, amd, true, "available"); + expect(automatic, true, intel, true, "available"); + expect(automatic, true, nvidia, false, "auto: NVIDIA"); + expect(automatic, false, amd, false, "not available"); + expect(automatic, false, nvidia, false, "not available"); + } + + // 0: never, whatever the device has. + expect("0", true, amd, false, "LEONIDA_HOST_IMAGE_COPY=0"); + expect("0", true, nvidia, false, "LEONIDA_HOST_IMAGE_COPY=0"); + expect("0", false, amd, false, "LEONIDA_HOST_IMAGE_COPY=0"); + + // 1: whenever available, NVIDIA included; it cannot turn on what the device does not have. + expect("1", true, nvidia, true, "LEONIDA_HOST_IMAGE_COPY=1"); + expect("1", true, amd, true, "LEONIDA_HOST_IMAGE_COPY=1"); + expect("1", false, nvidia, false, "not available"); + expect("1", false, amd, false, "not available"); + + // Anything else is auto: only the exact texts 0 and 1 are switches. + for (const char* garbage : {"yes", "on", "off", "true", "01", "10", " 1", "1 ", "2", "-1", "AUTO", "nvidia"}) { + expect(garbage, true, amd, true, "available"); + expect(garbage, true, nvidia, false, "auto: NVIDIA"); + expect(garbage, false, amd, false, "not available"); + } + + if (failures) { + std::fprintf(stderr, "%d failure(s)\n", failures); + return 1; + } + std::printf("host_image_copy_policy: all cases passed\n"); + return 0; +} diff --git a/runtime/test/title_texture_refresh_test.cpp b/runtime/test/title_texture_refresh_test.cpp new file mode 100644 index 0000000000..9333b3b3cd --- /dev/null +++ b/runtime/test/title_texture_refresh_test.cpp @@ -0,0 +1,128 @@ +// Portable CPU-only unit tests for runtime/src/title_texture_refresh.h (pure C++20 stdlib, no GPU, no game files). +// Covers merge_title_writes (empty, degenerate, sorted, unsorted, adjacent, nested), title_write_overlaps (O(1) +// envelope / single-range fast path and multi-range binary search), title_texture_snapshot, and poll_title_textures +// (resume cursor, mapped/stale skip, budget exhaustion, and explicit UINT64_MAX wrap). +#include "../src/title_texture_refresh.h" + +#include +#include +#include +#include +#include + +#define CHECK(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "line %d: CHECK failed: %s\n", __LINE__, #cond); \ + return 1; \ + } \ +} while (0) + +namespace { + +struct FakeTexture { + std::uint64_t id = 0; + bool mapped = false; + bool stale = false; +}; + +} // namespace + +int main() { + using namespace leonida; + + // 1. merge_title_writes: empty, single valid/degenerate, sorted, unsorted, adjacent, nested. + { + TitleWriteRanges empty; + merge_title_writes(empty); + CHECK(empty.empty()); + + TitleWriteRanges single_bad{{0x2000, 0x2000}}; + merge_title_writes(single_bad); + CHECK(single_bad.empty()); + + TitleWriteRanges single_inv{{0x3000, 0x1000}}; + merge_title_writes(single_inv); + CHECK(single_inv.empty()); + + TitleWriteRanges single_ok{{0x1000, 0x2000}}; + merge_title_writes(single_ok); + CHECK(single_ok.size() == 1 && single_ok[0] == std::make_pair(std::uintptr_t{0x1000}, std::uintptr_t{0x2000})); + + // Already-sorted input with adjacent & nested ranges. + TitleWriteRanges sorted{{0x1000, 0x2000}, {0x2000, 0x3000}, {0x2500, 0x2800}, {0x5000, 0x5000}, {0x6000, 0x7000}}; + merge_title_writes(sorted); + CHECK(sorted.size() == 2); + CHECK(sorted[0] == std::make_pair(std::uintptr_t{0x1000}, std::uintptr_t{0x3000})); + CHECK(sorted[1] == std::make_pair(std::uintptr_t{0x6000}, std::uintptr_t{0x7000})); + + // Unsorted overlapping input. + TitleWriteRanges unsorted{{0x8000, 0x9000}, {0x1000, 0x4000}, {0x2000, 0x3000}, {0x3500, 0x5000}, {0x9000, 0x8000}}; + merge_title_writes(unsorted); + CHECK(unsorted.size() == 2); + CHECK(unsorted[0] == std::make_pair(std::uintptr_t{0x1000}, std::uintptr_t{0x5000})); + CHECK(unsorted[1] == std::make_pair(std::uintptr_t{0x8000}, std::uintptr_t{0x9000})); + } + + // 2. title_write_overlaps: empty, degenerate query, single-range fast path, envelope reject, multi-range boundaries. + { + const TitleWriteRanges empty; + CHECK(!title_write_overlaps(empty, 0x1000, 0x2000)); + + const TitleWriteRanges one{{0x4000, 0x6000}}; + CHECK(!title_write_overlaps(one, 0x4000, 0x4000)); // empty query + CHECK(!title_write_overlaps(one, 0x5000, 0x4000)); // inverted query + CHECK(!title_write_overlaps(one, 0x1000, 0x4000)); // half-open touching left + CHECK(!title_write_overlaps(one, 0x6000, 0x7000)); // half-open touching right + CHECK(title_write_overlaps(one, 0x3fff, 0x4001)); // overlaps left edge + CHECK(title_write_overlaps(one, 0x5fff, 0x6001)); // overlaps right edge + CHECK(title_write_overlaps(one, 0x4500, 0x5500)); // inside + CHECK(title_write_overlaps(one, 0x1000, 0x9000)); // encloses + + const TitleWriteRanges multi{{0x1000, 0x2000}, {0x4000, 0x5000}, {0x8000, 0x9000}}; + CHECK(!title_write_overlaps(multi, 0x0, 0x1000)); + CHECK(!title_write_overlaps(multi, 0x9000, 0x10000)); + CHECK(!title_write_overlaps(multi, 0x2000, 0x4000)); + CHECK(!title_write_overlaps(multi, 0x5000, 0x8000)); + CHECK(title_write_overlaps(multi, 0x2000, 0x4001)); + CHECK(title_write_overlaps(multi, 0x4fff, 0x8000)); + CHECK(title_write_overlaps(multi, 0x2500, 0x8500)); + } + + // 3. title_texture_snapshot & poll_title_textures: cursor wrap, mapped/stale skips, budget exhaustion, UINT64_MAX. + { + std::map> reg; + reg[0x1000] = std::make_shared(FakeTexture{1, false, false}); + reg[0x2000] = std::make_shared(FakeTexture{2, true, false}); // mapped -> skipped + reg[0x3000] = std::make_shared(FakeTexture{3, false, true}); // stale -> skipped + reg[0x4000] = std::make_shared(FakeTexture{4, false, false}); + reg[UINT64_MAX] = std::make_shared(FakeTexture{5, false, false}); + + const auto snap = title_texture_snapshot(reg); + CHECK(snap.size() == 5); + + std::uint64_t cursor = 0; + std::vector visited; + // Budget stops after visiting 1st entry (advances at least one entry even when exhausted immediately). + poll_title_textures(snap, cursor, [&](FakeTexture& t) { visited.push_back(t.id); }, [] { return true; }); + CHECK(visited.size() == 1 && visited[0] == 1 && cursor == 0x1001); + + // Next pass starts at 0x2000 (skips mapped, skips stale, visits 4 and 5, wraps cursor at UINT64_MAX -> 0). + visited.clear(); + poll_title_textures(snap, cursor, [&](FakeTexture& t) { visited.push_back(t.id); }, [] { return false; }); + // Visits 0x4000, UINT64_MAX, then wraps inside the loop to 0x1000 (leaving cursor at 0x1001). + CHECK(visited.size() == 3 && visited[0] == 4 && visited[1] == 5 && visited[2] == 1 && cursor == 0x1001); + + // Stopping right on UINT64_MAX sets cursor explicitly to 0 so the next pass starts at 0x1000. + cursor = UINT64_MAX; + visited.clear(); + poll_title_textures(snap, cursor, [&](FakeTexture& t) { visited.push_back(t.id); }, [] { return true; }); + CHECK(visited.size() == 1 && visited[0] == 5 && cursor == 0u); + + visited.clear(); + poll_title_textures(snap, cursor, [&](FakeTexture& t) { visited.push_back(t.id); }, [] { return true; }); + CHECK(visited.size() == 1 && visited[0] == 1 && cursor == 0x1001); + } + + std::printf("title_texture_refresh_test: all checks passed\n"); + return 0; +} diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp index 6eadb4beaf..7cc51cf920 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 93cf2bed46..52a9ea12db 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 987ee6e35f..1cef1757f6 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; diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp index c6df1bc243..228c198ec6 100644 --- a/runtime/test/xg_xs_test.cpp +++ b/runtime/test/xg_xs_test.cpp @@ -81,6 +81,51 @@ void check_addresses(const Texture& t) { check(true, "every mip/array element has a distinct aligned address inside the resource"); } +// A fill of the smaller mips only (d3d12_vulkan_device.cpp, partial_mips) reads mip_chain_bytes(t, first) bytes from the +// base: those hold every element of the mips from `first` on, and the next larger mip is not among them. +void check_mip_prefix(uint32_t format, uint32_t layout, uint64_t width, uint32_t height, uint16_t mips) { + ResourceDesc d{}; + d.dimension = kTexture2D; + d.width = width; + d.height = height; + d.depth_or_array = 1; + d.mips = mips; + d.format = format; + d.samples = 1; + d.layout = layout; + Texture t; + check(build_texture(d, t), "mip prefix case lays out"); + const auto& plane = t.layout.plane[0]; + std::vector whole(size_t(t.layout.size)); + for (size_t i = 0; i < whole.size(); ++i) whole[i] = uint8_t(i * 31 + (i >> 8) * 7); + std::vector columns; + bool same = true, ordered = true, found = true; + for (unsigned first = 0; first < t.layout.mips; ++first) { + const uint64_t bytes = mip_chain_bytes(t, first); + // Exactly the prefix, so that a read past it is a heap error under a checked allocator and a difference here. + std::vector part(whole.size(), 0xee); + std::copy_n(whole.begin(), size_t(bytes), part.begin()); + for (unsigned level = first; level < t.layout.mips; ++level) { + const auto& mip = plane.mips[level]; + const uint32_t pitch = mip.width_elements * t.format.bytes; + std::vector a(size_t(pitch) * mip.height_elements), b(a.size()); + copy_elements(t, level, 0, whole.data(), a.data(), pitch, pitch * mip.height_elements, columns); + copy_elements(t, level, 0, part.data(), b.data(), pitch, pitch * mip.height_elements, columns); + same &= a == b; + } + const bool in_tail = first > plane.standard_mips; + found &= first_mip_within(t, bytes) == (in_tail ? plane.standard_mips : first); + found &= first_mip_within(t, bytes - 1) == (first >= plane.standard_mips ? t.layout.mips + : first + 1 < t.layout.mips ? first + 1 + : t.layout.mips); + if (first && first <= plane.standard_mips) ordered &= bytes < mip_chain_bytes(t, first - 1); + } + check(same, "the prefix of a mip holds it and every smaller one"); + check(ordered && mip_chain_bytes(t, 0) == t.layout.size, "a larger mip needs a longer prefix, mip 0 the whole texture"); + check(found, "the first mip within a readable prefix is the largest one it holds"); + check(first_mip_within(t, 0) == t.layout.mips, "nothing readable: no mip"); +} + // copy_elements (row + column addressing) reads every element where offset() says it is. void check_detile(const Texture& t) { const ElementAddress address(t); @@ -389,6 +434,19 @@ void test_models_agree() { } // namespace int main() { + check_mip_prefix(DXGI_FORMAT_BC7_UNORM, 0x109, 1024, 1024, 11); // 64 KiB blocks and a tail + check_mip_prefix(DXGI_FORMAT_BC1_UNORM, 0x105, 512, 256, 10); // 4 KiB blocks and a tail + check_mip_prefix(DXGI_FORMAT_BC7_UNORM, 0x109, 300, 700, 10); // extents that are no power of two + check_mip_prefix(DXGI_FORMAT_R8G8B8A8_UNORM, 0x10a, 256, 256, 1); // one mip + check_mip_prefix(DXGI_FORMAT_R8G8B8A8_UNORM, 0x105, 512, 512, 2); // a chain too short for a tail + check_mip_prefix(DXGI_FORMAT_R8G8B8A8_UNORM, 1, 256, 128, 9); // linear + { + ResourceDesc d{kTexture2D, 0, 256, 256, 6, 9, DXGI_FORMAT_BC7_UNORM, 1, 0, 0x109, 0}; + Texture cube; + check(build_texture(d, cube) && mip_chain_bytes(cube, 4) == cube.layout.size && + first_mip_within(cube, cube.layout.size - 1) == cube.layout.mips, + "an array is readable as a whole or not at all"); + } { struct Entry { bool mapped, stale; int id; }; Entry first{false, false, 1}, mapped{true, false, 2}, stale{false, true, 3}; @@ -594,6 +652,7 @@ int main() { DWORD previous = 0; if (!VirtualProtect(reservation, page, PAGE_READWRITE | PAGE_GUARD, &previous)) return 1; check(!leonida::texture_memory_readable(address, 2 * page), "guarded texture page remains untouched"); + check(leonida::texture_memory_readable_bytes(address, 2 * page) == 0, "the readable prefix ends at a guarded first page"); VirtualFree(reservation, page, MEM_DECOMMIT); check(!leonida::texture_memory_readable(address, page), "previously readable page is rechecked after decommit"); VirtualFree(reservation, 0, MEM_RELEASE);