From 9d41505a44adc7157b71ae4595cee8cf84cf3619 Mon Sep 17 00:00:00 2001 From: Dimitar Pavlov <360593571+azsekazvamdimitar@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:16:45 +0200 Subject: [PATCH 1/5] d3d12/vulkan: staged VRAM arena, DMA readback batching, parallel shadows, stream-pool fix On top of PR #2566 (8db8335d2), combines verified runtime performance and correctness improvements for non-ReBAR Vulkan GPUs (tested on Linux / Wine / RTX 3090 24 GB, BAR1 = 246 MiB, driver 590.48.01): - Stage 4 GiB GPU address arena + overflow TitleBufferWindows slabs in DEVICE_LOCAL VRAM with HOST_VISIBLE staging mirrors (arena_staging.h, arena_staging_test.cpp). - Fix startup glibc realloc() race by caching max_compute_shared_memory_size, sharing mutex-guarded VkPipelineLayouts, and eagerly loading pipeline_cache() during single-threaded Device construction. - Stage 9a-1: batch retired arena + external window host readbacks into a single copy_buffers_sync() submission on the dedicated DMA copy queue (wb: 27.6 ms -> 2.35 ms/frame). - Stage 9a-2: parallelize ShadowPages::refresh across 4 persistent threads via ShadowRefreshPool (shadows: 26.9 ms -> 10.2 ms/frame). - Fix resolve_pool_memory() zeroing out root descriptors probed with kRootViewBytes (64 KiB) near the end of committed stream-pool blocks (stream pool unbacked: 131,072 -> 16-33, root view unbacked: 0). AI-assisted. Verified with 151/151 portable Linux CTest passing and Windows MSVC build + retail boots on RTX 3090 (590.48.01). --- docs/d3d12_vulkan.md | 21 +- runtime/CMakeLists.txt | 7 + runtime/shims/d3d12_title_buffer_windows.h | 335 ++++++- runtime/shims/d3d12_vulkan_device.cpp | 1051 ++++++++++++++++---- runtime/src/arena_staging.h | 319 ++++++ runtime/src/vulkan_backend.h | 206 ++++ runtime/test/arena_staging_test.cpp | 286 ++++++ runtime/test/d3d12_existing_heap_test.cpp | 4 +- 8 files changed, 2004 insertions(+), 225 deletions(-) create mode 100644 runtime/src/arena_staging.h create mode 100644 runtime/test/arena_staging_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 083c91e0d2..c84d550236 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1908,9 +1908,24 @@ The runtime allocates image keys from `0x100000000` (4 GiB) in 256-byte steps, a `GPU address arena: 4080 MiB of the 4095 MiB asked for, capped by the device's Resizable BAR memory types`. Without Resizable BAR nothing changes. - M4+: allocate the arena `DEVICE_LOCAL` and stage CPU writes (descriptor heaps, shader blobs, buffer uploads) - through a host-visible staging buffer, copied before the commands that use them. The hash table is not in the - arena either: it is a normal storage buffer in `DEVICE_LOCAL` memory, uploaded from a mapped staging copy before - the commands that read it (D3D-76). + through a host-visible staging buffer, copied before the commands that use them (`runtime/src/arena_staging.h`, + `LEONIDA_DEVICE_LOCAL_ARENA=auto|1|0`). + - In `auto` mode (the default), when the arena does not fit in `DEVICE_LOCAL | HOST_VISIBLE` memory (e.g. discrete + GPUs without Resizable BAR where BAR1 is 256 MiB or less) and both a pure `DEVICE_LOCAL` VRAM type and a + `HOST_VISIBLE | HOST_COHERENT` system-RAM staging type fit, `arena.buffer` is allocated in pure `DEVICE_LOCAL` + VRAM and `arena.mapped` points at the `HOST_VISIBLE | HOST_COHERENT` staging mirror (`arena.staging_buffer`). On + GPUs with Resizable BAR or unified memory, `auto` keeps the zero-copy single buffer; `LEONIDA_DEVICE_LOCAL_ARENA=1` + forces the staged path for testing, and `LEONIDA_DEVICE_LOCAL_ARENA=0` keeps the single host-visible arena. + - CPU writes into `arena.mapped` (`ShadowPages`, console and standard shader-visible descriptor heaps, shader blobs, + `write_arena_value`, geometry leases, placed/committed buffer init and `Map`/`Unmap`) are tracked at exact byte + granularity (never rounded up to 4 KiB pages, so flushing a 256-byte shadow piece or 32-byte descriptor never + overwrites neighboring GPU writes on the same page), coalesced, and uploaded with batched `vkCmdCopyBuffer` plus + cross-queue timeline synchronization before each submission. GPU-to-CPU readbacks (`write_back_titles`, retired + shadow write-back, readable placed-buffer `Map()`, `read_arena`) subtract any unflushed dirty spans before copying + back via `VulkanContext::copy_buffer_sync()`. `arena_staging_test` (CPU) covers the policy and dirty tracker. + - The hash table is not in the + arena either: it is a normal storage buffer in `DEVICE_LOCAL` memory, uploaded from a mapped staging copy before + the commands that read it (D3D-76). - Upload-heap buffers prefer `DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT` memory when the GPU has Resizable BAR (D3D-96): the CPU writes them through the BAR and the GPU reads them from VRAM. `leonida::resizable_bar` (`runtime/src/vulkan_memory.h`) calls it Resizable BAR when such a type sits in a device-local heap larger than diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 86ac036267..724c3b8e93 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -5362,6 +5362,13 @@ if(TARGET Vulkan::Headers) add_executable(arena_size_test test/arena_size_test.cpp) target_link_libraries(arena_size_test PRIVATE Vulkan::Headers) add_test(NAME arena_size COMMAND arena_size_test) + # Staged DEVICE_LOCAL GPU address arena policy and exact byte-range dirty tracker (src/arena_staging.h). + add_executable(arena_staging_test test/arena_staging_test.cpp) + target_link_libraries(arena_staging_test PRIVATE Vulkan::Headers) + if(WIN32 AND MSVC) + target_compile_options(arena_staging_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME arena_staging COMMAND arena_staging_test) # The GPU address arena's free-block map: first fit, coalescing, and a walk a nested call re-cuts on the same # thread (src/arena_blocks.h). add_executable(arena_blocks_test test/arena_blocks_test.cpp) diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h index 9cdf52e381..5c910285c8 100644 --- a/runtime/shims/d3d12_title_buffer_windows.h +++ b/runtime/shims/d3d12_title_buffer_windows.h @@ -9,19 +9,32 @@ #include #include #include +#include #include #include +#include "../src/arena_staging.h" + namespace rt::d3d12 { // Storage for shader-addressed mirrors when the main arena has no usable offset. // Sub-ranges freed via free() are coalesced for reuse; one empty standard 4 MiB block is kept as a spare and any -// other empty block releases its Vulkan buffer and memory. +// other empty block releases its Vulkan buffer and memory. When staged mode is enabled (for BAR-restricted GPUs with +// a staged DEVICE_LOCAL arena), blocks are 64 MiB pure DEVICE_LOCAL VRAM slabs paired with a HOST_VISIBLE staging +// mirror and an exact byte-range dirty tracker, kept pooled until release(). class TitleBufferWindows { static constexpr VkDeviceSize kBlockSize = 4ull << 20; + static constexpr VkDeviceSize kStagedBlockSize = 64ull << 20; + struct StagedSlot { + leonida::ArenaStaging staging; + std::vector last_upload; + }; struct Block { VkBuffer buffer{}; VkDeviceMemory memory{}; + VkBuffer staging_buffer{}; + VkDeviceMemory staging_memory{}; + std::unique_ptr staged; VkDeviceAddress address{}; VkDeviceSize capacity{}, used{}, reserved_bytes{}; std::uint8_t* mapped{}; @@ -30,6 +43,7 @@ class TitleBufferWindows { }; std::vector blocks_; VkDeviceSize reserved_{}; + bool staged_ = false; // A new block's allocation failed at this time: none is tried again for kRetryAfter. After the story load the // driver refused every 4 MiB block (VK_ERROR_OUT_OF_HOST_MEMORY), and each V# that wanted a copy tried again, // through DeviceState::allocate's sleeping retries under the device's memory lock: one submission spent 28-35 s @@ -63,6 +77,8 @@ class TitleBufferWindows { VkDeviceSize capacity{}; std::uint8_t* mapped{}; VkBuffer buffer{}; + VkBuffer staging_buffer{}; + StagedSlot* staged{}; }; std::array published_{}; std::atomic published_count_{0}; @@ -80,7 +96,13 @@ class TitleBufferWindows { layout_generation_.fetch_add(1, std::memory_order_release); if constexpr (requires { d.title_block_gone(VkDeviceAddress{}, VkDeviceSize{}); }) d.title_block_gone(it->address, it->capacity); - d.context->vk.vkUnmapMemory(d.info.device, it->memory); + if (it->staged) { + d.context->vk.vkUnmapMemory(d.info.device, it->staging_memory); + d.context->vk.vkDestroyBuffer(d.info.device, it->staging_buffer, nullptr); + d.context->vk.vkFreeMemory(d.info.device, it->staging_memory, nullptr); + } else { + d.context->vk.vkUnmapMemory(d.info.device, it->memory); + } d.context->vk.vkDestroyBuffer(d.info.device, it->buffer, nullptr); d.context->vk.vkFreeMemory(d.info.device, it->memory, nullptr); reserved_ -= it->reserved_bytes; @@ -132,6 +154,8 @@ class TitleBufferWindows { static constexpr int kDeviceLocal = 0, kSystemCached = 1, kSystemUncached = 2; void set_system_memory(int kind) { system_memory_ = kind; } int system_memory() const { return system_memory_; } + void set_staged(bool enabled) { staged_ = enabled; } + bool staged() const { return staged_; } VkDeviceSize reserved() const { return reserved_; } // f(device address, capacity) for each live block; from any thread. template @@ -168,7 +192,9 @@ class TitleBufferWindows { template bool allocate(Device& d, VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped, - bool device_local = false, VkDeviceSize cap = UINT64_MAX, bool* at_cap = nullptr) { + bool device_local = false, VkDeviceSize cap = UINT64_MAX, bool* at_cap = nullptr, + VkBuffer* out_buffer = nullptr, VkDeviceSize* out_buffer_offset = nullptr, + VkDeviceAddress* out_address = nullptr) { if (!bytes) return false; const VkDeviceSize alignment = device_local ? 16 : 65536; auto take = [&](Block& b) { @@ -185,6 +211,9 @@ class TitleBufferWindows { ++b.live; mapped = b.mapped + start; offset = b.address - d.arena.address + start; + if (out_buffer) *out_buffer = b.buffer; + if (out_buffer_offset) *out_buffer_offset = start; + if (out_address) *out_address = b.address + start; return true; } return false; @@ -192,7 +221,7 @@ class TitleBufferWindows { if (!blocks_.empty() && take(blocks_.back())) return true; // A large view may start a new slab while smaller views still fit earlier tails or freed holes. // Use those even after the budget can no longer accommodate another slab. - if (device_local && blocks_.size() > 1) + if ((device_local || staged_) && blocks_.size() > 1) for (std::size_t i = blocks_.size() - 1; i != 0; --i) if (take(blocks_[i - 1])) return true; auto& vk = d.context->vk; @@ -208,7 +237,7 @@ class TitleBufferWindows { }; auto drop_unfitting_spare = [&] { for (auto it = blocks_.begin(); it != blocks_.end(); ++it) { - if (it->live == 0 && bytes > it->capacity) { + if (!it->staged && it->live == 0 && bytes > it->capacity) { destroy_block(d, it); return true; } @@ -223,11 +252,21 @@ class TitleBufferWindows { return false; } } + const bool make_staged = staged_ && !device_local; + const VkDeviceSize slab_size = make_staged ? kStagedBlockSize : kBlockSize; Block b{}; - b.capacity = std::max(bytes, std::min(kBlockSize, remaining_cap)); + b.capacity = std::max(bytes, std::min(slab_size, remaining_cap)); VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = b.capacity; info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + if (make_staged) { + info.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | + VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; + if constexpr (requires { d.info.conditional_rendering; }) { + if (d.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + } + } d.share(info); if (const VkResult made = vk.vkCreateBuffer(d.info.device, &info, nullptr, &b.buffer); made != VK_SUCCESS) { note_block_failure("vkCreateBuffer", made, b.capacity); @@ -243,43 +282,85 @@ class TitleBufferWindows { return false; } } - // Device-local (Resizable BAR) when asked and while the driver gives it; host memory otherwise. After the - // story load the driver refused every 4 MiB device-local, host-visible block with a device address - // (VK_ERROR_OUT_OF_HOST_MEMORY, speed-8/-9) while host memory still served: once that happens, later blocks - // go straight to host memory instead of through DeviceState::allocate's sleeping retries first. - // A device_local request under set_system_memory takes system memory instead, out of the types that are not - // device-local (memory_type_order would otherwise give the first host-visible type, which can be the BAR). - VkMemoryPropertyFlags chosen = 0; - const bool system = device_local && system_memory_ != kDeviceLocal; - const bool want_local = device_local && !local_refused_ && !system; - VkMemoryRequirements types = req; - if (system) types.memoryTypeBits = system_memory_types(d, req.memoryTypeBits, system_memory_ == kSystemCached); - b.memory = d.allocate(types, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT - : system && system_memory_ == kSystemCached ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT - : 0, - &chosen, true); - if (b.memory && system && !system_memory_logged_) { - system_memory_logged_ = true; - std::fprintf(stderr, "[rt] d3d12: title buffer copies in system memory (LEONIDA_GEOMETRY_HOST): memory " - "flags 0x%x (%s, %s)\n", - unsigned(chosen), - (chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ? "device-local: no other type" : "not VRAM", - (chosen & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) ? "write-back" : "write-combined"); - } - if (b.memory && want_local && !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { - local_refused_ = true; - std::fprintf(stderr, "[rt] d3d12: title buffer windows: device-local memory refused a %llu KiB block; " - "this and later blocks are in host memory\n", - static_cast(req.size >> 10)); - } void* host{}; VkResult bound = VK_ERROR_OUT_OF_DEVICE_MEMORY, mapped_result = VK_ERROR_MEMORY_MAP_FAILED; - if (!b.memory) note_block_failure("vkAllocateMemory (DeviceState::allocate)", bound, req.size); - else if ((bound = vk.vkBindBufferMemory(d.info.device, b.buffer, b.memory, 0)) != VK_SUCCESS) - note_block_failure("vkBindBufferMemory", bound, req.size); - else if ((mapped_result = vk.vkMapMemory(d.info.device, b.memory, 0, VK_WHOLE_SIZE, 0, &host)) != VK_SUCCESS) - note_block_failure("vkMapMemory", mapped_result, req.size); + bool block_staged = false; + if (make_staged && !local_refused_) { + VkMemoryPropertyFlags vram_chosen = 0; + VkDeviceMemory vram_mem = d.allocate(req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, &vram_chosen, true); + VkBuffer staging_buf = VK_NULL_HANDLE; + VkDeviceMemory staging_mem = VK_NULL_HANDLE; + if (vram_mem && (vram_chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { + VkBufferCreateInfo sinfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + sinfo.size = b.capacity; + sinfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + d.share(sinfo); + if (vk.vkCreateBuffer(d.info.device, &sinfo, nullptr, &staging_buf) == VK_SUCCESS) { + VkMemoryRequirements sreq{}; + vk.vkGetBufferMemoryRequirements(d.info.device, staging_buf, &sreq); + sreq.memoryTypeBits = system_memory_types(d, sreq.memoryTypeBits, /*cached=*/true); + staging_mem = d.allocate(sreq, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + VK_MEMORY_PROPERTY_HOST_CACHED_BIT, nullptr, false); + } + } + if (vram_mem && staging_buf && staging_mem && + vk.vkBindBufferMemory(d.info.device, b.buffer, vram_mem, 0) == VK_SUCCESS && + vk.vkBindBufferMemory(d.info.device, staging_buf, staging_mem, 0) == VK_SUCCESS && + vk.vkMapMemory(d.info.device, staging_mem, 0, VK_WHOLE_SIZE, 0, &host) == VK_SUCCESS) { + b.memory = vram_mem; + b.staging_buffer = staging_buf; + b.staging_memory = staging_mem; + bound = VK_SUCCESS; + mapped_result = VK_SUCCESS; + block_staged = true; + } else { + if (staging_buf) vk.vkDestroyBuffer(d.info.device, staging_buf, nullptr); + if (staging_mem) vk.vkFreeMemory(d.info.device, staging_mem, nullptr); + if (vram_mem) vk.vkFreeMemory(d.info.device, vram_mem, nullptr); + local_refused_ = true; + std::fprintf(stderr, "[rt] d3d12: title buffer windows: staged DEVICE_LOCAL slab of %llu KiB refused; " + "falling back to host memory for later blocks\n", + static_cast(req.size >> 10)); + } + } + if (!block_staged) { + // Device-local (Resizable BAR) when asked and while the driver gives it; host memory otherwise. After the + // story load the driver refused every 4 MiB device-local, host-visible block with a device address + // (VK_ERROR_OUT_OF_HOST_MEMORY, speed-8/-9) while host memory still served: once that happens, later blocks + // go straight to host memory instead of through DeviceState::allocate's sleeping retries first. + // A device_local request under set_system_memory takes system memory instead, out of the types that are not + // device-local (memory_type_order would otherwise give the first host-visible type, which can be the BAR). + VkMemoryPropertyFlags chosen = 0; + const bool system = device_local && system_memory_ != kDeviceLocal; + const bool want_local = device_local && !local_refused_ && !system; + VkMemoryRequirements types = req; + if (system) types.memoryTypeBits = system_memory_types(d, req.memoryTypeBits, system_memory_ == kSystemCached); + b.memory = d.allocate(types, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT + : system && system_memory_ == kSystemCached ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT + : 0, + &chosen, true); + if (b.memory && system && !system_memory_logged_) { + system_memory_logged_ = true; + std::fprintf(stderr, "[rt] d3d12: title buffer copies in system memory (LEONIDA_GEOMETRY_HOST): memory " + "flags 0x%x (%s, %s)\n", + unsigned(chosen), + (chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ? "device-local: no other type" : "not VRAM", + (chosen & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) ? "write-back" : "write-combined"); + } + if (b.memory && want_local && !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { + local_refused_ = true; + std::fprintf(stderr, "[rt] d3d12: title buffer windows: device-local memory refused a %llu KiB block; " + "this and later blocks are in host memory\n", + static_cast(req.size >> 10)); + } + if (!b.memory) note_block_failure("vkAllocateMemory (DeviceState::allocate)", bound, req.size); + else if ((bound = vk.vkBindBufferMemory(d.info.device, b.buffer, b.memory, 0)) != VK_SUCCESS) + note_block_failure("vkBindBufferMemory", bound, req.size); + else if ((mapped_result = vk.vkMapMemory(d.info.device, b.memory, 0, VK_WHOLE_SIZE, 0, &host)) != VK_SUCCESS) + note_block_failure("vkMapMemory", mapped_result, req.size); + } if (b.memory && bound == VK_SUCCESS && mapped_result == VK_SUCCESS) { VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = b.buffer; @@ -291,10 +372,16 @@ class TitleBufferWindows { b.mapped = static_cast(host); b.reserved_bytes = req.size; b.free_ranges.emplace(0, b.capacity); + if (block_staged) { + b.staged = std::make_unique(); + b.staged->staging.init(b.capacity); + } if (const std::size_t n = published_count_.load(std::memory_order_relaxed); n < kPublished) { published_[n].capacity = b.capacity; published_[n].mapped = b.mapped; published_[n].buffer = b.buffer; + published_[n].staging_buffer = b.staging_buffer; + published_[n].staged = b.staged.get(); published_[n].address.store(b.address, std::memory_order_relaxed); published_count_.store(n + 1, std::memory_order_release); } @@ -302,8 +389,9 @@ class TitleBufferWindows { blocks_.push_back(std::move(b)); reserved_ += req.size; if (blocks_.size() == 1 || !(blocks_.size() & (blocks_.size() - 1))) - std::fprintf(stderr, "[rt] d3d12: title buffer shadows outside the arena: %zu blocks, " - "new block %llu KiB at shader VA 0x%llx\n", blocks_.size(), + std::fprintf(stderr, "[rt] d3d12: title buffer shadows outside the arena%s: %zu blocks, " + "new block %llu KiB at shader VA 0x%llx\n", + block_staged ? " (DEVICE_LOCAL VRAM)" : "", blocks_.size(), static_cast(blocks_.back().capacity >> 10), static_cast(biased)); return take(blocks_.back()); @@ -316,15 +404,21 @@ class TitleBufferWindows { static_cast(b.address), static_cast(d.arena.address), signed_offsets ? "signed" : "unsigned"); } - vk.vkUnmapMemory(d.info.device, b.memory); + if (block_staged) { + vk.vkUnmapMemory(d.info.device, b.staging_memory); + vk.vkDestroyBuffer(d.info.device, b.staging_buffer, nullptr); + vk.vkFreeMemory(d.info.device, b.staging_memory, nullptr); + } else { + vk.vkUnmapMemory(d.info.device, b.memory); + } } vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr); if (b.memory) vk.vkFreeMemory(d.info.device, b.memory, nullptr); return failed(); } - // Returns [offset, offset + bytes) to its block for reuse; keeps one empty 4 MiB block as a spare and destroys - // any other empty block. Caller must guarantee no in-flight GPU work references this range. + // Returns [offset, offset + bytes) to its block for reuse; keeps staged blocks and one empty 4 MiB block pooled + // as spares and destroys any other empty block. Caller must guarantee no in-flight GPU work references this range. template bool free(Device& d, VkDeviceSize offset, VkDeviceSize bytes) { if (!bytes) return false; @@ -352,7 +446,7 @@ class TitleBufferWindows { b.free_ranges.emplace(merged_begin, merged_end - merged_begin); if (b.live > 0) --b.live; if (b.live == 0) { - if (b.capacity == kBlockSize && empty_blocks() == 1) { + if (b.staged || (b.capacity == kBlockSize && empty_blocks() == 1)) { b.free_ranges.clear(); b.free_ranges.emplace(0, b.capacity); b.used = 0; @@ -367,6 +461,140 @@ class TitleBufferWindows { // Allocations refused at once because a new block failed less than kRetryAfter ago. std::uint64_t quick_refusals() const { return quick_refusals_; } + // Lock-free dirty marking for CPU writes into a staged block's mapped staging mirror. + bool mark_dirty_ptr(const void* ptr, std::size_t bytes) const { + if (!staged_ || !ptr || !bytes) return false; + const auto* p = static_cast(ptr); + const std::size_t n = published_count_.load(std::memory_order_acquire); + for (std::size_t i = 0; i < n; ++i) { + const Published& b = published_[i]; + if (!b.staged || !b.address.load(std::memory_order_acquire)) continue; + if (p >= b.mapped && p - b.mapped < std::ptrdiff_t(b.capacity)) { + const VkDeviceSize off = static_cast(p - b.mapped); + const VkDeviceSize clamped = std::min(bytes, b.capacity - off); + b.staged->staging.mark(off, clamped); + return true; + } + } + return false; + } + + // Locates [ptr, ptr + bytes) in a staged block's mapped staging mirror, returning its published slot index and + // buffer-relative VkBufferCopy range. Lock-free. + bool find_staged_range(const std::uint8_t* ptr, std::size_t bytes, std::size_t& slot_index, + VkBufferCopy& region) const { + if (!staged_ || !ptr || !bytes) return false; + const std::size_t n = published_count_.load(std::memory_order_acquire); + for (std::size_t i = 0; i < n; ++i) { + const Published& b = published_[i]; + if (!b.staged || !b.address.load(std::memory_order_acquire)) continue; + if (ptr >= b.mapped && ptr - b.mapped < std::ptrdiff_t(b.capacity)) { + const VkDeviceSize off = static_cast(ptr - b.mapped); + const VkDeviceSize clamped = std::min(bytes, b.capacity - off); + slot_index = i; + region = {off, off, clamped}; + return true; + } + } + return false; + } + + // Records staged staging->VRAM buffer copies for all published staged blocks into `cmd`. Serialized by the + // caller's arena upload mutex. Returns true if at least one copy was recorded. + template + bool record_uploads(VkCommandBuffer cmd, const Vk& vk) { + if (!staged_) return false; + bool any = false; + const std::size_t n = published_count_.load(std::memory_order_acquire); + for (std::size_t i = 0; i < n; ++i) { + const Published& b = published_[i]; + if (!b.staged || !b.address.load(std::memory_order_acquire)) continue; + if (!b.staged->staging.drain(b.staged->last_upload)) continue; + vk.vkCmdCopyBuffer(cmd, b.staging_buffer, b.buffer, + static_cast(b.staged->last_upload.size()), + b.staged->last_upload.data()); + any = true; + } + return any; + } + + void commit_uploads(bool submitted) { + if (!staged_) return; + const std::size_t n = published_count_.load(std::memory_order_acquire); + for (std::size_t i = 0; i < n; ++i) { + const Published& b = published_[i]; + if (!b.staged) continue; + if (!b.staged->last_upload.empty()) { + if (!submitted) b.staged->staging.requeue(b.staged->last_upload); + b.staged->last_upload.clear(); + } + } + } + + // Collects GPU-written ranges from each staged block's VRAM buffer into `batches` (subtracting host-dirty ranges) + // so callers can submit arena + external window readbacks in a single `copy_buffers_sync` call. + template + void collect_host_readbacks(std::map>& per_slot, + std::vector& batches, std::vector& slots) { + if (!staged_ || per_slot.empty()) return; + const std::size_t n = published_count_.load(std::memory_order_acquire); + for (auto& [slot, copies] : per_slot) { + if (slot >= n || copies.empty()) continue; + const Published& b = published_[slot]; + if (!b.staged || !b.address.load(std::memory_order_acquire)) continue; + b.staged->staging.subtract_dirty(copies); + if (copies.empty()) continue; + batches.push_back(Batch{b.buffer, b.staging_buffer, copies}); + slots.push_back(slot); + } + } + + void note_host_readbacks(const std::vector& slots, + const std::map>& per_slot) { + if (!staged_ || slots.empty()) return; + const std::size_t n = published_count_.load(std::memory_order_acquire); + for (const std::size_t slot : slots) { + if (slot >= n) continue; + const auto it = per_slot.find(slot); + if (it == per_slot.end() || it->second.empty()) continue; + const Published& b = published_[slot]; + if (b.staged) b.staged->staging.note_readback(it->second); + } + } + + // Synchronously reads back GPU-written ranges from each staged block's VRAM buffer into its staging mirror + // in a single batched submission. + template + bool sync_to_host(Context& ctx, VkQueue queue, std::uint32_t queue_family, + std::map>& per_slot) { + if (!staged_ || per_slot.empty()) return true; + std::vector batches; + std::vector slots; + collect_host_readbacks(per_slot, batches, slots); + if (batches.empty()) return true; + if (!ctx.copy_buffers_sync(batches, queue, queue_family)) return false; + note_host_readbacks(slots, per_slot); + return true; + } + + leonida::ArenaStaging::Stats staging_stats() const { + leonida::ArenaStaging::Stats total{}; + if (!staged_) return total; + const std::size_t n = published_count_.load(std::memory_order_acquire); + for (std::size_t i = 0; i < n; ++i) { + const Published& b = published_[i]; + if (!b.staged) continue; + const auto st = b.staged->staging.stats(); + total.flushes += st.flushes; + total.regions += st.regions; + total.bytes += st.bytes; + total.readbacks += st.readbacks; + total.readback_regions += st.readback_regions; + total.readback_bytes += st.readback_bytes; + } + return total; + } + bool lookup(VkDeviceAddress address, std::uint64_t& host, std::uint64_t& remaining) const { for (const auto& b : blocks_) { const auto delta = address - b.address; @@ -383,13 +611,22 @@ class TitleBufferWindows { template void release(Device& d) { for (auto& b : blocks_) { - d.context->vk.vkUnmapMemory(d.info.device, b.memory); + if (b.staged) { + d.context->vk.vkUnmapMemory(d.info.device, b.staging_memory); + d.context->vk.vkDestroyBuffer(d.info.device, b.staging_buffer, nullptr); + d.context->vk.vkFreeMemory(d.info.device, b.staging_memory, nullptr); + } else { + d.context->vk.vkUnmapMemory(d.info.device, b.memory); + } d.context->vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr); d.context->vk.vkFreeMemory(d.info.device, b.memory, nullptr); } blocks_.clear(); - for (std::size_t i = 0, n = published_count_.load(std::memory_order_relaxed); i < n; ++i) + for (std::size_t i = 0, n = published_count_.load(std::memory_order_relaxed); i < n; ++i) { + published_[i].staged = nullptr; + published_[i].staging_buffer = VK_NULL_HANDLE; published_[i].address.store(0, std::memory_order_relaxed); + } published_count_.store(0, std::memory_order_release); layout_generation_.fetch_add(1, std::memory_order_release); reserved_ = 0; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1c97dad489..553c90e6fd 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/arena_staging.h" #include "../src/command_list_epochs.h" #include "../src/value_write_sink.h" #include "../src/address_guard.h" @@ -373,6 +374,42 @@ class ShadowPages { using GpuCopy = bool (*)(void* context, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes); static inline GpuCopy gpu_copy = nullptr; static inline void* gpu_copy_context = nullptr; + // RT-ARENA-DEVICE-LOCAL-STAGED: notifies the device when the CPU writes into a target mapped in the staged arena. + // Must only be called when lock_ is NOT held (ArenaStaging::mark uses the process heap). + using DirtyFn = void (*)(void* context, const void* ptr, std::size_t bytes); + void set_dirty_hook(void* context, DirtyFn fn) { + dirty_context_ = context; + dirty_fn_ = fn; + } + // Collects the arena byte spans of every target overlapping `ranges` so a staged DEVICE_LOCAL arena can read + // GPU-written bytes back into the host staging buffer before write_back() inspects them. Runs under shadow_mutex. + template + void for_each_target_range(const std::pair* ranges, std::size_t count, + const std::uint8_t* only, Fn&& fn) const { + if (!count) return; + for (std::size_t r = 0; r < count; ++r) { + const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); + if (from >= to) continue; + for_each_target(from, to, [&](const Target& t, std::uintptr_t a, std::uintptr_t b) { + if (!t.shadow || (only && t.retired && t.shadow != only)) return; + fn(t.shadow + (a - t.begin), b - a); + }); + } + } + void collect_arena_ranges(const std::pair* ranges, std::size_t count, + const std::uint8_t* only, const std::uint8_t* arena_mapped, VkDeviceSize arena_size, + std::vector& out) const { + if (!arena_mapped || !arena_size || !count) return; + const auto arena_lo = reinterpret_cast(arena_mapped); + const auto arena_hi = arena_lo + static_cast(arena_size); + for_each_target_range(ranges, count, only, [&](const std::uint8_t* ptr, std::size_t len) { + const auto dst = reinterpret_cast(ptr); + if (dst >= arena_lo && dst < arena_hi && len <= arena_hi - dst) { + const VkDeviceSize off = static_cast(dst - arena_lo); + out.push_back({off, off, static_cast(len)}); + } + }); + } // Bytes this tracker's refreshes handed to gpu_copy so far. std::uint64_t gpu_bytes() const { return gpu_bytes_; } @@ -394,7 +431,7 @@ class ShadowPages { // Every page made read-only here is read-write again: the title's pages outlive the buffer. void reopen_all() { AcquireSRWLockExclusive(&lock_); - if (std::any_of(state_.begin(), state_.end(), [](std::uint8_t s) { return s & kProtected; })) + if (std::any_of(state_.begin(), state_.end(), [](std::uint16_t s) { return s & kProtected; })) reopen_locked(first_, last_); ReleaseSRWLockExclusive(&lock_); for (auto& [va, block] : aliased_blocks_) release_cells(va, block); @@ -484,7 +521,7 @@ class ShadowPages { const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); if (from >= to) continue; for (std::size_t i = (from - first_) / kPage, i1 = (to - first_ + kPage - 1) / kPage; i < i1; ++i) { - const std::uint8_t s = state_[i]; + const std::uint16_t s = state_[i]; held_pages_[i - p0] = (s & (kZero | kRequery | kPinned | kAliased)) || (!(s & kProtected) && !(s & kClean)); } @@ -492,6 +529,7 @@ class ShadowPages { const auto held = [&](std::size_t i) { return held_pages_[i - p0] != 0; }; constexpr std::uintptr_t kPiece = 256; // compared and copied in pieces this size std::size_t written = 0; + Vector> dirty_targets; for (std::size_t r = 0; r < count; ++r) { const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); if (from >= to) continue; @@ -549,7 +587,7 @@ class ShadowPages { // An earlier range on these pages may have reopened them already. const std::size_t i0 = (at - first_) / kPage; if (std::any_of(state_.begin() + i0, state_.begin() + i0 + pages, - [](std::uint8_t page) { return page & kProtected; })) + [](std::uint16_t page) { return page & kProtected; })) reopen_locked(at, at + pages * kPage); opened = true; } @@ -563,9 +601,22 @@ class ShadowPages { 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]) + const std::uintptr_t lo = std::max(i, o->begin); + const std::uintptr_t hi = std::min(j, o->end); + std::uintptr_t run_start = hi; + for (std::uintptr_t v = lo; v < hi; ++v) { + if (o->shadow[v - o->begin] == before[v - c]) { o->shadow[v - o->begin] = copy[v - x]; + if (dirty_fn_ && run_start == hi) run_start = v; + } else if (dirty_fn_ && run_start < v) { + dirty_targets.push_back( + {o->shadow + (run_start - o->begin), v - run_start}); + run_start = hi; + } + } + if (dirty_fn_ && run_start < hi) + dirty_targets.push_back( + {o->shadow + (run_start - o->begin), hi - run_start}); } i = j; } @@ -579,6 +630,7 @@ class ShadowPages { } writer_.store(0, std::memory_order_relaxed); ReleaseSRWLockExclusive(&lock_); + for (const auto& [ptr, len] : dirty_targets) note_dirty(ptr, len); return written; } @@ -649,7 +701,7 @@ class ShadowPages { refresh_walked_all_ = full_walk; refresh_protects_ = alias_arms_; if (pinned_) { - for (std::uint8_t& s : state_) s &= ~kPinned; + for (std::uint16_t& s : state_) s &= ~kPinned; pinned_ = false; } leonida::kernel_writes::for_each_pin(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { @@ -676,9 +728,9 @@ class ShadowPages { // fifth of the submitting thread's time. So are aliased pages whose cells no write reached (aliased_clean): // a mapping, commitment or protection change over a cell moves its version too. const auto skip = [&](std::size_t i) { - const std::uint8_t s = state_[i]; + const std::uint16_t s = state_[i]; return unchanged(s) || ((s & ~(kZero | kProtected)) == kAliased && aliased_clean(i)) || - (!copy_aliased_ && (s == kAliased || s == kZero || s == (kZero | kAliased))); + (!copy_aliased_ && (s == kAliased || s == (kZero | kAliased))); }; if (!full_walk && skip(i0)) { std::size_t i = i0 + 1; @@ -714,7 +766,7 @@ class ShadowPages { zeroed_.back().bytes += bytes; else zeroed_.push_back({offset, bytes, false}); - state_[i] = std::uint8_t(kZero | (state_[i] & (kAliased | kPinned | kWatched))); + state_[i] = std::uint16_t(kZero | (state_[i] & (kAliased | kPinned | kWatched))); } break; case Kind::writable: @@ -730,19 +782,19 @@ class ShadowPages { // read-only with no owner, so the next write could fault. unguard_ours(i, j); for (std::size_t k = i; k < j; ++k) - state_[k] = std::uint8_t((state_[k] & ~(kZero | kProtected)) | kClean); + state_[k] = std::uint16_t((state_[k] & ~(kZero | kProtected | kExternalRo)) | kClean); add_job(i, j, streaming, Copy::write_watched); break; case Watch::open: // write-watched, but pinned for a kernel write: copied until the pin ends unguard_ours(i, j); - for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected | kClean); + for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected | kClean | kExternalRo); add_job(i, j, streaming, Copy::write_watched); break; case Watch::guard: if (kind == Kind::writable) guard_writable(i, j, region.Protect, streaming); else - guard_read_only(i, j, streaming); + guard_read_only(i, j, streaming, full_walk); break; } i = j; @@ -754,13 +806,20 @@ class ShadowPages { add_job(i0, i1, streaming, Copy::copy_on_write); break; } - for (std::size_t i = i0; i < i1; ++i) state_[i] &= std::uint8_t(~kRequery); // queried now + for (std::size_t i = i0; i < i1; ++i) state_[i] &= std::uint16_t(~kRequery); // queried now at = next; } // Remember the generation from before the walk, so a change during the walk triggers another one. map_generation_ = map_generation; const DWORD protect_error = std::exchange(protect_error_, 0); ReleaseSRWLockExclusive(&lock_); + if (dirty_fn_ && !zeroed_.empty()) { + for (const Job& z : zeroed_) + for_each_target(begin_ + z.offset, begin_ + z.offset + z.bytes, + [&](const Target& t, std::uintptr_t a, std::uintptr_t b) { + note_dirty(t.shadow + (a - t.begin), b - a); + }); + } if (protect_error) log_once("slot-133 shadow: VirtualProtect refused to watch the title's pages for writes, so they are " "copied at every submission; error", @@ -790,8 +849,10 @@ class ShadowPages { if (job.aliased && gpu_copy) ++pieces_.gpu_calls; if (job.aliased && gpu_copy && gpu_copy(gpu_copy_context, run_dst, run_src, run_bytes)) gpu_bytes_ += run_bytes; - else + else { copy_run(run_dst, run_src, run_bytes, job.streaming); + note_dirty(run_dst, run_bytes); + } run_bytes = 0; }; for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes, @@ -829,7 +890,7 @@ class ShadowPages { AcquireSRWLockExclusive(&lock_); if (first < first_) { const std::size_t n = (first_ - first) / kPage; - state_.insert(state_.begin(), n, std::uint8_t(0)); + state_.insert(state_.begin(), n, std::uint16_t(0)); idle_.insert(idle_.begin(), n, std::uint8_t(0)); sums_.insert(sums_.begin(), n * kPieces, std::uint64_t(0)); cover_.insert(cover_.begin(), n, 0u); @@ -876,7 +937,7 @@ class ShadowPages { pinned_ |= other.pinned_; watch_ = watch_ && other.watch_; faults_.fetch_add(other.faults(), std::memory_order_relaxed); - std::fill(other.state_.begin(), other.state_.end(), std::uint8_t(0)); + std::fill(other.state_.begin(), other.state_.end(), std::uint16_t(0)); other.targets_.clear(); ReleaseSRWLockExclusive(&other.lock_); index_targets(); @@ -912,9 +973,11 @@ class ShadowPages { const std::uintptr_t from = std::max(at, begin), to = std::min(next, end); if (kind == Kind::zero) { std::memset(shadow + (from - begin), 0, to - from); + note_dirty(shadow + (from - begin), to - from); } else { const bool streaming = (region.Protect & PAGE_WRITECOMBINE) != 0; copy_run(shadow + (from - begin), reinterpret_cast(from), to - from, streaming); + note_dirty(shadow + (from - begin), to - from); // The sums stand for what every target holds. The new target now holds the title's current bytes, so // the pieces where those differ from the sums are brought to the other targets too, and the sums // follow; otherwise a title that later writes the old bytes back would leave the new target behind. @@ -940,6 +1003,7 @@ class ShadowPages { page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) { for_each_target(a, b, [&](const Target& t, std::uintptr_t lo, std::uintptr_t hi) { std::memcpy(t.shadow + (lo - t.begin), source + (lo - a), hi - lo); + note_dirty(t.shadow + (lo - t.begin), hi - lo); }); }); va += n; @@ -999,7 +1063,7 @@ class ShadowPages { if (!held) AcquireSRWLockExclusive(&lock_); bool guarded = false; for (std::size_t i = (from - first_) / kPage, i1 = (to - first_) / kPage; i < i1; ++i) { - state_[i] &= ~kClean; + state_[i] &= ~(kClean | kExternalRo); guarded |= (state_[i] & kProtected) != 0; } if (guarded) reopen_locked(from, to); @@ -1013,7 +1077,7 @@ class ShadowPages { // lock, so by a later look the page can be read-only again (and this tracker's again), and the handler refused a // write it should have retried, which ended the process (seen natively on Windows 11: threads writing one page // across a submission). - bool reopen(std::uintptr_t address) { + bool reopen(std::uintptr_t address, bool* block_reopened = nullptr) { // On the thread whose write_back faulted, lock_ is held already (see write_back). const bool held = writer_.load(std::memory_order_relaxed) == GetCurrentThreadId(); if (!held) AcquireSRWLockExclusive(&lock_); @@ -1028,12 +1092,13 @@ class ShadowPages { const std::size_t i0 = (from - first_) / kPage, i1 = (to - first_) / kPage; for (std::size_t i = i0; i < i1; ++i) watched[i - i0] = (state_[i] & (kWatched | kHot | kProtected)) == (kWatched | kProtected); - reopen_locked(from, to); + reopen_locked(from, to, /*notify_map=*/false); retry = !(state_[index] & kProtected); + if (retry && block_reopened) *block_reopened = true; faults_.fetch_add(1, std::memory_order_relaxed); for (std::size_t i = i0; i < i1; ++i) { if (!watched[i - i0] || (state_[i] & kProtected)) continue; - state_[i] = std::uint8_t((state_[i] | kHot) & ~kClean); + state_[i] = std::uint16_t((state_[i] | kHot) & ~kClean); idle_[i] = 0; runs_stale_ = true; } @@ -1041,21 +1106,23 @@ class ShadowPages { MEMORY_BASIC_INFORMATION region{}; retry = VirtualQuery(reinterpret_cast(address), ®ion, sizeof(region)) && classify(region) == Kind::writable; + if (retry) state_[index] &= ~kExternalRo; } if (!held) ReleaseSRWLockExclusive(&lock_); return retry; } private: - enum : std::uint8_t { - kProtected = 1, // made read-only here: unchanged since it was copied - kZero = 2, // zero in the copies (not committed when last looked at) - kAliased = 4, // xmem maps its physical page at another address too - kPinned = 8, // a kernel write into it may be in flight (leonida::kernel_writes) - kWatched = 16, // in a write-watched reservation (leonida::title_write_watch) - kClean = 32, // hot, and not written since it was copied after an asking - kHot = 64, // write-watched and asked about at every refresh, never guarded - kRequery = 128, // its mapping, commitment or protection changed (title_memory_map): queried at the next walk + enum : std::uint16_t { + kProtected = 1, // made read-only here: unchanged since it was copied + kZero = 2, // zero in the copies (not committed when last looked at) + kAliased = 4, // xmem maps its physical page at another address too + kPinned = 8, // a kernel write into it may be in flight (leonida::kernel_writes) + kWatched = 16, // in a write-watched reservation (leonida::title_write_watch) + kClean = 32, // hot, and not written since it was copied after an asking + kHot = 64, // write-watched and asked about at every refresh, never guarded + kRequery = 128, // its mapping, commitment or protection changed (title_memory_map): queried at the next walk + kExternalRo = 256, // observed read-only (not ours) and copied once: unchanged until kRequery }; // Refreshes a hot block may go without a write before it is guarded again. static constexpr std::uint8_t kCool = 64; @@ -1083,14 +1150,17 @@ class ShadowPages { // How a committed, readable page is watched: by the kernel (clean, written or, pinned or aliased, open) or by // a guard. enum class Watch { clean, written, open, guard }; - static Watch watch_of(std::uint8_t s) { + static Watch watch_of(std::uint16_t s) { if ((s & (kWatched | kHot)) != (kWatched | kHot)) return Watch::guard; if (s & (kAliased | kPinned)) return Watch::open; return s & kClean ? Watch::clean : Watch::written; } // A page known unchanged since the last refresh, which one that doesn't walk everything passes over. - static bool unchanged(std::uint8_t s) { - return s == kProtected || s == (kWatched | kProtected) || s == (kWatched | kHot | kClean); + // Uncommitted (kZero) and externally read-only (kExternalRo) pages cannot change without a mapping or protection + // change (which sets kRequery via title_memory_map::changed). + static bool unchanged(std::uint16_t s) { + const std::uint16_t base = s & ~kWatched; + return base == kProtected || base == kExternalRo || base == kZero || s == (kWatched | kHot | kClean); } // One asking of the write watch, under lock_: the hot pages written since the last asking lose kClean (counted in @@ -1113,7 +1183,7 @@ class ShadowPages { reader_, watch_runs_, [&](std::uintptr_t from, std::uintptr_t to) { for (std::uintptr_t p = from; p < to; p += kPage) { - std::uint8_t& s = state_[(p - first_) / kPage]; + std::uint16_t& s = state_[(p - first_) / kPage]; if (!(s & kHot)) continue; // asked over a gap between hot pages: guarded refresh_written_ += (s & kClean) != 0; s &= ~kClean; @@ -1161,7 +1231,7 @@ class ShadowPages { std::size_t j = i + 1; while (j < i1 && bool(state_[j] & (kAliased | kPinned)) == unwatched) ++j; for (std::size_t k = i; k < j; ++k) { - state_[k] &= ~(kZero | kProtected); + state_[k] &= ~(kZero | kProtected | kExternalRo); // Writable with no write seen: its cells must be armed again (update_aliased). if (aliased_clean(k) && (rearm_.empty() || rearm_.back() != block_of(k))) rearm_.push_back(block_of(k)); } @@ -1178,16 +1248,17 @@ class ShadowPages { } } - // Guarded pages [i, j) of a read-only region: pages this tracker protected, and aliased pages whose cells no write - // reached, are as the last refresh left them; non-aliased pages already armed read-only by geometry_writes - // (TitleTextureCells / GeometryViews / TitleMirror) adopt kProtected after one copy so ShadowPages skips them on - // subsequent refreshes instead of recopying them forever as Copy::read_only (shadow_write_fault and - // open_shadow_pages reopen the whole 64 KiB tile via ShadowPages::reopen_range, and release()/set_hot() notify - // title_memory_map::changed()); any other read-only page is copied again. - void guard_read_only(std::size_t i0, std::size_t i1, bool streaming) { + // Guarded pages [i, j) of a read-only region: pages this tracker protected, externally read-only pages already + // copied with no intervening mapping/protection change, and aliased pages whose cells no write reached are as the + // last refresh left them; non-aliased pages already armed read-only by geometry_writes (TitleTextureCells / + // GeometryViews / TitleMirror) adopt kProtected after one copy so ShadowPages skips them on subsequent refreshes + // instead of recopying them forever as Copy::read_only; any other read-only page is copied once and marked + // kExternalRo until a mapping/protection change triggers kRequery. + void guard_read_only(std::size_t i0, std::size_t i1, bool streaming, bool full_walk) { const auto clean_at = [&](std::size_t k) { - const std::uint8_t s = state_[k]; + const std::uint16_t s = state_[k]; return (s & (kProtected | kAliased | kPinned)) == kProtected || + (!full_walk && (s & (kExternalRo | kRequery | kAliased | kPinned)) == kExternalRo) || ((s & (kAliased | kPinned)) == kAliased && aliased_clean(k)); }; for (std::size_t i = i0; i < i1;) { @@ -1215,7 +1286,12 @@ class ShadowPages { while (o_end < n && (gw[o_end] != 0) == adopted) ++o_end; for (std::size_t k = chunk + o; k < chunk + o_end; ++k) { state_[k] &= ~kZero; - if (adopted) state_[k] |= kProtected; + if (adopted) { + state_[k] |= kProtected; + state_[k] &= ~kExternalRo; + } else { + state_[k] |= kExternalRo; + } } add_job(chunk + o, chunk + o_end, streaming, adopted ? Copy::guarded : Copy::read_only); @@ -1224,7 +1300,13 @@ class ShadowPages { chunk += n; } } else { - for (std::size_t k = p; k < q; ++k) state_[k] &= ~kZero; + for (std::size_t k = p; k < q; ++k) { + state_[k] &= ~kZero; + if (!(state_[k] & (kProtected | kAliased | kPinned))) + state_[k] |= kExternalRo; + else + state_[k] &= ~kExternalRo; + } add_job(p, q, streaming, (flags & kAliased) ? Copy::aliased : (flags & kPinned) ? Copy::pinned @@ -1265,7 +1347,7 @@ class ShadowPages { if (generation != alias_generation_) { alias_generation_ = generation; aliased_list_.clear(); - for (std::uint8_t& s : state_) s &= ~kAliased; + for (std::uint16_t& s : state_) s &= ~kAliased; leonida::title_page_aliases::for_each_in(first_, last_, [&](std::uintptr_t va) { const std::uintptr_t from = std::max(va, first_), to = std::min(va + kBlock, last_); bool read = false; @@ -1337,7 +1419,7 @@ class ShadowPages { // asked and the walk has copied it. The runs may have closed (their reservation released) and come back over a // reservation made at the same address since, which a page's watched mark alone doesn't tell (re-review of #61). void forget_clean() { - for (std::uint8_t& page : state_) page &= std::uint8_t(~kClean); + for (std::uint16_t& page : state_) page &= std::uint16_t(~kClean); } // With the lock held, after the write-watched reservations changed: which pages are write-watched now. A page @@ -1350,8 +1432,8 @@ class ShadowPages { const auto side = [&](std::size_t upto, bool watched) { for (; i < upto; ++i) if (bool(state_[i] & kWatched) != watched) - state_[i] = - std::uint8_t((state_[i] & ~(kWatched | kClean | kHot | kZero)) | (watched ? kWatched : 0)); + state_[i] = std::uint16_t((state_[i] & ~(kWatched | kClean | kHot | kZero | kExternalRo)) | + (watched ? kWatched : 0)); }; leonida::title_write_watch::for_each_in(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { side((from - first_) / kPage, false); @@ -1481,6 +1563,7 @@ class ShadowPages { page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) { for_each_target(a, b, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { std::memcpy(t.shadow + (from - t.begin), source + (from - a), to - from); + note_dirty(t.shadow + (from - t.begin), to - from); copied += to - from; }); }); @@ -1570,7 +1653,7 @@ class ShadowPages { std::uint64_t unguarded_on_drop_ = 0; // times unguard_ours found pages of ours to reopen (diagnostic) // With the lock held: the pages in [from, to) this tracker made read-only are read-write again. - void reopen_locked(std::uintptr_t from, std::uintptr_t to) { + void reopen_locked(std::uintptr_t from, std::uintptr_t to, bool notify_map = true) { for (std::uintptr_t at = from; at < to;) { MEMORY_BASIC_INFORMATION region{}; std::uintptr_t next = at + kPage; @@ -1595,7 +1678,9 @@ class ShadowPages { VirtualProtect(reinterpret_cast(first_ + i * kPage), (j - i) * kPage, writable, &old)) { for (std::size_t k = i; k < j; ++k) state_[k] &= ~kProtected; - leonida::geometry_writes::note_external_reopen(first_ + i * kPage, first_ + j * kPage); + const std::uintptr_t run_lo = first_ + i * kPage, run_hi = first_ + j * kPage; + leonida::geometry_writes::note_external_reopen(run_lo, run_hi); + if (notify_map) leonida::title_memory_map::changed(run_lo, run_hi); } i = j; } @@ -1604,13 +1689,19 @@ class ShadowPages { } } + void note_dirty(const void* ptr, std::size_t bytes) const { + if (dirty_fn_ && bytes) dirty_fn_(dirty_context_, ptr, bytes); + } + + DirtyFn dirty_fn_ = nullptr; + void* dirty_context_ = nullptr; bool watch_; std::uintptr_t begin_ = 0, end_ = 0; // the targets' bytes: the first start and the furthest end std::uintptr_t first_ = 0, last_ = 0; // the pages covered SRWLOCK lock_ = SRWLOCK_INIT; // state_, cover_, the targets, and the protection of the pages std::atomic writer_{0}; // the thread in write_back, which holds lock_ while it copies into the title Vector held_pages_; // write_back's per-page decision, taken before its copies - Vector state_; // per 4 KiB page + Vector state_; // per 4 KiB page Vector cover_; // per 4 KiB page: the targets that read it Vector targets_; // by start Vector reach_; // see index_targets @@ -1683,7 +1774,10 @@ bool stray_read_only(EXCEPTION_POINTERS* info, std::uintptr_t address) { if (heal) { DWORD old = 0; ok = VirtualProtect(reinterpret_cast(page), 0x1000, (m.Protect & ~DWORD(0xff)) | PAGE_READWRITE, &old) != 0; - if (ok) healed.fetch_add(1, std::memory_order_relaxed); + if (ok) { + healed.fetch_add(1, std::memory_order_relaxed); + leonida::title_memory_map::changed(page, page + 0x1000); + } } if (told.fetch_add(1, std::memory_order_relaxed) < 32) { const auto rip = info && info->ContextRecord ? info->ContextRecord->Rip : 0; @@ -1724,10 +1818,15 @@ LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; const std::uintptr_t tile = address & ~(kTile - 1); AcquireSRWLockShared(&g_shadow_pages_lock); + bool shadow_block_reopened = false; for (ShadowPages* pages : shadow_pages_list()) { - if (pages->contains(address)) retry |= pages->reopen(address); // reopened, or another thread's fault did + if (pages->contains(address)) retry |= pages->reopen(address, &shadow_block_reopened); if (tile_reopened && pages->first() < tile + kTile && tile < pages->last()) pages->reopen_range(tile, tile + kTile); } + if (shadow_block_reopened && !tile_reopened) { + for (ShadowPages* pages : shadow_pages_list()) + if (pages->first() < tile + kTile && tile < pages->last()) pages->reopen_range(tile, tile + kTile); + } ReleaseSRWLockShared(&g_shadow_pages_lock); if (!retry) if (const auto unguard = leonida::kernel_writes::state().unguarder.load(std::memory_order_acquire)) @@ -3986,8 +4085,44 @@ struct DeviceState { // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. UINT no_output_sample_counts = 0; + std::uint32_t max_compute_shared_memory_size = 0; std::uint32_t f16_half_top_location = 29; float max_sampler_lod_bias = 0; + + // Shared VkPipelineLayout cache keyed by (push_stages, push_bytes, with_bindless). + // Avoids creating tens of thousands of identical layouts concurrently across slot 57/67 threads. + struct SharedLayoutKey { + VkShaderStageFlags push_stages = 0; + std::uint32_t push_bytes = 0; + bool with_bindless = false; + auto operator<=>(const SharedLayoutKey&) const = default; + }; + std::mutex shared_layout_mutex; + std::map shared_pipeline_layouts; + VkPipelineLayout shared_pipeline_layout(VkShaderStageFlags push_stages, std::uint32_t push_bytes, + bool with_bindless) { + std::lock_guard lock(shared_layout_mutex); + const SharedLayoutKey key{push_stages, push_bytes, with_bindless}; + if (const auto it = shared_pipeline_layouts.find(key); it != shared_pipeline_layouts.end()) + return it->second; + if (!context || !context->vk.vkCreatePipelineLayout) return VK_NULL_HANDLE; + const VkPushConstantRange push{push_stages, 0, push_bytes}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = &push; + VkDescriptorSetLayout set0_layout = VK_NULL_HANDLE; + if (with_bindless) { + if (!bindless) return VK_NULL_HANDLE; + set0_layout = bindless->layout(); + layout_info.setLayoutCount = 1; + layout_info.pSetLayouts = &set0_layout; + } + VkPipelineLayout layout = VK_NULL_HANDLE; + if (context->vk.vkCreatePipelineLayout(info.device, &layout_info, nullptr, &layout) != VK_SUCCESS) + return VK_NULL_HANDLE; + shared_pipeline_layouts.emplace(key, layout); + return layout; + } D3D12_CONSERVATIVE_RASTERIZATION_TIER conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED; VkSampleCountFlags sample_grid_1 = 0, sample_grid_4 = 0; D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER sample_positions_tier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; @@ -4029,6 +4164,93 @@ struct DeviceState { double heap_ms = 0; // spent in refresh_console_heaps since the last log line std::uint64_t shadow_faults = 0; // the write faults counted at the last log line + // Persistent 3-worker pool (+ caller thread = 4 threads) to parallelize ShadowPages::refresh across independent + // trackers (shadow_keep hashing, memcpy, arena_mark_dirty_ptr). Declared after `shadows` so it joins first. + struct ShadowRefreshPool { + static constexpr std::size_t kHelpers = 3; + static constexpr std::size_t kChunk = 32; + std::mutex mu; + std::condition_variable cv_work, cv_done; + std::vector threads; + const std::vector* list = nullptr; + bool copy_aliased = true; + std::atomic next{0}; + std::atomic copied{0}; + std::size_t epoch = 0; + std::size_t active = 0; + bool stop = false; + + ~ShadowRefreshPool() { + { + std::lock_guard lock(mu); + stop = true; + ++epoch; + } + cv_work.notify_all(); + for (auto& t : threads) + if (t.joinable()) t.join(); + } + + void run_chunk(const std::vector& s_list, bool aliased) { + const std::size_t n = s_list.size(); + std::uint64_t local_copied = 0; + for (;;) { + const std::size_t begin = next.fetch_add(kChunk, std::memory_order_relaxed); + if (begin >= n) break; + const std::size_t end = std::min(begin + kChunk, n); + for (std::size_t i = begin; i < end; ++i) local_copied += s_list[i]->refresh(aliased); + } + if (local_copied) copied.fetch_add(local_copied, std::memory_order_relaxed); + } + + std::uint64_t run(const std::vector& s_list, bool aliased) { + if (s_list.size() < kChunk * 2) { + std::uint64_t total = 0; + for (const ShadowPagesPtr& s : s_list) total += s->refresh(aliased); + return total; + } + { + std::lock_guard lock(mu); + if (threads.empty()) { + threads.reserve(kHelpers); + for (std::size_t i = 0; i < kHelpers; ++i) { + threads.emplace_back([this] { + std::size_t seen = 0; + for (;;) { + const std::vector* cur = nullptr; + bool ca = true; + { + std::unique_lock lk(mu); + cv_work.wait(lk, [&] { return stop || epoch != seen; }); + if (stop) return; + seen = epoch; + cur = list; + ca = copy_aliased; + } + run_chunk(*cur, ca); + std::lock_guard lk(mu); + if (--active == 0) cv_done.notify_one(); + } + }); + } + } + list = &s_list; + copy_aliased = aliased; + next.store(0, std::memory_order_relaxed); + copied.store(0, std::memory_order_relaxed); + active = threads.size(); + ++epoch; + } + cv_work.notify_all(); + run_chunk(s_list, aliased); + { + std::unique_lock lk(mu); + cv_done.wait(lk, [&] { return active == 0; }); + } + return copied.load(std::memory_order_relaxed); + } + } shadow_refresh_pool; + // A copy of the title's bytes [pages, pages + size) at `shadow`: filled now, then brought up to date before every // submission. Copies whose pages overlap or touch share one tracker (ShadowPages: a page has one owner that may // watch it), so a copy that reaches one or more trackers joins them into one. @@ -4047,6 +4269,7 @@ struct DeviceState { } if (hits.empty()) { ShadowPagesPtr tracker = make_shadow_pages(pages, shadow, size); + tracker->set_dirty_hook(this, &DeviceState::shadow_mark_dirty); tracker->refresh(); shadows.push_back(std::move(tracker)); return; @@ -4081,6 +4304,12 @@ struct DeviceState { if (!s.has_target(mapped)) continue; const std::pair range{static_cast(start), static_cast(start + size)}; + if (arena.staged) { + std::vector readbacks; + std::map> ext_readbacks; + collect_staged_shadow_readbacks(s, &range, 1, mapped, readbacks, ext_readbacks); + sync_retired_readbacks_to_host(readbacks, ext_readbacks); + } title_write_back_total += s.write_back(&range, 1, nullptr, mapped); s.remove_target(mapped); if (!s.targets()) shadows.erase(it); @@ -4124,11 +4353,9 @@ struct DeviceState { }()); const bool copy_aliased = alias_period.count() == 0 || start - shadow_alias_time >= alias_period; if (copy_aliased) shadow_alias_time = start; - std::uint64_t copied = 0; + const std::uint64_t copied = shadow_refresh_pool.run(shadows, copy_aliased); + if (copied) leonida::submit_phases::note_change(leonida::submit_phases::change_pages); // not a floor one for (const ShadowPagesPtr& s : shadows) { - const std::uint64_t pages = s->refresh(copy_aliased); - if (pages) leonida::submit_phases::note_change(leonida::submit_phases::change_pages); // not a floor one - copied += pages; shadow_queries += s->refresh_queries(); shadow_protects += s->refresh_protects(); shadow_walks += s->refresh_walked_all(); @@ -4312,8 +4539,74 @@ struct DeviceState { // title remaps per request, so a whole-pool allocation is not possible. static constexpr std::uint64_t kPoolExtentMax = 1ull << 20; std::mutex title_window_mutex; // taken before shadow_mutex, never under it + std::mutex external_windows_mutex; // leaf lock around external_windows mutate/lookup (ordered after title_window_mutex) rt::d3d12::TitleBufferWindows external_windows; + struct DeferredExternalFree { + std::uint64_t ticket; + VkDeviceSize offset; + VkDeviceSize size; + }; + std::deque deferred_external_frees; std::atomic external_window_made{false}; // a window lies outside the arena: device_reachable looks there + + void drain_deferred_external_frees_locked() { + if (deferred_external_frees.empty() || !context) return; + const std::uint64_t completed = context->completed_retire_ticket(); + while (!deferred_external_frees.empty() && deferred_external_frees.front().ticket <= completed) { + const auto entry = deferred_external_frees.front(); + deferred_external_frees.pop_front(); + external_windows.free(*this, entry.offset, entry.size); + } + } + + bool external_windows_allocate(VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped, + VkBuffer* out_buffer = nullptr, VkDeviceSize* out_buffer_offset = nullptr, + VkDeviceAddress* out_address = nullptr) { + std::lock_guard lock(external_windows_mutex); + drain_deferred_external_frees_locked(); + if (!external_windows.allocate(*this, bytes, offset, mapped, false, UINT64_MAX, nullptr, out_buffer, + out_buffer_offset, out_address)) + return false; + external_window_made.store(true, std::memory_order_release); + return true; + } + + void external_windows_free(VkDeviceSize offset, VkDeviceSize bytes) { + std::lock_guard lock(external_windows_mutex); + drain_deferred_external_frees_locked(); + external_windows.free(*this, offset, bytes); + } + + void external_windows_release_deferred(VkDeviceSize offset, VkDeviceSize bytes) { + if (!bytes) return; + const std::uint64_t ticket = context ? context->submitted_retire_ticket() + 1 : 0; + std::lock_guard lock(external_windows_mutex); + drain_deferred_external_frees_locked(); + deferred_external_frees.push_back({ticket, offset, bytes}); + } + + void collect_staged_shadow_readbacks(const ShadowPages& s, + const std::pair* ranges, std::size_t count, + const std::uint8_t* only, std::vector& arena_out, + std::map>& ext_out) const { + if (!arena.staged || !count) return; + const auto arena_lo = reinterpret_cast(arena.mapped); + const auto arena_hi = arena_lo + static_cast(arena.size); + const bool check_ext = external_windows.staged(); + s.for_each_target_range(ranges, count, only, [&](const std::uint8_t* ptr, std::size_t len) { + const auto dst = reinterpret_cast(ptr); + if (arena.mapped && dst >= arena_lo && dst < arena_hi && len <= arena_hi - dst) { + const VkDeviceSize off = static_cast(dst - arena_lo); + arena_out.push_back({off, off, static_cast(len)}); + return; + } + if (check_ext) { + std::size_t slot = 0; + VkBufferCopy region{}; + if (external_windows.find_staged_range(ptr, len, slot, region)) ext_out[slot].push_back(region); + } + }); + } std::vector title_windows; std::atomic title_window_count{0}; // title_windows.size(), read without the mutex std::uint64_t title_window_bytes = 0; @@ -4535,7 +4828,7 @@ struct DeviceState { arena_release(window.shader_va, window.size, arena_window); } else { backing(arena.address + window.shader_va, window.size, window.start, false); - external_windows.free(*this, window.shader_va, window.size); + external_windows_free(window.shader_va, window.size); } } } @@ -4687,8 +4980,7 @@ struct DeviceState { if (arena_allocate(size, kTitleWindowAlign, offset, arena_window)) { mapped = arena_host(offset, size); } else if (leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows); - stream_windows() && external_windows.allocate(*this, size, offset, mapped)) { - external_window_made.store(true, std::memory_order_release); + stream_windows() && external_windows_allocate(size, offset, mapped)) { } else { ++title_window_refusals; log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory has no window; window KiB:", @@ -4723,7 +5015,7 @@ struct DeviceState { arena_release(window.shader_va, window.size, arena_window); } else { backing(arena.address + window.shader_va, window.size, window.start, false); - external_windows.free(*this, window.shader_va, window.size); + external_windows_free(window.shader_va, window.size); } } @@ -4961,6 +5253,20 @@ struct DeviceState { // Each shadow takes all the ranges over it in one call, in address order (batches can overlap), and // decides which of its pages are held once for all of them (ShadowPages::write_back). std::vector> over; + if (arena.staged) { + std::vector readbacks; + std::map> ext_readbacks; + for (const ShadowPagesPtr& s : shadows) { + over.clear(); + for (const auto& [begin, end] : finished) + if (end > s->first() && begin < s->last()) + over.push_back({static_cast(begin), static_cast(end)}); + if (!over.empty()) + collect_staged_shadow_readbacks(*s, over.data(), over.size(), nullptr, readbacks, + ext_readbacks); + } + sync_retired_readbacks_to_host(readbacks, ext_readbacks); + } for (const ShadowPagesPtr& s : shadows) { over.clear(); for (const auto& [begin, end] : finished) @@ -4993,18 +5299,19 @@ struct DeviceState { // the same bytes instead of asking for a second mapping. // True when `va` is in a pool (out = its shader VA, or 0 when nothing could back the run). title_window_mutex // held. - bool resolve_pool_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { + bool resolve_pool_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out, bool has_mapping = false) { leonida::title_gpu_views::Range view{}; if (!leonida::title_gpu_views::view_at(static_cast(va), 1, view)) return false; const auto want = std::max(bytes, 1); - const auto unbacked = [&] { + const auto unbacked = [&](const char* reason) { + if (has_mapping) return false; // fall back to existing shorter mapping (e.g. root-view 64 KiB probe) out = 0; ++unbacked_requests; - note_unbacked("stream pool", va, bytes); + note_unbacked(reason, 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(); + if (want > view.size - offset) return unbacked("stream pool (bounds)"); // 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)); @@ -5014,7 +5321,7 @@ struct DeviceState { 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(); + if (!readable_page(source)) return unbacked("stream pool (unreadable)"); 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 = @@ -5023,7 +5330,7 @@ struct DeviceState { leonida::TitleWindowRange extent{}; if (!leonida::title_pool_extent(source - offset, pool_end, source, run_end, kTitleWindowAlign, kPoolExtentMax, extent)) - return unbacked(); + return unbacked("stream pool (no extent)"); 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); @@ -5035,21 +5342,28 @@ struct DeviceState { 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(); + unbacked("stream pool (clip)"); + if (want > std::min(extent.size - (source - extent.start), run_end - source)) { + if (reuse() || + cover_pool_request(source, twin_view, extent.start, request_end, source - offset, pool_end, out)) + return true; + // The committed readable run at `source` is shorter than `want` (e.g., a root view probed with + // kRootViewBytes = 64 KiB near the end of a committed stream-pool block). Still map the valid committed + // extent so root views get a real GPU pointer instead of 0; V#s with a declared length > room still + // enforce `room < bytes` in vsharp_address(). + if (extent.size == 0 || source < extent.start || source >= extent.start + extent.size) + return unbacked("stream pool (short)"); + } 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 (!shader) return reuse() || unbacked("stream pool (no window)"); if (!aliases.add_twin(extent.start, twin_start, extent.size, shader)) { if (!geometry_copy) drop_title_window(shader); - return reuse() || unbacked(); + return reuse() || unbacked("stream pool (add_twin)"); } pool_spans.push_back({extent.start, twin_start, shader, extent.size, geometry_copy}); pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); @@ -5149,7 +5463,7 @@ struct DeviceState { std::uint64_t host = 0, room = 0; if (geometry.cap() && geometry.lookup(arena.address + at, host, room)) return true; if (external_window_made.load(std::memory_order_acquire)) { - std::lock_guard lock(title_window_mutex); + std::lock_guard lock(external_windows_mutex); if (external_windows.lookup(arena.address + at, host, room)) return true; } if (context && !(i == 0 && buffers_checked) && context->knows_buffer_va(at)) return true; @@ -5217,7 +5531,7 @@ struct DeviceState { 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 (resolve_pool_memory(va, bytes, out, has_mapping)) return true; if (has_mapping) { out = made; return true; @@ -5525,6 +5839,7 @@ struct DeviceState { note_unbacked_arena(va, size); return Landing::refused; } + arena_mark_dirty(va, size); return Landing::landed; } @@ -5592,7 +5907,10 @@ struct DeviceState { if (!table) return; // Slots the title wrote in its own backing of this heap, if it gave the heap one. aliases.pull_descriptors(table, std::size_t(end - table_va)); - if (sampler) return; // S# words describe sampling state. They have no buffer address to translate. + if (sampler) { + arena_mark_dirty(table_va, end - table_va); + return; // S# words describe sampling state. They have no buffer address to translate. + } if (tsharp_index_words) refresh_tsharp_index_words(table, end - table_va); for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { auto* words = reinterpret_cast(table + (at - table_va)); @@ -5615,6 +5933,7 @@ struct DeviceState { // retries it - a counter whose backing arrives later stays with no records until the title rewrites it. if (at + kDescriptorSize <= end) fix_vsharp(words + 4, VsharpPath::table); } + arena_mark_dirty(table_va, end - table_va); } // The table slots scan_title_table wrote null in place (the layer's heaps have no separate GPU copy), by arena @@ -6067,6 +6386,13 @@ struct DeviceState { std::uint32_t sparse_memory_types = 0; // arena.buffer memoryTypeBits when sparse leonida::ArenaBacking backing; bool memory_type_known = false; + VkBuffer staging_buffer = VK_NULL_HANDLE; + VkDeviceMemory staging_memory = VK_NULL_HANDLE; + std::uint32_t staging_memory_type = 0; + bool staged = false; + leonida::ArenaStaging staging; + std::vector last_upload; // guarded by VulkanContext::tracker_mutex_ during execute_now + std::uint8_t* mapped = nullptr; VkDeviceAddress address = 0; VkDeviceSize size = 0; VkDeviceSize first = 0; // the first offset handed out: below it are the null region and kArenaReserved @@ -6087,6 +6413,75 @@ struct DeviceState { std::uint64_t allocations = 0, failures = 0; } arena; + void arena_mark_dirty(VkDeviceSize offset, VkDeviceSize bytes) { + if (arena.staged && bytes) arena.staging.mark(offset, bytes); + } + + void arena_mark_dirty_ptr(const void* ptr, std::size_t bytes) { + if (!arena.staged || !bytes || !ptr) return; + if (arena.mapped) { + const auto addr = reinterpret_cast(ptr); + const auto base = reinterpret_cast(arena.mapped); + if (addr >= base) { + const std::uintptr_t off = addr - base; + if (off < arena.size) { + arena.staging.mark(static_cast(off), + static_cast(std::min( + bytes, static_cast(arena.size) - off))); + return; + } + } + } + external_windows.mark_dirty_ptr(ptr, bytes); + } + + static void shadow_mark_dirty(void* ctx, const void* ptr, std::size_t bytes) { + static_cast(ctx)->arena_mark_dirty_ptr(ptr, bytes); + } + + bool sync_arena_to_host(std::vector& copies) { + if (!arena.staged || !context || copies.empty()) return true; + arena.staging.subtract_dirty(copies); + if (copies.empty()) return true; + if (!context->copy_buffer_sync(arena.buffer, arena.staging_buffer, copies, info.queue, info.queue_family)) + return false; + arena.staging.note_readback(copies); + return true; + } + + // Batches arena + external window readbacks for already-retired GPU submissions into ONE copy submission on the + // dedicated DMA copy queue (when available), avoiding stalls behind active graphics/compute work on info.queue. + bool sync_retired_readbacks_to_host(std::vector& arena_copies, + std::map>& ext_readbacks) { + if (!arena.staged || !context) return true; + std::vector batches; + batches.reserve(1 + ext_readbacks.size()); + bool has_arena = false; + if (!arena_copies.empty()) { + arena.staging.subtract_dirty(arena_copies); + if (!arena_copies.empty()) { + batches.push_back({arena.buffer, arena.staging_buffer, arena_copies}); + has_arena = true; + } + } + std::vector ext_slots; + if (!ext_readbacks.empty()) + external_windows.collect_host_readbacks(ext_readbacks, batches, ext_slots); + if (batches.empty()) return true; + if (!context->copy_buffers_sync(batches, readback_queue_handle(), readback_queue_family())) + return false; + if (has_arena) arena.staging.note_readback(arena_copies); + if (!ext_slots.empty()) external_windows.note_host_readbacks(ext_slots, ext_readbacks); + return true; + } + + bool sync_arena_to_host(VkDeviceSize offset, VkDeviceSize bytes) { + if (!arena.staged || !context || !bytes || offset >= arena.size) return true; + const VkDeviceSize clamped = std::min(bytes, arena.size - offset); + std::vector copies{{offset, offset, clamped}}; + return sync_arena_to_host(copies); + } + std::uint32_t sparse_buffer_memory_types = 0; bool sparse_image_tiles = false; bool sparse_unbind_zero_page = false; @@ -8066,6 +8461,27 @@ struct DeviceState { arena.use_peak[arena_heap] * mib, arena.use_peak[arena_window] * mib, (unsigned long long)arena.allocations, (unsigned long long)arena.failures, arena.blocks.count(), arena.blocks.largest().size * mib, arena.blocks.free_bytes() * mib); + if (arena.staged) { + const auto st = arena.staging.stats(); + std::fprintf(stderr, + "[rt] d3d12: GPU address arena staging (DEVICE_LOCAL VRAM): %llu flushes (%llu regions, %.1f " + "MiB uploaded), %llu readbacks (%llu regions, %.1f MiB read back)\n", + static_cast(st.flushes), static_cast(st.regions), + double(st.bytes) * mib, static_cast(st.readbacks), + static_cast(st.readback_regions), double(st.readback_bytes) * mib); + if (external_windows.staged()) { + const auto est = external_windows.staging_stats(); + if (est.flushes || est.readbacks) + std::fprintf(stderr, + "[rt] d3d12: overflow VRAM slabs staging: %llu flushes (%llu regions, %.1f MiB " + "uploaded), %llu readbacks (%llu regions, %.1f MiB read back)\n", + static_cast(est.flushes), + static_cast(est.regions), double(est.bytes) * mib, + static_cast(est.readbacks), + static_cast(est.readback_regions), + double(est.readback_bytes) * mib); + } + } } void report_title_memory() { { @@ -8340,7 +8756,8 @@ struct DeviceState { // (fix_vsharp). A slot fixed again because a change touched it is always resolved anew. // `out`: where the fixed slot goes, the heap's copy by default; for a heap read in place, its page's home in the // page mirror (filter_heap_page, refilter_slot). - void fix_console_slot(ConsoleHeap& heap, std::size_t slot, bool answers = false, std::uint8_t* out = nullptr) { + void fix_console_slot(ConsoleHeap& heap, std::size_t slot, bool answers = false, std::uint8_t* out = nullptr, + bool mark_dirty = true) { std::uint32_t w[kDescriptorSize / 4]; std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); bool vsharp = false; @@ -8415,7 +8832,9 @@ struct DeviceState { std::memset(w, 0, 16); } } - std::memcpy(out ? out : heap.copy + slot * kDescriptorSize, w, kDescriptorSize); + auto* const dst = out ? out : heap.copy + slot * kDescriptorSize; + std::memcpy(dst, w, kDescriptorSize); + if (mark_dirty) arena_mark_dirty_ptr(dst, kDescriptorSize); if (heap.resource_heap) { if (vsharp) for (unsigned half = 0; half < 2; ++half) @@ -8499,8 +8918,10 @@ struct DeviceState { const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); if (!heap.resource_heap) { std::memcpy(heap.copy + offset, heap.input + offset, end - offset); + arena_mark_dirty_ptr(heap.copy + offset, end - offset); return; } + std::size_t dirty_lo = end, dirty_hi = 0; for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; at += kDescriptorSize) { const std::size_t slot = at / kDescriptorSize; @@ -8516,6 +8937,8 @@ struct DeviceState { std::uint32_t w3 = 0; std::memcpy(&w3, heap.previous + at + 12, sizeof(w3)); const bool is_buffer_vsharp = !(w3 >> 30); + if (at < dirty_lo) dirty_lo = at; + dirty_hi = at + kDescriptorSize; if (heap.fix_over && !is_buffer_vsharp) { std::memset(heap.copy + at, 0, kDescriptorSize); heap.records.clear(slot); @@ -8527,8 +8950,9 @@ struct DeviceState { continue; } heap.retry[slot] = 0; - fix_console_slot(heap, slot, true); + fix_console_slot(heap, slot, true, nullptr, /*mark_dirty=*/false); } + if (dirty_hi > dirty_lo) arena_mark_dirty_ptr(heap.copy + dirty_lo, dirty_hi - dirty_lo); } // The slots LEONIDA_CONSOLE_FIX_US deferred at an earlier submission (null in the copy meanwhile): fixed first, @@ -9994,7 +10418,7 @@ struct DeviceState { // a heap's first refresh, which has no records yet. void refresh_console_heap(ConsoleHeap& heap, const std::vector* changes) { // console_heap_mutex held if (heap.imported) return; // directly imported sampler heap - if (heap.gpu >= 0) return refresh_console_heap_gpu(heap); + if (heap.gpu >= 0) return refresh_console_heap_gpu(heap, changes); // Read in place: filtered as the page mirror fills its pages (refresh_page_mirror, before this); what the filter // left (V#s the mirror does not hold, T#s to bind) is finished here, outside the mirror's lock. if (heap.in_place) { @@ -10011,6 +10435,7 @@ struct DeviceState { heap.copied += heap.pages->refresh(); heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { std::memset(heap.copy + offset, 0, bytes); + arena_mark_dirty_ptr(heap.copy + offset, bytes); std::memset(heap.previous + offset, 0, bytes); if (heap.resource_heap) { const auto first = std::uint32_t(offset / kDescriptorSize); @@ -10462,7 +10887,7 @@ struct DeviceState { // fetch and the pass's writes stay on the card. The CPU never writes the copy then (the pass does); [input | // previous] stay in host memory. No room in the arena: the import, as without the switch. bool in_arena = false; - if (resource_heap && geometry.cap() && heap_gpu && console_heap_gpu_enabled() && console_heap_arena_enabled() && + if (resource_heap && heap_gpu && console_heap_gpu_enabled() && console_heap_arena_enabled() && bytes <= SIZE_MAX / 2) { VkDeviceSize offset = 0; const VkDeviceSize size = bytes + guard; @@ -10537,6 +10962,7 @@ struct DeviceState { if (!heap->copy) return false; } std::memset(heap->copy, 0, std::size_t(bytes + heap->guard)); + arena_mark_dirty_ptr(heap->copy, std::size_t(bytes + heap->guard)); if (!heap->input) { heap->mirror.assign(std::size_t(bytes), 0); heap->made.assign(std::size_t(bytes), 0); @@ -10550,23 +10976,25 @@ struct DeviceState { // Changes are kept from now on, before the first refresh writes a record. slot_records_live.store(true, std::memory_order_release); } - heap->pages = make_shadow_pages(reinterpret_cast(static_cast(console_va)), - heap->input, std::size_t(bytes)); } shader_va = heap->shader_va; if (shader_va != console_va) console_heap_ranges().add(console_va, bytes, shader_va); const bool imported = heap->imported; const VkDeviceSize guarded = heap->guard; arena_guard_bytes.fetch_add(guarded, std::memory_order_relaxed); - // The pass copies a T#'s words as the title wrote them; it does not write the index word the library's modules - // read (tsharp_index_words), so such a library's heaps are fixed on the CPU, which writes it. if (heap_gpu && console_heap_gpu_enabled() && heap->scratch && resource_heap && !imported) { - if (!tsharp_index_words) - attach_console_heap_gpu(*heap); - else - log_once("LEONIDA_CONSOLE_HEAP_GPU: the pass does not write the T# index word the shaders read; console " - "descriptor heaps are fixed on the CPU; slots", - int(std::min(bytes / kDescriptorSize, INT_MAX))); + attach_console_heap_gpu(*heap); + } + if (!imported) { + // With tsharp_index_words on the GPU pass, ShadowPages copies raw title bytes into heap->mirror so + // unchanged slots in heap->input (which holds patched T# index words) are never clobbered on page re-copy. + std::uint8_t* shadow_dst = heap->input; + if (heap->gpu >= 0 && tsharp_index_words) { + heap->mirror.assign(std::size_t(bytes), 0); + shadow_dst = heap->mirror.data(); + } + heap->pages = make_shadow_pages(reinterpret_cast(static_cast(console_va)), + shadow_dst, std::size_t(bytes)); } { std::lock_guard lock(console_heap_mutex); @@ -11155,15 +11583,65 @@ struct DeviceState { }(); return on; } + void fix_gpu_tsharp_slot(ConsoleHeap& heap, std::size_t slot, std::vector& queued) { + using Records = leonida::ConsoleHeapSlotRecords; + leonida::gfx10::ImageWords words; + std::memcpy(words.data(), heap.previous + slot * kDescriptorSize, sizeof(words)); + if (!(words[3] >> 30)) { + if (heap.records.state(slot, 0) != Records::none) heap.records.clear(slot); + return; + } + if (!leonida::gfx10::is_image(words)) { + ++heap.images[unsigned(TitleImage::not_tsharp)]; + if (heap.records.state(slot, 0) != Records::none) heap.records.clear(slot); + std::memcpy(heap.input + slot * kDescriptorSize, words.data(), kDescriptorSize); + queued.push_back(std::uint32_t(slot) | leonida::ConsoleHeapGpu::kZeroFirst); + return; + } + const char* why = nullptr; + std::uint32_t index_word = 0; + std::uint64_t bound_address = 0; + const TitleImage result = bind_title_image(*this, words, &why, &index_word, &bound_address); + const bool unbound = result == TitleImage::unknown || result == TitleImage::refused; + const bool waiting_index = !unbound && result != TitleImage::not_tsharp && index_word == 0; + if (unbound) { + note_refused_tsharp(heap, slot * kDescriptorSize, words, why); + ++heap.refused_reasons[why ? why : "?"]; + } + ++heap.images[unsigned(result)]; + if (result == TitleImage::not_tsharp) { + if (heap.records.state(slot, 0) != Records::none) heap.records.clear(slot); + std::memcpy(heap.input + slot * kDescriptorSize, words.data(), kDescriptorSize); + queued.push_back(std::uint32_t(slot) | leonida::ConsoleHeapGpu::kZeroFirst); + return; + } + leonida::gfx10::Image image{}; + leonida::gfx10::decode(words, image); + const std::uint64_t texture_address = bound_address ? bound_address : tsharp_texture_key(image.address); + const Records::State texture = (!unbound && !waiting_index) ? Records::texture_bound + : (unbound && (why == kTsharpArrayFull || why == kTsharpStorageFull)) + ? Records::texture_waiting_room + : Records::texture_waiting; + if (unbound || waiting_index) ++heap.texture_waits; + else if (Records::is_waiting(heap.records.state(slot, 0)) && heap.records.base(slot, 0) == texture_address) + ++heap.texture_refills; + words[leonida::gfx10::kTsharpIndexDword] = (unbound || waiting_index) ? 0u : index_word; + std::memcpy(heap.input + slot * kDescriptorSize, words.data(), kDescriptorSize); + heap.records.set_texture(slot, texture, texture_address); + queued.push_back(std::uint32_t(slot)); + } + std::vector tsharp_jobs; // console_heap_mutex - void refresh_console_heap_gpu(ConsoleHeap& heap) { // console_heap_mutex held - const bool tsharps_off_thread = tsharps_off_thread_enabled() && gpu_resolver; + void refresh_console_heap_gpu(ConsoleHeap& heap, + const std::vector* changes) { // console_heap_mutex held + const bool tsharps_off_thread = !tsharp_index_words && tsharps_off_thread_enabled() && gpu_resolver; static const std::uint64_t budget_us = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_FIX_US", text, sizeof(text)); return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 4000ull; }(); using clock = std::chrono::steady_clock; + using Records = leonida::ConsoleHeapSlotRecords; const auto ms = [](clock::time_point a, clock::time_point b) { return std::chrono::duration(b - a).count(); }; @@ -11171,13 +11649,17 @@ struct DeviceState { heap.copied += heap.pages->refresh(); auto& queued = gpu_queue_scratch; queued.clear(); - // The tracker zeroed these in `input` too: the pass copies the zeros. + const bool separate_mirror = !heap.mirror.empty(); + const std::uint8_t* raw = separate_mirror ? heap.mirror.data() : heap.input; + // The tracker zeroed these in `raw` too: mirror into `input` when separate, then queue. heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { std::memset(heap.previous + offset, 0, bytes); + if (separate_mirror) std::memset(heap.input + offset, 0, bytes); for (std::size_t slot = offset / kDescriptorSize; slot * kDescriptorSize < offset + bytes && slot < heap.retry.size(); ++slot) { heap.retry[slot] = 0; set_vsharp_bit(heap, slot, false); + if (tsharp_index_words && heap.records.state(slot, 0) != Records::none) heap.records.clear(slot); queued.push_back(std::uint32_t(slot)); } }); @@ -11188,19 +11670,26 @@ struct DeviceState { const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; at += kDescriptorSize) { - if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; - std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); + if (!std::memcmp(heap.previous + at, raw + at, kDescriptorSize)) continue; + std::memcpy(heap.previous + at, raw + at, kDescriptorSize); note_changed_slot(heap, heap.previous + at); const std::size_t slot = at / kDescriptorSize; heap.gpu_high = std::max(heap.gpu_high, std::uint32_t(slot + 1)); const auto* w = reinterpret_cast(heap.previous + at); if (!(w[3] >> 30)) { + if (separate_mirror) std::memcpy(heap.input + at, raw + at, kDescriptorSize); queued.push_back(std::uint32_t(slot)); set_vsharp_bit(heap, slot, w[2] || w[6]); heap.retry[slot] = 0; + if (tsharp_index_words && heap.records.state(slot, 0) != Records::none) heap.records.clear(slot); continue; } set_vsharp_bit(heap, slot, false); + if (tsharp_index_words) { + heap.retry[slot] = 0; + fix_gpu_tsharp_slot(heap, slot, queued); + continue; + } if (tsharps_off_thread) { // Only decoded here: words that are no T# are zeroed by the pass; a T# goes to the resolver to // be registered (shaders find it by its words; until then they get the fallback). @@ -11232,6 +11721,17 @@ struct DeviceState { } } }); + if (tsharp_index_words && changes && !changes->empty()) { + std::vector tex_changes; + for (const auto& c : *changes) + if (c.kind == leonida::SlotChange::texture_gone || c.kind == leonida::SlotChange::texture_added || + c.kind == leonida::SlotChange::texture_room) + tex_changes.push_back(c); + if (!tex_changes.empty()) { + heap.records.touched(tex_changes.data(), tex_changes.size(), slot_change_scratch); + for (const std::uint32_t slot : slot_change_scratch) fix_gpu_tsharp_slot(heap, slot, queued); + } + } heap_gpu->queue(heap.gpu, queued.begin(), queued.end()); heap.gpu_queued += queued.size(); if (!tsharp_jobs.empty()) { @@ -11291,7 +11791,7 @@ struct DeviceState { leonida::gfx10::Buffer desc{}; const bool copy_geometry = leonida::gfx10::decode(words, desc) && (span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words)); - return vsharp_address(base, span, leonida::TitleVaAliases::table_view, false, copy_geometry); + return vsharp_address(base, span, leonida::TitleVaAliases::table_view, !geometry.cap(), copy_geometry); } // vsharp_address's backed(): [offset, offset + bytes) of the shader VAs is a live allocation or geometry copy. @@ -11475,6 +11975,7 @@ struct DeviceState { header->table = table - arena.address; std::atomic_thread_fence(std::memory_order_release); header->magic = ag::magic(); // last: a shader that sees it sees the rest + arena_mark_dirty(ag::kGuardHeader, ag::kGuardEnd - ag::kGuardHeader); std::fprintf(stderr, "[rt] d3d12: address guard on (LEONIDA_ADDRESS_GUARD): %llu KiB page table, header at " "heap_base + 0x%llx; shaders translated with --address-guard read 0 from memory nothing " "backs and drop their stores there\n", @@ -11567,10 +12068,14 @@ struct DeviceState { guard.overflow_logged, guard.table->blocks_used()); } } + const auto now = std::chrono::steady_clock::now(); + if (arena.staged) { + if (now - guard.logged < std::chrono::seconds(1)) return; + sync_arena_to_host(ag::kGuardHeader, sizeof(ag::AddressGuardHeader)); + } auto* header = reinterpret_cast(arena_host(ag::kGuardHeader, sizeof(ag::AddressGuardHeader))); if (!header) return; const std::uint32_t refused = std::atomic_ref(header->refused).load(std::memory_order_relaxed); - const auto now = std::chrono::steady_clock::now(); if (refused != guard.refused_logged && now - guard.logged >= std::chrono::seconds(1)) { guard.logged = now; std::fprintf(stderr, "[rt] d3d12: address guard: %u access(es) refused so far (+%u), the last at heap " @@ -11581,6 +12086,8 @@ struct DeviceState { static_cast(guard.updates), static_cast(guard.words_written)); guard.refused_logged = refused; + } else if (arena.staged) { + guard.logged = now; } } @@ -14283,11 +14790,21 @@ struct ProbeApiWrite { UINT count; const char* what; ~ProbeApiWrite() { + state.arena_mark_dirty_ptr(reinterpret_cast(ptr), std::size_t(count) * kDescriptorSize); state.probe_api(ptr, count, what); state.probe_view(what, ptr, count); } }; +struct ArenaDirtySlot { + DeviceState& state; + SIZE_T ptr; + UINT count = 1; + ~ArenaDirtySlot() { + state.arena_mark_dirty_ptr(reinterpret_cast(ptr), std::size_t(count) * kDescriptorSize); + } +}; + struct ConsoleDescriptorHeapDesc { D3D12_DESCRIPTOR_HEAP_DESC desc{}; std::uint64_t address = 0; @@ -14348,6 +14865,7 @@ class DescriptorHeap final in_arena_ = true; cpu_ = device.arena_host(arena_offset_, bytes + guard_); std::memset(cpu_, 0, std::size_t(bytes + guard_)); + device.arena_mark_dirty(arena_offset_, bytes + guard_); if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { std::lock_guard lock(device.visible_heap_mutex); device.visible_heaps[arena_offset_] = {arena_offset_ + bytes, desc.Type}; @@ -14510,7 +15028,7 @@ class Resource final device_.context->remove_resource(id()); // Before the memory goes to the deferred queue: no submission copies into it after this. if (shadow_) device_.remove_shadow(shadow_); - if (shadow_ && !in_arena_) device_.remove_copy_target(shadow_); + if (shadow_ && !in_arena_ && !in_external_window_) device_.remove_copy_target(shadow_); if (host_import_) { // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole // lifetime, and a title may free them right after releasing the resource. So the memory is not left to @@ -14530,6 +15048,11 @@ class Resource final if (in_arena_) device_.arena_release(arena_offset_, desc_.Width, shadow_ ? DeviceState::arena_window : DeviceState::arena_buffer); + if (in_external_window_) device_.external_windows_release_deferred(arena_offset_, desc_.Width); + if (heap_range_ && device_.arena.staged) { + for (std::uint32_t refs = arena_map_refs_.exchange(0, std::memory_order_relaxed); refs > 0; --refs) + device_.arena.staging.untrack_mapped(va_, desc_.Width); + } if (pooled_image_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::pooled_title_image, pooled_image_.release()); else if (image_ && !sparse_image_) @@ -14646,6 +15169,7 @@ class Resource final arena_offset_, DeviceState::arena_buffer)) { in_arena_ = true; std::memset(device_.arena_host(arena_offset_, desc_.Width), 0, std::size_t(desc_.Width)); + device_.arena_mark_dirty(arena_offset_, desc_.Width); va_ = arena_offset_; binding.va = va_; binding.buffer = device_.arena.buffer; @@ -15049,6 +15573,36 @@ class Resource final alias_title_va(arena_offset_); return S_OK; } + if (device_.arena_ready() && device_.external_windows.staged()) { + VkDeviceSize ext_offset = 0; + std::uint8_t* ext_mapped = nullptr; + VkBuffer ext_buffer = VK_NULL_HANDLE; + VkDeviceSize ext_buf_offset = 0; + VkDeviceAddress ext_bda = 0; + leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows); + if (device_.external_windows_allocate(desc_.Width, ext_offset, ext_mapped, &ext_buffer, &ext_buf_offset, + &ext_bda)) { + in_external_window_ = true; + arena_offset_ = ext_offset; + shadow_ = ext_mapped; + device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); + mapped_ = address; + va_ = reinterpret_cast(address); + buffer_va_ = gpu_va_ = ext_bda; + device_.log_va("title-placed buffer (VRAM slab shadow)", va_, desc_.Width); + leonida::ResourceBinding binding{}; + binding.buffer = ext_buffer; + binding.indirect_arguments = true; + binding.buffer_offset = ext_buf_offset; + binding.size = desc_.Width; + binding.host = shadow_; + binding.va = va_; + index_shader_backing(buffer_va_); + device_.context->add_resource(id(), binding); + alias_title_va(ext_offset); + return S_OK; + } + } log_once("a title-placed shadow buffer does not fit the GPU address arena (raise LEONIDA_ARENA_MB), so it " "has its own memory; size in KiB:", int(desc_.Width / 1024)); @@ -15200,6 +15754,7 @@ class Resource final heap_range_ = std::move(heap_range); if (cpu_visible()) mapped_ = host; std::memset(host, 0, std::size_t(desc_.Width)); // a fresh place reads as zeroed + device_.arena_mark_dirty(va_, desc_.Width); leonida::ResourceBinding binding{}; binding.size = desc_.Width; binding.buffer = device_.arena.buffer; @@ -16075,6 +16630,17 @@ class Resource final } if (!mapped_ || subresource != 0) return E_INVALIDARG; if (read && read->Begin < read->End && read->End > desc_.Width) return E_INVALIDARG; + if (device_.arena.staged && !host_import_ && !shadow_ && heap_range_) { + if (heap_.Type != D3D12_HEAP_TYPE_UPLOAD && (!read || read->End > read->Begin)) { + const VkDeviceSize begin = read ? static_cast(read->Begin) : 0; + const VkDeviceSize end = read ? static_cast(read->End) : desc_.Width; + if (end > begin) device_.sync_arena_to_host(va_ + begin, end - begin); + } + if (cpu_writable()) { + device_.arena.staging.track_mapped(va_, desc_.Width); + arena_map_refs_.fetch_add(1, std::memory_order_relaxed); + } + } if (data) *data = mapped_; return S_OK; } @@ -16126,6 +16692,17 @@ class Resource final // A texture the title placed: Unmap ends its CPU writes (the title's lock passes the range it wrote), so its // image is filled again before the next submission (TitleTexture). void STDMETHODCALLTYPE Unmap(UINT sub, const D3D12_RANGE* written) override { + if (device_.arena.staged && !image_ && !host_import_ && !shadow_ && heap_range_ && mapped_ && sub == 0 && + cpu_writable()) { + if (!written || written->End > written->Begin) { + const VkDeviceSize begin = written ? std::min(written->Begin, desc_.Width) : 0; + const VkDeviceSize end = written ? std::min(written->End, desc_.Width) : desc_.Width; + if (end > begin) device_.arena_mark_dirty(va_ + begin, end - begin); + } + std::uint32_t refs = arena_map_refs_.load(std::memory_order_relaxed); + while (refs > 0 && !arena_map_refs_.compare_exchange_weak(refs, refs - 1, std::memory_order_relaxed)) {} + if (refs > 0) device_.arena.staging.untrack_mapped(va_, desc_.Width); + } if (image_ && title_address_ && title_texture_ && (!written || written->End > written->Begin)) device_.title_texture_unmapped(this, reinterpret_cast(title_address_)); if (!title_linear_) return; @@ -16537,9 +17114,11 @@ class Resource final D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; // a buffer's console VA, or a slot-133 texture's title address VkDeviceSize arena_offset_ = 0; bool in_arena_ = false; + bool in_external_window_ = false; // A placed buffer's heap range, held as a D3D12 placed resource holds its heap: the app may release the heap // first, and the range must not go to another allocation while this buffer lives. std::shared_ptr heap_range_; + std::atomic arena_map_refs_{0}; }; // One immutable, zeroed BC image per exact view shape (zeroed on the host, or by the first shader submission). It has @@ -16795,8 +17374,10 @@ bool DeviceState::materialize_table(std::uint64_t address, std::uint32_t slots) const auto refreshed = std::min(end-address, std::uint64_t(kViewScanLimit)*kDescriptorSize); std::uint8_t* const table = arena_host(address, end-address); // a live heap's table: one allocation if (!table) return false; - if (end-address>refreshed) + if (end-address>refreshed) { leonida::title_va_aliases().pull_descriptors(table+refreshed,std::size_t(end-address-refreshed)); + arena_mark_dirty(address + refreshed, end - address - refreshed); + } for (auto at=address; atvk; const VkDevice dev = device_.info.device; if (pipeline_.pipeline) vk.vkDestroyPipeline(dev, pipeline_.pipeline, nullptr); - if (pipeline_.layout) vk.vkDestroyPipelineLayout(dev, pipeline_.layout, nullptr); + if (pipeline_.layout && owns_compute_layout_) vk.vkDestroyPipelineLayout(dev, pipeline_.layout, nullptr); if (module_) vk.vkDestroyShaderModule(dev, module_, nullptr); if (graphics_.pipeline) vk.vkDestroyPipeline(dev, graphics_.pipeline, nullptr); for (const auto& [unbound, built] : variants_) vk.vkDestroyPipeline(dev, built, nullptr); - if (graphics_.masked_layout) vk.vkDestroyPipelineLayout(dev, graphics_.masked_layout, nullptr); - if (graphics_.layout) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); + if (graphics_.masked_layout && owns_graphics_layouts_) + vk.vkDestroyPipelineLayout(dev, graphics_.masked_layout, nullptr); + if (graphics_.layout && owns_graphics_layouts_) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); modules_.clear(); if (code_bytes_) device_.arena_release(code_base_, code_bytes_, DeviceState::arena_shader); --live_pipeline_state_count; @@ -18944,29 +19528,20 @@ class PipelineState final for (const Stage& stage : stages) if (stage.bit != VK_SHADER_STAGE_GEOMETRY_BIT || device_.info.features.geometryShader) graphics_.push_stages |= stage.bit; - const VkPushConstantRange push{graphics_.push_stages, 0, sizeof(leonida::ShaderUserData)}; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout_info.pushConstantRangeCount = 1; - layout_info.pPushConstantRanges = &push; - VkDescriptorSetLayout set0_layout = VK_NULL_HANDLE; - if (uses_bindless) { - set0_layout = device_.bindless->layout(); - layout_info.setLayoutCount = 1; - layout_info.pSetLayouts = &set0_layout; - graphics_.bindless_set = device_.bindless->set(); - } - if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &graphics_.layout) != VK_SUCCESS) return E_FAIL; + if (uses_bindless) graphics_.bindless_set = device_.bindless->set(); + graphics_.layout = device_.shared_pipeline_layout(graphics_.push_stages, sizeof(leonida::ShaderUserData), + uses_bindless); + if (!graphics_.layout) return E_FAIL; + owns_graphics_layouts_ = false; // Separate 148-byte push-constant layout for on-demand OMSetSampleMaskX masked twin variants. // Depth-only PSOs (!has_fragment_), PostDepthCoverage shaders, and devices with maxPushConstantsSize < 148 // keep masked_layout null. const std::uint32_t push_limit = device_.info.max_push_constants_size; if (has_fragment_ && !fragment_post_depth && (push_limit == 0 || push_limit >= leonida::kPixelMaskPushBytes)) { - const VkPushConstantRange masked_push{graphics_.push_stages, 0, leonida::kPixelMaskPushBytes}; - VkPipelineLayoutCreateInfo masked_layout_info = layout_info; - masked_layout_info.pPushConstantRanges = &masked_push; - if (vk.vkCreatePipelineLayout(dev, &masked_layout_info, nullptr, &graphics_.masked_layout) != VK_SUCCESS) - return E_FAIL; + graphics_.masked_layout = + device_.shared_pipeline_layout(graphics_.push_stages, leonida::kPixelMaskPushBytes, uses_bindless); + if (!graphics_.masked_layout) return E_FAIL; } // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. @@ -19033,6 +19608,7 @@ class PipelineState final if (!device_.arena_allocate(code_stage->fssm.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; std::memcpy(device_.arena_host(offset, code_stage->fssm.size()), code_stage->fssm.data(), code_stage->fssm.size()); + device_.arena_mark_dirty(offset, code_stage->fssm.size()); code_bytes_ = code_stage->fssm.size(); code_base_ = offset; graphics_.code_base = offset; @@ -19135,39 +19711,36 @@ class PipelineState final // SHADER-309: a module over the device's maxComputeSharedMemorySize is invalid usage that spirv-val accepts // and RADV dies on (#1721); some drivers report 32768. Refuse it here instead of creating the pipeline. if (entry->lds_bytes) { - const auto& dinfo = device_.info; - if (const auto get_props = reinterpret_cast( - dinfo.get_instance_proc ? dinfo.get_instance_proc(dinfo.instance, "vkGetPhysicalDeviceProperties") - : nullptr)) { - VkPhysicalDeviceProperties props{}; - get_props(dinfo.physical, &props); - if (entry->lds_bytes > props.limits.maxComputeSharedMemorySize) { - std::fprintf(stderr, - "[rt] d3d12: %s declares %u bytes of workgroup memory, over the device's " - "maxComputeSharedMemorySize %u\n", - entry->name.c_str(), unsigned(entry->lds_bytes), - unsigned(props.limits.maxComputeSharedMemorySize)); - return stream_unsupported("compute shader exceeds shared memory limit"); + std::uint32_t max_shared = device_.max_compute_shared_memory_size; + if (!max_shared) { + const auto& dinfo = device_.info; + if (const auto get_props = reinterpret_cast( + dinfo.get_instance_proc ? dinfo.get_instance_proc(dinfo.instance, "vkGetPhysicalDeviceProperties") + : nullptr)) { + VkPhysicalDeviceProperties props{}; + get_props(dinfo.physical, &props); + max_shared = props.limits.maxComputeSharedMemorySize; } } + if (max_shared && entry->lds_bytes > max_shared) { + std::fprintf(stderr, + "[rt] d3d12: %s declares %u bytes of workgroup memory, over the device's " + "maxComputeSharedMemorySize %u\n", + entry->name.c_str(), unsigned(entry->lds_bytes), unsigned(max_shared)); + return stream_unsupported("compute shader exceeds shared memory limit"); + } } const std::size_t spirv_bytes = library->spirv_bytes(*entry); if (!spirv_bytes) { std::fprintf(stderr, "[rt] d3d12: %s.spv is missing\n", entry->name.c_str()); return E_FAIL; } - const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout_info.pushConstantRangeCount = 1; - layout_info.pPushConstantRanges = &push; - VkDescriptorSetLayout set0_layout = VK_NULL_HANDLE; - if (entry->binding_count) { - set0_layout = device_.bindless->layout(); - layout_info.setLayoutCount = 1; - layout_info.pSetLayouts = &set0_layout; - pipeline_.bindless_set = device_.bindless->set(); - } - if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; + const bool with_bindless = entry->binding_count != 0; + if (with_bindless) pipeline_.bindless_set = device_.bindless->set(); + pipeline_.layout = device_.shared_pipeline_layout(VK_SHADER_STAGE_COMPUTE_BIT, + sizeof(leonida::ShaderUserData), with_bindless); + if (!pipeline_.layout) return E_FAIL; + owns_compute_layout_ = false; compute_entry_ = entry; stage_bytes_ = spirv_bytes; pipeline_.estimate = leonida::large_module_estimate(spirv_bytes); @@ -19219,6 +19792,7 @@ class PipelineState final const auto& code = program.bytes; if (!device_.arena_allocate(code.size(), 256, code_base_, DeviceState::arena_shader)) return E_OUTOFMEMORY; std::memcpy(device_.arena_host(code_base_, code.size()), code.data(), code.size()); + device_.arena_mark_dirty(code_base_, code.size()); code_bytes_ = code.size(); pipeline_.code_base = code_base_; } @@ -19936,6 +20510,8 @@ class PipelineState final DeviceState& device_; leonida::ComputePipeline pipeline_; leonida::GraphicsPipeline graphics_; + bool owns_compute_layout_ = true; + bool owns_graphics_layouts_ = true; Recipe recipe_; const leonida::ShaderEntry* compute_entry_ = nullptr; // compute: the translated shader build_compute reads bool compute_failed_ = false; // compute: could not be built; not retried @@ -21879,6 +22455,7 @@ class Device final state_.info.max_push_constants_size = props.limits.maxPushConstantsSize; state_.info.push_constants_need_fallback = (state_.info.max_push_constants_size < 144); } + state_.max_compute_shared_memory_size = props.limits.maxComputeSharedMemorySize; // The counts D3D12 offers with no outputs are the target-independent-rasterization ones: 1, 4, 8 // and 16 (ForcedSampleCount is 0, 1, 4, 8 or 16; DirectX-Specs VulkanOn12.md "Sample-frequency MSAA // with no render targets bound": a driver reports at least 0b11101). 2x is not one of them, though @@ -22658,6 +23235,10 @@ class Device final } } state_.create_page_mirror(sparse_aliasing && info.features.sparseResidencyBuffer); + // Eagerly seed the shared Vulkan pipeline cache while device setup is still single-threaded so the + // 800+ MiB vkCreatePipelineCache load never races with concurrent slot 57/67 pipeline creation under Wine. + if (state_.context && state_.context->loaded() && !compile_helper::build_host) + state_.pipeline_cache(); } // Set 0 of every translated shader that declares bindings: images, samplers and the descriptor hash table @@ -23060,10 +23641,15 @@ class Device final return false; } } + // RT-ARENA-DEVICE-LOCAL-STAGED: LEONIDA_DEVICE_LOCAL_ARENA=auto|1|0. + char stage_env[16] = {}; + const DWORD stage_env_len = GetEnvironmentVariableA("LEONIDA_DEVICE_LOCAL_ARENA", stage_env, sizeof(stage_env)); + const char* stage_arg = (stage_env_len > 0 && stage_env_len < sizeof(stage_env)) ? stage_env : nullptr; + const leonida::ArenaStagingMode stage_mode = leonida::parse_arena_staging_mode(stage_arg); // With Resizable BAR, keep the arena where its buffer may still use DEVICE_LOCAL | HOST_VISIBLE memory // A large buffer can exclude that type, or require more bytes than its heap can hold. (A sparse arena's memory - // comes in blocks, which any heap holds.) - if (!sparse && leonida::resizable_bar(state_.memory)) { + // comes in blocks, which any heap holds.) Skip shrinking when LEONIDA_DEVICE_LOCAL_ARENA=1 forces staging. + if (!sparse && stage_mode != leonida::ArenaStagingMode::force && leonida::resizable_bar(state_.memory)) { const VkDeviceSize asked = info.size; const VkDeviceSize fitted = leonida::device_local_arena_bytes(asked, [&](VkDeviceSize bytes) { if (bytes == asked) return leonida::device_local_arena_fits(state_.memory, requirements); @@ -23182,30 +23768,96 @@ class Device final return false; } } else { - { - leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena); - arena.memory = state_.allocate(requirements, leonida::kArenaRequiredMemory, - leonida::kArenaPreferredMemory, nullptr, true, &arena.memory_type); - } void* mapped = nullptr; - if (!arena.memory || - vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS || - vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { - // Without an arena every buffer keeps its own memory; a leftover handle would make them addressable - // with heap base 0, so their VAs would be raw device addresses above 4 GiB. - vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); - if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); - arena.buffer = VK_NULL_HANDLE; - arena.memory = VK_NULL_HANDLE; - return false; + if (stage_mode != leonida::ArenaStagingMode::off) { + VkBufferCreateInfo stage_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + stage_info.size = info.size; + stage_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + state_.share(stage_info); + VkBuffer candidate_staging = VK_NULL_HANDLE; + if (vk.vkCreateBuffer(state_.info.device, &stage_info, nullptr, &candidate_staging) == VK_SUCCESS) { + VkMemoryRequirements stage_reqs{}; + vk.vkGetBufferMemoryRequirements(state_.info.device, candidate_staging, &stage_reqs); + const leonida::ArenaStagingDecision decision = + leonida::decide_arena_staging(stage_arg, state_.memory, requirements, stage_reqs); + if (decision.use_staged) { + VkMemoryRequirements dev_reqs = requirements; + dev_reqs.memoryTypeBits = 1u << decision.device_memory_type; + VkMemoryRequirements host_reqs = stage_reqs; + host_reqs.memoryTypeBits = 1u << decision.host_memory_type; + { + leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena); + arena.memory = state_.allocate(dev_reqs, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, nullptr, + true, &arena.memory_type); + } + { + leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::upload); + arena.staging_memory = + arena.memory + ? state_.allocate(host_reqs, leonida::kArenaRequiredMemory, 0, nullptr, false, + &arena.staging_memory_type) + : VK_NULL_HANDLE; + } + if (arena.memory && arena.staging_memory && + vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) == VK_SUCCESS && + vk.vkBindBufferMemory(state_.info.device, candidate_staging, arena.staging_memory, 0) == + VK_SUCCESS && + vk.vkMapMemory(state_.info.device, arena.staging_memory, 0, VK_WHOLE_SIZE, 0, &mapped) == + VK_SUCCESS) { + arena.staging_buffer = candidate_staging; + candidate_staging = VK_NULL_HANDLE; + arena.staged = true; + arena.staging.init(info.size); + } else { + if (arena.staging_memory) + vk.vkFreeMemory(state_.info.device, arena.staging_memory, nullptr); + if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); + arena.staging_memory = VK_NULL_HANDLE; + arena.memory = VK_NULL_HANDLE; + mapped = nullptr; + } + } + if (candidate_staging) vk.vkDestroyBuffer(state_.info.device, candidate_staging, nullptr); + } + } + if (!arena.staged) { + { + leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena); + arena.memory = state_.allocate(requirements, leonida::kArenaRequiredMemory, + leonida::kArenaPreferredMemory, nullptr, true, &arena.memory_type); + } + if (!arena.memory || + vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS || + vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { + // Without an arena every buffer keeps its own memory; a leftover handle would make them addressable + // with heap base 0, so their VAs would be raw device addresses above 4 GiB. + vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); + if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); + arena.buffer = VK_NULL_HANDLE; + arena.memory = VK_NULL_HANDLE; + return false; + } } arena.memory_type_known = true; - arena.backing.init_fixed(info.size, arena.memory, static_cast(mapped)); + arena.mapped = static_cast(mapped); + arena.backing.init_fixed(info.size, arena.staged ? arena.staging_memory : arena.memory, arena.mapped); + } + if (arena.staged) { + std::fprintf(stderr, + "[rt] d3d12: GPU address arena: %llu MiB in DEVICE_LOCAL VRAM (type %u, heap %u) with " + "HOST_VISIBLE staging mirror (type %u, heap %u) (LEONIDA_ARENA_MB %s, " + "LEONIDA_DEVICE_LOCAL_ARENA %s)\n", + static_cast(info.size >> 20), unsigned(arena.memory_type), + unsigned(state_.memory.memoryTypes[arena.memory_type].heapIndex), + unsigned(arena.staging_memory_type), + unsigned(state_.memory.memoryTypes[arena.staging_memory_type].heapIndex), + set ? text : "unset", stage_arg ? stage_arg : "auto"); + } else { + std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB of address range (LEONIDA_ARENA_MB %s), %s\n", + static_cast(info.size >> 20), set ? text : "unset", + sparse ? "sparse: memory bound in 2 MiB blocks as allocations need it" + : "one allocation behind all of it"); } - std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB of address range (LEONIDA_ARENA_MB %s), %s\n", - static_cast(info.size >> 20), set ? text : "unset", - sparse ? "sparse: memory bound in 2 MiB blocks as allocations need it" - : "one allocation behind all of it"); // LEONIDA_ARENA_NULL_MB= (for compute-on boots): the first n MiB of the arena, at heap_base + 0, are zeroed // and never handed out, and the zero page and the quad indices move above them. A translated shader whose // address arithmetic starts from a null base (a scalar or flat load the translator does not bounds-check) @@ -23248,6 +23900,37 @@ class Device final [base](std::uint32_t index) { return base + index; }); } } + state_.arena_mark_dirty(0, null_bytes + kArenaReserved); + if (arena.staged) { + state_.external_windows.set_staged(true); + state_.context->set_arena_upload( + [st = &state_](VkCommandBuffer cmd) -> bool { + if (!st->arena.staged) return false; + auto& vk = st->context->vk; + bool any = false; + if (st->arena.staging.drain(st->arena.last_upload)) { + vk.vkCmdCopyBuffer(cmd, st->arena.staging_buffer, st->arena.buffer, + static_cast(st->arena.last_upload.size()), + st->arena.last_upload.data()); + any = true; + } + if (st->external_windows.record_uploads(cmd, vk)) any = true; + if (!any) return false; + VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + vk.vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, + 1, &barrier, 0, nullptr, 0, nullptr); + return true; + }, + [st = &state_](bool submitted) { + if (!st->arena.last_upload.empty()) { + if (!submitted) st->arena.staging.requeue(st->arena.last_upload); + st->arena.last_upload.clear(); + } + st->external_windows.commit_uploads(submitted); + }); + } if (null_bytes) std::fprintf(stderr, "[rt] d3d12: arena null region: the first %llu MiB at heap_base are zeroed and never " "allocated (LEONIDA_ARENA_NULL_MB)\n", @@ -23329,6 +24012,7 @@ class Device final return ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(at), host + (at - va), SIZE_T(n), &copied) && copied == n; })) return false; + st->arena_mark_dirty(lease->offset, bytes); result={va,bytes,st->arena.buffer,lease->offset,std::move(lease)}; return true; }); @@ -23414,6 +24098,7 @@ class Device final } if (state_.context) { if (state_.gpu_resolver) state_.gpu_resolver->halt(); // it calls into the geometry copies + state_.context->set_arena_upload(nullptr, nullptr); ShadowPages::gpu_copy = nullptr; state_.geometry.release(state_); state_.external_windows.release(state_); @@ -23422,6 +24107,13 @@ class Device final } state_.staging_queue.reset(); // they use the context state_.staging_copy_queue.reset(); + if (state_.context) { + std::lock_guard lock(state_.shared_layout_mutex); + for (const auto& [key, layout] : state_.shared_pipeline_layouts) + if (layout && state_.context->vk.vkDestroyPipelineLayout) + state_.context->vk.vkDestroyPipelineLayout(state_.info.device, layout, nullptr); + state_.shared_pipeline_layouts.clear(); + } 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); @@ -23434,8 +24126,11 @@ class Device final state_.destroy_address_guard(); if (state_.context) state_.destroy_page_mirror(); if (state_.context && state_.arena.buffer) { + state_.context->set_arena_upload(nullptr, nullptr); leonida::fsdraw::forget_arena(&state_); auto& vk = state_.context->vk; + if (state_.arena.staging_buffer) vk.vkDestroyBuffer(state_.info.device, state_.arena.staging_buffer, nullptr); + if (state_.arena.staging_memory) vk.vkFreeMemory(state_.info.device, state_.arena.staging_memory, nullptr); vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); { std::lock_guard lock(state_.arena.mutex); @@ -23605,6 +24300,7 @@ class Device final SIZE_T ptr; bool unordered; ~PlacedWrite() { + state.arena_mark_dirty_ptr(reinterpret_cast(ptr), kDescriptorSize); if (rt::compute_probe::enabled()) state.probe_api(ptr, 1, unordered ? "slot71" : "slot70"); } } probe{state_, destination.ptr, unordered}; @@ -23625,6 +24321,7 @@ class Device final // slot a null view (zeros); every reason is counted and logged once per format and layout. bool write_placed_texture_view(const std::uint32_t* resource_words, const std::uint32_t* view_words, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { + ArenaDirtySlot dirty_slot{state_, destination.ptr}; std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); rt::xg_xs::ResourceDesc d{}; std::memcpy(&d, resource_words, sizeof(d)); @@ -23659,6 +24356,7 @@ class Device final // Slot 71 names GPU-writable memory. Its contents belong to the existing image. bool write_placed_texture_uav(const std::uint32_t* words, const std::uint32_t* view, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE dest) { + ArenaDirtySlot dirty_slot{state_, dest.ptr}; static const bool enabled = [] { const char* v = std::getenv("LEONIDA_PLACED_TEXTURE_UAV"); return !v || std::strcmp(v, "0"); @@ -27407,9 +28105,11 @@ class Device final ++s; s_at = 0; } else { - std::memmove(reinterpret_cast(destinations[d].ptr) + std::size_t(d_at) * step, + auto* dst = reinterpret_cast(destinations[d].ptr) + std::size_t(d_at) * step; + std::memmove(dst, reinterpret_cast(sources[s].ptr) + std::size_t(s_at++) * step, step); + state_.arena_mark_dirty_ptr(dst, step); state_.probe_api(destinations[d].ptr + SIZE_T(d_at++) * step, 1); // LOCAL DIAGNOSTIC } } @@ -27422,6 +28122,7 @@ class Device final const UINT step = descriptor_increment(type); std::memmove(reinterpret_cast(destination.ptr), reinterpret_cast(source.ptr), std::size_t(count) * step); + state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), std::size_t(count) * step); state_.probe_api(destination.ptr, count); // LOCAL DIAGNOSTIC state_.probe_view("CopyDescriptorsSimple", destination.ptr, count); } @@ -27931,9 +28632,13 @@ class Device final d3d12_trace::record("ID3D12Device::CreateSampler"); if (!destination.ptr) return; std::memset(reinterpret_cast(destination.ptr), 0, kSamplerDescriptorSize); - if (!desc) return; + if (!desc) { + state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), kSamplerDescriptorSize); + return; + } const leonida::gfx10::SamplerWords words = leonida::gfx10::encode(sampler_descriptor(*desc, &state_)); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); + state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), kSamplerDescriptorSize); state_.bind_sampler(words); } @@ -27952,6 +28657,7 @@ class Device final const leonida::gfx10::SamplerWords words = sampler2_words(*desc); std::memset(reinterpret_cast(destination.ptr), 0, kSamplerDescriptorSize); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); + state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), kSamplerDescriptorSize); state_.bind_sampler(words); } @@ -29960,6 +30666,7 @@ class Device final !g::multisampled(image.type)) { state_.remember_sample(words,{const_cast(&resource),image,view_format,channels_format}); std::memcpy(reinterpret_cast(destination.ptr),words.data(),sizeof(words)); + state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), sizeof(words)); return; } const auto bound = const_cast(resource).bound_image(); @@ -29983,6 +30690,7 @@ class Device final } // The CPU UAV used by ClearUnorderedAccessView is independent of set 0. std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); + state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), sizeof(words)); resource.note_shader_view(leonida::effective_min_mip(image.first_mip, g::image_min_lod(words))); } @@ -31143,9 +31851,10 @@ bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t b if (!device || !out) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; - const Device* d = Device::from(real); + Device* d = Device::from(real); // Any arena address (a diagnostic's): read under the backing's shared lock, refused where no memory is. if (!d || !d->state().arena_ready()) return false; + if (d->state().arena.staged && bytes) d->state().sync_arena_to_host(va, bytes); return d->state().arena.backing.with_host(va, bytes, [&](const std::uint8_t* host) { std::memcpy(out, host, bytes); }); } diff --git a/runtime/src/arena_staging.h b/runtime/src/arena_staging.h new file mode 100644 index 0000000000..fd57842969 --- /dev/null +++ b/runtime/src/arena_staging.h @@ -0,0 +1,319 @@ +#pragma once + +// Staged DEVICE_LOCAL GPU address arena (RT-ARENA-DEVICE-LOCAL-STAGED): +// +// On GPUs without Resizable BAR (where the DEVICE_LOCAL | HOST_VISIBLE BAR1 heap is <= 256 MiB), a host-visible +// 4 GiB GPU address arena cannot fit in BAR1 and falls back to HOST_VISIBLE system RAM over PCIe (~15-25 GB/s +// instead of GDDR VRAM bandwidth). Putting `arena.buffer` in DEVICE_LOCAL-only VRAM and pairing it with a +// HOST_VISIBLE | HOST_COHERENT staging buffer keeps shader reads in VRAM while CPU writers (ShadowPages, console +// descriptor heaps, shader uploads, write_arena_value, placed buffers) continue writing to `arena.mapped`. +// +// Dirty writes are tracked at exact byte granularity (not rounded up to 4 KiB pages) so flushing a 256-byte +// ShadowPages piece, a 32-byte descriptor slot, or an 8-byte list value never clobbers a neighboring GPU write +// on the same page. +// +// Controlled by LEONIDA_DEVICE_LOCAL_ARENA: +// - unset / "auto" : enabled automatically when the arena cannot fit in DEVICE_LOCAL | HOST_VISIBLE memory +// and a DEVICE_LOCAL memory type plus a HOST_VISIBLE staging type both fit; +// - "1" / "on" : forced on whenever DEVICE_LOCAL + HOST_VISIBLE types fit (for testing on ReBAR / iGPUs); +// - "0" / "off" : disabled (keep the single host-visible arena). +// +// Pure header depending only on Vulkan headers and the C++ standard library, so it builds and tests natively on +// Linux, macOS, and Windows (arena_staging_test). + +#include "arena_size.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +enum class ArenaStagingMode { auto_mode, force, off }; + +inline ArenaStagingMode parse_arena_staging_mode(const char* env) { + if (!env || !*env) return ArenaStagingMode::auto_mode; + auto eq_ci = [](const char* a, const char* b) { + while (*a && *b) { + if (std::tolower(static_cast(*a)) != std::tolower(static_cast(*b))) + return false; + ++a; + ++b; + } + return *a == 0 && *b == 0; + }; + if (eq_ci(env, "0") || eq_ci(env, "off") || eq_ci(env, "false")) return ArenaStagingMode::off; + if (eq_ci(env, "1") || eq_ci(env, "on") || eq_ci(env, "true")) return ArenaStagingMode::force; + return ArenaStagingMode::auto_mode; +} + +struct ArenaStagingDecision { + bool use_staged = false; + std::uint32_t device_memory_type = UINT32_MAX; + std::uint32_t host_memory_type = UINT32_MAX; +}; + +// Picks whether the arena should use a DEVICE_LOCAL buffer + HOST_VISIBLE staging buffer, and which Vulkan memory +// types each buffer should use. `host_requirements` may differ from `device_requirements` (the staging buffer only +// needs TRANSFER_SRC | TRANSFER_DST). +inline ArenaStagingDecision decide_arena_staging(const char* env, const VkPhysicalDeviceMemoryProperties& memory, + const VkMemoryRequirements& device_requirements, + const VkMemoryRequirements& host_requirements) { + ArenaStagingDecision out{}; + const ArenaStagingMode mode = parse_arena_staging_mode(env); + if (mode == ArenaStagingMode::off) return out; + if (mode == ArenaStagingMode::auto_mode && device_local_arena_fits(memory, device_requirements)) return out; + + auto dev_order = memory_type_order(memory, device_requirements.memoryTypeBits, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, device_requirements.size); + if (dev_order.empty()) return out; + // Prefer pure DEVICE_LOCAL (not HOST_VISIBLE) so the arena lives in full VRAM, never in a 256 MiB BAR1 window. + std::stable_partition(dev_order.begin(), dev_order.end(), [&](std::uint32_t t) { + return (memory.memoryTypes[t].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0; + }); + if (mode == ArenaStagingMode::auto_mode && + (memory.memoryTypes[dev_order.front()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) + return out; + + auto host_order = memory_type_order(memory, host_requirements.memoryTypeBits, kArenaRequiredMemory, 0, + host_requirements.size); + if (host_order.empty()) return out; + // Keep the staging mirror out of DEVICE_LOCAL (do not consume BAR1 or VRAM for the host mirror). + std::stable_partition(host_order.begin(), host_order.end(), [&](std::uint32_t t) { + return (memory.memoryTypes[t].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0; + }); + + out.use_staged = true; + out.device_memory_type = dev_order.front(); + out.host_memory_type = host_order.front(); + return out; +} + +inline ArenaStagingDecision decide_arena_staging(const char* env, const VkPhysicalDeviceMemoryProperties& memory, + const VkMemoryRequirements& requirements) { + return decide_arena_staging(env, memory, requirements, requirements); +} + +class ArenaStaging { +public: + struct Span { + VkDeviceSize begin = 0; + VkDeviceSize end = 0; + }; + + struct Stats { + std::uint64_t flushes = 0; + std::uint64_t regions = 0; + std::uint64_t bytes = 0; + std::uint64_t readbacks = 0; + std::uint64_t readback_regions = 0; + std::uint64_t readback_bytes = 0; + }; + + void init(VkDeviceSize size) { + std::lock_guard lock(mutex_); + size_ = size; + pending_.clear(); + mapped_.clear(); + compact_at_ = kCompactThreshold; + stats_ = {}; + has_dirty_.store(false, std::memory_order_release); + has_mapped_.store(false, std::memory_order_release); + } + + void reset() { init(0); } + + bool active() const { return size_ != 0; } + VkDeviceSize size() const { return size_; } + + // Records [offset, offset + bytes) as modified in the host staging buffer and needing upload to DEVICE_LOCAL VRAM. + void mark(VkDeviceSize offset, VkDeviceSize bytes) { + if (!bytes || offset >= size_) return; + const VkDeviceSize end = offset + std::min(bytes, size_ - offset); + if (end <= offset) return; + std::lock_guard lock(mutex_); + if (!pending_.empty()) { + Span& back = pending_.back(); + if (offset <= back.end && end >= back.begin) { + if (offset < back.begin) back.begin = offset; + if (end > back.end) back.end = end; + has_dirty_.store(true, std::memory_order_release); + return; + } + } + pending_.push_back({offset, end}); + if (pending_.size() >= compact_at_) { + coalesce_locked(pending_); + compact_at_ = std::max(kCompactThreshold, pending_.size() * 2); + } + has_dirty_.store(true, std::memory_order_release); + } + + // Tracks a CPU-writable buffer range that the application keeps persistently Map()ed in the arena. + void track_mapped(VkDeviceSize offset, VkDeviceSize bytes) { + if (!bytes || offset >= size_) return; + const VkDeviceSize end = offset + std::min(bytes, size_ - offset); + if (end <= offset) return; + std::lock_guard lock(mutex_); + for (auto& m : mapped_) { + if (m.begin == offset && m.end == end) { + ++m.refs; + return; + } + } + mapped_.push_back({offset, end, 1}); + has_mapped_.store(true, std::memory_order_release); + } + + void untrack_mapped(VkDeviceSize offset, VkDeviceSize bytes) { + if (!bytes || offset >= size_) return; + const VkDeviceSize end = offset + std::min(bytes, size_ - offset); + std::lock_guard lock(mutex_); + for (auto it = mapped_.begin(); it != mapped_.end(); ++it) { + if (it->begin == offset && it->end == end) { + if (--it->refs == 0) mapped_.erase(it); + break; + } + } + has_mapped_.store(!mapped_.empty(), std::memory_order_release); + } + + // Drains all dirty ranges (plus any actively mapped writable ranges) into coalesced VkBufferCopy regions. + bool drain(std::vector& out) { + out.clear(); + if (!has_dirty_.load(std::memory_order_acquire) && !has_mapped_.load(std::memory_order_acquire)) return false; + std::vector local; + { + std::lock_guard lock(mutex_); + local.swap(pending_); + compact_at_ = kCompactThreshold; + has_dirty_.store(false, std::memory_order_release); + for (const auto& m : mapped_) local.push_back({m.begin, m.end}); + } + if (local.empty()) return false; + coalesce_locked(local); + out.reserve(local.size()); + std::uint64_t total_bytes = 0; + for (const Span& s : local) { + if (s.end <= s.begin) continue; + const VkDeviceSize len = s.end - s.begin; + out.push_back({s.begin, s.begin, len}); + total_bytes += len; + } + if (out.empty()) return false; + { + std::lock_guard lock(mutex_); + ++stats_.flushes; + stats_.regions += out.size(); + stats_.bytes += total_bytes; + } + return true; + } + + // Restores previously drained copies if vkQueueSubmit failed before reaching the GPU. + void requeue(const std::vector& copies) { + if (copies.empty()) return; + std::lock_guard lock(mutex_); + pending_.reserve(pending_.size() + copies.size()); + for (const VkBufferCopy& c : copies) { + if (!c.size || c.srcOffset >= size_) continue; + const VkDeviceSize end = c.srcOffset + std::min(c.size, size_ - c.srcOffset); + if (end > c.srcOffset) pending_.push_back({c.srcOffset, end}); + } + if (!pending_.empty()) { + coalesce_locked(pending_); + compact_at_ = std::max(kCompactThreshold, pending_.size() * 2); + has_dirty_.store(true, std::memory_order_release); + } + } + + // Removes any sub-ranges currently marked dirty (or actively mapped writable) from `readback` so a GPU->host + // readback copy never overwrites unflushed CPU writes in the host staging buffer. Coalesces `readback` as well. + void subtract_dirty(std::vector& readback) const { + if (readback.empty()) return; + std::vector req; + req.reserve(readback.size()); + for (const VkBufferCopy& c : readback) { + if (!c.size || c.srcOffset >= size_) continue; + const VkDeviceSize end = c.srcOffset + std::min(c.size, size_ - c.srcOffset); + if (end > c.srcOffset) req.push_back({c.srcOffset, end}); + } + coalesce_locked(req); + + std::vector dirty; + if (has_dirty_.load(std::memory_order_acquire) || has_mapped_.load(std::memory_order_acquire)) { + std::lock_guard lock(mutex_); + dirty = pending_; + for (const auto& m : mapped_) dirty.push_back({m.begin, m.end}); + } + coalesce_locked(dirty); + + readback.clear(); + std::size_t d = 0; + for (const Span& r : req) { + VkDeviceSize cur = r.begin; + while (d < dirty.size() && dirty[d].end <= cur) ++d; + for (std::size_t k = d; k < dirty.size() && dirty[k].begin < r.end; ++k) { + if (dirty[k].begin > cur) readback.push_back({cur, cur, dirty[k].begin - cur}); + cur = std::max(cur, dirty[k].end); + if (cur >= r.end) break; + } + if (cur < r.end) readback.push_back({cur, cur, r.end - cur}); + } + } + + void note_readback(const std::vector& copies) { + if (copies.empty()) return; + std::uint64_t bytes = 0; + for (const VkBufferCopy& c : copies) bytes += c.size; + std::lock_guard lock(mutex_); + ++stats_.readbacks; + stats_.readback_regions += copies.size(); + stats_.readback_bytes += bytes; + } + + Stats stats() const { + std::lock_guard lock(mutex_); + return stats_; + } + +private: + struct MappedRange { + VkDeviceSize begin = 0; + VkDeviceSize end = 0; + std::uint32_t refs = 0; + }; + + static constexpr std::size_t kCompactThreshold = 4096; + + static void coalesce_locked(std::vector& spans) { + if (spans.size() <= 1) return; + std::sort(spans.begin(), spans.end(), [](const Span& a, const Span& b) { + return a.begin < b.begin || (a.begin == b.begin && a.end < b.end); + }); + std::size_t out = 0; + for (std::size_t i = 1; i < spans.size(); ++i) { + if (spans[i].begin <= spans[out].end) { + if (spans[i].end > spans[out].end) spans[out].end = spans[i].end; + } else { + spans[++out] = spans[i]; + } + } + spans.resize(out + 1); + } + + VkDeviceSize size_ = 0; + mutable std::mutex mutex_; + std::vector pending_; + std::vector mapped_; + std::size_t compact_at_ = kCompactThreshold; + std::atomic has_dirty_{false}; + std::atomic has_mapped_{false}; + Stats stats_{}; +}; + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index db6c9ae26d..43f65dbcdc 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1358,6 +1358,10 @@ class VulkanContext { stop_profile_resolver(); // drain/join profile resolver before destroying idle query pools gpu_profile_.stop(); // after the fence callbacks and profile resolver that hold its recordings deletion_queue_.drain(UINT64_MAX, device_, vk); + if (readback_sem_) vk.vkDestroySemaphore(device_, readback_sem_, nullptr); + for (const auto& [fam, ch] : readback_channels_) + if (ch.pool) vk.vkDestroyCommandPool(device_, ch.pool, nullptr); + readback_channels_.clear(); for (const auto& [key, framebuffer] : resolve_framebuffers_) vk.vkDestroyFramebuffer(device_, framebuffer, nullptr); for (const auto& [key, pass] : resolve_passes_) vk.vkDestroyRenderPass(device_, pass, nullptr); @@ -2185,6 +2189,153 @@ class VulkanContext { prelude_commit_ = std::move(commit); } + // Staged DEVICE_LOCAL arena uploads (src/arena_staging.h): runs on every queue kind (including transfer-only + // queues) right before the prelude and command-list replay, under tracker_mutex_. Cross-queue timeline waits + // guarantee no other queue reads arena.buffer before a prior submission's dirty ranges finish copying. + void set_arena_upload(std::function record, std::function commit) { + arena_upload_record_ = std::move(record); + arena_upload_commit_ = std::move(commit); + } + + // Synchronous GPU->host buffer copy for staged DEVICE_LOCAL arena readbacks (write-back, readback Map, diagnostics). + // Uses a dedicated reusable command buffer + timeline semaphore guarded by readback_mutex_, holding submit_mutex_ + // ONLY around vkQueueSubmit so waiting on the copy never blocks another queue's submission. + struct BufferCopyBatch { + VkBuffer src = VK_NULL_HANDLE; + VkBuffer dst = VK_NULL_HANDLE; + std::span copies; + }; + + bool copy_buffers_sync(std::span batches, VkQueue queue, std::uint32_t queue_family, + std::uint64_t timeout_ns = 5'000'000'000ULL) { + bool any = false; + for (const auto& b : batches) { + if (!b.copies.empty()) { + if (!b.src || !b.dst) return false; + any = true; + } + } + if (!any) return true; + if (!loaded_ || is_device_lost() || !queue) return false; + std::lock_guard rb_lock(readback_mutex_); + if (readback_busy_) { + VkSemaphoreWaitInfo prev_wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; + prev_wait.semaphoreCount = 1; + prev_wait.pSemaphores = &readback_sem_; + prev_wait.pValues = &readback_ticket_; + const VkResult pwr = observe_result(vk.vkWaitSemaphores(device_, &prev_wait, timeout_ns), + "vkWaitSemaphores (arena readback drain)"); + if (pwr == VK_ERROR_DEVICE_LOST) mark_device_lost(); + if (pwr != VK_SUCCESS) return false; + readback_busy_ = false; + } + if (!readback_sem_) { + VkSemaphoreTypeCreateInfo type_info{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; + type_info.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; + type_info.initialValue = 0; + VkSemaphoreCreateInfo sem_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type_info}; + if (vk.vkCreateSemaphore(device_, &sem_info, nullptr, &readback_sem_) != VK_SUCCESS) { + readback_sem_ = VK_NULL_HANDLE; + return false; + } + } + auto& ch = readback_channels_[queue_family]; + if (!ch.pool) { + VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; + pool_info.queueFamilyIndex = queue_family; + if (vk.vkCreateCommandPool(device_, &pool_info, nullptr, &ch.pool) != VK_SUCCESS) { + ch.pool = VK_NULL_HANDLE; + return false; + } + VkCommandBufferAllocateInfo alloc{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + alloc.commandPool = ch.pool; + alloc.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + alloc.commandBufferCount = 1; + if (vk.vkAllocateCommandBuffers(device_, &alloc, &ch.cmd) != VK_SUCCESS) { + vk.vkDestroyCommandPool(device_, ch.pool, nullptr); + ch.pool = VK_NULL_HANDLE; + ch.cmd = VK_NULL_HANDLE; + return false; + } + } + if (vk.vkResetCommandBuffer(ch.cmd, 0) != VK_SUCCESS) return false; + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + if (vk.vkBeginCommandBuffer(ch.cmd, &begin) != VK_SUCCESS) return false; + VkMemoryBarrier pre{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + pre.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; + pre.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + vk.vkCmdPipelineBarrier(ch.cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, + 1, &pre, 0, nullptr, 0, nullptr); + for (const auto& b : batches) { + if (!b.copies.empty()) + vk.vkCmdCopyBuffer(ch.cmd, b.src, b.dst, std::uint32_t(b.copies.size()), b.copies.data()); + } + VkMemoryBarrier post{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + post.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + post.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + vk.vkCmdPipelineBarrier(ch.cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &post, + 0, nullptr, 0, nullptr); + if (vk.vkEndCommandBuffer(ch.cmd) != VK_SUCCESS) return false; + + VkSemaphore upload_wait_sem = VK_NULL_HANDLE; + std::uint64_t upload_wait_val = 0; + { + std::lock_guard lock(storage_mutex_); + if (arena_upload_semaphore_ && arena_upload_value_) { + upload_wait_sem = arena_upload_semaphore_; + upload_wait_val = arena_upload_value_; + } + } + const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; + const std::uint64_t target = readback_ticket_ + 1; + VkTimelineSemaphoreSubmitInfo ts{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; + if (upload_wait_sem) { + ts.waitSemaphoreValueCount = 1; + ts.pWaitSemaphoreValues = &upload_wait_val; + } + ts.signalSemaphoreValueCount = 1; + ts.pSignalSemaphoreValues = ⌖ + VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &ts}; + if (upload_wait_sem) { + submit.waitSemaphoreCount = 1; + submit.pWaitSemaphores = &upload_wait_sem; + submit.pWaitDstStageMask = &wait_stage; + } + submit.commandBufferCount = 1; + submit.pCommandBuffers = &ch.cmd; + submit.signalSemaphoreCount = 1; + submit.pSignalSemaphores = &readback_sem_; + VkResult sr = VK_SUCCESS; + { + std::lock_guard qlock(submit_mutex_); + sr = observe_result(vk.vkQueueSubmit(queue, 1, &submit, VK_NULL_HANDLE), + "vkQueueSubmit (arena readback)"); + } + if (sr == VK_ERROR_DEVICE_LOST) mark_device_lost(); + if (sr != VK_SUCCESS) return false; + readback_ticket_ = target; + readback_busy_ = true; + + VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; + wait.semaphoreCount = 1; + wait.pSemaphores = &readback_sem_; + wait.pValues = ⌖ + const VkResult wr = observe_result(vk.vkWaitSemaphores(device_, &wait, timeout_ns), + "vkWaitSemaphores (arena readback)"); + if (wr == VK_ERROR_DEVICE_LOST) mark_device_lost(); + if (wr == VK_SUCCESS) readback_busy_ = false; + return wr == VK_SUCCESS; + } + + bool copy_buffer_sync(VkBuffer src, VkBuffer dst, std::span copies, VkQueue queue, + std::uint32_t queue_family, std::uint64_t timeout_ns = 5'000'000'000ULL) { + if (copies.empty()) return true; + const BufferCopyBatch batch{src, dst, copies}; + return copy_buffers_sync(std::span(&batch, 1), queue, queue_family, timeout_ns); + } + void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); bindless_prepare_ = std::move(prepare); @@ -2743,6 +2894,20 @@ class VulkanContext { VkSemaphore prelude_semaphore_ = VK_NULL_HANDLE; // the queue whose submission recorded the last prelude std::uint64_t prelude_value_ = 0; std::uint64_t prelude_version_ = 0; + std::function arena_upload_record_; + std::function arena_upload_commit_; + VkSemaphore arena_upload_semaphore_ = VK_NULL_HANDLE; + std::uint64_t arena_upload_value_ = 0; + std::uint64_t arena_upload_version_ = 0; + std::mutex readback_mutex_; + struct ReadbackChannel { + VkCommandPool pool = VK_NULL_HANDLE; + VkCommandBuffer cmd = VK_NULL_HANDLE; + }; + std::unordered_map readback_channels_; + VkSemaphore readback_sem_ = VK_NULL_HANDLE; + std::uint64_t readback_ticket_ = 0; + bool readback_busy_ = false; std::unique_ptr depth24_; std::unique_ptr scratch_; // copies staged through a buffer (depth <-> colour) std::function bindless_commit_; @@ -4162,6 +4327,16 @@ class VulkanQueue : private QueueHolds::Holder { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &filled, 0, nullptr, 0, nullptr); } + const bool arena_uploaded = context_.arena_upload_record_ && context_.arena_upload_record_(command_buffer); + { + std::lock_guard lock(context_.storage_mutex_); + if (context_.arena_upload_semaphore_ && context_.arena_upload_semaphore_ != progress_ && + context_.arena_upload_version_ != arena_upload_seen_) { + exec_waits_.push_back(context_.arena_upload_semaphore_); + exec_wait_values_.push_back(context_.arena_upload_value_); + } + arena_upload_seen_ = context_.arena_upload_version_; + } const bool prelude = !skip_shader_prep && context_.prelude_record_ && context_.prelude_record_(command_buffer); static const bool cross_wait_empty = [] { const char* v = std::getenv("LEONIDA_PRELUDE_QUEUE_WAIT"); @@ -4204,6 +4379,16 @@ class VulkanQueue : private QueueHolds::Holder { ++context_.bindless_upload_version_; bindless_upload_seen_ = context_.bindless_upload_version_; } + if (arena_uploaded) { + if (submitted) { + std::lock_guard lock(context_.storage_mutex_); + context_.arena_upload_semaphore_ = progress_; + context_.arena_upload_value_ = submitted_; + ++context_.arena_upload_version_; + arena_upload_seen_ = context_.arena_upload_version_; + } + if (context_.arena_upload_commit_) context_.arena_upload_commit_(submitted); + } if (prelude) { if (submitted) { std::lock_guard lock(context_.storage_mutex_); @@ -4601,6 +4786,16 @@ class VulkanQueue : private QueueHolds::Holder { auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED); detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker); } + const bool arena_uploaded = context_.arena_upload_record_ && context_.arena_upload_record_(command_buffer); + { + std::lock_guard lock(context_.storage_mutex_); + if (context_.arena_upload_semaphore_ && context_.arena_upload_semaphore_ != progress_ && + context_.arena_upload_version_ != arena_upload_seen_) { + exec_waits_.push_back(context_.arena_upload_semaphore_); + exec_wait_values_.push_back(context_.arena_upload_value_); + } + arena_upload_seen_ = context_.arena_upload_version_; + } // The prelude (set_prelude): recorded here, after the set's upload and before the lists, and in either case // after the last submission of another queue that recorded one (its pass writes what these lists read, and // a pass here must not overtake it). @@ -4750,6 +4945,16 @@ class VulkanQueue : private QueueHolds::Holder { ++context_.bindless_upload_version_; bindless_upload_seen_ = context_.bindless_upload_version_; } + if (arena_uploaded) { + if (submitted) { + std::lock_guard lock(context_.storage_mutex_); + context_.arena_upload_semaphore_ = progress_; + context_.arena_upload_value_ = submitted_; + ++context_.arena_upload_version_; + arena_upload_seen_ = context_.arena_upload_version_; + } + if (context_.arena_upload_commit_) context_.arena_upload_commit_(submitted); + } if (prelude) { if (submitted) { std::lock_guard lock(context_.storage_mutex_); @@ -6292,6 +6497,7 @@ class VulkanQueue : private QueueHolds::Holder { VkSemaphore title_upload_sem_seen_ = VK_NULL_HANDLE; std::uint64_t title_upload_seen_ = 0; // the staged title-upload timeline value this queue has waited for std::uint64_t pending_wait_vis_seq_ = 0; // CPU Fence::Signal visibility epoch carried from signal-only wait + std::uint64_t arena_upload_seen_ = 0; // the arena_upload_version_ this queue has waited for std::uint64_t prelude_seen_ = 0; // the prelude_version_ this queue has waited for (or recorded) ReplayFunctions cached_replay_{}; std::uint64_t cached_replay_version_ = 0; diff --git a/runtime/test/arena_staging_test.cpp b/runtime/test/arena_staging_test.cpp new file mode 100644 index 0000000000..e0a3ac5fdd --- /dev/null +++ b/runtime/test/arena_staging_test.cpp @@ -0,0 +1,286 @@ +// Staged DEVICE_LOCAL GPU address arena (src/arena_staging.h) without a GPU: policy selection across ReBAR, +// BAR-restricted discrete GPU (256 MiB BAR1), and UMA/iGPU memory layouts, plus exact byte-range dirty tracking, +// coalescing, requeue, persistent mapped ranges, and readback subtraction. +// No game data. +#include "../src/arena_staging.h" + +#include +#include + +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ + } while (0) + +using namespace leonida; + +namespace { + +constexpr VkDeviceSize MiB = kArenaMiB; +constexpr VkDeviceSize GiB = 1024 * MiB; + +// Synthetic RTX 3090 without Resizable BAR: +// heap 0: 24 GiB DEVICE_LOCAL (type 0: DEVICE_LOCAL) +// heap 1: 48 GiB system RAM (type 1: HOST_VISIBLE | HOST_COHERENT, type 2: + HOST_CACHED) +// heap 2: 246 MiB BAR1 (type 3: DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT) +VkPhysicalDeviceMemoryProperties make_non_rebar_discrete() { + VkPhysicalDeviceMemoryProperties m{}; + m.memoryHeapCount = 3; + m.memoryHeaps[0] = {24 * GiB, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + m.memoryHeaps[1] = {48 * GiB, 0}; + m.memoryHeaps[2] = {246 * MiB, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + m.memoryTypeCount = 4; + m.memoryTypes[0] = {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0}; + m.memoryTypes[1] = {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 1}; + m.memoryTypes[2] = {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | + VK_MEMORY_PROPERTY_HOST_CACHED_BIT, + 1}; + m.memoryTypes[3] = {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + 2}; + return m; +} + +// Synthetic ReBAR discrete GPU: +// heap 0: 24 GiB DEVICE_LOCAL (type 0: DEVICE_LOCAL, type 2: DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT) +// heap 1: 48 GiB system RAM (type 1: HOST_VISIBLE | HOST_COHERENT) +VkPhysicalDeviceMemoryProperties make_rebar_discrete() { + VkPhysicalDeviceMemoryProperties m{}; + m.memoryHeapCount = 2; + m.memoryHeaps[0] = {24 * GiB, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + m.memoryHeaps[1] = {48 * GiB, 0}; + m.memoryTypeCount = 3; + m.memoryTypes[0] = {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0}; + m.memoryTypes[1] = {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 1}; + m.memoryTypes[2] = {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + 0}; + return m; +} + +// Synthetic UMA / integrated GPU (or software driver): single DEVICE_LOCAL | HOST_VISIBLE heap. +VkPhysicalDeviceMemoryProperties make_uma() { + VkPhysicalDeviceMemoryProperties m{}; + m.memoryHeapCount = 1; + m.memoryHeaps[0] = {16 * GiB, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + m.memoryTypeCount = 1; + m.memoryTypes[0] = {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + 0}; + return m; +} + +int test_mode_parsing() { + CHECK(parse_arena_staging_mode(nullptr) == ArenaStagingMode::auto_mode); + CHECK(parse_arena_staging_mode("") == ArenaStagingMode::auto_mode); + CHECK(parse_arena_staging_mode("auto") == ArenaStagingMode::auto_mode); + CHECK(parse_arena_staging_mode("AUTO") == ArenaStagingMode::auto_mode); + CHECK(parse_arena_staging_mode("1") == ArenaStagingMode::force); + CHECK(parse_arena_staging_mode("on") == ArenaStagingMode::force); + CHECK(parse_arena_staging_mode("TRUE") == ArenaStagingMode::force); + CHECK(parse_arena_staging_mode("0") == ArenaStagingMode::off); + CHECK(parse_arena_staging_mode("off") == ArenaStagingMode::off); + CHECK(parse_arena_staging_mode("False") == ArenaStagingMode::off); + CHECK(parse_arena_staging_mode("weird") == ArenaStagingMode::auto_mode); + return 0; +} + +int test_decision_policy() { + const VkMemoryRequirements req_4g{4094 * MiB, 256, 0xffffffffu}; + const VkMemoryRequirements req_128m{128 * MiB, 256, 0xffffffffu}; + + // Non-ReBAR discrete GPU: 4 GiB does not fit in 246 MiB BAR1 -> auto enables staged VRAM + sysmem mirror. + { + const auto mem = make_non_rebar_discrete(); + const auto d = decide_arena_staging(nullptr, mem, req_4g); + CHECK(d.use_staged); + CHECK(d.device_memory_type == 0u); // pure DEVICE_LOCAL VRAM (heap 0) + CHECK(d.host_memory_type == 1u); // sysmem HOST_VISIBLE | HOST_COHERENT (heap 1, NOT BAR1) + + // Explicit off disables staging even on non-ReBAR. + const auto off = decide_arena_staging("0", mem, req_4g); + CHECK(!off.use_staged); + + // A small 128 MiB arena fits inside the 246 MiB BAR1 heap -> auto keeps zero-copy single buffer. + const auto small_auto = decide_arena_staging(nullptr, mem, req_128m); + CHECK(!small_auto.use_staged); + + // Explicit force on small arena still picks pure DEVICE_LOCAL (type 0) + sysmem (type 1), never BAR1. + const auto small_force = decide_arena_staging("1", mem, req_128m); + CHECK(small_force.use_staged); + CHECK(small_force.device_memory_type == 0u); + CHECK(small_force.host_memory_type == 1u); + + // If the VRAM heap is too small (e.g. 2 GiB VRAM card asked for 4 GiB arena), fall back cleanly. + auto tiny_vram = mem; + tiny_vram.memoryHeaps[0].size = 2 * GiB; + CHECK(!decide_arena_staging(nullptr, tiny_vram, req_4g).use_staged); + CHECK(!decide_arena_staging("1", tiny_vram, req_4g).use_staged); + } + + // ReBAR discrete GPU: auto keeps zero-copy DEVICE_LOCAL | HOST_VISIBLE; force enables staged VRAM + sysmem. + { + const auto mem = make_rebar_discrete(); + CHECK(!decide_arena_staging(nullptr, mem, req_4g).use_staged); + + const auto forced = decide_arena_staging("1", mem, req_4g); + CHECK(forced.use_staged); + CHECK(forced.device_memory_type == 0u); // pure DEVICE_LOCAL + CHECK(forced.host_memory_type == 1u); // sysmem, not VRAM + + // When driver excludes BAR type from memoryTypeBits on large buffer, auto falls back to staged VRAM. + VkMemoryRequirements no_bar_bit = req_4g; + no_bar_bit.memoryTypeBits = (1u << 0) | (1u << 1); + const auto no_bar = decide_arena_staging(nullptr, mem, no_bar_bit); + CHECK(no_bar.use_staged); + CHECK(no_bar.device_memory_type == 0u); + CHECK(no_bar.host_memory_type == 1u); + } + + // UMA / iGPU: auto never stages (already DEVICE_LOCAL | HOST_VISIBLE); force allows testing the staging path. + { + const auto mem = make_uma(); + CHECK(!decide_arena_staging(nullptr, mem, req_4g).use_staged); + const auto forced = decide_arena_staging("1", mem, req_4g); + CHECK(forced.use_staged); + CHECK(forced.device_memory_type == 0u); + CHECK(forced.host_memory_type == 0u); + } + + // Separate device vs host requirements (staging buffer only needs TRANSFER_SRC | TRANSFER_DST). + { + const auto mem = make_non_rebar_discrete(); + VkMemoryRequirements dev_req{4094 * MiB, 256, 1u << 0}; // device buffer only accepts type 0 + VkMemoryRequirements host_req{4094 * MiB, 256, 1u << 1}; // staging buffer accepts type 1 + const auto d = decide_arena_staging(nullptr, mem, dev_req, host_req); + CHECK(d.use_staged); + CHECK(d.device_memory_type == 0u); + CHECK(d.host_memory_type == 1u); + } + return 0; +} + +int test_exact_byte_dirty_coalescing() { + ArenaStaging s; + s.init(64 * 1024); + std::vector out; + CHECK(!s.drain(out) && out.empty()); + + // Exact byte granularity: two disjoint 8-byte writes on the same 4 KiB page stay separate (must NOT round to page). + s.mark(0x100, 8); + s.mark(0x120, 8); + CHECK(s.drain(out)); + CHECK(out.size() == 2); + CHECK(out[0].srcOffset == 0x100 && out[0].dstOffset == 0x100 && out[0].size == 8); + CHECK(out[1].srcOffset == 0x120 && out[1].dstOffset == 0x120 && out[1].size == 8); + CHECK(!s.drain(out)); + + // Adjacent, overlapping, out-of-order, and clamped writes coalesce cleanly. + s.mark(500, 100); // [500, 600) + s.mark(600, 50); // adjacent -> [500, 650) + s.mark(100, 40); // [100, 140) + s.mark(120, 80); // overlap -> [100, 200) + s.mark(64 * 1024 - 16, 64); // clamped -> [65520, 65536) + s.mark(64 * 1024, 32); // past end -> ignored + s.mark(300, 0); // empty -> ignored + CHECK(s.drain(out)); + CHECK(out.size() == 3); + CHECK(out[0].srcOffset == 100 && out[0].size == 100); + CHECK(out[1].srcOffset == 500 && out[1].size == 150); + CHECK(out[2].srcOffset == 64 * 1024 - 16 && out[2].size == 16); + + // Stats track flushes, regions, and bytes. + const auto st = s.stats(); + CHECK(st.flushes == 2); + CHECK(st.regions == 5); + CHECK(st.bytes == 16 + 100 + 150 + 16); + + // Requeue restores copies after a failed submit and merges with subsequent marks. + s.requeue(out); + s.mark(200, 50); // extends [100, 200) to [100, 250) + std::vector retry; + CHECK(s.drain(retry)); + CHECK(retry.size() == 3); + CHECK(retry[0].srcOffset == 100 && retry[0].size == 150); + CHECK(retry[1].srcOffset == 500 && retry[1].size == 150); + CHECK(retry[2].srcOffset == 64 * 1024 - 16 && retry[2].size == 16); + return 0; +} + +int test_mapped_ranges_and_readback_subtract() { + ArenaStaging s; + s.init(16 * 1024); + + // Nested Map() refcounting: stays active until both unmaps. + s.track_mapped(4096, 1024); + s.track_mapped(4096, 1024); + std::vector out; + CHECK(s.drain(out)); + CHECK(out.size() == 1 && out[0].srcOffset == 4096 && out[0].size == 1024); + // Persistent map drains again on the next submission even with no new mark(). + CHECK(s.drain(out)); + CHECK(out.size() == 1 && out[0].srcOffset == 4096 && out[0].size == 1024); + + s.untrack_mapped(4096, 1024); + CHECK(s.drain(out)); // still 1 ref active + CHECK(out.size() == 1); + + // subtract_dirty must protect both pending dirty writes and active mapped ranges from GPU->host readbacks. + s.mark(100, 50); // [100, 150) dirty + s.mark(300, 200); // [300, 500) dirty + std::vector rb{ + {0, 0, 400}, // split around [100, 150) and clipped at 300 -> [0, 100), [150, 300) + {350, 350, 100}, // fully eclipsed by [300, 500) -> dropped + {450, 450, 150}, // clipped at front -> [500, 600) + {4000, 4000, 2000} // split around active mapped [4096, 5120) -> [4000, 4096), [5120, 6000) + }; + s.subtract_dirty(rb); + CHECK(rb.size() == 5); + CHECK(rb[0].srcOffset == 0 && rb[0].size == 100); + CHECK(rb[1].srcOffset == 150 && rb[1].size == 150); + CHECK(rb[2].srcOffset == 500 && rb[2].size == 100); + CHECK(rb[3].srcOffset == 4000 && rb[3].size == 96); + CHECK(rb[4].srcOffset == 5120 && rb[4].size == 880); + + s.note_readback(rb); + const auto st = s.stats(); + CHECK(st.readbacks == 1); + CHECK(st.readback_regions == 5); + CHECK(st.readback_bytes == 100 + 150 + 100 + 96 + 880); + + s.untrack_mapped(4096, 1024); + CHECK(s.drain(out)); // drains only the two mark() spans now + CHECK(out.size() == 2); + CHECK(!s.drain(out)); + return 0; +} + +int test_compaction_under_many_small_marks() { + ArenaStaging s; + s.init(4 * MiB); + // Exceed kCompactThreshold (4096) with out-of-order adjacent 32-byte descriptor slots. + for (int i = 0; i < 6000; ++i) { + const VkDeviceSize off = static_cast((i & 1) ? i : (5998 - i)) * 32; + s.mark(off, 32); + } + std::vector out; + CHECK(s.drain(out)); + CHECK(out.size() == 1); + CHECK(out[0].srcOffset == 0 && out[0].size == 6000 * 32); + return 0; +} + +} // namespace + +int main() { + if (test_mode_parsing()) return 1; + if (test_decision_policy()) return 1; + if (test_exact_byte_dirty_coalescing()) return 1; + if (test_mapped_ranges_and_readback_subtract()) return 1; + if (test_compaction_under_many_small_marks()) return 1; + std::printf("arena_staging_test: OK\n"); + return 0; +} diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 01011b3ef6..9708598ee5 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -835,8 +835,8 @@ int check_commit_changes(ID3D12Device* device) { EXPECT(reader.read(buffer.p, got) == 0); wchar_t flag[2]{}; const bool full_walk = GetEnvironmentVariableW(L"LEONIDA_SHADOW_FULL_WALK", flag, 2) == 1 && flag[0] == L'1'; - // The full walk also queries the clean, protected half. - EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == (full_walk ? 2 : 1)); + // The full walk queries both the clean protected half and the uncommitted zero half; normal walk skips both. + EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == (full_walk ? 2 : 0)); EXPECT(first_difference(got, want) == -1); // Committed after the shadow was made, then written. std::uint8_t* later = pages + 3 * 0x10000; From 4e483f7ce0767785dc0abefb4199741181c20b4b Mon Sep 17 00:00:00 2001 From: Dimitar Pavlov <360593571+azsekazvamdimitar@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:30:40 +0200 Subject: [PATCH 2/5] rdna2spirv: TO_DATA merges, --compute-serial-waves, --mesh-native-wave32, --spirv-opt On top of PR #2566 (8db8335d2), combines verified translator performance and correctness improvements for NVIDIA Wave32 GPUs (tested on RTX 3090 24 GB, driver 590.48.01): - Cherry-pick PR #2501 lane_masks.insert_data_merges (TO_DATA) fixing lib_cs_03010 bit-scanning loops (91-370 ms/call -> < 2.5 ms/frame). - Add --compute-serial-waves for >64-thread barrier/LDS/atomic-free compute shaders (lib_cs_00977 + lib_cs_00986: 160 ms/frame -> < 2.4 ms/frame) while preserving unmodified PR #2566 d88b2deea VulkanMemoryModel coherency. - Add --mesh-native-wave32 for strictly partition-invariant mesh shaders (9,116 / 9,282 dxbc MS shaders), running all threads natively in 1 Wave32 pass with zero %x_buf LDS/barriers (-13% to -35% on hot mesh shaders). - Add --spirv-opt (-O below 750 KiB, safe SSA pass set at >= 750 KiB to avoid NVIDIA 590.48.01 --scalar-replacement=0 compiler segfaults, with automatic fallback + spirv-val check). AI-assisted. Verified with semantic tests and retail boots on RTX 3090 (590.48.01). --- tests/semantic/test_ballot_bit_loop.py | 180 +++++++++++++++++++ tests/semantic/test_mesh_native_wave32.py | 81 +++++++++ tools/lane_masks.py | 205 ++++++++++++++++++++++ tools/rdna2spirv.py | 186 +++++++++++++++----- 4 files changed, 605 insertions(+), 47 deletions(-) create mode 100644 tests/semantic/test_ballot_bit_loop.py create mode 100644 tests/semantic/test_mesh_native_wave32.py diff --git a/tests/semantic/test_ballot_bit_loop.py b/tests/semantic/test_ballot_bit_loop.py new file mode 100644 index 0000000000..7fc5fbfec6 --- /dev/null +++ b/tests/semantic/test_ballot_bit_loop.py @@ -0,0 +1,180 @@ +"""A scalar loop over the lanes of a ballot, inside a wave64 loop that ends on a vote (SHADER-WAVE-LOOP-EXEC-VOTE). + +The compiler walks the lanes a ballot found with a scalar loop: `s_and_b64 s[26:27], vcc, exec`, then +`s_ff1_i32_b32` / `s_xor_b32` of s26 and `s_mov_b32 s26, sN` on the back edge, so s26 is a lane mask on the way in and +a number around the loop. The translator keeps a mask as each lane's own bit (0 or ~0) and data as one number, and at +the loop header took s26 as data without gathering the mask's bits: every lane found its own first bit and took its +own number of passes, where the wave takes one (lane_masks.insert_data_merges now gathers them on the way in). + +The program is hand-written in the shape of a library compute program that ran its outer loop to the loop guard +(#1608, SHADER-LIB-LOOP-AT-GUARD): an outer loop over the lanes' work items, 64 apart, that ends when +`v_cmpx_le` + `s_andn2_b64 saved, saved, exec` leaves no lane; inside it, one bit loop over each half of a ballot with a +lane-local `s_cbranch_execz` region. No game data. + + python -I tests/semantic/test_ballot_bit_loop.py +""" +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from test_loop_ballot_barrier import VSHARP, _translate_cs, run_compute_workgroup # noqa: E402 + + +def program(count): + p = [ + f"s_movk_i32 s12, {count}", + "s_mov_b64 s[14:15], exec", + "s_add_u32 s16, s12, 63", # s16 = min(ceil(count / 64), 4) * 64: the passes, at most 4 + "s_lshr_b32 s16, s16, 6", + "s_min_u32 s16, s16, 4", + "s_lshl_b32 s16, s16, 6", + "v_mov_b32_e32 v1, v0", # the lane, kept + "v_mov_b32_e32 v2, 0", # passes of the outer loop + "v_mov_b32_e32 v3, 0", # passes of the bit loops' lane-local regions + "v_cmpx_gt_i32_e32 s16, v0", + "s_cbranch_execz done", + "s_mov_b64 s[18:19], exec", + "s_mov_b64 s[24:25], exec", # the lanes still looping + "s_branch body", + "head:", + "s_mov_b64 exec, s[24:25]", + "body:", + "v_add_nc_u32_e32 v2, 1, v2", + "v_cmpx_gt_u32_e32 s12, v0", # the lanes with an item this pass + "v_and_b32_e32 v4, 1, v0", + "v_cmp_eq_u32_e32 vcc, 0, v4", # ... whose item is even: the ballot + "s_and_b64 s[26:27], vcc, exec", + "s_mov_b64 exec, s[24:25]", + # Lanes 0-31 of the ballot, one pass per lane set; lanes below 16 count them. + "s_cmp_lg_i32 s26, 0", + "s_cbranch_scc0 after_lo", + "lo:", + "s_ff1_i32_b32 s32, s26", + "s_lshl_b32 s32, 1, s32", + "s_xor_b32 s35, s32, s26", + "v_cmp_gt_u32_e32 vcc, 16, v1", + "s_and_b64 exec, vcc, exec", + "s_cbranch_execz skip_lo", + "v_add_nc_u32_e32 v3, 1, v3", + "skip_lo:", + "s_mov_b64 exec, s[24:25]", + "s_cmp_eq_i32 s26, s32", + "s_cbranch_scc1 after_lo", + "s_mov_b32 s26, s35", + "s_branch lo", + "after_lo:", + # Lanes 32-63, the same through s27; lanes above 47 count them in the second byte. + "s_cmp_lg_i32 s27, 0", + "s_cbranch_scc0 after_hi", + "hi:", + "s_ff1_i32_b32 s32, s27", + "s_lshl_b32 s32, 1, s32", + "s_xor_b32 s35, s32, s27", + "v_cmp_lt_u32_e32 vcc, 47, v1", + "s_and_b64 exec, vcc, exec", + "s_cbranch_execz skip_hi", + "v_add_nc_u32_e32 v3, 0x100, v3", + "skip_hi:", + "s_mov_b64 exec, s[24:25]", + "s_cmp_eq_i32 s27, s32", + "s_cbranch_scc1 after_hi", + "s_mov_b32 s27, s35", + "s_branch hi", + "after_hi:", + # The next item 64 on; the loop ends when no lane has one left. + "v_add_nc_u32_e32 v0, 64, v0", + "v_cmpx_le_i32_e32 s16, v0", + "s_andn2_b64 s[24:25], s[24:25], exec", + "s_cbranch_scc1 head", + "s_mov_b64 exec, s[18:19]", + "done:", + "s_mov_b64 exec, s[14:15]", + "v_lshlrev_b32_e32 v6, 3, v1", + "buffer_store_dword v2, v6, s[0:3], 0 offen offset:0", + "buffer_store_dword v3, v6, s[0:3], 0 offen offset:4", + "s_endpgm", + ] + return p + + +def expected(count): + """(outer passes, bit-loop visits) per lane, as one wave64 runs it.""" + limit = min((count + 63) >> 6, 4) << 6 + item = {t: t for t in range(64)} + passes = {t: 0 for t in range(64)} + visits = {t: 0 for t in range(64)} + alive = [t for t in range(64) if item[t] < limit] + while alive: + for t in alive: + passes[t] += 1 + ballot = [t for t in alive if item[t] < count and item[t] % 2 == 0] + for _ in [t for t in ballot if t < 32]: + for t in alive: + visits[t] += 1 if t < 16 else 0 + for _ in [t for t in ballot if t >= 32]: + for t in alive: + visits[t] += 0x100 if t > 47 else 0 + for t in alive: + item[t] += 64 + alive = [t for t in alive if item[t] < limit] + return {t: (passes[t], visits[t]) for t in range(64)} + + +def mask_use_program(take_mask): + """A lane mask (even lanes) on one path and a number (lanes 0-15: 0xffff) on the other meet in s[6:7], which then + only goes into EXEC. Taken as data at the merge, each lane's 0 / ~0 on the mask path still gives its own bit + (bit L of a data register for lane L), so no gather is needed and none is inserted.""" + return [ + f"s_mov_b32 s40, {1 if take_mask else 0}", + "s_mov_b64 s[14:15], exec", + "v_mov_b32_e32 v2, 0", + "v_and_b32_e32 v4, 1, v0", + "v_cmp_eq_u32_e32 vcc, 0, v4", + "s_mov_b64 s[6:7], vcc", + "s_cmp_eq_u32 s40, 1", + "s_cbranch_scc1 join", + "s_mov_b32 s6, 0xffff", + "s_mov_b32 s7, 0", + "join:", + "s_and_b64 exec, s[6:7], exec", + "v_mov_b32_e32 v2, 1", + "s_mov_b64 exec, s[14:15]", + "v_lshlrev_b32_e32 v6, 2, v0", + "buffer_store_dword v2, v6, s[0:3], 0 offen offset:0", + "s_endpgm", + ] + + +class BallotBitLoop(unittest.TestCase): + def test_a_merged_mask_used_as_a_mask_needs_no_gather(self): + for take_mask in (True, False): + want = {t: int(t % 2 == 0) if take_mask else int(t < 16) for t in range(64)} + for label, emulate, sg in (("native64", False, 64), ("emulate_sg32", True, 32)): + with self.subTest(take_mask=take_mask, mode=label): + spv, _ = _translate_cs(f"cs_merged_mask_{label}_{int(take_mask)}", mask_use_program(take_mask), + threads=64, emulate=emulate) + mem = run_compute_workgroup(spv, 64, sg, push_constants=VSHARP) + for t in range(64): + self.assertEqual(mem.get(4 * t, -1), want[t], f"{label} lane {t}") + + def test_every_lane_walks_the_wave_ballot(self): + configs = [ + ("native64", False, 64, True), + ("emulate_sg32", True, 32, True), + ("emulate_sg32_rounds", True, 32, False), + ] + for count in (100, 200, 7): + want = expected(count) + for label, emulate, sg, structured in configs: + with self.subTest(count=count, mode=label): + spv, _ = _translate_cs(f"cs_ballot_bit_loop_{label}_{count}", program(count), threads=64, + emulate=emulate, structured=structured) + mem = run_compute_workgroup(spv, 64, sg, push_constants=VSHARP) + for t in range(64): + got = (mem.get(8 * t, -1), mem.get(8 * t + 4, -1)) + self.assertEqual(got, want[t], f"{label} count {count} lane {t}") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_mesh_native_wave32.py b/tests/semantic/test_mesh_native_wave32.py new file mode 100644 index 0000000000..4bc7fea2b4 --- /dev/null +++ b/tests/semantic/test_mesh_native_wave32.py @@ -0,0 +1,81 @@ +"""Unit tests for --mesh-native-wave32 and --compute-serial-waves. + +Verifies: + 1. A 128-thread barrier-free compute shader with no LDS or atomics uses --compute-serial-waves + (LocalSize 64 1 1, compute_serial_waves == 2) when --wave64-emulate --compute-serial-waves are set. + 2. A 128-thread compute shader with s_barrier stays on the side-by-side form (compute_serial_waves not set). + 3. --spirv-opt threshold constants are well-defined and assemble_spirv accepts spirv_opt=False/True cleanly. +""" +import os +import struct +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import support # noqa: F401 +import rdna2spirv + + +def _cs_fssm(sx=128, sy=1, sz=1): + fssm = bytearray(0x148) + struct.pack_into("<4I", fssm, 0x138, 0x8088, sx, sy, sz) + return bytes(fssm) + + +def _translate_cs(asm_lines, sx=128, sy=1, sz=1, csw=True): + with tempfile.TemporaryDirectory() as td: + os.makedirs(os.path.join(td, "disasm")) + os.makedirs(os.path.join(td, "fssm")) + sp = os.path.join(td, "disasm", "CS_test.s") + fp = os.path.join(td, "fssm", "CS_test.fssm") + with open(sp, "w", encoding="utf-8", newline="\n") as f: + f.write("; CS_test code 0x0..0x100 (header), gfx1013, 0 invalid words\n") + for line in asm_lines: + f.write("\t" + line + "\n") + with open(fp, "wb") as f: + f.write(_cs_fssm(sx, sy, sz)) + old_w64 = rdna2spirv.WAVE64_EMULATE + old_csw = rdna2spirv.COMPUTE_SERIAL_WAVES + try: + rdna2spirv.WAVE64_EMULATE = True + rdna2spirv.COMPUTE_SERIAL_WAVES = csw + asm = rdna2spirv.translate(sp) + gen = rdna2spirv.translate.last_gen + meta = rdna2spirv.shader_meta(gen, asm, src_path=sp, fssm_path=fp) + return asm, gen, meta + finally: + rdna2spirv.WAVE64_EMULATE = old_w64 + rdna2spirv.COMPUTE_SERIAL_WAVES = old_csw + + +class ComputeSerialWavesAndOptTest(unittest.TestCase): + def test_csw_activates_on_barrier_free_128_thread_cs(self): + asm, gen, meta = _translate_cs([ + "s_mov_b64 exec, -1", + "v_add_nc_u32_e32 v0, 1, v0", + "s_endpgm", + ], sx=128, csw=True) + self.assertEqual(gen.cs_serial, 2) + self.assertEqual(meta.get("compute_serial_waves"), 2) + self.assertIn("OpExecutionMode %main LocalSize 64 1 1", asm) + + def test_csw_skips_when_barrier_present(self): + asm, gen, meta = _translate_cs([ + "s_mov_b64 exec, -1", + "s_barrier", + "v_add_nc_u32_e32 v0, 1, v0", + "s_endpgm", + ], sx=128, csw=True) + self.assertFalse(gen.cs_serial) + self.assertNotIn("compute_serial_waves", meta) + + def test_spirv_opt_constants(self): + self.assertGreater(rdna2spirv.SPIRV_OPT_LARGE_BYTES, 0) + self.assertIn("--ssa-rewrite", rdna2spirv.SPIRV_OPT_SSA_PASSES) + self.assertNotIn("--scalar-replacement=0", rdna2spirv.SPIRV_OPT_SSA_PASSES) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/lane_masks.py b/tools/lane_masks.py index d97b874dab..5e6c8147c0 100644 --- a/tools/lane_masks.py +++ b/tools/lane_masks.py @@ -161,6 +161,9 @@ def step(state, ins, wave64=True): op, a = base_op(ins["op"]), ins["args"] if not a or op.startswith(NO_DESTINATION): return + if op == TO_DATA: # the wave's bits of a mask: data, the same in every lane + put(state, a[0], None, wave64) + return if ins.get("vcc_data_pair"): # Gen materializes both scalar words (including a source mask's lane bits). put(state, a[0], None, wave64) @@ -474,6 +477,208 @@ def _step_spills(st, ins): return read_ids, sorted(slots) +TO_DATA = "s_mask_to_data_b32" # the translator's own: sD = the real bits of the lane-mask word in sD + + +def _fixpoint(blocks, succ, wave64): + """Each block's state on entry (None where it is not reached), as analyse() works it out.""" + entry = [None] * len(blocks) + if blocks: + entry[0] = {} + work = [0] if blocks else [] + while work: + n = work.pop() + state = dict(entry[n]) + for ins in blocks[n]: + step(state, ins, wave64) + for s in succ[n]: + merged = dict(state) if entry[s] is None else _merge(entry[s], state) + if merged != entry[s]: + entry[s] = merged + work.append(s) + return entry + + +def _merge(a, b): + """A mask on both paths, or a mask on one and 0 / -1 on the other; anything else is data (left out).""" + merged = {} + for r in a.keys() & b.keys(): + a_k, b_k = a[r], b[r] + if a_k == b_k: + merged[r] = a_k + elif a_k == EITHER: + merged[r] = b_k + elif b_k == EITHER: + merged[r] = a_k + else: + merged[r] = MASK + return merged + + +ALL = "all" # an instruction that may read any SGPR (s_movrels / s_movrelsd: the register comes from M0) + + +def _sgprs(x): + if x.get("k") == "sgpr": + return set(range(x["r"], x["r"] + x.get("n", 1))) + if x.get("k") == "slist": + return {r for r in x["r"] if isinstance(r, int)} + return set() + + +def _reads_writes(ins): + """The SGPR numbers `ins` reads and the ones it surely writes (a destination it may leave alone is read too).""" + op, a = base_op(ins["op"]), ins["args"] + if op.startswith(("s_movrels", "s_movreld", "s_swappc", "s_setpc", "s_call", "s_cbranch_g_fork")): + return ALL, set() + if not a: + return set(), set() + if op.startswith(NO_DESTINATION): + reads = set() + for x in a: + if x is not None: + reads |= _sgprs(x) + return reads, set() + reads = set() + for x in a[1:]: + if x is not None: + reads |= _sgprs(x) + # A SOPK read-modify-write, a 16-bit or SDWA/DPP partial write, or a VOP3b carry-out pair: the first operand is + # taken as read too, which only ever keeps a register live. (A compare writes its whole mask in any encoding.) + if op in ("s_addk_i32", "s_mulk_i32", "s_cmovk_i32") or op.startswith("s_cmov") or "_co_" in op or \ + (ins["op"].endswith(("_sdwa", "_dpp", "_dpp8")) and not op.startswith("v_cmp")): + reads |= _sgprs(a[0]) + return reads, set() + return reads, _sgprs(a[0]) + + +def _is_mask_operand(x, masks): + if x is None: + return False + if x.get("k") == "special": + return x.get("t", "").startswith(("exec", "vcc")) + return x.get("k") == "sgpr" and any(x["r"] + i in masks for i in range(x.get("n", 1))) + + +# The scalar ops that read a register as a whole word of lane bits: the first or last set bit, or how many there are. +WORD_SCANS = ("s_ff0_i32_b", "s_ff1_i32_b", "s_bcnt0_i32_b", "s_bcnt1_i32_b", "s_flbit_i32") + + +def _numeric_reads(ins, masks): + """(reads, through) for insert_data_merges: the SGPR numbers `ins` scans as a whole word of lane bits + (WORD_SCANS), which a register taken as data must hold the wave's bits for. `through`: a scalar copy or + bitwise op of data, whose sources count only where its result is scanned in turn (`s_xor_b32 s35, s32, s26` + then `s_mov_b32 s26, s35`). Other reads are left out. As a mask (EXEC, a bitwise op with a mask, v_cndmask) + this lane's 0 / ~0 is exact: the translator takes bit L of a data register there (rdna2spirv's mask_src). + `masks`: the registers holding a mask before `ins` (analyse()).""" + reads, _ = _reads_writes(ins) + if reads is ALL: + return ALL, False + op, a = base_op(ins["op"]), ins["args"] + if not a: + return set(), False + if op.startswith(WORD_SCANS): + return reads, False + if op.startswith(("s_mov_b", "s_not_b") + BITWISE) and a[0].get("k") == "sgpr" and not any(_is_mask_operand(x, masks) for x in a[1:]): + return reads, True + return set(), False + + +def _numeric_live_in(blocks, succ, masks_before): + """The SGPR numbers each block may read as a number before writing them (ALL for every one), following scalar + copies and bitwise ops of data to where their results are read (_numeric_reads).""" + info = [[(_reads_writes(ins)[1], *_numeric_reads(ins, masks_before.get(id(ins), {}))) for ins in blk] + for blk in blocks] + + def through(n, live): + for w, reads, via in reversed(info[n]): + if reads is ALL: + return ALL + needed = not via or bool(w & live) + live = live - w + if needed: + live = live | reads + return live + + live = [set() for _ in blocks] + changed = True + while changed: + changed = False + for n in range(len(blocks) - 1, -1, -1): + if live[n] is ALL: + continue + out = set() + for s in succ[n]: + if live[s] is ALL: + out = ALL + break + out |= live[s] + new = ALL if out is ALL else through(n, out) + if new != live[n]: + live[n] = new + changed = True + return live + + +def insert_data_merges(blocks, succ, branches, wave64=True): + """In place: where an SGPR holds a lane mask at the end of a block but is data where a successor begins (a + mask on one path to it, a number on another), insert a TO_DATA instruction for it before the block's branch. + + The two kinds of value are kept differently: a mask as this lane's bit (all ones or zero), data as the same + number in every lane. Where they meet the register is taken as data, which the path that wrote the mask does + not hold. The compiler makes such a merge when it walks the lanes of a ballot with a scalar loop: + `s_and_b64 s[26:27], vcc, exec`, then s_ff1_i32_b32 / s_xor_b32 of s26 and `s_mov_b32 s26, sN` on the back + edge. The loop's s26 was this lane's 0 / ~0 on the first pass, so each lane found its own first bit and took + its own number of passes, where the wave takes one. TO_DATA gathers the wave's real bits into the register + (rdna2spirv's lane_mask_word), so the loop sees on every path what the hardware has. + + A register is converted only when every successor takes it as data (one that still reads it as a mask keeps + this lane's bit) and some successor may scan its lane bits before writing it (s_ff0 / s_ff1 / s_bcnt0 / + s_bcnt1 / s_flbit, also through scalar copies of it: _numeric_reads). The gather is a cross-lane step (a + barrier round under --wave64-emulate), and most such merges are only ever read as masks again (written back to + EXEC, ANDed with it), where this lane's 0 / ~0 is already exact: the translator takes bit L of a data register + for lane L there (rdna2spirv's mask_src). Other number reads of such a merge (an add, a compare) would need the + gather too; none is known in a shader, and they are left as they were to keep the change to the lane loops. + TO_DATA itself writes data (step), so a second run finds nothing left to insert. + + Under --wave64-emulate the gather is an exchange round that both halves of the wave must join, so it relies on + its block being reached by the whole wave, through scalar (wave-uniform) branches, as the compiler's lane loops + are; wave64_emulate_opt keeps it out of lane-local regions (_MASK_WORD_READERS). + `branches`: the opcodes that end a block. Returns how many instructions were inserted.""" + inserted = 0 + before, _ = analyse(blocks, succ, wave64=wave64) + live = _numeric_live_in(blocks, succ, before) + for _ in range(len(blocks) + 1): # each round only takes masks away, so this ends + entry = _fixpoint(blocks, succ, wave64) + added = 0 + for n, blk in enumerate(blocks): + if entry[n] is None or not succ[n]: + continue + state = dict(entry[n]) + for ins in blk: + step(state, ins, wave64) + regs = [] + for r, k in sorted((r, k) for r, k in state.items() if isinstance(r, int) and k in MASK_KINDS): + if all(entry[s] is not None and r not in entry[s] for s in succ[n]) and \ + any(live[s] is ALL or r in live[s] for s in succ[n]): + regs.append(r) + if not regs: + continue + last = blk[-1] if blk else None + at = len(blk) - 1 if last is not None and (base_op(last["op"]) in branches) else len(blk) + pc = last.get("pc", 0) if last is not None else 0 + for r in regs: + reg = {"k": "sgpr", "r": r, "n": 1} + blk.insert(at, {"op": TO_DATA, "args": [dict(reg), dict(reg)], "mods": [], "pc": pc, "enc": "", + "synthetic": True}) + at += 1 + added += 1 + inserted += added + if not added: + break + return inserted + + def analyse(blocks, succ, *, include_either=False, wave64=True): entry = [None] * len(blocks) # None: not reached yet if blocks: diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index d6f0db65b8..d7ea4c01f1 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -133,6 +133,14 @@ # runs its waves one after the other in 64 invocations, one pass per wave, so each pass is a single wave (the # inline_all structured form) instead of several waves side by side under mini-schedulers. See assemble(). MESH_SERIAL_WAVES = False +# --compute-serial-waves (with --wave64-emulate): the same for a compute shader of more than 64 threads with no LDS +# access, s_barrier or atomic: its waves are not ordered against each other, so they run one after the other in 64 +# invocations, one pass per wave, turning 2-wave OpSwitch schedulers into single-wave inline_all structured SPIR-V. +COMPUTE_SERIAL_WAVES = False +# --mesh-native-wave32 (with --wave64-emulate): a partition-invariant mesh shader (no LDS, store, atomic, +# cross-lane shuffle/ballot/reduction, and only constant -1 v_mbcnt for lane ID) skips --wave64-emulate and runs +# all threads natively in 1 pass at LocalSize (e.g. 128) on 32-wide subgroups (zero %x_buf LDS/barriers). +MESH_NATIVE_WAVE32 = False # --pc-tail-ubo: for devices with 128 bytes of push constants, Vulkan's minimum (AMD's Windows driver on RDNA2 iGPUs, # some Intel Arc drivers; D3D-14's push_constants_need_fallback). The push-constant block keeps s0..s31 (128 bytes). # The tail that follows them by default (dwords 32..35: heap base, code base; 36..37: the --mesh-compute output @@ -557,6 +565,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.coherent_images = False # a glc image_load/image_store: the storage views are decorated Coherent self.uses_vmm = False # glc/dlc or intra-workgroup barrier coherency: VulkanMemoryModel + DeviceScope self.uses_barrier = False # s_barrier or wave64-emulate ordering barrier executed in cs/ms + self.uses_s_barrier = False # explicit RDNA2 s_barrier executed in cs/ms self.reads_glc_buffer = False # glc/dlc buffer/global/scalar load: runtime pre-dispatch barrier hint self.writes_depth = False self.db_shader_control = None # PS: DB_SHADER_CONTROL register from FSSM header (E + 0x138) @@ -631,6 +640,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.scalar_spills = set() # (vgpr, lane) pure scalar spill slots lowered to self.parked (all waves/stages) self.spill_readlanes = set() # id(ins) of mixed-VGPR v_readlane_b32 proven to reload a parked spill slot self.emulate = False # --wave64-emulate: exact wave64 on any subgroup size (cs/ms; see x_round) + self.ms_native_wave32 = False # --mesh-native-wave32: partition-invariant MS skipped wave64 emulation self.emulate_inline = False # emulate: current block emits direct inline barriers (no x_split) self.emulate_plan = None # emulate: structured plan from wave64_emulate_opt.plan_structured_emulation self.x_one_lane = False # emulate: emitting a fold that at most one lane of the wave runs ("one_lane") @@ -650,6 +660,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.cur_either = () self.x_lanes = 64 # emulate: workgroup invocations rounded up to whole waves self.ms_serial = 0 # --mesh-serial-waves: number of passes (waves run one after the other), or 0 + self.cs_serial = 0 # --compute-serial-waves: the same for a compute shader self.scc_live = None # emulate: set of id(ins) whose SCC write is live-out (wave64_emulate_opt) self.cur_scc_live = True # emulate: whether the current instruction's SCC result is live-out self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler) @@ -6484,8 +6495,9 @@ def _ensure_x_pre_fn(self, kind): Outlines the ~20-30 instructions of ring-buffer slot clearing (`sn = (it + 1) % 3`), mask/data slot indexing, and pre-barrier %x_buf store/OpAtomicOr out of %main while keeping OpControlBarrier directly at the callsite - in %main. Returns the helper function's SPIR-V id (`%x_pre_vote_fn`, `%x_pre_mask_fn`, or `%x_pre_data_fn`). + in %main. Returns the helper function's SPIR-V id (`%x_pre_{kind}_fn`). """ + fn_key = kind fn_name = f"%x_pre_{kind}_fn" if kind in self.x_round_fns: return fn_name @@ -6497,7 +6509,7 @@ def _ensure_x_pre_fn(self, kind): p_names = ["it", "li", "lane", "wave"] + tail_params arity = len(p_names) fn_type = self.x_round_fn_types.setdefault(arity, f"%fn_x_pre{arity}") - params = {k: f"%xp_{kind}_{k}" for k in p_names} + params = {k: f"%xp_{fn_key}_{k}" for k in p_names} p_it, p_li = params["it"], params["li"] saved, self.body = self.body, [] n1, sn = self.tmp(), self.tmp() @@ -6572,7 +6584,7 @@ def _ensure_x_pre_fn(self, kind): self.emit(f"{old1} = OpAtomicOr %uint {p1} {self.cu(2)} {self.cu(0)} {params['b1']}") ret_id = rm lines, self.body = self.body, saved - self.x_round_fns[kind] = ( + self.x_round_fns[fn_key] = ( [f"{fn_name} = OpFunction %uint None {fn_type}"] + [f"{params[k]} = OpFunctionParameter %uint" for k in p_names] + [f"{fn_name}_entry = OpLabel"] + @@ -8310,6 +8322,13 @@ def insn(self, ins): self.x_memory_order(base_op(ins["op"])) self.cur_either = self.lane_either.get(id(ins), ()) try: + if ins["op"] == lane_masks.TO_DATA: + # A lane mask that a merge further on takes as data (lane_masks.insert_data_merges): the + # register gets the wave's real bits, the same number in every lane. + src = ins["args"][1] + val = self.lane_mask_word(src) if self.holds_lane_mask(src) else self.src_u(src) + self.dst(ins["args"][0], val) + return None if ins["op"].endswith("_dpp"): bop = base_op(ins["op"]) if bop in SOPC_CMP32_OPS or bop in SOPC_CMP64_OPS or bop in SOPC_BITCMP_OPS: @@ -9987,6 +10006,7 @@ def f64(sv): if self.stage not in ("cs", "ms"): raise Unsupported("s_barrier outside compute") self.uses_barrier = True + self.uses_s_barrier = True bar_sem = 0x6948 if self.uses_vmm else 0x948 if self.emulate_inline: self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(bar_sem)}") @@ -17846,21 +17866,15 @@ def insert_late_constants(gen, out, written): def ms_serial_passes(gen, fn, lists): - """--mesh-serial-waves: the function's variables, then a loop over the passes around the prologue (and, appended - by the caller, the body). Returns the new `fn`, the lines that close the loop after the body, and the export - variables with their per-pass twins. - - Pass w runs the invocations as lanes 64 * w .. 64 * w + 63 of the workgroup: `%local_index` is a Function variable - here, the built-in (now `%real_local_index`) plus 64 * w, so the launch state (v5, the wave id in s3), the lane - and everything else that reads it see wave w. Every initialised Function variable gets its initial value again at - the start of a pass. What a pass exported sits in Function variables (`%ms_pos`, `%ms_prim`, ...): they are copied - to the pass's twins before the next pass overwrites them, and the epilogue writes each pass's outputs from its - twins after the loop, once the counts are known.""" - w_count = gen.ms_serial + """--mesh-serial-waves, --compute-serial-waves: the function's variables, then a loop over the passes around the + prologue (and, appended by the caller, the body). Returns the new `fn`, the lines that close the loop after the + body, and the export variables with their per-pass twins.""" + w_count = gen.ms_serial or gen.cs_serial + builtin = "%local_index" if gen.ms_serial else "%local_id" for lines in lists: for i, l in enumerate(lines): - if "%local_index" in l: - lines[i] = re.sub(r"%local_index\b", "%real_local_index", l) + if builtin in l: + lines[i] = re.sub(builtin + r"\b", "%real_" + builtin[1:], l) last_var = max(i for i, l in enumerate(fn) if " = OpVariable " in l) head, rest = fn[:last_var + 1], fn[last_var + 1:] var = re.compile(r"^(%\w+) = OpVariable (\S+) Function(?: (\S+))?$") @@ -17876,15 +17890,25 @@ def ms_serial_passes(gen, fn, lists): exports.append(name) twins += [f"{name}__w{w} = OpVariable {ptr} Function" + (f" {init}" if init else "") for w in range(w_count)] c = gen.cu - head = head + ["%local_index = OpVariable %_ptr_Function_uint Function " + c(0), + head = head + [("%local_index = OpVariable %_ptr_Function_uint Function " + c(0) if gen.ms_serial else + "%local_id = OpVariable %_ptr_Function_v3u Function"), "%msw_pass = OpVariable %_ptr_Function_uint Function " + c(0)] + twins open_loop = ["OpBranch %msw_head", "%msw_head = OpLabel", "OpLoopMerge %msw_exit %msw_cont None", - "OpBranch %msw_body", "%msw_body = OpLabel"] + reinit + [ - "%msw_w = OpLoad %uint %msw_pass", "%msw_rl = OpLoad %uint %real_local_index", - f"%msw_off = OpIMul %uint %msw_w {c(64)}", "%msw_li = OpIAdd %uint %msw_rl %msw_off", - "OpStore %local_index %msw_li"] + "OpBranch %msw_body", "%msw_body = OpLabel"] + reinit + ["%msw_w = OpLoad %uint %msw_pass"] + if gen.ms_serial: + open_loop += ["%msw_rl = OpLoad %uint %real_local_index"] + else: + open_loop += ["%msw_rid = OpLoad %v3uint %real_local_id", "%msw_rl = OpCompositeExtract %uint %msw_rid 0"] + open_loop += [f"%msw_off = OpIMul %uint %msw_w {c(64)}", "%msw_li = OpIAdd %uint %msw_rl %msw_off"] + if gen.ms_serial: + open_loop += ["OpStore %local_index %msw_li"] + else: + sx, sy, _ = gen.cs["size"] + open_loop += [f"%msw_x = OpUMod %uint %msw_li {c(sx)}", f"%msw_yz = OpUDiv %uint %msw_li {c(sx)}", + f"%msw_y = OpUMod %uint %msw_yz {c(sy)}", f"%msw_z = OpUDiv %uint %msw_yz {c(sy)}", + "%msw_id = OpCompositeConstruct %v3uint %msw_x %msw_y %msw_z", "OpStore %local_id %msw_id"] close = [] - for w in range(w_count): + for w in range(w_count if exports else 0): close += [f"%msw_is{w} = OpIEqual %bool %msw_w {c(w)}", f"OpSelectionMerge %msw_sv_end{w} None", f"OpBranchConditional %msw_is{w} %msw_sv{w} %msw_sv_end{w}", f"%msw_sv{w} = OpLabel"] @@ -18081,13 +18105,13 @@ def assemble(gen): if any("OpGroupNonUniform" in l or "%sg_lane" in l for b in gen.blocks + list(gen.x_segs.values()) if b is not None for l in b): raise Unsupported("wave64 emulation: a subgroup operation is left") - gen.uses_subgroup = gen.uses_vote = gen.uses_ballot = gen.uses_wave_bits = gen.uses_quad = False - gen.uses_bcast_first = False + gen.uses_subgroup = gen.uses_vote = gen.uses_ballot = gen.uses_quad = False + gen.uses_wave_bits = gen.uses_bcast_first = False x_waves, x_mask, x_sched, x_sink = gen.x_sizes() x_zero = x_sink - x_mask # mask and schedule words: zeroed before the first round x_threads = (gen.cs or gen.ms)["size"] x_threads = x_threads[0] * x_threads[1] * x_threads[2] - if gen.ms_serial: + if gen.ms_serial or gen.cs_serial: x_threads = 64 # the invocations of one pass sx, sy, _ = (gen.cs or gen.ms)["size"] for v in (0, 1, 2, 3, 6, 31, 63, 0x948, x_mask, x_sched, x_sink, x_sink + 1, x_zero - 1, x_threads, @@ -18261,7 +18285,7 @@ def assemble(gen): f"OpMemoryModel {'PhysicalStorageBuffer64' if psb else 'Logical'} {'Vulkan' if gen.uses_vmm else 'GLSL450'}", f"OpEntryPoint {model} %main \"main\" {' '.join(iface)}"] if cs: - hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*gen.cs["size"])) + hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*((64, 1, 1) if gen.cs_serial else gen.cs["size"]))) if gsx: hdr += ["OpExecutionMode %main Triangles", "OpExecutionMode %main Invocations 1", "OpExecutionMode %main OutputTriangleStrip", f"OpExecutionMode %main OutputVertices {gen.gs['maxv']}"] @@ -18739,6 +18763,8 @@ def _out_var(n): if cs: types += ["%v3uint = OpTypeVector %uint 3", "%_ptr_Input_v3u = OpTypePointer Input %v3uint"] gvars += ["%wg_id = OpVariable %_ptr_Input_v3u Input", "%local_id = OpVariable %_ptr_Input_v3u Input"] + if gen.cs_serial: + types += ["%_ptr_Function_v3u = OpTypePointer Function %v3uint"] if gen.uses_lds: types += [f"%lds_arr = OpTypeArray %uint {gen.cu(max(gen.lds_dwords, 1))}", "%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr", "%_ptr_WG_uint = OpTypePointer Workgroup %uint"] @@ -19179,7 +19205,7 @@ def label(prefix): if pops: fn.append("OpBeginInvocationInterlockEXT") # end of the entry block: uniform, executed once serial_close, serial_exports = [], [] - if ms and gen.ms_serial: + if (ms and gen.ms_serial) or gen.cs_serial: fn, serial_close, serial_exports = ms_serial_passes(gen, fn, (hdr, dec, gvars)) out = hdr + dec + types + gvars + helpers + fn end_lock = " OpEndInvocationInterlockEXT\n" if pops else "" @@ -22577,21 +22603,41 @@ def _uses_vcc_tuple(ins): user_limit = g.cs["user"] if g.cs else USER_SGPRS sys_sgprs = (3,) if stage in ("ms", "gs") else () if WAVE64_EMULATE and g.wave64 and stage in ("cs", "ms"): - g.emulate = True - size = (g.cs or g.ms)["size"] - g.x_lanes = -(-size[0] * size[1] * size[2] // 64) * 64 - threads = size[0] * size[1] * size[2] - if (MESH_SERIAL_WAVES and stage == "ms" and threads > 64 and threads % 64 == 0 - and not any(i["op"].startswith("ds_") or "store" in i["op"] or "atomic" in i["op"] for i in insns)): - # The waves of such a program cannot pass each other anything: no LDS, and no store or atomic to - # memory another wave could read (ms_wave_info_s3 counts lanes in LDS across an s_barrier and keeps - # the side-by-side form). What is left between them is the allocation request and the exports, which - # assemble() orders itself. The order of the waves is then not observable. - g.ms_serial = threads // 64 # passes; every pass is one whole wave - g.x_lanes = 64 - for k in range(g.ms_serial + 1): - g.cu(k) - g.cu(64 * k) + if (MESH_NATIVE_WAVE32 and stage == "ms" + and not any( + i["op"].startswith("ds_") + or any(b in i["op"] for b in ("v_readlane", "v_writelane", "v_permlane", "s_bcnt1", + "s_ff1", "s_flbit", "_dpp", "quad", "atomic", "store")) + or (i["op"].startswith("v_mbcnt_") + and not (len(i["args"]) >= 2 and i["args"][1]["k"] == "imm" and i["args"][1]["v"] == -1)) + for i in insns)): + g.ms_native_wave32 = True + else: + g.emulate = True + size = (g.cs or g.ms)["size"] + g.x_lanes = -(-size[0] * size[1] * size[2] // 64) * 64 + threads = size[0] * size[1] * size[2] + if (MESH_SERIAL_WAVES and stage == "ms" and threads > 64 and threads % 64 == 0 + and not any(i["op"].startswith("ds_") or "store" in i["op"] or "atomic" in i["op"] for i in insns)): + # The waves of such a program cannot pass each other anything: no LDS, and no store or atomic to + # memory another wave could read (ms_wave_info_s3 counts lanes in LDS across an s_barrier and keeps + # the side-by-side form). What is left between them is the allocation request and the exports, which + # assemble() orders itself. The order of the waves is then not observable. + g.ms_serial = threads // 64 # passes; every pass is one whole wave + g.x_lanes = 64 + for k in range(g.ms_serial + 1): + g.cu(k) + g.cu(64 * k) + elif (COMPUTE_SERIAL_WAVES and stage == "cs" and threads > 64 and threads % 64 == 0 + and not any(i["op"].startswith("ds_") or "atomic" in i["op"] or base_op(i["op"]) == "s_barrier" + for i in insns)): + g.cs_serial = threads // 64 + g.x_lanes = 64 + for v in size[:2]: + g.cu(v) + for k in range(g.cs_serial + 1): + g.cu(k) + g.cu(64 * k) insns = fold_far_branches(insns) if stage == "ps" and g.mrt_types: insns = unpatch_int_mrt_exports(insns, g.mrt_targets, g.mrt_types, g.mrt_masks) @@ -22703,6 +22749,8 @@ def target(ins): succ = [list(dict.fromkeys(e)) for e in raw_edges] g.out_pcs = _block_out_pcs(blocks, raw_edges, succ) g.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ) + # A lane mask that meets data at a merge is turned into the wave's bits on the way there (lane_masks.py). + lane_masks.insert_data_merges(blocks, succ, BRANCHES | {"s_endpgm"}, wave64=g.wave64) g.park_masks((blocks, succ)) halves_analysis(g, blocks, succ) meta_extra = {} @@ -23176,7 +23224,7 @@ def x_prologue(gen, threads): # (0-63), not from the workgroup index of the lane it runs in this pass (ms_serial_passes). L += ["%x_li = OpLoad %uint " + ("%real_local_index" if gen.ms_serial else "%local_index")] else: - L += ["%x_lid = OpLoad %v3uint %local_id", "%x_lx = OpCompositeExtract %uint %x_lid 0", + L += ["%x_lid = OpLoad %v3uint " + ("%real_local_id" if gen.cs_serial else "%local_id"), "%x_lx = OpCompositeExtract %uint %x_lid 0", "%x_ly = OpCompositeExtract %uint %x_lid 1", "%x_lz = OpCompositeExtract %uint %x_lid 2", f"%x_ly2 = OpIMul %uint %x_ly {c(sx)}", f"%x_lz2 = OpIMul %uint %x_lz {c(sx * sy)}", "%x_lxy = OpIAdd %uint %x_lx %x_ly2", "%x_li = OpIAdd %uint %x_lxy %x_lz2"] @@ -23572,6 +23620,10 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): # Exact on any subgroup size: no subgroup operation, cross-lane data in %x_buf (workgroup memory). m["wave64_exchange"] = "workgroup" m["subgroup_size"] = None + elif g.ms_native_wave32: + m["mesh_native_wave32"] = True + m["wave64_emulated"] = True + m["subgroup_size"] = None if "Offset " in asm and re.search(r"OpImageSample\w+ [^\n]*Offset", asm): m["needs_maintenance8"] = True if "SignedZeroInfNanPreserve" in caps: @@ -23588,6 +23640,8 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): m["uses_code_base"] = True if g.cs: m["local_size"] = list(g.cs["size"]) + if g.cs_serial: + m["compute_serial_waves"] = g.cs_serial m["user_sgprs"] = g.cs["user"] if getattr(g, "msc_layout", None): # --mesh-compute: dispatch it as compute (same grid), then draw the slots with tools/mesh_compute_vs.py. @@ -23875,7 +23929,15 @@ def _clean_stale_spirv_temps(out): "--eliminate-local-single-block", "--redundancy-elimination", "--eliminate-dead-code-aggressive") -def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as", validate=True, compact=False): +SPIRV_OPT_SSA_PASSES = ( + "--convert-local-access-chains", "--ssa-rewrite", "--eliminate-dead-code-aggressive", + "--ccp", "--simplify-instructions", "--redundancy-elimination", + "--eliminate-dead-const", "--merge-blocks", +) +SPIRV_OPT_LARGE_BYTES = 750 * 1024 # >= 750 KiB uses SSA passes to avoid NVIDIA 590 --scalar-replacement=0 crash + + +def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as", validate=True, compact=False, spirv_opt=False): """Keep the assembled module out of the final path until validation succeeds. `assembler="spirv-as"` invokes the external spirv-as binary on `sa` (default); @@ -23912,7 +23974,26 @@ def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as", validate=True, c result.stdout = result.stdout.decode("utf-8", "replace") if isinstance(result.stderr, bytes): result.stderr = result.stderr.decode("utf-8", "replace") - if result.returncode == 0 and compact: + if result.returncode == 0 and spirv_opt: + opt_tmp = Path(str(tmp) + ".opt.spv") + try: + sz = tmp.stat().st_size + opt_flags = SPIRV_OPT_SSA_PASSES if sz >= SPIRV_OPT_LARGE_BYTES else ("-O",) + opt_res = _run_spirv_tool(["spirv-opt", "--target-env=vulkan1.3", "--skip-validation", + *opt_flags, tmp.name, "-o", opt_tmp.name], + capture_output=True, text=True, cwd=folder) + if opt_res.returncode == 0: + if validate: + val_opt = _run_spirv_tool(["spirv-val", "--target-env", "vulkan1.2", + "--allow-offset-texture-operand", opt_tmp.name], + capture_output=True, text=True, cwd=folder) + if val_opt.returncode == 0: + opt_tmp.replace(tmp) + else: + opt_tmp.replace(tmp) + finally: + opt_tmp.unlink(missing_ok=True) + elif result.returncode == 0 and compact: # spirv-opt lacks spirv-val's maintenance8 offset switch. Use the same project validator # below on the optimized binary, before publishing it. Both paths stay ASCII for Windows. result = _run_spirv_tool(["spirv-opt", "--target-env=vulkan1.2", "--skip-validation", @@ -24042,6 +24123,12 @@ def main(): help="with --wave64-emulate: a mesh shader of more than 64 threads whose waves cannot pass each " "other anything (no LDS, no store or atomic) runs its waves one after the other in 64 " "invocations, one single-wave pass per wave, instead of side by side (docs/design.md)") + ap.add_argument("--compute-serial-waves", action="store_true", + help="with --wave64-emulate: a compute shader of more than 64 threads with no LDS, s_barrier or " + "atomic runs its waves one after the other in 64 invocations (metadata: compute_serial_waves)") + ap.add_argument("--mesh-native-wave32", action="store_true", + help="with --wave64-emulate: partition-invariant mesh shaders skip wave64 emulation and run " + "natively in 1 pass at full LocalSize on 32-wide subgroups (metadata: mesh_native_wave32)") ap.add_argument("--shader-clock", choices=("off", "khr"), default="off", help="s_memtime / s_memrealtime: off = Unsupported (default), khr = OpReadClockKHR (needs " "VK_KHR_shader_clock; feature shaderSubgroupClock / shaderDeviceClock in the metadata)") @@ -24083,6 +24170,9 @@ def main(): "but compiles 1.7-2x slower on NVIDIA (SHADER-427, docs/design.md \"Control flow\")") ap.add_argument("--compact-spirv", action="store_true", help="remove redundant local loads, repeated values and dead instructions with spirv-opt") + ap.add_argument("--spirv-opt", action="store_true", + help="run spirv-opt (-O below 750 KiB, safe SSA pass set at >= 750 KiB) with automatic fallback " + "to unoptimized SPIR-V if spirv-opt or spirv-val rejects the optimized module") ap.add_argument("--opt", action="store_true", help="run basic-block SPIR-V peephole optimization (tools/spirv_opt.py: register store-to-load " "forwarding, OpAccessChain CSE, dead-store elimination, OpSelect/CopyObject folding, DCE)") @@ -24116,7 +24206,7 @@ def _on_sigterm(_signum, _frame): MAX_STRUCTURED_DEPTH = a.max_structured_depth global INTEGER_DOT_FALLBACK global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, EXPLICIT_LOD_BIAS, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV - global MESH_SERIAL_WAVES + global MESH_SERIAL_WAVES, COMPUTE_SERIAL_WAVES, MESH_NATIVE_WAVE32 global PC_TAIL_UBO, ADDR_PAIR, ADDRESS_GUARD PC_TAIL_UBO = a.pc_tail_ubo ADDRESS_GUARD = a.address_guard @@ -24139,6 +24229,8 @@ def _on_sigterm(_signum, _frame): EXPLICIT_LOD_BIAS = a.explicit_lod_bias MESH_COMPUTE = a.mesh_compute MESH_SERIAL_WAVES = a.mesh_serial_waves + COMPUTE_SERIAL_WAVES = a.compute_serial_waves + MESH_NATIVE_WAVE32 = a.mesh_native_wave32 F16_HALVES = a.f16_interp_fallback OPT_SPIRV = a.opt if a.merge: @@ -24244,7 +24336,7 @@ def drop_stale(name): f.write(asm) try: r = assemble_spirv(sa, sv, asm_text=asm, assembler=a.assembler, validate=not a.no_validate, - compact=a.compact_spirv) + compact=a.compact_spirv, spirv_opt=a.spirv_opt) except OSError as e: # A missing spirv-as/spirv-val fails every shader the same way; report it once as a setup # error (exit 2) instead of a FileNotFoundError traceback from the first one. From 098f7ff761cef6de2fab29464c50a3f262f23bef Mon Sep 17 00:00:00 2001 From: Dimitar Pavlov <360593571+azsekazvamdimitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:59:57 +0200 Subject: [PATCH 3/5] rdna2spirv: guard v_readfirstlane in --mesh-native-wave32 and lower --spirv-opt SSA threshold to 512 KiB - Exclude v_readfirstlane from --mesh-native-wave32 until per-use uniformity analysis proves the source wave-uniform (with ms_native_readfirstlane.asm and test_mesh_native_wave32.py regression test + docs/design.md update). - Lower SPIRV_OPT_LARGE_BYTES from 750 KiB to 512 KiB so library/lib_cs_03245 and siblings use the safe SSA pass set instead of --scalar-replacement=0 (avoiding NVIDIA 590.48.01 compiler SIGSEGV during warmup). AI-assisted. --- docs/design.md | 2 ++ tests/semantic/ms_native_readfirstlane.asm | 8 ++++++++ tests/semantic/test_mesh_native_wave32.py | 19 ++++++++++++++++--- tools/rdna2spirv.py | 7 +++++-- 4 files changed, 31 insertions(+), 5 deletions(-) create mode 100644 tests/semantic/ms_native_readfirstlane.asm diff --git a/docs/design.md b/docs/design.md index 79385b39d7..fe636200da 100644 --- a/docs/design.md +++ b/docs/design.md @@ -375,6 +375,7 @@ How the generated SPIR-V expects the runtime to work: | Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. All 9,282 mesh-shader listings of 1.0.2.1 (names starting with `.` included) read exactly v5 before writing anything (`rdna2spirv.read_before_write_vgprs` over the code `translate()` keeps). An earlier sample of 1,500 put 27 aside as adding loop-carried registers; over the corpus no extra read is loop-carried. Read raw, 266 of the 309 listings with embedded data words seem to read more VGPRs, each after a branch (in 101 the register is written after the read); they come from data words decoded as instructions and are gone once the listing is re-anchored to the FSSM code and cut to reachable code, as `translate()` does. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). `%ms_cull` (the `PerPrimitiveEXT` `CullPrimitiveEXT` `Block`) is listed before `%ms_out_vtx` in `OpEntryPoint MeshEXT`'s interface list: AMD's proprietary Windows Vulkan driver `24.10.24` (LLPC) was reported, on one Ryzen 5 7600 iGPU, to segfault (`0xC0000005`) during `vkCreateGraphicsPipelines` when the per-vertex clip/cull `Block` precedes the per-primitive `Block` (even on `glslangValidator` output), while driver `32.0.32029.2010` on an RX 9070 XT and an RX 7900 XT accepts either order; the order has no meaning in SPIR-V, so this one costs nothing on other drivers; reordering the interface list fixes `ms_clip` on AMD Ryzen 5 7600 RDNA2 iGPU (`2048/2048` clipped, `2048/2048` drawn, `4096/4096` culled when `CullPrimitiveEXT = true`, 0 validation errors) while keeping `CullPrimitiveEXT` in its `Block+bool` form for SPIRV-Tools ≤2025.1 (`SHADER-MS-CLIP-IFACE`). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. `Layer` and `ViewportIndex` from the `pos1` misc vector (`z[10:0]`, `z[19:16]`) are per-primitive members of `%ms_cull` (`Gen.export_misc_pos1`): each lane stages the value it exports and writes it to the primitive with its own index. That is exact when the value is the same for all vertices of a primitive; whether the hardware takes it from the primitive's provoking vertex instead is not measured. Confirmed by the translator tests (`tests/test_translate.py`); none of the 1,906 mesh shaders of the corpus that export `pos1` writes either, so the game's mesh shaders only gain unused declarations. Compressed exports (`exp pos1` / `exp param` with `compr`) unpack their two f16 pairs the way the pixel-shader compressed export does (`Gen.export_comps`): LLVM lists each register twice (`v4, v4, v5, v5`), so the pair is operands 1 and 3, each unpacked with `UnpackHalf2x16` into (x, y) and (z, w), and an `off` register leaves its two components unwritten. Before, such an export was refused. Confirmed by the translator tests (`tests/test_translate.py`); none of the 9,282 mesh shaders of the corpus uses one, so the game's translation does not change. | | Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one), and on by itself in `make_game.py` on Intel's Windows Vulkan driver (`VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS` with mesh shaders, `runtime_gpu_mesh_draws_crash`): there `vkCmdDrawMeshTasksEXT` crashes (0xC0000409 in `igvk64.dll`) for a mesh shader with a live push-constant load at byte 32 or later, which every corpus mesh shader has, while `--mesh-compute` is exact (BUILD-2202, Arc A770, driver 32.0.101.9175; no fixed version known; `--native-mesh` keeps native mesh shaders). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | | Mesh shaders with their waves in series (`--mesh-serial-waves`) | With `--wave64-emulate`, a mesh shader of more than 64 threads is several waves side by side in one workgroup, and what its waves do not do alike (a region one wave enters and the other skips, with votes or memory accesses inside) goes to mini-schedulers: a round loop over a `%pc` switch. With this flag a mesh shader whose thread count is a multiple of 64 and whose waves cannot pass each other anything (no `ds_` instruction, no store or atomic to memory) declares `LocalSize 64` and runs one pass per wave instead (`ms_serial_passes`, `ms_serial_epilogue`). `%local_index` becomes a Function variable, the built-in (`%real_local_index`) plus 64 x pass, so the launch state (v5, the wave id in s3) and every lane computation see the wave of the pass; every initialised Function variable is stored again at the start of a pass; what a pass exported is copied to per-pass twins of the export variables; after the loop the epilogue does its barrier, reads the counts and calls `OpSetMeshOutputsEXT` once, then writes each pass's vertices and primitives at index built-in + 64 x pass. Under `--mesh-compute` (devices without `VK_EXT_mesh_shader`, such as NVIDIA Pascal) the compute program does the same, and its slot writes (`mesh_compute_epilogue`) are repeated per pass the same way: the header from index 0, which only pass 0's lane 0 has, each pass's vertices and primitives at built-in + 64 x pass; the metadata keeps the program's thread count in `local_size` (the runtime only checks it for whole subgroups and the invocation limit, which 64 passes as well). Each pass is one wave, so the plan is the single-wave one (`inline_all` when the program has branches) and the exchange buffer is one wave's, addressed by the invocation's own index. Why the order of the waves is not observable: the waves of such a program share nothing but the allocation request and the exports, which the epilogue orders itself (the request may come from any wave: the counts are read after all passes). A program that shares LDS (`ms_wave_info_s3`) or writes memory keeps the side-by-side form, as does everything without the flag: off by default, and with it off the output is unchanged. Measured on an RTX 4080 (NVIDIA 621.24, 32-wide subgroups): the `ms_*` GPU tests pass in both forms, among them `ms_w64x_wave_votes`, whose two waves take different branches with their own ballots and whose triangle takes vertices from both; module shape by `tests/test_mesh_serial_waves.py`. Not measured: other vendors, llvmpipe, a thread count that is not a multiple of 64 (kept side by side). | +| Native Wave32 mesh eligibility (`--mesh-native-wave32`) | With `--wave64-emulate`, a mesh shader whose program passes the instruction check in `translate()` (no `ds_`, no store or atomic, no `v_readlane`/`v_writelane`/`v_permlane`, DPP or quad op, no `s_bcnt1`/`s_ff1`/`s_flbit`, and no `v_mbcnt` of anything but `-1`) runs its 128 threads as four native 32-wide subgroups instead of the emulated workgroup. `v_readfirstlane_b32` is not partition-invariant: the hardware gives the first lane on in EXEC of the wave one value for all 64 lanes, and on a 32-wide subgroup each subgroup takes its own first active lane, so the halves disagree whenever the source VGPR is not wave-uniform. A mesh shader with any `v_readfirstlane_b32` therefore keeps the emulation. Count over the corpus: 9,282 of 9,282 mesh shaders have at least one (about 71,000 uses; 10,672 read `v5`, the rest other VGPRs), so with this rule the flag selects 0 of 9,282 instead of 9,116. The group-index idiom of the row above is invariant by itself (every lane's `v5 >> 7` is the group index) and is emulated only because the check is per instruction, not per consumer; a per-use rule that admits a read `wave64_halves.py` proves wave-uniform (`readfirstlane-uniform`, `waterfall`) is the follow-up, confirmed by a GPU test before any corpus shader runs native again. Confirmed by the synthetic `tests/semantic/ms_native_readfirstlane.asm` (the lane number read back per lane: the translator must select full-wave emulation) and by the count. Why now: with the 9,116 native modules the full corpus lost the device in every boot that reached the world on an RTX 3090 (3 of 3, `VK_ERROR_DEVICE_LOST`; the same runtime with emulated mesh shaders, 0 of 13), and the loss followed the dxbc pack; no single shader was isolated. | | Mesh primitive export and allocation (`exp prim`, `MSG_GS_ALLOC_REQ`) | The GFX10 NGG formats, from Mesa 22.3 `src/amd/llvm/ac_llvm_build.c`: `ac_build_sendmsg_gs_alloc_req` (lines 4475–4477) puts `prim_cnt << 12 \| vtx_cnt` in m0, and `ac_pack_prim_export` (lines 4518–4539) packs index 0, 1 and 2 in bits 0–8, 10–18 and 20–28, the edge flags in bits 9, 19 and 29 and "null primitive (skip)" in bit 31. Thread t exports vertex t and primitive t, only below the vertex and primitive counts (`src/amd/common/ac_nir_lower_ngg.c`, `emit_ms_finale`, lines 4056–4067). Translated: the counts from m0 (each clamped to PSV0's maximum) go to `OpSetMeshOutputsEXT` or the `--mesh-compute` header; `PrimitiveTriangleIndicesEXT` takes the three 9-bit fields without the edge flags, and `CullPrimitiveEXT` (or the slot's culled word) is bit 31; invocations at or past a count write nothing. **Indices stay below the vertex count**: every `exp prim` in the corpus comes from an epilogue that compares each 10-bit field with the vertex count and, when one is at or past it, sets bit 31 and keeps the fields (count over the 1.0.2.1 corpus: all 8,666 listings with `exp prim`), so a null primitive can carry indices up to 511. The hardware skips it, but `VK_EXT_mesh_shader` leaves an index at or past the vertex count undefined even on a culled primitive. The translator writes index k as `null ? 0 : umin(field_k, vertex count - 1)`, as Mesa's mesh lowering clamps them (`ac_nir_lower_ngg.c` line 4112), and a primitive count of 0 when the vertex count is 0 (so `vertex count - 1` never wraps); `CullPrimitiveEXT` is unchanged. Until 2026-11-26 the raw fields were written, a suspected cause of device losses in mesh draws on NVIDIA (not confirmed). Executed for both paths in `tests/semantic/test_ms_prim_export.py` (72 threads in two wave64 waves: odd threads set the edge flags, threads with t & 2 the null bit; and `fixtures/ms_prim_null_clamp.asm`, 128 threads at vertex counts 0, 10, 100 and 128, whose null primitives carry fields 300, 511, 0x3FF and the vertex count itself: its assertions fail on the old translator); `spirv-val` accepts both modules, plain and `--wave64-emulate`. **Not GPU-checked.** | | Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks, and rejecting (`Unsupported`) an `OpEmitVertex` in a loop header before its `OpLoopMerge`, which the split would move; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | | Legacy GS wide and strided LDS | `ds_write_b96` and `ds_write_b128` stage three or four consecutive output dwords from consecutive VGPRs. The `ds_read2st64_b32` and `ds_write2st64_b32` immediate offsets each count 64-dword units, as in compute. One such unit advances one synthetic ES input vertex on reads. Writes address the flat staged output slots, each `4 * nreg` dwords wide. The synthetic `tests/test_gs_ds_ring.py` Vulkan readback checks these mappings against ordinary LDS instructions and an unstrided control. | @@ -413,6 +414,7 @@ How the generated SPIR-V expects the runtime to work: | Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and CPU interpreter check both reads at two points of one triangle. [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). The gathered mask is stored to a variable of its own before a reader uses it (`Gen.eager`, as DPP's ballot and shuffle are since SHADER-529): `v_mbcnt` writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary (`active ? popcount(simd_or(...) & below) + acc : old`), where a lane that is off never ran it and its bit was missing from every other lane's count. Confirmed on an Apple M5 (MoltenVK 1.4.2) with `tools/crosslane_fuzz.py --wave 32 --modes native --no-maskdata`: 4 of 100 programs of the default seed mismatched before, none after (SHADER-WAVEMASK-EAGER, `tests/semantic/test_wave_mask_eager.py`). Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). The mask-word gather is emitted for every such data read. EXEC narrowing is a per-lane value in the translator's model, not SPIR-V control flow, and mask-data readers are kept out of lane-local `if (active)` runs, so lanes EXEC has off still execute the gather and contribute the mask bits they hold. The eager store above keeps compiler lowering from moving that subgroup op into an EXEC-selected arm (the MoltenVK failure mode). Narrowed-EXEC SGPR/VCC reads, an independent all-ones SGPR restore, and the composed vector-bitwise masks are covered in `tests/semantic/test_lane_masks_vector_bitwise.py`; `tests/semantic/test_wave_mask_eager.py` checks that no gather is conditional. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | +| Lane masks merged as data (`SHADER-WAVE-LOOP-EXEC-VOTE`, #2501) | When a CFG merge joins a register that is a per-lane mask on one incoming edge and ordinary scalar data on another (for example, a ballot/EXEC-vote loop iterating over set bits with `s_ff1_i32_b32` + `s_bitset0_b32`), `lane_masks.insert_data_merges` inserts an explicit `s_mask_to_data_b32` (`TO_DATA`) on the mask-carrying predecessor so the merge receives the gathered 32-bit/64-bit bitmask rather than each lane's single bit. Without it, a loop draining a lane-mask SGPR via bit-clears can spin on stale per-lane bits in wave64 emulation (observed in retail `lib_cs_03010`: 91–370 ms/call without `TO_DATA` vs < 2.5 ms/frame with it on RTX 3090). Confirmed by `tests/semantic/test_ballot_bit_loop.py` and the full semantic suite (`551 files, 6,680 tests`). | | Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does on some GPUs when it folds an all-constant `Fma` while compiling the pipeline: `runtime/test/shaders/cs_div_fmas_f64.asm`, whose operands are literals, gives the split 0 instead of 2^-60 for `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) on the RTX 4090 (621.24, Windows), RTX 3070 (621.01, Windows) and Quadro RTX 4000 (Turing, 615.71.09, Linux), and the fused result on an RTX 5060 Laptop (Blackwell, 621.24). `cs_div_fmas_f64_rt.asm` reads the same operands at run time from s4..s7 and is fused on the 4090, 3070 and 5060 (and on an RTX 4070, #4536); the f32 `cs_fma_fused` fuses 8/8 on the 4090. `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). | | `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | | `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | diff --git a/tests/semantic/ms_native_readfirstlane.asm b/tests/semantic/ms_native_readfirstlane.asm new file mode 100644 index 0000000000..de5f5ed0dd --- /dev/null +++ b/tests/semantic/ms_native_readfirstlane.asm @@ -0,0 +1,8 @@ +; The first active lane in a full wave64 is lane 0. Reading the lane number in +; two independent wave32 halves would give the second half 32 instead. +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mbcnt_hi_u32_b32 v0, -1, v0 +v_readfirstlane_b32 s4, v0 +v_add_nc_u32_e32 v1, s4, v0 +exp pos0 v1, v1, v1, v1 done +s_endpgm diff --git a/tests/semantic/test_mesh_native_wave32.py b/tests/semantic/test_mesh_native_wave32.py index 4bc7fea2b4..dfdf46002f 100644 --- a/tests/semantic/test_mesh_native_wave32.py +++ b/tests/semantic/test_mesh_native_wave32.py @@ -1,21 +1,25 @@ """Unit tests for --mesh-native-wave32 and --compute-serial-waves. Verifies: - 1. A 128-thread barrier-free compute shader with no LDS or atomics uses --compute-serial-waves + 1. A mesh shader that reads the first active lane retains workgroup wave64 emulation. + 2. A 128-thread barrier-free compute shader with no LDS or atomics uses --compute-serial-waves (LocalSize 64 1 1, compute_serial_waves == 2) when --wave64-emulate --compute-serial-waves are set. - 2. A 128-thread compute shader with s_barrier stays on the side-by-side form (compute_serial_waves not set). - 3. --spirv-opt threshold constants are well-defined and assemble_spirv accepts spirv_opt=False/True cleanly. + 3. A 128-thread compute shader with s_barrier stays on the side-by-side form (compute_serial_waves not set). + 4. --spirv-opt threshold constants select the SSA pass set for large shaders. """ import os import struct import sys import tempfile import unittest +from pathlib import Path +from unittest.mock import patch sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import support # noqa: F401 import rdna2spirv +from test_mesh_cull_store import _dxbc, _mesh_psv0 def _cs_fssm(sx=128, sy=1, sz=1): @@ -51,6 +55,15 @@ def _translate_cs(asm_lines, sx=128, sy=1, sz=1, csw=True): class ComputeSerialWavesAndOptTest(unittest.TestCase): + def test_mesh_first_active_lane_uses_the_whole_wave(self): + source = Path(__file__).with_name("ms_native_readfirstlane.asm") + lines = [line for line in source.read_text(encoding="utf-8").splitlines() if not line.startswith(";")] + dxbc = _dxbc([(b"PSV0", _mesh_psv0(128, 64, 64))]) + with patch.object(rdna2spirv, "WAVE64_EMULATE", True), patch.object(rdna2spirv, "MESH_NATIVE_WAVE32", True): + support.translate_lines("ms_first_active", lines, dxbc=dxbc) + self.assertTrue(rdna2spirv.translate.last_gen.emulate) + self.assertFalse(rdna2spirv.translate.last_gen.ms_native_wave32) + def test_csw_activates_on_barrier_free_128_thread_cs(self): asm, gen, meta = _translate_cs([ "s_mov_b64 exec, -1", diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index d7ea4c01f1..80e323f2cc 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -22603,10 +22603,13 @@ def _uses_vcc_tuple(ins): user_limit = g.cs["user"] if g.cs else USER_SGPRS sys_sgprs = (3,) if stage in ("ms", "gs") else () if WAVE64_EMULATE and g.wave64 and stage in ("cs", "ms"): + # A first-active-lane read can see different values in the two physical subgroups: the lowering takes the + # first active lane of the executing subgroup. Every corpus mesh shader has one on a VGPR other than v5 + # (9,282/9,282), so the flag selects none of them until a per-use rule proves the source wave-uniform. if (MESH_NATIVE_WAVE32 and stage == "ms" and not any( i["op"].startswith("ds_") - or any(b in i["op"] for b in ("v_readlane", "v_writelane", "v_permlane", "s_bcnt1", + or any(b in i["op"] for b in ("v_readlane", "v_readfirstlane", "v_writelane", "v_permlane", "s_bcnt1", "s_ff1", "s_flbit", "_dpp", "quad", "atomic", "store")) or (i["op"].startswith("v_mbcnt_") and not (len(i["args"]) >= 2 and i["args"][1]["k"] == "imm" and i["args"][1]["v"] == -1)) @@ -23934,7 +23937,7 @@ def _clean_stale_spirv_temps(out): "--ccp", "--simplify-instructions", "--redundancy-elimination", "--eliminate-dead-const", "--merge-blocks", ) -SPIRV_OPT_LARGE_BYTES = 750 * 1024 # >= 750 KiB uses SSA passes to avoid NVIDIA 590 --scalar-replacement=0 crash +SPIRV_OPT_LARGE_BYTES = 512 * 1024 # >= 512 KiB uses SSA passes to avoid NVIDIA 590 --scalar-replacement=0 crash def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as", validate=True, compact=False, spirv_opt=False): From 8ebe7cc2e854b9467cd2d464307ece5cd4d2c2ac Mon Sep 17 00:00:00 2001 From: Dimitar Pavlov <360593571+azsekazvamdimitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:32:49 +0200 Subject: [PATCH 4/5] d3d12/vulkan + make_game: ReBAR DMA readback, budgeted staged slabs, test fixes & CLI wiring --- docs/design.md | 2 +- make_game.py | 13 +- runtime/shims/d3d12_title_buffer_windows.h | 80 +++++-- runtime/shims/d3d12_vulkan_device.cpp | 235 ++++++++++++++++++++- runtime/test/arena_staging_test.cpp | 129 +++++++++++ runtime/test/d3d12_existing_heap_test.cpp | 10 +- tools/rdna2spirv.py | 2 +- 7 files changed, 438 insertions(+), 33 deletions(-) diff --git a/docs/design.md b/docs/design.md index fe636200da..ba4abc67a1 100644 --- a/docs/design.md +++ b/docs/design.md @@ -414,7 +414,7 @@ How the generated SPIR-V expects the runtime to work: | Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and CPU interpreter check both reads at two points of one triangle. [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | | Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). The gathered mask is stored to a variable of its own before a reader uses it (`Gen.eager`, as DPP's ballot and shuffle are since SHADER-529): `v_mbcnt` writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary (`active ? popcount(simd_or(...) & below) + acc : old`), where a lane that is off never ran it and its bit was missing from every other lane's count. Confirmed on an Apple M5 (MoltenVK 1.4.2) with `tools/crosslane_fuzz.py --wave 32 --modes native --no-maskdata`: 4 of 100 programs of the default seed mismatched before, none after (SHADER-WAVEMASK-EAGER, `tests/semantic/test_wave_mask_eager.py`). Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). The mask-word gather is emitted for every such data read. EXEC narrowing is a per-lane value in the translator's model, not SPIR-V control flow, and mask-data readers are kept out of lane-local `if (active)` runs, so lanes EXEC has off still execute the gather and contribute the mask bits they hold. The eager store above keeps compiler lowering from moving that subgroup op into an EXEC-selected arm (the MoltenVK failure mode). Narrowed-EXEC SGPR/VCC reads, an independent all-ones SGPR restore, and the composed vector-bitwise masks are covered in `tests/semantic/test_lane_masks_vector_bitwise.py`; `tests/semantic/test_wave_mask_eager.py` checks that no gather is conditional. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | -| Lane masks merged as data (`SHADER-WAVE-LOOP-EXEC-VOTE`, #2501) | When a CFG merge joins a register that is a per-lane mask on one incoming edge and ordinary scalar data on another (for example, a ballot/EXEC-vote loop iterating over set bits with `s_ff1_i32_b32` + `s_bitset0_b32`), `lane_masks.insert_data_merges` inserts an explicit `s_mask_to_data_b32` (`TO_DATA`) on the mask-carrying predecessor so the merge receives the gathered 32-bit/64-bit bitmask rather than each lane's single bit. Without it, a loop draining a lane-mask SGPR via bit-clears can spin on stale per-lane bits in wave64 emulation (observed in retail `lib_cs_03010`: 91–370 ms/call without `TO_DATA` vs < 2.5 ms/frame with it on RTX 3090). Confirmed by `tests/semantic/test_ballot_bit_loop.py` and the full semantic suite (`551 files, 6,680 tests`). | +| Lane masks merged as data (`SHADER-WAVE-LOOP-EXEC-VOTE`, #2501) | When a CFG merge joins a register that is a per-lane mask on one incoming edge and ordinary scalar data on another (for example, a ballot/EXEC-vote loop iterating over set bits with `s_ff1_i32_b32` + `s_bitset0_b32`), `lane_masks.insert_data_merges` inserts an explicit `s_mask_to_data_b32` (`TO_DATA`) on the mask-carrying predecessor so the merge receives the gathered 32-bit/64-bit bitmask rather than each lane's single bit. Without it, a loop draining a lane-mask SGPR via bit-clears can spin on stale per-lane bits in wave64 emulation (observed in retail `lib_cs_03010`: 91–370 ms/call without `TO_DATA` vs < 2.5 ms/frame with it on RTX 3090). Confirmed by `tests/semantic/test_ballot_bit_loop.py` and the full semantic suite (`555 files, 6,727 tests`). | | Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does on some GPUs when it folds an all-constant `Fma` while compiling the pipeline: `runtime/test/shaders/cs_div_fmas_f64.asm`, whose operands are literals, gives the split 0 instead of 2^-60 for `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) on the RTX 4090 (621.24, Windows), RTX 3070 (621.01, Windows) and Quadro RTX 4000 (Turing, 615.71.09, Linux), and the fused result on an RTX 5060 Laptop (Blackwell, 621.24). `cs_div_fmas_f64_rt.asm` reads the same operands at run time from s4..s7 and is fused on the 4090, 3070 and 5060 (and on an RTX 4070, #4536); the f32 `cs_fma_fused` fuses 8/8 on the 4090. `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). | | `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | | `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | diff --git a/make_game.py b/make_game.py index 4d857315ee..20c0b35d40 100644 --- a/make_game.py +++ b/make_game.py @@ -2018,7 +2018,10 @@ def exe_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"), ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo"), ("--compact-spirv", "compact_spirv"), ("--integer-dot-fallback", "integer_dot_fallback"), - ("--mesh-serial-waves", "mesh_serial_waves"), ("--explicit-lod-bias", "explicit_lod_bias")) + ("--mesh-serial-waves", "mesh_serial_waves"), ("--explicit-lod-bias", "explicit_lod_bias"), + ("--compute-serial-waves", "compute_serial_waves"), + ("--mesh-native-wave32", "mesh_native_wave32"), + ("--spirv-opt", "spirv_opt")) def fallback_flags(a) -> tuple[str, ...]: @@ -3688,6 +3691,14 @@ def main() -> int: "Only wave64 mesh shaders of more than 64 threads, a multiple of 64, with no LDS " "instruction, store or atomic take that form; the others, and every shader translated " "natively or with --mesh-compute, come out as before. Off by default") + ap.add_argument("--compute-serial-waves", action="store_true", + help="with wave64 emulation, serialize multi-wave compute shaders in 64 invocations instead " + "of side-by-side wave emulation (forwards --compute-serial-waves to rdna2spirv.py). Off by default") + ap.add_argument("--mesh-native-wave32", action="store_true", + help="forward --mesh-native-wave32 to rdna2spirv.py for eligible mesh shaders. Off by default") + ap.add_argument("--spirv-opt", action="store_true", + help="forward --spirv-opt to rdna2spirv.py (runs spirv-opt -O below 512 KiB and safe SSA passes " + "at >= 512 KiB with automatic fallback on validation failure). Off by default") ap.add_argument("--native-mesh", action="store_true", help="keep native mesh shaders on Intel's Windows Vulkan driver instead of turning on " "--mesh-compute (for a driver that fixes BUILD-2202's crash)") diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h index 5c910285c8..10bf79e8ee 100644 --- a/runtime/shims/d3d12_title_buffer_windows.h +++ b/runtime/shims/d3d12_title_buffer_windows.h @@ -14,14 +14,16 @@ #include #include "../src/arena_staging.h" +#include "../src/memory_breakdown.h" namespace rt::d3d12 { // Storage for shader-addressed mirrors when the main arena has no usable offset. -// Sub-ranges freed via free() are coalesced for reuse; one empty standard 4 MiB block is kept as a spare and any -// other empty block releases its Vulkan buffer and memory. When staged mode is enabled (for BAR-restricted GPUs with -// a staged DEVICE_LOCAL arena), blocks are 64 MiB pure DEVICE_LOCAL VRAM slabs paired with a HOST_VISIBLE staging -// mirror and an exact byte-range dirty tracker, kept pooled until release(). +// Sub-ranges freed via free() are coalesced for reuse; one empty standard block (4 MiB unstaged or 64 MiB staged) is +// kept as a spare and any other empty block releases its Vulkan buffer and memory. When staged mode is enabled (for +// BAR-restricted GPUs with a staged DEVICE_LOCAL arena), blocks are 64 MiB pure DEVICE_LOCAL VRAM slabs paired with a +// HOST_VISIBLE staging mirror and an exact byte-range dirty tracker; both VRAM and host staging bytes count against +// `reserved_` and `cap`. class TitleBufferWindows { static constexpr VkDeviceSize kBlockSize = 4ull << 20; static constexpr VkDeviceSize kStagedBlockSize = 64ull << 20; @@ -79,6 +81,7 @@ class TitleBufferWindows { VkBuffer buffer{}; VkBuffer staging_buffer{}; StagedSlot* staged{}; + bool host_cached{false}; }; std::array published_{}; std::atomic published_count_{0}; @@ -237,28 +240,31 @@ class TitleBufferWindows { }; auto drop_unfitting_spare = [&] { for (auto it = blocks_.begin(); it != blocks_.end(); ++it) { - if (!it->staged && it->live == 0 && bytes > it->capacity) { + if (it->live == 0 && bytes > it->capacity) { destroy_block(d, it); return true; } } return false; }; + const bool make_staged = staged_ && !device_local; + const VkDeviceSize min_budget = make_staged ? (bytes <= UINT64_MAX / 2 ? bytes * 2 : UINT64_MAX) : bytes; VkDeviceSize remaining_cap = reserved_ < cap ? cap - reserved_ : 0; - if (bytes > remaining_cap) { + if (min_budget > remaining_cap) { if (drop_unfitting_spare()) remaining_cap = reserved_ < cap ? cap - reserved_ : 0; - if (bytes > remaining_cap) { + if (min_budget > remaining_cap) { if (at_cap) *at_cap = true; return false; } } - const bool make_staged = staged_ && !device_local; const VkDeviceSize slab_size = make_staged ? kStagedBlockSize : kBlockSize; + const VkDeviceSize max_single = make_staged ? remaining_cap / 2 : remaining_cap; Block b{}; - b.capacity = std::max(bytes, std::min(slab_size, remaining_cap)); + b.capacity = std::max(bytes, std::min(slab_size, max_single)); VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = b.capacity; - info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | + VK_BUFFER_USAGE_TRANSFER_SRC_BIT; if (make_staged) { info.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | @@ -285,23 +291,32 @@ class TitleBufferWindows { void* host{}; VkResult bound = VK_ERROR_OUT_OF_DEVICE_MEMORY, mapped_result = VK_ERROR_MEMORY_MAP_FAILED; bool block_staged = false; + bool block_host_cached = false; + VkDeviceSize staging_reserved = 0; if (make_staged && !local_refused_) { VkMemoryPropertyFlags vram_chosen = 0; - VkDeviceMemory vram_mem = d.allocate(req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, &vram_chosen, true); + VkDeviceMemory vram_mem = VK_NULL_HANDLE; + { + leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows); + vram_mem = d.allocate(req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, &vram_chosen, true); + } VkBuffer staging_buf = VK_NULL_HANDLE; VkDeviceMemory staging_mem = VK_NULL_HANDLE; + VkMemoryRequirements sreq{}; if (vram_mem && (vram_chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { VkBufferCreateInfo sinfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; sinfo.size = b.capacity; sinfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; d.share(sinfo); if (vk.vkCreateBuffer(d.info.device, &sinfo, nullptr, &staging_buf) == VK_SUCCESS) { - VkMemoryRequirements sreq{}; vk.vkGetBufferMemoryRequirements(d.info.device, staging_buf, &sreq); - sreq.memoryTypeBits = system_memory_types(d, sreq.memoryTypeBits, /*cached=*/true); - staging_mem = d.allocate(sreq, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - VK_MEMORY_PROPERTY_HOST_CACHED_BIT, nullptr, false); + if (req.size <= remaining_cap && sreq.size <= remaining_cap - req.size) { + sreq.memoryTypeBits = system_memory_types(d, sreq.memoryTypeBits, /*cached=*/true); + leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging); + staging_mem = d.allocate( + sreq, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + VK_MEMORY_PROPERTY_HOST_CACHED_BIT, nullptr, false); + } } } if (vram_mem && staging_buf && staging_mem && @@ -314,6 +329,8 @@ class TitleBufferWindows { bound = VK_SUCCESS; mapped_result = VK_SUCCESS; block_staged = true; + block_host_cached = true; + staging_reserved = sreq.size; } else { if (staging_buf) vk.vkDestroyBuffer(d.info.device, staging_buf, nullptr); if (staging_mem) vk.vkFreeMemory(d.info.device, staging_mem, nullptr); @@ -355,6 +372,7 @@ class TitleBufferWindows { "this and later blocks are in host memory\n", static_cast(req.size >> 10)); } + if (b.memory) block_host_cached = (chosen & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) != 0; if (!b.memory) note_block_failure("vkAllocateMemory (DeviceState::allocate)", bound, req.size); else if ((bound = vk.vkBindBufferMemory(d.info.device, b.buffer, b.memory, 0)) != VK_SUCCESS) note_block_failure("vkBindBufferMemory", bound, req.size); @@ -370,7 +388,7 @@ class TitleBufferWindows { if constexpr (requires { d.vsharp_offsets_signed(); }) signed_offsets = d.vsharp_offsets_signed(); if (shader_reachable(b.address, b.capacity, d.arena.address, signed_offsets)) { b.mapped = static_cast(host); - b.reserved_bytes = req.size; + b.reserved_bytes = req.size + staging_reserved; b.free_ranges.emplace(0, b.capacity); if (block_staged) { b.staged = std::make_unique(); @@ -382,12 +400,13 @@ class TitleBufferWindows { published_[n].buffer = b.buffer; published_[n].staging_buffer = b.staging_buffer; published_[n].staged = b.staged.get(); + published_[n].host_cached = block_host_cached; published_[n].address.store(b.address, std::memory_order_relaxed); published_count_.store(n + 1, std::memory_order_release); } layout_generation_.fetch_add(1, std::memory_order_release); blocks_.push_back(std::move(b)); - reserved_ += req.size; + reserved_ += blocks_.back().reserved_bytes; if (blocks_.size() == 1 || !(blocks_.size() & (blocks_.size() - 1))) std::fprintf(stderr, "[rt] d3d12: title buffer shadows outside the arena%s: %zu blocks, " "new block %llu KiB at shader VA 0x%llx\n", @@ -446,7 +465,8 @@ class TitleBufferWindows { b.free_ranges.emplace(merged_begin, merged_end - merged_begin); if (b.live > 0) --b.live; if (b.live == 0) { - if (b.staged || (b.capacity == kBlockSize && empty_blocks() == 1)) { + const VkDeviceSize std_cap = b.staged ? kStagedBlockSize : kBlockSize; + if (b.capacity == std_cap && empty_blocks() == 1) { b.free_ranges.clear(); b.free_ranges.emplace(0, b.capacity); b.used = 0; @@ -562,6 +582,28 @@ class TitleBufferWindows { } } + // If [ptr, ptr+len) lies in an uncached (e.g. ReBAR WC BAR1) non-staged block, returns true with its VkBuffer + // and byte offset so callers can DMA-read it into a HOST_CACHED scratch buffer instead of doing slow WC reads. + bool find_uncached_buffer(const std::uint8_t* ptr, std::size_t len, VkBuffer& out_buffer, + VkDeviceSize& out_offset) const { + if (staged_ || !ptr || !len) return false; + const auto p = reinterpret_cast(ptr); + const std::size_t n = published_count_.load(std::memory_order_acquire); + for (std::size_t i = 0; i < n; ++i) { + const Published& b = published_[i]; + if (b.host_cached || b.staged || !b.mapped || !b.buffer || !b.address.load(std::memory_order_acquire)) + continue; + const auto lo = reinterpret_cast(b.mapped); + const auto hi = lo + static_cast(b.capacity); + if (p >= lo && p < hi && len <= hi - p) { + out_buffer = b.buffer; + out_offset = static_cast(p - lo); + return true; + } + } + return false; + } + // Synchronously reads back GPU-written ranges from each staged block's VRAM buffer into its staging mirror // in a single batched submission. template diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 553c90e6fd..a1ebe70b40 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -462,8 +462,35 @@ class ShadowPages { // // `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. + struct ReadbackLookup { + struct Entry { + std::uintptr_t src_lo = 0; + std::uintptr_t src_hi = 0; + const std::uint8_t* cached = nullptr; + }; + const Entry* entries = nullptr; + std::size_t count = 0; + const std::uint8_t* map(const std::uint8_t* ptr, std::size_t len) const { + if (!entries || !count || !ptr || !len) return ptr; + const auto p = reinterpret_cast(ptr); + std::size_t lo = 0, hi = count; + while (lo < hi) { + const std::size_t mid = lo + (hi - lo) / 2; + if (entries[mid].src_lo <= p) + lo = mid + 1; + else + hi = mid; + } + if (lo == 0) return ptr; + const Entry& e = entries[lo - 1]; + if (p >= e.src_lo && p < e.src_hi && len <= e.src_hi - p) return e.cached + (p - e.src_lo); + return ptr; + } + }; + std::size_t write_back(const std::pair* ranges, std::size_t count, - std::size_t* reached = nullptr, const std::uint8_t* only = nullptr) { + std::size_t* reached = nullptr, const std::uint8_t* only = nullptr, + const ReadbackLookup* readback = nullptr) { if (reached) *reached = 0; std::uintptr_t lo = last_, hi = first_; // the pages the ranges cover for (std::size_t r = 0; r < count; ++r) { @@ -562,7 +589,8 @@ class ShadowPages { 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 std::uint8_t* raw_copy = t->shadow + (x - t->begin); + const std::uint8_t* copy = readback ? readback->map(raw_copy, y - x) : raw_copy; const void* now = saved ? static_cast(before + (x - c)) : reinterpret_cast(x); if (std::memcmp(now, copy, y - x) == 0) continue; @@ -603,9 +631,13 @@ class ShadowPages { if (o == t) continue; const std::uintptr_t lo = std::max(i, o->begin); const std::uintptr_t hi = std::min(j, o->end); + const std::uint8_t* o_read = + readback && lo < hi + ? readback->map(o->shadow + (lo - o->begin), hi - lo) + : (o->shadow + (lo - o->begin)); std::uintptr_t run_start = hi; for (std::uintptr_t v = lo; v < hi; ++v) { - if (o->shadow[v - o->begin] == before[v - c]) { + if (o_read[v - lo] == before[v - c]) { o->shadow[v - o->begin] = copy[v - x]; if (dirty_fn_ && run_start == hi) run_start = v; } else if (dirty_fn_ && run_start < v) { @@ -4304,13 +4336,18 @@ struct DeviceState { if (!s.has_target(mapped)) continue; const std::pair range{static_cast(start), static_cast(start + size)}; + ShadowPages::ReadbackLookup rebar_lookup{}; if (arena.staged) { std::vector readbacks; std::map> ext_readbacks; collect_staged_shadow_readbacks(s, &range, 1, mapped, readbacks, ext_readbacks); sync_retired_readbacks_to_host(readbacks, ext_readbacks); + } else { + prepare_rebar_readbacks( + [&](const auto& add) { s.for_each_target_range(&range, 1, mapped, add); }, rebar_lookup); } - title_write_back_total += s.write_back(&range, 1, nullptr, mapped); + title_write_back_total += + s.write_back(&range, 1, nullptr, mapped, rebar_lookup.count ? &rebar_lookup : nullptr); s.remove_target(mapped); if (!s.targets()) shadows.erase(it); return; @@ -4559,12 +4596,29 @@ struct DeviceState { } } + static VkDeviceSize external_window_cap(bool staged) { + static const VkDeviceSize env_cap = []() -> VkDeviceSize { + char text[32] = {}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_EXTERNAL_WINDOWS_MB", text, sizeof(text)); + if (n > 0 && n < sizeof(text)) { + const unsigned long long mb = std::strtoull(text, nullptr, 10); + if (mb > 0) return VkDeviceSize(mb) << 20; + } + return 0; + }(); + if (env_cap) return env_cap; + // Staged mode counts both VRAM and host staging mirror in reserved_; 4 GiB total = up to 2 GiB VRAM + 2 GiB + // sysmem mirror. Unstaged mode caps at 2 GiB. + return staged ? (4096ull << 20) : (2048ull << 20); + } + bool external_windows_allocate(VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped, VkBuffer* out_buffer = nullptr, VkDeviceSize* out_buffer_offset = nullptr, VkDeviceAddress* out_address = nullptr) { std::lock_guard lock(external_windows_mutex); drain_deferred_external_frees_locked(); - if (!external_windows.allocate(*this, bytes, offset, mapped, false, UINT64_MAX, nullptr, out_buffer, + if (!external_windows.allocate(*this, bytes, offset, mapped, false, + external_window_cap(external_windows.staged()), nullptr, out_buffer, out_buffer_offset, out_address)) return false; external_window_made.store(true, std::memory_order_release); @@ -4607,6 +4661,159 @@ struct DeviceState { } }); } + + // Grow-only HOST_VISIBLE | HOST_CACHED scratch buffer for DMA readback from uncached ReBAR (WC BAR1) arena + // and external window buffers during ShadowPages::write_back. Guarded by shadow_mutex. + struct RebarReadbackScratch { + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + std::uint8_t* mapped = nullptr; + VkDeviceSize capacity = 0; + bool coherent = true; + std::vector entries; + } rebar_readback; + + void destroy_rebar_readback() { + if (!context) return; + auto& vk = context->vk; + if (rebar_readback.mapped && rebar_readback.memory) { + vk.vkUnmapMemory(info.device, rebar_readback.memory); + rebar_readback.mapped = nullptr; + } + if (rebar_readback.buffer) { + vk.vkDestroyBuffer(info.device, rebar_readback.buffer, nullptr); + rebar_readback.buffer = VK_NULL_HANDLE; + } + if (rebar_readback.memory) { + vk.vkFreeMemory(info.device, rebar_readback.memory, nullptr); + rebar_readback.memory = VK_NULL_HANDLE; + } + rebar_readback.capacity = 0; + rebar_readback.entries.clear(); + } + + bool ensure_rebar_readback(VkDeviceSize need) { + if (need <= rebar_readback.capacity && rebar_readback.buffer && rebar_readback.mapped) return true; + if (!context) return false; + VkDeviceSize cap = std::max(rebar_readback.capacity ? rebar_readback.capacity * 2 : (16ull << 20), + (need + 65535ull) & ~65535ull); + auto& vk = context->vk; + VkBufferCreateInfo binfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + binfo.size = cap; + binfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + share(binfo); + VkBuffer buf = VK_NULL_HANDLE; + if (vk.vkCreateBuffer(info.device, &binfo, nullptr, &buf) != VK_SUCCESS) return false; + VkMemoryRequirements req{}; + vk.vkGetBufferMemoryRequirements(info.device, buf, &req); + VkMemoryPropertyFlags chosen = 0; + VkDeviceMemory mem = VK_NULL_HANDLE; + { + leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging); + mem = allocate(req, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | + VK_MEMORY_PROPERTY_HOST_CACHED_BIT, + 0, &chosen, false); + } + void* ptr = nullptr; + if (!mem || vk.vkBindBufferMemory(info.device, buf, mem, 0) != VK_SUCCESS || + vk.vkMapMemory(info.device, mem, 0, VK_WHOLE_SIZE, 0, &ptr) != VK_SUCCESS) { + if (buf) vk.vkDestroyBuffer(info.device, buf, nullptr); + if (mem) vk.vkFreeMemory(info.device, mem, nullptr); + return false; + } + destroy_rebar_readback(); + rebar_readback.buffer = buf; + rebar_readback.memory = mem; + rebar_readback.mapped = static_cast(ptr); + rebar_readback.capacity = cap; + rebar_readback.coherent = (chosen & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0; + return true; + } + + bool arena_uncached_rebar() const { + if (arena.staged || !arena.buffer || !arena.mapped || !arena.size) return false; + if (arena.memory_type >= memory.memoryTypeCount) return false; + const VkMemoryPropertyFlags flags = memory.memoryTypes[arena.memory_type].propertyFlags; + return (flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) == 0; + } + + template + bool prepare_rebar_readbacks(Emit&& emit, ShadowPages::ReadbackLookup& out) { + out = {}; + if (arena.staged || !context) return false; + const bool arena_wc = arena_uncached_rebar(); + const auto arena_lo = reinterpret_cast(arena.mapped); + const auto arena_hi = arena_lo + static_cast(arena.size); + struct Req { + VkBuffer buf; + VkDeviceSize src_off; + std::uintptr_t src_ptr; + VkDeviceSize len; + }; + std::vector reqs; + emit([&](const std::uint8_t* ptr, std::size_t len) { + if (!ptr || !len) return; + const auto p = reinterpret_cast(ptr); + if (arena_wc && p >= arena_lo && p < arena_hi && len <= arena_hi - p) { + reqs.push_back({arena.buffer, static_cast(p - arena_lo), p, static_cast(len)}); + return; + } + VkBuffer ext_buf = VK_NULL_HANDLE; + VkDeviceSize ext_off = 0; + if (external_windows.find_uncached_buffer(ptr, len, ext_buf, ext_off)) + reqs.push_back({ext_buf, ext_off, p, static_cast(len)}); + }); + if (reqs.empty()) return false; + std::sort(reqs.begin(), reqs.end(), [](const Req& a, const Req& b) { + if (a.buf != b.buf) return a.buf < b.buf; + if (a.src_off != b.src_off) return a.src_off < b.src_off; + return a.len > b.len; + }); + // Merge overlapping/adjacent ranges per VkBuffer. + std::vector merged; + merged.reserve(reqs.size()); + for (const Req& r : reqs) { + if (!merged.empty() && merged.back().buf == r.buf && + r.src_off <= merged.back().src_off + merged.back().len) { + const VkDeviceSize end = std::max(merged.back().src_off + merged.back().len, r.src_off + r.len); + merged.back().len = end - merged.back().src_off; + } else { + merged.push_back(r); + } + } + VkDeviceSize total = 0; + for (const Req& r : merged) total = ((total + 63ull) & ~63ull) + r.len; + if (!ensure_rebar_readback(total)) return false; + std::vector> per_buf_copies; + std::vector bufs; + rebar_readback.entries.clear(); + rebar_readback.entries.reserve(merged.size()); + VkDeviceSize dst_off = 0; + for (const Req& r : merged) { + dst_off = (dst_off + 63ull) & ~63ull; + if (bufs.empty() || bufs.back() != r.buf) { + bufs.push_back(r.buf); + per_buf_copies.emplace_back(); + } + per_buf_copies.back().push_back({r.src_off, dst_off, r.len}); + rebar_readback.entries.push_back( + {r.src_ptr, r.src_ptr + static_cast(r.len), rebar_readback.mapped + dst_off}); + dst_off += r.len; + } + std::vector batches; + batches.reserve(bufs.size()); + for (std::size_t i = 0; i < bufs.size(); ++i) + batches.push_back({bufs[i], rebar_readback.buffer, per_buf_copies[i]}); + if (!context->copy_buffers_sync(batches, info.queue, info.queue_family)) { + rebar_readback.entries.clear(); + return false; + } + std::sort(rebar_readback.entries.begin(), rebar_readback.entries.end(), + [](const auto& a, const auto& b) { return a.src_lo < b.src_lo; }); + out = {rebar_readback.entries.data(), rebar_readback.entries.size()}; + return true; + } std::vector title_windows; std::atomic title_window_count{0}; // title_windows.size(), read without the mutex std::uint64_t title_window_bytes = 0; @@ -5253,6 +5460,7 @@ struct DeviceState { // Each shadow takes all the ranges over it in one call, in address order (batches can overlap), and // decides which of its pages are held once for all of them (ShadowPages::write_back). std::vector> over; + ShadowPages::ReadbackLookup rebar_lookup{}; if (arena.staged) { std::vector readbacks; std::map> ext_readbacks; @@ -5266,6 +5474,19 @@ struct DeviceState { ext_readbacks); } sync_retired_readbacks_to_host(readbacks, ext_readbacks); + } else { + prepare_rebar_readbacks( + [&](const auto& add) { + for (const ShadowPagesPtr& s : shadows) { + over.clear(); + for (const auto& [begin, end] : finished) + if (end > s->first() && begin < s->last()) + over.push_back( + {static_cast(begin), static_cast(end)}); + if (!over.empty()) s->for_each_target_range(over.data(), over.size(), nullptr, add); + } + }, + rebar_lookup); } for (const ShadowPagesPtr& s : shadows) { over.clear(); @@ -5274,7 +5495,8 @@ struct DeviceState { over.push_back({static_cast(begin), static_cast(end)}); if (over.empty()) continue; std::size_t reached = 0; - written += s->write_back(over.data(), over.size(), &reached); + written += s->write_back(over.data(), over.size(), &reached, nullptr, + rebar_lookup.count ? &rebar_lookup : nullptr); ranges += reached; } } @@ -24125,6 +24347,7 @@ class Device final state_.report_arena(); state_.destroy_address_guard(); if (state_.context) state_.destroy_page_mirror(); + state_.destroy_rebar_readback(); if (state_.context && state_.arena.buffer) { state_.context->set_arena_upload(nullptr, nullptr); leonida::fsdraw::forget_arena(&state_); diff --git a/runtime/test/arena_staging_test.cpp b/runtime/test/arena_staging_test.cpp index e0a3ac5fdd..2df2c66f06 100644 --- a/runtime/test/arena_staging_test.cpp +++ b/runtime/test/arena_staging_test.cpp @@ -3,6 +3,7 @@ // coalescing, requeue, persistent mapped ranges, and readback subtraction. // No game data. #include "../src/arena_staging.h" +#include "../shims/d3d12_title_buffer_windows.h" #include #include @@ -273,6 +274,133 @@ int test_compaction_under_many_small_marks() { return 0; } +int test_staged_slab_budget_and_reclamation() { + using leonida::memory_breakdown::Consumer; + struct MockVk { + std::vector buf_sizes; + std::vector> mem_storage; + std::size_t live_buffers = 0; + std::size_t live_memories = 0; + + VkResult vkCreateBuffer(VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*, + VkBuffer* out) { + buf_sizes.push_back(info->size); + *out = reinterpret_cast(static_cast(buf_sizes.size())); + ++live_buffers; + return VK_SUCCESS; + } + void vkDestroyBuffer(VkDevice, VkBuffer b, const VkAllocationCallbacks*) { + if (b && live_buffers) --live_buffers; + } + void vkGetBufferMemoryRequirements(VkDevice, VkBuffer b, VkMemoryRequirements* req) { + const auto idx = reinterpret_cast(b) - 1; + req->size = buf_sizes[idx]; + req->alignment = 64; + req->memoryTypeBits = 0x3u; // bit 0 = VRAM, bit 1 = host cached + } + VkResult vkBindBufferMemory(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) { return VK_SUCCESS; } + VkResult vkMapMemory(VkDevice, VkDeviceMemory m, VkDeviceSize, VkDeviceSize, VkMemoryMapFlags, void** out) { + const auto idx = reinterpret_cast(m) - 1; + *out = mem_storage[idx].data(); + return VK_SUCCESS; + } + void vkUnmapMemory(VkDevice, VkDeviceMemory) {} + void vkFreeMemory(VkDevice, VkDeviceMemory m, const VkAllocationCallbacks*) { + if (m && live_memories) --live_memories; + } + static VkDeviceAddress get_bda(VkDevice, const VkBufferDeviceAddressInfo* info) { + const auto idx = reinterpret_cast(info->buffer); + return 0x100000000ull + idx * (128ull << 20); + } + VkDeviceAddress (*vkGetBufferDeviceAddress)(VkDevice, const VkBufferDeviceAddressInfo*) = &get_bda; + }; + struct MockContext { + MockVk vk; + }; + struct MockDevice { + MockContext ctx; + MockContext* context = &ctx; + struct { + VkDevice device = nullptr; + } info; + struct { + VkDeviceAddress address = 0x100000000ull; + } arena; + VkPhysicalDeviceMemoryProperties memory{}; + std::size_t vram_owner_hits = 0; + std::size_t staging_owner_hits = 0; + + MockDevice() { + memory.memoryTypeCount = 2; + memory.memoryHeapCount = 2; + memory.memoryHeaps[0] = {24ull << 30, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + memory.memoryHeaps[1] = {64ull << 30, 0}; + memory.memoryTypes[0] = {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0}; + memory.memoryTypes[1] = {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | + VK_MEMORY_PROPERTY_HOST_CACHED_BIT, + 1}; + } + void share(VkBufferCreateInfo&) const {} + bool vsharp_offsets_signed() const { return false; } + VkDeviceMemory allocate(const VkMemoryRequirements& req, VkMemoryPropertyFlags required, + VkMemoryPropertyFlags /*preferred*/, VkMemoryPropertyFlags* chosen, + bool /*device_local*/) { + if (required & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { + if (leonida::memory_breakdown::current_owner() == Consumer::windows) ++vram_owner_hits; + if (chosen) *chosen = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + ctx.vk.mem_storage.emplace_back(1); // VRAM doesn't need host backing + } else { + if (leonida::memory_breakdown::current_owner() == Consumer::staging) ++staging_owner_hits; + if (chosen) + *chosen = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | + VK_MEMORY_PROPERTY_HOST_CACHED_BIT; + ctx.vk.mem_storage.emplace_back(64); + } + ++ctx.vk.live_memories; + return reinterpret_cast(static_cast(ctx.vk.mem_storage.size())); + } + void invalidate_backed_table() {} + }; + + MockDevice dev; + rt::d3d12::TitleBufferWindows pool; + pool.set_staged(true); + // Cap = 256 MiB total -> fits at most TWO 64 MiB staged slabs (2 * (64 MiB VRAM + 64 MiB staging) = 256 MiB). + constexpr VkDeviceSize kCap = 256ull << 20; + VkDeviceSize off1 = 0, off2 = 0, off3 = 0; + std::uint8_t *m1 = nullptr, *m2 = nullptr, *m3 = nullptr; + bool at_cap = false; + + // 1st staged slab (64 MiB VRAM + 64 MiB staging = 128 MiB reserved). + CHECK(pool.allocate(dev, 40ull << 20, off1, m1, false, kCap, &at_cap)); + CHECK(!at_cap); + CHECK(pool.reserved() == (128ull << 20)); + CHECK(dev.vram_owner_hits == 1 && dev.staging_owner_hits == 1); + + // 2nd staged slab (40 MiB doesn't fit in 1st slab's remaining 24 MiB -> new 64 MiB slab -> 256 MiB reserved). + CHECK(pool.allocate(dev, 40ull << 20, off2, m2, false, kCap, &at_cap)); + CHECK(!at_cap); + CHECK(pool.reserved() == (256ull << 20)); + CHECK(dev.vram_owner_hits == 2 && dev.staging_owner_hits == 2); + + // 3rd allocation exceeds the 256 MiB cap (both VRAM + host mirror accounted for) -> refused with at_cap. + CHECK(!pool.allocate(dev, 40ull << 20, off3, m3, false, kCap, &at_cap)); + CHECK(at_cap); + + // Freeing off1 leaves 1 empty 64 MiB spare (kept -> 256 MiB reserved); freeing off2 makes 2 empty slabs, so the + // 2nd is destroyed, leaving 1 spare (128 MiB reserved, 2 buffers + 2 memories live). + CHECK(pool.free(dev, off1, 40ull << 20)); + CHECK(pool.reserved() == (256ull << 20)); + CHECK(pool.free(dev, off2, 40ull << 20)); + CHECK(pool.reserved() == (128ull << 20)); + CHECK(dev.ctx.vk.live_buffers == 2 && dev.ctx.vk.live_memories == 2); + + pool.release(dev); + CHECK(pool.reserved() == 0); + CHECK(dev.ctx.vk.live_buffers == 0 && dev.ctx.vk.live_memories == 0); + return 0; +} + } // namespace int main() { @@ -281,6 +409,7 @@ int main() { if (test_exact_byte_dirty_coalescing()) return 1; if (test_mapped_ranges_and_readback_subtract()) return 1; if (test_compaction_under_many_small_marks()) return 1; + if (test_staged_slab_budget_and_reclamation()) return 1; std::printf("arena_staging_test: OK\n"); return 0; } diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 9708598ee5..d35c10c155 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -3694,17 +3694,17 @@ int check_shadow_adopts_geometry_guard(ID3D12Device* device) { if (reader.init(device, size)) return 1; // First submission copies the initial bytes and adopts kProtected on the geometry_writes-guarded tile. EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); - // Second clean submission skips the committed tile (only the reserved second half is queried: 1 query, not 2). + // Second clean submission skips both the committed tile (kProtected) and the reserved tail (kZero). EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); - EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 1); + EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 0); // A write to the shared tile faults through geometry_writes + ShadowPages::reopen_range(), re-arms via // geometry_writes ahead of refresh_shadows(), and reaches the GPU on the next submission. for (SIZE_T i = 0x1000; i < 0x2000; ++i) want[i] = pages[i] = pattern_byte(i, 199); EXPECT(leonida::geometry_writes::arm(tile, *cell)); EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); - // After re-adopting kProtected, the following clean submission again skips the committed tile. + // After re-adopting kProtected, the following clean submission again skips both halves. EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); - EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 1); + EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 0); // Marking the tile hot reopens it without a write fault and notifies title_memory_map::changed(): // adopted ShadowPages must requery and copy writes made while hot. leonida::geometry_writes::set_hot(tile, true); @@ -3719,7 +3719,7 @@ int check_shadow_adopts_geometry_guard(ID3D12Device* device) { EXPECT((protection_of(pages) & 0xff) == PAGE_READONLY); EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); - EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 1); + EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 0); } // ShadowPages destruction reopened the adopted tile and called note_external_reopen(), clearing Cell::restore[]. EXPECT((protection_of(pages) & 0xff) == PAGE_READWRITE); diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 80e323f2cc..404faeed95 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -24174,7 +24174,7 @@ def main(): ap.add_argument("--compact-spirv", action="store_true", help="remove redundant local loads, repeated values and dead instructions with spirv-opt") ap.add_argument("--spirv-opt", action="store_true", - help="run spirv-opt (-O below 750 KiB, safe SSA pass set at >= 750 KiB) with automatic fallback " + help="run spirv-opt (-O below 512 KiB, safe SSA pass set at >= 512 KiB) with automatic fallback " "to unoptimized SPIR-V if spirv-opt or spirv-val rejects the optimized module") ap.add_argument("--opt", action="store_true", help="run basic-block SPIR-V peephole optimization (tools/spirv_opt.py: register store-to-load " From 4a305d0666c1e23df2a4d4c738dc6245b01203d9 Mon Sep 17 00:00:00 2001 From: Dimitar Pavlov <360593571+azsekazvamdimitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:04:33 +0200 Subject: [PATCH 5/5] d3d12/vulkan: bind/map staging before binding VRAM buffer & document LEONIDA_EXTERNAL_WINDOWS_MB --- docs/d3d12_vulkan.md | 3 +++ runtime/shims/d3d12_title_buffer_windows.h | 8 +++++-- runtime/shims/d3d12_vulkan_device.cpp | 6 +++-- runtime/test/arena_staging_test.cpp | 26 +++++++++++++++++++++- 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index c84d550236..52cd58419b 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1916,6 +1916,9 @@ The runtime allocates image keys from `0x100000000` (4 GiB) in 256-byte steps, a VRAM and `arena.mapped` points at the `HOST_VISIBLE | HOST_COHERENT` staging mirror (`arena.staging_buffer`). On GPUs with Resizable BAR or unified memory, `auto` keeps the zero-copy single buffer; `LEONIDA_DEVICE_LOCAL_ARENA=1` forces the staged path for testing, and `LEONIDA_DEVICE_LOCAL_ARENA=0` keeps the single host-visible arena. + - Overflow `TitleBufferWindows` slabs outside the main arena are budgeted by `LEONIDA_EXTERNAL_WINDOWS_MB` (default + 4096 MiB total when staged — counting both VRAM and host staging mirror — or 2048 MiB when unstaged). Empty slabs + beyond one spare are reclaimed. - CPU writes into `arena.mapped` (`ShadowPages`, console and standard shader-visible descriptor heaps, shader blobs, `write_arena_value`, geometry leases, placed/committed buffer init and `Map`/`Unmap`) are tracked at exact byte granularity (never rounded up to 4 KiB pages, so flushing a 256-byte shadow piece or 32-byte descriptor never diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h index 10bf79e8ee..949a487662 100644 --- a/runtime/shims/d3d12_title_buffer_windows.h +++ b/runtime/shims/d3d12_title_buffer_windows.h @@ -320,9 +320,9 @@ class TitleBufferWindows { } } if (vram_mem && staging_buf && staging_mem && - vk.vkBindBufferMemory(d.info.device, b.buffer, vram_mem, 0) == VK_SUCCESS && vk.vkBindBufferMemory(d.info.device, staging_buf, staging_mem, 0) == VK_SUCCESS && - vk.vkMapMemory(d.info.device, staging_mem, 0, VK_WHOLE_SIZE, 0, &host) == VK_SUCCESS) { + vk.vkMapMemory(d.info.device, staging_mem, 0, VK_WHOLE_SIZE, 0, &host) == VK_SUCCESS && + vk.vkBindBufferMemory(d.info.device, b.buffer, vram_mem, 0) == VK_SUCCESS) { b.memory = vram_mem; b.staging_buffer = staging_buf; b.staging_memory = staging_mem; @@ -332,6 +332,10 @@ class TitleBufferWindows { block_host_cached = true; staging_reserved = sreq.size; } else { + if (host && staging_mem) { + vk.vkUnmapMemory(d.info.device, staging_mem); + host = nullptr; + } if (staging_buf) vk.vkDestroyBuffer(d.info.device, staging_buf, nullptr); if (staging_mem) vk.vkFreeMemory(d.info.device, staging_mem, nullptr); if (vram_mem) vk.vkFreeMemory(d.info.device, vram_mem, nullptr); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index a1ebe70b40..3302e056f9 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -24021,16 +24021,18 @@ class Device final : VK_NULL_HANDLE; } if (arena.memory && arena.staging_memory && - vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) == VK_SUCCESS && vk.vkBindBufferMemory(state_.info.device, candidate_staging, arena.staging_memory, 0) == VK_SUCCESS && vk.vkMapMemory(state_.info.device, arena.staging_memory, 0, VK_WHOLE_SIZE, 0, &mapped) == - VK_SUCCESS) { + VK_SUCCESS && + vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) == VK_SUCCESS) { arena.staging_buffer = candidate_staging; candidate_staging = VK_NULL_HANDLE; arena.staged = true; arena.staging.init(info.size); } else { + if (mapped && arena.staging_memory) + vk.vkUnmapMemory(state_.info.device, arena.staging_memory); if (arena.staging_memory) vk.vkFreeMemory(state_.info.device, arena.staging_memory, nullptr); if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); diff --git a/runtime/test/arena_staging_test.cpp b/runtime/test/arena_staging_test.cpp index 2df2c66f06..133f27e7ad 100644 --- a/runtime/test/arena_staging_test.cpp +++ b/runtime/test/arena_staging_test.cpp @@ -279,12 +279,15 @@ int test_staged_slab_budget_and_reclamation() { struct MockVk { std::vector buf_sizes; std::vector> mem_storage; + std::vector buf_binds; std::size_t live_buffers = 0; std::size_t live_memories = 0; + bool fail_next_map = false; VkResult vkCreateBuffer(VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*, VkBuffer* out) { buf_sizes.push_back(info->size); + buf_binds.push_back(0); *out = reinterpret_cast(static_cast(buf_sizes.size())); ++live_buffers; return VK_SUCCESS; @@ -298,8 +301,16 @@ int test_staged_slab_budget_and_reclamation() { req->alignment = 64; req->memoryTypeBits = 0x3u; // bit 0 = VRAM, bit 1 = host cached } - VkResult vkBindBufferMemory(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) { return VK_SUCCESS; } + VkResult vkBindBufferMemory(VkDevice, VkBuffer b, VkDeviceMemory, VkDeviceSize) { + const auto idx = reinterpret_cast(b) - 1; + ++buf_binds[idx]; + return buf_binds[idx] == 1 ? VK_SUCCESS : VK_ERROR_UNKNOWN; + } VkResult vkMapMemory(VkDevice, VkDeviceMemory m, VkDeviceSize, VkDeviceSize, VkMemoryMapFlags, void** out) { + if (fail_next_map) { + fail_next_map = false; + return VK_ERROR_MEMORY_MAP_FAILED; + } const auto idx = reinterpret_cast(m) - 1; *out = mem_storage[idx].data(); return VK_SUCCESS; @@ -398,6 +409,19 @@ int test_staged_slab_budget_and_reclamation() { pool.release(dev); CHECK(pool.reserved() == 0); CHECK(dev.ctx.vk.live_buffers == 0 && dev.ctx.vk.live_memories == 0); + + // Staging map failure injection: b.buffer must stay unbound until staging bind+map succeed, so host fallback + // binds b.buffer exactly once (never a duplicate vkBindBufferMemory). + rt::d3d12::TitleBufferWindows fallback_pool; + fallback_pool.set_staged(true); + dev.ctx.vk.fail_next_map = true; + VkDeviceSize off_fb = 0; + std::uint8_t* m_fb = nullptr; + CHECK(fallback_pool.allocate(dev, 4ull << 20, off_fb, m_fb, false, kCap, &at_cap)); + CHECK(m_fb != nullptr); + for (const std::size_t binds : dev.ctx.vk.buf_binds) CHECK(binds <= 1); + fallback_pool.release(dev); + CHECK(dev.ctx.vk.live_buffers == 0 && dev.ctx.vk.live_memories == 0); return 0; }