upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorSuarezPM <SuarezPM@users.noreply.github.com>2026-11-21 23:02:36 -0300
committerSuarezPM <SuarezPM@users.noreply.github.com>2026-11-21 23:30:46 -0300
commite6eaecd05a7d5d332ce8b84191c1d383ae7be18e (patch)
tree8d783e7d636881633dbf256a67ff47d5283518f8 /runtime/src
parent67204bf8c0471335d9046890288b33e8d5e2875b (diff)
Runtime: the descriptor table lives in device-local memory (D3D-76)
AI-assisted. Set 0 binding 2 is the table every T#/S# lookup probes. BindlessSet allocated it HOST_VISIBLE | HOST_COHERENT and flush() memcpy'd into the mapping, so a divergent lookup read it over PCIe: 19.5x slower for T#+S# pairs and 46.2x for a divergent miss at 100k entries on an RTX 2060 SUPER (vk_descriptor_bench, #639; 58-796x on the 5080). The table now lives in DEVICE_LOCAL (HOST_VISIBLE kept as a fallback for a device without it). flush() takes the command buffer that will use the set and uploads only what changed: the whole table from a mapped staging buffer when the buffers were just created (first use or growth), and the changed slots with vkCmdUpdateBuffer otherwise, which copies the data into the command buffer while recording so no staging bytes are read at execution. A TRANSFER_WRITE -> SHADER_READ barrier follows, before the draws. DescriptorTable tracks the slots that insert, replace, erase, clear and grow touched, including both slots of a relocation, so a flush no longer rebuilds an 80 MiB table for one descriptor. A command buffer whose vkQueueSubmit is rejected never runs the upload, so the set keeps the obligation: VulkanQueue::execute reports the submit result through a commit callback, and the set rebuilds the table on the next flush, which also reports flush_needs_idle() and makes the device wait before it. The same wait now honours the pre-existing contract for replaced/erased entries and for growth (the device ignored flush_needs_idle() before), and frees the retired buffers once the queue is idle instead of at teardown. Verified on an NVIDIA RTX 2060 SUPER, Linux 620.73.04, Vulkan 1.4.357: - ctest 10/10, including descriptor_table cases for the change list, relocation marking and consume-once reads. - vk_bindless_test with LEONIDA_VK_VALIDATION=1: 14 draws (probe depth, erase, relocation, growth 64 -> 512 slots, rebind, failed-submit retry, other view, removal) read back exact, table in device-local memory in both descriptor-indexing configurations. With the retry disabled the test is red. - GPU suite 64/91 with the same 27 64-wide skips as main, 0 failures; 91/91 with LEONIDA_W64_EMULATE=1. No game data; synthetic fixtures only.
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/descriptor_table.h54
-rw-r--r--runtime/src/vulkan_backend.h15
-rw-r--r--runtime/src/vulkan_bindless.h236
3 files changed, 255 insertions, 50 deletions
diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h
index d04109b45..3466bc325 100644
--- a/runtime/src/descriptor_table.h
+++ b/runtime/src/descriptor_table.h
@@ -143,6 +143,8 @@ public:
143 std::lock_guard lock(mutex_); 143 std::lock_guard lock(mutex_);
144 std::fill(entries_.begin(), entries_.end(), DescriptorEntry{}); 144 std::fill(entries_.begin(), entries_.end(), DescriptorEntry{});
145 occupied_count_ = 0; 145 occupied_count_ = 0;
146 all_changed_ = true;
147 changed_slots_.clear();
146 } 148 }
147 149
148 std::size_t size() const { 150 std::size_t size() const {
@@ -184,6 +186,38 @@ public:
184 return out; 186 return out;
185 } 187 }
186 188
189 // What a shader's copy of the table needs re-uploaded since the last take_changes().
190 struct Changes {
191 bool all = false; // the mask (table grew or was cleared): every slot and the header
192 std::vector<std::uint32_t> slots; // slots whose 10 dwords changed, in no particular order
193 };
194
195 Changes take_changes() {
196 std::lock_guard lock(mutex_);
197 Changes changes;
198 changes.all = all_changed_;
199 changes.slots = std::move(changed_slots_);
200 changed_slots_.clear();
201 all_changed_ = false;
202 return changes;
203 }
204
205 // One slot's 10 dwords (key[8], index, pad) to `dest`; false when the slot is out of range.
206 bool read_slot(std::uint32_t slot, std::uint32_t* dest) const { return read_slots(slot, 1, dest); }
207
208 // `count` consecutive slots' 10 dwords each to `dest`, under one lock; false when any is out of range.
209 bool read_slots(std::uint32_t first, std::uint32_t count, std::uint32_t* dest) const {
210 std::lock_guard lock(mutex_);
211 if (first + count > entries_.size()) return false;
212 for (std::uint32_t i = 0; i < count; ++i) {
213 const DescriptorEntry& entry = entries_[first + i];
214 std::memcpy(dest + i * 10, entry.key, sizeof(entry.key));
215 dest[i * 10 + 8] = entry.index;
216 dest[i * 10 + 9] = entry.pad;
217 }
218 return true;
219 }
220
187 void write_to_buffer(void* dest, bool clear_pad = false) const { 221 void write_to_buffer(void* dest, bool clear_pad = false) const {
188 if (!dest) return; 222 if (!dest) return;
189 const auto buf = build_gpu_buffer(clear_pad); 223 const auto buf = build_gpu_buffer(clear_pad);
@@ -191,10 +225,14 @@ public:
191 } 225 }
192 226
193private: 227private:
228 void mark(std::uint32_t slot) { changed_slots_.push_back(slot); }
229
194 // All eight slots for the incoming key are occupied. Try moving one resident 230 // All eight slots for the incoming key are occupied. Try moving one resident
195 // to the first empty slot beyond that window, within its own eight probes. 231 // to the first empty slot beyond that window, within its own eight probes.
196 // A later hole is farther from every resident, so failure here is final for a single move. 232 // A later hole is farther from every resident, so failure here is final for a single move.
197 static int make_probe_slot(std::vector<DescriptorEntry>& entries, std::uint32_t hash) { 233 // `moved_to` receives the hole the resident moved into, so the caller can mark that slot changed too.
234 static int make_probe_slot(std::vector<DescriptorEntry>& entries, std::uint32_t hash,
235 std::uint32_t* moved_to = nullptr) {
198 const auto mask = static_cast<std::uint32_t>(entries.size() - 1); 236 const auto mask = static_cast<std::uint32_t>(entries.size() - 1);
199 for (auto offset = kDescriptorProbes; offset < 2 * kDescriptorProbes - 1; ++offset) { 237 for (auto offset = kDescriptorProbes; offset < 2 * kDescriptorProbes - 1; ++offset) {
200 const auto hole = (hash + offset) & mask; 238 const auto hole = (hash + offset) & mask;
@@ -204,6 +242,7 @@ private:
204 const auto home = hash_descriptor_key(entries[slot].key); 242 const auto home = hash_descriptor_key(entries[slot].key);
205 if (((hole - home) & mask) < kDescriptorProbes) { 243 if (((hole - home) & mask) < kDescriptorProbes) {
206 entries[hole] = entries[slot]; 244 entries[hole] = entries[slot];
245 if (moved_to) *moved_to = hole;
207 return static_cast<int>(slot); // caller immediately overwrites the resident 246 return static_cast<int>(slot); // caller immediately overwrites the resident
208 } 247 }
209 } 248 }
@@ -224,6 +263,7 @@ private:
224 if (std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { 263 if (std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
225 if (entry.index == index) return InsertResult::unchanged; 264 if (entry.index == index) return InsertResult::unchanged;
226 entry.index = index; 265 entry.index = index;
266 mark(slot);
227 return InsertResult::replaced; 267 return InsertResult::replaced;
228 } 268 }
229 } else if (empty_slot < 0) { 269 } else if (empty_slot < 0) {
@@ -237,13 +277,16 @@ private:
237 } 277 }
238 278
239 const bool relocate = empty_slot < 0; 279 const bool relocate = empty_slot < 0;
240 if (relocate) empty_slot = make_probe_slot(entries_, h); 280 std::uint32_t moved_to = 0;
281 if (relocate) empty_slot = make_probe_slot(entries_, h, &moved_to);
241 if (empty_slot >= 0) { 282 if (empty_slot >= 0) {
242 auto& entry = entries_[empty_slot]; 283 auto& entry = entries_[empty_slot];
243 std::memcpy(entry.key, key, sizeof(entry.key)); 284 std::memcpy(entry.key, key, sizeof(entry.key));
244 entry.index = index; 285 entry.index = index;
245 entry.pad = kSlotOccupiedMarker; 286 entry.pad = kSlotOccupiedMarker;
246 ++occupied_count_; 287 ++occupied_count_;
288 if (relocate) mark(moved_to);
289 mark(std::uint32_t(empty_slot));
247 return relocate ? InsertResult::added_with_relocation : InsertResult::added; 290 return relocate ? InsertResult::added_with_relocation : InsertResult::added;
248 } 291 }
249 292
@@ -269,6 +312,7 @@ private:
269 // Backward-shift entries in the probe cluster to maintain probe chains 312 // Backward-shift entries in the probe cluster to maintain probe chains
270 std::uint32_t i = found_slot; 313 std::uint32_t i = found_slot;
271 std::uint32_t j = i; 314 std::uint32_t j = i;
315 mark(found_slot);
272 while (true) { 316 while (true) {
273 j = (j + 1) & mask_; 317 j = (j + 1) & mask_;
274 if (entries_[j].pad != kSlotOccupiedMarker) break; 318 if (entries_[j].pad != kSlotOccupiedMarker) break;
@@ -277,10 +321,12 @@ private:
277 const std::uint32_t dist_r_to_j = (j - r) & mask_; 321 const std::uint32_t dist_r_to_j = (j - r) & mask_;
278 if (dist_r_to_i < dist_r_to_j && dist_r_to_i < kDescriptorProbes) { 322 if (dist_r_to_i < dist_r_to_j && dist_r_to_i < kDescriptorProbes) {
279 entries_[i] = entries_[j]; 323 entries_[i] = entries_[j];
324 mark(i);
280 i = j; 325 i = j;
281 } 326 }
282 } 327 }
283 entries_[i] = DescriptorEntry{}; 328 entries_[i] = DescriptorEntry{};
329 mark(i);
284 --occupied_count_; 330 --occupied_count_;
285 return true; 331 return true;
286 } 332 }
@@ -314,6 +360,8 @@ private:
314 if (rehash_ok) { 360 if (rehash_ok) {
315 entries_ = std::move(new_entries); 361 entries_ = std::move(new_entries);
316 mask_ = new_mask; 362 mask_ = new_mask;
363 all_changed_ = true;
364 changed_slots_.clear();
317 break; 365 break;
318 } 366 }
319 new_cap *= 2; 367 new_cap *= 2;
@@ -324,6 +372,8 @@ private:
324 std::uint32_t mask_ = 15; 372 std::uint32_t mask_ = 15;
325 std::vector<DescriptorEntry> entries_; 373 std::vector<DescriptorEntry> entries_;
326 std::size_t occupied_count_ = 0; 374 std::size_t occupied_count_ = 0;
375 bool all_changed_ = false; // clear() or a grow: the mask and every slot changed
376 std::vector<std::uint32_t> changed_slots_; // slots inserted, replaced or moved since take_changes()
327}; 377};
328 378
329} // namespace leonida 379} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index a99e7e5f1..1bc19c75b 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -143,6 +143,13 @@ public:
143 bindless_prepare_ = std::move(prepare); 143 bindless_prepare_ = std::move(prepare);
144 } 144 }
145 145
146 // Called after that command buffer's submit: true when it was accepted, false when vkQueueSubmit failed. The
147 // set keeps its upload pending in the second case, because the copy never reached the GPU.
148 void set_bindless_commit(std::function<void(bool)> commit) {
149 std::lock_guard lock(mutex_);
150 bindless_commit_ = std::move(commit);
151 }
152
146 VulkanDeviceFunctions vk; 153 VulkanDeviceFunctions vk;
147 154
148 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. 155 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one.
@@ -185,6 +192,7 @@ private:
185 LayoutTracker tracker_; 192 LayoutTracker tracker_;
186 std::map<std::tuple<VkImage, VkImageAspectFlags, std::uint32_t, std::uint32_t, std::uint32_t, VkFormat>, VkImageView> views_; 193 std::map<std::tuple<VkImage, VkImageAspectFlags, std::uint32_t, std::uint32_t, std::uint32_t, VkFormat>, VkImageView> views_;
187 std::function<bool(VkCommandBuffer)> bindless_prepare_; 194 std::function<bool(VkCommandBuffer)> bindless_prepare_;
195 std::function<void(bool)> bindless_commit_;
188 ReplayFunctions replay_; 196 ReplayFunctions replay_;
189}; 197};
190 198
@@ -286,7 +294,8 @@ public:
286 if (context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { 294 if (context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) {
287 // The command buffer holds at most what the set recorded for itself; submit it so the buffer is reused. 295 // The command buffer holds at most what the set recorded for itself; submit it so the buffer is reused.
288 context_.vk.vkEndCommandBuffer(command_buffer); 296 context_.vk.vkEndCommandBuffer(command_buffer);
289 submit(command_buffer, VK_NULL_HANDLE, 0); 297 const bool submitted = submit(command_buffer, VK_NULL_HANDLE, 0);
298 if (context_.bindless_commit_) context_.bindless_commit_(submitted);
290 return ReplayResult::unsupported; 299 return ReplayResult::unsupported;
291 } 300 }
292 for (const auto& list : prepared) emit(list, command_buffer, context_.replay_, &context_.tracker_); 301 for (const auto& list : prepared) emit(list, command_buffer, context_.replay_, &context_.tracker_);
@@ -298,7 +307,9 @@ public:
298 context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT, 307 context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT,
299 0, 1, &host, 0, nullptr, 0, nullptr); 308 0, 1, &host, 0, nullptr, 0, nullptr);
300 context_.vk.vkEndCommandBuffer(command_buffer); 309 context_.vk.vkEndCommandBuffer(command_buffer);
301 return submit(command_buffer, VK_NULL_HANDLE, 0) ? ReplayResult::success : ReplayResult::unsupported; 310 const bool submitted = submit(command_buffer, VK_NULL_HANDLE, 0);
311 if (context_.bindless_commit_) context_.bindless_commit_(submitted);
312 return submitted ? ReplayResult::success : ReplayResult::unsupported;
302 } 313 }
303 314
304 // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. 315 // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far.
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h
index f839933e0..6f1c18e1c 100644
--- a/runtime/src/vulkan_bindless.h
+++ b/runtime/src/vulkan_bindless.h
@@ -25,6 +25,11 @@
25// is false; without it the caller flushes only when none is. With partially_bound (descriptorBindingPartiallyBound) only index 0 is written at 25// is false; without it the caller flushes only when none is. With partially_bound (descriptorBindingPartiallyBound) only index 0 is written at
26// creation; otherwise every element of every array starts as the fallback. 26// creation; otherwise every element of every array starts as the fallback.
27// 27//
28// The table of binding 2 lives in DEVICE_LOCAL memory: every divergent T#/S# lookup reads it, and a HOST_VISIBLE
29// table measured 19-46x slower there at 100k entries on an RTX 2060 SUPER (vk_descriptor_bench, D3D-56, #639).
30// flush() takes the command buffer that will use the set: it uploads only the slots that changed, from a mapped
31// staging buffer, and barriers the copy before the draws. The table at creation is empty until that first flush.
32//
28// Not thread-safe: the owner serialises calls. 33// Not thread-safe: the owner serialises calls.
29 34
30#ifndef VK_NO_PROTOTYPES 35#ifndef VK_NO_PROTOTYPES
@@ -111,12 +116,12 @@ public:
111 BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, 116 BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory,
112 BindlessFeatures features = {}) 117 BindlessFeatures features = {})
113 : device_(device), memory_(memory), features_(features) { 118 : device_(device), memory_(memory), features_(features) {
114 ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffer() && fill(); 119 ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill();
115 } 120 }
116 121
117 ~BindlessSet() { 122 ~BindlessSet() {
118 release_retired(); 123 release_retired();
119 if (table_buffer_.buffer) destroy(table_buffer_); 124 destroy(table_buffers_);
120 if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr); 125 if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr);
121 for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr); 126 for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr);
122 for (const auto& image : fallback_images_) { 127 for (const auto& image : fallback_images_) {
@@ -227,35 +232,36 @@ public:
227 232
228 // True when the next flush() will change entries a running shader may be probing, or replace the table's 233 // True when the next flush() will change entries a running shader may be probing, or replace the table's
229 // buffer: the caller then flushes only once no command buffer that uses the set is still executing. Without 234 // buffer: the caller then flushes only once no command buffer that uses the set is still executing. Without
230 // it the flush only adds entries to the buffer in place, which a running lookup cannot see half done. 235 // it the flush only adds entries, and the copy of an entry is not atomic: a shader probing a different key
236 // could in principle see a torn entry that matches it, which is accepted as vanishingly unlikely because the
237 // added key is new (there is no live key equal to it).
231 bool flush_needs_idle() const { 238 bool flush_needs_idle() const {
232 return table_dirty_ && (existing_entries_changed_ || table_.size_bytes() > table_buffer_.size); 239 return table_dirty_ && (existing_entries_changed_ || force_full_upload_ ||
240 table_.size_bytes() > table_buffers_.table.size);
241 }
242
243 // True when the table's buffer was allocated in DEVICE_LOCAL memory (the fallback for a device without it is
244 // HOST_VISIBLE, which still works, just slower).
245 bool table_in_device_local_memory() const { return table_device_local_; }
246
247 // True when the command buffer that carried the last table upload reached the queue; false keeps the upload
248 // obligation, and the next flush() rebuilds the whole table (the changed-slot list was consumed when the copy
249 // was recorded). A failed vkQueueSubmit is the caller's signal, not ours.
250 void table_upload_result(bool submitted) {
251 if (!upload_in_flight_) return;
252 upload_in_flight_ = false;
253 if (submitted) return;
254 table_dirty_ = true;
255 force_full_upload_ = true;
233 } 256 }
234 257
235 // Writes the pending descriptor changes and the table: before the commands that use the set are executed. 258 // Writes the pending descriptor changes and uploads the table, in `command_buffer`, before the commands that use
236 // A table that has grown gets a new buffer (binding 2 is rewritten); the old one is kept until 259 // the set are recorded after it. A table that has grown gets new buffers (binding 2 is rewritten); the old ones
237 // release_retired(). False when that buffer cannot be made: the set then still has the table as of the last 260 // stay until release_retired(). False when they cannot be made: the set then still has the table as of the last
238 // flush. 261 // flush.
239 bool flush() { 262 bool flush(VkCommandBuffer command_buffer) {
240 bool written = true; 263 bool written = true;
241 if (table_dirty_) { 264 if (table_dirty_ || !table_uploaded_) written = upload_table(command_buffer);
242 const std::vector<std::uint32_t> words = table_.build_gpu_buffer();
243 const VkDeviceSize bytes = words.size() * sizeof(std::uint32_t);
244 if (bytes > table_buffer_.size) {
245 TableBuffer larger;
246 if (create(larger, bytes)) {
247 retired_.push_back(table_buffer_);
248 table_buffer_ = larger;
249 write_table_binding();
250 } else {
251 written = false;
252 }
253 }
254 if (written) {
255 std::memcpy(table_buffer_.mapped, words.data(), bytes);
256 table_dirty_ = existing_entries_changed_ = false;
257 }
258 }
259 if (!pending_.empty()) { 265 if (!pending_.empty()) {
260 std::vector<VkWriteDescriptorSet> writes(pending_.size()); 266 std::vector<VkWriteDescriptorSet> writes(pending_.size());
261 for (std::size_t i = 0; i < pending_.size(); ++i) { 267 for (std::size_t i = 0; i < pending_.size(); ++i) {
@@ -276,7 +282,7 @@ public:
276 282
277 // Frees the buffers of tables that have since grown: when nothing submitted before the last flush() still runs. 283 // Frees the buffers of tables that have since grown: when nothing submitted before the last flush() still runs.
278 void release_retired() { 284 void release_retired() {
279 for (auto& buffer : retired_) destroy(buffer); 285 for (auto& buffers : retired_) destroy(buffers);
280 retired_.clear(); 286 retired_.clear();
281 } 287 }
282 288
@@ -288,7 +294,7 @@ private:
288 X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \ 294 X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \
289 X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \ 295 X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \
290 X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \ 296 X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \
291 X(vkCmdPipelineBarrier) X(vkCmdClearColorImage) 297 X(vkCmdPipelineBarrier) X(vkCmdCopyBuffer) X(vkCmdUpdateBuffer) X(vkCmdClearColorImage)
292#define LEONIDA_BINDLESS_MEMBER(name) PFN_##name name = nullptr; 298#define LEONIDA_BINDLESS_MEMBER(name) PFN_##name name = nullptr;
293 LEONIDA_BINDLESS_FUNCTIONS(LEONIDA_BINDLESS_MEMBER) 299 LEONIDA_BINDLESS_FUNCTIONS(LEONIDA_BINDLESS_MEMBER)
294#undef LEONIDA_BINDLESS_MEMBER 300#undef LEONIDA_BINDLESS_MEMBER
@@ -317,6 +323,12 @@ private:
317 std::size_t size = 0; 323 std::size_t size = 0;
318 }; 324 };
319 325
326 // The table and the mapped staging copy the CPU writes before vkCmdCopyBuffer moves the changes.
327 struct TableBuffers {
328 TableBuffer table; // DEVICE_LOCAL when the device has it; what binding 2 names
329 TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT
330 };
331
320 struct Pending { 332 struct Pending {
321 std::uint32_t binding; 333 std::uint32_t binding;
322 std::uint32_t index; 334 std::uint32_t index;
@@ -435,10 +447,11 @@ private:
435 return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS; 447 return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS;
436 } 448 }
437 449
438 bool create(TableBuffer& out, std::size_t bytes) const { 450 bool create(TableBuffer& out, std::size_t bytes, bool device_local, bool* got_device_local = nullptr) const {
439 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 451 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
440 info.size = bytes; 452 info.size = bytes;
441 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; 453 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
454 (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
442 TableBuffer made; 455 TableBuffer made;
443 made.size = bytes; 456 made.size = bytes;
444 if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; 457 if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false;
@@ -446,12 +459,23 @@ private:
446 vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); 459 vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements);
447 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; 460 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
448 allocation.allocationSize = requirements.size; 461 allocation.allocationSize = requirements.size;
449 allocation.memoryTypeIndex = memory_type( 462 allocation.memoryTypeIndex =
450 requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); 463 device_local ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
451 const bool ready = allocation.memoryTypeIndex != 0xffffffffu && 464 : memory_type(requirements.memoryTypeBits,
452 vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory) == VK_SUCCESS && 465 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
453 vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0) == VK_SUCCESS && 466 if (device_local && allocation.memoryTypeIndex == 0xffffffffu)
454 vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped) == VK_SUCCESS; 467 allocation.memoryTypeIndex = memory_type(requirements.memoryTypeBits,
468 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
469 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
470 if (got_device_local)
471 *got_device_local = allocation.memoryTypeIndex != 0xffffffffu &&
472 (memory_.memoryTypes[allocation.memoryTypeIndex].propertyFlags &
473 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0;
474 bool ready = allocation.memoryTypeIndex != 0xffffffffu &&
475 vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory) == VK_SUCCESS &&
476 vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0) == VK_SUCCESS;
477 if (ready && !device_local)
478 ready = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped) == VK_SUCCESS;
455 if (!ready) { 479 if (!ready) {
456 destroy(made); 480 destroy(made);
457 return false; 481 return false;
@@ -466,17 +490,133 @@ private:
466 buffer = {}; 490 buffer = {};
467 } 491 }
468 492
469 bool create_table_buffer() { 493 void destroy(TableBuffers& buffers) const {
470 const std::vector<std::uint32_t> words = table_.build_gpu_buffer(); 494 destroy(buffers.staging);
471 const VkDeviceSize bytes = words.size() * sizeof(std::uint32_t); 495 destroy(buffers.table);
472 if (!create(table_buffer_, bytes)) return false; 496 }
473 std::memcpy(table_buffer_.mapped, words.data(), bytes); 497
498 bool create_table_buffers() {
499 const std::size_t bytes = table_.size_bytes();
500 TableBuffers made;
501 bool device_local = false;
502 if (!create(made.table, bytes, true, &device_local) || !create(made.staging, bytes, false)) {
503 destroy(made);
504 return false;
505 }
506 table_buffers_ = made;
507 table_device_local_ = device_local;
508 table_uploaded_ = false; // the first flush() uploads it, in the command buffer that will use it
509 table_dirty_ = existing_entries_changed_ = false;
510 return true;
511 }
512
513 // Uploads what changed since the last call: the whole table when it grew (the mask moved) or was never uploaded,
514 // the changed slots otherwise. The copy and its barrier go into `command_buffer`, before the draws.
515 bool upload_table(VkCommandBuffer command_buffer) {
516 if (!command_buffer) return false;
517 const std::size_t bytes = table_.size_bytes();
518 bool full = force_full_upload_ || !table_uploaded_ || bytes > table_buffers_.table.size;
519 bool grew = false;
520 if (bytes > table_buffers_.table.size) {
521 TableBuffers larger;
522 bool device_local = false;
523 if (!create(larger.table, bytes, true, &device_local) || !create(larger.staging, bytes, false)) {
524 destroy(larger);
525 return false;
526 }
527 table_device_local_ = device_local;
528 retired_.push_back(table_buffers_);
529 table_buffers_ = larger;
530 write_table_binding(table_buffers_.table.buffer);
531 full = true;
532 grew = true;
533 }
534 const DescriptorTable::Changes changes = table_.take_changes();
535 full = full || changes.all;
536 bool recorded = false;
537 // The staging buffer is written only for buffers that were just created (first upload or growth): a later
538 // flush then either updates slots with vkCmdUpdateBuffer or rebuilds from a fresh pair, so no copy still in
539 // flight can be reading bytes the CPU rewrites.
540 const bool fresh = grew || !table_uploaded_;
541 const auto upload_all = [&]() {
542 const std::vector<std::uint32_t> words = table_.build_gpu_buffer();
543 if (fresh) {
544 std::memcpy(table_buffers_.staging.mapped, words.data(), bytes);
545 copy_table_range(command_buffer, 0, bytes);
546 } else {
547 update_table_range(command_buffer, 0, words.data(), bytes);
548 }
549 recorded = true;
550 };
551 if (full) {
552 upload_all();
553 } else if (!changes.slots.empty()) {
554 std::vector<std::uint32_t> slots = changes.slots;
555 std::sort(slots.begin(), slots.end());
556 slots.erase(std::unique(slots.begin(), slots.end()), slots.end());
557 bool staged = true;
558 for (std::size_t first = 0; staged && first < slots.size();) {
559 std::size_t last = first;
560 while (last + 1 < slots.size() && slots[last + 1] == slots[last] + 1) ++last;
561 const std::uint32_t count = std::uint32_t(last - first + 1);
562 std::vector<std::uint32_t> words(std::size_t(count) * 10);
563 staged = table_.read_slots(slots[first], count, words.data());
564 if (staged) {
565 update_table_range(command_buffer, entry_offset(slots[first]), words.data(),
566 VkDeviceSize(words.size() * sizeof(std::uint32_t)));
567 recorded = true;
568 }
569 first = last + 1;
570 }
571 if (!staged) upload_all(); // an inconsistent slot list: the whole table is still correct
572 }
573 if (!recorded) return true; // nothing was copied: keep the obligation for the next flush
574 record_table_barrier(command_buffer);
575 upload_in_flight_ = true;
474 table_dirty_ = existing_entries_changed_ = false; 576 table_dirty_ = existing_entries_changed_ = false;
577 table_uploaded_ = true;
578 force_full_upload_ = false;
475 return true; 579 return true;
476 } 580 }
477 581
478 void write_table_binding() const { 582 // Copies the data into the command buffer while recording (64 KiB per call, the Vulkan limit), so no staging
479 const VkDescriptorBufferInfo info{table_buffer_.buffer, 0, VK_WHOLE_SIZE}; 583 // buffer is read at execution: a later flush can rewrite its own staging without racing a pending copy.
584 void update_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, const void* data,
585 VkDeviceSize size) const {
586 constexpr VkDeviceSize max_chunk = 65536;
587 const auto* bytes = static_cast<const std::uint8_t*>(data);
588 for (VkDeviceSize done = 0; done < size; done += max_chunk) {
589 const VkDeviceSize chunk = std::min(max_chunk, size - done);
590 vk_.vkCmdUpdateBuffer(command_buffer, table_buffers_.table.buffer, offset + done, chunk, bytes + done);
591 }
592 }
593
594 void copy_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, VkDeviceSize size) const {
595 const VkBufferCopy region{offset, offset, size};
596 vk_.vkCmdCopyBuffer(command_buffer, table_buffers_.staging.buffer, table_buffers_.table.buffer, 1, &region);
597 }
598
599 void record_table_barrier(VkCommandBuffer command_buffer) const {
600 VkBufferMemoryBarrier barrier{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
601 barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
602 barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
603 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
604 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
605 barrier.buffer = table_buffers_.table.buffer;
606 barrier.offset = 0;
607 barrier.size = VK_WHOLE_SIZE;
608 vk_.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0,
609 nullptr, 1, &barrier, 0, nullptr);
610 }
611
612 // The entry's first dword after the mask word; each entry is 10 dwords (40 bytes).
613 static constexpr VkDeviceSize entry_bytes = 10 * sizeof(std::uint32_t);
614 static VkDeviceSize entry_offset(std::uint32_t slot) {
615 return sizeof(std::uint32_t) + VkDeviceSize(slot) * entry_bytes;
616 }
617
618 void write_table_binding(VkBuffer buffer) const {
619 const VkDescriptorBufferInfo info{buffer, 0, VK_WHOLE_SIZE};
480 VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; 620 VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
481 write.dstSet = set_; 621 write.dstSet = set_;
482 write.dstBinding = bindless::table_binding; 622 write.dstBinding = bindless::table_binding;
@@ -503,7 +643,7 @@ private:
503 643
504 // The table at binding 2 and the fallback at index 0 of every array, or in every element without partially_bound. 644 // The table at binding 2 and the fallback at index 0 of every array, or in every element without partially_bound.
505 bool fill() { 645 bool fill() {
506 write_table_binding(); 646 write_table_binding(table_buffers_.table.buffer);
507 std::vector<std::vector<VkDescriptorImageInfo>> infos; 647 std::vector<std::vector<VkDescriptorImageInfo>> infos;
508 std::vector<VkWriteDescriptorSet> writes; 648 std::vector<VkWriteDescriptorSet> writes;
509 infos.reserve(bindless::bindings.size()); 649 infos.reserve(bindless::bindings.size());
@@ -573,10 +713,14 @@ private:
573 std::vector<Pending> pending_; 713 std::vector<Pending> pending_;
574 std::unordered_map<std::uint64_t, std::size_t> pending_slots_; // binding and index -> place in pending_ 714 std::unordered_map<std::uint64_t, std::size_t> pending_slots_; // binding and index -> place in pending_
575 DescriptorTable table_{64}; 715 DescriptorTable table_{64};
576 TableBuffer table_buffer_; 716 TableBuffers table_buffers_;
717 bool table_uploaded_ = false; // the table's current contents are in table_buffers_.table
718 bool table_device_local_ = false;
577 bool table_dirty_ = false; // the table differs from the buffer 719 bool table_dirty_ = false; // the table differs from the buffer
578 bool existing_entries_changed_ = false; // ... and not only by entries added 720 bool existing_entries_changed_ = false; // ... and not only by entries added
579 std::vector<TableBuffer> retired_; 721 bool upload_in_flight_ = false; // a copy is recorded, not yet known to have reached the queue
722 bool force_full_upload_ = false; // the last submit failed: rebuild the whole table on the next flush
723 std::vector<TableBuffers> retired_;
580}; 724};
581 725
582} // namespace leonida 726} // namespace leonida