diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-25 17:04:49 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-25 17:04:49 -0500 |
| commit | dd6d3fd8a5c61840e822aa6469214c65c534cd7b (patch) | |
| tree | a0d59e7d36b3fbf683aea20eb5c6ec1b3ceaf305 /runtime/src | |
| parent | 6af9c80a990c6543a4593665d2465f2f14b502e7 (diff) | |
| parent | d3b8251bc390418cdbc1f2d30727b6b31d889cfa (diff) | |
Merge main into stream-output (#1630)
Brings #1630 up to date with main; no conflicts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
| -rw-r--r-- | runtime/src/arena_blocks.h | 35 | ||||
| -rw-r--r-- | runtime/src/arena_size.h | 31 | ||||
| -rw-r--r-- | runtime/src/command_list.h | 4 | ||||
| -rw-r--r-- | runtime/src/console_heap_vsharp_slots.h | 115 | ||||
| -rw-r--r-- | runtime/src/gfx10_descriptors.h | 29 | ||||
| -rw-r--r-- | runtime/src/indirect_draw_stats.h | 97 | ||||
| -rw-r--r-- | runtime/src/large_module_gate.h | 293 | ||||
| -rw-r--r-- | runtime/src/main.cpp | 52 | ||||
| -rw-r--r-- | runtime/src/title_window_plan.h | 17 | ||||
| -rw-r--r-- | runtime/src/vulkan_backend.h | 457 | ||||
| -rw-r--r-- | runtime/src/vulkan_indirect_clamp.h | 62 | ||||
| -rw-r--r-- | runtime/src/vulkan_replay.h | 282 | ||||
| -rw-r--r-- | runtime/src/vulkan_scratch.h | 7 |
13 files changed, 1180 insertions, 301 deletions
diff --git a/runtime/src/arena_blocks.h b/runtime/src/arena_blocks.h index f6b379e2f..c7ac093d8 100644 --- a/runtime/src/arena_blocks.h +++ b/runtime/src/arena_blocks.h | |||
| @@ -14,6 +14,7 @@ | |||
| 14 | #include <algorithm> | 14 | #include <algorithm> |
| 15 | #include <cstddef> | 15 | #include <cstddef> |
| 16 | #include <cstdint> | 16 | #include <cstdint> |
| 17 | #include <limits> | ||
| 17 | #include <map> | 18 | #include <map> |
| 18 | #include <utility> | 19 | #include <utility> |
| 19 | #include <vector> | 20 | #include <vector> |
| @@ -66,11 +67,18 @@ public: | |||
| 66 | const std::uint64_t block = next->first; | 67 | const std::uint64_t block = next->first; |
| 67 | const std::uint64_t block_size = next->second; | 68 | const std::uint64_t block_size = next->second; |
| 68 | const std::uint64_t end = block + block_size; | 69 | const std::uint64_t end = block + block_size; |
| 69 | std::uint64_t start = align_up(block, alignment); | 70 | std::uint64_t start = 0; |
| 70 | while (start < end && bytes <= end - start) { | 71 | if (align_up(block, alignment, start)) { |
| 71 | const std::uint64_t keep_out_end = keep_out(start, start + bytes); | 72 | while (start < end && bytes <= end - start) { |
| 72 | if (!keep_out_end) break; | 73 | const std::uint64_t keep_out_end = keep_out(start, start + bytes); |
| 73 | start = align_up(keep_out_end, alignment); | 74 | if (!keep_out_end) break; |
| 75 | if (keep_out_end <= start || !align_up(keep_out_end, alignment, start)) { | ||
| 76 | start = end; | ||
| 77 | break; | ||
| 78 | } | ||
| 79 | } | ||
| 80 | } else { | ||
| 81 | start = end; | ||
| 74 | } | 82 | } |
| 75 | if (cuts_ != cuts) break; // the map moved under the walk: search the new one | 83 | if (cuts_ != cuts) break; // the map moved under the walk: search the new one |
| 76 | if (start < end && bytes <= end - start) { | 84 | if (start < end && bytes <= end - start) { |
| @@ -189,7 +197,10 @@ public: | |||
| 189 | 197 | ||
| 190 | // Whether the map's free bytes and the device's live bytes add up to the arena: a byte released twice, or a | 198 | // Whether the map's free bytes and the device's live bytes add up to the arena: a byte released twice, or a |
| 191 | // released range that was never allocated, breaks this. O(1), so the device checks it on every call. | 199 | // released range that was never allocated, breaks this. O(1), so the device checks it on every call. |
| 192 | bool consistent(std::uint64_t live_bytes) const { return free_bytes_ + live_bytes == size_ - reserved_; } | 200 | bool consistent(std::uint64_t live_bytes) const { |
| 201 | const std::uint64_t total = size_ > reserved_ ? size_ - reserved_ : 0; | ||
| 202 | return live_bytes <= total && free_bytes_ == total - live_bytes; | ||
| 203 | } | ||
| 193 | 204 | ||
| 194 | // Faults reported so far, and the last one this call reported. | 205 | // Faults reported so far, and the last one this call reported. |
| 195 | std::uint64_t faults() const { return faults_; } | 206 | std::uint64_t faults() const { return faults_; } |
| @@ -202,8 +213,16 @@ public: | |||
| 202 | static constexpr int kAttempts = 8; | 213 | static constexpr int kAttempts = 8; |
| 203 | 214 | ||
| 204 | private: | 215 | private: |
| 205 | static std::uint64_t align_up(std::uint64_t value, std::uint64_t alignment) { | 216 | static bool align_up(std::uint64_t value, std::uint64_t alignment, std::uint64_t& out) { |
| 206 | return (value + alignment - 1) / alignment * alignment; | 217 | const std::uint64_t rem = value % alignment; |
| 218 | if (!rem) { | ||
| 219 | out = value; | ||
| 220 | return true; | ||
| 221 | } | ||
| 222 | const std::uint64_t add = alignment - rem; | ||
| 223 | if (value > std::numeric_limits<std::uint64_t>::max() - add) return false; | ||
| 224 | out = value + add; | ||
| 225 | return true; | ||
| 207 | } | 226 | } |
| 208 | 227 | ||
| 209 | Fault note_fault(Fault fault) { | 228 | Fault note_fault(Fault fault) { |
diff --git a/runtime/src/arena_size.h b/runtime/src/arena_size.h index 196b03e3e..66eed0dc2 100644 --- a/runtime/src/arena_size.h +++ b/runtime/src/arena_size.h | |||
| @@ -9,7 +9,7 @@ | |||
| 9 | // The decision is a pure function of the variable's text and the two limits, so it is tested without a GPU | 9 | // The decision is a pure function of the variable's text and the two limits, so it is tested without a GPU |
| 10 | // (arena_size_test). It depends only on the Vulkan headers. | 10 | // (arena_size_test). It depends only on the Vulkan headers. |
| 11 | 11 | ||
| 12 | #include <vulkan/vulkan_core.h> | 12 | #include "vulkan_memory.h" |
| 13 | 13 | ||
| 14 | #include <algorithm> | 14 | #include <algorithm> |
| 15 | #include <cstdint> | 15 | #include <cstdint> |
| @@ -21,6 +21,9 @@ constexpr VkDeviceSize kArenaMiB = VkDeviceSize(1) << 20; | |||
| 21 | constexpr VkDeviceSize kArenaDefaultMiB = 256; | 21 | constexpr VkDeviceSize kArenaDefaultMiB = 256; |
| 22 | constexpr VkDeviceSize kArenaMinMiB = 16; | 22 | constexpr VkDeviceSize kArenaMinMiB = 16; |
| 23 | constexpr VkDeviceSize kArenaMaxMiB = 4095; | 23 | constexpr VkDeviceSize kArenaMaxMiB = 4095; |
| 24 | constexpr VkMemoryPropertyFlags kArenaRequiredMemory = | ||
| 25 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; | ||
| 26 | constexpr VkMemoryPropertyFlags kArenaPreferredMemory = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; | ||
| 24 | 27 | ||
| 25 | // The device's limits; 0 is "not known", which caps nothing. | 28 | // The device's limits; 0 is "not known", which caps nothing. |
| 26 | struct ArenaLimits { | 29 | struct ArenaLimits { |
| @@ -43,6 +46,7 @@ enum ArenaCap : unsigned { | |||
| 43 | arena_cap_none = 0, | 46 | arena_cap_none = 0, |
| 44 | arena_cap_buffer = 1, // maxBufferSize | 47 | arena_cap_buffer = 1, // maxBufferSize |
| 45 | arena_cap_allocation = 2, // maxMemoryAllocationSize | 48 | arena_cap_allocation = 2, // maxMemoryAllocationSize |
| 49 | arena_cap_bar = 4, // the largest size whose buffer may use DEVICE_LOCAL | HOST_VISIBLE memory | ||
| 46 | }; | 50 | }; |
| 47 | 51 | ||
| 48 | struct ArenaSize { | 52 | struct ArenaSize { |
| @@ -82,6 +86,7 @@ inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, V | |||
| 82 | 86 | ||
| 83 | // The Vulkan names of the limits in `capped`, for the log line. | 87 | // The Vulkan names of the limits in `capped`, for the log line. |
| 84 | inline const char* arena_cap_name(unsigned capped) { | 88 | inline const char* arena_cap_name(unsigned capped) { |
| 89 | if (capped & arena_cap_bar) return "Resizable BAR memory types for a buffer that large"; | ||
| 85 | switch (capped) { | 90 | switch (capped) { |
| 86 | case arena_cap_buffer: return "maxBufferSize"; | 91 | case arena_cap_buffer: return "maxBufferSize"; |
| 87 | case arena_cap_allocation: return "maxMemoryAllocationSize"; | 92 | case arena_cap_allocation: return "maxMemoryAllocationSize"; |
| @@ -90,4 +95,28 @@ inline const char* arena_cap_name(unsigned capped) { | |||
| 90 | } | 95 | } |
| 91 | } | 96 | } |
| 92 | 97 | ||
| 98 | constexpr VkDeviceSize kArenaBarStep = 16 * kArenaMiB; | ||
| 99 | |||
| 100 | // Apply the same memory-type eligibility checks as the arena allocation, requiring its preferred device-local type. | ||
| 101 | inline bool device_local_arena_fits(const VkPhysicalDeviceMemoryProperties& memory, | ||
| 102 | const VkMemoryRequirements& requirements) { | ||
| 103 | return !memory_type_order(memory, requirements.memoryTypeBits, kArenaRequiredMemory | kArenaPreferredMemory, | ||
| 104 | 0, requirements.size).empty(); | ||
| 105 | } | ||
| 106 | |||
| 107 | // With Resizable BAR the arena belongs in VRAM the CPU can write. A driver can leave those memory types out of a | ||
| 108 | // large buffer's memoryTypeBits: on an RTX 5070 Ti (NVIDIA 617.42, Windows 11) a 4,090 MiB buffer may use the | ||
| 109 | // DEVICE_LOCAL | HOST_VISIBLE type and a 4,092 MiB one may not, so LEONIDA_ARENA_MB=4096 (4,095 MiB) put the whole | ||
| 110 | // arena in system memory. `fits(bytes)` says whether a buffer of that size may use such a type. Returns the size to | ||
| 111 | // create: `bytes` when it fits (or when nothing in reach does), else the largest size below it, in 16 MiB steps | ||
| 112 | // and losing at most an eighth, that fits. | ||
| 113 | template <class Fits> | ||
| 114 | VkDeviceSize device_local_arena_bytes(VkDeviceSize bytes, Fits fits) { | ||
| 115 | if (fits(bytes)) return bytes; | ||
| 116 | const VkDeviceSize floor = std::max(bytes - bytes / 8, kArenaMinMiB * kArenaMiB); | ||
| 117 | for (VkDeviceSize size = bytes / kArenaBarStep * kArenaBarStep; size >= floor && size > 0; size -= kArenaBarStep) | ||
| 118 | if (size < bytes && fits(size)) return size; | ||
| 119 | return bytes; | ||
| 120 | } | ||
| 121 | |||
| 93 | } // namespace leonida | 122 | } // namespace leonida |
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 3d7ed093b..b68b413fc 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h | |||
| @@ -545,8 +545,8 @@ struct UavView { | |||
| 545 | std::uint64_t size; // buffer: bytes in the view | 545 | std::uint64_t size; // buffer: bytes in the view |
| 546 | std::uint32_t element_size; // buffer: bytes an element (rects count elements), 4 for a raw view | 546 | std::uint32_t element_size; // buffer: bytes an element (rects count elements), 4 for a raw view |
| 547 | std::uint32_t mip; // texture | 547 | std::uint32_t mip; // texture |
| 548 | std::uint32_t first_layer; | 548 | std::uint32_t first_layer; // 1D/2D array: first slice; 3D volume: FirstWSlice |
| 549 | std::uint32_t layer_count; | 549 | std::uint32_t layer_count; // 1D/2D array: slice count; 3D volume: WSize |
| 550 | bool exact_clear_format = false; // newly exposed 1D/3D UAVs: do not clear via a different backing format | 550 | bool exact_clear_format = false; // newly exposed 1D/3D UAVs: do not clear via a different backing format |
| 551 | }; | 551 | }; |
| 552 | 552 | ||
diff --git a/runtime/src/console_heap_vsharp_slots.h b/runtime/src/console_heap_vsharp_slots.h new file mode 100644 index 000000000..0b0830053 --- /dev/null +++ b/runtime/src/console_heap_vsharp_slots.h | |||
| @@ -0,0 +1,115 @@ | |||
| 1 | #pragma once | ||
| 2 | // Host-RAM bitset of console resource-heap slots whose GPU copy (`heap.copy`) currently holds a live buffer V# | ||
| 3 | // (`!(w[3] >> 30) && (w[2] || w[6])`). | ||
| 4 | // | ||
| 5 | // When a buffer backing or title VA alias is released, `refresh_console_heap` must re-run `fix_console_slot` on every | ||
| 6 | // slot that might still point at the released allocation. Scanning `heap.copy` linearly reads every 32-byte slot of | ||
| 7 | // the heap (4-5.5+ MiB): when `heap.copy` sits in `arena.mapped` (uncached write-combined GPU memory), each release | ||
| 8 | // triggers ~180k uncached PCIe reads. Tracking the live V# slots in host RAM keeps invalidation scans strictly in CPU | ||
| 9 | // cache (zero reads from `heap.copy`) and skips empty and T# slots 64 at a time. | ||
| 10 | |||
| 11 | #include <algorithm> | ||
| 12 | #include <bit> | ||
| 13 | #include <cstddef> | ||
| 14 | #include <cstdint> | ||
| 15 | #include <vector> | ||
| 16 | |||
| 17 | namespace leonida { | ||
| 18 | |||
| 19 | class ConsoleHeapVsharpSlots { | ||
| 20 | public: | ||
| 21 | // Matches the descriptor predicate for a non-empty buffer V# (primary or counter half) in a 32-byte slot. | ||
| 22 | static constexpr bool is_live_vsharp(const std::uint32_t* w) noexcept { | ||
| 23 | return !(w[3] >> 30) && (w[2] || w[6]); | ||
| 24 | } | ||
| 25 | |||
| 26 | void reset(std::size_t slot_count) { | ||
| 27 | slot_count_ = slot_count; | ||
| 28 | live_count_ = 0; | ||
| 29 | words_.assign((slot_count + 63) / 64, 0); | ||
| 30 | } | ||
| 31 | |||
| 32 | void set(std::size_t slot, bool live) noexcept { | ||
| 33 | if (slot >= slot_count_) return; | ||
| 34 | std::uint64_t& word = words_[slot >> 6]; | ||
| 35 | const std::uint64_t mask = std::uint64_t{1} << (slot & 63); | ||
| 36 | const bool was = (word & mask) != 0; | ||
| 37 | if (live == was) return; | ||
| 38 | if (live) { | ||
| 39 | word |= mask; | ||
| 40 | ++live_count_; | ||
| 41 | } else { | ||
| 42 | word &= ~mask; | ||
| 43 | --live_count_; | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | void clear(std::size_t slot) noexcept { set(slot, false); } | ||
| 48 | |||
| 49 | // Clears every slot in [first, end), clamping to slot_count(). | ||
| 50 | void clear_range(std::size_t first, std::size_t end) noexcept { | ||
| 51 | if (first >= end || first >= slot_count_ || live_count_ == 0) return; | ||
| 52 | end = (std::min)(end, slot_count_); | ||
| 53 | std::size_t w = first >> 6; | ||
| 54 | const std::size_t last_w = (end - 1) >> 6; | ||
| 55 | const unsigned first_bit = static_cast<unsigned>(first & 63); | ||
| 56 | const unsigned end_bit = static_cast<unsigned>(end & 63); | ||
| 57 | const std::uint64_t head_mask = ~std::uint64_t{0} << first_bit; | ||
| 58 | const std::uint64_t tail_mask = end_bit ? ((std::uint64_t{1} << end_bit) - 1) : ~std::uint64_t{0}; | ||
| 59 | if (w == last_w) { | ||
| 60 | const std::uint64_t mask = head_mask & tail_mask; | ||
| 61 | const std::uint64_t cleared = words_[w] & mask; | ||
| 62 | if (cleared) { | ||
| 63 | words_[w] &= ~mask; | ||
| 64 | live_count_ -= static_cast<std::size_t>(std::popcount(cleared)); | ||
| 65 | } | ||
| 66 | return; | ||
| 67 | } | ||
| 68 | if (const std::uint64_t cleared = words_[w] & head_mask) { | ||
| 69 | words_[w] &= ~head_mask; | ||
| 70 | live_count_ -= static_cast<std::size_t>(std::popcount(cleared)); | ||
| 71 | } | ||
| 72 | for (++w; w < last_w; ++w) { | ||
| 73 | if (const std::uint64_t cleared = words_[w]) { | ||
| 74 | words_[w] = 0; | ||
| 75 | live_count_ -= static_cast<std::size_t>(std::popcount(cleared)); | ||
| 76 | } | ||
| 77 | } | ||
| 78 | if (const std::uint64_t cleared = words_[last_w] & tail_mask) { | ||
| 79 | words_[last_w] &= ~tail_mask; | ||
| 80 | live_count_ -= static_cast<std::size_t>(std::popcount(cleared)); | ||
| 81 | } | ||
| 82 | } | ||
| 83 | |||
| 84 | // Calls fn(slot) in ascending slot order for every set bit present when its 64-slot word is entered. | ||
| 85 | // Safe if fn mutates the bit for `slot` (e.g., fix_console_slot clearing an invalidated V#). | ||
| 86 | template <class F> | ||
| 87 | void for_each(F&& fn) const { | ||
| 88 | if (live_count_ == 0) return; | ||
| 89 | for (std::size_t w = 0; w < words_.size(); ++w) { | ||
| 90 | std::uint64_t bits = words_[w]; | ||
| 91 | if (!bits) continue; | ||
| 92 | const std::size_t base = w << 6; | ||
| 93 | while (bits) { | ||
| 94 | const unsigned bit = static_cast<unsigned>(std::countr_zero(bits)); | ||
| 95 | bits &= bits - 1; | ||
| 96 | fn(base + bit); | ||
| 97 | } | ||
| 98 | } | ||
| 99 | } | ||
| 100 | |||
| 101 | bool test(std::size_t slot) const noexcept { | ||
| 102 | return slot < slot_count_ && ((words_[slot >> 6] >> (slot & 63)) & 1u) != 0; | ||
| 103 | } | ||
| 104 | |||
| 105 | std::size_t slot_count() const noexcept { return slot_count_; } | ||
| 106 | std::size_t live_count() const noexcept { return live_count_; } | ||
| 107 | bool empty() const noexcept { return live_count_ == 0; } | ||
| 108 | |||
| 109 | private: | ||
| 110 | std::size_t slot_count_ = 0; | ||
| 111 | std::size_t live_count_ = 0; | ||
| 112 | std::vector<std::uint64_t> words_; | ||
| 113 | }; | ||
| 114 | |||
| 115 | } // namespace leonida | ||
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index 9dad4ed7a..acfa590f8 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h | |||
| @@ -159,11 +159,24 @@ inline constexpr std::uint32_t packed_uav_flag = 0x00400000; | |||
| 159 | inline constexpr std::uint32_t volume_uav_word(std::uint32_t offset, std::uint32_t count) { | 159 | inline constexpr std::uint32_t volume_uav_word(std::uint32_t offset, std::uint32_t count) { |
| 160 | return volume_uav_tag | ((count - 1) << 11) | offset; | 160 | return volume_uav_tag | ((count - 1) << 11) | offset; |
| 161 | } | 161 | } |
| 162 | struct VolumeUavRange { | ||
| 163 | std::uint32_t first_w = 0; | ||
| 164 | std::uint32_t w_size = 0; | ||
| 165 | }; | ||
| 166 | // The tag stores the first W slice and the slice count minus one. Bit 22 is independent packed-format metadata. | ||
| 167 | inline constexpr bool volume_uav_range(const ImageWords& words, const Image& image, VolumeUavRange& out) { | ||
| 168 | if (image.type != ImageType::image_3d || !(words[4] & volume_uav_flag) || | ||
| 169 | (words[7] & volume_uav_tag_mask) != volume_uav_tag) | ||
| 170 | return false; | ||
| 171 | out.first_w = words[7] & 0x7ffu; | ||
| 172 | out.w_size = ((words[7] >> 11) & 0x7ffu) + 1u; | ||
| 173 | return true; | ||
| 174 | } | ||
| 162 | inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& image) { | 175 | inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& image) { |
| 176 | VolumeUavRange range{}; | ||
| 177 | if (!volume_uav_range(words, image, range)) return false; | ||
| 163 | const auto mip_depth = image.depth >> image.first_mip; | 178 | const auto mip_depth = image.depth >> image.first_mip; |
| 164 | return image.type == ImageType::image_3d && (words[4] & volume_uav_flag) && | 179 | return range.first_w != 0 || range.w_size != (mip_depth ? mip_depth : 1u); |
| 165 | (words[7] & volume_uav_tag_mask) == volume_uav_tag && | ||
| 166 | (words[7] & ~packed_uav_flag) != volume_uav_word(0, mip_depth ? mip_depth : 1u); | ||
| 167 | } | 180 | } |
| 168 | 181 | ||
| 169 | inline constexpr float image_min_lod(const ImageWords& words) { | 182 | inline constexpr float image_min_lod(const ImageWords& words) { |
| @@ -223,6 +236,16 @@ inline constexpr VkImageViewType vulkan_view_type(ImageType type) { | |||
| 223 | } | 236 | } |
| 224 | } | 237 | } |
| 225 | 238 | ||
| 239 | inline constexpr VkImageSubresourceRange vulkan_subresource_range(const Image& image, VkImageAspectFlags aspects) { | ||
| 240 | const bool volume = image.type == ImageType::image_3d; | ||
| 241 | return {aspects, image.first_mip, image.mip_count, volume ? 0u : image.first_layer, | ||
| 242 | volume ? 1u : image.layer_count}; | ||
| 243 | } | ||
| 244 | |||
| 245 | inline constexpr bool has_hardware_volume_uav_slice_offset(const ImageWords& words, const Image& image) { | ||
| 246 | return image.type == ImageType::image_3d && image.first_layer != 0 && detail::get(words[5], 0, 4) == 1; | ||
| 247 | } | ||
| 248 | |||
| 226 | // ---- formats ---- | 249 | // ---- formats ---- |
| 227 | 250 | ||
| 228 | // One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A | 251 | // One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A |
diff --git a/runtime/src/indirect_draw_stats.h b/runtime/src/indirect_draw_stats.h index 39ed09b35..0413ae5d8 100644 --- a/runtime/src/indirect_draw_stats.h +++ b/runtime/src/indirect_draw_stats.h | |||
| @@ -1,45 +1,104 @@ | |||
| 1 | // Process-wide counts of calls recorded and replay attempts. A command list can replay more than once. | 1 | // Process-wide counts of calls recorded and replay attempts. A command list can replay more than once. |
| 2 | #pragma once | 2 | #pragma once |
| 3 | #include <atomic> | 3 | #include <atomic> |
| 4 | #include <cstddef> | ||
| 5 | #include <cstdint> | ||
| 4 | #include <cstdio> | 6 | #include <cstdio> |
| 5 | 7 | ||
| 6 | namespace leonida::indirect_stats { | 8 | namespace leonida::indirect_stats { |
| 7 | enum class Event { recorded, emitted, record_skip, replay_skip }; | 9 | enum class Event { recorded, emitted, record_skip, replay_skip }; |
| 10 | // One flag per reason, shared across resolver instantiations. | ||
| 11 | enum Reason { compound, disabled, pipeline, root_layout, viewport, mesh, topology, first_instance, entry, robust_index, | ||
| 12 | count_limit, multi_draw, count_feature, raw_count_limit, argument_usage, count_usage, | ||
| 13 | divisor, pending_pipeline, index_view, index_range, stateless, reason_count }; | ||
| 14 | |||
| 15 | // D3D_PRIMITIVE_TOPOLOGY values whose Vulkan dynamic topology (or rectangle-list geometry-stage variant) needs no CPU | ||
| 16 | // vertex/index-count expansion at prepare time: POINTLIST(1), LINELIST(2), LINESTRIP(3), TRIANGLELIST(4), | ||
| 17 | // TRIANGLESTRIP(5), *_ADJ(10..13), and console RECTLIST(17). UNDEFINED(0), QUADLIST(19), and patch lists remain skipped. | ||
| 18 | inline constexpr bool topology_supported(std::uint32_t value) { | ||
| 19 | return (value >= 1 && value <= 5) || (value >= 10 && value <= 13) || value == 17; | ||
| 20 | } | ||
| 21 | |||
| 22 | inline constexpr const char* reason_name(Reason reason) { | ||
| 23 | constexpr const char* names[]{"compound signature", "opt-out", "missing pipeline", "missing root signature", | ||
| 24 | "empty viewport", "mesh indirect", "topology", "drawIndirectFirstInstance", "missing Vulkan entry point", | ||
| 25 | "robust sized index binding", "maxDrawIndirectCount", "multiDrawIndirect", "drawIndirectCount", | ||
| 26 | "counted draw requires maxDrawIndirectCount == UINT32_MAX", "argument buffer lacks indirect creation usage", | ||
| 27 | "count buffer lacks indirect creation usage", "nonunit vertex divisor", "pipeline pending", | ||
| 28 | "invalid index view", "index view outside buffer or misaligned", "legacy command has no graphics state"}; | ||
| 29 | static_assert(sizeof(names) / sizeof(*names) == reason_count); | ||
| 30 | return static_cast<unsigned>(reason) < reason_count ? names[reason] : "unknown"; | ||
| 31 | } | ||
| 32 | |||
| 33 | inline constexpr const char* reason_tag(Reason reason) { | ||
| 34 | constexpr const char* tags[]{"compound", "disabled", "pipeline", "root_layout", "viewport", "mesh", "topology", | ||
| 35 | "first_instance", "entry", "robust_index", "count_limit", "multi_draw", "count_feature", "raw_count_limit", | ||
| 36 | "argument_usage", "count_usage", "divisor", "pending_pipeline", "index_view", "index_range", "stateless"}; | ||
| 37 | static_assert(sizeof(tags) / sizeof(*tags) == reason_count); | ||
| 38 | return static_cast<unsigned>(reason) < reason_count ? tags[reason] : "unknown"; | ||
| 39 | } | ||
| 40 | |||
| 8 | struct Counts { | 41 | struct Counts { |
| 9 | std::atomic<unsigned long long> values[4]{}; | 42 | std::atomic<unsigned long long> values[4]{}; |
| 10 | void report() const { | 43 | std::atomic<unsigned long long> by_reason[reason_count]{}; |
| 11 | std::fprintf(stderr, "[rt] indirect graphics: recorded=%llu emitted=%llu record_skips=%llu replay_skips=%llu\n", | 44 | void report(std::FILE* out = stderr) const { |
| 12 | values[0].load(), values[1].load(), values[2].load(), values[3].load()); | 45 | char line[1280]; |
| 46 | int pos = std::snprintf( | ||
| 47 | line, sizeof(line), | ||
| 48 | "[rt] indirect graphics: recorded=%llu emitted=%llu record_skips=%llu replay_skips=%llu", | ||
| 49 | values[0].load(std::memory_order_relaxed), values[1].load(std::memory_order_relaxed), | ||
| 50 | values[2].load(std::memory_order_relaxed), values[3].load(std::memory_order_relaxed)); | ||
| 51 | if (pos < 0) return; | ||
| 52 | if (static_cast<std::size_t>(pos) >= sizeof(line)) pos = static_cast<int>(sizeof(line) - 1); | ||
| 53 | bool first_reason = true; | ||
| 54 | for (unsigned i = 0; i < reason_count; ++i) { | ||
| 55 | const auto count = by_reason[i].load(std::memory_order_relaxed); | ||
| 56 | if (!count) continue; | ||
| 57 | const int rem = static_cast<int>(sizeof(line)) - pos; | ||
| 58 | if (rem <= 2) break; | ||
| 59 | const int n = std::snprintf(line + pos, static_cast<std::size_t>(rem), "%s%s=%llu", | ||
| 60 | first_reason ? " [" : ", ", | ||
| 61 | reason_tag(static_cast<Reason>(i)), count); | ||
| 62 | if (n <= 0) break; | ||
| 63 | pos += (n < rem) ? n : (rem - 1); | ||
| 64 | first_reason = false; | ||
| 65 | } | ||
| 66 | if (!first_reason && static_cast<std::size_t>(pos) + 1 < sizeof(line)) line[pos++] = ']'; | ||
| 67 | std::fprintf(out, "%.*s\n", pos, line); | ||
| 13 | } | 68 | } |
| 14 | ~Counts() { | 69 | ~Counts() { |
| 15 | for (const auto& value : values) { | 70 | for (const auto& value : values) { |
| 16 | if (value.load()) { | 71 | if (value.load(std::memory_order_relaxed)) { |
| 17 | report(); | 72 | report(); |
| 18 | break; | 73 | break; |
| 19 | } | 74 | } |
| 20 | } | 75 | } |
| 21 | } | 76 | } |
| 22 | }; | 77 | }; |
| 78 | |||
| 79 | inline Counts& counts() { | ||
| 80 | static Counts instance; | ||
| 81 | return instance; | ||
| 82 | } | ||
| 83 | |||
| 84 | inline unsigned long long reason_skips(Reason reason) { | ||
| 85 | return static_cast<unsigned>(reason) < reason_count | ||
| 86 | ? counts().by_reason[reason].load(std::memory_order_relaxed) | ||
| 87 | : 0ull; | ||
| 88 | } | ||
| 89 | |||
| 23 | inline void note(Event event) { | 90 | inline void note(Event event) { |
| 24 | static Counts counts; | 91 | auto& c = counts(); |
| 25 | const auto n = 1 + counts.values[static_cast<unsigned>(event)].fetch_add(1, std::memory_order_relaxed); | 92 | const auto n = 1 + c.values[static_cast<unsigned>(event)].fetch_add(1, std::memory_order_relaxed); |
| 26 | if ((n & (n - 1)) == 0) counts.report(); | 93 | if ((n & (n - 1)) == 0) c.report(); |
| 27 | } | 94 | } |
| 28 | // One flag per reason, shared across resolver instantiations. | 95 | |
| 29 | enum Reason { compound, disabled, pipeline, root_layout, viewport, mesh, topology, first_instance, entry, robust_index, | ||
| 30 | count_limit, multi_draw, count_feature, raw_count_limit, argument_usage, count_usage, | ||
| 31 | divisor, pending_pipeline, index_view, index_range, stateless, reason_count }; | ||
| 32 | inline void skip(Event event, Reason reason) { | 96 | inline void skip(Event event, Reason reason) { |
| 33 | static constexpr const char* names[]{"compound signature", "opt-out", "missing pipeline", "missing root signature", | 97 | if (static_cast<unsigned>(reason) >= reason_count) return; |
| 34 | "empty viewport", "mesh indirect", "topology", "drawIndirectFirstInstance", "missing Vulkan entry point", | ||
| 35 | "robust sized index binding", "maxDrawIndirectCount", "multiDrawIndirect", "drawIndirectCount", | ||
| 36 | "counted draw requires maxDrawIndirectCount == UINT32_MAX", "argument buffer lacks indirect creation usage", | ||
| 37 | "count buffer lacks indirect creation usage", "nonunit vertex divisor", "pipeline pending", | ||
| 38 | "invalid index view", "index view outside buffer or misaligned", "legacy command has no graphics state"}; | ||
| 39 | static_assert(sizeof(names) / sizeof(*names) == reason_count); | ||
| 40 | static std::atomic_flag shown[reason_count]{}; | 98 | static std::atomic_flag shown[reason_count]{}; |
| 41 | if (!shown[reason].test_and_set(std::memory_order_relaxed)) | 99 | if (!shown[reason].test_and_set(std::memory_order_relaxed)) |
| 42 | std::fprintf(stderr, "[rt] indirect graphics skipped: %s\n", names[reason]); | 100 | std::fprintf(stderr, "[rt] indirect graphics skipped: %s\n", reason_name(reason)); |
| 101 | counts().by_reason[reason].fetch_add(1, std::memory_order_relaxed); | ||
| 43 | note(event); | 102 | note(event); |
| 44 | } | 103 | } |
| 45 | } | 104 | } |
diff --git a/runtime/src/large_module_gate.h b/runtime/src/large_module_gate.h new file mode 100644 index 000000000..f66420bc2 --- /dev/null +++ b/runtime/src/large_module_gate.h | |||
| @@ -0,0 +1,293 @@ | |||
| 1 | // How many large SPIR-V modules vk_pipeline_check and the runtime let into the driver at once, by a memory budget. | ||
| 2 | // | ||
| 3 | // Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute | ||
| 4 | // module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB. | ||
| 5 | // Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6 | ||
| 6 | // threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin | ||
| 7 | // over the measurement. The NVIDIA 621.24 driver (RTX 3080) took 85 to 131 bytes per SPIR-V byte for synthetic compute | ||
| 8 | // modules of 128 KiB to 4 MiB (docs/d3d12_vulkan.md, "Large pipelines"). | ||
| 9 | // | ||
| 10 | // The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas | ||
| 11 | // (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each | ||
| 12 | // large module. | ||
| 13 | #pragma once | ||
| 14 | |||
| 15 | #include <algorithm> | ||
| 16 | #include <condition_variable> | ||
| 17 | #include <cstddef> | ||
| 18 | #include <cstdint> | ||
| 19 | #include <cstdio> | ||
| 20 | #include <functional> | ||
| 21 | #include <list> | ||
| 22 | #include <mutex> | ||
| 23 | #include <optional> | ||
| 24 | #include <string> | ||
| 25 | #include <utility> | ||
| 26 | |||
| 27 | #ifdef _WIN32 | ||
| 28 | #ifndef NOMINMAX | ||
| 29 | #define NOMINMAX | ||
| 30 | #endif | ||
| 31 | #include <windows.h> | ||
| 32 | #endif | ||
| 33 | #if defined(__GLIBC__) | ||
| 34 | #include <malloc.h> | ||
| 35 | #endif | ||
| 36 | |||
| 37 | namespace leonida { | ||
| 38 | |||
| 39 | inline constexpr uint64_t kBytesPerSpirvByte = 512; | ||
| 40 | |||
| 41 | inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; } | ||
| 42 | |||
| 43 | #if defined(__linux__) | ||
| 44 | // The first unsigned number in a file ("max" and unreadable files give no value). | ||
| 45 | inline bool read_u64_file(const std::string& path, uint64_t& value) { | ||
| 46 | std::FILE* f = std::fopen(path.c_str(), "r"); | ||
| 47 | if (!f) return false; | ||
| 48 | unsigned long long v = 0; | ||
| 49 | const bool ok = std::fscanf(f, "%llu", &v) == 1; | ||
| 50 | std::fclose(f); | ||
| 51 | value = v; | ||
| 52 | return ok; | ||
| 53 | } | ||
| 54 | |||
| 55 | // The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or | ||
| 56 | // systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests. | ||
| 57 | inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup", | ||
| 58 | const std::string& cgroup_root = "/sys/fs/cgroup") { | ||
| 59 | std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r"); | ||
| 60 | if (!f) return UINT64_MAX; | ||
| 61 | char line[4096]; | ||
| 62 | std::string rel; | ||
| 63 | while (std::fgets(line, sizeof(line), f)) { | ||
| 64 | std::string l(line); | ||
| 65 | if (l.rfind("0::", 0) == 0) { // the cgroup v2 line | ||
| 66 | rel = l.substr(3); | ||
| 67 | while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back(); | ||
| 68 | break; | ||
| 69 | } | ||
| 70 | } | ||
| 71 | std::fclose(f); | ||
| 72 | uint64_t room = UINT64_MAX; | ||
| 73 | for (std::string dir = rel; !dir.empty();) { | ||
| 74 | // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root. | ||
| 75 | const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir; | ||
| 76 | uint64_t max = 0, current = 0; | ||
| 77 | if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current)) | ||
| 78 | room = std::min(room, max > current ? max - current : 0); | ||
| 79 | const auto slash = dir.find_last_of('/'); | ||
| 80 | if (dir == "/" || slash == std::string::npos) break; | ||
| 81 | dir.resize(slash == 0 ? 1 : slash); | ||
| 82 | } | ||
| 83 | return room; | ||
| 84 | } | ||
| 85 | #endif | ||
| 86 | |||
| 87 | // Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate). | ||
| 88 | inline uint64_t available_memory_bytes() { | ||
| 89 | #ifdef _WIN32 | ||
| 90 | MEMORYSTATUSEX status{}; | ||
| 91 | status.dwLength = sizeof(status); | ||
| 92 | return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0; | ||
| 93 | #elif defined(__linux__) | ||
| 94 | std::FILE* f = std::fopen("/proc/meminfo", "r"); | ||
| 95 | if (!f) return 0; | ||
| 96 | char line[256]; | ||
| 97 | unsigned long long kb = 0; | ||
| 98 | bool found = false; | ||
| 99 | while (std::fgets(line, sizeof(line), f)) | ||
| 100 | if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; } | ||
| 101 | std::fclose(f); | ||
| 102 | if (!found) return 0; | ||
| 103 | const uint64_t room = cgroup_memory_room(); | ||
| 104 | return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown" | ||
| 105 | #else | ||
| 106 | return 0; | ||
| 107 | #endif | ||
| 108 | } | ||
| 109 | |||
| 110 | // What large compiles may use of the free RAM and of the room under the commit limit: three quarters of the smaller. (On | ||
| 111 | // Windows an allocation that the limit has no room for fails, whatever RAM is free.) | ||
| 112 | inline uint64_t large_compile_share(uint64_t free_ram, uint64_t commit_room) { | ||
| 113 | return std::min(free_ram, commit_room) / 4 * 3; | ||
| 114 | } | ||
| 115 | |||
| 116 | // The same of the memory that is free at this moment. 0 when it is unknown: then they compile one at a time. | ||
| 117 | inline uint64_t large_compile_budget_bytes() { | ||
| 118 | #ifdef _WIN32 | ||
| 119 | MEMORYSTATUSEX status{}; | ||
| 120 | status.dwLength = sizeof(status); | ||
| 121 | if (!GlobalMemoryStatusEx(&status)) return 0; | ||
| 122 | return large_compile_share(status.ullAvailPhys, status.ullAvailPageFile); | ||
| 123 | #else | ||
| 124 | return large_compile_share(available_memory_bytes(), UINT64_MAX); | ||
| 125 | #endif | ||
| 126 | } | ||
| 127 | |||
| 128 | // LEONIDA_BIG_COMPILE_BUDGET_MB: a fixed budget in MiB instead of the share of the free memory (0: one at a time). Unset | ||
| 129 | // or empty, and text that is not a number: none. `valid` is false for the latter. | ||
| 130 | struct LargeCompileBudget { | ||
| 131 | std::optional<uint64_t> fixed{}; | ||
| 132 | bool valid = true; | ||
| 133 | }; | ||
| 134 | |||
| 135 | inline LargeCompileBudget large_compile_budget(const char* text) { | ||
| 136 | if (!text || !*text) return {}; | ||
| 137 | uint64_t mib = 0; | ||
| 138 | for (const char* c = text; *c; ++c) { | ||
| 139 | if (*c < '0' || *c > '9') return {std::nullopt, false}; | ||
| 140 | mib = std::min<uint64_t>(mib * 10 + uint64_t(*c - '0'), UINT64_MAX >> 20); | ||
| 141 | } | ||
| 142 | return {mib << 20, true}; | ||
| 143 | } | ||
| 144 | |||
| 145 | // Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it). | ||
| 146 | inline void release_free_memory() { | ||
| 147 | #if defined(__GLIBC__) | ||
| 148 | malloc_trim(0); | ||
| 149 | #endif | ||
| 150 | } | ||
| 151 | |||
| 152 | // Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in | ||
| 153 | // when none is, so a module bigger than the whole budget still compiles (alone among the large ones). | ||
| 154 | // | ||
| 155 | // The second constructor is the runtime's: the budget is read again whenever a place is given or returned, and the | ||
| 156 | // modules get in in the order they came, those a submission waits for (demand) before the others (speculative). While the | ||
| 157 | // first in line does not fit, the next behind it that does may pass, as long as all that have passed it would fit the | ||
| 158 | // budget together with it. So, with the budget as it is, it waits at most for those that were in when it became the first, | ||
| 159 | // however many come after it, and one larger than the budget is not passed. A speculative one gets in only while no demand | ||
| 160 | // waits and no submission has a Demand, and only within a quarter of the budget, so that a demand finds the rest free. An | ||
| 161 | // estimate counts in full until its module leaves, although the driver has allocated part of it by then and the budget is | ||
| 162 | // that much smaller: what is in has not taken all it is going to. | ||
| 163 | class LargeModuleGate { | ||
| 164 | public: | ||
| 165 | enum class Work { demand, speculative }; | ||
| 166 | |||
| 167 | LargeModuleGate(uint64_t budget, unsigned max_inflight) | ||
| 168 | : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {} | ||
| 169 | explicit LargeModuleGate(std::function<uint64_t()> budget) | ||
| 170 | : budget_(0), max_inflight_(UINT32_MAX), read_budget_(std::move(budget)) {} | ||
| 171 | |||
| 172 | bool admits(uint64_t estimate) const { | ||
| 173 | std::lock_guard<std::mutex> g(mu_); | ||
| 174 | return admits_locked(estimate, budget()); | ||
| 175 | } | ||
| 176 | void enter(uint64_t estimate, Work work = Work::demand) { | ||
| 177 | std::unique_lock<std::mutex> l(mu_); | ||
| 178 | if (!read_budget_) { | ||
| 179 | cv_.wait(l, [&] { return admits_locked(estimate, limit_for(work)); }); | ||
| 180 | } else { | ||
| 181 | auto& queue = waiting_[work == Work::demand ? 0 : 1]; | ||
| 182 | const auto me = queue.insert(queue.end(), Waiter{estimate}); | ||
| 183 | cv_.wait(l, [&] { | ||
| 184 | return (work == Work::demand || (waiting_[0].empty() && !demanded_)) && next_locked(work) == &*me; | ||
| 185 | }); | ||
| 186 | if (me != queue.begin()) queue.front().passed += estimate; | ||
| 187 | queue.erase(me); | ||
| 188 | } | ||
| 189 | used_ += estimate; | ||
| 190 | ++inflight_; | ||
| 191 | if (!waiting_[0].empty() || !waiting_[1].empty()) cv_.notify_all(); // the next in the queue may fit as well | ||
| 192 | } | ||
| 193 | void leave(uint64_t estimate) { | ||
| 194 | { | ||
| 195 | std::lock_guard<std::mutex> g(mu_); | ||
| 196 | used_ -= estimate; | ||
| 197 | --inflight_; | ||
| 198 | } | ||
| 199 | cv_.notify_all(); | ||
| 200 | } | ||
| 201 | unsigned inflight() const { | ||
| 202 | std::lock_guard<std::mutex> g(mu_); | ||
| 203 | return inflight_; | ||
| 204 | } | ||
| 205 | size_t waiting(Work work) const { // in order: the threads in enter(), with a budget that is read | ||
| 206 | std::lock_guard<std::mutex> g(mu_); | ||
| 207 | return waiting_[work == Work::demand ? 0 : 1].size(); | ||
| 208 | } | ||
| 209 | uint64_t budget() const { return read_budget_ ? read_budget_() : budget_; } | ||
| 210 | unsigned max_inflight() const { return max_inflight_; } | ||
| 211 | |||
| 212 | // A submission that has large modules to build: until it ends, the places that its modules leave between one and the | ||
| 213 | // next are not taken by speculative ones. | ||
| 214 | class Demand { | ||
| 215 | public: | ||
| 216 | explicit Demand(LargeModuleGate& gate) : gate_(gate) { | ||
| 217 | std::lock_guard<std::mutex> g(gate_.mu_); | ||
| 218 | ++gate_.demanded_; | ||
| 219 | } | ||
| 220 | ~Demand() { | ||
| 221 | { | ||
| 222 | std::lock_guard<std::mutex> g(gate_.mu_); | ||
| 223 | --gate_.demanded_; | ||
| 224 | } | ||
| 225 | gate_.cv_.notify_all(); | ||
| 226 | } | ||
| 227 | Demand(const Demand&) = delete; | ||
| 228 | Demand& operator=(const Demand&) = delete; | ||
| 229 | |||
| 230 | private: | ||
| 231 | LargeModuleGate& gate_; | ||
| 232 | }; | ||
| 233 | |||
| 234 | // Holds a place from construction until destruction (or release()), then hands freed memory back. | ||
| 235 | class Ticket { | ||
| 236 | public: | ||
| 237 | Ticket() = default; | ||
| 238 | Ticket(LargeModuleGate& gate, uint64_t estimate, Work work = Work::demand) : gate_(&gate), estimate_(estimate) { | ||
| 239 | gate.enter(estimate, work); | ||
| 240 | } | ||
| 241 | Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; } | ||
| 242 | Ticket& operator=(Ticket&& o) noexcept { | ||
| 243 | if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; } | ||
| 244 | return *this; | ||
| 245 | } | ||
| 246 | Ticket(const Ticket&) = delete; | ||
| 247 | Ticket& operator=(const Ticket&) = delete; | ||
| 248 | ~Ticket() { release(); } | ||
| 249 | void release() { | ||
| 250 | if (!gate_) return; | ||
| 251 | gate_->leave(estimate_); | ||
| 252 | gate_ = nullptr; | ||
| 253 | release_free_memory(); | ||
| 254 | } | ||
| 255 | private: | ||
| 256 | LargeModuleGate* gate_ = nullptr; | ||
| 257 | uint64_t estimate_ = 0; | ||
| 258 | }; | ||
| 259 | |||
| 260 | private: | ||
| 261 | struct Waiter { | ||
| 262 | uint64_t estimate; | ||
| 263 | uint64_t passed = 0; // the estimates of those that have passed it while it was the first in line | ||
| 264 | }; | ||
| 265 | |||
| 266 | uint64_t limit_for(Work work) const { return work == Work::demand ? budget() : budget() / 4; } | ||
| 267 | bool admits_locked(uint64_t estimate, uint64_t limit) const { | ||
| 268 | return inflight_ == 0 || (inflight_ < max_inflight_ && used_ + estimate <= limit); | ||
| 269 | } | ||
| 270 | // The one in line that gets in now, if any: the first, or else the first that fits and may pass it. | ||
| 271 | const Waiter* next_locked(Work work) const { | ||
| 272 | const auto& queue = waiting_[work == Work::demand ? 0 : 1]; | ||
| 273 | const uint64_t limit = limit_for(work); | ||
| 274 | for (const Waiter& w : queue) { | ||
| 275 | const Waiter& first = queue.front(); | ||
| 276 | if (&w != &first && first.passed + w.estimate + first.estimate > limit) continue; | ||
| 277 | if (admits_locked(w.estimate, limit)) return &w; | ||
| 278 | } | ||
| 279 | return nullptr; | ||
| 280 | } | ||
| 281 | |||
| 282 | const uint64_t budget_; | ||
| 283 | const unsigned max_inflight_; | ||
| 284 | const std::function<uint64_t()> read_budget_; | ||
| 285 | mutable std::mutex mu_; | ||
| 286 | std::condition_variable cv_; | ||
| 287 | std::list<Waiter> waiting_[2]; // demand, speculative: one for each thread in enter(), in the order they came | ||
| 288 | uint64_t used_ = 0; | ||
| 289 | unsigned inflight_ = 0; | ||
| 290 | unsigned demanded_ = 0; // the Demands | ||
| 291 | }; | ||
| 292 | |||
| 293 | } // namespace leonida | ||
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index f01997775..094aaa321 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp | |||
| @@ -24,6 +24,7 @@ | |||
| 24 | #include <exception> | 24 | #include <exception> |
| 25 | #include <filesystem> | 25 | #include <filesystem> |
| 26 | #include <map> | 26 | #include <map> |
| 27 | #include <mutex> | ||
| 27 | #include <string> | 28 | #include <string> |
| 28 | #include <system_error> | 29 | #include <system_error> |
| 29 | #include <vector> | 30 | #include <vector> |
| @@ -196,7 +197,9 @@ bool configure_first_run_ui(const std::filesystem::path& package, std::filesyste | |||
| 196 | {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"}, | 197 | {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"}, |
| 197 | {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"}, | 198 | {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"}, |
| 198 | {L"LEONIDA_FRAME_PACING", L"1"}, | 199 | {L"LEONIDA_FRAME_PACING", L"1"}, |
| 199 | {L"LEONIDA_KEYBOARD_PAD", L"always"}, | 200 | // Focused, not always: keys typed into another window must not press anything on a consent page. |
| 201 | // Scripted presses (LEONIDA_INPUT_SCRIPT) still run while the window is unfocused. | ||
| 202 | {L"LEONIDA_KEYBOARD_PAD", L"1"}, | ||
| 200 | }; | 203 | }; |
| 201 | for (const auto& setting : settings) { | 204 | for (const auto& setting : settings) { |
| 202 | if (!set_default(setting.name, setting.value)) return false; | 205 | if (!set_default(setting.name, setting.value)) return false; |
| @@ -231,15 +234,53 @@ int usage() { | |||
| 231 | // The run ends with the title's Vulkan device alive, so no ~Device stops the background pipeline compiler: stop it | 234 | // The run ends with the title's Vulkan device alive, so no ~Device stops the background pipeline compiler: stop it |
| 232 | // here, before ExitProcess ends its thread, maybe inside the driver's compiler (rt::d3d12::stop_pipeline_compiles). | 235 | // here, before ExitProcess ends its thread, maybe inside the driver's compiler (rt::d3d12::stop_pipeline_compiles). |
| 233 | constexpr unsigned kExitCompileWaitMs = 2000; // a console close gives the whole process 5 s | 236 | constexpr unsigned kExitCompileWaitMs = 2000; // a console close gives the whole process 5 s |
| 237 | // For a build still running on a title thread, then the session cache write (rt::d3d12::save_pipeline_caches_at_exit). | ||
| 238 | constexpr unsigned kExitCacheWaitMs = 1000; | ||
| 234 | 239 | ||
| 235 | static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) { | 240 | static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) { |
| 236 | if (event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT || event == CTRL_CLOSE_EVENT) { | 241 | if (event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT || event == CTRL_CLOSE_EVENT) { |
| 237 | rt::d3d12_xs::stop_list_values(500); // as at the run's end: no list-value thread cut off inside the layer | 242 | rt::d3d12_xs::stop_list_values(500); // as at the run's end: no list-value thread cut off inside the layer |
| 238 | rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); | 243 | rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); |
| 244 | rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs); | ||
| 239 | } | 245 | } |
| 240 | return FALSE; // the next handler (the default one: ExitProcess) ends the process, as before | 246 | return FALSE; // the next handler (the default one: ExitProcess) ends the process, as before |
| 241 | } | 247 | } |
| 242 | 248 | ||
| 249 | // A run that ends in an exception nothing handles (a fault in the title or one of its DLLs, the int3 after a device | ||
| 250 | // loss) would otherwise keep none of the pipelines it compiled, and the next boot builds them all again. The device is | ||
| 251 | // left alone apart from that write; the exception then goes on as before (the previous filter, or Windows' own | ||
| 252 | // handling), so the exit code is the exception's. Not for a stack overflow: no stack is left to write with. | ||
| 253 | static LPTOP_LEVEL_EXCEPTION_FILTER previous_fatal_filter = nullptr; | ||
| 254 | // The retail title installs a filter of its own (SetUnhandledExceptionFilter from api-ms-win-core-errorhandling), | ||
| 255 | // which replaced this one and ended the process without it (measured: a title fault at 354 s wrote nothing). Its | ||
| 256 | // call is served here instead: this filter stays installed and hands the exception to the title's, as Windows would. | ||
| 257 | static void* volatile title_fatal_filter = nullptr; | ||
| 258 | |||
| 259 | static LPTOP_LEVEL_EXCEPTION_FILTER WINAPI title_set_unhandled_exception_filter(LPTOP_LEVEL_EXCEPTION_FILTER filter) { | ||
| 260 | return reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>( | ||
| 261 | InterlockedExchangePointer(&title_fatal_filter, reinterpret_cast<void*>(filter))); | ||
| 262 | } | ||
| 263 | |||
| 264 | static LONG WINAPI save_caches_on_fatal_exception(EXCEPTION_POINTERS* info) { | ||
| 265 | const DWORD code = info && info->ExceptionRecord ? info->ExceptionRecord->ExceptionCode : 0; | ||
| 266 | if (code != EXCEPTION_STACK_OVERFLOW) { | ||
| 267 | // Several title threads can fault at once (measured: eight within a second). The first writes; the others | ||
| 268 | // wait here for it, so none of them reaches the title's filter, which may end the process, mid-write. | ||
| 269 | static std::once_flag once; | ||
| 270 | std::call_once(once, [code] { | ||
| 271 | std::fprintf(stderr, "[rt] unhandled exception 0x%08lx: writing the session pipeline cache before the " | ||
| 272 | "process ends\n", static_cast<unsigned long>(code)); | ||
| 273 | rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); | ||
| 274 | rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs); | ||
| 275 | std::fflush(stderr); | ||
| 276 | }); | ||
| 277 | } | ||
| 278 | if (auto* title = reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>( | ||
| 279 | InterlockedCompareExchangePointer(&title_fatal_filter, nullptr, nullptr))) | ||
| 280 | return title(info); | ||
| 281 | return previous_fatal_filter ? previous_fatal_filter(info) : EXCEPTION_CONTINUE_SEARCH; | ||
| 282 | } | ||
| 283 | |||
| 243 | static BOOL WINAPI show_package_window(HWND window, int command) { | 284 | static BOOL WINAPI show_package_window(HWND window, int command) { |
| 244 | const BOOL previous = ShowWindow(window, command); | 285 | const BOOL previous = ShowWindow(window, command); |
| 245 | const DWORD error = GetLastError(); | 286 | const DWORD error = GetLastError(); |
| @@ -347,6 +388,13 @@ int wmain(int argc, wchar_t** argv) { | |||
| 347 | rt::fs::configure(game_dir, overlay_dir); | 388 | rt::fs::configure(game_dir, overlay_dir); |
| 348 | #ifdef LEONIDA_VULKAN_DEVICE | 389 | #ifdef LEONIDA_VULKAN_DEVICE |
| 349 | if (run) { | 390 | if (run) { |
| 391 | // Before the image is loaded, so its import binds here (save_caches_on_fatal_exception). | ||
| 392 | const rt::shims::Entry filter_imports[] = { | ||
| 393 | {"api-ms-win-core-errorhandling-l1-1-0.dll", "SetUnhandledExceptionFilter", | ||
| 394 | reinterpret_cast<void*>(&title_set_unhandled_exception_filter)}, | ||
| 395 | {"kernel32.dll", "SetUnhandledExceptionFilter", reinterpret_cast<void*>(&title_set_unhandled_exception_filter)}, | ||
| 396 | }; | ||
| 397 | rt::shims::Table{filter_imports, std::size(filter_imports)}; | ||
| 350 | rt::package_splash::configure(game_dir); | 398 | rt::package_splash::configure(game_dir); |
| 351 | if (rt::package_splash::configured()) { | 399 | if (rt::package_splash::configured()) { |
| 352 | const rt::shims::Entry window_imports[] = { | 400 | const rt::shims::Entry window_imports[] = { |
| @@ -516,6 +564,7 @@ int wmain(int argc, wchar_t** argv) { | |||
| 516 | leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic) | 564 | leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic) |
| 517 | #ifdef LEONIDA_VULKAN_DEVICE | 565 | #ifdef LEONIDA_VULKAN_DEVICE |
| 518 | SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE); | 566 | SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE); |
| 567 | previous_fatal_filter = SetUnhandledExceptionFilter(&save_caches_on_fatal_exception); | ||
| 519 | #endif | 568 | #endif |
| 520 | int code; | 569 | int code; |
| 521 | { | 570 | { |
| @@ -536,6 +585,7 @@ int wmain(int argc, wchar_t** argv) { | |||
| 536 | rt::d3d12_xs::stop_list_values(500); | 585 | rt::d3d12_xs::stop_list_values(500); |
| 537 | #ifdef LEONIDA_VULKAN_DEVICE | 586 | #ifdef LEONIDA_VULKAN_DEVICE |
| 538 | rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); | 587 | rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); |
| 588 | rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs); | ||
| 539 | #endif | 589 | #endif |
| 540 | rt::cleanup_tls_clones(); | 590 | rt::cleanup_tls_clones(); |
| 541 | ExitProcess(static_cast<UINT>(code)); | 591 | ExitProcess(static_cast<UINT>(code)); |
diff --git a/runtime/src/title_window_plan.h b/runtime/src/title_window_plan.h index 807641df1..cd17bc596 100644 --- a/runtime/src/title_window_plan.h +++ b/runtime/src/title_window_plan.h | |||
| @@ -31,12 +31,13 @@ inline bool title_window_fits(std::uint64_t cap, std::uint64_t used, std::uint64 | |||
| 31 | inline bool title_window_range(std::uint64_t va, std::uint64_t bytes, std::uint64_t lo, std::uint64_t hi, | 31 | inline bool title_window_range(std::uint64_t va, std::uint64_t bytes, std::uint64_t lo, std::uint64_t hi, |
| 32 | std::uint64_t align, std::uint64_t most, std::uint64_t cap, std::uint64_t used, | 32 | std::uint64_t align, std::uint64_t most, std::uint64_t cap, std::uint64_t used, |
| 33 | TitleWindowRange& out) { | 33 | TitleWindowRange& out) { |
| 34 | if (!align || hi <= va) return false; | 34 | if (!align || (align & (align - 1)) != 0 || !most || va < lo || hi <= va) return false; |
| 35 | const std::uint64_t want = std::clamp<std::uint64_t>(bytes ? bytes : 1, 1, most); | 35 | const std::uint64_t want = (std::min)(bytes ? bytes : std::uint64_t(1), most); |
| 36 | const std::uint64_t start = (std::max)(va & ~(align - 1), lo); | 36 | const std::uint64_t start = (std::max)(va & ~(align - 1), lo); |
| 37 | std::uint64_t end = va > UINT64_MAX - want - align ? UINT64_MAX : (va + want + align - 1) & ~(align - 1); | 37 | const std::uint64_t raw_end = want > UINT64_MAX - va ? UINT64_MAX : va + want; |
| 38 | std::uint64_t end = raw_end > UINT64_MAX - (align - 1) ? UINT64_MAX : (raw_end + align - 1) & ~(align - 1); | ||
| 38 | end = (std::min)(end, hi); | 39 | end = (std::min)(end, hi); |
| 39 | if (end <= start) return false; | 40 | if (end <= va || end <= start) return false; |
| 40 | const TitleWindowRange range{start, end - start}; | 41 | const TitleWindowRange range{start, end - start}; |
| 41 | if (!title_window_fits(cap, used, range.size)) return false; | 42 | if (!title_window_fits(cap, used, range.size)) return false; |
| 42 | out = range; | 43 | out = range; |
| @@ -49,13 +50,15 @@ inline bool title_window_range(std::uint64_t va, std::uint64_t bytes, std::uint6 | |||
| 49 | inline bool title_pool_extent(std::uint64_t pool_lo, std::uint64_t pool_hi, std::uint64_t va, | 50 | inline bool title_pool_extent(std::uint64_t pool_lo, std::uint64_t pool_hi, std::uint64_t va, |
| 50 | std::uint64_t readable_end, std::uint64_t align, std::uint64_t most, | 51 | std::uint64_t readable_end, std::uint64_t align, std::uint64_t most, |
| 51 | TitleWindowRange& out) { | 52 | TitleWindowRange& out) { |
| 52 | if (!align || pool_hi <= pool_lo || va < pool_lo || va >= pool_hi) return false; | 53 | if (!align || (align & (align - 1)) != 0 || pool_hi <= pool_lo || va < pool_lo || va >= pool_hi || |
| 54 | readable_end <= va) | ||
| 55 | return false; | ||
| 53 | const std::uint64_t start = (std::max)(va & ~(align - 1), pool_lo); | 56 | const std::uint64_t start = (std::max)(va & ~(align - 1), pool_lo); |
| 54 | std::uint64_t end = (std::min)(readable_end, pool_hi); | 57 | std::uint64_t end = (std::min)(readable_end, pool_hi); |
| 55 | if (most) end = (std::min)(end, start > UINT64_MAX - most ? UINT64_MAX : start + most); | ||
| 56 | end = end > UINT64_MAX - (align - 1) ? UINT64_MAX : (end + align - 1) & ~(align - 1); | 58 | end = end > UINT64_MAX - (align - 1) ? UINT64_MAX : (end + align - 1) & ~(align - 1); |
| 59 | if (most) end = (std::min)(end, start > UINT64_MAX - most ? UINT64_MAX : start + most); | ||
| 57 | end = (std::min)(end, pool_hi); | 60 | end = (std::min)(end, pool_hi); |
| 58 | if (end <= va) return false; | 61 | if (end <= va || end <= start) return false; |
| 59 | out = {start, end - start}; | 62 | out = {start, end - start}; |
| 60 | return true; | 63 | return true; |
| 61 | } | 64 | } |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index d86b3ded7..68ab9b194 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -1337,12 +1337,13 @@ public: | |||
| 1337 | // device-local memory, and must set VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT. LEONIDA_INDIRECT_CLAMP=0 turns the | 1337 | // device-local memory, and must set VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT. LEONIDA_INDIRECT_CLAMP=0 turns the |
| 1338 | // pass off at replay time. | 1338 | // pass off at replay time. |
| 1339 | void enable_indirect_clamp(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, | 1339 | void enable_indirect_clamp(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, |
| 1340 | const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate) { | 1340 | const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate, |
| 1341 | std::vector<std::uint32_t> families = {}) { | ||
| 1341 | std::unique_lock lock(resource_mutex_); | 1342 | std::unique_lock lock(resource_mutex_); |
| 1342 | replay_.require_indirect_clamp = indirect_clamp_enabled(); | 1343 | replay_.require_indirect_clamp = indirect_clamp_enabled(); |
| 1343 | if (!replay_.require_indirect_clamp) return; | 1344 | if (!replay_.require_indirect_clamp) return; |
| 1344 | indirect_clamp_ = std::make_unique<IndirectArgumentClamp>(get, device_, memory, limits, std::move(allocate), | 1345 | indirect_clamp_ = std::make_unique<IndirectArgumentClamp>(get, device_, memory, limits, std::move(allocate), |
| 1345 | device_fault_.get()); | 1346 | device_fault_.get(), std::move(families)); |
| 1346 | if (!indirect_clamp_->loaded()) { | 1347 | if (!indirect_clamp_->loaded()) { |
| 1347 | indirect_clamp_.reset(); | 1348 | indirect_clamp_.reset(); |
| 1348 | return; | 1349 | return; |
| @@ -1556,32 +1557,42 @@ public: | |||
| 1556 | } | 1557 | } |
| 1557 | 1558 | ||
| 1558 | // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. | 1559 | // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. |
| 1560 | // Guarded by pipeline_mutex_ (separate from resource_mutex_) so shader compilation on one queue does not block | ||
| 1561 | // resource registration or destruction on the render thread. | ||
| 1559 | void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { | 1562 | void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { |
| 1560 | std::unique_lock lock(resource_mutex_); | 1563 | std::unique_lock lock(pipeline_mutex_); |
| 1561 | pipelines_[id] = pipeline; | 1564 | pipelines_[id] = pipeline; |
| 1562 | if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; | 1565 | if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; |
| 1563 | } | 1566 | } |
| 1564 | void remove_pipeline(std::uintptr_t id) { | 1567 | void remove_pipeline(std::uintptr_t id) { |
| 1565 | std::unique_lock lock(resource_mutex_); | 1568 | std::unique_lock lock(pipeline_mutex_); |
| 1566 | pipelines_.erase(id); | 1569 | pipelines_.erase(id); |
| 1567 | graphics_pipelines_.erase(id); | 1570 | graphics_pipelines_.erase(id); |
| 1568 | if (device_fault_) device_fault_->pipeline_names.erase(id); | 1571 | if (device_fault_) device_fault_->pipeline_names.erase(id); |
| 1569 | } | 1572 | } |
| 1570 | void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, | 1573 | void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, |
| 1571 | const CheckpointShaders* shaders = nullptr) { | 1574 | const CheckpointShaders* shaders = nullptr) { |
| 1572 | std::unique_lock lock(resource_mutex_); | 1575 | std::unique_lock lock(pipeline_mutex_); |
| 1573 | graphics_pipelines_[id] = pipeline; | 1576 | graphics_pipelines_[id] = pipeline; |
| 1574 | if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; | 1577 | if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; |
| 1575 | } | 1578 | } |
| 1576 | // Workers for the pipelines a submission needs and that are not built yet. Null (the default): each is built where | 1579 | // Workers for the pipelines a submission needs and that are not built yet. Null (the default): compiled serially on |
| 1577 | // prepare() meets it, on the submitting thread. Replacing it waits for submissions that are compiling, and ends the | 1580 | // the submitting thread once resource_mutex_ is released. Replacing it waits for submissions that are compiling, and |
| 1578 | // workers it had. | 1581 | // ends the workers it had. |
| 1579 | void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) { | 1582 | void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) { |
| 1580 | std::unique_lock lock(resource_mutex_); | 1583 | std::unique_lock lock(pipeline_mutex_); |
| 1581 | pipeline_workers_.swap(workers); | 1584 | pipeline_workers_.swap(workers); |
| 1582 | } | 1585 | } |
| 1586 | // For the large pipelines of a submission: the memory they may use while they compile together | ||
| 1587 | // (PipelineCompiles::build), and what is kept while they do (LargeModuleGate::Demand). None (the default): they compile | ||
| 1588 | // one after another. | ||
| 1589 | void set_large_compiles(std::function<std::uint64_t()> budget, std::function<std::shared_ptr<void>()> demand) { | ||
| 1590 | std::unique_lock lock(pipeline_mutex_); | ||
| 1591 | large_compile_budget_ = std::move(budget); | ||
| 1592 | large_compile_demand_ = std::move(demand); | ||
| 1593 | } | ||
| 1583 | PipelineWorkers::Stats pipeline_worker_stats() { | 1594 | PipelineWorkers::Stats pipeline_worker_stats() { |
| 1584 | std::shared_lock lock(resource_mutex_); | 1595 | std::shared_lock lock(pipeline_mutex_); |
| 1585 | return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; | 1596 | return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; |
| 1586 | } | 1597 | } |
| 1587 | // Configure before queue creation, when the selected queue family supports compute. | 1598 | // Configure before queue creation, when the selected queue family supports compute. |
| @@ -1785,7 +1796,7 @@ public: | |||
| 1785 | return true; | 1796 | return true; |
| 1786 | } | 1797 | } |
| 1787 | const char* diagnostic_compute_name(std::uintptr_t id) { | 1798 | const char* diagnostic_compute_name(std::uintptr_t id) { |
| 1788 | std::shared_lock lock(resource_mutex_); | 1799 | std::shared_lock lock(pipeline_mutex_); |
| 1789 | if (!device_fault_) return nullptr; | 1800 | if (!device_fault_) return nullptr; |
| 1790 | const auto it = device_fault_->pipeline_names.find(id); | 1801 | const auto it = device_fault_->pipeline_names.find(id); |
| 1791 | return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; | 1802 | return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; |
| @@ -2177,6 +2188,7 @@ private: | |||
| 2177 | bool ray_tracing_ = false; | 2188 | bool ray_tracing_ = false; |
| 2178 | std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records | 2189 | std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records |
| 2179 | std::atomic<bool> device_lost_{false}; | 2190 | std::atomic<bool> device_lost_{false}; |
| 2191 | alignas(64) std::shared_mutex pipeline_mutex_; // shared for prepare/compile/emit pipeline lookups, unique for add/remove/workers | ||
| 2180 | alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove | 2192 | alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove |
| 2181 | alignas(64) std::mutex tracker_mutex_; | 2193 | alignas(64) std::mutex tracker_mutex_; |
| 2182 | alignas(64) std::mutex views_mutex_; | 2194 | alignas(64) std::mutex views_mutex_; |
| @@ -2196,6 +2208,8 @@ private: | |||
| 2196 | std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; | 2208 | std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; |
| 2197 | std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; | 2209 | std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; |
| 2198 | std::unique_ptr<PipelineWorkers> pipeline_workers_; | 2210 | std::unique_ptr<PipelineWorkers> pipeline_workers_; |
| 2211 | std::function<std::uint64_t()> large_compile_budget_; | ||
| 2212 | std::function<std::shared_ptr<void>()> large_compile_demand_; | ||
| 2199 | std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; | 2213 | std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; |
| 2200 | LayoutTracker tracker_; | 2214 | LayoutTracker tracker_; |
| 2201 | std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only | 2215 | std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only |
| @@ -2910,11 +2924,15 @@ private: | |||
| 2910 | } | 2924 | } |
| 2911 | } khr_guard{this}; | 2925 | } khr_guard{this}; |
| 2912 | std::function<void(bool)> bindless_commit; | 2926 | std::function<void(bool)> bindless_commit; |
| 2913 | // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. | 2927 | // Lock hierarchy: state_mutex_ -> pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> submit_mutex_. |
| 2914 | // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during | 2928 | // Shared pipeline_lock keeps registered pipelines, pipeline_names, and pipeline_workers_ alive across |
| 2915 | // prepare() only if a list actually converts a depth24_as_float copy, and otherwise right before | 2929 | // preparation, compilation, and emit. Shared resource_lock allows concurrent prepare() across queues and is |
| 2916 | // bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and submissions stay in order. | 2930 | // released while unbuilt pipelines compile so add_resource()/remove_resource() never stall behind shader |
| 2917 | std::shared_lock resource_lock(context_.resource_mutex_); | 2931 | // compiles; tracker_mutex_ is acquired lazily during prepare() only if a list uses a shared helper, and |
| 2932 | // otherwise right before bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and | ||
| 2933 | // submissions stay in order. | ||
| 2934 | std::shared_lock pipeline_lock(context_.pipeline_mutex_); | ||
| 2935 | std::shared_lock resource_lock(context_.resource_mutex_, std::defer_lock); | ||
| 2918 | std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); | 2936 | std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); |
| 2919 | // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools | 2937 | // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools |
| 2920 | // with ticket 0 while tracker_lock is still held. | 2938 | // with ticket 0 while tracker_lock is still held. |
| @@ -2925,7 +2943,7 @@ private: | |||
| 2925 | ~Depth24Guard() { | 2943 | ~Depth24Guard() { |
| 2926 | if (active && d24) d24->retire(progress, 0); | 2944 | if (active && d24) d24->retire(progress, 0); |
| 2927 | } | 2945 | } |
| 2928 | } depth24_guard{context_.depth24_.get(), progress_, false}; | 2946 | } depth24_guard{nullptr, progress_, false}; |
| 2929 | struct ScratchGuard { // the same for the copy scratch | 2947 | struct ScratchGuard { // the same for the copy scratch |
| 2930 | ScratchBuffers* scratch = nullptr; | 2948 | ScratchBuffers* scratch = nullptr; |
| 2931 | VkSemaphore progress = VK_NULL_HANDLE; | 2949 | VkSemaphore progress = VK_NULL_HANDLE; |
| @@ -2933,7 +2951,7 @@ private: | |||
| 2933 | ~ScratchGuard() { | 2951 | ~ScratchGuard() { |
| 2934 | if (active && scratch) scratch->retire(progress, 0); | 2952 | if (active && scratch) scratch->retire(progress, 0); |
| 2935 | } | 2953 | } |
| 2936 | } scratch_guard{context_.scratch_.get(), progress_, false}; | 2954 | } scratch_guard{nullptr, progress_, false}; |
| 2937 | struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch | 2955 | struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch |
| 2938 | IndirectArgumentClamp* clamp = nullptr; | 2956 | IndirectArgumentClamp* clamp = nullptr; |
| 2939 | VkSemaphore progress = VK_NULL_HANDLE; | 2957 | VkSemaphore progress = VK_NULL_HANDLE; |
| @@ -2941,9 +2959,8 @@ private: | |||
| 2941 | ~ClampGuard() { | 2959 | ~ClampGuard() { |
| 2942 | if (active && clamp) clamp->retire(progress, 0); | 2960 | if (active && clamp) clamp->retire(progress, 0); |
| 2943 | } | 2961 | } |
| 2944 | } clamp_guard{context_.indirect_clamp_.get(), progress_, false}; | 2962 | } clamp_guard{nullptr, progress_, false}; |
| 2945 | const bool transfer_only = family_ == context_.transfer_only_family_; | 2963 | const bool transfer_only = family_ == context_.transfer_only_family_; |
| 2946 | if (!transfer_only) bindless_commit = context_.bindless_commit_; | ||
| 2947 | // Kept between executions: prepare refills each list's entries in the storage the last execution left, where | 2964 | // Kept between executions: prepare refills each list's entries in the storage the last execution left, where |
| 2948 | // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). | 2965 | // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). |
| 2949 | auto& prepared = prepared_; | 2966 | auto& prepared = prepared_; |
| @@ -2951,42 +2968,9 @@ private: | |||
| 2951 | // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below | 2968 | // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below |
| 2952 | // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. | 2969 | // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. |
| 2953 | if (prepared.size() < lists.size()) prepared.resize(lists.size()); | 2970 | if (prepared.size() < lists.size()) prepared.resize(lists.size()); |
| 2954 | ReplayFunctions replay = context_.replay_; | 2971 | ReplayFunctions replay{}; |
| 2955 | unsigned mesh_draws = 0; | 2972 | unsigned mesh_draws = 0; |
| 2956 | if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws; | ||
| 2957 | std::vector<VulkanContext::GeometryUpload> geometry; | 2973 | std::vector<VulkanContext::GeometryUpload> geometry; |
| 2958 | if (context_.geometry_provider_) { | ||
| 2959 | replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { | ||
| 2960 | if (!va || !bytes || bytes>UINT64_MAX-va) return false; | ||
| 2961 | for (const auto& upload : geometry) { | ||
| 2962 | if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue; | ||
| 2963 | buffer=upload.buffer; offset=upload.offset+(va-upload.source); | ||
| 2964 | return true; | ||
| 2965 | } | ||
| 2966 | VulkanContext::GeometryUpload upload; | ||
| 2967 | if (!context_.geometry_provider_(va,bytes,upload)) return false; | ||
| 2968 | buffer=upload.buffer;offset=upload.offset; | ||
| 2969 | geometry.push_back(std::move(upload)); | ||
| 2970 | return true; | ||
| 2971 | }; | ||
| 2972 | } | ||
| 2973 | replay.graphics_family = family_ == context_.graphics_family_; | ||
| 2974 | replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy | ||
| 2975 | : kind_ == QueueKind::compute ? detail::queue_stages_compute | ||
| 2976 | : 0; | ||
| 2977 | replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build, | ||
| 2978 | VkDeviceAddress& address) { | ||
| 2979 | return stage_khr_instances(replay, build, khr_guard.stages, address); | ||
| 2980 | }; | ||
| 2981 | replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) { | ||
| 2982 | return stage_xdxr_table(khr_guard.stages, address, count); | ||
| 2983 | }; | ||
| 2984 | if (replay.write_acceleration_structures_properties) { | ||
| 2985 | replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool, | ||
| 2986 | std::uint32_t& first) { | ||
| 2987 | return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first); | ||
| 2988 | }; | ||
| 2989 | } | ||
| 2990 | std::uint64_t captures = 0; | 2974 | std::uint64_t captures = 0; |
| 2991 | for (const auto* list : lists) | 2975 | for (const auto* list : lists) |
| 2992 | for (const auto& command : list->commands()) | 2976 | for (const auto& command : list->commands()) |
| @@ -2995,149 +2979,239 @@ private: | |||
| 2995 | std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; | 2979 | std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; |
| 2996 | std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; | 2980 | std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; |
| 2997 | std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch; | 2981 | std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch; |
| 2998 | if (captures) { | 2982 | const auto& occlusion_memory = context_.occlusion_resolve_memory_; |
| 2999 | if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) | 2983 | const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; |
| 3000 | return queue_unsupported(__LINE__); | 2984 | const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; |
| 3001 | // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, | 2985 | std::uint32_t segments = 0, statistics_segments = 0; |
| 3002 | // retaining main's resource -> tracker -> submit lock order through emit and submission. | 2986 | bool has_queries = false; |
| 3003 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | 2987 | const auto run_compiles = [this](std::size_t count, const std::function<void(std::size_t)>& job) { |
| 3004 | batch = context_.predicate_reducer_->batch(captures); | 2988 | context_.pipeline_workers_->run(count, job); |
| 3005 | if (!batch) return queue_unsupported(__LINE__); | 2989 | }; |
| 3006 | replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { | 2990 | PipelineCompiles prior_compiles; |
| 3007 | return batch->prepare(buffer, offset, out); | 2991 | bool has_prior_compiles = false; |
| 2992 | for (int pass = 0;; ++pass) { | ||
| 2993 | resource_lock.lock(); | ||
| 2994 | bindless_commit = !transfer_only ? context_.bindless_commit_ : std::function<void(bool)>{}; | ||
| 2995 | replay = context_.replay_; | ||
| 2996 | mesh_draws = 0; | ||
| 2997 | if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws; | ||
| 2998 | if (context_.geometry_provider_) { | ||
| 2999 | replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { | ||
| 3000 | if (!va || !bytes || bytes>UINT64_MAX-va) return false; | ||
| 3001 | for (const auto& upload : geometry) { | ||
| 3002 | if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue; | ||
| 3003 | buffer=upload.buffer; offset=upload.offset+(va-upload.source); | ||
| 3004 | return true; | ||
| 3005 | } | ||
| 3006 | VulkanContext::GeometryUpload upload; | ||
| 3007 | if (!context_.geometry_provider_(va,bytes,upload)) return false; | ||
| 3008 | buffer=upload.buffer;offset=upload.offset; | ||
| 3009 | geometry.push_back(std::move(upload)); | ||
| 3010 | return true; | ||
| 3011 | }; | ||
| 3012 | } | ||
| 3013 | replay.graphics_family = family_ == context_.graphics_family_; | ||
| 3014 | replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy | ||
| 3015 | : kind_ == QueueKind::compute ? detail::queue_stages_compute | ||
| 3016 | : 0; | ||
| 3017 | replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build, | ||
| 3018 | VkDeviceAddress& address) { | ||
| 3019 | return stage_khr_instances(replay, build, khr_guard.stages, address); | ||
| 3008 | }; | 3020 | }; |
| 3009 | replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { | 3021 | replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) { |
| 3010 | context_.predicate_reducer_->capture(cb, p); | 3022 | return stage_xdxr_table(khr_guard.stages, address, count); |
| 3011 | }; | 3023 | }; |
| 3012 | if (context_.predicated_copier_) { | 3024 | if (replay.write_acceleration_structures_properties) { |
| 3013 | copy_batch = context_.predicated_copier_->batch(); | 3025 | replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool, |
| 3014 | replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, | 3026 | std::uint32_t& first) { |
| 3015 | VkDeviceSize dst, VkDeviceSize size, | 3027 | return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first); |
| 3016 | std::vector<PredicatedCopyDispatch>& out) { | ||
| 3017 | return copy_batch->prepare(source, destination, src, dst, size, out); | ||
| 3018 | }; | ||
| 3019 | replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) { | ||
| 3020 | context_.predicated_copier_->emit(cb, jobs); | ||
| 3021 | }; | 3028 | }; |
| 3022 | } | 3029 | } |
| 3023 | } | 3030 | if (captures) { |
| 3024 | if (context_.scratch_) { | 3031 | if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) |
| 3025 | replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, | 3032 | return queue_unsupported(__LINE__); |
| 3026 | VkDeviceSize& offset) { | 3033 | // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, |
| 3034 | // retaining pipeline -> resource -> tracker -> submit lock order through emit and submission. | ||
| 3027 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | 3035 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); |
| 3028 | if (!scratch_guard.active) { | 3036 | batch = context_.predicate_reducer_->batch(captures); |
| 3029 | context_.scratch_->collect(); | 3037 | if (!batch) return queue_unsupported(__LINE__); |
| 3030 | scratch_guard.active = true; | 3038 | replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { |
| 3039 | return batch->prepare(buffer, offset, out); | ||
| 3040 | }; | ||
| 3041 | replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { | ||
| 3042 | context_.predicate_reducer_->capture(cb, p); | ||
| 3043 | }; | ||
| 3044 | if (context_.predicated_copier_) { | ||
| 3045 | copy_batch = context_.predicated_copier_->batch(); | ||
| 3046 | replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, | ||
| 3047 | VkDeviceSize dst, VkDeviceSize size, | ||
| 3048 | std::vector<PredicatedCopyDispatch>& out) { | ||
| 3049 | return copy_batch->prepare(source, destination, src, dst, size, out); | ||
| 3050 | }; | ||
| 3051 | replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) { | ||
| 3052 | context_.predicated_copier_->emit(cb, jobs); | ||
| 3053 | }; | ||
| 3031 | } | 3054 | } |
| 3032 | return context_.scratch_->get(bytes, buffer, offset); | 3055 | } |
| 3033 | }; | 3056 | if (context_.scratch_) { |
| 3034 | } | 3057 | replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, |
| 3035 | if (kind_ != QueueKind::copy && context_.indirect_clamp_) { | 3058 | VkDeviceSize& offset) { |
| 3036 | // The record scratch belongs to this submission: collected here, retired below with its ticket. The | 3059 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); |
| 3037 | // counter slots are read back once that ticket completes (the batch's destructor). | 3060 | if (!scratch_guard.active) { |
| 3038 | replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( | 3061 | scratch_guard.scratch = context_.scratch_.get(); |
| 3039 | VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, | 3062 | context_.scratch_->collect(); |
| 3040 | VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, | 3063 | scratch_guard.active = true; |
| 3041 | std::uint32_t max_count, ClampedIndirect& out) { | 3064 | } |
| 3042 | // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. | 3065 | return context_.scratch_->get(bytes, buffer, offset); |
| 3043 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | 3066 | }; |
| 3044 | if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); | 3067 | } |
| 3045 | if (!clamp_guard.active) { | 3068 | if (kind_ != QueueKind::copy && context_.indirect_clamp_) { |
| 3046 | context_.indirect_clamp_->collect(); | 3069 | // The record scratch belongs to this submission: collected here, retired below with its ticket. The |
| 3047 | clamp_guard.active = true; | 3070 | // counter slots are read back once that ticket completes (the batch's destructor). |
| 3071 | replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( | ||
| 3072 | VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, | ||
| 3073 | VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, | ||
| 3074 | std::uint32_t max_count, ClampedIndirect& out) { | ||
| 3075 | // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. | ||
| 3076 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 3077 | if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); | ||
| 3078 | if (!clamp_guard.active) { | ||
| 3079 | clamp_guard.clamp = context_.indirect_clamp_.get(); | ||
| 3080 | context_.indirect_clamp_->collect(); | ||
| 3081 | clamp_guard.active = true; | ||
| 3082 | } | ||
| 3083 | return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, | ||
| 3084 | max_count, out); | ||
| 3085 | }; | ||
| 3086 | } | ||
| 3087 | if (kind_ != QueueKind::copy && context_.counted_dispatch_) { | ||
| 3088 | replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( | ||
| 3089 | VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, | ||
| 3090 | std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { | ||
| 3091 | // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. | ||
| 3092 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 3093 | if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); | ||
| 3094 | return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out); | ||
| 3095 | }; | ||
| 3096 | replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) { | ||
| 3097 | context_.counted_dispatch_->emit(cb, job); | ||
| 3098 | }; | ||
| 3099 | } | ||
| 3100 | if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) { | ||
| 3101 | replay.prepare_quad_indices = [this, &tracker_lock]( | ||
| 3102 | VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads, | ||
| 3103 | VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { | ||
| 3104 | // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. | ||
| 3105 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 3106 | return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch, | ||
| 3107 | scratch_offset, out); | ||
| 3108 | }; | ||
| 3109 | replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) { | ||
| 3110 | context_.quad_indices_->emit(cb, job); | ||
| 3111 | }; | ||
| 3112 | } | ||
| 3113 | if (context_.depth24_ && !transfer_only) { | ||
| 3114 | replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, | ||
| 3115 | std::vector<Depth24Job>& parts) { | ||
| 3116 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 3117 | if (!depth24_guard.active) { | ||
| 3118 | depth24_guard.d24 = context_.depth24_.get(); | ||
| 3119 | context_.depth24_->collect(); | ||
| 3120 | depth24_guard.active = true; | ||
| 3121 | } | ||
| 3122 | return context_.depth24_->prepare(job, parts); | ||
| 3123 | }; | ||
| 3124 | } | ||
| 3125 | if (can_resolve_occlusion) { | ||
| 3126 | replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | ||
| 3127 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | ||
| 3128 | occlusion_resolve_->sum(cb, pool, first, count, dst, offset); | ||
| 3129 | }; | ||
| 3130 | replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | ||
| 3131 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | ||
| 3132 | occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); | ||
| 3133 | }; | ||
| 3134 | replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, | ||
| 3135 | VkQueryPool primitives_pool, const std::uint8_t* mesh, | ||
| 3136 | std::uint32_t first, std::uint32_t count, VkBuffer dst, | ||
| 3137 | VkDeviceSize offset) { | ||
| 3138 | occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, | ||
| 3139 | offset); | ||
| 3140 | }; | ||
| 3141 | replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | ||
| 3142 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | ||
| 3143 | occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); | ||
| 3144 | }; | ||
| 3145 | } | ||
| 3146 | segments = 0; | ||
| 3147 | statistics_segments = 0; | ||
| 3148 | has_queries = false; | ||
| 3149 | // Collect unbuilt pipelines via PipelineCompiles (whether pipeline_workers_ is enabled or serial). | ||
| 3150 | // On pass 0, if any pipeline must be compiled, release pass-0 transient state along with tracker_lock | ||
| 3151 | // and resource_lock before invoking the compiler (keeping pipeline_lock so registered pipelines and | ||
| 3152 | // workers stay alive), then re-prepare on pass 1 against current resources. | ||
| 3153 | PipelineCompiles compiles; | ||
| 3154 | replay.compiles = &compiles; | ||
| 3155 | ReplayResult prepare_result = ReplayResult::success; | ||
| 3156 | for (std::size_t i = 0; i < lists.size(); ++i) { | ||
| 3157 | const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion); | ||
| 3158 | if (result != ReplayResult::success) { | ||
| 3159 | prepare_result = result; | ||
| 3160 | break; | ||
| 3048 | } | 3161 | } |
| 3049 | return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, max_count, | 3162 | if (prepared[i].segment_count > UINT32_MAX - segments || |
| 3050 | out); | 3163 | prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) |
| 3051 | }; | 3164 | return queue_unsupported(__LINE__); |
| 3052 | } | 3165 | segments += prepared[i].segment_count; |
| 3053 | if (kind_ != QueueKind::copy && context_.counted_dispatch_) { | 3166 | statistics_segments += prepared[i].statistics_segment_count; |
| 3054 | replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( | 3167 | has_queries = has_queries || !prepared[i].queries.empty(); |
| 3055 | VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, | 3168 | } |
| 3056 | std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { | 3169 | if (pass == 0 && !compiles.empty()) { |
| 3057 | // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. | 3170 | if (depth24_guard.active) { |
| 3058 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | 3171 | context_.depth24_->retire(progress_, 0); |
| 3059 | if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); | 3172 | depth24_guard.active = false; |
| 3060 | return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out); | ||
| 3061 | }; | ||
| 3062 | replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) { | ||
| 3063 | context_.counted_dispatch_->emit(cb, job); | ||
| 3064 | }; | ||
| 3065 | } | ||
| 3066 | if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) { | ||
| 3067 | replay.prepare_quad_indices = [this, &tracker_lock]( | ||
| 3068 | VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads, | ||
| 3069 | VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { | ||
| 3070 | // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. | ||
| 3071 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 3072 | return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch, | ||
| 3073 | scratch_offset, out); | ||
| 3074 | }; | ||
| 3075 | replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) { | ||
| 3076 | context_.quad_indices_->emit(cb, job); | ||
| 3077 | }; | ||
| 3078 | } | ||
| 3079 | if (context_.depth24_ && !transfer_only) { | ||
| 3080 | replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, | ||
| 3081 | std::vector<Depth24Job>& parts) { | ||
| 3082 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | ||
| 3083 | if (!depth24_guard.active) { | ||
| 3084 | context_.depth24_->collect(); | ||
| 3085 | depth24_guard.active = true; | ||
| 3086 | } | 3173 | } |
| 3087 | return context_.depth24_->prepare(job, parts); | 3174 | if (scratch_guard.active) { |
| 3088 | }; | 3175 | context_.scratch_->retire(progress_, 0); |
| 3089 | } | 3176 | scratch_guard.active = false; |
| 3090 | const auto& occlusion_memory = context_.occlusion_resolve_memory_; | 3177 | } |
| 3091 | const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; | 3178 | if (clamp_guard.active) { |
| 3092 | if (can_resolve_occlusion) { | 3179 | context_.indirect_clamp_->retire(progress_, 0); |
| 3093 | replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | 3180 | clamp_guard.active = false; |
| 3094 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | 3181 | } |
| 3095 | occlusion_resolve_->sum(cb, pool, first, count, dst, offset); | 3182 | batch.reset(); |
| 3096 | }; | 3183 | copy_batch.reset(); |
| 3097 | replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | 3184 | counted_batch.reset(); |
| 3098 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | 3185 | clamp_batch.reset(); |
| 3099 | occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); | 3186 | if (tracker_lock.owns_lock()) tracker_lock.unlock(); |
| 3100 | }; | 3187 | resource_lock.unlock(); |
| 3101 | replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, | 3188 | recycle_khr_stages(khr_guard.stages); |
| 3102 | VkQueryPool primitives_pool, const std::uint8_t* mesh, | 3189 | recycle_khr_as_queries(khr_guard.as_queries); |
| 3103 | std::uint32_t first, std::uint32_t count, VkBuffer dst, | 3190 | geometry.clear(); |
| 3104 | VkDeviceSize offset) { | 3191 | |
| 3105 | occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, | 3192 | std::shared_ptr<void> demand; |
| 3106 | offset); | 3193 | if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_(); |
| 3107 | }; | 3194 | if (context_.pipeline_workers_) |
| 3108 | replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | 3195 | compiles.build(run_compiles, context_.large_compile_budget_); |
| 3109 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | 3196 | else |
| 3110 | occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); | 3197 | compiles.build_serial(); |
| 3111 | }; | 3198 | demand.reset(); |
| 3112 | } | 3199 | const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result); |
| 3113 | const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; | 3200 | if (compile_result != ReplayResult::success) return compile_result; |
| 3114 | std::uint32_t segments = 0, statistics_segments = 0; | 3201 | prior_compiles = std::move(compiles); |
| 3115 | bool has_queries = false; | 3202 | has_prior_compiles = true; |
| 3116 | // With workers, the pipelines the lists need and that are not built yet are compiled together below instead of | 3203 | continue; |
| 3117 | // one after another in prepare(). resource_lock is held until they are all built, which keeps the pipeline | ||
| 3118 | // states that own them alive (remove_pipeline takes it uniquely). | ||
| 3119 | PipelineCompiles compiles; | ||
| 3120 | if (context_.pipeline_workers_) replay.compiles = &compiles; | ||
| 3121 | ReplayResult prepare_result = ReplayResult::success; | ||
| 3122 | for (std::size_t i = 0; i < lists.size(); ++i) { | ||
| 3123 | const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion); | ||
| 3124 | if (result != ReplayResult::success) { | ||
| 3125 | prepare_result = result; | ||
| 3126 | break; | ||
| 3127 | } | 3204 | } |
| 3128 | if (prepared[i].segment_count > UINT32_MAX - segments || | 3205 | const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr; |
| 3129 | prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) | 3206 | prepare_result = context_.pipeline_workers_ |
| 3130 | return queue_unsupported(__LINE__); | 3207 | ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result, |
| 3131 | segments += prepared[i].segment_count; | 3208 | run_compiles, context_.large_compile_budget_, prior) |
| 3132 | statistics_segments += prepared[i].statistics_segment_count; | 3209 | : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()), |
| 3133 | has_queries = has_queries || !prepared[i].queries.empty(); | 3210 | prepare_result, prior); |
| 3134 | } | 3211 | replay.compiles = nullptr; |
| 3135 | prepare_result = build_pipelines( | 3212 | if (prepare_result != ReplayResult::success) return prepare_result; |
| 3136 | compiles, std::span(prepared).first(lists.size()), prepare_result, | 3213 | break; |
| 3137 | [this](std::size_t count, const std::function<void(std::size_t)>& job) { | 3214 | } |
| 3138 | context_.pipeline_workers_->run(count, job); | ||
| 3139 | }); | ||
| 3140 | if (prepare_result != ReplayResult::success) return prepare_result; | ||
| 3141 | const auto segment_pool = [this](VkQueryType type, std::uint32_t count, | 3215 | const auto segment_pool = [this](VkQueryType type, std::uint32_t count, |
| 3142 | std::shared_ptr<OcclusionSegmentPool>& out) { | 3216 | std::shared_ptr<OcclusionSegmentPool>& out) { |
| 3143 | const auto& vk = context_.vk; | 3217 | const auto& vk = context_.vk; |
| @@ -3264,6 +3338,7 @@ private: | |||
| 3264 | const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), | 3338 | const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), |
| 3265 | "vkEndCommandBuffer") == VK_SUCCESS; | 3339 | "vkEndCommandBuffer") == VK_SUCCESS; |
| 3266 | resource_lock.unlock(); | 3340 | resource_lock.unlock(); |
| 3341 | pipeline_lock.unlock(); | ||
| 3267 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); | 3342 | const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); |
| 3268 | if (!submitted) discard(); | 3343 | if (!submitted) discard(); |
| 3269 | if (depth24_guard.active) { | 3344 | if (depth24_guard.active) { |
| @@ -3397,7 +3472,8 @@ private: | |||
| 3397 | } | 3472 | } |
| 3398 | const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), | 3473 | const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), |
| 3399 | "vkEndCommandBuffer") == VK_SUCCESS; | 3474 | "vkEndCommandBuffer") == VK_SUCCESS; |
| 3400 | resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held | 3475 | resource_lock.unlock(); // release resource_mutex_ and pipeline_mutex_ before vkQueueSubmit while keeping tracker_lock held |
| 3476 | pipeline_lock.unlock(); | ||
| 3401 | const bool wait_previous = ordered_timestamps && submitted_; | 3477 | const bool wait_previous = ordered_timestamps && submitted_; |
| 3402 | if (wait_previous) { | 3478 | if (wait_previous) { |
| 3403 | waits_.push_back(progress_); | 3479 | waits_.push_back(progress_); |
| @@ -4082,7 +4158,8 @@ private: | |||
| 4082 | std::vector<PreparedList> prepared_; | 4158 | std::vector<PreparedList> prepared_; |
| 4083 | std::uint32_t open_labels_ = 0; // queue labels begun and not ended | 4159 | std::uint32_t open_labels_ = 0; // queue labels begun and not ended |
| 4084 | bool ok_ = false; | 4160 | bool ok_ = false; |
| 4085 | // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and | 4161 | // Wait-before-Signal. state_mutex_ is outermost (before pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> |
| 4162 | // submit_mutex_) and | ||
| 4086 | // guards the members above that execute, signal, wait and marker touch. | 4163 | // guards the members above that execute, signal, wait and marker touch. |
| 4087 | std::mutex state_mutex_; | 4164 | std::mutex state_mutex_; |
| 4088 | std::deque<Deferred> held_; | 4165 | std::deque<Deferred> held_; |
diff --git a/runtime/src/vulkan_indirect_clamp.h b/runtime/src/vulkan_indirect_clamp.h index e510e3b0c..3eb192d0f 100644 --- a/runtime/src/vulkan_indirect_clamp.h +++ b/runtime/src/vulkan_indirect_clamp.h | |||
| @@ -135,7 +135,8 @@ public: | |||
| 135 | 135 | ||
| 136 | IndirectArgumentClamp(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, | 136 | IndirectArgumentClamp(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, |
| 137 | const VkPhysicalDeviceLimits& limits, Allocate allocate, | 137 | const VkPhysicalDeviceLimits& limits, Allocate allocate, |
| 138 | DeviceFaultDiagnostics* diagnostics = nullptr); | 138 | DeviceFaultDiagnostics* diagnostics = nullptr, |
| 139 | std::vector<std::uint32_t> families = {}); | ||
| 139 | ~IndirectArgumentClamp(); | 140 | ~IndirectArgumentClamp(); |
| 140 | IndirectArgumentClamp(const IndirectArgumentClamp&) = delete; | 141 | IndirectArgumentClamp(const IndirectArgumentClamp&) = delete; |
| 141 | IndirectArgumentClamp& operator=(const IndirectArgumentClamp&) = delete; | 142 | IndirectArgumentClamp& operator=(const IndirectArgumentClamp&) = delete; |
| @@ -189,7 +190,14 @@ public: | |||
| 189 | if (counted) owner_.release_one(slot); | 190 | if (counted) owner_.release_one(slot); |
| 190 | return false; | 191 | return false; |
| 191 | } | 192 | } |
| 192 | if (counted) slots_.push_back(slot); | 193 | if (counted) { |
| 194 | try { | ||
| 195 | slots_.push_back(slot); | ||
| 196 | } catch (...) { | ||
| 197 | owner_.release_one(slot); | ||
| 198 | throw; | ||
| 199 | } | ||
| 200 | } | ||
| 193 | return true; | 201 | return true; |
| 194 | } | 202 | } |
| 195 | 203 | ||
| @@ -240,7 +248,7 @@ private: | |||
| 240 | VkDevice device_; | 248 | VkDevice device_; |
| 241 | VkPhysicalDeviceMemoryProperties memory_{}; | 249 | VkPhysicalDeviceMemoryProperties memory_{}; |
| 242 | VkPhysicalDeviceLimits limits_{}; | 250 | VkPhysicalDeviceLimits limits_{}; |
| 243 | DeviceFaultDiagnostics* diagnostics_ = nullptr; | 251 | std::vector<std::uint32_t> families_; |
| 244 | ScratchBuffers scratch_; | 252 | ScratchBuffers scratch_; |
| 245 | VkPipelineLayout layout_ = VK_NULL_HANDLE; | 253 | VkPipelineLayout layout_ = VK_NULL_HANDLE; |
| 246 | VkPipeline pipeline_ = VK_NULL_HANDLE; | 254 | VkPipeline pipeline_ = VK_NULL_HANDLE; |
| @@ -281,9 +289,10 @@ inline constexpr VkBufferUsageFlags indirect_clamp_scratch_usage = | |||
| 281 | inline IndirectArgumentClamp::IndirectArgumentClamp(PFN_vkGetDeviceProcAddr get, VkDevice device, | 289 | inline IndirectArgumentClamp::IndirectArgumentClamp(PFN_vkGetDeviceProcAddr get, VkDevice device, |
| 282 | const VkPhysicalDeviceMemoryProperties& memory, | 290 | const VkPhysicalDeviceMemoryProperties& memory, |
| 283 | const VkPhysicalDeviceLimits& limits, Allocate allocate, | 291 | const VkPhysicalDeviceLimits& limits, Allocate allocate, |
| 284 | DeviceFaultDiagnostics* diagnostics) | 292 | DeviceFaultDiagnostics* diagnostics, |
| 285 | : get_(get), device_(device), memory_(memory), limits_(limits), diagnostics_(diagnostics), | 293 | std::vector<std::uint32_t> families) |
| 286 | scratch_(get, device, std::move(allocate), diagnostics, detail::indirect_clamp_scratch_usage) {} | 294 | : get_(get), device_(device), memory_(memory), limits_(limits), families_(std::move(families)), |
| 295 | scratch_(get, device, std::move(allocate), diagnostics, detail::indirect_clamp_scratch_usage, families_) {} | ||
| 287 | 296 | ||
| 288 | inline IndirectArgumentClamp::~IndirectArgumentClamp() { | 297 | inline IndirectArgumentClamp::~IndirectArgumentClamp() { |
| 289 | const auto destroy_pipeline = fn<PFN_vkDestroyPipeline>("vkDestroyPipeline"); | 298 | const auto destroy_pipeline = fn<PFN_vkDestroyPipeline>("vkDestroyPipeline"); |
| @@ -354,7 +363,17 @@ inline bool IndirectArgumentClamp::make_area() { | |||
| 354 | VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; | 363 | VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; |
| 355 | info.size = VkDeviceSize(area.slots) * HostArea::slot_bytes; | 364 | info.size = VkDeviceSize(area.slots) * HostArea::slot_bytes; |
| 356 | info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; | 365 | info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; |
| 366 | // Direct and async-compute queues copy counter slots into the same HostArea buffer concurrently. | ||
| 367 | share_across_queue_families(info, families_); | ||
| 357 | if (create_buffer(device_, &info, nullptr, &area.buffer) != VK_SUCCESS) return false; | 368 | if (create_buffer(device_, &info, nullptr, &area.buffer) != VK_SUCCESS) return false; |
| 369 | const auto destroy_buffer = fn<PFN_vkDestroyBuffer>("vkDestroyBuffer"); | ||
| 370 | const auto free_memory = fn<PFN_vkFreeMemory>("vkFreeMemory"); | ||
| 371 | const auto cleanup = [&] { | ||
| 372 | if (area.buffer && destroy_buffer) destroy_buffer(device_, area.buffer, nullptr); | ||
| 373 | if (area.memory && free_memory) free_memory(device_, area.memory, nullptr); | ||
| 374 | area.buffer = VK_NULL_HANDLE; | ||
| 375 | area.memory = VK_NULL_HANDLE; | ||
| 376 | }; | ||
| 358 | VkMemoryRequirements requirements{}; | 377 | VkMemoryRequirements requirements{}; |
| 359 | requirements_fn(device_, area.buffer, &requirements); | 378 | requirements_fn(device_, area.buffer, &requirements); |
| 360 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | 379 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; |
| @@ -371,16 +390,23 @@ inline bool IndirectArgumentClamp::make_area() { | |||
| 371 | } | 390 | } |
| 372 | bound = bind_fn(device_, area.buffer, area.memory, 0) == VK_SUCCESS; | 391 | bound = bind_fn(device_, area.buffer, area.memory, 0) == VK_SUCCESS; |
| 373 | if (bound) break; | 392 | if (bound) break; |
| 393 | if (free_memory) free_memory(device_, area.memory, nullptr); | ||
| 394 | area.memory = VK_NULL_HANDLE; | ||
| 374 | } | 395 | } |
| 375 | if (!bound || map_fn(device_, area.memory, 0, info.size, 0, reinterpret_cast<void**>(&area.host)) != VK_SUCCESS) { | 396 | if (!bound || map_fn(device_, area.memory, 0, info.size, 0, reinterpret_cast<void**>(&area.host)) != VK_SUCCESS) { |
| 376 | const auto destroy_buffer = fn<PFN_vkDestroyBuffer>("vkDestroyBuffer"); | 397 | cleanup(); |
| 377 | const auto free_memory = fn<PFN_vkFreeMemory>("vkFreeMemory"); | ||
| 378 | if (area.buffer && destroy_buffer) destroy_buffer(device_, area.buffer, nullptr); | ||
| 379 | if (area.memory && free_memory) free_memory(device_, area.memory, nullptr); | ||
| 380 | return false; | 398 | return false; |
| 381 | } | 399 | } |
| 382 | std::memset(area.host, 0, size_t(info.size)); | 400 | std::memset(area.host, 0, size_t(info.size)); |
| 383 | for (std::uint32_t i = 0; i < area.slots; ++i) free_slots_.push_back({std::uint32_t(areas_.size()), i}); | 401 | try { |
| 402 | free_slots_.reserve(free_slots_.size() + area.slots); | ||
| 403 | areas_.reserve(areas_.size() + 1); | ||
| 404 | } catch (...) { | ||
| 405 | cleanup(); | ||
| 406 | throw; | ||
| 407 | } | ||
| 408 | const auto area_index = std::uint32_t(areas_.size()); | ||
| 409 | for (std::uint32_t i = 0; i < area.slots; ++i) free_slots_.push_back({area_index, i}); | ||
| 384 | areas_.push_back(area); | 410 | areas_.push_back(area); |
| 385 | return true; | 411 | return true; |
| 386 | } | 412 | } |
| @@ -408,12 +434,15 @@ inline void IndirectArgumentClamp::release(std::vector<Slot>& slots, bool read) | |||
| 408 | for (const Slot& slot : slots) { | 434 | for (const Slot& slot : slots) { |
| 409 | if (read && slot.area < areas_.size() && slot.index < areas_[slot.area].slots) { | 435 | if (read && slot.area < areas_.size() && slot.index < areas_[slot.area].slots) { |
| 410 | const HostArea& area = areas_[slot.area]; | 436 | const HostArea& area = areas_[slot.area]; |
| 411 | const std::uint32_t* words = | 437 | auto* words = |
| 412 | reinterpret_cast<const std::uint32_t*>(area.host + std::size_t(slot.index) * HostArea::slot_bytes); | 438 | reinterpret_cast<std::uint32_t*>(area.host + std::size_t(slot.index) * HostArea::slot_bytes); |
| 413 | delta.records_clamped += words[0]; | 439 | delta.records_clamped += words[0]; |
| 414 | delta.counts_clamped += words[1]; | 440 | delta.counts_clamped += words[1]; |
| 415 | delta.over_budget += words[2]; | 441 | delta.over_budget += words[2]; |
| 416 | delta.zeroed += words[3]; | 442 | delta.zeroed += words[3]; |
| 443 | // Clear after reading so a later aborted batch that reuses this slot without submitting never | ||
| 444 | // double-counts a previous submission's counters. | ||
| 445 | std::memset(words, 0, 4 * sizeof(std::uint32_t)); | ||
| 417 | } | 446 | } |
| 418 | free_slots_.push_back(slot); | 447 | free_slots_.push_back(slot); |
| 419 | } | 448 | } |
| @@ -461,8 +490,9 @@ inline bool IndirectArgumentClamp::prepare(VkBuffer arguments, VkDeviceSize argu | |||
| 461 | std::uint32_t max_count, Slot slot, ClampedIndirect& out) { | 490 | std::uint32_t max_count, Slot slot, ClampedIndirect& out) { |
| 462 | out = {}; | 491 | out = {}; |
| 463 | const std::uint32_t record_size = indirect_clamp_record_size(kind); | 492 | const std::uint32_t record_size = indirect_clamp_record_size(kind); |
| 464 | if (kind > indirect_clamp_mesh || !arguments || !max_count || stride < record_size || stride % 4) { | 493 | if (kind > indirect_clamp_mesh || !arguments || !max_count || stride < record_size || stride % 4 || |
| 465 | fallback("an argument stride this pass does not handle"); | 494 | (argument_offset % 4) != 0 || (count && (count_offset % 4) != 0)) { |
| 495 | fallback("an argument stride or offset this pass does not handle"); | ||
| 466 | return false; | 496 | return false; |
| 467 | } | 497 | } |
| 468 | const VkDeviceSize records_bytes = VkDeviceSize(max_count) * record_size; | 498 | const VkDeviceSize records_bytes = VkDeviceSize(max_count) * record_size; |
| @@ -514,10 +544,10 @@ inline bool IndirectArgumentClamp::prepare(VkBuffer arguments, VkDeviceSize argu | |||
| 514 | out.stats = address + stats_scratch; | 544 | out.stats = address + stats_scratch; |
| 515 | out.list_budget = out.stats + 4 * sizeof(std::uint32_t); | 545 | out.list_budget = out.stats + 4 * sizeof(std::uint32_t); |
| 516 | out.stats_scratch_offset = offset + stats_scratch; | 546 | out.stats_scratch_offset = offset + stats_scratch; |
| 517 | out.stats_buffer = slot.area == no_slot ? VK_NULL_HANDLE : areas_[slot.area].buffer; // no_slot: no copy-back | ||
| 518 | out.stats_offset = slot.area == no_slot ? 0 : VkDeviceSize(slot.index) * HostArea::slot_bytes; | 547 | out.stats_offset = slot.area == no_slot ? 0 : VkDeviceSize(slot.index) * HostArea::slot_bytes; |
| 519 | { | 548 | { |
| 520 | std::lock_guard lock(mutex_); | 549 | std::lock_guard lock(mutex_); |
| 550 | out.stats_buffer = slot.area == no_slot ? VK_NULL_HANDLE : areas_[slot.area].buffer; // no_slot: no copy-back | ||
| 521 | ++counters_.calls; | 551 | ++counters_.calls; |
| 522 | counters_.records += max_count; | 552 | counters_.records += max_count; |
| 523 | } | 553 | } |
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 08d4a7caa..d84f26ccf 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h | |||
| @@ -60,6 +60,7 @@ | |||
| 60 | #include <limits> | 60 | #include <limits> |
| 61 | #include <map> | 61 | #include <map> |
| 62 | #include <memory> | 62 | #include <memory> |
| 63 | #include <mutex> | ||
| 63 | #include <optional> | 64 | #include <optional> |
| 64 | #include <type_traits> | 65 | #include <type_traits> |
| 65 | #include <unordered_map> | 66 | #include <unordered_map> |
| @@ -548,6 +549,27 @@ inline bool a8_mixed_backing(VkFormat a, VkFormat b) { | |||
| 548 | #endif | 549 | #endif |
| 549 | } | 550 | } |
| 550 | 551 | ||
| 552 | // Two depth formats whose depth aspect has the same encoding but which are not the same VkFormat: D32_SFLOAT and | ||
| 553 | // D32_SFLOAT_S8_UINT, D16_UNORM and D16_UNORM_S8_UINT, X8_D24_UNORM_PACK32 and D24_UNORM_S8_UINT. D3D12 copies the | ||
| 554 | // depth plane between them; Vulkan's vkCmdCopyImage requires depth/stencil formats to match exactly | ||
| 555 | // (VUID-vkCmdCopyImage-srcImage-01548), and an NVIDIA driver handed D32_SFLOAT_S8_UINT -> D32_SFLOAT writes past the | ||
| 556 | // end of the D32 image (the world-start WRITE_INVALID). The replay stages these through a buffer, where the depth | ||
| 557 | // aspect has the same texel layout on both sides. | ||
| 558 | inline bool depth_format_pair(VkFormat a, VkFormat b) { | ||
| 559 | const auto encoding = [](VkFormat format) -> int { | ||
| 560 | switch (format) { | ||
| 561 | case VK_FORMAT_D32_SFLOAT: | ||
| 562 | case VK_FORMAT_D32_SFLOAT_S8_UINT: return 32; | ||
| 563 | case VK_FORMAT_X8_D24_UNORM_PACK32: | ||
| 564 | case VK_FORMAT_D24_UNORM_S8_UINT: return 24; | ||
| 565 | case VK_FORMAT_D16_UNORM: | ||
| 566 | case VK_FORMAT_D16_UNORM_S8_UINT: return 16; | ||
| 567 | default: return 0; | ||
| 568 | } | ||
| 569 | }; | ||
| 570 | return a != b && encoding(a) && encoding(a) == encoding(b); | ||
| 571 | } | ||
| 572 | |||
| 551 | inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) { | 573 | inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) { |
| 552 | const auto family = [](VkFormat format) -> int { | 574 | const auto family = [](VkFormat format) -> int { |
| 553 | switch (format) { | 575 | switch (format) { |
| @@ -852,8 +874,9 @@ struct ComputePipeline { | |||
| 852 | // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a | 874 | // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a |
| 853 | // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles. | 875 | // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles. |
| 854 | VkPipeline (*built)(void*) = nullptr; | 876 | VkPipeline (*built)(void*) = nullptr; |
| 855 | bool large = false; // compiled one after another with the other large ones (PipelineCompiles) | 877 | bool large = false; // PipelineCompiles limits how many of these compile at once |
| 856 | bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped | 878 | bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped |
| 879 | std::uint64_t estimate = 0; // large: the bytes of memory its compile is expected to take | ||
| 857 | }; | 880 | }; |
| 858 | 881 | ||
| 859 | // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it | 882 | // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it |
| @@ -887,6 +910,7 @@ struct GraphicsPipeline { | |||
| 887 | std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count | 910 | std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count |
| 888 | bool async_build = false; | 911 | bool async_build = false; |
| 889 | bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation | 912 | bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation |
| 913 | std::uint64_t estimate = 0; // as ComputePipeline::estimate | ||
| 890 | }; | 914 | }; |
| 891 | 915 | ||
| 892 | // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. | 916 | // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. |
| @@ -972,7 +996,7 @@ inline ReplayResult unsupported_at(int line) { | |||
| 972 | 996 | ||
| 973 | // The pipelines of a submission that are not built yet. prepare() adds each of them once and goes on; build_pipelines() | 997 | // The pipelines of a submission that are not built yet. prepare() adds each of them once and goes on; build_pipelines() |
| 974 | // then compiles them all and puts them where prepare() left them out. Holds pointers to registered pipelines: valid | 998 | // then compiles them all and puts them where prepare() left them out. Holds pointers to registered pipelines: valid |
| 975 | // while the context's resource lock is held. | 999 | // while the context's pipeline lock is held. |
| 976 | class PipelineCompiles { | 1000 | class PipelineCompiles { |
| 977 | public: | 1001 | public: |
| 978 | // Where a prepared command finds its pipeline: an index for `built`, plus one; 0 when it needs none. | 1002 | // Where a prepared command finds its pipeline: an index for `built`, plus one; 0 when it needs none. |
| @@ -984,7 +1008,7 @@ public: | |||
| 984 | User user; | 1008 | User user; |
| 985 | }; | 1009 | }; |
| 986 | // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics | 1010 | // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics |
| 987 | // pipelines of this much or more are `large`. | 1011 | // pipelines of this much or more are `large`. For compute pipelines the D3D12 layer decides. |
| 988 | static constexpr std::uint64_t large_spirv_bytes = 1u << 20; | 1012 | static constexpr std::uint64_t large_spirv_bytes = 1u << 20; |
| 989 | 1013 | ||
| 990 | Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) { | 1014 | Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) { |
| @@ -993,29 +1017,111 @@ public: | |||
| 993 | Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); } | 1017 | Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); } |
| 994 | 1018 | ||
| 995 | bool empty() const { return jobs_.empty(); } | 1019 | bool empty() const { return jobs_.empty(); } |
| 1020 | bool any_large() const { | ||
| 1021 | return std::any_of(jobs_.begin(), jobs_.end(), [](const Job& job) { return is_large(job); }); | ||
| 1022 | } | ||
| 996 | std::size_t size() const { return jobs_.size(); } | 1023 | std::size_t size() const { return jobs_.size(); } |
| 997 | VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; } | 1024 | VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; } |
| 998 | const std::vector<Use>& uses() const { return uses_; } // in the order of the commands | 1025 | const std::vector<Use>& uses() const { return uses_; } // in the order of the commands |
| 999 | 1026 | ||
| 1000 | // Compiles all of them through run(count, job) (PipelineWorkers::run): the large ones one after another, as without | 1027 | // Whether this batch already attempted (pipeline, flags); writes its outcome (built handle or VK_NULL_HANDLE) to `out`. |
| 1001 | // workers, beside the others. | 1028 | bool lookup(const GraphicsPipeline* graphics, const ComputePipeline* compute, std::uint32_t flags, |
| 1029 | VkPipeline& out) const { | ||
| 1030 | const void* const pipeline = graphics ? static_cast<const void*>(graphics) : compute; | ||
| 1031 | const auto it = tickets_.find({pipeline, flags}); | ||
| 1032 | if (it == tickets_.end()) return false; | ||
| 1033 | out = jobs_[it->second - 1].built; | ||
| 1034 | return true; | ||
| 1035 | } | ||
| 1036 | |||
| 1037 | // Whether this batch already attempted the job named by `other`'s `ticket`. | ||
| 1038 | bool contains_ticket(const PipelineCompiles& other, Ticket ticket) const { | ||
| 1039 | VkPipeline unused = VK_NULL_HANDLE; | ||
| 1040 | const Job& job = other.jobs_[ticket - 1]; | ||
| 1041 | return lookup(job.graphics, job.compute, job.flags, unused); | ||
| 1042 | } | ||
| 1043 | |||
| 1044 | // Compiles all of them through run(count, job) (PipelineWorkers::run). The large ones share budget() bytes of memory: | ||
| 1045 | // the largest first, as many at once as their estimates fit, one at least; while the next one does not fit, the | ||
| 1046 | // others are compiled first. No budget, or 0: the large ones one after another, as without workers, beside the others. | ||
| 1002 | template<typename Run> | 1047 | template<typename Run> |
| 1003 | void build(Run&& run) { | 1048 | void build(Run&& run, const std::function<std::uint64_t()>& read_budget = {}, |
| 1049 | const PipelineCompiles* prior = nullptr) { | ||
| 1004 | std::vector<std::size_t> single, large; | 1050 | std::vector<std::size_t> single, large; |
| 1005 | for (std::size_t i = 0; i < jobs_.size(); ++i) (is_large(jobs_[i]) ? large : single).push_back(i); | 1051 | for (std::size_t i = 0; i < jobs_.size(); ++i) { |
| 1052 | if (prior && prior->lookup(jobs_[i].graphics, jobs_[i].compute, jobs_[i].flags, jobs_[i].built)) continue; | ||
| 1053 | (is_large(jobs_[i]) ? large : single).push_back(i); | ||
| 1054 | } | ||
| 1055 | if (single.empty() && large.empty()) return; | ||
| 1056 | // The first jobs of the run are lanes, which take large ones until none is left: no more of them than there are | ||
| 1057 | // large ones that fit the budget together (the smallest), so that no thread waits here for room in vain. | ||
| 1058 | std::size_t lanes = large.empty() ? 0 : 1; | ||
| 1059 | const std::uint64_t budget = lanes && read_budget ? read_budget() : 0; | ||
| 1060 | if (budget) { | ||
| 1061 | std::stable_sort(large.begin(), large.end(), [this](std::size_t a, std::size_t b) { | ||
| 1062 | return estimate(jobs_[a]) > estimate(jobs_[b]); | ||
| 1063 | }); | ||
| 1064 | std::uint64_t sum = estimate(jobs_[large.back()]); | ||
| 1065 | while (lanes < large.size() && (sum += estimate(jobs_[large[large.size() - 1 - lanes]])) <= budget) ++lanes; | ||
| 1066 | } | ||
| 1006 | const auto compile = [this](std::size_t i) { | 1067 | const auto compile = [this](std::size_t i) { |
| 1007 | Job& job = jobs_[i]; | 1068 | Job& job = jobs_[i]; |
| 1008 | job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); | 1069 | job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); |
| 1009 | }; | 1070 | }; |
| 1010 | const std::size_t chain = large.empty() ? 0 : 1; // the large ones are one unit, the first | 1071 | std::mutex mutex; // guards the four below |
| 1011 | run(chain + single.size(), [&](std::size_t i) { | 1072 | std::size_t next_single = 0, next_large = 0, compiling = 0; |
| 1012 | if (i >= chain) | 1073 | std::uint64_t reserved = 0; // the estimates of the large ones compiling |
| 1013 | compile(single[i - chain]); | 1074 | run(lanes + single.size(), [&](std::size_t i) { |
| 1014 | else | 1075 | std::unique_lock lock(mutex); |
| 1015 | for (const std::size_t each : large) compile(each); | 1076 | if (i >= lanes) { |
| 1077 | if (next_single == single.size()) return; // a lane has taken it | ||
| 1078 | const std::size_t index = single[next_single++]; | ||
| 1079 | lock.unlock(); | ||
| 1080 | compile(index); | ||
| 1081 | return; | ||
| 1082 | } | ||
| 1083 | while (next_large < large.size()) { | ||
| 1084 | const std::uint64_t need = estimate(jobs_[large[next_large]]); | ||
| 1085 | const bool fits = !compiling || reserved + need <= budget; | ||
| 1086 | if (!fits && next_single < single.size()) { | ||
| 1087 | const std::size_t index = single[next_single++]; | ||
| 1088 | lock.unlock(); | ||
| 1089 | compile(index); | ||
| 1090 | lock.lock(); | ||
| 1091 | continue; | ||
| 1092 | } | ||
| 1093 | const std::size_t index = large[next_large++]; | ||
| 1094 | ++compiling; | ||
| 1095 | reserved += need; | ||
| 1096 | lock.unlock(); | ||
| 1097 | compile(index); | ||
| 1098 | lock.lock(); | ||
| 1099 | --compiling; | ||
| 1100 | reserved -= need; | ||
| 1101 | } | ||
| 1016 | }); | 1102 | }); |
| 1017 | } | 1103 | } |
| 1018 | 1104 | ||
| 1105 | // Compiles jobs serially in command order without workers, stopping at the first fatal refusal (a failed draw, a | ||
| 1106 | // failed indirect dispatch, or any failed dispatch under strict_replay()). Matches serial prepare() short-circuit | ||
| 1107 | // semantics while allowing the caller to compile outside resource_mutex_. | ||
| 1108 | void build_serial(const PipelineCompiles* prior = nullptr) { | ||
| 1109 | std::vector<bool> done(jobs_.size(), false); | ||
| 1110 | for (const Use& use : uses_) { | ||
| 1111 | const std::size_t i = use.ticket - 1; | ||
| 1112 | if (!done[i]) { | ||
| 1113 | done[i] = true; | ||
| 1114 | Job& job = jobs_[i]; | ||
| 1115 | if (!prior || !prior->lookup(job.graphics, job.compute, job.flags, job.built)) { | ||
| 1116 | job.built = | ||
| 1117 | job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); | ||
| 1118 | } | ||
| 1119 | } | ||
| 1120 | if (!jobs_[i].built && (use.user == User::draw || use.user == User::indirect_dispatch || strict_replay())) | ||
| 1121 | return; | ||
| 1122 | } | ||
| 1123 | } | ||
| 1124 | |||
| 1019 | private: | 1125 | private: |
| 1020 | struct Job { | 1126 | struct Job { |
| 1021 | const GraphicsPipeline* graphics; // one of the two | 1127 | const GraphicsPipeline* graphics; // one of the two |
| @@ -1024,6 +1130,9 @@ private: | |||
| 1024 | VkPipeline built = VK_NULL_HANDLE; | 1130 | VkPipeline built = VK_NULL_HANDLE; |
| 1025 | }; | 1131 | }; |
| 1026 | static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; } | 1132 | static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; } |
| 1133 | static std::uint64_t estimate(const Job& job) { | ||
| 1134 | return job.graphics ? job.graphics->estimate : job.compute->estimate; | ||
| 1135 | } | ||
| 1027 | Ticket add(const Job& job, User user) { | 1136 | Ticket add(const Job& job, User user) { |
| 1028 | const void* const pipeline = job.graphics ? static_cast<const void*>(job.graphics) : job.compute; | 1137 | const void* const pipeline = job.graphics ? static_cast<const void*>(job.graphics) : job.compute; |
| 1029 | const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1)); | 1138 | const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1)); |
| @@ -1315,7 +1424,7 @@ struct Prepared { | |||
| 1315 | // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination. | 1424 | // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination. |
| 1316 | VkBuffer staged = VK_NULL_HANDLE; | 1425 | VkBuffer staged = VK_NULL_HANDLE; |
| 1317 | std::vector<VkBufferImageCopy> staged_reads, staged_writes; | 1426 | std::vector<VkBufferImageCopy> staged_reads, staged_writes; |
| 1318 | VkDeviceSize clear_pattern_bytes = 0; // rectangular UAV clear on a compute-only queue | 1427 | VkDeviceSize clear_pattern_bytes = 0; // staged transfer UAV clear (compute-only rects or sliced/rect 3D) |
| 1319 | std::vector<VkImageSubresourceRange> discards; // DiscardResource: the subresources to discard | 1428 | std::vector<VkImageSubresourceRange> discards; // DiscardResource: the subresources to discard |
| 1320 | VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands | 1429 | VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands |
| 1321 | VkDeviceSize write_offset = 0; | 1430 | VkDeviceSize write_offset = 0; |
| @@ -1600,6 +1709,13 @@ inline VkExtent2D mip_extent(const ResourceBinding& resource, std::uint32_t mip) | |||
| 1600 | return {std::max(1u, resource.width >> mip), std::max(1u, resource.height >> mip)}; | 1709 | return {std::max(1u, resource.width >> mip), std::max(1u, resource.height >> mip)}; |
| 1601 | } | 1710 | } |
| 1602 | 1711 | ||
| 1712 | // Nonempty, clipped rectangle. The entire constant pattern fits in one vkCmdUpdateBuffer for wide texels. | ||
| 1713 | inline VkExtent2D volume_clear_tile(VkExtent2D rect, std::uint32_t texel_bytes) { | ||
| 1714 | const std::uint32_t max_texels = 65536 / texel_bytes; | ||
| 1715 | const auto width = std::min(rect.width, max_texels); | ||
| 1716 | return {width, std::min(rect.height, max_texels / width)}; | ||
| 1717 | } | ||
| 1718 | |||
| 1603 | // Into `out`, replacing what it held: a kept PreparedList entry reuses the vector's storage. | 1719 | // Into `out`, replacing what it held: a kept PreparedList entry reuses the vector's storage. |
| 1604 | inline void clip(std::span<const Rect> rects, VkExtent2D extent, std::uint32_t layers, std::vector<VkClearRect>& out) { | 1720 | inline void clip(std::span<const Rect> rects, VkExtent2D extent, std::uint32_t layers, std::vector<VkClearRect>& out) { |
| 1605 | out.clear(); | 1721 | out.clear(); |
| @@ -2201,7 +2317,9 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 2201 | return ReplayResult::invalid_copy; | 2317 | return ReplayResult::invalid_copy; |
| 2202 | if (buffer.size > UINT64_MAX - buffer.buffer_offset) return ReplayResult::invalid_copy; | 2318 | if (buffer.size > UINT64_MAX - buffer.buffer_offset) return ReplayResult::invalid_copy; |
| 2203 | const VkDeviceSize backing_offset = buffer.buffer_offset + offset; | 2319 | const VkDeviceSize backing_offset = buffer.buffer_offset + offset; |
| 2204 | if (backing_offset % alignment && !copy.tile_footprint) return unsupported_at(__LINE__); | 2320 | // A host-import prefix may be word aligned without being texel aligned (e.g. +4 for RGBA16). |
| 2321 | // The replay stages those copies through aligned scratch; VkBufferCopy still needs word alignment. | ||
| 2322 | if (backing_offset % alignment && backing_offset % 4 && !copy.tile_footprint) return unsupported_at(__LINE__); | ||
| 2205 | VkBufferImageCopy region{}; | 2323 | VkBufferImageCopy region{}; |
| 2206 | region.bufferOffset = backing_offset; | 2324 | region.bufferOffset = backing_offset; |
| 2207 | region.bufferRowLength = placed.row_pitch / format.bytes * format.block; | 2325 | region.bufferRowLength = placed.row_pitch / format.bytes * format.block; |
| @@ -2221,13 +2339,13 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 2221 | return ReplayResult::success; | 2339 | return ReplayResult::success; |
| 2222 | } | 2340 | } |
| 2223 | 2341 | ||
| 2224 | // CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel/block | 2342 | // CopyTiles byte offsets and word-aligned imported host prefixes may violate VkBufferImageCopy texel/block |
| 2225 | // alignment (VUID-vkCmdCopyBufferToImage-dstImage-07975). Stage only the occupied texels/blocks through aligned | 2343 | // alignment (VUID-vkCmdCopyBufferToImage-dstImage-07975). Stage only the occupied texels/blocks through aligned |
| 2226 | // transfer scratch; leave partial-tile padding alone. | 2344 | // transfer scratch; leave partial-tile padding alone. |
| 2227 | inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, const ResourceBinding& image, | 2345 | inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, const ResourceBinding& image, |
| 2228 | const BlockFormat& fmt, bool upload) { | 2346 | const BlockFormat& fmt, bool upload) { |
| 2229 | auto& region = p.buffer_image_copies.front(); | 2347 | auto& region = p.buffer_image_copies.front(); |
| 2230 | if (!fmt.bytes || !fmt.block || image.rgb96 || | 2348 | if (!vk.copy_buffer || !fmt.bytes || !fmt.block || image.rgb96 || |
| 2231 | (image.depth24_as_float && region.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT)) | 2349 | (image.depth24_as_float && region.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT)) |
| 2232 | return false; | 2350 | return false; |
| 2233 | const VkDeviceSize blocks_w = (VkDeviceSize(region.imageExtent.width) + fmt.block - 1) / fmt.block; | 2351 | const VkDeviceSize blocks_w = (VkDeviceSize(region.imageExtent.width) + fmt.block - 1) / fmt.block; |
| @@ -2558,7 +2676,9 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R | |||
| 2558 | return ReplayResult::success; | 2676 | return ReplayResult::success; |
| 2559 | }; | 2677 | }; |
| 2560 | if (draw.mesh) return skip(indirect_stats::mesh); | 2678 | if (draw.mesh) return skip(indirect_stats::mesh); |
| 2561 | if (draw.topology != 4) return skip(indirect_stats::topology); | 2679 | static_assert(indirect_stats::topology_supported(topology_rect_list) && |
| 2680 | !indirect_stats::topology_supported(topology_quad_list)); | ||
| 2681 | if (!indirect_stats::topology_supported(draw.topology)) return skip(indirect_stats::topology); | ||
| 2562 | if (!vk.draw_indirect_first_instance) return skip(indirect_stats::first_instance); | 2682 | if (!vk.draw_indirect_first_instance) return skip(indirect_stats::first_instance); |
| 2563 | if (!entry_available) return skip(indirect_stats::entry); | 2683 | if (!entry_available) return skip(indirect_stats::entry); |
| 2564 | if (draw.indexed && !vk.bind_robust_index_view) return skip(indirect_stats::robust_index); | 2684 | if (draw.indexed && !vk.bind_robust_index_view) return skip(indirect_stats::robust_index); |
| @@ -2674,7 +2794,8 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R | |||
| 2674 | if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; | 2794 | if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; |
| 2675 | if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; | 2795 | if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; |
| 2676 | if (unbound || !p.pipeline) { | 2796 | if (unbound || !p.pipeline) { |
| 2677 | if (vk.compiles && pipeline->variant && pipeline->built && !pipeline->async_build) { | 2797 | const bool indirect_rect_variant = arguments && (unbound & GraphicsPipeline::rectangle_stage); |
| 2798 | if (vk.compiles && pipeline->variant && pipeline->built && !pipeline->async_build && !indirect_rect_variant) { | ||
| 2678 | p.pipeline = pipeline->built(unbound); | 2799 | p.pipeline = pipeline->built(unbound); |
| 2679 | if (!p.pipeline) p.compile = vk.compiles->add(*pipeline, unbound); | 2800 | if (!p.pipeline) p.compile = vk.compiles->add(*pipeline, unbound); |
| 2680 | } else { | 2801 | } else { |
| @@ -2684,6 +2805,11 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R | |||
| 2684 | p.skipped = true; | 2805 | p.skipped = true; |
| 2685 | return ReplayResult::success; | 2806 | return ReplayResult::success; |
| 2686 | } | 2807 | } |
| 2808 | if (!p.pipeline && !pipeline->async_build && indirect_rect_variant) { | ||
| 2809 | indirect_stats::skip(indirect_stats::Event::replay_skip, indirect_stats::topology); | ||
| 2810 | p.skipped = true; | ||
| 2811 | return ReplayResult::success; | ||
| 2812 | } | ||
| 2687 | if (!p.pipeline) return unsupported_at(__LINE__); | 2813 | if (!p.pipeline) return unsupported_at(__LINE__); |
| 2688 | } | 2814 | } |
| 2689 | } | 2815 | } |
| @@ -2911,30 +3037,51 @@ public: | |||
| 2911 | std::vector<detail::PreparedKhrPostbuild> khr_postbuilds; | 3037 | std::vector<detail::PreparedKhrPostbuild> khr_postbuilds; |
| 2912 | }; | 3038 | }; |
| 2913 | 3039 | ||
| 2914 | // Ends the preparation of a submission whose prepare() calls used `compiles` and returned `result` (the first that | 3040 | // Checks the outcomes of a compiled PipelineCompiles batch against `result` (the first prepare() failure, if any). |
| 2915 | // failed, if any): builds the pipelines through run(count, job), puts them into `lists`, and returns what the calls would | 3041 | // Every use in `compiles` comes from a command before the one that failed, so a pipeline that cannot be built counts |
| 2916 | // have returned had they built each pipeline themselves. Every use in `compiles` comes from a command before the one that | 3042 | // first, at the earliest command that uses it: it fails the list of a draw or an indirect dispatch, and a dispatch is |
| 2917 | // failed, so a pipeline that cannot be built counts first, at the earliest command that uses it: it fails the list of a | 3043 | // dropped as prepare() drops one. Non-strict failed dispatches already logged in `prior` are not logged twice. |
| 2918 | // draw or an indirect dispatch, and a dispatch is dropped as prepare() drops one. | 3044 | inline ReplayResult check_compiled_pipelines(const PipelineCompiles& compiles, ReplayResult result, |
| 2919 | template<typename Run> | 3045 | const PipelineCompiles* prior = nullptr) { |
| 2920 | ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result, | ||
| 2921 | Run&& run) { | ||
| 2922 | if (compiles.empty()) return result; | ||
| 2923 | compiles.build(run); | ||
| 2924 | for (const PipelineCompiles::Use& use : compiles.uses()) { | 3046 | for (const PipelineCompiles::Use& use : compiles.uses()) { |
| 2925 | if (compiles.built(use.ticket)) continue; | 3047 | if (compiles.built(use.ticket)) continue; |
| 2926 | if (use.user == PipelineCompiles::User::draw) return unsupported_at(__LINE__); | 3048 | if (use.user == PipelineCompiles::User::draw) return unsupported_at(__LINE__); |
| 2927 | if (use.user == PipelineCompiles::User::indirect_dispatch || strict_replay()) return unresolved_at(__LINE__); | 3049 | if (use.user == PipelineCompiles::User::indirect_dispatch || strict_replay()) return unresolved_at(__LINE__); |
| 2928 | unresolved_at(__LINE__); | 3050 | if (!prior || !prior->contains_ticket(compiles, use.ticket)) unresolved_at(__LINE__); |
| 2929 | } | 3051 | } |
| 2930 | if (result != ReplayResult::success) return result; | 3052 | return result; |
| 3053 | } | ||
| 3054 | |||
| 3055 | inline ReplayResult finish_compiled_pipelines(const PipelineCompiles& compiles, std::span<PreparedList> lists, | ||
| 3056 | ReplayResult result, const PipelineCompiles* prior = nullptr) { | ||
| 3057 | const ReplayResult checked = check_compiled_pipelines(compiles, result, prior); | ||
| 3058 | if (checked != ReplayResult::success) return checked; | ||
| 2931 | for (PreparedList& list : lists) { | 3059 | for (PreparedList& list : lists) { |
| 2932 | for (detail::Prepared& command : list.commands) | 3060 | for (detail::Prepared& command : list.commands) |
| 2933 | if (command.compile) command.pipeline.pipeline = compiles.built(command.compile); | 3061 | if (command.compile) command.pipeline.pipeline = compiles.built(command.compile); |
| 2934 | for (std::size_t i = 0; i < list.draw_count; ++i) | 3062 | for (std::size_t i = 0; i < list.draw_count; ++i) |
| 2935 | if (list.draws[i].compile) list.draws[i].pipeline = compiles.built(list.draws[i].compile); | 3063 | if (list.draws[i].compile) list.draws[i].pipeline = compiles.built(list.draws[i].compile); |
| 2936 | } | 3064 | } |
| 2937 | return result; | 3065 | return checked; |
| 3066 | } | ||
| 3067 | |||
| 3068 | // Ends the preparation of a submission whose prepare() calls used `compiles` and returned `result` (the first that | ||
| 3069 | // failed, if any): builds the pipelines through run(count, job), puts them into `lists`, and returns what the calls would | ||
| 3070 | // have returned had they built each pipeline themselves. | ||
| 3071 | template<typename Run> | ||
| 3072 | ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result, | ||
| 3073 | Run&& run, const std::function<std::uint64_t()>& budget = {}, | ||
| 3074 | const PipelineCompiles* prior = nullptr) { | ||
| 3075 | if (compiles.empty()) return result; | ||
| 3076 | compiles.build(run, budget, prior); | ||
| 3077 | return finish_compiled_pipelines(compiles, lists, result, prior); | ||
| 3078 | } | ||
| 3079 | |||
| 3080 | inline ReplayResult build_pipelines_serial(PipelineCompiles& compiles, std::span<PreparedList> lists, | ||
| 3081 | ReplayResult result, const PipelineCompiles* prior = nullptr) { | ||
| 3082 | if (compiles.empty()) return result; | ||
| 3083 | compiles.build_serial(prior); | ||
| 3084 | return finish_compiled_pipelines(compiles, lists, result, prior); | ||
| 2938 | } | 3085 | } |
| 2939 | 3086 | ||
| 2940 | inline ReplayResult plan_occlusion_segments(PreparedList& out) { | 3087 | inline ReplayResult plan_occlusion_segments(PreparedList& out) { |
| @@ -3076,8 +3223,8 @@ inline void plan_statistics_segments(PreparedList& out) { | |||
| 3076 | } | 3223 | } |
| 3077 | 3224 | ||
| 3078 | // Overlapping pipeline-statistics queries (D3D-252): the same physical-segment layout the occlusion planner | 3225 | // Overlapping pipeline-statistics queries (D3D-252): the same physical-segment layout the occlusion planner |
| 3079 | // builds, in the statistics pool. Each Begin and End of a statistics query â€� and every non-timestamp resolve | 3226 | // builds, in the statistics pool. Each Begin and End of a statistics query — and every non-timestamp resolve |
| 3080 | // while one runs, because its helper dispatch would be counted â€� closes the one open physical query and opens | 3227 | // while one runs, because its helper dispatch would be counted — closes the one open physical query and opens |
| 3081 | // a new one, so each logical query keeps a contiguous slot range and its result is the sum of that range | 3228 | // a new one, so each logical query keeps a contiguous slot range and its result is the sum of that range |
| 3082 | // (statistics_sum.comp). A Begin or End of another query kind leaves the segments alone. | 3229 | // (statistics_sum.comp). A Begin or End of another query kind leaves the segments alone. |
| 3083 | inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) { | 3230 | inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) { |
| @@ -3468,36 +3615,46 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3468 | : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; | 3615 | : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; |
| 3469 | const bool reinterpret = view_format != p.binding.format && attachment && view_attachable && !packed_rgb9e5; | 3616 | const bool reinterpret = view_format != p.binding.format && attachment && view_attachable && !packed_rgb9e5; |
| 3470 | if (view.exact_clear_format && view_format != p.binding.format && !packed_rgb9e5) | 3617 | if (view.exact_clear_format && view_format != p.binding.format && !packed_rgb9e5) |
| 3471 | return ReplayResult::unsupported; | 3618 | return unsupported_at(__LINE__); |
| 3472 | const VkFormat clear_format = reinterpret ? view_format : p.binding.format; | 3619 | const VkFormat clear_format = reinterpret ? view_format : p.binding.format; |
| 3473 | if (!uav_clear::decode(clear_format, p.element, p.clear_color)) | 3620 | if (!uav_clear::decode(clear_format, p.element, p.clear_color)) |
| 3474 | return unsupported_at(__LINE__); | 3621 | return unsupported_at(__LINE__); |
| 3475 | if (reinterpret) p.clear_format = view_format; | 3622 | if (reinterpret) p.clear_format = view_format; |
| 3476 | // Compute list barriers have no attachment stages, and a dedicated compute queue cannot render. | 3623 | // A 3D transfer clear covers a whole mip and a compute-only queue cannot render rectangles. |
| 3477 | // Copy the encoded texel bits from a filled buffer. Transfers cannot implement a predicated clear. | 3624 | // Copy the encoded texel bits instead. These copies cannot implement a predicated clear. |
| 3478 | if ((vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && | 3625 | const bool sliced = p.binding.volume && view.layer_count != std::max(1u, p.binding.depth >> view.mip); |
| 3479 | (!uav->rects.empty() || reinterpret || predicated)) { | 3626 | const bool stage_volume = p.binding.volume && (sliced || !uav->rects.empty()); |
| 3480 | if (predicated || p.binding.volume || !vk.copy_scratch || !vk.fill_buffer || !vk.copy_buffer_to_image || | 3627 | const bool stage_compute = (vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && |
| 3481 | (p.element.size != 1 && p.element.size != 2 && p.element.size != 4)) | 3628 | (!uav->rects.empty() || reinterpret || predicated); |
| 3482 | return ReplayResult::unsupported; | 3629 | if (stage_volume || stage_compute) { |
| 3630 | if (predicated) return unsupported_at(__LINE__); | ||
| 3631 | if (stage_volume && view_format != p.binding.format && !packed_rgb9e5) | ||
| 3632 | return unsupported_at(__LINE__); | ||
| 3633 | if (!vk.copy_scratch || !vk.copy_buffer_to_image || | ||
| 3634 | (p.element.size <= 4 ? !vk.fill_buffer : (!stage_volume || !vk.update_buffer))) | ||
| 3635 | return unsupported_at(__LINE__); | ||
| 3483 | const auto rects = uav->rects.empty() ? std::span<const Rect>(&whole_view, 1) : | 3636 | const auto rects = uav->rects.empty() ? std::span<const Rect>(&whole_view, 1) : |
| 3484 | std::span<const Rect>(uav->rects); | 3637 | std::span<const Rect>(uav->rects); |
| 3485 | detail::clip(rects, detail::mip_extent(p.binding, view.mip), view.layer_count, p.rects); | 3638 | detail::clip(rects, detail::mip_extent(p.binding, view.mip), p.range.layerCount, p.rects); |
| 3486 | if (p.rects.empty()) { p.skip = true; continue; } | 3639 | if (p.rects.empty()) { p.skip = true; continue; } |
| 3487 | for (const auto& rect : p.rects) { | 3640 | for (const auto& rect : p.rects) { |
| 3488 | VkBufferImageCopy region{}; | 3641 | VkBufferImageCopy region{}; |
| 3489 | region.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, view.mip, view.first_layer, view.layer_count}; | 3642 | region.imageSubresource = {p.range.aspectMask, view.mip, p.range.baseArrayLayer, p.range.layerCount}; |
| 3490 | region.imageOffset = {rect.rect.offset.x, rect.rect.offset.y, 0}; | 3643 | region.imageOffset = {rect.rect.offset.x, rect.rect.offset.y, 0}; |
| 3491 | region.imageExtent = {rect.rect.extent.width, rect.rect.extent.height, 1}; | 3644 | region.imageExtent = {rect.rect.extent.width, rect.rect.extent.height, 1}; |
| 3492 | const VkDeviceSize pixels = VkDeviceSize(region.imageExtent.width) * region.imageExtent.height; | 3645 | const auto tile = stage_volume ? detail::volume_clear_tile(rect.rect.extent, p.element.size) |
| 3493 | const VkDeviceSize stride = VkDeviceSize(view.layer_count) * p.element.size; | 3646 | : rect.rect.extent; |
| 3494 | if (pixels > (UINT64_MAX - 3) / stride) return ReplayResult::unsupported; | 3647 | const VkDeviceSize pixels = VkDeviceSize(tile.width) * tile.height; |
| 3648 | const VkDeviceSize stride = VkDeviceSize(p.range.layerCount) * p.element.size; | ||
| 3649 | if (pixels > (UINT64_MAX - 3) / stride) return unsupported_at(__LINE__); | ||
| 3650 | // Pad only the private pattern for vkCmdFillBuffer; copies use the exact image extent. | ||
| 3495 | p.clear_pattern_bytes = std::max(p.clear_pattern_bytes, (pixels * stride + 3) & ~VkDeviceSize(3)); | 3651 | p.clear_pattern_bytes = std::max(p.clear_pattern_bytes, (pixels * stride + 3) & ~VkDeviceSize(3)); |
| 3496 | p.staged_writes.push_back(region); | 3652 | p.staged_writes.push_back(region); |
| 3497 | } | 3653 | } |
| 3498 | VkDeviceSize offset = 0; | 3654 | VkDeviceSize offset = 0; |
| 3499 | if (!vk.copy_scratch(p.clear_pattern_bytes, p.staged, offset) || !p.staged || offset % 4) | 3655 | if (!vk.copy_scratch(p.clear_pattern_bytes, p.staged, offset) || !p.staged || |
| 3500 | return ReplayResult::unsupported; | 3656 | offset % std::max(4u, p.element.size) || offset > UINT64_MAX - p.clear_pattern_bytes) |
| 3657 | return unsupported_at(__LINE__); | ||
| 3501 | for (auto& region : p.staged_writes) region.bufferOffset = offset; | 3658 | for (auto& region : p.staged_writes) region.bufferOffset = offset; |
| 3502 | continue; | 3659 | continue; |
| 3503 | } | 3660 | } |
| @@ -3577,7 +3734,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3577 | static_cast<unsigned long long>(n)); | 3734 | static_cast<unsigned long long>(n)); |
| 3578 | } | 3735 | } |
| 3579 | const ResourceBinding& image = upload ? p.binding : p.source; | 3736 | const ResourceBinding& image = upload ? p.binding : p.source; |
| 3580 | if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty()) { | 3737 | if (result == ReplayResult::success && !p.buffer_image_copies.empty()) { |
| 3581 | const auto& region = p.buffer_image_copies.front(); | 3738 | const auto& region = p.buffer_image_copies.front(); |
| 3582 | const BlockFormat fmt = copy_block_format(image, region.imageSubresource.aspectMask); | 3739 | const BlockFormat fmt = copy_block_format(image, region.imageSubresource.aspectMask); |
| 3583 | const std::uint32_t alignment = | 3740 | const std::uint32_t alignment = |
| @@ -3642,7 +3799,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3642 | } | 3799 | } |
| 3643 | if (result == ReplayResult::success && !p.image_copies.empty() && | 3800 | if (result == ReplayResult::success && !p.image_copies.empty() && |
| 3644 | (p.image_copies[0].srcSubresource.aspectMask != p.image_copies[0].dstSubresource.aspectMask || | 3801 | (p.image_copies[0].srcSubresource.aspectMask != p.image_copies[0].dstSubresource.aspectMask || |
| 3645 | a8_mixed_backing(p.source.format, p.binding.format))) { | 3802 | a8_mixed_backing(p.source.format, p.binding.format) || |
| 3803 | depth_format_pair(p.source.format, p.binding.format))) { | ||
| 3646 | // Depth <-> colour: vkCmdCopyImage cannot mix aspects, so each region goes image -> scratch -> image, | 3804 | // Depth <-> colour: vkCmdCopyImage cannot mix aspects, so each region goes image -> scratch -> image, |
| 3647 | // tightly packed. Depth aspects want 4-byte buffer offsets; 16 covers every texel size here. The two | 3805 | // tightly packed. Depth aspects want 4-byte buffer offsets; 16 covers every texel size here. The two |
| 3648 | // backings of A8_UNORM take the same route: one byte per texel on both sides, but Vulkan does not | 3806 | // backings of A8_UNORM take the same route: one byte per texel on both sides, but Vulkan does not |
| @@ -4666,7 +4824,27 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4666 | detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, | 4824 | detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 4667 | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, | 4825 | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, |
| 4668 | VK_PIPELINE_STAGE_TRANSFER_BIT); | 4826 | VK_PIPELINE_STAGE_TRANSFER_BIT); |
| 4669 | vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, ®ion); | 4827 | if (!p.binding.volume) { |
| 4828 | vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, ®ion); | ||
| 4829 | continue; | ||
| 4830 | } | ||
| 4831 | // Tiles within this rectangle are disjoint. Reuse the same scratch texels for every | ||
| 4832 | // tile and W slice; keep only one region per clipped rectangle in the prepared list. | ||
| 4833 | const auto tile = detail::volume_clear_tile({region.imageExtent.width, region.imageExtent.height}, | ||
| 4834 | p.element.size); | ||
| 4835 | auto piece = region; | ||
| 4836 | for (std::uint32_t z = 0; z < uav->view.layer_count; ++z) { | ||
| 4837 | piece.imageOffset.z = std::int32_t(uav->view.first_layer + z); | ||
| 4838 | for (std::uint32_t y = 0; y < region.imageExtent.height; y += tile.height) { | ||
| 4839 | piece.imageOffset.y = region.imageOffset.y + std::int32_t(y); | ||
| 4840 | piece.imageExtent.height = std::min(tile.height, region.imageExtent.height - y); | ||
| 4841 | for (std::uint32_t x = 0; x < region.imageExtent.width; x += tile.width) { | ||
| 4842 | piece.imageOffset.x = region.imageOffset.x + std::int32_t(x); | ||
| 4843 | piece.imageExtent.width = std::min(tile.width, region.imageExtent.width - x); | ||
| 4844 | vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, &piece); | ||
| 4845 | } | ||
| 4846 | } | ||
| 4847 | } | ||
| 4670 | } | 4848 | } |
| 4671 | }); | 4849 | }); |
| 4672 | continue; | 4850 | continue; |
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 3e6a8eab8..958f27ca5 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h | |||
| @@ -44,10 +44,13 @@ public: | |||
| 44 | 44 | ||
| 45 | // `usage` is what the chunks are created with. A chunk that declares VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | 45 | // `usage` is what the chunks are created with. A chunk that declares VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
| 46 | // gets its device address from get() as well, and its memory must have been allocated with | 46 | // gets its device address from get() as well, and its memory must have been allocated with |
| 47 | // VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT (the allocate callback's job). | 47 | // VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT (the allocate callback's job). `families` keeps retired chunks shareable |
| 48 | // across queue families (graphics + async compute). | ||
| 48 | ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, | 49 | ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, |
| 49 | DeviceFaultDiagnostics* diagnostics, VkBufferUsageFlags usage) | 50 | DeviceFaultDiagnostics* diagnostics, VkBufferUsageFlags usage, |
| 51 | std::vector<std::uint32_t> families = {}) | ||
| 50 | : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)), usage_(usage), | 52 | : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)), usage_(usage), |
| 53 | families_(std::move(families)), | ||
| 51 | addressable_((usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0) { | 54 | addressable_((usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0) { |
| 52 | loaded_ = vk_.load(get, device, addressable_); | 55 | loaded_ = vk_.load(get, device, addressable_); |
| 53 | } | 56 | } |