turnip: Add support for uniform texel buffers.
[mesa.git] / src / freedreno / vulkan / tu_device.c
1 /*
2 * Copyright © 2016 Red Hat.
3 * Copyright © 2016 Bas Nieuwenhuizen
4 *
5 * based in part on anv driver which is:
6 * Copyright © 2015 Intel Corporation
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice (including the next
16 * paragraph) shall be included in all copies or substantial portions of the
17 * Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 * DEALINGS IN THE SOFTWARE.
26 */
27
28 #include "tu_private.h"
29
30 #include <fcntl.h>
31 #include <libsync.h>
32 #include <stdbool.h>
33 #include <string.h>
34 #include <sys/mman.h>
35 #include <sys/sysinfo.h>
36 #include <unistd.h>
37 #include <xf86drm.h>
38
39 #include "compiler/glsl_types.h"
40 #include "util/debug.h"
41 #include "util/disk_cache.h"
42 #include "vk_format.h"
43 #include "vk_util.h"
44
45 #include "drm-uapi/msm_drm.h"
46
47 static int
48 tu_device_get_cache_uuid(uint16_t family, void *uuid)
49 {
50 uint32_t mesa_timestamp;
51 uint16_t f = family;
52 memset(uuid, 0, VK_UUID_SIZE);
53 if (!disk_cache_get_function_timestamp(tu_device_get_cache_uuid,
54 &mesa_timestamp))
55 return -1;
56
57 memcpy(uuid, &mesa_timestamp, 4);
58 memcpy((char *) uuid + 4, &f, 2);
59 snprintf((char *) uuid + 6, VK_UUID_SIZE - 10, "tu");
60 return 0;
61 }
62
63 static void
64 tu_get_driver_uuid(void *uuid)
65 {
66 memset(uuid, 0, VK_UUID_SIZE);
67 snprintf(uuid, VK_UUID_SIZE, "freedreno");
68 }
69
70 static void
71 tu_get_device_uuid(void *uuid)
72 {
73 memset(uuid, 0, VK_UUID_SIZE);
74 }
75
76 static VkResult
77 tu_bo_init(struct tu_device *dev,
78 struct tu_bo *bo,
79 uint32_t gem_handle,
80 uint64_t size)
81 {
82 uint64_t iova = tu_gem_info_iova(dev, gem_handle);
83 if (!iova)
84 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
85
86 *bo = (struct tu_bo) {
87 .gem_handle = gem_handle,
88 .size = size,
89 .iova = iova,
90 };
91
92 return VK_SUCCESS;
93 }
94
95 VkResult
96 tu_bo_init_new(struct tu_device *dev, struct tu_bo *bo, uint64_t size)
97 {
98 /* TODO: Choose better flags. As of 2018-11-12, freedreno/drm/msm_bo.c
99 * always sets `flags = MSM_BO_WC`, and we copy that behavior here.
100 */
101 uint32_t gem_handle = tu_gem_new(dev, size, MSM_BO_WC);
102 if (!gem_handle)
103 return vk_error(dev->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
104
105 VkResult result = tu_bo_init(dev, bo, gem_handle, size);
106 if (result != VK_SUCCESS) {
107 tu_gem_close(dev, gem_handle);
108 return vk_error(dev->instance, result);
109 }
110
111 return VK_SUCCESS;
112 }
113
114 VkResult
115 tu_bo_init_dmabuf(struct tu_device *dev,
116 struct tu_bo *bo,
117 uint64_t size,
118 int fd)
119 {
120 uint32_t gem_handle = tu_gem_import_dmabuf(dev, fd, size);
121 if (!gem_handle)
122 return vk_error(dev->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
123
124 VkResult result = tu_bo_init(dev, bo, gem_handle, size);
125 if (result != VK_SUCCESS) {
126 tu_gem_close(dev, gem_handle);
127 return vk_error(dev->instance, result);
128 }
129
130 return VK_SUCCESS;
131 }
132
133 int
134 tu_bo_export_dmabuf(struct tu_device *dev, struct tu_bo *bo)
135 {
136 return tu_gem_export_dmabuf(dev, bo->gem_handle);
137 }
138
139 VkResult
140 tu_bo_map(struct tu_device *dev, struct tu_bo *bo)
141 {
142 if (bo->map)
143 return VK_SUCCESS;
144
145 uint64_t offset = tu_gem_info_offset(dev, bo->gem_handle);
146 if (!offset)
147 return vk_error(dev->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
148
149 /* TODO: Should we use the wrapper os_mmap() like Freedreno does? */
150 void *map = mmap(0, bo->size, PROT_READ | PROT_WRITE, MAP_SHARED,
151 dev->physical_device->local_fd, offset);
152 if (map == MAP_FAILED)
153 return vk_error(dev->instance, VK_ERROR_MEMORY_MAP_FAILED);
154
155 bo->map = map;
156 return VK_SUCCESS;
157 }
158
159 void
160 tu_bo_finish(struct tu_device *dev, struct tu_bo *bo)
161 {
162 assert(bo->gem_handle);
163
164 if (bo->map)
165 munmap(bo->map, bo->size);
166
167 tu_gem_close(dev, bo->gem_handle);
168 }
169
170 static VkResult
171 tu_physical_device_init(struct tu_physical_device *device,
172 struct tu_instance *instance,
173 drmDevicePtr drm_device)
174 {
175 const char *path = drm_device->nodes[DRM_NODE_RENDER];
176 VkResult result = VK_SUCCESS;
177 drmVersionPtr version;
178 int fd;
179 int master_fd = -1;
180
181 fd = open(path, O_RDWR | O_CLOEXEC);
182 if (fd < 0) {
183 return vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
184 "failed to open device %s", path);
185 }
186
187 /* Version 1.3 added MSM_INFO_IOVA. */
188 const int min_version_major = 1;
189 const int min_version_minor = 3;
190
191 version = drmGetVersion(fd);
192 if (!version) {
193 close(fd);
194 return vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
195 "failed to query kernel driver version for device %s",
196 path);
197 }
198
199 if (strcmp(version->name, "msm")) {
200 drmFreeVersion(version);
201 close(fd);
202 return vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
203 "device %s does not use the msm kernel driver", path);
204 }
205
206 if (version->version_major != min_version_major ||
207 version->version_minor < min_version_minor) {
208 result = vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
209 "kernel driver for device %s has version %d.%d, "
210 "but Vulkan requires version >= %d.%d",
211 path, version->version_major, version->version_minor,
212 min_version_major, min_version_minor);
213 drmFreeVersion(version);
214 close(fd);
215 return result;
216 }
217
218 drmFreeVersion(version);
219
220 if (instance->debug_flags & TU_DEBUG_STARTUP)
221 tu_logi("Found compatible device '%s'.", path);
222
223 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
224 device->instance = instance;
225 assert(strlen(path) < ARRAY_SIZE(device->path));
226 strncpy(device->path, path, ARRAY_SIZE(device->path));
227
228 if (instance->enabled_extensions.KHR_display) {
229 master_fd =
230 open(drm_device->nodes[DRM_NODE_PRIMARY], O_RDWR | O_CLOEXEC);
231 if (master_fd >= 0) {
232 /* TODO: free master_fd is accel is not working? */
233 }
234 }
235
236 device->master_fd = master_fd;
237 device->local_fd = fd;
238
239 if (tu_drm_get_gpu_id(device, &device->gpu_id)) {
240 if (instance->debug_flags & TU_DEBUG_STARTUP)
241 tu_logi("Could not query the GPU ID");
242 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
243 "could not get GPU ID");
244 goto fail;
245 }
246
247 if (tu_drm_get_gmem_size(device, &device->gmem_size)) {
248 if (instance->debug_flags & TU_DEBUG_STARTUP)
249 tu_logi("Could not query the GMEM size");
250 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
251 "could not get GMEM size");
252 goto fail;
253 }
254
255 memset(device->name, 0, sizeof(device->name));
256 sprintf(device->name, "FD%d", device->gpu_id);
257
258 switch (device->gpu_id) {
259 case 630:
260 case 640:
261 device->tile_align_w = 64;
262 device->tile_align_h = 16;
263 break;
264 default:
265 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
266 "device %s is unsupported", device->name);
267 goto fail;
268 }
269 if (tu_device_get_cache_uuid(device->gpu_id, device->cache_uuid)) {
270 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
271 "cannot generate UUID");
272 goto fail;
273 }
274
275 /* The gpu id is already embedded in the uuid so we just pass "tu"
276 * when creating the cache.
277 */
278 char buf[VK_UUID_SIZE * 2 + 1];
279 disk_cache_format_hex_id(buf, device->cache_uuid, VK_UUID_SIZE * 2);
280 device->disk_cache = disk_cache_create(device->name, buf, 0);
281
282 fprintf(stderr, "WARNING: tu is not a conformant vulkan implementation, "
283 "testing use only.\n");
284
285 tu_get_driver_uuid(&device->device_uuid);
286 tu_get_device_uuid(&device->device_uuid);
287
288 tu_fill_device_extension_table(device, &device->supported_extensions);
289
290 if (result != VK_SUCCESS) {
291 vk_error(instance, result);
292 goto fail;
293 }
294
295 result = tu_wsi_init(device);
296 if (result != VK_SUCCESS) {
297 vk_error(instance, result);
298 goto fail;
299 }
300
301 return VK_SUCCESS;
302
303 fail:
304 close(fd);
305 if (master_fd != -1)
306 close(master_fd);
307 return result;
308 }
309
310 static void
311 tu_physical_device_finish(struct tu_physical_device *device)
312 {
313 tu_wsi_finish(device);
314
315 disk_cache_destroy(device->disk_cache);
316 close(device->local_fd);
317 if (device->master_fd != -1)
318 close(device->master_fd);
319 }
320
321 static void *
322 default_alloc_func(void *pUserData,
323 size_t size,
324 size_t align,
325 VkSystemAllocationScope allocationScope)
326 {
327 return malloc(size);
328 }
329
330 static void *
331 default_realloc_func(void *pUserData,
332 void *pOriginal,
333 size_t size,
334 size_t align,
335 VkSystemAllocationScope allocationScope)
336 {
337 return realloc(pOriginal, size);
338 }
339
340 static void
341 default_free_func(void *pUserData, void *pMemory)
342 {
343 free(pMemory);
344 }
345
346 static const VkAllocationCallbacks default_alloc = {
347 .pUserData = NULL,
348 .pfnAllocation = default_alloc_func,
349 .pfnReallocation = default_realloc_func,
350 .pfnFree = default_free_func,
351 };
352
353 static const struct debug_control tu_debug_options[] = {
354 { "startup", TU_DEBUG_STARTUP },
355 { "nir", TU_DEBUG_NIR },
356 { "ir3", TU_DEBUG_IR3 },
357 { "nobin", TU_DEBUG_NOBIN },
358 { NULL, 0 }
359 };
360
361 const char *
362 tu_get_debug_option_name(int id)
363 {
364 assert(id < ARRAY_SIZE(tu_debug_options) - 1);
365 return tu_debug_options[id].string;
366 }
367
368 static int
369 tu_get_instance_extension_index(const char *name)
370 {
371 for (unsigned i = 0; i < TU_INSTANCE_EXTENSION_COUNT; ++i) {
372 if (strcmp(name, tu_instance_extensions[i].extensionName) == 0)
373 return i;
374 }
375 return -1;
376 }
377
378 VkResult
379 tu_CreateInstance(const VkInstanceCreateInfo *pCreateInfo,
380 const VkAllocationCallbacks *pAllocator,
381 VkInstance *pInstance)
382 {
383 struct tu_instance *instance;
384 VkResult result;
385
386 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
387
388 uint32_t client_version;
389 if (pCreateInfo->pApplicationInfo &&
390 pCreateInfo->pApplicationInfo->apiVersion != 0) {
391 client_version = pCreateInfo->pApplicationInfo->apiVersion;
392 } else {
393 tu_EnumerateInstanceVersion(&client_version);
394 }
395
396 instance = vk_zalloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
397 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
398 if (!instance)
399 return vk_error(NULL, VK_ERROR_OUT_OF_HOST_MEMORY);
400
401 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
402
403 if (pAllocator)
404 instance->alloc = *pAllocator;
405 else
406 instance->alloc = default_alloc;
407
408 instance->api_version = client_version;
409 instance->physical_device_count = -1;
410
411 instance->debug_flags =
412 parse_debug_string(getenv("TU_DEBUG"), tu_debug_options);
413
414 if (instance->debug_flags & TU_DEBUG_STARTUP)
415 tu_logi("Created an instance");
416
417 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
418 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
419 int index = tu_get_instance_extension_index(ext_name);
420
421 if (index < 0 || !tu_supported_instance_extensions.extensions[index]) {
422 vk_free2(&default_alloc, pAllocator, instance);
423 return vk_error(instance, VK_ERROR_EXTENSION_NOT_PRESENT);
424 }
425
426 instance->enabled_extensions.extensions[index] = true;
427 }
428
429 result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
430 if (result != VK_SUCCESS) {
431 vk_free2(&default_alloc, pAllocator, instance);
432 return vk_error(instance, result);
433 }
434
435 glsl_type_singleton_init_or_ref();
436
437 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
438
439 *pInstance = tu_instance_to_handle(instance);
440
441 return VK_SUCCESS;
442 }
443
444 void
445 tu_DestroyInstance(VkInstance _instance,
446 const VkAllocationCallbacks *pAllocator)
447 {
448 TU_FROM_HANDLE(tu_instance, instance, _instance);
449
450 if (!instance)
451 return;
452
453 for (int i = 0; i < instance->physical_device_count; ++i) {
454 tu_physical_device_finish(instance->physical_devices + i);
455 }
456
457 VG(VALGRIND_DESTROY_MEMPOOL(instance));
458
459 glsl_type_singleton_decref();
460
461 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
462
463 vk_free(&instance->alloc, instance);
464 }
465
466 static VkResult
467 tu_enumerate_devices(struct tu_instance *instance)
468 {
469 /* TODO: Check for more devices ? */
470 drmDevicePtr devices[8];
471 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
472 int max_devices;
473
474 instance->physical_device_count = 0;
475
476 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
477
478 if (instance->debug_flags & TU_DEBUG_STARTUP)
479 tu_logi("Found %d drm nodes", max_devices);
480
481 if (max_devices < 1)
482 return vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
483
484 for (unsigned i = 0; i < (unsigned) max_devices; i++) {
485 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
486 devices[i]->bustype == DRM_BUS_PLATFORM) {
487
488 result = tu_physical_device_init(
489 instance->physical_devices + instance->physical_device_count,
490 instance, devices[i]);
491 if (result == VK_SUCCESS)
492 ++instance->physical_device_count;
493 else if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
494 break;
495 }
496 }
497 drmFreeDevices(devices, max_devices);
498
499 return result;
500 }
501
502 VkResult
503 tu_EnumeratePhysicalDevices(VkInstance _instance,
504 uint32_t *pPhysicalDeviceCount,
505 VkPhysicalDevice *pPhysicalDevices)
506 {
507 TU_FROM_HANDLE(tu_instance, instance, _instance);
508 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
509
510 VkResult result;
511
512 if (instance->physical_device_count < 0) {
513 result = tu_enumerate_devices(instance);
514 if (result != VK_SUCCESS && result != VK_ERROR_INCOMPATIBLE_DRIVER)
515 return result;
516 }
517
518 for (uint32_t i = 0; i < instance->physical_device_count; ++i) {
519 vk_outarray_append(&out, p)
520 {
521 *p = tu_physical_device_to_handle(instance->physical_devices + i);
522 }
523 }
524
525 return vk_outarray_status(&out);
526 }
527
528 VkResult
529 tu_EnumeratePhysicalDeviceGroups(
530 VkInstance _instance,
531 uint32_t *pPhysicalDeviceGroupCount,
532 VkPhysicalDeviceGroupProperties *pPhysicalDeviceGroupProperties)
533 {
534 TU_FROM_HANDLE(tu_instance, instance, _instance);
535 VK_OUTARRAY_MAKE(out, pPhysicalDeviceGroupProperties,
536 pPhysicalDeviceGroupCount);
537 VkResult result;
538
539 if (instance->physical_device_count < 0) {
540 result = tu_enumerate_devices(instance);
541 if (result != VK_SUCCESS && result != VK_ERROR_INCOMPATIBLE_DRIVER)
542 return result;
543 }
544
545 for (uint32_t i = 0; i < instance->physical_device_count; ++i) {
546 vk_outarray_append(&out, p)
547 {
548 p->physicalDeviceCount = 1;
549 p->physicalDevices[0] =
550 tu_physical_device_to_handle(instance->physical_devices + i);
551 p->subsetAllocation = false;
552 }
553 }
554
555 return vk_outarray_status(&out);
556 }
557
558 void
559 tu_GetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice,
560 VkPhysicalDeviceFeatures *pFeatures)
561 {
562 memset(pFeatures, 0, sizeof(*pFeatures));
563
564 *pFeatures = (VkPhysicalDeviceFeatures) {
565 .robustBufferAccess = false,
566 .fullDrawIndexUint32 = false,
567 .imageCubeArray = false,
568 .independentBlend = false,
569 .geometryShader = false,
570 .tessellationShader = false,
571 .sampleRateShading = false,
572 .dualSrcBlend = false,
573 .logicOp = false,
574 .multiDrawIndirect = false,
575 .drawIndirectFirstInstance = false,
576 .depthClamp = false,
577 .depthBiasClamp = false,
578 .fillModeNonSolid = false,
579 .depthBounds = false,
580 .wideLines = false,
581 .largePoints = false,
582 .alphaToOne = false,
583 .multiViewport = false,
584 .samplerAnisotropy = true,
585 .textureCompressionETC2 = true,
586 .textureCompressionASTC_LDR = true,
587 .textureCompressionBC = true,
588 .occlusionQueryPrecise = false,
589 .pipelineStatisticsQuery = false,
590 .vertexPipelineStoresAndAtomics = false,
591 .fragmentStoresAndAtomics = false,
592 .shaderTessellationAndGeometryPointSize = false,
593 .shaderImageGatherExtended = false,
594 .shaderStorageImageExtendedFormats = false,
595 .shaderStorageImageMultisample = false,
596 .shaderUniformBufferArrayDynamicIndexing = false,
597 .shaderSampledImageArrayDynamicIndexing = false,
598 .shaderStorageBufferArrayDynamicIndexing = false,
599 .shaderStorageImageArrayDynamicIndexing = false,
600 .shaderStorageImageReadWithoutFormat = false,
601 .shaderStorageImageWriteWithoutFormat = false,
602 .shaderClipDistance = false,
603 .shaderCullDistance = false,
604 .shaderFloat64 = false,
605 .shaderInt64 = false,
606 .shaderInt16 = false,
607 .sparseBinding = false,
608 .variableMultisampleRate = false,
609 .inheritedQueries = false,
610 };
611 }
612
613 void
614 tu_GetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
615 VkPhysicalDeviceFeatures2 *pFeatures)
616 {
617 vk_foreach_struct(ext, pFeatures->pNext)
618 {
619 switch (ext->sType) {
620 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES: {
621 VkPhysicalDeviceVariablePointersFeatures *features = (void *) ext;
622 features->variablePointersStorageBuffer = false;
623 features->variablePointers = false;
624 break;
625 }
626 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
627 VkPhysicalDeviceMultiviewFeatures *features =
628 (VkPhysicalDeviceMultiviewFeatures *) ext;
629 features->multiview = false;
630 features->multiviewGeometryShader = false;
631 features->multiviewTessellationShader = false;
632 break;
633 }
634 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES: {
635 VkPhysicalDeviceShaderDrawParametersFeatures *features =
636 (VkPhysicalDeviceShaderDrawParametersFeatures *) ext;
637 features->shaderDrawParameters = false;
638 break;
639 }
640 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
641 VkPhysicalDeviceProtectedMemoryFeatures *features =
642 (VkPhysicalDeviceProtectedMemoryFeatures *) ext;
643 features->protectedMemory = false;
644 break;
645 }
646 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES: {
647 VkPhysicalDevice16BitStorageFeatures *features =
648 (VkPhysicalDevice16BitStorageFeatures *) ext;
649 features->storageBuffer16BitAccess = false;
650 features->uniformAndStorageBuffer16BitAccess = false;
651 features->storagePushConstant16 = false;
652 features->storageInputOutput16 = false;
653 break;
654 }
655 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
656 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
657 (VkPhysicalDeviceSamplerYcbcrConversionFeatures *) ext;
658 features->samplerYcbcrConversion = false;
659 break;
660 }
661 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT: {
662 VkPhysicalDeviceDescriptorIndexingFeaturesEXT *features =
663 (VkPhysicalDeviceDescriptorIndexingFeaturesEXT *) ext;
664 features->shaderInputAttachmentArrayDynamicIndexing = false;
665 features->shaderUniformTexelBufferArrayDynamicIndexing = false;
666 features->shaderStorageTexelBufferArrayDynamicIndexing = false;
667 features->shaderUniformBufferArrayNonUniformIndexing = false;
668 features->shaderSampledImageArrayNonUniformIndexing = false;
669 features->shaderStorageBufferArrayNonUniformIndexing = false;
670 features->shaderStorageImageArrayNonUniformIndexing = false;
671 features->shaderInputAttachmentArrayNonUniformIndexing = false;
672 features->shaderUniformTexelBufferArrayNonUniformIndexing = false;
673 features->shaderStorageTexelBufferArrayNonUniformIndexing = false;
674 features->descriptorBindingUniformBufferUpdateAfterBind = false;
675 features->descriptorBindingSampledImageUpdateAfterBind = false;
676 features->descriptorBindingStorageImageUpdateAfterBind = false;
677 features->descriptorBindingStorageBufferUpdateAfterBind = false;
678 features->descriptorBindingUniformTexelBufferUpdateAfterBind = false;
679 features->descriptorBindingStorageTexelBufferUpdateAfterBind = false;
680 features->descriptorBindingUpdateUnusedWhilePending = false;
681 features->descriptorBindingPartiallyBound = false;
682 features->descriptorBindingVariableDescriptorCount = false;
683 features->runtimeDescriptorArray = false;
684 break;
685 }
686 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT: {
687 VkPhysicalDeviceConditionalRenderingFeaturesEXT *features =
688 (VkPhysicalDeviceConditionalRenderingFeaturesEXT *) ext;
689 features->conditionalRendering = false;
690 features->inheritedConditionalRendering = false;
691 break;
692 }
693 default:
694 break;
695 }
696 }
697 return tu_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
698 }
699
700 void
701 tu_GetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,
702 VkPhysicalDeviceProperties *pProperties)
703 {
704 TU_FROM_HANDLE(tu_physical_device, pdevice, physicalDevice);
705 VkSampleCountFlags sample_counts = VK_SAMPLE_COUNT_1_BIT |
706 VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT;
707
708 /* make sure that the entire descriptor set is addressable with a signed
709 * 32-bit int. So the sum of all limits scaled by descriptor size has to
710 * be at most 2 GiB. the combined image & samples object count as one of
711 * both. This limit is for the pipeline layout, not for the set layout, but
712 * there is no set limit, so we just set a pipeline limit. I don't think
713 * any app is going to hit this soon. */
714 size_t max_descriptor_set_size =
715 ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS) /
716 (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
717 32 /* storage buffer, 32 due to potential space wasted on alignment */ +
718 32 /* sampler, largest when combined with image */ +
719 64 /* sampled image */ + 64 /* storage image */);
720
721 VkPhysicalDeviceLimits limits = {
722 .maxImageDimension1D = (1 << 14),
723 .maxImageDimension2D = (1 << 14),
724 .maxImageDimension3D = (1 << 11),
725 .maxImageDimensionCube = (1 << 14),
726 .maxImageArrayLayers = (1 << 11),
727 .maxTexelBufferElements = 128 * 1024 * 1024,
728 .maxUniformBufferRange = UINT32_MAX,
729 .maxStorageBufferRange = MAX_STORAGE_BUFFER_RANGE,
730 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
731 .maxMemoryAllocationCount = UINT32_MAX,
732 .maxSamplerAllocationCount = 64 * 1024,
733 .bufferImageGranularity = 64, /* A cache line */
734 .sparseAddressSpaceSize = 0xffffffffu, /* buffer max size */
735 .maxBoundDescriptorSets = MAX_SETS,
736 .maxPerStageDescriptorSamplers = max_descriptor_set_size,
737 .maxPerStageDescriptorUniformBuffers = max_descriptor_set_size,
738 .maxPerStageDescriptorStorageBuffers = max_descriptor_set_size,
739 .maxPerStageDescriptorSampledImages = max_descriptor_set_size,
740 .maxPerStageDescriptorStorageImages = max_descriptor_set_size,
741 .maxPerStageDescriptorInputAttachments = max_descriptor_set_size,
742 .maxPerStageResources = max_descriptor_set_size,
743 .maxDescriptorSetSamplers = max_descriptor_set_size,
744 .maxDescriptorSetUniformBuffers = max_descriptor_set_size,
745 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS,
746 .maxDescriptorSetStorageBuffers = max_descriptor_set_size,
747 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS,
748 .maxDescriptorSetSampledImages = max_descriptor_set_size,
749 .maxDescriptorSetStorageImages = max_descriptor_set_size,
750 .maxDescriptorSetInputAttachments = max_descriptor_set_size,
751 .maxVertexInputAttributes = 32,
752 .maxVertexInputBindings = 32,
753 .maxVertexInputAttributeOffset = 2047,
754 .maxVertexInputBindingStride = 2048,
755 .maxVertexOutputComponents = 128,
756 .maxTessellationGenerationLevel = 64,
757 .maxTessellationPatchSize = 32,
758 .maxTessellationControlPerVertexInputComponents = 128,
759 .maxTessellationControlPerVertexOutputComponents = 128,
760 .maxTessellationControlPerPatchOutputComponents = 120,
761 .maxTessellationControlTotalOutputComponents = 4096,
762 .maxTessellationEvaluationInputComponents = 128,
763 .maxTessellationEvaluationOutputComponents = 128,
764 .maxGeometryShaderInvocations = 127,
765 .maxGeometryInputComponents = 64,
766 .maxGeometryOutputComponents = 128,
767 .maxGeometryOutputVertices = 256,
768 .maxGeometryTotalOutputComponents = 1024,
769 .maxFragmentInputComponents = 128,
770 .maxFragmentOutputAttachments = 8,
771 .maxFragmentDualSrcAttachments = 1,
772 .maxFragmentCombinedOutputResources = 8,
773 .maxComputeSharedMemorySize = 32768,
774 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
775 .maxComputeWorkGroupInvocations = 2048,
776 .maxComputeWorkGroupSize = { 2048, 2048, 2048 },
777 .subPixelPrecisionBits = 4 /* FIXME */,
778 .subTexelPrecisionBits = 4 /* FIXME */,
779 .mipmapPrecisionBits = 4 /* FIXME */,
780 .maxDrawIndexedIndexValue = UINT32_MAX,
781 .maxDrawIndirectCount = UINT32_MAX,
782 .maxSamplerLodBias = 16,
783 .maxSamplerAnisotropy = 16,
784 .maxViewports = MAX_VIEWPORTS,
785 .maxViewportDimensions = { (1 << 14), (1 << 14) },
786 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
787 .viewportSubPixelBits = 8,
788 .minMemoryMapAlignment = 4096, /* A page */
789 .minTexelBufferOffsetAlignment = 64,
790 .minUniformBufferOffsetAlignment = 4,
791 .minStorageBufferOffsetAlignment = 4,
792 .minTexelOffset = -32,
793 .maxTexelOffset = 31,
794 .minTexelGatherOffset = -32,
795 .maxTexelGatherOffset = 31,
796 .minInterpolationOffset = -2,
797 .maxInterpolationOffset = 2,
798 .subPixelInterpolationOffsetBits = 8,
799 .maxFramebufferWidth = (1 << 14),
800 .maxFramebufferHeight = (1 << 14),
801 .maxFramebufferLayers = (1 << 10),
802 .framebufferColorSampleCounts = sample_counts,
803 .framebufferDepthSampleCounts = sample_counts,
804 .framebufferStencilSampleCounts = sample_counts,
805 .framebufferNoAttachmentsSampleCounts = sample_counts,
806 .maxColorAttachments = MAX_RTS,
807 .sampledImageColorSampleCounts = sample_counts,
808 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
809 .sampledImageDepthSampleCounts = sample_counts,
810 .sampledImageStencilSampleCounts = sample_counts,
811 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
812 .maxSampleMaskWords = 1,
813 .timestampComputeAndGraphics = false, /* FINISHME */
814 .timestampPeriod = 1,
815 .maxClipDistances = 8,
816 .maxCullDistances = 8,
817 .maxCombinedClipAndCullDistances = 8,
818 .discreteQueuePriorities = 1,
819 .pointSizeRange = { 0.125, 255.875 },
820 .lineWidthRange = { 0.0, 7.9921875 },
821 .pointSizeGranularity = (1.0 / 8.0),
822 .lineWidthGranularity = (1.0 / 128.0),
823 .strictLines = false, /* FINISHME */
824 .standardSampleLocations = true,
825 .optimalBufferCopyOffsetAlignment = 128,
826 .optimalBufferCopyRowPitchAlignment = 128,
827 .nonCoherentAtomSize = 64,
828 };
829
830 *pProperties = (VkPhysicalDeviceProperties) {
831 .apiVersion = tu_physical_device_api_version(pdevice),
832 .driverVersion = vk_get_driver_version(),
833 .vendorID = 0, /* TODO */
834 .deviceID = 0,
835 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
836 .limits = limits,
837 .sparseProperties = { 0 },
838 };
839
840 strcpy(pProperties->deviceName, pdevice->name);
841 memcpy(pProperties->pipelineCacheUUID, pdevice->cache_uuid, VK_UUID_SIZE);
842 }
843
844 void
845 tu_GetPhysicalDeviceProperties2(VkPhysicalDevice physicalDevice,
846 VkPhysicalDeviceProperties2 *pProperties)
847 {
848 TU_FROM_HANDLE(tu_physical_device, pdevice, physicalDevice);
849 tu_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
850
851 vk_foreach_struct(ext, pProperties->pNext)
852 {
853 switch (ext->sType) {
854 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
855 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
856 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
857 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
858 break;
859 }
860 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
861 VkPhysicalDeviceIDProperties *properties =
862 (VkPhysicalDeviceIDProperties *) ext;
863 memcpy(properties->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
864 memcpy(properties->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
865 properties->deviceLUIDValid = false;
866 break;
867 }
868 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
869 VkPhysicalDeviceMultiviewProperties *properties =
870 (VkPhysicalDeviceMultiviewProperties *) ext;
871 properties->maxMultiviewViewCount = MAX_VIEWS;
872 properties->maxMultiviewInstanceIndex = INT_MAX;
873 break;
874 }
875 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
876 VkPhysicalDevicePointClippingProperties *properties =
877 (VkPhysicalDevicePointClippingProperties *) ext;
878 properties->pointClippingBehavior =
879 VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
880 break;
881 }
882 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
883 VkPhysicalDeviceMaintenance3Properties *properties =
884 (VkPhysicalDeviceMaintenance3Properties *) ext;
885 /* Make sure everything is addressable by a signed 32-bit int, and
886 * our largest descriptors are 96 bytes. */
887 properties->maxPerSetDescriptors = (1ull << 31) / 96;
888 /* Our buffer size fields allow only this much */
889 properties->maxMemoryAllocationSize = 0xFFFFFFFFull;
890 break;
891 }
892 default:
893 break;
894 }
895 }
896 }
897
898 static const VkQueueFamilyProperties tu_queue_family_properties = {
899 .queueFlags =
900 VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT,
901 .queueCount = 1,
902 .timestampValidBits = 0, /* FINISHME */
903 .minImageTransferGranularity = { 1, 1, 1 },
904 };
905
906 void
907 tu_GetPhysicalDeviceQueueFamilyProperties(
908 VkPhysicalDevice physicalDevice,
909 uint32_t *pQueueFamilyPropertyCount,
910 VkQueueFamilyProperties *pQueueFamilyProperties)
911 {
912 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
913
914 vk_outarray_append(&out, p) { *p = tu_queue_family_properties; }
915 }
916
917 void
918 tu_GetPhysicalDeviceQueueFamilyProperties2(
919 VkPhysicalDevice physicalDevice,
920 uint32_t *pQueueFamilyPropertyCount,
921 VkQueueFamilyProperties2 *pQueueFamilyProperties)
922 {
923 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
924
925 vk_outarray_append(&out, p)
926 {
927 p->queueFamilyProperties = tu_queue_family_properties;
928 }
929 }
930
931 static uint64_t
932 tu_get_system_heap_size()
933 {
934 struct sysinfo info;
935 sysinfo(&info);
936
937 uint64_t total_ram = (uint64_t) info.totalram * (uint64_t) info.mem_unit;
938
939 /* We don't want to burn too much ram with the GPU. If the user has 4GiB
940 * or less, we use at most half. If they have more than 4GiB, we use 3/4.
941 */
942 uint64_t available_ram;
943 if (total_ram <= 4ull * 1024ull * 1024ull * 1024ull)
944 available_ram = total_ram / 2;
945 else
946 available_ram = total_ram * 3 / 4;
947
948 return available_ram;
949 }
950
951 void
952 tu_GetPhysicalDeviceMemoryProperties(
953 VkPhysicalDevice physicalDevice,
954 VkPhysicalDeviceMemoryProperties *pMemoryProperties)
955 {
956 pMemoryProperties->memoryHeapCount = 1;
957 pMemoryProperties->memoryHeaps[0].size = tu_get_system_heap_size();
958 pMemoryProperties->memoryHeaps[0].flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT;
959
960 pMemoryProperties->memoryTypeCount = 1;
961 pMemoryProperties->memoryTypes[0].propertyFlags =
962 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
963 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
964 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
965 pMemoryProperties->memoryTypes[0].heapIndex = 0;
966 }
967
968 void
969 tu_GetPhysicalDeviceMemoryProperties2(
970 VkPhysicalDevice physicalDevice,
971 VkPhysicalDeviceMemoryProperties2 *pMemoryProperties)
972 {
973 return tu_GetPhysicalDeviceMemoryProperties(
974 physicalDevice, &pMemoryProperties->memoryProperties);
975 }
976
977 static VkResult
978 tu_queue_init(struct tu_device *device,
979 struct tu_queue *queue,
980 uint32_t queue_family_index,
981 int idx,
982 VkDeviceQueueCreateFlags flags)
983 {
984 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
985 queue->device = device;
986 queue->queue_family_index = queue_family_index;
987 queue->queue_idx = idx;
988 queue->flags = flags;
989
990 int ret = tu_drm_submitqueue_new(device, 0, &queue->msm_queue_id);
991 if (ret)
992 return VK_ERROR_INITIALIZATION_FAILED;
993
994 tu_fence_init(&queue->submit_fence, false);
995
996 return VK_SUCCESS;
997 }
998
999 static void
1000 tu_queue_finish(struct tu_queue *queue)
1001 {
1002 tu_fence_finish(&queue->submit_fence);
1003 tu_drm_submitqueue_close(queue->device, queue->msm_queue_id);
1004 }
1005
1006 static int
1007 tu_get_device_extension_index(const char *name)
1008 {
1009 for (unsigned i = 0; i < TU_DEVICE_EXTENSION_COUNT; ++i) {
1010 if (strcmp(name, tu_device_extensions[i].extensionName) == 0)
1011 return i;
1012 }
1013 return -1;
1014 }
1015
1016 VkResult
1017 tu_CreateDevice(VkPhysicalDevice physicalDevice,
1018 const VkDeviceCreateInfo *pCreateInfo,
1019 const VkAllocationCallbacks *pAllocator,
1020 VkDevice *pDevice)
1021 {
1022 TU_FROM_HANDLE(tu_physical_device, physical_device, physicalDevice);
1023 VkResult result;
1024 struct tu_device *device;
1025
1026 /* Check enabled features */
1027 if (pCreateInfo->pEnabledFeatures) {
1028 VkPhysicalDeviceFeatures supported_features;
1029 tu_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1030 VkBool32 *supported_feature = (VkBool32 *) &supported_features;
1031 VkBool32 *enabled_feature = (VkBool32 *) pCreateInfo->pEnabledFeatures;
1032 unsigned num_features =
1033 sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1034 for (uint32_t i = 0; i < num_features; i++) {
1035 if (enabled_feature[i] && !supported_feature[i])
1036 return vk_error(physical_device->instance,
1037 VK_ERROR_FEATURE_NOT_PRESENT);
1038 }
1039 }
1040
1041 device = vk_zalloc2(&physical_device->instance->alloc, pAllocator,
1042 sizeof(*device), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1043 if (!device)
1044 return vk_error(physical_device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1045
1046 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1047 device->instance = physical_device->instance;
1048 device->physical_device = physical_device;
1049
1050 if (pAllocator)
1051 device->alloc = *pAllocator;
1052 else
1053 device->alloc = physical_device->instance->alloc;
1054
1055 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1056 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
1057 int index = tu_get_device_extension_index(ext_name);
1058 if (index < 0 ||
1059 !physical_device->supported_extensions.extensions[index]) {
1060 vk_free(&device->alloc, device);
1061 return vk_error(physical_device->instance,
1062 VK_ERROR_EXTENSION_NOT_PRESENT);
1063 }
1064
1065 device->enabled_extensions.extensions[index] = true;
1066 }
1067
1068 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
1069 const VkDeviceQueueCreateInfo *queue_create =
1070 &pCreateInfo->pQueueCreateInfos[i];
1071 uint32_t qfi = queue_create->queueFamilyIndex;
1072 device->queues[qfi] = vk_alloc(
1073 &device->alloc, queue_create->queueCount * sizeof(struct tu_queue),
1074 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1075 if (!device->queues[qfi]) {
1076 result = VK_ERROR_OUT_OF_HOST_MEMORY;
1077 goto fail;
1078 }
1079
1080 memset(device->queues[qfi], 0,
1081 queue_create->queueCount * sizeof(struct tu_queue));
1082
1083 device->queue_count[qfi] = queue_create->queueCount;
1084
1085 for (unsigned q = 0; q < queue_create->queueCount; q++) {
1086 result = tu_queue_init(device, &device->queues[qfi][q], qfi, q,
1087 queue_create->flags);
1088 if (result != VK_SUCCESS)
1089 goto fail;
1090 }
1091 }
1092
1093 device->compiler = ir3_compiler_create(NULL, physical_device->gpu_id);
1094 if (!device->compiler)
1095 goto fail;
1096
1097 VkPipelineCacheCreateInfo ci;
1098 ci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
1099 ci.pNext = NULL;
1100 ci.flags = 0;
1101 ci.pInitialData = NULL;
1102 ci.initialDataSize = 0;
1103 VkPipelineCache pc;
1104 result =
1105 tu_CreatePipelineCache(tu_device_to_handle(device), &ci, NULL, &pc);
1106 if (result != VK_SUCCESS)
1107 goto fail;
1108
1109 device->mem_cache = tu_pipeline_cache_from_handle(pc);
1110
1111 *pDevice = tu_device_to_handle(device);
1112 return VK_SUCCESS;
1113
1114 fail:
1115 for (unsigned i = 0; i < TU_MAX_QUEUE_FAMILIES; i++) {
1116 for (unsigned q = 0; q < device->queue_count[i]; q++)
1117 tu_queue_finish(&device->queues[i][q]);
1118 if (device->queue_count[i])
1119 vk_free(&device->alloc, device->queues[i]);
1120 }
1121
1122 if (device->compiler)
1123 ralloc_free(device->compiler);
1124
1125 vk_free(&device->alloc, device);
1126 return result;
1127 }
1128
1129 void
1130 tu_DestroyDevice(VkDevice _device, const VkAllocationCallbacks *pAllocator)
1131 {
1132 TU_FROM_HANDLE(tu_device, device, _device);
1133
1134 if (!device)
1135 return;
1136
1137 for (unsigned i = 0; i < TU_MAX_QUEUE_FAMILIES; i++) {
1138 for (unsigned q = 0; q < device->queue_count[i]; q++)
1139 tu_queue_finish(&device->queues[i][q]);
1140 if (device->queue_count[i])
1141 vk_free(&device->alloc, device->queues[i]);
1142 }
1143
1144 /* the compiler does not use pAllocator */
1145 ralloc_free(device->compiler);
1146
1147 VkPipelineCache pc = tu_pipeline_cache_to_handle(device->mem_cache);
1148 tu_DestroyPipelineCache(tu_device_to_handle(device), pc, NULL);
1149
1150 vk_free(&device->alloc, device);
1151 }
1152
1153 VkResult
1154 tu_EnumerateInstanceLayerProperties(uint32_t *pPropertyCount,
1155 VkLayerProperties *pProperties)
1156 {
1157 *pPropertyCount = 0;
1158 return VK_SUCCESS;
1159 }
1160
1161 VkResult
1162 tu_EnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice,
1163 uint32_t *pPropertyCount,
1164 VkLayerProperties *pProperties)
1165 {
1166 *pPropertyCount = 0;
1167 return VK_SUCCESS;
1168 }
1169
1170 void
1171 tu_GetDeviceQueue2(VkDevice _device,
1172 const VkDeviceQueueInfo2 *pQueueInfo,
1173 VkQueue *pQueue)
1174 {
1175 TU_FROM_HANDLE(tu_device, device, _device);
1176 struct tu_queue *queue;
1177
1178 queue =
1179 &device->queues[pQueueInfo->queueFamilyIndex][pQueueInfo->queueIndex];
1180 if (pQueueInfo->flags != queue->flags) {
1181 /* From the Vulkan 1.1.70 spec:
1182 *
1183 * "The queue returned by vkGetDeviceQueue2 must have the same
1184 * flags value from this structure as that used at device
1185 * creation time in a VkDeviceQueueCreateInfo instance. If no
1186 * matching flags were specified at device creation time then
1187 * pQueue will return VK_NULL_HANDLE."
1188 */
1189 *pQueue = VK_NULL_HANDLE;
1190 return;
1191 }
1192
1193 *pQueue = tu_queue_to_handle(queue);
1194 }
1195
1196 void
1197 tu_GetDeviceQueue(VkDevice _device,
1198 uint32_t queueFamilyIndex,
1199 uint32_t queueIndex,
1200 VkQueue *pQueue)
1201 {
1202 const VkDeviceQueueInfo2 info =
1203 (VkDeviceQueueInfo2) { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
1204 .queueFamilyIndex = queueFamilyIndex,
1205 .queueIndex = queueIndex };
1206
1207 tu_GetDeviceQueue2(_device, &info, pQueue);
1208 }
1209
1210 VkResult
1211 tu_QueueSubmit(VkQueue _queue,
1212 uint32_t submitCount,
1213 const VkSubmitInfo *pSubmits,
1214 VkFence _fence)
1215 {
1216 TU_FROM_HANDLE(tu_queue, queue, _queue);
1217
1218 for (uint32_t i = 0; i < submitCount; ++i) {
1219 const VkSubmitInfo *submit = pSubmits + i;
1220 const bool last_submit = (i == submitCount - 1);
1221 struct tu_bo_list bo_list;
1222 tu_bo_list_init(&bo_list);
1223
1224 uint32_t entry_count = 0;
1225 for (uint32_t j = 0; j < submit->commandBufferCount; ++j) {
1226 TU_FROM_HANDLE(tu_cmd_buffer, cmdbuf, submit->pCommandBuffers[j]);
1227 entry_count += cmdbuf->cs.entry_count;
1228 }
1229
1230 struct drm_msm_gem_submit_cmd cmds[entry_count];
1231 uint32_t entry_idx = 0;
1232 for (uint32_t j = 0; j < submit->commandBufferCount; ++j) {
1233 TU_FROM_HANDLE(tu_cmd_buffer, cmdbuf, submit->pCommandBuffers[j]);
1234 struct tu_cs *cs = &cmdbuf->cs;
1235 for (unsigned i = 0; i < cs->entry_count; ++i, ++entry_idx) {
1236 cmds[entry_idx].type = MSM_SUBMIT_CMD_BUF;
1237 cmds[entry_idx].submit_idx =
1238 tu_bo_list_add(&bo_list, cs->entries[i].bo,
1239 MSM_SUBMIT_BO_READ | MSM_SUBMIT_BO_DUMP);
1240 cmds[entry_idx].submit_offset = cs->entries[i].offset;
1241 cmds[entry_idx].size = cs->entries[i].size;
1242 cmds[entry_idx].pad = 0;
1243 cmds[entry_idx].nr_relocs = 0;
1244 cmds[entry_idx].relocs = 0;
1245 }
1246
1247 tu_bo_list_merge(&bo_list, &cmdbuf->bo_list);
1248 }
1249
1250 uint32_t flags = MSM_PIPE_3D0;
1251 if (last_submit) {
1252 flags |= MSM_SUBMIT_FENCE_FD_OUT;
1253 }
1254
1255 struct drm_msm_gem_submit req = {
1256 .flags = flags,
1257 .queueid = queue->msm_queue_id,
1258 .bos = (uint64_t)(uintptr_t) bo_list.bo_infos,
1259 .nr_bos = bo_list.count,
1260 .cmds = (uint64_t)(uintptr_t)cmds,
1261 .nr_cmds = entry_count,
1262 };
1263
1264 int ret = drmCommandWriteRead(queue->device->physical_device->local_fd,
1265 DRM_MSM_GEM_SUBMIT,
1266 &req, sizeof(req));
1267 if (ret) {
1268 fprintf(stderr, "submit failed: %s\n", strerror(errno));
1269 abort();
1270 }
1271
1272 tu_bo_list_destroy(&bo_list);
1273
1274 if (last_submit) {
1275 /* no need to merge fences as queue execution is serialized */
1276 tu_fence_update_fd(&queue->submit_fence, req.fence_fd);
1277 }
1278 }
1279
1280 if (_fence != VK_NULL_HANDLE) {
1281 TU_FROM_HANDLE(tu_fence, fence, _fence);
1282 tu_fence_copy(fence, &queue->submit_fence);
1283 }
1284
1285 return VK_SUCCESS;
1286 }
1287
1288 VkResult
1289 tu_QueueWaitIdle(VkQueue _queue)
1290 {
1291 TU_FROM_HANDLE(tu_queue, queue, _queue);
1292
1293 tu_fence_wait_idle(&queue->submit_fence);
1294
1295 return VK_SUCCESS;
1296 }
1297
1298 VkResult
1299 tu_DeviceWaitIdle(VkDevice _device)
1300 {
1301 TU_FROM_HANDLE(tu_device, device, _device);
1302
1303 for (unsigned i = 0; i < TU_MAX_QUEUE_FAMILIES; i++) {
1304 for (unsigned q = 0; q < device->queue_count[i]; q++) {
1305 tu_QueueWaitIdle(tu_queue_to_handle(&device->queues[i][q]));
1306 }
1307 }
1308 return VK_SUCCESS;
1309 }
1310
1311 VkResult
1312 tu_EnumerateInstanceExtensionProperties(const char *pLayerName,
1313 uint32_t *pPropertyCount,
1314 VkExtensionProperties *pProperties)
1315 {
1316 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
1317
1318 /* We spport no lyaers */
1319 if (pLayerName)
1320 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
1321
1322 for (int i = 0; i < TU_INSTANCE_EXTENSION_COUNT; i++) {
1323 if (tu_supported_instance_extensions.extensions[i]) {
1324 vk_outarray_append(&out, prop) { *prop = tu_instance_extensions[i]; }
1325 }
1326 }
1327
1328 return vk_outarray_status(&out);
1329 }
1330
1331 VkResult
1332 tu_EnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,
1333 const char *pLayerName,
1334 uint32_t *pPropertyCount,
1335 VkExtensionProperties *pProperties)
1336 {
1337 /* We spport no lyaers */
1338 TU_FROM_HANDLE(tu_physical_device, device, physicalDevice);
1339 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
1340
1341 /* We spport no lyaers */
1342 if (pLayerName)
1343 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
1344
1345 for (int i = 0; i < TU_DEVICE_EXTENSION_COUNT; i++) {
1346 if (device->supported_extensions.extensions[i]) {
1347 vk_outarray_append(&out, prop) { *prop = tu_device_extensions[i]; }
1348 }
1349 }
1350
1351 return vk_outarray_status(&out);
1352 }
1353
1354 PFN_vkVoidFunction
1355 tu_GetInstanceProcAddr(VkInstance _instance, const char *pName)
1356 {
1357 TU_FROM_HANDLE(tu_instance, instance, _instance);
1358
1359 return tu_lookup_entrypoint_checked(
1360 pName, instance ? instance->api_version : 0,
1361 instance ? &instance->enabled_extensions : NULL, NULL);
1362 }
1363
1364 /* The loader wants us to expose a second GetInstanceProcAddr function
1365 * to work around certain LD_PRELOAD issues seen in apps.
1366 */
1367 PUBLIC
1368 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL
1369 vk_icdGetInstanceProcAddr(VkInstance instance, const char *pName);
1370
1371 PUBLIC
1372 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL
1373 vk_icdGetInstanceProcAddr(VkInstance instance, const char *pName)
1374 {
1375 return tu_GetInstanceProcAddr(instance, pName);
1376 }
1377
1378 PFN_vkVoidFunction
1379 tu_GetDeviceProcAddr(VkDevice _device, const char *pName)
1380 {
1381 TU_FROM_HANDLE(tu_device, device, _device);
1382
1383 return tu_lookup_entrypoint_checked(pName, device->instance->api_version,
1384 &device->instance->enabled_extensions,
1385 &device->enabled_extensions);
1386 }
1387
1388 static VkResult
1389 tu_alloc_memory(struct tu_device *device,
1390 const VkMemoryAllocateInfo *pAllocateInfo,
1391 const VkAllocationCallbacks *pAllocator,
1392 VkDeviceMemory *pMem)
1393 {
1394 struct tu_device_memory *mem;
1395 VkResult result;
1396
1397 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
1398
1399 if (pAllocateInfo->allocationSize == 0) {
1400 /* Apparently, this is allowed */
1401 *pMem = VK_NULL_HANDLE;
1402 return VK_SUCCESS;
1403 }
1404
1405 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
1406 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1407 if (mem == NULL)
1408 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1409
1410 const VkImportMemoryFdInfoKHR *fd_info =
1411 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
1412 if (fd_info && !fd_info->handleType)
1413 fd_info = NULL;
1414
1415 if (fd_info) {
1416 assert(fd_info->handleType ==
1417 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
1418 fd_info->handleType ==
1419 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1420
1421 /*
1422 * TODO Importing the same fd twice gives us the same handle without
1423 * reference counting. We need to maintain a per-instance handle-to-bo
1424 * table and add reference count to tu_bo.
1425 */
1426 result = tu_bo_init_dmabuf(device, &mem->bo,
1427 pAllocateInfo->allocationSize, fd_info->fd);
1428 if (result == VK_SUCCESS) {
1429 /* take ownership and close the fd */
1430 close(fd_info->fd);
1431 }
1432 } else {
1433 result =
1434 tu_bo_init_new(device, &mem->bo, pAllocateInfo->allocationSize);
1435 }
1436
1437 if (result != VK_SUCCESS) {
1438 vk_free2(&device->alloc, pAllocator, mem);
1439 return result;
1440 }
1441
1442 mem->size = pAllocateInfo->allocationSize;
1443 mem->type_index = pAllocateInfo->memoryTypeIndex;
1444
1445 mem->map = NULL;
1446 mem->user_ptr = NULL;
1447
1448 *pMem = tu_device_memory_to_handle(mem);
1449
1450 return VK_SUCCESS;
1451 }
1452
1453 VkResult
1454 tu_AllocateMemory(VkDevice _device,
1455 const VkMemoryAllocateInfo *pAllocateInfo,
1456 const VkAllocationCallbacks *pAllocator,
1457 VkDeviceMemory *pMem)
1458 {
1459 TU_FROM_HANDLE(tu_device, device, _device);
1460 return tu_alloc_memory(device, pAllocateInfo, pAllocator, pMem);
1461 }
1462
1463 void
1464 tu_FreeMemory(VkDevice _device,
1465 VkDeviceMemory _mem,
1466 const VkAllocationCallbacks *pAllocator)
1467 {
1468 TU_FROM_HANDLE(tu_device, device, _device);
1469 TU_FROM_HANDLE(tu_device_memory, mem, _mem);
1470
1471 if (mem == NULL)
1472 return;
1473
1474 tu_bo_finish(device, &mem->bo);
1475 vk_free2(&device->alloc, pAllocator, mem);
1476 }
1477
1478 VkResult
1479 tu_MapMemory(VkDevice _device,
1480 VkDeviceMemory _memory,
1481 VkDeviceSize offset,
1482 VkDeviceSize size,
1483 VkMemoryMapFlags flags,
1484 void **ppData)
1485 {
1486 TU_FROM_HANDLE(tu_device, device, _device);
1487 TU_FROM_HANDLE(tu_device_memory, mem, _memory);
1488 VkResult result;
1489
1490 if (mem == NULL) {
1491 *ppData = NULL;
1492 return VK_SUCCESS;
1493 }
1494
1495 if (mem->user_ptr) {
1496 *ppData = mem->user_ptr;
1497 } else if (!mem->map) {
1498 result = tu_bo_map(device, &mem->bo);
1499 if (result != VK_SUCCESS)
1500 return result;
1501 *ppData = mem->map = mem->bo.map;
1502 } else
1503 *ppData = mem->map;
1504
1505 if (*ppData) {
1506 *ppData += offset;
1507 return VK_SUCCESS;
1508 }
1509
1510 return vk_error(device->instance, VK_ERROR_MEMORY_MAP_FAILED);
1511 }
1512
1513 void
1514 tu_UnmapMemory(VkDevice _device, VkDeviceMemory _memory)
1515 {
1516 /* I do not see any unmapping done by the freedreno Gallium driver. */
1517 }
1518
1519 VkResult
1520 tu_FlushMappedMemoryRanges(VkDevice _device,
1521 uint32_t memoryRangeCount,
1522 const VkMappedMemoryRange *pMemoryRanges)
1523 {
1524 return VK_SUCCESS;
1525 }
1526
1527 VkResult
1528 tu_InvalidateMappedMemoryRanges(VkDevice _device,
1529 uint32_t memoryRangeCount,
1530 const VkMappedMemoryRange *pMemoryRanges)
1531 {
1532 return VK_SUCCESS;
1533 }
1534
1535 void
1536 tu_GetBufferMemoryRequirements(VkDevice _device,
1537 VkBuffer _buffer,
1538 VkMemoryRequirements *pMemoryRequirements)
1539 {
1540 TU_FROM_HANDLE(tu_buffer, buffer, _buffer);
1541
1542 pMemoryRequirements->memoryTypeBits = 1;
1543 pMemoryRequirements->alignment = 16;
1544 pMemoryRequirements->size =
1545 align64(buffer->size, pMemoryRequirements->alignment);
1546 }
1547
1548 void
1549 tu_GetBufferMemoryRequirements2(
1550 VkDevice device,
1551 const VkBufferMemoryRequirementsInfo2 *pInfo,
1552 VkMemoryRequirements2 *pMemoryRequirements)
1553 {
1554 tu_GetBufferMemoryRequirements(device, pInfo->buffer,
1555 &pMemoryRequirements->memoryRequirements);
1556 }
1557
1558 void
1559 tu_GetImageMemoryRequirements(VkDevice _device,
1560 VkImage _image,
1561 VkMemoryRequirements *pMemoryRequirements)
1562 {
1563 TU_FROM_HANDLE(tu_image, image, _image);
1564
1565 pMemoryRequirements->memoryTypeBits = 1;
1566 pMemoryRequirements->size = image->layout.size;
1567 pMemoryRequirements->alignment = image->alignment;
1568 }
1569
1570 void
1571 tu_GetImageMemoryRequirements2(VkDevice device,
1572 const VkImageMemoryRequirementsInfo2 *pInfo,
1573 VkMemoryRequirements2 *pMemoryRequirements)
1574 {
1575 tu_GetImageMemoryRequirements(device, pInfo->image,
1576 &pMemoryRequirements->memoryRequirements);
1577 }
1578
1579 void
1580 tu_GetImageSparseMemoryRequirements(
1581 VkDevice device,
1582 VkImage image,
1583 uint32_t *pSparseMemoryRequirementCount,
1584 VkSparseImageMemoryRequirements *pSparseMemoryRequirements)
1585 {
1586 tu_stub();
1587 }
1588
1589 void
1590 tu_GetImageSparseMemoryRequirements2(
1591 VkDevice device,
1592 const VkImageSparseMemoryRequirementsInfo2 *pInfo,
1593 uint32_t *pSparseMemoryRequirementCount,
1594 VkSparseImageMemoryRequirements2 *pSparseMemoryRequirements)
1595 {
1596 tu_stub();
1597 }
1598
1599 void
1600 tu_GetDeviceMemoryCommitment(VkDevice device,
1601 VkDeviceMemory memory,
1602 VkDeviceSize *pCommittedMemoryInBytes)
1603 {
1604 *pCommittedMemoryInBytes = 0;
1605 }
1606
1607 VkResult
1608 tu_BindBufferMemory2(VkDevice device,
1609 uint32_t bindInfoCount,
1610 const VkBindBufferMemoryInfo *pBindInfos)
1611 {
1612 for (uint32_t i = 0; i < bindInfoCount; ++i) {
1613 TU_FROM_HANDLE(tu_device_memory, mem, pBindInfos[i].memory);
1614 TU_FROM_HANDLE(tu_buffer, buffer, pBindInfos[i].buffer);
1615
1616 if (mem) {
1617 buffer->bo = &mem->bo;
1618 buffer->bo_offset = pBindInfos[i].memoryOffset;
1619 } else {
1620 buffer->bo = NULL;
1621 }
1622 }
1623 return VK_SUCCESS;
1624 }
1625
1626 VkResult
1627 tu_BindBufferMemory(VkDevice device,
1628 VkBuffer buffer,
1629 VkDeviceMemory memory,
1630 VkDeviceSize memoryOffset)
1631 {
1632 const VkBindBufferMemoryInfo info = {
1633 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
1634 .buffer = buffer,
1635 .memory = memory,
1636 .memoryOffset = memoryOffset
1637 };
1638
1639 return tu_BindBufferMemory2(device, 1, &info);
1640 }
1641
1642 VkResult
1643 tu_BindImageMemory2(VkDevice device,
1644 uint32_t bindInfoCount,
1645 const VkBindImageMemoryInfo *pBindInfos)
1646 {
1647 for (uint32_t i = 0; i < bindInfoCount; ++i) {
1648 TU_FROM_HANDLE(tu_image, image, pBindInfos[i].image);
1649 TU_FROM_HANDLE(tu_device_memory, mem, pBindInfos[i].memory);
1650
1651 if (mem) {
1652 image->bo = &mem->bo;
1653 image->bo_offset = pBindInfos[i].memoryOffset;
1654 } else {
1655 image->bo = NULL;
1656 image->bo_offset = 0;
1657 }
1658 }
1659
1660 return VK_SUCCESS;
1661 }
1662
1663 VkResult
1664 tu_BindImageMemory(VkDevice device,
1665 VkImage image,
1666 VkDeviceMemory memory,
1667 VkDeviceSize memoryOffset)
1668 {
1669 const VkBindImageMemoryInfo info = {
1670 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
1671 .image = image,
1672 .memory = memory,
1673 .memoryOffset = memoryOffset
1674 };
1675
1676 return tu_BindImageMemory2(device, 1, &info);
1677 }
1678
1679 VkResult
1680 tu_QueueBindSparse(VkQueue _queue,
1681 uint32_t bindInfoCount,
1682 const VkBindSparseInfo *pBindInfo,
1683 VkFence _fence)
1684 {
1685 return VK_SUCCESS;
1686 }
1687
1688 // Queue semaphore functions
1689
1690 VkResult
1691 tu_CreateSemaphore(VkDevice _device,
1692 const VkSemaphoreCreateInfo *pCreateInfo,
1693 const VkAllocationCallbacks *pAllocator,
1694 VkSemaphore *pSemaphore)
1695 {
1696 TU_FROM_HANDLE(tu_device, device, _device);
1697
1698 struct tu_semaphore *sem =
1699 vk_alloc2(&device->alloc, pAllocator, sizeof(*sem), 8,
1700 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1701 if (!sem)
1702 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1703
1704 *pSemaphore = tu_semaphore_to_handle(sem);
1705 return VK_SUCCESS;
1706 }
1707
1708 void
1709 tu_DestroySemaphore(VkDevice _device,
1710 VkSemaphore _semaphore,
1711 const VkAllocationCallbacks *pAllocator)
1712 {
1713 TU_FROM_HANDLE(tu_device, device, _device);
1714 TU_FROM_HANDLE(tu_semaphore, sem, _semaphore);
1715 if (!_semaphore)
1716 return;
1717
1718 vk_free2(&device->alloc, pAllocator, sem);
1719 }
1720
1721 VkResult
1722 tu_CreateEvent(VkDevice _device,
1723 const VkEventCreateInfo *pCreateInfo,
1724 const VkAllocationCallbacks *pAllocator,
1725 VkEvent *pEvent)
1726 {
1727 TU_FROM_HANDLE(tu_device, device, _device);
1728 struct tu_event *event =
1729 vk_alloc2(&device->alloc, pAllocator, sizeof(*event), 8,
1730 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1731
1732 if (!event)
1733 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1734
1735 VkResult result = tu_bo_init_new(device, &event->bo, 0x1000);
1736 if (result != VK_SUCCESS)
1737 goto fail_alloc;
1738
1739 result = tu_bo_map(device, &event->bo);
1740 if (result != VK_SUCCESS)
1741 goto fail_map;
1742
1743 *pEvent = tu_event_to_handle(event);
1744
1745 return VK_SUCCESS;
1746
1747 fail_map:
1748 tu_bo_finish(device, &event->bo);
1749 fail_alloc:
1750 vk_free2(&device->alloc, pAllocator, event);
1751 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1752 }
1753
1754 void
1755 tu_DestroyEvent(VkDevice _device,
1756 VkEvent _event,
1757 const VkAllocationCallbacks *pAllocator)
1758 {
1759 TU_FROM_HANDLE(tu_device, device, _device);
1760 TU_FROM_HANDLE(tu_event, event, _event);
1761
1762 if (!event)
1763 return;
1764 vk_free2(&device->alloc, pAllocator, event);
1765 }
1766
1767 VkResult
1768 tu_GetEventStatus(VkDevice _device, VkEvent _event)
1769 {
1770 TU_FROM_HANDLE(tu_event, event, _event);
1771
1772 if (*(uint64_t*) event->bo.map == 1)
1773 return VK_EVENT_SET;
1774 return VK_EVENT_RESET;
1775 }
1776
1777 VkResult
1778 tu_SetEvent(VkDevice _device, VkEvent _event)
1779 {
1780 TU_FROM_HANDLE(tu_event, event, _event);
1781 *(uint64_t*) event->bo.map = 1;
1782
1783 return VK_SUCCESS;
1784 }
1785
1786 VkResult
1787 tu_ResetEvent(VkDevice _device, VkEvent _event)
1788 {
1789 TU_FROM_HANDLE(tu_event, event, _event);
1790 *(uint64_t*) event->bo.map = 0;
1791
1792 return VK_SUCCESS;
1793 }
1794
1795 VkResult
1796 tu_CreateBuffer(VkDevice _device,
1797 const VkBufferCreateInfo *pCreateInfo,
1798 const VkAllocationCallbacks *pAllocator,
1799 VkBuffer *pBuffer)
1800 {
1801 TU_FROM_HANDLE(tu_device, device, _device);
1802 struct tu_buffer *buffer;
1803
1804 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
1805
1806 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
1807 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1808 if (buffer == NULL)
1809 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1810
1811 buffer->size = pCreateInfo->size;
1812 buffer->usage = pCreateInfo->usage;
1813 buffer->flags = pCreateInfo->flags;
1814
1815 *pBuffer = tu_buffer_to_handle(buffer);
1816
1817 return VK_SUCCESS;
1818 }
1819
1820 void
1821 tu_DestroyBuffer(VkDevice _device,
1822 VkBuffer _buffer,
1823 const VkAllocationCallbacks *pAllocator)
1824 {
1825 TU_FROM_HANDLE(tu_device, device, _device);
1826 TU_FROM_HANDLE(tu_buffer, buffer, _buffer);
1827
1828 if (!buffer)
1829 return;
1830
1831 vk_free2(&device->alloc, pAllocator, buffer);
1832 }
1833
1834 static uint32_t
1835 tu_surface_max_layer_count(struct tu_image_view *iview)
1836 {
1837 return iview->type == VK_IMAGE_VIEW_TYPE_3D
1838 ? iview->extent.depth
1839 : (iview->base_layer + iview->layer_count);
1840 }
1841
1842 VkResult
1843 tu_CreateFramebuffer(VkDevice _device,
1844 const VkFramebufferCreateInfo *pCreateInfo,
1845 const VkAllocationCallbacks *pAllocator,
1846 VkFramebuffer *pFramebuffer)
1847 {
1848 TU_FROM_HANDLE(tu_device, device, _device);
1849 struct tu_framebuffer *framebuffer;
1850
1851 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
1852
1853 size_t size = sizeof(*framebuffer) + sizeof(struct tu_attachment_info) *
1854 pCreateInfo->attachmentCount;
1855 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
1856 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1857 if (framebuffer == NULL)
1858 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1859
1860 framebuffer->attachment_count = pCreateInfo->attachmentCount;
1861 framebuffer->width = pCreateInfo->width;
1862 framebuffer->height = pCreateInfo->height;
1863 framebuffer->layers = pCreateInfo->layers;
1864 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
1865 VkImageView _iview = pCreateInfo->pAttachments[i];
1866 struct tu_image_view *iview = tu_image_view_from_handle(_iview);
1867 framebuffer->attachments[i].attachment = iview;
1868
1869 framebuffer->width = MIN2(framebuffer->width, iview->extent.width);
1870 framebuffer->height = MIN2(framebuffer->height, iview->extent.height);
1871 framebuffer->layers =
1872 MIN2(framebuffer->layers, tu_surface_max_layer_count(iview));
1873 }
1874
1875 *pFramebuffer = tu_framebuffer_to_handle(framebuffer);
1876 return VK_SUCCESS;
1877 }
1878
1879 void
1880 tu_DestroyFramebuffer(VkDevice _device,
1881 VkFramebuffer _fb,
1882 const VkAllocationCallbacks *pAllocator)
1883 {
1884 TU_FROM_HANDLE(tu_device, device, _device);
1885 TU_FROM_HANDLE(tu_framebuffer, fb, _fb);
1886
1887 if (!fb)
1888 return;
1889 vk_free2(&device->alloc, pAllocator, fb);
1890 }
1891
1892 static enum a6xx_tex_clamp
1893 tu6_tex_wrap(VkSamplerAddressMode address_mode, bool *needs_border)
1894 {
1895 switch (address_mode) {
1896 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
1897 return A6XX_TEX_REPEAT;
1898 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
1899 return A6XX_TEX_MIRROR_REPEAT;
1900 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
1901 return A6XX_TEX_CLAMP_TO_EDGE;
1902 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
1903 *needs_border = true;
1904 return A6XX_TEX_CLAMP_TO_BORDER;
1905 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
1906 /* only works for PoT.. need to emulate otherwise! */
1907 return A6XX_TEX_MIRROR_CLAMP;
1908 default:
1909 unreachable("illegal tex wrap mode");
1910 break;
1911 }
1912 }
1913
1914 static enum a6xx_tex_filter
1915 tu6_tex_filter(VkFilter filter, unsigned aniso)
1916 {
1917 switch (filter) {
1918 case VK_FILTER_NEAREST:
1919 return A6XX_TEX_NEAREST;
1920 case VK_FILTER_LINEAR:
1921 return aniso ? A6XX_TEX_ANISO : A6XX_TEX_LINEAR;
1922 case VK_FILTER_CUBIC_IMG:
1923 default:
1924 unreachable("illegal texture filter");
1925 break;
1926 }
1927 }
1928
1929 static void
1930 tu_init_sampler(struct tu_device *device,
1931 struct tu_sampler *sampler,
1932 const VkSamplerCreateInfo *pCreateInfo)
1933 {
1934 unsigned aniso = pCreateInfo->anisotropyEnable ?
1935 util_last_bit(MIN2((uint32_t)pCreateInfo->maxAnisotropy >> 1, 8)) : 0;
1936 bool miplinear = (pCreateInfo->mipmapMode == VK_SAMPLER_MIPMAP_MODE_LINEAR);
1937 bool needs_border = false;
1938
1939 sampler->state[0] =
1940 COND(miplinear, A6XX_TEX_SAMP_0_MIPFILTER_LINEAR_NEAR) |
1941 A6XX_TEX_SAMP_0_XY_MAG(tu6_tex_filter(pCreateInfo->magFilter, aniso)) |
1942 A6XX_TEX_SAMP_0_XY_MIN(tu6_tex_filter(pCreateInfo->minFilter, aniso)) |
1943 A6XX_TEX_SAMP_0_ANISO(aniso) |
1944 A6XX_TEX_SAMP_0_WRAP_S(tu6_tex_wrap(pCreateInfo->addressModeU, &needs_border)) |
1945 A6XX_TEX_SAMP_0_WRAP_T(tu6_tex_wrap(pCreateInfo->addressModeV, &needs_border)) |
1946 A6XX_TEX_SAMP_0_WRAP_R(tu6_tex_wrap(pCreateInfo->addressModeW, &needs_border)) |
1947 A6XX_TEX_SAMP_0_LOD_BIAS(pCreateInfo->mipLodBias);
1948 sampler->state[1] =
1949 /* COND(!cso->seamless_cube_map, A6XX_TEX_SAMP_1_CUBEMAPSEAMLESSFILTOFF) | */
1950 COND(pCreateInfo->unnormalizedCoordinates, A6XX_TEX_SAMP_1_UNNORM_COORDS) |
1951 A6XX_TEX_SAMP_1_MIN_LOD(pCreateInfo->minLod) |
1952 A6XX_TEX_SAMP_1_MAX_LOD(pCreateInfo->maxLod) |
1953 COND(pCreateInfo->compareEnable, A6XX_TEX_SAMP_1_COMPARE_FUNC(pCreateInfo->compareOp));
1954 sampler->state[2] = 0;
1955 sampler->state[3] = 0;
1956
1957 /* TODO:
1958 * A6XX_TEX_SAMP_1_MIPFILTER_LINEAR_FAR disables mipmapping, but vk has no NONE mipfilter?
1959 * border color
1960 */
1961
1962 sampler->needs_border = needs_border;
1963 sampler->border = pCreateInfo->borderColor;
1964 }
1965
1966 VkResult
1967 tu_CreateSampler(VkDevice _device,
1968 const VkSamplerCreateInfo *pCreateInfo,
1969 const VkAllocationCallbacks *pAllocator,
1970 VkSampler *pSampler)
1971 {
1972 TU_FROM_HANDLE(tu_device, device, _device);
1973 struct tu_sampler *sampler;
1974
1975 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
1976
1977 sampler = vk_alloc2(&device->alloc, pAllocator, sizeof(*sampler), 8,
1978 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1979 if (!sampler)
1980 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1981
1982 tu_init_sampler(device, sampler, pCreateInfo);
1983 *pSampler = tu_sampler_to_handle(sampler);
1984
1985 return VK_SUCCESS;
1986 }
1987
1988 void
1989 tu_DestroySampler(VkDevice _device,
1990 VkSampler _sampler,
1991 const VkAllocationCallbacks *pAllocator)
1992 {
1993 TU_FROM_HANDLE(tu_device, device, _device);
1994 TU_FROM_HANDLE(tu_sampler, sampler, _sampler);
1995
1996 if (!sampler)
1997 return;
1998 vk_free2(&device->alloc, pAllocator, sampler);
1999 }
2000
2001 /* vk_icd.h does not declare this function, so we declare it here to
2002 * suppress Wmissing-prototypes.
2003 */
2004 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2005 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
2006
2007 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2008 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
2009 {
2010 /* For the full details on loader interface versioning, see
2011 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2012 * What follows is a condensed summary, to help you navigate the large and
2013 * confusing official doc.
2014 *
2015 * - Loader interface v0 is incompatible with later versions. We don't
2016 * support it.
2017 *
2018 * - In loader interface v1:
2019 * - The first ICD entrypoint called by the loader is
2020 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2021 * entrypoint.
2022 * - The ICD must statically expose no other Vulkan symbol unless it
2023 * is linked with -Bsymbolic.
2024 * - Each dispatchable Vulkan handle created by the ICD must be
2025 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2026 * ICD must initialize VK_LOADER_DATA.loadMagic to
2027 * ICD_LOADER_MAGIC.
2028 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2029 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2030 * such loader-managed surfaces.
2031 *
2032 * - Loader interface v2 differs from v1 in:
2033 * - The first ICD entrypoint called by the loader is
2034 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
2035 * statically expose this entrypoint.
2036 *
2037 * - Loader interface v3 differs from v2 in:
2038 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
2039 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
2040 * because the loader no longer does so.
2041 */
2042 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
2043 return VK_SUCCESS;
2044 }
2045
2046 VkResult
2047 tu_GetMemoryFdKHR(VkDevice _device,
2048 const VkMemoryGetFdInfoKHR *pGetFdInfo,
2049 int *pFd)
2050 {
2051 TU_FROM_HANDLE(tu_device, device, _device);
2052 TU_FROM_HANDLE(tu_device_memory, memory, pGetFdInfo->memory);
2053
2054 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
2055
2056 /* At the moment, we support only the below handle types. */
2057 assert(pGetFdInfo->handleType ==
2058 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2059 pGetFdInfo->handleType ==
2060 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2061
2062 int prime_fd = tu_bo_export_dmabuf(device, &memory->bo);
2063 if (prime_fd < 0)
2064 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
2065
2066 *pFd = prime_fd;
2067 return VK_SUCCESS;
2068 }
2069
2070 VkResult
2071 tu_GetMemoryFdPropertiesKHR(VkDevice _device,
2072 VkExternalMemoryHandleTypeFlagBits handleType,
2073 int fd,
2074 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
2075 {
2076 assert(handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2077 pMemoryFdProperties->memoryTypeBits = 1;
2078 return VK_SUCCESS;
2079 }
2080
2081 void
2082 tu_GetPhysicalDeviceExternalSemaphoreProperties(
2083 VkPhysicalDevice physicalDevice,
2084 const VkPhysicalDeviceExternalSemaphoreInfo *pExternalSemaphoreInfo,
2085 VkExternalSemaphoreProperties *pExternalSemaphoreProperties)
2086 {
2087 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
2088 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
2089 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
2090 }
2091
2092 void
2093 tu_GetPhysicalDeviceExternalFenceProperties(
2094 VkPhysicalDevice physicalDevice,
2095 const VkPhysicalDeviceExternalFenceInfo *pExternalFenceInfo,
2096 VkExternalFenceProperties *pExternalFenceProperties)
2097 {
2098 pExternalFenceProperties->exportFromImportedHandleTypes = 0;
2099 pExternalFenceProperties->compatibleHandleTypes = 0;
2100 pExternalFenceProperties->externalFenceFeatures = 0;
2101 }
2102
2103 VkResult
2104 tu_CreateDebugReportCallbackEXT(
2105 VkInstance _instance,
2106 const VkDebugReportCallbackCreateInfoEXT *pCreateInfo,
2107 const VkAllocationCallbacks *pAllocator,
2108 VkDebugReportCallbackEXT *pCallback)
2109 {
2110 TU_FROM_HANDLE(tu_instance, instance, _instance);
2111 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
2112 pCreateInfo, pAllocator,
2113 &instance->alloc, pCallback);
2114 }
2115
2116 void
2117 tu_DestroyDebugReportCallbackEXT(VkInstance _instance,
2118 VkDebugReportCallbackEXT _callback,
2119 const VkAllocationCallbacks *pAllocator)
2120 {
2121 TU_FROM_HANDLE(tu_instance, instance, _instance);
2122 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
2123 _callback, pAllocator, &instance->alloc);
2124 }
2125
2126 void
2127 tu_DebugReportMessageEXT(VkInstance _instance,
2128 VkDebugReportFlagsEXT flags,
2129 VkDebugReportObjectTypeEXT objectType,
2130 uint64_t object,
2131 size_t location,
2132 int32_t messageCode,
2133 const char *pLayerPrefix,
2134 const char *pMessage)
2135 {
2136 TU_FROM_HANDLE(tu_instance, instance, _instance);
2137 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
2138 object, location, messageCode, pLayerPrefix, pMessage);
2139 }
2140
2141 void
2142 tu_GetDeviceGroupPeerMemoryFeatures(
2143 VkDevice device,
2144 uint32_t heapIndex,
2145 uint32_t localDeviceIndex,
2146 uint32_t remoteDeviceIndex,
2147 VkPeerMemoryFeatureFlags *pPeerMemoryFeatures)
2148 {
2149 assert(localDeviceIndex == remoteDeviceIndex);
2150
2151 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
2152 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
2153 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
2154 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
2155 }