-
Notifications
You must be signed in to change notification settings - Fork 13
/
vulkan.c
1603 lines (1392 loc) · 52.3 KB
/
vulkan.c
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 © 2019 nyorain
*
* 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 (including the next
* paragraph) 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.
*
* Author: nyorain <[email protected]>
*/
#include "kms-quads.h"
#include <vulkan/vulkan.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <math.h>
#include <vulkan.frag.h>
#include <vulkan.vert.h>
// This corresponds to the XRGB drm format.
// The egl format hardcodes this format so we can probably too.
// It's guaranteed to be supported by the vulkan spec for everything
// we need. SRGB is the correct choice here, as always. You'd see
// that when rendering a texture.
static const VkFormat format = VK_FORMAT_B8G8R8A8_SRGB;
struct vk_device {
VkInstance instance;
VkDebugUtilsMessengerEXT messenger;
// whether the required extensions for explicit fencing are supported
bool explicit_fencing;
struct {
PFN_vkCreateDebugUtilsMessengerEXT createDebugUtilsMessengerEXT;
PFN_vkDestroyDebugUtilsMessengerEXT destroyDebugUtilsMessengerEXT;
PFN_vkGetMemoryFdPropertiesKHR getMemoryFdPropertiesKHR;
PFN_vkGetSemaphoreFdKHR getSemaphoreFdKHR;
PFN_vkImportSemaphoreFdKHR importSemaphoreFdKHR;
} api;
VkPhysicalDevice phdev;
VkDevice dev;
uint32_t queue_family;
VkQueue queue;
// pipeline
VkDescriptorSetLayout ds_layout;
VkRenderPass rp;
VkPipelineLayout pipe_layout;
VkPipeline pipe;
VkCommandPool command_pool;
VkDescriptorPool ds_pool;
};
struct vk_image {
struct buffer buffer;
VkDeviceMemory memories[4]; // worst case: 4 planes, 4 memory objects
VkImage image;
VkImageView image_view;
VkCommandBuffer cb;
VkFramebuffer fb;
bool first;
VkBuffer ubo;
VkDeviceMemory ubo_mem;
void *ubo_map;
VkDescriptorSet ds;
// We have to use a semaphore here since we want to "wait for it
// on the device" (i.e. only start rendering when the semaphore
// is signaled) and that isn't possible with a fence.
VkSemaphore buffer_semaphore; // signaled by kernal when image can be reused
// vulkan can signal a semaphore and a fence when a command buffer
// has completed, so we can use either here without any significant
// difference (the exporting semantics are the same for both).
VkSemaphore render_semaphore; // signaled by vulkan when rendering finishes
// We don't need this theoretically. But the validation layers
// are happy if we signal them via this fence that execution
// has finished.
VkFence render_fence; // signaled by vulkan when rendering finishes
};
// #define vk_error(res, fmt, ...)
#define vk_error(res, fmt) error(fmt ": %s (%d)\n", vulkan_strerror(res), res)
// Returns a VkResult value as string.
static const char *vulkan_strerror(VkResult err) {
#define ERR_STR(r) case VK_ ##r: return #r
switch (err) {
ERR_STR(SUCCESS);
ERR_STR(NOT_READY);
ERR_STR(TIMEOUT);
ERR_STR(EVENT_SET);
ERR_STR(EVENT_RESET);
ERR_STR(INCOMPLETE);
ERR_STR(SUBOPTIMAL_KHR);
ERR_STR(ERROR_OUT_OF_HOST_MEMORY);
ERR_STR(ERROR_OUT_OF_DEVICE_MEMORY);
ERR_STR(ERROR_INITIALIZATION_FAILED);
ERR_STR(ERROR_DEVICE_LOST);
ERR_STR(ERROR_MEMORY_MAP_FAILED);
ERR_STR(ERROR_LAYER_NOT_PRESENT);
ERR_STR(ERROR_EXTENSION_NOT_PRESENT);
ERR_STR(ERROR_FEATURE_NOT_PRESENT);
ERR_STR(ERROR_INCOMPATIBLE_DRIVER);
ERR_STR(ERROR_TOO_MANY_OBJECTS);
ERR_STR(ERROR_FORMAT_NOT_SUPPORTED);
ERR_STR(ERROR_SURFACE_LOST_KHR);
ERR_STR(ERROR_NATIVE_WINDOW_IN_USE_KHR);
ERR_STR(ERROR_OUT_OF_DATE_KHR);
ERR_STR(ERROR_FRAGMENTED_POOL);
ERR_STR(ERROR_INCOMPATIBLE_DISPLAY_KHR);
ERR_STR(ERROR_VALIDATION_FAILED_EXT);
ERR_STR(ERROR_INVALID_EXTERNAL_HANDLE);
ERR_STR(ERROR_OUT_OF_POOL_MEMORY);
ERR_STR(ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT);
default:
return "<unknown>";
}
#undef ERR_STR
}
static VkImageAspectFlagBits mem_plane_ascpect(unsigned i)
{
switch(i) {
case 0: return VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT;
case 1: return VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT;
case 2: return VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT;
case 3: return VK_IMAGE_ASPECT_MEMORY_PLANE_3_BIT_EXT;
default: assert(false); // unreachable
}
}
int find_mem_type(VkPhysicalDevice phdev,
VkMemoryPropertyFlags flags, uint32_t req_bits)
{
VkPhysicalDeviceMemoryProperties props;
vkGetPhysicalDeviceMemoryProperties(phdev, &props);
for (unsigned i = 0u; i < props.memoryTypeCount; ++i) {
if (req_bits & (1 << i)) {
if ((props.memoryTypes[i].propertyFlags & flags) == flags) {
return i;
}
}
}
return -1;
}
static bool has_extension(const VkExtensionProperties *avail,
uint32_t availc, const char *req)
{
// check if all required extensions are supported
for (size_t j = 0; j < availc; ++j) {
if (!strcmp(avail[j].extensionName, req)) {
return true;
}
}
return false;
}
static VkBool32 debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
VkDebugUtilsMessageTypeFlagsEXT type,
const VkDebugUtilsMessengerCallbackDataEXT *debug_data,
void *data) {
((void) data);
((void) type);
// we ignore some of the non-helpful warnings
// static const char *const ignored[] = {};
// if (debug_data->pMessageIdName) {
// for (unsigned i = 0; i < sizeof(ignored) / sizeof(ignored[0]); ++i) {
// if (!strcmp(debug_data->pMessageIdName, ignored[i])) {
// return false;
// }
// }
// }
const char* importance = "UNKNOWN";
switch(severity) {
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
importance = "ERROR";
break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
importance = "WARNING";
break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
importance = "INFO";
break;
default:
break;
}
debug("%s: %s (%s, %d)\n", importance, debug_data->pMessage,
debug_data->pMessageIdName, debug_data->messageIdNumber);
if (debug_data->queueLabelCount > 0) {
const char *name = debug_data->pQueueLabels[0].pLabelName;
if (name) {
debug(" last queue label '%s'\n", name);
}
}
if (debug_data->cmdBufLabelCount > 0) {
const char *name = debug_data->pCmdBufLabels[0].pLabelName;
if (name) {
debug(" last cmdbuf label '%s'\n", name);
}
}
for (unsigned i = 0; i < debug_data->objectCount; ++i) {
if (debug_data->pObjects[i].pObjectName) {
debug(" involving '%s'\n", debug_data->pMessage);
}
}
// Returning true not allowed by spec but helpful for debugging
// makes function that caused the error return validation_failed
// error which we can detect
// return true;
return false;
}
// Returns whether the given drm device pci info matches the given physical
// device. Will write/realloc the given extensions count and data of
// the queried physical device.
bool match(drmPciBusInfoPtr pci_bus_info, VkPhysicalDevice phdev,
uint32_t *extc, VkExtensionProperties **exts)
{
VkResult res;
res = vkEnumerateDeviceExtensionProperties(phdev, NULL,
extc, NULL);
if ((res != VK_SUCCESS) || (*extc == 0)) {
*extc = 0;
vk_error(res, "Could not enumerate device extensions (1)");
return false;
}
*exts = realloc(*exts, sizeof(**exts) * *extc);
res = vkEnumerateDeviceExtensionProperties(phdev, NULL,
extc, *exts);
if (res != VK_SUCCESS) {
vk_error(res, "Could not enumerate device extensions (2)");
return false;
}
if (!has_extension(*exts, *extc, VK_EXT_PCI_BUS_INFO_EXTENSION_NAME)) {
error("Physical device has not support for VK_EXT_pci_bus_info\n");
return false;
}
VkPhysicalDevicePCIBusInfoPropertiesEXT pci_props = {0};
pci_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT;
VkPhysicalDeviceProperties2 phdev_props = {0};
phdev_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
phdev_props.pNext = &pci_props;
vkGetPhysicalDeviceProperties2(phdev, &phdev_props);
bool match = pci_props.pciBus == pci_bus_info->bus &&
pci_props.pciDevice == pci_bus_info->dev &&
pci_props.pciDomain == pci_bus_info->domain &&
pci_props.pciFunction == pci_bus_info->func;
VkPhysicalDeviceProperties *props = &phdev_props.properties;
uint32_t vv_major = (props->apiVersion >> 22);
uint32_t vv_minor = (props->apiVersion >> 12) & 0x3ff;
uint32_t vv_patch = (props->apiVersion) & 0xfff;
uint32_t dv_major = (props->driverVersion >> 22);
uint32_t dv_minor = (props->driverVersion >> 12) & 0x3ff;
uint32_t dv_patch = (props->driverVersion) & 0xfff;
const char* dev_type = "unknown";
switch(props->deviceType) {
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
dev_type = "integrated";
break;
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
dev_type = "discrete";
break;
case VK_PHYSICAL_DEVICE_TYPE_CPU:
dev_type = "cpu";
break;
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
dev_type = "gpu";
break;
default:
break;
}
debug("Vulkan device: '%s'\n", props->deviceName);
debug(" Device type: '%s'\n", dev_type);
debug(" Supported API version: %u.%u.%u\n", vv_major, vv_minor, vv_patch);
debug(" Driver version: %u.%u.%u\n", dv_major, dv_minor, dv_patch);
debug(" match: %d\n", (int) match);
return match;
}
void vk_device_destroy(struct vk_device *device)
{
if (device->pipe) {
vkDestroyPipeline(device->dev, device->pipe, NULL);
}
if (device->rp) {
vkDestroyRenderPass(device->dev, device->rp, NULL);
}
if (device->pipe_layout) {
vkDestroyPipelineLayout(device->dev, device->pipe_layout, NULL);
}
if (device->command_pool) {
vkDestroyCommandPool(device->dev, device->command_pool, NULL);
}
if (device->ds_layout) {
vkDestroyDescriptorSetLayout(device->dev, device->ds_layout, NULL);
}
if (device->ds_pool) {
vkDestroyDescriptorPool(device->dev, device->ds_pool, NULL);
}
if (device->dev) {
vkDestroyDevice(device->dev, NULL);
}
if (device->messenger && device->api.destroyDebugUtilsMessengerEXT) {
device->api.destroyDebugUtilsMessengerEXT(device->instance,
device->messenger, NULL);
}
if (device->instance) {
vkDestroyInstance(device->instance, NULL);
}
free(device);
}
static bool init_pipeline(struct vk_device *dev)
{
// render pass
// We don't care about previous contents of the image since
// we always render the full image. For incremental presentation you
// have to use LOAD_OP_STORE and a valid image layout.
VkAttachmentDescription attachment = {0};
attachment.format = format;
attachment.samples = VK_SAMPLE_COUNT_1_BIT;
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
// attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
// can basically be anything since we have to manually transition
// the image afterwards anyways (see depdency reasoning below)
attachment.finalLayout = VK_IMAGE_LAYOUT_GENERAL;
VkAttachmentReference color_ref = {0};
color_ref.attachment = 0u;
color_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass = {0};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color_ref;
// Note how we don't specify any (external) subpass dependencies.
// The transfer of an image to an external queue (i.e. transfer logical
// ownership of the image from the vulkan driver to drm) can't be represented
// as a subpass dependency, so we have to transition the image
// after and before a renderpass manually anyways.
VkRenderPassCreateInfo rp_info = {0};
rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
rp_info.attachmentCount = 1;
rp_info.pAttachments = &attachment;
rp_info.subpassCount = 1;
rp_info.pSubpasses = &subpass;
VkResult res = vkCreateRenderPass(dev->dev, &rp_info, NULL, &dev->rp);
if (res != VK_SUCCESS) {
vk_error(res, "vkCreateRenderPass");
return false;
}
// pipeline layout
VkDescriptorSetLayoutBinding binding = {0};
binding.binding = 0;
binding.descriptorCount = 1;
binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
VkDescriptorSetLayoutCreateInfo dli = {0};
dli.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
dli.bindingCount = 1u;
dli.pBindings = &binding;
res = vkCreateDescriptorSetLayout(dev->dev, &dli, NULL, &dev->ds_layout);
if (res != VK_SUCCESS) {
vk_error(res, "vkCreateDescriptorSetLayout");
return false;
}
VkPipelineLayoutCreateInfo pli = {0};
pli.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pli.setLayoutCount = 1;
pli.pSetLayouts = &dev->ds_layout;
res = vkCreatePipelineLayout(dev->dev, &pli, NULL, &dev->pipe_layout);
if (res != VK_SUCCESS) {
vk_error(res, "vkCreatePipelineLayout");
return false;
}
// pipeline
VkShaderModule vert_module;
VkShaderModule frag_module;
VkShaderModuleCreateInfo si = {0};
si.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
si.codeSize = sizeof(vulkan_vert_data);
si.pCode = vulkan_vert_data;
res = vkCreateShaderModule(dev->dev, &si, NULL, &vert_module);
if (res != VK_SUCCESS) {
vk_error(res, "Failed to create vertex shader module");
return false;
}
si.codeSize = sizeof(vulkan_frag_data);
si.pCode = vulkan_frag_data;
res = vkCreateShaderModule(dev->dev, &si, NULL, &frag_module);
if (res != VK_SUCCESS) {
vk_error(res, "Failed to create fragment shader module");
vkDestroyShaderModule(dev->dev, vert_module, NULL);
return false;
}
VkPipelineShaderStageCreateInfo pipe_stages[2] = {{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
NULL, 0, VK_SHADER_STAGE_VERTEX_BIT, vert_module, "main", NULL
}, {
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
NULL, 0, VK_SHADER_STAGE_FRAGMENT_BIT, frag_module, "main", NULL
}
};
// info
VkPipelineInputAssemblyStateCreateInfo assembly = {0};
assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN;
VkPipelineRasterizationStateCreateInfo rasterization = {0};
rasterization.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterization.polygonMode = VK_POLYGON_MODE_FILL;
rasterization.cullMode = VK_CULL_MODE_NONE;
rasterization.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterization.lineWidth = 1.f;
VkPipelineColorBlendAttachmentState blend_attachment = {0};
blend_attachment.blendEnable = false;
blend_attachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT |
VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT;
VkPipelineColorBlendStateCreateInfo blend = {0};
blend.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
blend.attachmentCount = 1;
blend.pAttachments = &blend_attachment;
VkPipelineMultisampleStateCreateInfo multisample = {0};
multisample.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineViewportStateCreateInfo viewport = {0};
viewport.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewport.viewportCount = 1;
viewport.scissorCount = 1;
VkDynamicState dynStates[2] = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR,
};
VkPipelineDynamicStateCreateInfo dynamic = {0};
dynamic.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamic.pDynamicStates = dynStates;
dynamic.dynamicStateCount = 2;
VkPipelineVertexInputStateCreateInfo vertex = {0};
vertex.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
VkGraphicsPipelineCreateInfo pipe_info = {0};
pipe_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipe_info.layout = dev->pipe_layout;
pipe_info.renderPass = dev->rp;
pipe_info.subpass = 0;
pipe_info.stageCount = 2;
pipe_info.pStages = pipe_stages;
pipe_info.pInputAssemblyState = &assembly;
pipe_info.pRasterizationState = &rasterization;
pipe_info.pColorBlendState = &blend;
pipe_info.pMultisampleState = &multisample;
pipe_info.pViewportState = &viewport;
pipe_info.pDynamicState = &dynamic;
pipe_info.pVertexInputState = &vertex;
// could use a cache here for faster loading
VkPipelineCache cache = VK_NULL_HANDLE;
res = vkCreateGraphicsPipelines(dev->dev, cache, 1, &pipe_info,
NULL, &dev->pipe);
vkDestroyShaderModule(dev->dev, vert_module, NULL);
vkDestroyShaderModule(dev->dev, frag_module, NULL);
if (res != VK_SUCCESS) {
error("failed to create vulkan pipeline: %d\n", res);
return false;
}
return true;
}
struct vk_device *vk_device_create(struct device *device)
{
// check for drm device support
// vulkan requires modifier support to import dma bufs
if (!device->fb_modifiers) {
debug("Can't use vulkan since drm doesn't support modifiers\n");
return NULL;
}
// query extension support
uint32_t avail_extc = 0;
VkResult res;
res = vkEnumerateInstanceExtensionProperties(NULL, &avail_extc, NULL);
if ((res != VK_SUCCESS) || (avail_extc == 0)) {
vk_error(res, "Could not enumerate instance extensions (1)");
return NULL;
}
VkExtensionProperties *avail_exts = calloc(avail_extc, sizeof(*avail_exts));
res = vkEnumerateInstanceExtensionProperties(NULL, &avail_extc, avail_exts);
if (res != VK_SUCCESS) {
free(avail_exts);
vk_error(res, "Could not enumerate instance extensions (2)");
return NULL;
}
for (size_t j = 0; j < avail_extc; ++j) {
debug("Vulkan Instance extensions %s\n", avail_exts[j].extensionName);
}
struct vk_device *vk_dev = calloc(1, sizeof(*vk_dev));
assert(vk_dev);
// create instance
const char *req = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
const char** enable_exts = NULL;
uint32_t enable_extc = 0;
if (has_extension(avail_exts, avail_extc, req)) {
enable_exts = &req;
enable_extc++;
}
free(avail_exts);
VkApplicationInfo application_info = {0};
application_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
application_info.pApplicationName = "kms-vulkan";
application_info.applicationVersion = 1;
application_info.pEngineName = "kms-vulkan";
application_info.engineVersion = 1;
// will only run on the latest drivers anyways so we can require
// vulkan 1.1 without problems
application_info.apiVersion = VK_MAKE_VERSION(1,1,0);
// layer reports error in api usage to debug callback
const char *layers[] = {
"VK_LAYER_KHRONOS_validation",
};
VkInstanceCreateInfo instance_info = {0};
instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instance_info.pApplicationInfo = &application_info;
instance_info.enabledExtensionCount = enable_extc;
instance_info.ppEnabledExtensionNames = enable_exts;
instance_info.enabledLayerCount = ARRAY_LENGTH(layers);
instance_info.ppEnabledLayerNames = layers;
res = vkCreateInstance(&instance_info, NULL, &vk_dev->instance);
if (res != VK_SUCCESS) {
vk_error(res, "Could not create instance");
goto error;
}
// debug callback
if (enable_extc) {
vk_dev->api.createDebugUtilsMessengerEXT =
(PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(
vk_dev->instance, "vkCreateDebugUtilsMessengerEXT");
vk_dev->api.destroyDebugUtilsMessengerEXT =
(PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(
vk_dev->instance, "vkDestroyDebugUtilsMessengerEXT");
if (vk_dev->api.createDebugUtilsMessengerEXT) {
VkDebugUtilsMessageSeverityFlagsEXT severity =
// VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
VkDebugUtilsMessageTypeFlagsEXT types =
// VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
VkDebugUtilsMessengerCreateInfoEXT debug_info = {0};
debug_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
debug_info.messageSeverity = severity;
debug_info.messageType = types;
debug_info.pfnUserCallback = &debug_callback;
vk_dev->api.createDebugUtilsMessengerEXT(vk_dev->instance,
&debug_info, NULL, &vk_dev->messenger);
} else {
error("vkCreateDebugUtilsMessengerEXT not found\n");
}
}
// get pci information of device
drmDevicePtr drm_dev;
drmGetDevice(device->kms_fd, &drm_dev);
if(drm_dev->bustype != DRM_BUS_PCI) {
error("Given device isn't a pci device\n");
goto error;
}
// enumerate physical devices to find the one matching the given
// gbm device.
uint32_t num_phdevs;
res = vkEnumeratePhysicalDevices(vk_dev->instance, &num_phdevs, NULL);
if (res != VK_SUCCESS || num_phdevs == 0) {
vk_error(res, "Could not retrieve physical device");
goto error;
}
VkPhysicalDevice *phdevs = calloc(num_phdevs, sizeof(*phdevs));
res = vkEnumeratePhysicalDevices(vk_dev->instance, &num_phdevs, phdevs);
if (res != VK_SUCCESS || num_phdevs == 0) {
free(phdevs);
vk_error(res, "Could not retrieve physical device");
goto error;
}
drmPciBusInfoPtr pci = drm_dev->businfo.pci;
debug("PCI bus: %04x:%02x:%02x.%x\n", pci->domain,
pci->bus, pci->dev, pci->func);
VkExtensionProperties *phdev_exts = NULL;
uint32_t phdev_extc = 0;
VkPhysicalDevice phdev = VK_NULL_HANDLE;
for (unsigned i = 0u; i < num_phdevs; ++i) {
VkPhysicalDevice phdevi = phdevs[i];
if (match(drm_dev->businfo.pci, phdevi, &phdev_extc, &phdev_exts)) {
phdev = phdevi;
break;
}
}
free(phdevs);
if (phdev == VK_NULL_HANDLE) {
error("Can't find vulkan physical device for drm dev\n");
goto error;
}
for (size_t j = 0; j < phdev_extc; ++j) {
debug("Vulkan Device extensions %s\n", phdev_exts[j].extensionName);
}
vk_dev->phdev = phdev;
// query extensions
const char* dev_exts[8];
uint32_t dev_extc = 0;
const char* mem_exts[] = {
VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME,
VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME,
VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME,
VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME, // required by drm ext
// NOTE: strictly speaking this extension is required to
// correctly transfer image ownership but since no mesa
// driver implements its yet (no even an updated patch for that),
// let's see how far we get without it
// VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME,
};
for (unsigned i = 0u; i < ARRAY_LENGTH(mem_exts); ++i) {
if (!has_extension(phdev_exts, phdev_extc, mem_exts[i])) {
error("Physical device doesn't supported required extension: %s\n",
mem_exts[i]);
goto error;
} else {
dev_exts[dev_extc++] = mem_exts[i];
}
}
// explicit fencing extensions
// we currently only import/export semaphores
vk_dev->explicit_fencing = true;
const char* sync_exts[] = {
// VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME,
VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME,
};
for (unsigned i = 0u; i < ARRAY_LENGTH(sync_exts); ++i) {
if (!has_extension(phdev_exts, phdev_extc, sync_exts[i])) {
error("Physical device doesn't supported extension %s, which "
"is required for explicit fencing. Will disable explicit "
"fencing but that is a suboptimal workaround",
dev_exts[i]);
vk_dev->explicit_fencing = false;
break;
} else {
dev_exts[dev_extc++] = sync_exts[i];
}
}
// create device
// queue families
uint32_t qfam_count;
vkGetPhysicalDeviceQueueFamilyProperties(phdev, &qfam_count, NULL);
VkQueueFamilyProperties *qprops = calloc(sizeof(*qprops), qfam_count);
vkGetPhysicalDeviceQueueFamilyProperties(phdev, &qfam_count, qprops);
uint32_t qfam = 0xFFFFFFFFu; // graphics queue family
for (unsigned i = 0u; i < qfam_count; ++i) {
if (qprops[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
qfam = i;
break;
}
}
// vulkan standard guarantees that the must be at least one graphics
// queue family
assert(qfam != 0xFFFFFFFFu);
vk_dev->queue_family = qfam;
// info
float prio = 1.f;
VkDeviceQueueCreateInfo qinfo = {0};
qinfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
qinfo.queueFamilyIndex = qfam;
qinfo.queueCount = 1;
qinfo.pQueuePriorities = &prio;
VkDeviceCreateInfo dev_info = {0};
dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
dev_info.queueCreateInfoCount = 1;
dev_info.pQueueCreateInfos = &qinfo;
dev_info.enabledExtensionCount = dev_extc;
dev_info.ppEnabledExtensionNames = dev_exts;
res = vkCreateDevice(phdev, &dev_info, NULL, &vk_dev->dev);
if (res != VK_SUCCESS){
vk_error(res, "Failed to create vulkan device");
goto error;
}
vkGetDeviceQueue(vk_dev->dev, vk_dev->queue_family, 0, &vk_dev->queue);
// command pool
VkCommandPoolCreateInfo cpi = {0};
cpi.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
cpi.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
cpi.queueFamilyIndex = vk_dev->queue_family;
res = vkCreateCommandPool(vk_dev->dev, &cpi, NULL, &vk_dev->command_pool);
if (res != VK_SUCCESS) {
vk_error(res, "vkCreateCommandPool");
goto error;
}
// descriptor pool
VkDescriptorPoolSize pool_size = {0};
pool_size.descriptorCount = BUFFER_QUEUE_DEPTH;
pool_size.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
VkDescriptorPoolCreateInfo dpi = {0};
dpi.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
dpi.maxSets = BUFFER_QUEUE_DEPTH;
dpi.poolSizeCount = 1u;
dpi.pPoolSizes = &pool_size;
res = vkCreateDescriptorPool(vk_dev->dev, &dpi, NULL, &vk_dev->ds_pool);
if (res != VK_SUCCESS) {
vk_error(res, "vkCreateDescriptorPool");
goto error;
}
if (vk_dev->explicit_fencing) {
// semaphore import/export support
// we import kms_fence_fd as semaphore and add that as wait semaphore
// to a render submission so that we only render a buffer when
// kms signals that it's finished with it.
// we alos export the semaphore for our render submission as sync_fd
// and pass that as render_fence_fd to the kernel, signaling
// that the buffer can only be used when that semaphore is signaled,
// i.e. we are finished with rendering and all barriers.
VkPhysicalDeviceExternalSemaphoreInfo esi = {0};
esi.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO;
esi.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
VkExternalSemaphoreProperties esp = {0};
esp.sType = VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES;
vkGetPhysicalDeviceExternalSemaphoreProperties(phdev, &esi, &esp);
if((esp.externalSemaphoreFeatures &
VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT) == 0) {
error("Vulkan can't import sync_fd semaphores");
goto error;
}
vk_dev->api.getSemaphoreFdKHR = (PFN_vkGetSemaphoreFdKHR)
vkGetDeviceProcAddr(vk_dev->dev, "vkGetSemaphoreFdKHR");
if (!vk_dev->api.getSemaphoreFdKHR) {
error("Failed to retrieve vkGetSemaphoreFdKHR\n");
vk_dev->explicit_fencing = false;
}
vk_dev->api.importSemaphoreFdKHR = (PFN_vkImportSemaphoreFdKHR)
vkGetDeviceProcAddr(vk_dev->dev, "vkImportSemaphoreFdKHR");
if (!vk_dev->api.importSemaphoreFdKHR) {
error("Failed to retrieve vkImportSemaphoreFdKHR\n");
vk_dev->explicit_fencing = false;
}
if (!vk_dev->explicit_fencing) {
printf("Disabling explicit fencing since not all required "
"functions could be loaded. Suboptimal workaround\n");
}
}
vk_dev->api.getMemoryFdPropertiesKHR = (PFN_vkGetMemoryFdPropertiesKHR)
vkGetDeviceProcAddr(vk_dev->dev, "vkGetMemoryFdPropertiesKHR");
if (!vk_dev->api.getMemoryFdPropertiesKHR) {
error("Failed to retrieve required vkGetMemoryFdPropertiesKHR\n");
goto error;
}
// init renderpass and pipeline
if (!init_pipeline(vk_dev)) {
goto error;
}
device->vk_device = vk_dev;
return vk_dev;
error:
vk_device_destroy(vk_dev);
return NULL;
}
bool output_vulkan_setup(struct output *output)
{
struct vk_device *vk_dev = output->device->vk_device;
assert(vk_dev);
VkResult res;
// vulkan builds upon explicit fencing. The workaround with simply
// waiting until rendering has finished in case of no explicit
// fencing is suboptimal
if (!output->explicit_fencing) {
printf("Vulkan renderer: drm doesn't support explicit fencing "
"that means the renderer has to stall (bad)\n");
}
output->explicit_fencing &= vk_dev->explicit_fencing;
if (output->num_modifiers == 0) {
error("Output doesn't support any modifiers, vulkan requires modifiers");
return false;
}
// check format support
// we simply iterate over all the modifiers supported by drm (stored
// in output) and query with vulkan if the modifier can be used
// for rendering via vkGetPhysicalDeviceImageFormatProperties2.
// We are allowed to query it this way (even for modifiers the driver
// doesn't even know), the function will simply return format_not_supported
// when it doesn't support/know the modifier.
// - input -
VkPhysicalDeviceImageDrmFormatModifierInfoEXT modi = {0};
modi.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_DRM_FORMAT_MODIFIER_INFO_EXT;
VkPhysicalDeviceExternalImageFormatInfo efmti = {0};
efmti.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO;
efmti.pNext = &modi;
efmti.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
VkPhysicalDeviceImageFormatInfo2 fmti = {0};
fmti.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
fmti.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
fmti.type = VK_IMAGE_TYPE_2D;
fmti.format = format;
fmti.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
fmti.pNext = &efmti;
// - output -
VkExternalImageFormatProperties efmtp = {0};
efmtp.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES;
VkImageFormatProperties2 ifmtp = {0};
ifmtp.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
ifmtp.pNext = &efmtp;
// supported modifiers
uint32_t smod_count = 0;
uint64_t *smods = calloc(output->num_modifiers, sizeof(*smods));
assert(smods);
for(unsigned i = 0u; i < output->num_modifiers; ++i) {
uint64_t mod = output->modifiers[i];
modi.drmFormatModifier = mod;
res = vkGetPhysicalDeviceImageFormatProperties2(vk_dev->phdev,
&fmti, &ifmtp);
if (res == VK_ERROR_FORMAT_NOT_SUPPORTED) {
continue;
} else if (res != VK_SUCCESS) {
vk_error(res, "vkGetPhysicalDeviceImageFormatProperties2");
return false;
}
// we need dmabufs with the given format and modifier to be importable
// otherwise we can't use the modifier
if ((efmtp.externalMemoryProperties.externalMemoryFeatures &
VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT) == 0) {
debug("KMS modifier %lu not supported by vulkan (2)\n", mod);
continue;
}
smods[smod_count++] = mod;
debug("Vulkan and KMS support modifier %lu\n", mod);
// we could check/store ifmtp.maxExtent but it should
// be enough. Otherwise the gpu is connected to an output
// it can't power on full resolution
}
if (smod_count == 0) {
error("No modifier supported by kms and vulkan");
return false;
}
free(output->modifiers);
output->num_modifiers = smod_count;
output->modifiers = smods;
return true;
}
struct buffer *buffer_vk_create(struct device *device, struct output *output)
{
struct vk_image *img = calloc(1, sizeof(*img));
struct vk_device *vk_dev = device->vk_device;
assert(vk_dev);
uint32_t num_planes;
int dma_buf_fds[4] = {-1, -1, -1, -1};
VkResult res;
// fill buffer info
img->first = true;
img->buffer.output = output;
img->buffer.render_fence_fd = -1;
img->buffer.kms_fence_fd = -1;
img->buffer.format = DRM_FORMAT_XRGB8888;
img->buffer.width = output->mode.hdisplay;
img->buffer.height = output->mode.vdisplay;
uint32_t width = img->buffer.width;
uint32_t height = img->buffer.height;
// create gbm bo with modifiers supported by output and vulkan
img->buffer.gbm.bo = gbm_bo_create_with_modifiers(device->gbm_device,
width, height, DRM_FORMAT_XRGB8888,
output->modifiers, output->num_modifiers);
if (!img->buffer.gbm.bo) {
error("failed to create %u x %u BO\n", output->mode.hdisplay,