upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_backend.h
diff options
context:
space:
mode:
authorsds-228 <329233051+sds-228@users.noreply.github.com>2026-11-23 02:12:09 +0300
committersds-228 <329233051+sds-228@users.noreply.github.com>2026-11-23 02:12:09 +0300
commitcc4b37449929516fefbd4e999b77836698a9bfd4 (patch)
tree598d1551196216ddd47cf46b22ea07359442fbb5 /runtime/src/vulkan_backend.h
parentaa2988cc555bad7ecd508b48a702adbb32fe7c95 (diff)
d3d12: translate ARRAY_OF_POINTERS instances on the KHR path
KHR TLAS builds hardcoded arrayOfPointers = VK_FALSE and passed the guest's console-VA pointer list straight to Vulkan. Carry DescsLayout into the recorded build, validate each pointer, stage a copy with heap_base added into a device-addressable buffer, and use it as the build input. The guest input is not modified and GPU-written pointer lists are refused. Adds ARRAY and ARRAY_OF_POINTERS RayQuery coverage plus a null-entry refusal check.
Diffstat (limited to 'runtime/src/vulkan_backend.h')
-rw-r--r--runtime/src/vulkan_backend.h128
1 files changed, 127 insertions, 1 deletions
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 03ab7ba26..5e6e25a3d 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -45,6 +45,13 @@
45 45
46namespace leonida { 46namespace leonida {
47 47
48// A CPU-written Vulkan-address instance pointer array, kept until the submission that builds with it completes.
49struct KhrInstanceStage {
50 VkBuffer buffer = VK_NULL_HANDLE;
51 VkDeviceMemory memory = VK_NULL_HANDLE;
52 VkDeviceAddress address = 0;
53};
54
48// VK_EXT_debug_utils labels: an instance extension, so a device has them only when its instance enabled it. 55// VK_EXT_debug_utils labels: an instance extension, so a device has them only when its instance enabled it.
49struct DebugLabelFunctions { 56struct DebugLabelFunctions {
50 PFN_vkCmdInsertDebugUtilsLabelEXT cmd_insert = nullptr; 57 PFN_vkCmdInsertDebugUtilsLabelEXT cmd_insert = nullptr;
@@ -874,6 +881,18 @@ public:
874 size = std::min<std::uint64_t>(size, b->size - (va - b->va)); 881 size = std::min<std::uint64_t>(size, b->size - (va - b->va));
875 return true; 882 return true;
876 }; 883 };
884 // Host reads of small CPU-written inputs. Unlike buffer_at, the whole range must be in one host-visible
885 // mapping: a partial read would see bytes the application has not written through the D3D12 API.
886 replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) {
887 BufferVaIndex<ResourceId>::Hit hit{};
888 if (!buffer_vas_.find(va, hit)) return false;
889 const ResourceBinding* b = resolve(hit.id);
890 if (!b || !b->host) return false;
891 const std::uint64_t offset = va - b->va;
892 if (offset > b->size || bytes > b->size - offset) return false;
893 host = b->host + offset;
894 return true;
895 };
877 if (xdxr && loaded_) { 896 if (xdxr && loaded_) {
878 xdxr_ = std::make_unique<XdxrBuilder>(get, device); 897 xdxr_ = std::make_unique<XdxrBuilder>(get, device);
879 if (xdxr_->loaded()) { 898 if (xdxr_->loaded()) {
@@ -1491,7 +1510,10 @@ public:
1491 } 1510 }
1492 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); 1511 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr);
1493 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); 1512 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr);
1494 for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end()); 1513 for (auto& slot : buffers_) {
1514 destroy_khr_stages(slot.khr_instances);
1515 free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end());
1516 }
1495 for (VkEvent event : free_events_) vk.vkDestroyEvent(context_.device(), event, nullptr); 1517 for (VkEvent event : free_events_) vk.vkDestroyEvent(context_.device(), event, nullptr);
1496 } 1518 }
1497 1519
@@ -1640,6 +1662,97 @@ public:
1640 } 1662 }
1641 1663
1642private: 1664private:
1665 void destroy_khr_stages(std::vector<KhrInstanceStage>& stages) {
1666 for (const auto& stage : stages) {
1667 if (stage.memory) context_.vk.vkFreeMemory(context_.device(), stage.memory, nullptr);
1668 if (stage.buffer) context_.vk.vkDestroyBuffer(context_.device(), stage.buffer, nullptr);
1669 }
1670 stages.clear();
1671 }
1672
1673 // A KHR TLAS built with D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS holds console VAs in its pointer list; Vulkan
1674 // reads those 8-byte entries as device addresses. Stage a translated copy in our own host-visible buffer instead
1675 // of editing the guest's input. The caller keeps the buffer until the submission that builds with it completes.
1676 bool stage_khr_instances(const ReplayFunctions& vk, const BuildAccelerationStructure& build,
1677 std::vector<KhrInstanceStage>& stages, VkDeviceAddress& address) {
1678 const auto& funcs = context_.vk;
1679 if (!funcs.vkCreateBuffer || !funcs.vkDestroyBuffer || !funcs.vkGetBufferMemoryRequirements ||
1680 !funcs.vkAllocateMemory || !funcs.vkFreeMemory || !funcs.vkBindBufferMemory || !funcs.vkMapMemory ||
1681 !funcs.vkUnmapMemory || !funcs.vkGetBufferDeviceAddress || !vk.host_at || !vk.buffer_at ||
1682 !build.instance_count)
1683 return false;
1684 const std::uint64_t bytes = 8ull * build.instance_count;
1685 const std::uint8_t* guest = nullptr;
1686 if (!vk.host_at(build.instances_va, bytes, guest)) return false;
1687 std::vector<std::uint64_t> translated;
1688 translated.reserve(build.instance_count);
1689 for (std::uint32_t i = 0; i < build.instance_count; ++i) {
1690 std::uint64_t va = 0;
1691 std::memcpy(&va, guest + 8ull * i, sizeof(va));
1692 VkBuffer buffer = VK_NULL_HANDLE;
1693 VkDeviceSize offset = 0;
1694 std::uint64_t room = 64; // one D3D12_RAYTRACING_INSTANCE_DESC
1695 if (!va || !vk.buffer_at(va, room, buffer, offset) || room < 64 || va > UINT64_MAX - vk.heap_base)
1696 return false;
1697 translated.push_back(vk.heap_base + va);
1698 }
1699 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
1700 info.size = bytes;
1701 info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
1702 VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR;
1703 KhrInstanceStage stage{};
1704 const auto discard = [&] {
1705 if (stage.memory) funcs.vkFreeMemory(context_.device(), stage.memory, nullptr);
1706 if (stage.buffer) funcs.vkDestroyBuffer(context_.device(), stage.buffer, nullptr);
1707 };
1708 if (funcs.vkCreateBuffer(context_.device(), &info, nullptr, &stage.buffer) != VK_SUCCESS) return false;
1709 VkMemoryRequirements requirements{};
1710 funcs.vkGetBufferMemoryRequirements(context_.device(), stage.buffer, &requirements);
1711 const auto& memory = context_.occlusion_resolve_memory_;
1712 constexpr VkMemoryPropertyFlags host_flags =
1713 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
1714 std::uint32_t type = memory.memoryTypeCount;
1715 for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) {
1716 if (!(requirements.memoryTypeBits & (1u << i))) continue;
1717 if ((memory.memoryTypes[i].propertyFlags & host_flags) == host_flags) {
1718 type = i;
1719 break;
1720 }
1721 }
1722 if (type == memory.memoryTypeCount) {
1723 discard();
1724 return false;
1725 }
1726 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO};
1727 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
1728 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags};
1729 allocation.allocationSize = requirements.size;
1730 allocation.memoryTypeIndex = type;
1731 if (funcs.vkAllocateMemory(context_.device(), &allocation, nullptr, &stage.memory) != VK_SUCCESS ||
1732 funcs.vkBindBufferMemory(context_.device(), stage.buffer, stage.memory, 0) != VK_SUCCESS) {
1733 discard();
1734 return false;
1735 }
1736 void* mapped = nullptr;
1737 if (funcs.vkMapMemory(context_.device(), stage.memory, 0, bytes, 0, &mapped) != VK_SUCCESS) {
1738 discard();
1739 return false;
1740 }
1741 for (std::size_t i = 0; i < translated.size(); ++i)
1742 std::memcpy(static_cast<std::uint8_t*>(mapped) + 8 * i, &translated[i], sizeof(std::uint64_t));
1743 funcs.vkUnmapMemory(context_.device(), stage.memory);
1744 VkBufferDeviceAddressInfo device_address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
1745 device_address.buffer = stage.buffer;
1746 stage.address = funcs.vkGetBufferDeviceAddress(context_.device(), &device_address);
1747 if (!stage.address) {
1748 discard();
1749 return false;
1750 }
1751 stages.push_back(stage);
1752 address = stage.address;
1753 return true;
1754 }
1755
1643 ReplayResult execute_now(std::span<const CommandList* const> lists) { 1756 ReplayResult execute_now(std::span<const CommandList* const> lists) {
1644 if (context_.is_device_lost()) return ReplayResult::unsupported; 1757 if (context_.is_device_lost()) return ReplayResult::unsupported;
1645 if (kind_ != QueueKind::direct) 1758 if (kind_ != QueueKind::direct)
@@ -1649,6 +1762,11 @@ private:
1649 std::holds_alternative<ClearDepthStencil>(command)) 1762 std::holds_alternative<ClearDepthStencil>(command))
1650 return ReplayResult::unsupported; 1763 return ReplayResult::unsupported;
1651 VkCommandBuffer command_buffer = VK_NULL_HANDLE; 1764 VkCommandBuffer command_buffer = VK_NULL_HANDLE;
1765 struct KhrGuard {
1766 VulkanQueue* queue;
1767 std::vector<KhrInstanceStage> stages;
1768 ~KhrGuard() { queue->destroy_khr_stages(stages); }
1769 } khr_guard{this};
1652 std::function<void(bool)> bindless_commit; 1770 std::function<void(bool)> bindless_commit;
1653 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. 1771 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_.
1654 // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during 1772 // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during
@@ -1684,6 +1802,10 @@ private:
1684 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy 1802 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
1685 : kind_ == QueueKind::compute ? detail::queue_stages_compute 1803 : kind_ == QueueKind::compute ? detail::queue_stages_compute
1686 : 0; 1804 : 0;
1805 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
1806 VkDeviceAddress& address) {
1807 return stage_khr_instances(replay, build, khr_guard.stages, address);
1808 };
1687 std::uint64_t captures = 0; 1809 std::uint64_t captures = 0;
1688 for (const auto* list : lists) 1810 for (const auto* list : lists)
1689 for (const auto& command : list->commands()) 1811 for (const auto& command : list->commands())
@@ -1816,6 +1938,8 @@ private:
1816 1938
1817 CommandSlot* slot = acquire(); 1939 CommandSlot* slot = acquire();
1818 if (!slot) return ReplayResult::unsupported; 1940 if (!slot) return ReplayResult::unsupported;
1941 slot->khr_instances = std::move(khr_guard.stages); // freed when this slot is reused
1942 khr_guard.stages.clear();
1819 command_buffer = slot->buffer; 1943 command_buffer = slot->buffer;
1820 // MoltenVK writes a timestamp at the end of a Metal encoder and resolves it with a blit that nothing orders 1944 // MoltenVK writes a timestamp at the end of a Metal encoder and resolves it with a blit that nothing orders
1821 // after that write, so a copy in the same or the next command buffer reads the old value (docs section 4.6). 1945 // after that write, so a copy in the same or the next command buffer reads the old value (docs section 4.6).
@@ -2111,6 +2235,7 @@ private:
2111 std::vector<VkEvent> events; // order_timestamp_copy's, reset and reused once the slot completes 2235 std::vector<VkEvent> events; // order_timestamp_copy's, reset and reused once the slot completes
2112 std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy; 2236 std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy;
2113 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes 2237 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes
2238 std::vector<KhrInstanceStage> khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime
2114 }; 2239 };
2115 2240
2116 struct PendingBindings { 2241 struct PendingBindings {
@@ -2218,6 +2343,7 @@ private:
2218 for (auto& slot : buffers_) { 2343 for (auto& slot : buffers_) {
2219 if (slot.ticket > done) continue; 2344 if (slot.ticket > done) continue;
2220 slot.segments.clear(); 2345 slot.segments.clear();
2346 destroy_khr_stages(slot.khr_instances);
2221 for (VkEvent event : slot.events) 2347 for (VkEvent event : slot.events)
2222 if (context_.vk.vkResetEvent(context_.device(), event) == VK_SUCCESS) free_events_.push_back(event); 2348 if (context_.vk.vkResetEvent(context_.device(), event) == VK_SUCCESS) free_events_.push_back(event);
2223 else context_.vk.vkDestroyEvent(context_.device(), event, nullptr); 2349 else context_.vk.vkDestroyEvent(context_.device(), event, nullptr);