upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_predicated_copy.h
blob: 2cc0e38fd3b45d6b084276effc2aef761eaab76e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Byte-granular conditional CopyBufferRegion. Requires enabled storageBuffer8BitAccess, not shaderInt8.
#pragma once
#ifndef VK_NO_PROTOTYPES
#define VK_NO_PROTOTYPES
#endif
#include <vulkan/vulkan.h>
#include <algorithm>
#include <cstdint>
#include <memory>
#include <initializer_list>
#include <vector>
#include "predicated_copy_spv.h"
#include "vulkan_aftermath.h"
namespace leonida {
struct PredicatedCopyDispatch {
    VkDescriptorSet set = VK_NULL_HANDLE;
    std::uint32_t source = 0, destination = 0, bytes = 0;
};
class PredicatedBufferCopier {
public:
    PredicatedBufferCopier(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits)
        : get_(get), device_(device), limits_(limits) {}
    ~PredicatedBufferCopier() {
        if (pipeline_) vk_.destroy_pipeline(device_, pipeline_, nullptr);
        if (layout_) vk_.destroy_layout(device_, layout_, nullptr);
        if (set_layout_) vk_.destroy_set_layout(device_, set_layout_, nullptr);
    }
    PredicatedBufferCopier(const PredicatedBufferCopier&)=delete;
    PredicatedBufferCopier& operator=(const PredicatedBufferCopier&)=delete;
    struct Batch {
        PredicatedBufferCopier& owner;
        std::vector<VkDescriptorPool> pools;
        explicit Batch(PredicatedBufferCopier& value):owner(value){}
        ~Batch(){for(auto pool:pools)owner.vk_.destroy_pool(owner.device_,pool,nullptr);}
        bool prepare(VkBuffer source,VkBuffer destination,VkDeviceSize src,VkDeviceSize dst,VkDeviceSize bytes,
                     std::vector<PredicatedCopyDispatch>& out) {
            out.clear();
            if(!bytes)return true;
            if(!source||!destination||bytes>UINT64_MAX-src||bytes>UINT64_MAX-dst)return false;
            if(source==destination && src<dst+bytes && dst<src+bytes)return false;
            if(!owner.make_pipeline())return false;
            // Align each descriptor base down, keeping byte prefixes in push constants. Split at the smaller
            // remaining descriptor range or dispatch limit, so no uint32 shader index can wrap or overread.
            struct Window{VkDescriptorBufferInfo source,destination;std::uint32_t src,dst,bytes;};
            std::vector<Window> windows;
            const auto alignment=std::max<VkDeviceSize>(1,owner.limits_.minStorageBufferOffsetAlignment);
            const VkDeviceSize maximum=owner.limits_.maxStorageBufferRange;
            const VkDeviceSize threads=VkDeviceSize(owner.limits_.maxComputeWorkGroupCount[0])*64;
            for(VkDeviceSize done=0;done<bytes;){
                const auto s=src+done,d=dst+done,sp=s%alignment,dp=d%alignment;
                if(sp>=maximum||dp>=maximum||!threads)return false;
                const auto n=std::min({bytes-done,maximum-sp,maximum-dp,threads});
                if(!n||n>UINT32_MAX)return false;
                windows.push_back({{source,s-sp,sp+n},{destination,d-dp,dp+n},
                                   static_cast<std::uint32_t>(sp),static_cast<std::uint32_t>(dp),static_cast<std::uint32_t>(n)});
                if(windows.size()>UINT32_MAX/2)return false;
                done+=n;
            }
            const auto count=static_cast<std::uint32_t>(windows.size());
            const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,count*2};
            VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
            pool_info.maxSets=count;pool_info.poolSizeCount=1;pool_info.pPoolSizes=&size;
            VkDescriptorPool pool=VK_NULL_HANDLE;
            if(owner.vk_.create_pool(owner.device_,&pool_info,nullptr,&pool)!=VK_SUCCESS)return false;
            const std::vector<VkDescriptorSetLayout> layouts(count,owner.set_layout_);
            std::vector<VkDescriptorSet> sets(count);
            VkDescriptorSetAllocateInfo allocate{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
            allocate.descriptorPool=pool;allocate.descriptorSetCount=count;allocate.pSetLayouts=layouts.data();
            if(owner.vk_.allocate_sets(owner.device_,&allocate,sets.data())!=VK_SUCCESS){
                owner.vk_.destroy_pool(owner.device_,pool,nullptr);
                return false;
            }
            // The batch is retained with the command buffer until its timeline ticket completes.
            pools.push_back(pool);
            for(std::uint32_t i=0;i<count;++i){
                VkWriteDescriptorSet writes[2]{};
                const VkDescriptorBufferInfo* infos[]={&windows[i].source,&windows[i].destination};
                for(std::uint32_t binding=0;binding<2;++binding){
                    auto& w=writes[binding];w.sType=VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;w.dstSet=sets[i];
                    w.dstBinding=binding;w.descriptorCount=1;w.descriptorType=VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;w.pBufferInfo=infos[binding];
                }
                owner.vk_.update_sets(owner.device_,2,writes,0,nullptr);
                out.push_back({sets[i],windows[i].src,windows[i].dst,windows[i].bytes});
            }
            return true;
        }
    };
    std::unique_ptr<Batch> batch(){return std::make_unique<Batch>(*this);}
    void emit(VkCommandBuffer cb,const std::vector<PredicatedCopyDispatch>& jobs)const{
        // Barriers are unconditional even when the dispatch is skipped by conditional rendering. They order
        // transfer producers, dependent copies, and adjacent windows whose aligned descriptors may overlap.
        for(const auto& job:jobs){
            VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
            before.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT;
            before.dstAccessMask=VK_ACCESS_SHADER_READ_BIT|VK_ACCESS_SHADER_WRITE_BIT;
            vk_.cmd_barrier(cb,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,0,1,&before,0,nullptr,0,nullptr);
            vk_.cmd_bind_pipeline(cb,VK_PIPELINE_BIND_POINT_COMPUTE,pipeline_);
            vk_.cmd_bind_sets(cb,VK_PIPELINE_BIND_POINT_COMPUTE,layout_,0,1,&job.set,0,nullptr);
            const std::uint32_t push[]={job.source,job.destination,job.bytes};
            vk_.cmd_push_constants(cb,layout_,VK_SHADER_STAGE_COMPUTE_BIT,0,sizeof(push),push);
            vk_.cmd_dispatch(cb,(job.bytes-1u)/64u+1u,1,1);
            VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
            after.srcAccessMask=VK_ACCESS_SHADER_WRITE_BIT|VK_ACCESS_SHADER_READ_BIT;
            after.dstAccessMask=VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT;
            vk_.cmd_barrier(cb,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,1,&after,0,nullptr,0,nullptr);
        }
    }
private:
    struct Functions {
        PFN_vkCreateDescriptorPool create_pool = nullptr;
        PFN_vkDestroyDescriptorPool destroy_pool = nullptr;
        PFN_vkAllocateDescriptorSets allocate_sets = nullptr;
        PFN_vkUpdateDescriptorSets update_sets = nullptr;
        PFN_vkCreateShaderModule create_shader = nullptr;
        PFN_vkDestroyShaderModule destroy_shader = nullptr;
        PFN_vkCreateDescriptorSetLayout create_set_layout = nullptr;
        PFN_vkDestroyDescriptorSetLayout destroy_set_layout = nullptr;
        PFN_vkCreatePipelineLayout create_layout = nullptr;
        PFN_vkDestroyPipelineLayout destroy_layout = nullptr;
        PFN_vkCreateComputePipelines create_pipelines = nullptr;
        PFN_vkDestroyPipeline destroy_pipeline = nullptr;
        PFN_vkCmdPipelineBarrier cmd_barrier = nullptr;
        PFN_vkCmdBindPipeline cmd_bind_pipeline = nullptr;
        PFN_vkCmdBindDescriptorSets cmd_bind_sets = nullptr;
        PFN_vkCmdPushConstants cmd_push_constants = nullptr;
        PFN_vkCmdDispatch cmd_dispatch = nullptr;
    };
    template<class T> bool load_fn(T& out, const char* name) const {
        out = reinterpret_cast<T>(get_(device_, name));
        return out != nullptr;
    }
    bool make_pipeline() {
        if (pipeline_) return true;
        // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything.
        Functions f{};
        if (!load_fn(f.create_pool, "vkCreateDescriptorPool") || !load_fn(f.destroy_pool, "vkDestroyDescriptorPool") ||
            !load_fn(f.allocate_sets, "vkAllocateDescriptorSets") || !load_fn(f.update_sets, "vkUpdateDescriptorSets") ||
            !load_fn(f.create_shader, "vkCreateShaderModule") || !load_fn(f.destroy_shader, "vkDestroyShaderModule") ||
            !load_fn(f.create_set_layout, "vkCreateDescriptorSetLayout") ||
            !load_fn(f.destroy_set_layout, "vkDestroyDescriptorSetLayout") ||
            !load_fn(f.create_layout, "vkCreatePipelineLayout") ||
            !load_fn(f.destroy_layout, "vkDestroyPipelineLayout") ||
            !load_fn(f.create_pipelines, "vkCreateComputePipelines") ||
            !load_fn(f.destroy_pipeline, "vkDestroyPipeline") ||
            !load_fn(f.cmd_barrier, "vkCmdPipelineBarrier") ||
            !load_fn(f.cmd_bind_pipeline, "vkCmdBindPipeline") ||
            !load_fn(f.cmd_bind_sets, "vkCmdBindDescriptorSets") ||
            !load_fn(f.cmd_push_constants, "vkCmdPushConstants") || !load_fn(f.cmd_dispatch, "vkCmdDispatch"))
            return false;
        VkDescriptorSetLayout set = VK_NULL_HANDLE;
        VkPipelineLayout layout = VK_NULL_HANDLE;
        VkShaderModule shader = VK_NULL_HANDLE;
        VkPipeline pipeline = VK_NULL_HANDLE;
        const VkDescriptorSetLayoutBinding bindings[]={{0,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr},{1,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr}};
        VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
        set_info.bindingCount = 2; set_info.pBindings = bindings;
        bool ok = f.create_set_layout(device_, &set_info, nullptr, &set) == VK_SUCCESS;
        const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 12};
        VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
        layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set;
        layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push;
        ok = ok && f.create_layout(device_, &layout_info, nullptr, &layout) == VK_SUCCESS;
        VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
        module.codeSize = sizeof(predicated_copy_spirv); module.pCode = predicated_copy_spirv;
        const aftermath::ShaderName aftermath_name("(runtime) predicated_copy");
        ok = ok && f.create_shader(device_, &module, nullptr, &shader) == VK_SUCCESS;
        VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
        info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
        info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main";
        info.layout = layout;
        ok = ok && f.create_pipelines(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS;
        if (shader) f.destroy_shader(device_, shader, nullptr);
        if (!ok) {
            if (pipeline) f.destroy_pipeline(device_, pipeline, nullptr);
            if (layout) f.destroy_layout(device_, layout, nullptr);
            if (set) f.destroy_set_layout(device_, set, nullptr);
            return false;
        }
        vk_ = f;
        set_layout_ = set; layout_ = layout; pipeline_ = pipeline;
        return true;
    }
    PFN_vkGetDeviceProcAddr get_;
    VkDevice device_;
    VkPhysicalDeviceLimits limits_;
    Functions vk_{};
    VkDescriptorSetLayout set_layout_=VK_NULL_HANDLE;
    VkPipelineLayout layout_=VK_NULL_HANDLE;
    VkPipeline pipeline_=VK_NULL_HANDLE;
};
}