-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathvulkan.cpp
More file actions
3526 lines (3105 loc) · 143 KB
/
vulkan.cpp
File metadata and controls
3526 lines (3105 loc) · 143 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2022-2023 NVIDIA CORPORATION. All rights reserved
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "source/core/sl.log/log.h"
#include "source/platforms/sl.chi/vulkan.h"
#include "source/core/sl.param/parameters.h"
#include "source/core/sl.security/secureLoadLibrary.h"
#include "shaders/vulkan_clear_image_view_spirv.h"
#include "nvllvk.h"
#include "external/vulkan/include/vulkan/vulkan_win32.h"
// Errors are negative so don't check for VK_SUCCESS only since there are other 'non fatal' values > 0, we show them as warnings
#define VK_CHECK(f) {auto _r = f;if(_r < 0){SL_LOG_ERROR("%s failed - error %d",#f,_r); return ComputeStatus::eError;} else if(_r != 0) {SL_LOG_WARN("%s - warning %d",#f,_r);}}
#define VK_CHECK_RV(f) {auto _r = f;if(_r < 0){SL_LOG_ERROR("%s failed - error %d",#f,_r); return;} else if(_r != 0) {SL_LOG_WARN("%s - warning %d",#f,_r);}}
#define VK_CHECK_RF(f) {auto _r = f;if(_r < 0){SL_LOG_ERROR("%s failed - error %d",#f,_r); return false;} else if(_r != 0) {SL_LOG_WARN("%s - warning %d",#f,_r);}}
#define VK_CHECK_RN(f) {auto _r = f;if(_r < 0){SL_LOG_ERROR("%s failed - error %d",#f,_r); return nullptr;} else if(_r != 0) {SL_LOG_WARN("%s - warning %d",#f,_r);}}
#define VK_CHECK_RE(res, f) res = f;if(res < 0){SL_LOG_ERROR("%s failed - error %d",#f,res); return res;} else if(res != 0) {SL_LOG_WARN("%s - warning %d",#f,res);}
#define VK_CHECK_RWS(f) {auto _r = f;if(_r < 0){SL_LOG_ERROR("%s failed - error %d",#f,_r); return WaitStatus::eError;} else if(_r == VK_TIMEOUT) {SL_LOG_WARN("%s - timed out", #f); return WaitStatus::eTimeout;}}
#define CHECK_REFLEX() do { if (!m_reflex){ SL_LOG_WARN_ONCE("No reflex"); return ComputeStatus::eError; } } while(false)
namespace sl
{
namespace chi
{
Vulkan s_vulkan;
ICompute *getVulkan()
{
return &s_vulkan;
}
void KernelDataVK::destroy(const VkLayerDispatchTable& ddt, VkDevice device)
{
if (pipeline)
{
ddt.DestroyPipeline(device, pipeline, nullptr);
ddt.DestroyPipelineLayout(device, pipelineLayout, nullptr);
ddt.DestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
}
if (shaderModule)
{
ddt.DestroyShaderModule(device, shaderModule, nullptr);
}
pipeline = VK_NULL_HANDLE;
pipelineLayout = VK_NULL_HANDLE;
descriptorSetLayout = VK_NULL_HANDLE;
shaderModule = VK_NULL_HANDLE;
}
struct Allocator
{
void init(VkCommandPool pAllocator, VkLayerDispatchTable* pDdt, ICompute* pCompute, VkDevice pDevice, std::string sDebugName)
{
destroy();
m_pAllocator = pAllocator;
m_pDdt = pDdt;
m_pCompute = pCompute;
m_pDevice = pDevice;
m_sDebugName = sDebugName;
// at all times we want to have at least one command buffer - because we have getCommandBuffer() function
TimedCommandBuffer cmdBuffer;
cmdBuffer.m_pBuffer = allocateNewCmdBuffer();
m_pCmdBuffers.push_back(cmdBuffer);
}
~Allocator()
{
destroy();
}
void destroy()
{
for (uint32_t u = 0; u < m_pCmdBuffers.size(); ++u)
{
freeCmdBuffer(m_pCmdBuffers[u].m_pBuffer);
}
m_pCmdBuffers.resize(0);
if (m_pAllocator)
{
m_pDdt->DestroyCommandPool(m_pDevice, m_pAllocator, nullptr);
}
m_pAllocator = nullptr;
m_pDdt = nullptr;
m_pCompute = nullptr;
m_pDevice = nullptr;
m_sDebugName.clear();
}
VkCommandPool getCmdAllocator()
{
return m_pAllocator;
}
VkCommandBuffer &getLatestCommandBuffer()
{
return m_pCmdBuffers.rbegin()->m_pBuffer;
}
VkCommandBuffer beginCommandList(uint64_t signalledFenceValue, uint64_t completedFenceValue)
{
assert(m_pCmdBuffers.size() < 20); // why would we have some many command buffers? something seems wrong
// The command buffers are sorted according to the fence value.
// Find how many command buffers have already executed on the GPU
uint32_t nOldCommandLists = 0;
for ( ; ; ++nOldCommandLists)
{
if (nOldCommandLists >= m_pCmdBuffers.size())
break;
if (m_pCmdBuffers[nOldCommandLists].isInUse(completedFenceValue))
{
break;
}
}
TimedCommandBuffer cmdBuffer;
if (nOldCommandLists > 0)
{
for (uint32_t u = 1; u < nOldCommandLists; ++u) // free all buffers except one
{
freeCmdBuffer(m_pCmdBuffers[u].m_pBuffer);
}
cmdBuffer = m_pCmdBuffers[0];
m_pCmdBuffers.erase(m_pCmdBuffers.begin(), m_pCmdBuffers.begin() + nOldCommandLists);
}
else
{
cmdBuffer.m_pBuffer = allocateNewCmdBuffer();
}
cmdBuffer.m_fenceValueWhenFree = signalledFenceValue + 1;
m_pCmdBuffers.push_back(cmdBuffer);
return cmdBuffer.m_pBuffer;
}
private:
struct TimedCommandBuffer
{
bool isInUse(uint64_t completedFenceValue)
{
return completedFenceValue < m_fenceValueWhenFree;
}
VkCommandBuffer m_pBuffer = nullptr;
uint64_t m_fenceValueWhenFree = 0;
};
VkCommandBuffer allocateNewCmdBuffer()
{
const VkCommandBufferAllocateInfo allocInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
nullptr,
m_pAllocator,
VK_COMMAND_BUFFER_LEVEL_PRIMARY,
1};
VkCommandBuffer cmdBuffer;
VK_CHECK_RN(m_pDdt->AllocateCommandBuffers(m_pDevice, &allocInfo, &cmdBuffer));
sl::Resource r;
r.native = cmdBuffer;
r.type = (ResourceType)ResourceType::eCommandBuffer;
m_pCompute->setDebugName(&r, (m_sDebugName + "_command_buffer").c_str());
return cmdBuffer;
}
void freeCmdBuffer(VkCommandBuffer cmdBuffer)
{
m_pDdt->FreeCommandBuffers(m_pDevice, m_pAllocator, 1, &cmdBuffer);
}
std::vector<TimedCommandBuffer> m_pCmdBuffers;
VkCommandPool m_pAllocator = nullptr;
VkLayerDispatchTable* m_pDdt = nullptr;
ICompute* m_pCompute = nullptr;
VkDevice m_pDevice = nullptr;
std::string m_sDebugName;
};
class CommandListContextVK : public ICommandListContext
{
struct WaitInfo
{
VkSemaphore fence;
uint64_t value;
};
std::vector<WaitInfo> m_waitingQueue;
VkLayerDispatchTable m_ddt;
interposer::VkTable* m_vk;
ICompute* m_compute = {};
VkQueue m_cmdQueue;
VkSemaphore m_presentSemaphore{};
std::vector<VkSemaphore> m_acquireSemaphore{}; // binary semaphore correspondng to each swapchain buffer passed to swapchain-acquisition VK API.
std::vector<VkFence> m_acquireFence{}; // Host-side (CPU) fence correspondng to each swapchain buffer passed to swapchain-acquisition to be able to do CPU wait.
uint32_t m_acquireIndex{}; // indexes into m_acquireSemaphore and m_acquireFence list.
std::vector<Allocator> m_allocators;
std::vector<VkSemaphore> m_fence;
std::vector<uint64_t> m_fenceValue = {};
bool m_cmdListIsRecording = false;
uint32_t m_index = 0;
uint32_t m_lastIndex = UINT_MAX;
uint32_t m_bufferCount = 0;
uint32_t m_bufferToPresent = 0;
std::wstring m_name;
VkDevice m_device = {};
std::mutex m_mtxQueueList;
std::mutex m_mtxSyncGPU;
// Keep validation layer happy
const VkPipelineStageFlags waitDstStageMask[4] = { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT , VK_PIPELINE_STAGE_ALL_COMMANDS_BIT , VK_PIPELINE_STAGE_ALL_COMMANDS_BIT , VK_PIPELINE_STAGE_ALL_COMMANDS_BIT };
public:
void init(ICompute* c, interposer::VkTable* vkMap, const char* debugName, VkDevice dev, CommandQueueVk* queue, uint32_t count)
{
m_compute = c;
m_device = dev;
m_vk = vkMap;
m_ddt = m_vk->dispatchDeviceMap[dev];
m_name = extra::utf8ToUtf16(debugName);
m_cmdQueue = (VkQueue)queue->native;
m_bufferCount = count;
m_acquireSemaphore.resize(m_bufferCount);
m_acquireFence.resize(m_bufferCount);
m_acquireIndex = m_bufferCount - 1;
m_allocators.resize(m_bufferCount);
m_fence.resize(m_bufferCount);
m_fenceValue.resize(m_bufferCount);
VkSemaphoreCreateInfo createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
createInfo.pNext = {};
createInfo.flags = 0;
VK_CHECK_RV(m_ddt.CreateSemaphore(dev, &createInfo, NULL, &m_presentSemaphore));
sl::Resource r{};
r.type = (ResourceType)ResourceType::eFence;
r.native = m_presentSemaphore;
m_compute->setDebugName(&r, "SL_present_semaphore");
VkFenceCreateInfo fenceCreateinfo = {};
fenceCreateinfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceCreateinfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (uint32_t i = 0; i < m_bufferCount; i++)
{
VK_CHECK_RV(m_ddt.CreateSemaphore(dev, &createInfo, NULL, &m_acquireSemaphore[i]));
r.type = (ResourceType)ResourceType::eFence;
r.native = m_acquireSemaphore[i];
std::stringstream name{};
name << "SL_acquire_semaphore_" << i;
m_compute->setDebugName(&r, name.str().c_str());
VK_CHECK_RV(m_ddt.CreateFence(dev, &fenceCreateinfo, NULL, &m_acquireFence[i]));
r.type = (ResourceType)ResourceType::eHostFence;
r.native = m_acquireFence[i];
name = std::stringstream{};
name << "SL_acquire_fence_" << i;
m_compute->setDebugName(&r, name.str().c_str());
}
SL_LOG_INFO("Creating command context %s - cmd buffers %u", debugName, m_bufferCount);
for (uint32_t i = 0; i < m_bufferCount; i++)
{
{
VkSemaphoreTypeCreateInfo timelineCreateInfo;
timelineCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO;
timelineCreateInfo.pNext = NULL;
timelineCreateInfo.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE;
timelineCreateInfo.initialValue = 0;
VkSemaphoreCreateInfo createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
createInfo.pNext = &timelineCreateInfo;
createInfo.flags = 0;
VK_CHECK_RV(m_ddt.CreateSemaphore(dev, &createInfo, NULL, &m_fence[i]));
m_fenceValue[i] = 0;
sl::Resource r;
r.native = m_fence[i];
r.type = (ResourceType)ResourceType::eFence;
m_compute->setDebugName(&r, (std::string(debugName) + "_semaphore").c_str());
}
{
VkCommandPool allocator{};
const VkCommandPoolCreateInfo createInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, nullptr, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queue->family };
VK_CHECK_RV(m_ddt.CreateCommandPool(m_device, &createInfo, nullptr, &allocator));
sl::Resource r;
r.native = allocator;
r.type = (ResourceType)ResourceType::eCommandPool;
m_compute->setDebugName(&r, (std::string(debugName) + "_command_pool").c_str());
m_allocators[i].init(allocator, &m_ddt, m_compute, m_device, debugName);
}
}
}
void shutdown()
{
assert(m_device != NULL);
for (uint32_t i = 0; i < m_bufferCount; i++)
{
m_allocators[i].destroy();
m_ddt.DestroySemaphore(m_device, m_fence[i], nullptr);
m_ddt.DestroyFence(m_device, m_acquireFence[i], NULL);
m_ddt.DestroySemaphore(m_device, m_acquireSemaphore[i], nullptr);
}
m_ddt.DestroySemaphore(m_device, m_presentSemaphore, nullptr);
m_fenceValue.clear();
m_fence.clear();
m_allocators.clear();
m_acquireFence.clear();
m_acquireSemaphore.clear();
}
RenderAPI getType() { return RenderAPI::eVulkan; }
CommandList getCmdList()
{
return m_allocators[m_index].getLatestCommandBuffer();
}
CommandQueue getCmdQueue()
{
return m_cmdQueue;
}
CommandAllocator getCmdAllocator()
{
return m_allocators[m_index].getCmdAllocator();
}
Handle getFenceEvent()
{
return nullptr;
}
Fence getFence(uint32_t index)
{
return m_fence[index];
}
bool beginCommandList()
{
if (m_cmdListIsRecording)
{
return true;
}
auto idx = m_index;
auto syncValue = m_fenceValue[m_index];
uint64_t signalledFenceValue = m_fenceValue[idx];
uint64_t completedFenceValue;
VK_CHECK_RF(m_ddt.GetSemaphoreCounterValue(m_device, m_fence[idx], &completedFenceValue));
VkCommandBuffer cmdBuffer = m_allocators[idx].beginCommandList(signalledFenceValue, completedFenceValue);
// One time usage since we wait for the last workload to finish
const VkCommandBufferBeginInfo info =
{
VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, nullptr
};
m_cmdListIsRecording = VK_SUCCESS == m_ddt.BeginCommandBuffer(cmdBuffer, &info);
return m_cmdListIsRecording;
}
bool executeCommandList(const GPUSyncInfo* info)
{
if (!m_cmdListIsRecording)
{
return false;
}
// Helps with crash dumps if we lose device below by allowing correct execution of the begin/end command buffer logic
m_cmdListIsRecording = false;
VkCommandBuffer cmdBuffer = m_allocators[m_index].getLatestCommandBuffer();
VK_CHECK_RF(m_ddt.EndCommandBuffer(cmdBuffer));
auto idx = m_index;
uint64_t syncValue = m_fenceValue[m_index] + 1;
m_fenceValue[m_index] = syncValue;
m_lastIndex = m_index;
m_index = (m_index + 1) % m_bufferCount;
std::vector<chi::Fence> waitSemaphores;
std::vector<chi::Fence> signalSemaphores = { m_fence[idx] };
std::vector<uint64_t> waitValues;
std::vector<uint64_t> signalValues = { syncValue };
if (info)
{
waitSemaphores.insert(waitSemaphores.end(), info->waitSemaphores.begin(), info->waitSemaphores.end());
signalSemaphores.insert(signalSemaphores.end(), info->signalSemaphores.begin(), info->signalSemaphores.end());
signalValues.insert(signalValues.end(), info->signalValues.begin(), info->signalValues.end());
waitValues.insert(waitValues.end(), info->waitValues.begin(), info->waitValues.end());
if (info->signalPresentSemaphore)
{
signalSemaphores.insert(signalSemaphores.end(), m_presentSemaphore);
signalValues.insert(signalValues.end(), kBinarySemaphoreValue); // Must provide value although this is binary semaphore
}
}
VkTimelineSemaphoreSubmitInfo timelineInfo;
timelineInfo.sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO;
timelineInfo.pNext = NULL;
timelineInfo.waitSemaphoreValueCount = (uint32_t)waitValues.size();
timelineInfo.pWaitSemaphoreValues = waitValues.data();
timelineInfo.signalSemaphoreValueCount = (uint32_t)signalValues.size();
timelineInfo.pSignalSemaphoreValues = signalValues.data();
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.pNext = &timelineInfo;
submitInfo.waitSemaphoreCount = (uint32_t)waitSemaphores.size();
submitInfo.pWaitSemaphores = (VkSemaphore*)waitSemaphores.data();
submitInfo.signalSemaphoreCount = (uint32_t)signalSemaphores.size();
submitInfo.pSignalSemaphores = (VkSemaphore*)signalSemaphores.data();
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &cmdBuffer;
submitInfo.pWaitDstStageMask = waitDstStageMask;
VK_CHECK_RF(m_ddt.QueueSubmit(m_cmdQueue, 1, &submitInfo, info ? (VkFence)info->fence : nullptr));
//SL_LOG_INFO("Submitting on %S index %u value %llu", name.c_str(), index, syncValue);
return true;
}
WaitStatus flushAll()
{
// Wait for the last signaled value to complete on all semaphores
VkSemaphoreWaitInfo waitInfo;
waitInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO;
waitInfo.pNext = NULL;
waitInfo.flags = 0;
waitInfo.semaphoreCount = m_bufferCount;
waitInfo.pSemaphores = &m_fence[0];
waitInfo.pValues = &m_fenceValue[0];
VK_CHECK_RWS(m_ddt.WaitSemaphores(m_device, &waitInfo, kMaxSemaphoreWaitUs));
return WaitStatus::eNoTimeout;
}
uint32_t getPrevCommandListIndex() override
{
assert(m_bufferCount > 0); // can't call this if you don't have any buffers
return (m_index + m_bufferCount - 1) % m_bufferCount;
}
uint32_t getCurrentCommandListIndex()
{
return m_index;
}
bool isCommandListRecording()
{
return m_cmdListIsRecording;
}
uint64_t getSyncValueAtIndex(uint32_t idx)
{
return m_fenceValue[idx];
}
SyncPoint getSyncPointAtIndex(uint32_t idx) override
{
return { m_fence[idx], m_fenceValue[idx] };
}
Fence getNextVkAcquireFence() override final
{
return m_acquireFence[m_acquireIndex];
}
bool signalAllWaitingOnQueues()
{
std::lock_guard<std::mutex> lock(m_mtxQueueList);
for (auto& other : m_waitingQueue)
{
// We are waiting on GPU for these queues, signal them to get out of the deadlock
uint64_t completedValue{};
VK_CHECK_RF(m_ddt.GetSemaphoreCounterValue(m_device, other.fence, &completedValue));
// Desperate times desperate measures, make sure to signal new value
auto syncValue = other.value;
while (completedValue >= syncValue)
{
syncValue++;
}
VkSemaphoreSignalInfo info{};
info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO;
info.semaphore = other.fence;
info.value = other.value;
VK_CHECK_RF(m_ddt.SignalSemaphore(m_device, &info));
//SL_LOG_INFO("Signaled %S index %u value %llu", other.ctx->name.c_str(), other.clIndex, other.syncValue);
}
m_waitingQueue.clear();
return true;
}
WaitStatus waitForCommandListToFinish(uint32_t i)
{
if (!didCommandListFinish(i))
{
VkSemaphoreWaitInfo waitInfo;
waitInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO;
waitInfo.pNext = NULL;
waitInfo.flags = 0;
waitInfo.semaphoreCount = 1;
waitInfo.pSemaphores = &m_fence[i];
waitInfo.pValues = &m_fenceValue[i];
VK_CHECK_RWS(m_ddt.WaitSemaphores(m_device, &waitInfo, kMaxSemaphoreWaitUs));
}
//SL_LOG_INFO("Flushing on %S index %u value %llu", name.c_str(), i, fenceValue[i]);
return WaitStatus::eNoTimeout;
}
bool didCommandListFinish(uint32_t index)
{
uint64_t completedValue;
VK_CHECK_RF(m_ddt.GetSemaphoreCounterValue(m_device, m_fence[index], &completedValue));
return completedValue >= m_fenceValue[m_index];
}
void syncGPU(const GPUSyncInfo* info)
{
std::vector<chi::Fence> waitSemaphores;
std::vector<uint64_t> waitValues;
std::vector<chi::Fence> signalSemaphores;
std::vector<uint64_t> signalValues;
// External semaphores (if any)
if (info)
{
waitSemaphores.insert(waitSemaphores.end(), info->waitSemaphores.begin(), info->waitSemaphores.end());
waitValues.insert(waitValues.end(), info->waitValues.begin(), info->waitValues.end());
}
if(info)
{
signalSemaphores.insert(signalSemaphores.end(), info->signalSemaphores.begin(), info->signalSemaphores.end());
signalValues.insert(signalValues.end(), info->signalValues.begin(), info->signalValues.end());
}
VkTimelineSemaphoreSubmitInfo timelineInfo{};
timelineInfo.sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO;
timelineInfo.pNext = NULL;
timelineInfo.waitSemaphoreValueCount = (uint32_t)waitValues.size();
timelineInfo.pWaitSemaphoreValues = waitValues.data();
timelineInfo.signalSemaphoreValueCount = (uint32_t)signalValues.size();
timelineInfo.pSignalSemaphoreValues = signalValues.data();
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.pNext = &timelineInfo;
submitInfo.waitSemaphoreCount = (uint32_t)waitSemaphores.size();
submitInfo.pWaitSemaphores = (VkSemaphore*)waitSemaphores.data();
submitInfo.signalSemaphoreCount = (uint32_t)signalSemaphores.size();
submitInfo.pSignalSemaphores = (VkSemaphore*)signalSemaphores.data();
submitInfo.pWaitDstStageMask = waitDstStageMask;
VK_CHECK_RV(m_ddt.QueueSubmit(m_cmdQueue, 1, &submitInfo, info ? (VkFence)info->fence : VK_NULL_HANDLE));
}
bool signalGPUFenceAt(uint32_t index) override
{
return signalGPUFence(m_fence[index], ++m_fenceValue[m_index]);
}
bool signalGPUFence(Fence fence, uint64_t syncValue) override
{
GPUSyncInfo info;
info.signalSemaphores = { (VkSemaphore)fence };
info.signalValues = { syncValue };
syncGPU(&info);
return true;
}
void waitGPUFence(Fence fence, uint64_t syncValue, const DebugInfo &debugInfo) override
{
GPUSyncInfo info;
info.waitSemaphores = { (VkSemaphore)fence };
info.waitValues = { syncValue };
syncGPU(&info);
}
void waitOnGPUForTheOtherQueue(const ICommandListContext* other, uint32_t clIndex,
uint64_t syncValue, const DebugInfo &debugInfo) override
{
auto tmp = (const CommandListContextVK*)other;
if (!tmp || tmp->m_cmdQueue == m_cmdQueue) return;
VkSemaphore waitFence = tmp->m_fence[clIndex];
uint64_t waitFenceValue = syncValue;
GPUSyncInfo info;
info.waitSemaphores = { waitFence };
info.waitValues = { waitFenceValue };
syncGPU(&info);
// Store sync data
std::lock_guard<std::mutex> lock(m_mtxQueueList);
bool found = false;
for (auto& other : m_waitingQueue)
{
if (other.fence == waitFence)
{
found = true;
other.fence = waitFence;
other.value = waitFenceValue;
break;
}
}
if (!found)
{
m_waitingQueue.push_back({ waitFence, waitFenceValue });
}
}
WaitStatus waitForCommandList(FlushType ft)
{
// Flush command list, to avoid it still referencing resources that may be destroyed after this call
if (m_cmdListIsRecording)
{
executeCommandList(nullptr);
}
if (ft == eCurrent)
{
VkSemaphoreWaitInfo waitInfo;
waitInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO;
waitInfo.pNext = NULL;
waitInfo.flags = 0;
waitInfo.semaphoreCount = 1;
waitInfo.pSemaphores = &m_fence[m_lastIndex];
waitInfo.pValues = &m_fenceValue[m_lastIndex];
VK_CHECK_RWS(m_ddt.WaitSemaphores(m_device, &waitInfo, kMaxSemaphoreWaitUs));
//SL_LOG_INFO("Flush current %S index %u value %llu", name.c_str(), index, syncValue);
}
else if (ft == eDefault)
{
// Default, wait for previous frame at this index (N frames behind to finish)
auto syncValue = m_fenceValue[m_lastIndex] - 1;
VkSemaphoreWaitInfo waitInfo;
waitInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO;
waitInfo.pNext = NULL;
waitInfo.flags = 0;
waitInfo.semaphoreCount = 1;
waitInfo.pSemaphores = &m_fence[m_lastIndex];
waitInfo.pValues = &syncValue;
VK_CHECK_RWS(m_ddt.WaitSemaphores(m_device, &waitInfo, kMaxSemaphoreWaitUs));
}
return WaitStatus::eNoTimeout;
}
int acquireNextBufferIndex(SwapChain chain, uint32_t& bufferIndex, Fence* waitSemaphore)
{
SwapChainVk* sc = (SwapChainVk*)chain;
const uint64_t timeout = 2000000000; // 2 seconds
bufferIndex = UINT32_MAX;
// With VK it is important to always return the "error" code
int res{};
m_acquireIndex = (m_acquireIndex + 1) % m_bufferCount;
// CPU wait not possible with binary semaphores, hence needing corresponding host fence.
VK_CHECK_RE(res, m_ddt.WaitForFences(m_device, 1, &m_acquireFence[m_acquireIndex], VK_TRUE, timeout));
VK_CHECK_RE(res, m_ddt.ResetFences(m_device, 1, &m_acquireFence[m_acquireIndex]));
VK_CHECK_RE(res, m_ddt.AcquireNextImageKHR(m_device, (VkSwapchainKHR)sc->native, timeout, m_acquireSemaphore[m_acquireIndex], nullptr, &bufferIndex));
m_bufferToPresent = bufferIndex;
if (waitSemaphore)
{
*waitSemaphore = m_acquireSemaphore[m_acquireIndex];
}
return res;
}
int present(SwapChain chain, uint32_t sync, uint32_t flags, void* params)
{
SwapChainVk* sc = (SwapChainVk*)chain;
auto swapChain = (VkSwapchainKHR)sc->native;
const VkPresentInfoKHR info =
{
VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
params,
// Cannot wait here on present semaphore (however acquires next image has to wait before doing a copy to back buffer)
1,
&m_presentSemaphore,
1,
&swapChain,
&m_bufferToPresent, nullptr
};
// With VK it is important to always return the "error" code
int res{};
res = m_ddt.QueuePresentKHR(m_cmdQueue, &info);
// Error check, accounting for the special case of VK_ERROR_OUT_OF_DATE_KHR when swapchain resizes
if (res == VK_ERROR_OUT_OF_DATE_KHR)
{
SL_LOG_WARN("%s - warning %d", "m_ddt.QueuePresentKHR(m_cmdQueue, &info)", res);
}
else if (res < 0)
{
SL_LOG_ERROR("%s failed - error %d", "m_ddt.QueuePresentKHR(m_cmdQueue, &info)", res);
}
return res;
}
void getFrameStats(SwapChain chain, void* frameStats)
{
assert(false);
SL_LOG_ERROR("Not implemented");
return;
}
void getLastPresentID(SwapChain chain, uint32_t& id)
{
assert(false);
SL_LOG_ERROR("Not implemented");
return;
}
void waitForVblank(SwapChain chain)
{
assert(false);
SL_LOG_ERROR("Not implemented");
return;
}
};
inline VkImageLayout toVkImageLayout(ResourceState state)
{
switch (state)
{
default:
case ResourceState::eGeneral: return VK_IMAGE_LAYOUT_GENERAL;
case ResourceState::eTextureRead: return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
case ResourceState::eColorAttachmentRead:
case ResourceState::eColorAttachmentWrite:
case ResourceState::eColorAttachmentRW: return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
case ResourceState::eDepthStencilAttachmentRead: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
case ResourceState::eDepthStencilAttachmentWrite:
case ResourceState::eDepthStencilAttachmentRW: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
case ResourceState::eCopySource:
case ResourceState::eResolveSource: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
case ResourceState::eCopyDestination:
case ResourceState::eResolveDestination: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
case ResourceState::ePresent: return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
case ResourceState::eUndefined: return VK_IMAGE_LAYOUT_UNDEFINED;
}
};
VkAccessFlags toVkAccessFlags(ResourceState state)
{
switch (state)
{
case ResourceState::eVertexBuffer: return VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
case ResourceState::eIndexBuffer: return VK_ACCESS_INDEX_READ_BIT;
case ResourceState::eConstantBuffer: return VK_ACCESS_UNIFORM_READ_BIT;
case ResourceState::eArgumentBuffer: return VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
case ResourceState::eTextureRead: return VK_ACCESS_SHADER_READ_BIT;
case ResourceState::eStorageRead: return VK_ACCESS_SHADER_READ_BIT;
case ResourceState::eStorageWrite: return VK_ACCESS_SHADER_WRITE_BIT;
case ResourceState::eStorageRW: return VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
case ResourceState::eColorAttachmentRead: return VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
case ResourceState::eColorAttachmentWrite: return VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
case ResourceState::eColorAttachmentRW: return VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
case ResourceState::eDepthStencilAttachmentRead: return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
case ResourceState::eDepthStencilAttachmentWrite: return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
case ResourceState::eDepthStencilAttachmentRW: return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
case ResourceState::eCopySource: return VK_ACCESS_TRANSFER_READ_BIT;
case ResourceState::eCopyDestination: return VK_ACCESS_TRANSFER_WRITE_BIT;
case ResourceState::eAccelStructRead: return VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR;
case ResourceState::eAccelStructWrite: return VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR;
case ResourceState::eResolveSource: return VK_ACCESS_TRANSFER_READ_BIT;
case ResourceState::eResolveDestination: return VK_ACCESS_TRANSFER_WRITE_BIT;
default: return 0;
}
}
VkImageAspectFlags toVkAspectFlags(uint32_t nativeFormat, bool isImageViewForTexture, bool isImageViewTypeStencil)
{
switch (nativeFormat)
{
case VK_FORMAT_D16_UNORM:
case VK_FORMAT_X8_D24_UNORM_PACK32:
case VK_FORMAT_D32_SFLOAT:
return VK_IMAGE_ASPECT_DEPTH_BIT;
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
// VUID - VkDescriptorImageInfo - imageView - 01976: If imageView is created from a depth / stencil image, the aspectMask used to create the imageView must include
// either VK_IMAGE_ASPECT_DEPTH_BIT or VK_IMAGE_ASPECT_STENCIL_BIT but not both.
return isImageViewForTexture ? (isImageViewTypeStencil ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT) : (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT);
case VK_FORMAT_S8_UINT: return VK_IMAGE_ASPECT_STENCIL_BIT;
default: return VK_IMAGE_ASPECT_COLOR_BIT;
}
}
DispatchData::~DispatchData()
{
assert(pddt != nullptr && device != NULL);
if (pddt != nullptr && device != NULL)
{
for (auto&[bindingDesc, poolDescCombo] : signatureToDesc)
{
if (bindingDesc != nullptr)
{
poolDescCombo.descSetData.descSet.clear();
poolDescCombo.descSetData = {};
pddt->DestroyDescriptorPool(device, poolDescCombo.pool, nullptr);
}
}
}
signatureToDesc.clear();
assert(compute != nullptr);
for (auto&[pso, bindingDesc] : psoToSignature)
{
if (bindingDesc != nullptr)
{
if (compute != nullptr)
{
for (auto& descriptor : bindingDesc->descriptors)
{
if (descriptor.second.type == DescriptorType::eConstantBuffer)
{
for (auto& handle : descriptor.second.handles)
{
if (handle != nullptr)
{
compute->destroyResource(reinterpret_cast<Resource>(handle), 0);
}
}
}
}
}
delete bindingDesc;
}
}
psoToSignature.clear();
}
ComputeStatus Vulkan::getResourceState(uint32_t states, ResourceState& resourceStates)
{
switch (states)
{
case VK_IMAGE_LAYOUT_UNDEFINED:
resourceStates = ResourceState::eUndefined;
break;
default:
case VK_IMAGE_LAYOUT_GENERAL:
resourceStates = ResourceState::eGeneral;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
resourceStates = ResourceState::eColorAttachmentRW;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL:
case VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL:
resourceStates = ResourceState::eDepthStencilAttachmentRW;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL:
case VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL:
resourceStates = ResourceState::eDepthStencilAttachmentRead;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
resourceStates = ResourceState::eTextureRead;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
resourceStates = ResourceState::eCopySource;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
resourceStates = ResourceState::eCopyDestination;
break;
case VK_IMAGE_LAYOUT_PREINITIALIZED:
resourceStates = ResourceState::eGenericRead;
break;
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
case VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR:
resourceStates = ResourceState::ePresent;
break;
}
return ComputeStatus::eOk;
}
ComputeStatus Vulkan::getNativeResourceState(ResourceState states, uint32_t& resourceStates)
{
resourceStates = toVkImageLayout(states);
return ComputeStatus::eOk;
}
VkImageUsageFlags toVkImageUsageFlags(ResourceFlags usageFlags)
{
VkImageUsageFlags flags = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
if (usageFlags & ResourceFlags::eShaderResource)
{
flags |= VK_IMAGE_USAGE_SAMPLED_BIT;
}
if (usageFlags & ResourceFlags::eShaderResourceStorage)
{
flags |= VK_IMAGE_USAGE_STORAGE_BIT;
}
if (usageFlags & ResourceFlags::eColorAttachment)
{
flags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
}
if (usageFlags & ResourceFlags::eDepthStencilAttachment)
{
flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
}
return flags;
}
VKAPI_ATTR VkBool32 VKAPI_CALL debugUtilsMessengerCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData)
{
if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
}
else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
}
else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
//std::string s(pCallbackData->pMessage);
//std::replace(s.begin(), s.end(), '%', ' ');
//SL_LOG_WARN(s.c_str());
}
else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
//assert(0x1608dec0 != pCallbackData->messageIdNumber);
// 0x3936bc0c - barrier validation - cannot issue barrier within renderpass
// 0xd3c27d87 - barrier validation - cannot issue clear image within renderpass
// 0x1608dec0 - donut error cmdDraw
std::vector<uint32_t> s_disable = { 0x3936bc0c, 0xd3c27d87, 0x1608dec0, 0xb50452b0, 0x1e8b83b0, 0xe825f293, 0x3cf4c632, 0x15559cd5 };
if (std::find(s_disable.begin(), s_disable.end(), pCallbackData->messageIdNumber) == s_disable.end())
{
SL_LOG_ERROR( pCallbackData->pMessage);
}
}
// The return value of this callback controls whether the Vulkan call that caused the validation message will be aborted or not
// We return VK_FALSE as we DON'T want Vulkan calls that cause a validation message to abort
// If you instead want to have calls abort, pass in VK_TRUE and the function will return VK_ERROR_VALIDATION_FAILED_EXT
return VK_FALSE;
}
ComputeStatus Vulkan::init(Device device, param::IParameters* params)
{
void ** deviceArray = (void**)device;
m_instance = (VkInstance)deviceArray[0];
m_device = (VkDevice)deviceArray[1];
m_physicalDevice = (VkPhysicalDevice)deviceArray[2];
#ifdef SL_WITH_NVLLVK
m_reflex = CreateNvLowLatencyVk(m_device, params);
#else
#error "Not implemented"
#endif
// For callbacks we just need VkDevice
Generic::init(m_device, params);