turnip: enable largePoints
[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 "util/u_atomic.h"
43 #include "vk_format.h"
44 #include "vk_util.h"
45
46 #include "drm-uapi/msm_drm.h"
47
48 /* for fd_get_driver/device_uuid() */
49 #include "freedreno/common/freedreno_uuid.h"
50
51 static void
52 tu_semaphore_remove_temp(struct tu_device *device,
53 struct tu_semaphore *sem);
54
55 static int
56 tu_device_get_cache_uuid(uint16_t family, void *uuid)
57 {
58 uint32_t mesa_timestamp;
59 uint16_t f = family;
60 memset(uuid, 0, VK_UUID_SIZE);
61 if (!disk_cache_get_function_timestamp(tu_device_get_cache_uuid,
62 &mesa_timestamp))
63 return -1;
64
65 memcpy(uuid, &mesa_timestamp, 4);
66 memcpy((char *) uuid + 4, &f, 2);
67 snprintf((char *) uuid + 6, VK_UUID_SIZE - 10, "tu");
68 return 0;
69 }
70
71 static VkResult
72 tu_bo_init(struct tu_device *dev,
73 struct tu_bo *bo,
74 uint32_t gem_handle,
75 uint64_t size)
76 {
77 uint64_t iova = tu_gem_info_iova(dev, gem_handle);
78 if (!iova)
79 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
80
81 *bo = (struct tu_bo) {
82 .gem_handle = gem_handle,
83 .size = size,
84 .iova = iova,
85 };
86
87 return VK_SUCCESS;
88 }
89
90 VkResult
91 tu_bo_init_new(struct tu_device *dev, struct tu_bo *bo, uint64_t size)
92 {
93 /* TODO: Choose better flags. As of 2018-11-12, freedreno/drm/msm_bo.c
94 * always sets `flags = MSM_BO_WC`, and we copy that behavior here.
95 */
96 uint32_t gem_handle = tu_gem_new(dev, size, MSM_BO_WC);
97 if (!gem_handle)
98 return vk_error(dev->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
99
100 VkResult result = tu_bo_init(dev, bo, gem_handle, size);
101 if (result != VK_SUCCESS) {
102 tu_gem_close(dev, gem_handle);
103 return vk_error(dev->instance, result);
104 }
105
106 return VK_SUCCESS;
107 }
108
109 VkResult
110 tu_bo_init_dmabuf(struct tu_device *dev,
111 struct tu_bo *bo,
112 uint64_t size,
113 int fd)
114 {
115 uint32_t gem_handle = tu_gem_import_dmabuf(dev, fd, size);
116 if (!gem_handle)
117 return vk_error(dev->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
118
119 VkResult result = tu_bo_init(dev, bo, gem_handle, size);
120 if (result != VK_SUCCESS) {
121 tu_gem_close(dev, gem_handle);
122 return vk_error(dev->instance, result);
123 }
124
125 return VK_SUCCESS;
126 }
127
128 int
129 tu_bo_export_dmabuf(struct tu_device *dev, struct tu_bo *bo)
130 {
131 return tu_gem_export_dmabuf(dev, bo->gem_handle);
132 }
133
134 VkResult
135 tu_bo_map(struct tu_device *dev, struct tu_bo *bo)
136 {
137 if (bo->map)
138 return VK_SUCCESS;
139
140 uint64_t offset = tu_gem_info_offset(dev, bo->gem_handle);
141 if (!offset)
142 return vk_error(dev->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
143
144 /* TODO: Should we use the wrapper os_mmap() like Freedreno does? */
145 void *map = mmap(0, bo->size, PROT_READ | PROT_WRITE, MAP_SHARED,
146 dev->physical_device->local_fd, offset);
147 if (map == MAP_FAILED)
148 return vk_error(dev->instance, VK_ERROR_MEMORY_MAP_FAILED);
149
150 bo->map = map;
151 return VK_SUCCESS;
152 }
153
154 void
155 tu_bo_finish(struct tu_device *dev, struct tu_bo *bo)
156 {
157 assert(bo->gem_handle);
158
159 if (bo->map)
160 munmap(bo->map, bo->size);
161
162 tu_gem_close(dev, bo->gem_handle);
163 }
164
165 static VkResult
166 tu_physical_device_init(struct tu_physical_device *device,
167 struct tu_instance *instance,
168 drmDevicePtr drm_device)
169 {
170 const char *path = drm_device->nodes[DRM_NODE_RENDER];
171 VkResult result = VK_SUCCESS;
172 drmVersionPtr version;
173 int fd;
174 int master_fd = -1;
175
176 fd = open(path, O_RDWR | O_CLOEXEC);
177 if (fd < 0) {
178 return vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
179 "failed to open device %s", path);
180 }
181
182 /* Version 1.3 added MSM_INFO_IOVA. */
183 const int min_version_major = 1;
184 const int min_version_minor = 3;
185
186 version = drmGetVersion(fd);
187 if (!version) {
188 close(fd);
189 return vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
190 "failed to query kernel driver version for device %s",
191 path);
192 }
193
194 if (strcmp(version->name, "msm")) {
195 drmFreeVersion(version);
196 close(fd);
197 return vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
198 "device %s does not use the msm kernel driver", path);
199 }
200
201 if (version->version_major != min_version_major ||
202 version->version_minor < min_version_minor) {
203 result = vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
204 "kernel driver for device %s has version %d.%d, "
205 "but Vulkan requires version >= %d.%d",
206 path, version->version_major, version->version_minor,
207 min_version_major, min_version_minor);
208 drmFreeVersion(version);
209 close(fd);
210 return result;
211 }
212
213 device->msm_major_version = version->version_major;
214 device->msm_minor_version = version->version_minor;
215
216 drmFreeVersion(version);
217
218 if (instance->debug_flags & TU_DEBUG_STARTUP)
219 tu_logi("Found compatible device '%s'.", path);
220
221 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
222 device->instance = instance;
223 assert(strlen(path) < ARRAY_SIZE(device->path));
224 strncpy(device->path, path, ARRAY_SIZE(device->path));
225
226 if (instance->enabled_extensions.KHR_display) {
227 master_fd =
228 open(drm_device->nodes[DRM_NODE_PRIMARY], O_RDWR | O_CLOEXEC);
229 if (master_fd >= 0) {
230 /* TODO: free master_fd is accel is not working? */
231 }
232 }
233
234 device->master_fd = master_fd;
235 device->local_fd = fd;
236
237 if (tu_drm_get_gpu_id(device, &device->gpu_id)) {
238 if (instance->debug_flags & TU_DEBUG_STARTUP)
239 tu_logi("Could not query the GPU ID");
240 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
241 "could not get GPU ID");
242 goto fail;
243 }
244
245 if (tu_drm_get_gmem_size(device, &device->gmem_size)) {
246 if (instance->debug_flags & TU_DEBUG_STARTUP)
247 tu_logi("Could not query the GMEM size");
248 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
249 "could not get GMEM size");
250 goto fail;
251 }
252
253 if (tu_drm_get_gmem_base(device, &device->gmem_base)) {
254 if (instance->debug_flags & TU_DEBUG_STARTUP)
255 tu_logi("Could not query the GMEM size");
256 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
257 "could not get GMEM size");
258 goto fail;
259 }
260
261 memset(device->name, 0, sizeof(device->name));
262 sprintf(device->name, "FD%d", device->gpu_id);
263
264 switch (device->gpu_id) {
265 case 618:
266 device->ccu_offset_gmem = 0x7c000; /* 0x7e000 in some cases? */
267 device->ccu_offset_bypass = 0x10000;
268 device->tile_align_w = 64;
269 device->magic.PC_UNKNOWN_9805 = 0x0;
270 device->magic.SP_UNKNOWN_A0F8 = 0x0;
271 break;
272 case 630:
273 case 640:
274 device->ccu_offset_gmem = 0xf8000;
275 device->ccu_offset_bypass = 0x20000;
276 device->tile_align_w = 64;
277 device->magic.PC_UNKNOWN_9805 = 0x1;
278 device->magic.SP_UNKNOWN_A0F8 = 0x1;
279 break;
280 case 650:
281 device->ccu_offset_gmem = 0x114000;
282 device->ccu_offset_bypass = 0x30000;
283 device->tile_align_w = 96;
284 device->magic.PC_UNKNOWN_9805 = 0x2;
285 device->magic.SP_UNKNOWN_A0F8 = 0x2;
286 break;
287 default:
288 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
289 "device %s is unsupported", device->name);
290 goto fail;
291 }
292 if (tu_device_get_cache_uuid(device->gpu_id, device->cache_uuid)) {
293 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
294 "cannot generate UUID");
295 goto fail;
296 }
297
298 /* The gpu id is already embedded in the uuid so we just pass "tu"
299 * when creating the cache.
300 */
301 char buf[VK_UUID_SIZE * 2 + 1];
302 disk_cache_format_hex_id(buf, device->cache_uuid, VK_UUID_SIZE * 2);
303 device->disk_cache = disk_cache_create(device->name, buf, 0);
304
305 fprintf(stderr, "WARNING: tu is not a conformant vulkan implementation, "
306 "testing use only.\n");
307
308 fd_get_driver_uuid(device->driver_uuid);
309 fd_get_device_uuid(device->device_uuid, device->gpu_id);
310
311 tu_physical_device_get_supported_extensions(device, &device->supported_extensions);
312
313 if (result != VK_SUCCESS) {
314 vk_error(instance, result);
315 goto fail;
316 }
317
318 result = tu_wsi_init(device);
319 if (result != VK_SUCCESS) {
320 vk_error(instance, result);
321 goto fail;
322 }
323
324 return VK_SUCCESS;
325
326 fail:
327 close(fd);
328 if (master_fd != -1)
329 close(master_fd);
330 return result;
331 }
332
333 static void
334 tu_physical_device_finish(struct tu_physical_device *device)
335 {
336 tu_wsi_finish(device);
337
338 disk_cache_destroy(device->disk_cache);
339 close(device->local_fd);
340 if (device->master_fd != -1)
341 close(device->master_fd);
342 }
343
344 static VKAPI_ATTR void *
345 default_alloc_func(void *pUserData,
346 size_t size,
347 size_t align,
348 VkSystemAllocationScope allocationScope)
349 {
350 return malloc(size);
351 }
352
353 static VKAPI_ATTR void *
354 default_realloc_func(void *pUserData,
355 void *pOriginal,
356 size_t size,
357 size_t align,
358 VkSystemAllocationScope allocationScope)
359 {
360 return realloc(pOriginal, size);
361 }
362
363 static VKAPI_ATTR void
364 default_free_func(void *pUserData, void *pMemory)
365 {
366 free(pMemory);
367 }
368
369 static const VkAllocationCallbacks default_alloc = {
370 .pUserData = NULL,
371 .pfnAllocation = default_alloc_func,
372 .pfnReallocation = default_realloc_func,
373 .pfnFree = default_free_func,
374 };
375
376 static const struct debug_control tu_debug_options[] = {
377 { "startup", TU_DEBUG_STARTUP },
378 { "nir", TU_DEBUG_NIR },
379 { "ir3", TU_DEBUG_IR3 },
380 { "nobin", TU_DEBUG_NOBIN },
381 { "sysmem", TU_DEBUG_SYSMEM },
382 { "forcebin", TU_DEBUG_FORCEBIN },
383 { "noubwc", TU_DEBUG_NOUBWC },
384 { NULL, 0 }
385 };
386
387 const char *
388 tu_get_debug_option_name(int id)
389 {
390 assert(id < ARRAY_SIZE(tu_debug_options) - 1);
391 return tu_debug_options[id].string;
392 }
393
394 static int
395 tu_get_instance_extension_index(const char *name)
396 {
397 for (unsigned i = 0; i < TU_INSTANCE_EXTENSION_COUNT; ++i) {
398 if (strcmp(name, tu_instance_extensions[i].extensionName) == 0)
399 return i;
400 }
401 return -1;
402 }
403
404 VkResult
405 tu_CreateInstance(const VkInstanceCreateInfo *pCreateInfo,
406 const VkAllocationCallbacks *pAllocator,
407 VkInstance *pInstance)
408 {
409 struct tu_instance *instance;
410 VkResult result;
411
412 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
413
414 uint32_t client_version;
415 if (pCreateInfo->pApplicationInfo &&
416 pCreateInfo->pApplicationInfo->apiVersion != 0) {
417 client_version = pCreateInfo->pApplicationInfo->apiVersion;
418 } else {
419 tu_EnumerateInstanceVersion(&client_version);
420 }
421
422 instance = vk_zalloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
423 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
424 if (!instance)
425 return vk_error(NULL, VK_ERROR_OUT_OF_HOST_MEMORY);
426
427 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
428
429 if (pAllocator)
430 instance->alloc = *pAllocator;
431 else
432 instance->alloc = default_alloc;
433
434 instance->api_version = client_version;
435 instance->physical_device_count = -1;
436
437 instance->debug_flags =
438 parse_debug_string(getenv("TU_DEBUG"), tu_debug_options);
439
440 if (instance->debug_flags & TU_DEBUG_STARTUP)
441 tu_logi("Created an instance");
442
443 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
444 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
445 int index = tu_get_instance_extension_index(ext_name);
446
447 if (index < 0 || !tu_instance_extensions_supported.extensions[index]) {
448 vk_free2(&default_alloc, pAllocator, instance);
449 return vk_error(instance, VK_ERROR_EXTENSION_NOT_PRESENT);
450 }
451
452 instance->enabled_extensions.extensions[index] = true;
453 }
454
455 result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
456 if (result != VK_SUCCESS) {
457 vk_free2(&default_alloc, pAllocator, instance);
458 return vk_error(instance, result);
459 }
460
461 glsl_type_singleton_init_or_ref();
462
463 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
464
465 *pInstance = tu_instance_to_handle(instance);
466
467 return VK_SUCCESS;
468 }
469
470 void
471 tu_DestroyInstance(VkInstance _instance,
472 const VkAllocationCallbacks *pAllocator)
473 {
474 TU_FROM_HANDLE(tu_instance, instance, _instance);
475
476 if (!instance)
477 return;
478
479 for (int i = 0; i < instance->physical_device_count; ++i) {
480 tu_physical_device_finish(instance->physical_devices + i);
481 }
482
483 VG(VALGRIND_DESTROY_MEMPOOL(instance));
484
485 glsl_type_singleton_decref();
486
487 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
488
489 vk_free(&instance->alloc, instance);
490 }
491
492 static VkResult
493 tu_enumerate_devices(struct tu_instance *instance)
494 {
495 /* TODO: Check for more devices ? */
496 drmDevicePtr devices[8];
497 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
498 int max_devices;
499
500 instance->physical_device_count = 0;
501
502 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
503
504 if (instance->debug_flags & TU_DEBUG_STARTUP) {
505 if (max_devices < 0)
506 tu_logi("drmGetDevices2 returned error: %s\n", strerror(max_devices));
507 else
508 tu_logi("Found %d drm nodes", max_devices);
509 }
510
511 if (max_devices < 1)
512 return vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
513
514 for (unsigned i = 0; i < (unsigned) max_devices; i++) {
515 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
516 devices[i]->bustype == DRM_BUS_PLATFORM) {
517
518 result = tu_physical_device_init(
519 instance->physical_devices + instance->physical_device_count,
520 instance, devices[i]);
521 if (result == VK_SUCCESS)
522 ++instance->physical_device_count;
523 else if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
524 break;
525 }
526 }
527 drmFreeDevices(devices, max_devices);
528
529 return result;
530 }
531
532 VkResult
533 tu_EnumeratePhysicalDevices(VkInstance _instance,
534 uint32_t *pPhysicalDeviceCount,
535 VkPhysicalDevice *pPhysicalDevices)
536 {
537 TU_FROM_HANDLE(tu_instance, instance, _instance);
538 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
539
540 VkResult result;
541
542 if (instance->physical_device_count < 0) {
543 result = tu_enumerate_devices(instance);
544 if (result != VK_SUCCESS && result != VK_ERROR_INCOMPATIBLE_DRIVER)
545 return result;
546 }
547
548 for (uint32_t i = 0; i < instance->physical_device_count; ++i) {
549 vk_outarray_append(&out, p)
550 {
551 *p = tu_physical_device_to_handle(instance->physical_devices + i);
552 }
553 }
554
555 return vk_outarray_status(&out);
556 }
557
558 VkResult
559 tu_EnumeratePhysicalDeviceGroups(
560 VkInstance _instance,
561 uint32_t *pPhysicalDeviceGroupCount,
562 VkPhysicalDeviceGroupProperties *pPhysicalDeviceGroupProperties)
563 {
564 TU_FROM_HANDLE(tu_instance, instance, _instance);
565 VK_OUTARRAY_MAKE(out, pPhysicalDeviceGroupProperties,
566 pPhysicalDeviceGroupCount);
567 VkResult result;
568
569 if (instance->physical_device_count < 0) {
570 result = tu_enumerate_devices(instance);
571 if (result != VK_SUCCESS && result != VK_ERROR_INCOMPATIBLE_DRIVER)
572 return result;
573 }
574
575 for (uint32_t i = 0; i < instance->physical_device_count; ++i) {
576 vk_outarray_append(&out, p)
577 {
578 p->physicalDeviceCount = 1;
579 p->physicalDevices[0] =
580 tu_physical_device_to_handle(instance->physical_devices + i);
581 p->subsetAllocation = false;
582 }
583 }
584
585 return vk_outarray_status(&out);
586 }
587
588 void
589 tu_GetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice,
590 VkPhysicalDeviceFeatures *pFeatures)
591 {
592 memset(pFeatures, 0, sizeof(*pFeatures));
593
594 *pFeatures = (VkPhysicalDeviceFeatures) {
595 .robustBufferAccess = true,
596 .fullDrawIndexUint32 = true,
597 .imageCubeArray = true,
598 .independentBlend = true,
599 .geometryShader = true,
600 .tessellationShader = true,
601 .sampleRateShading = true,
602 .dualSrcBlend = true,
603 .logicOp = true,
604 .multiDrawIndirect = true,
605 .drawIndirectFirstInstance = true,
606 .depthClamp = true,
607 .depthBiasClamp = false,
608 .fillModeNonSolid = true,
609 .depthBounds = true,
610 .wideLines = false,
611 .largePoints = true,
612 .alphaToOne = true,
613 .multiViewport = false,
614 .samplerAnisotropy = true,
615 .textureCompressionETC2 = true,
616 .textureCompressionASTC_LDR = true,
617 .textureCompressionBC = true,
618 .occlusionQueryPrecise = true,
619 .pipelineStatisticsQuery = false,
620 .vertexPipelineStoresAndAtomics = false,
621 .fragmentStoresAndAtomics = false,
622 .shaderTessellationAndGeometryPointSize = false,
623 .shaderImageGatherExtended = false,
624 .shaderStorageImageExtendedFormats = false,
625 .shaderStorageImageMultisample = false,
626 .shaderUniformBufferArrayDynamicIndexing = false,
627 .shaderSampledImageArrayDynamicIndexing = false,
628 .shaderStorageBufferArrayDynamicIndexing = false,
629 .shaderStorageImageArrayDynamicIndexing = false,
630 .shaderStorageImageReadWithoutFormat = false,
631 .shaderStorageImageWriteWithoutFormat = false,
632 .shaderClipDistance = false,
633 .shaderCullDistance = false,
634 .shaderFloat64 = false,
635 .shaderInt64 = false,
636 .shaderInt16 = false,
637 .sparseBinding = false,
638 .variableMultisampleRate = false,
639 .inheritedQueries = false,
640 };
641 }
642
643 void
644 tu_GetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
645 VkPhysicalDeviceFeatures2 *pFeatures)
646 {
647 vk_foreach_struct(ext, pFeatures->pNext)
648 {
649 switch (ext->sType) {
650 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES: {
651 VkPhysicalDeviceVulkan11Features *features = (void *) ext;
652 features->storageBuffer16BitAccess = false;
653 features->uniformAndStorageBuffer16BitAccess = false;
654 features->storagePushConstant16 = false;
655 features->storageInputOutput16 = false;
656 features->multiview = false;
657 features->multiviewGeometryShader = false;
658 features->multiviewTessellationShader = false;
659 features->variablePointersStorageBuffer = false;
660 features->variablePointers = false;
661 features->protectedMemory = false;
662 features->samplerYcbcrConversion = true;
663 features->shaderDrawParameters = true;
664 break;
665 }
666 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES: {
667 VkPhysicalDeviceVariablePointersFeatures *features = (void *) ext;
668 features->variablePointersStorageBuffer = false;
669 features->variablePointers = false;
670 break;
671 }
672 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
673 VkPhysicalDeviceMultiviewFeatures *features =
674 (VkPhysicalDeviceMultiviewFeatures *) ext;
675 features->multiview = false;
676 features->multiviewGeometryShader = false;
677 features->multiviewTessellationShader = false;
678 break;
679 }
680 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES: {
681 VkPhysicalDeviceShaderDrawParametersFeatures *features =
682 (VkPhysicalDeviceShaderDrawParametersFeatures *) ext;
683 features->shaderDrawParameters = true;
684 break;
685 }
686 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
687 VkPhysicalDeviceProtectedMemoryFeatures *features =
688 (VkPhysicalDeviceProtectedMemoryFeatures *) ext;
689 features->protectedMemory = false;
690 break;
691 }
692 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES: {
693 VkPhysicalDevice16BitStorageFeatures *features =
694 (VkPhysicalDevice16BitStorageFeatures *) ext;
695 features->storageBuffer16BitAccess = false;
696 features->uniformAndStorageBuffer16BitAccess = false;
697 features->storagePushConstant16 = false;
698 features->storageInputOutput16 = false;
699 break;
700 }
701 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
702 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
703 (VkPhysicalDeviceSamplerYcbcrConversionFeatures *) ext;
704 features->samplerYcbcrConversion = true;
705 break;
706 }
707 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT: {
708 VkPhysicalDeviceDescriptorIndexingFeaturesEXT *features =
709 (VkPhysicalDeviceDescriptorIndexingFeaturesEXT *) ext;
710 features->shaderInputAttachmentArrayDynamicIndexing = false;
711 features->shaderUniformTexelBufferArrayDynamicIndexing = false;
712 features->shaderStorageTexelBufferArrayDynamicIndexing = false;
713 features->shaderUniformBufferArrayNonUniformIndexing = false;
714 features->shaderSampledImageArrayNonUniformIndexing = false;
715 features->shaderStorageBufferArrayNonUniformIndexing = false;
716 features->shaderStorageImageArrayNonUniformIndexing = false;
717 features->shaderInputAttachmentArrayNonUniformIndexing = false;
718 features->shaderUniformTexelBufferArrayNonUniformIndexing = false;
719 features->shaderStorageTexelBufferArrayNonUniformIndexing = false;
720 features->descriptorBindingUniformBufferUpdateAfterBind = false;
721 features->descriptorBindingSampledImageUpdateAfterBind = false;
722 features->descriptorBindingStorageImageUpdateAfterBind = false;
723 features->descriptorBindingStorageBufferUpdateAfterBind = false;
724 features->descriptorBindingUniformTexelBufferUpdateAfterBind = false;
725 features->descriptorBindingStorageTexelBufferUpdateAfterBind = false;
726 features->descriptorBindingUpdateUnusedWhilePending = false;
727 features->descriptorBindingPartiallyBound = false;
728 features->descriptorBindingVariableDescriptorCount = false;
729 features->runtimeDescriptorArray = false;
730 break;
731 }
732 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT: {
733 VkPhysicalDeviceConditionalRenderingFeaturesEXT *features =
734 (VkPhysicalDeviceConditionalRenderingFeaturesEXT *) ext;
735 features->conditionalRendering = false;
736 features->inheritedConditionalRendering = false;
737 break;
738 }
739 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT: {
740 VkPhysicalDeviceTransformFeedbackFeaturesEXT *features =
741 (VkPhysicalDeviceTransformFeedbackFeaturesEXT *) ext;
742 features->transformFeedback = true;
743 features->geometryStreams = false;
744 break;
745 }
746 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INDEX_TYPE_UINT8_FEATURES_EXT: {
747 VkPhysicalDeviceIndexTypeUint8FeaturesEXT *features =
748 (VkPhysicalDeviceIndexTypeUint8FeaturesEXT *)ext;
749 features->indexTypeUint8 = true;
750 break;
751 }
752 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
753 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
754 (VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
755 features->vertexAttributeInstanceRateDivisor = true;
756 features->vertexAttributeInstanceRateZeroDivisor = true;
757 break;
758 }
759 default:
760 break;
761 }
762 }
763 return tu_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
764 }
765
766 void
767 tu_GetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,
768 VkPhysicalDeviceProperties *pProperties)
769 {
770 TU_FROM_HANDLE(tu_physical_device, pdevice, physicalDevice);
771 VkSampleCountFlags sample_counts =
772 VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT;
773
774 /* I have no idea what the maximum size is, but the hardware supports very
775 * large numbers of descriptors (at least 2^16). This limit is based on
776 * CP_LOAD_STATE6, which has a 28-bit field for the DWORD offset, so that
777 * we don't have to think about what to do if that overflows, but really
778 * nothing is likely to get close to this.
779 */
780 const size_t max_descriptor_set_size = (1 << 28) / A6XX_TEX_CONST_DWORDS;
781
782 VkPhysicalDeviceLimits limits = {
783 .maxImageDimension1D = (1 << 14),
784 .maxImageDimension2D = (1 << 14),
785 .maxImageDimension3D = (1 << 11),
786 .maxImageDimensionCube = (1 << 14),
787 .maxImageArrayLayers = (1 << 11),
788 .maxTexelBufferElements = 128 * 1024 * 1024,
789 .maxUniformBufferRange = MAX_UNIFORM_BUFFER_RANGE,
790 .maxStorageBufferRange = MAX_STORAGE_BUFFER_RANGE,
791 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
792 .maxMemoryAllocationCount = UINT32_MAX,
793 .maxSamplerAllocationCount = 64 * 1024,
794 .bufferImageGranularity = 64, /* A cache line */
795 .sparseAddressSpaceSize = 0xffffffffu, /* buffer max size */
796 .maxBoundDescriptorSets = MAX_SETS,
797 .maxPerStageDescriptorSamplers = max_descriptor_set_size,
798 .maxPerStageDescriptorUniformBuffers = max_descriptor_set_size,
799 .maxPerStageDescriptorStorageBuffers = max_descriptor_set_size,
800 .maxPerStageDescriptorSampledImages = max_descriptor_set_size,
801 .maxPerStageDescriptorStorageImages = max_descriptor_set_size,
802 .maxPerStageDescriptorInputAttachments = MAX_RTS,
803 .maxPerStageResources = max_descriptor_set_size,
804 .maxDescriptorSetSamplers = max_descriptor_set_size,
805 .maxDescriptorSetUniformBuffers = max_descriptor_set_size,
806 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS,
807 .maxDescriptorSetStorageBuffers = max_descriptor_set_size,
808 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS,
809 .maxDescriptorSetSampledImages = max_descriptor_set_size,
810 .maxDescriptorSetStorageImages = max_descriptor_set_size,
811 .maxDescriptorSetInputAttachments = MAX_RTS,
812 .maxVertexInputAttributes = 32,
813 .maxVertexInputBindings = 32,
814 .maxVertexInputAttributeOffset = 4095,
815 .maxVertexInputBindingStride = 2048,
816 .maxVertexOutputComponents = 128,
817 .maxTessellationGenerationLevel = 64,
818 .maxTessellationPatchSize = 32,
819 .maxTessellationControlPerVertexInputComponents = 128,
820 .maxTessellationControlPerVertexOutputComponents = 128,
821 .maxTessellationControlPerPatchOutputComponents = 120,
822 .maxTessellationControlTotalOutputComponents = 4096,
823 .maxTessellationEvaluationInputComponents = 128,
824 .maxTessellationEvaluationOutputComponents = 128,
825 .maxGeometryShaderInvocations = 32,
826 .maxGeometryInputComponents = 64,
827 .maxGeometryOutputComponents = 128,
828 .maxGeometryOutputVertices = 256,
829 .maxGeometryTotalOutputComponents = 1024,
830 .maxFragmentInputComponents = 124,
831 .maxFragmentOutputAttachments = 8,
832 .maxFragmentDualSrcAttachments = 1,
833 .maxFragmentCombinedOutputResources = 8,
834 .maxComputeSharedMemorySize = 32768,
835 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
836 .maxComputeWorkGroupInvocations = 2048,
837 .maxComputeWorkGroupSize = { 2048, 2048, 2048 },
838 .subPixelPrecisionBits = 8,
839 .subTexelPrecisionBits = 8,
840 .mipmapPrecisionBits = 8,
841 .maxDrawIndexedIndexValue = UINT32_MAX,
842 .maxDrawIndirectCount = UINT32_MAX,
843 .maxSamplerLodBias = 4095.0 / 256.0, /* [-16, 15.99609375] */
844 .maxSamplerAnisotropy = 16,
845 .maxViewports = MAX_VIEWPORTS,
846 .maxViewportDimensions = { (1 << 14), (1 << 14) },
847 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
848 .viewportSubPixelBits = 8,
849 .minMemoryMapAlignment = 4096, /* A page */
850 .minTexelBufferOffsetAlignment = 64,
851 .minUniformBufferOffsetAlignment = 64,
852 .minStorageBufferOffsetAlignment = 64,
853 .minTexelOffset = -16,
854 .maxTexelOffset = 15,
855 .minTexelGatherOffset = -32,
856 .maxTexelGatherOffset = 31,
857 .minInterpolationOffset = -0.5,
858 .maxInterpolationOffset = 0.4375,
859 .subPixelInterpolationOffsetBits = 4,
860 .maxFramebufferWidth = (1 << 14),
861 .maxFramebufferHeight = (1 << 14),
862 .maxFramebufferLayers = (1 << 10),
863 .framebufferColorSampleCounts = sample_counts,
864 .framebufferDepthSampleCounts = sample_counts,
865 .framebufferStencilSampleCounts = sample_counts,
866 .framebufferNoAttachmentsSampleCounts = sample_counts,
867 .maxColorAttachments = MAX_RTS,
868 .sampledImageColorSampleCounts = sample_counts,
869 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
870 .sampledImageDepthSampleCounts = sample_counts,
871 .sampledImageStencilSampleCounts = sample_counts,
872 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
873 .maxSampleMaskWords = 1,
874 .timestampComputeAndGraphics = true,
875 .timestampPeriod = 1000000000.0 / 19200000.0, /* CP_ALWAYS_ON_COUNTER is fixed 19.2MHz */
876 .maxClipDistances = 8,
877 .maxCullDistances = 8,
878 .maxCombinedClipAndCullDistances = 8,
879 .discreteQueuePriorities = 1,
880 .pointSizeRange = { 1, 4092 },
881 .lineWidthRange = { 0.0, 7.9921875 },
882 .pointSizeGranularity = 0.0625,
883 .lineWidthGranularity = (1.0 / 128.0),
884 .strictLines = false, /* FINISHME */
885 .standardSampleLocations = true,
886 .optimalBufferCopyOffsetAlignment = 128,
887 .optimalBufferCopyRowPitchAlignment = 128,
888 .nonCoherentAtomSize = 64,
889 };
890
891 *pProperties = (VkPhysicalDeviceProperties) {
892 .apiVersion = tu_physical_device_api_version(pdevice),
893 .driverVersion = vk_get_driver_version(),
894 .vendorID = 0, /* TODO */
895 .deviceID = 0,
896 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
897 .limits = limits,
898 .sparseProperties = { 0 },
899 };
900
901 strcpy(pProperties->deviceName, pdevice->name);
902 memcpy(pProperties->pipelineCacheUUID, pdevice->cache_uuid, VK_UUID_SIZE);
903 }
904
905 void
906 tu_GetPhysicalDeviceProperties2(VkPhysicalDevice physicalDevice,
907 VkPhysicalDeviceProperties2 *pProperties)
908 {
909 TU_FROM_HANDLE(tu_physical_device, pdevice, physicalDevice);
910 tu_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
911
912 vk_foreach_struct(ext, pProperties->pNext)
913 {
914 switch (ext->sType) {
915 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
916 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
917 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
918 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
919 break;
920 }
921 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
922 VkPhysicalDeviceIDProperties *properties =
923 (VkPhysicalDeviceIDProperties *) ext;
924 memcpy(properties->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
925 memcpy(properties->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
926 properties->deviceLUIDValid = false;
927 break;
928 }
929 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
930 VkPhysicalDeviceMultiviewProperties *properties =
931 (VkPhysicalDeviceMultiviewProperties *) ext;
932 properties->maxMultiviewViewCount = MAX_VIEWS;
933 properties->maxMultiviewInstanceIndex = INT_MAX;
934 break;
935 }
936 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
937 VkPhysicalDevicePointClippingProperties *properties =
938 (VkPhysicalDevicePointClippingProperties *) ext;
939 properties->pointClippingBehavior =
940 VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
941 break;
942 }
943 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
944 VkPhysicalDeviceMaintenance3Properties *properties =
945 (VkPhysicalDeviceMaintenance3Properties *) ext;
946 /* Make sure everything is addressable by a signed 32-bit int, and
947 * our largest descriptors are 96 bytes. */
948 properties->maxPerSetDescriptors = (1ull << 31) / 96;
949 /* Our buffer size fields allow only this much */
950 properties->maxMemoryAllocationSize = 0xFFFFFFFFull;
951 break;
952 }
953 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT: {
954 VkPhysicalDeviceTransformFeedbackPropertiesEXT *properties =
955 (VkPhysicalDeviceTransformFeedbackPropertiesEXT *)ext;
956
957 properties->maxTransformFeedbackStreams = IR3_MAX_SO_STREAMS;
958 properties->maxTransformFeedbackBuffers = IR3_MAX_SO_BUFFERS;
959 properties->maxTransformFeedbackBufferSize = UINT32_MAX;
960 properties->maxTransformFeedbackStreamDataSize = 512;
961 properties->maxTransformFeedbackBufferDataSize = 512;
962 properties->maxTransformFeedbackBufferDataStride = 512;
963 properties->transformFeedbackQueries = true;
964 properties->transformFeedbackStreamsLinesTriangles = false;
965 properties->transformFeedbackRasterizationStreamSelect = false;
966 properties->transformFeedbackDraw = true;
967 break;
968 }
969 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT: {
970 VkPhysicalDeviceSampleLocationsPropertiesEXT *properties =
971 (VkPhysicalDeviceSampleLocationsPropertiesEXT *)ext;
972 properties->sampleLocationSampleCounts = 0;
973 if (pdevice->supported_extensions.EXT_sample_locations) {
974 properties->sampleLocationSampleCounts =
975 VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT;
976 }
977 properties->maxSampleLocationGridSize = (VkExtent2D) { 1 , 1 };
978 properties->sampleLocationCoordinateRange[0] = 0.0f;
979 properties->sampleLocationCoordinateRange[1] = 0.9375f;
980 properties->sampleLocationSubPixelBits = 4;
981 properties->variableSampleLocations = true;
982 break;
983 }
984 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES: {
985 VkPhysicalDeviceSamplerFilterMinmaxProperties *properties =
986 (VkPhysicalDeviceSamplerFilterMinmaxProperties *)ext;
987 properties->filterMinmaxImageComponentMapping = true;
988 properties->filterMinmaxSingleComponentFormats = true;
989 break;
990 }
991 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
992 VkPhysicalDeviceSubgroupProperties *properties =
993 (VkPhysicalDeviceSubgroupProperties *)ext;
994 properties->subgroupSize = 64;
995 properties->supportedStages = VK_SHADER_STAGE_COMPUTE_BIT;
996 properties->supportedOperations = VK_SUBGROUP_FEATURE_BASIC_BIT |
997 VK_SUBGROUP_FEATURE_VOTE_BIT;
998 properties->quadOperationsInAllStages = false;
999 break;
1000 }
1001 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
1002 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *props =
1003 (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
1004 props->maxVertexAttribDivisor = UINT32_MAX;
1005 break;
1006 }
1007 default:
1008 break;
1009 }
1010 }
1011 }
1012
1013 static const VkQueueFamilyProperties tu_queue_family_properties = {
1014 .queueFlags =
1015 VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT,
1016 .queueCount = 1,
1017 .timestampValidBits = 48,
1018 .minImageTransferGranularity = { 1, 1, 1 },
1019 };
1020
1021 void
1022 tu_GetPhysicalDeviceQueueFamilyProperties(
1023 VkPhysicalDevice physicalDevice,
1024 uint32_t *pQueueFamilyPropertyCount,
1025 VkQueueFamilyProperties *pQueueFamilyProperties)
1026 {
1027 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
1028
1029 vk_outarray_append(&out, p) { *p = tu_queue_family_properties; }
1030 }
1031
1032 void
1033 tu_GetPhysicalDeviceQueueFamilyProperties2(
1034 VkPhysicalDevice physicalDevice,
1035 uint32_t *pQueueFamilyPropertyCount,
1036 VkQueueFamilyProperties2 *pQueueFamilyProperties)
1037 {
1038 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
1039
1040 vk_outarray_append(&out, p)
1041 {
1042 p->queueFamilyProperties = tu_queue_family_properties;
1043 }
1044 }
1045
1046 static uint64_t
1047 tu_get_system_heap_size()
1048 {
1049 struct sysinfo info;
1050 sysinfo(&info);
1051
1052 uint64_t total_ram = (uint64_t) info.totalram * (uint64_t) info.mem_unit;
1053
1054 /* We don't want to burn too much ram with the GPU. If the user has 4GiB
1055 * or less, we use at most half. If they have more than 4GiB, we use 3/4.
1056 */
1057 uint64_t available_ram;
1058 if (total_ram <= 4ull * 1024ull * 1024ull * 1024ull)
1059 available_ram = total_ram / 2;
1060 else
1061 available_ram = total_ram * 3 / 4;
1062
1063 return available_ram;
1064 }
1065
1066 void
1067 tu_GetPhysicalDeviceMemoryProperties(
1068 VkPhysicalDevice physicalDevice,
1069 VkPhysicalDeviceMemoryProperties *pMemoryProperties)
1070 {
1071 pMemoryProperties->memoryHeapCount = 1;
1072 pMemoryProperties->memoryHeaps[0].size = tu_get_system_heap_size();
1073 pMemoryProperties->memoryHeaps[0].flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT;
1074
1075 pMemoryProperties->memoryTypeCount = 1;
1076 pMemoryProperties->memoryTypes[0].propertyFlags =
1077 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
1078 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
1079 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
1080 pMemoryProperties->memoryTypes[0].heapIndex = 0;
1081 }
1082
1083 void
1084 tu_GetPhysicalDeviceMemoryProperties2(
1085 VkPhysicalDevice physicalDevice,
1086 VkPhysicalDeviceMemoryProperties2 *pMemoryProperties)
1087 {
1088 return tu_GetPhysicalDeviceMemoryProperties(
1089 physicalDevice, &pMemoryProperties->memoryProperties);
1090 }
1091
1092 static VkResult
1093 tu_queue_init(struct tu_device *device,
1094 struct tu_queue *queue,
1095 uint32_t queue_family_index,
1096 int idx,
1097 VkDeviceQueueCreateFlags flags)
1098 {
1099 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1100 queue->device = device;
1101 queue->queue_family_index = queue_family_index;
1102 queue->queue_idx = idx;
1103 queue->flags = flags;
1104
1105 int ret = tu_drm_submitqueue_new(device, 0, &queue->msm_queue_id);
1106 if (ret)
1107 return VK_ERROR_INITIALIZATION_FAILED;
1108
1109 tu_fence_init(&queue->submit_fence, false);
1110
1111 return VK_SUCCESS;
1112 }
1113
1114 static void
1115 tu_queue_finish(struct tu_queue *queue)
1116 {
1117 tu_fence_finish(&queue->submit_fence);
1118 tu_drm_submitqueue_close(queue->device, queue->msm_queue_id);
1119 }
1120
1121 static int
1122 tu_get_device_extension_index(const char *name)
1123 {
1124 for (unsigned i = 0; i < TU_DEVICE_EXTENSION_COUNT; ++i) {
1125 if (strcmp(name, tu_device_extensions[i].extensionName) == 0)
1126 return i;
1127 }
1128 return -1;
1129 }
1130
1131 struct PACKED bcolor_entry {
1132 uint32_t fp32[4];
1133 uint16_t ui16[4];
1134 int16_t si16[4];
1135 uint16_t fp16[4];
1136 uint16_t rgb565;
1137 uint16_t rgb5a1;
1138 uint16_t rgba4;
1139 uint8_t __pad0[2];
1140 uint8_t ui8[4];
1141 int8_t si8[4];
1142 uint32_t rgb10a2;
1143 uint32_t z24; /* also s8? */
1144 uint16_t srgb[4]; /* appears to duplicate fp16[], but clamped, used for srgb */
1145 uint8_t __pad1[56];
1146 } border_color[] = {
1147 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = {},
1148 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = {},
1149 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = {
1150 .fp32[3] = 0x3f800000,
1151 .ui16[3] = 0xffff,
1152 .si16[3] = 0x7fff,
1153 .fp16[3] = 0x3c00,
1154 .rgb5a1 = 0x8000,
1155 .rgba4 = 0xf000,
1156 .ui8[3] = 0xff,
1157 .si8[3] = 0x7f,
1158 .rgb10a2 = 0xc0000000,
1159 .srgb[3] = 0x3c00,
1160 },
1161 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = {
1162 .fp32[3] = 1,
1163 .fp16[3] = 1,
1164 },
1165 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = {
1166 .fp32[0 ... 3] = 0x3f800000,
1167 .ui16[0 ... 3] = 0xffff,
1168 .si16[0 ... 3] = 0x7fff,
1169 .fp16[0 ... 3] = 0x3c00,
1170 .rgb565 = 0xffff,
1171 .rgb5a1 = 0xffff,
1172 .rgba4 = 0xffff,
1173 .ui8[0 ... 3] = 0xff,
1174 .si8[0 ... 3] = 0x7f,
1175 .rgb10a2 = 0xffffffff,
1176 .z24 = 0xffffff,
1177 .srgb[0 ... 3] = 0x3c00,
1178 },
1179 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = {
1180 .fp32[0 ... 3] = 1,
1181 .fp16[0 ... 3] = 1,
1182 },
1183 };
1184
1185
1186 VkResult
1187 tu_CreateDevice(VkPhysicalDevice physicalDevice,
1188 const VkDeviceCreateInfo *pCreateInfo,
1189 const VkAllocationCallbacks *pAllocator,
1190 VkDevice *pDevice)
1191 {
1192 TU_FROM_HANDLE(tu_physical_device, physical_device, physicalDevice);
1193 VkResult result;
1194 struct tu_device *device;
1195
1196 /* Check enabled features */
1197 if (pCreateInfo->pEnabledFeatures) {
1198 VkPhysicalDeviceFeatures supported_features;
1199 tu_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1200 VkBool32 *supported_feature = (VkBool32 *) &supported_features;
1201 VkBool32 *enabled_feature = (VkBool32 *) pCreateInfo->pEnabledFeatures;
1202 unsigned num_features =
1203 sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1204 for (uint32_t i = 0; i < num_features; i++) {
1205 if (enabled_feature[i] && !supported_feature[i])
1206 return vk_error(physical_device->instance,
1207 VK_ERROR_FEATURE_NOT_PRESENT);
1208 }
1209 }
1210
1211 device = vk_zalloc2(&physical_device->instance->alloc, pAllocator,
1212 sizeof(*device), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1213 if (!device)
1214 return vk_error(physical_device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1215
1216 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1217 device->instance = physical_device->instance;
1218 device->physical_device = physical_device;
1219 device->_lost = false;
1220
1221 if (pAllocator)
1222 device->alloc = *pAllocator;
1223 else
1224 device->alloc = physical_device->instance->alloc;
1225
1226 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1227 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
1228 int index = tu_get_device_extension_index(ext_name);
1229 if (index < 0 ||
1230 !physical_device->supported_extensions.extensions[index]) {
1231 vk_free(&device->alloc, device);
1232 return vk_error(physical_device->instance,
1233 VK_ERROR_EXTENSION_NOT_PRESENT);
1234 }
1235
1236 device->enabled_extensions.extensions[index] = true;
1237 }
1238
1239 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
1240 const VkDeviceQueueCreateInfo *queue_create =
1241 &pCreateInfo->pQueueCreateInfos[i];
1242 uint32_t qfi = queue_create->queueFamilyIndex;
1243 device->queues[qfi] = vk_alloc(
1244 &device->alloc, queue_create->queueCount * sizeof(struct tu_queue),
1245 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1246 if (!device->queues[qfi]) {
1247 result = VK_ERROR_OUT_OF_HOST_MEMORY;
1248 goto fail_queues;
1249 }
1250
1251 memset(device->queues[qfi], 0,
1252 queue_create->queueCount * sizeof(struct tu_queue));
1253
1254 device->queue_count[qfi] = queue_create->queueCount;
1255
1256 for (unsigned q = 0; q < queue_create->queueCount; q++) {
1257 result = tu_queue_init(device, &device->queues[qfi][q], qfi, q,
1258 queue_create->flags);
1259 if (result != VK_SUCCESS)
1260 goto fail_queues;
1261 }
1262 }
1263
1264 device->compiler = ir3_compiler_create(NULL, physical_device->gpu_id);
1265 if (!device->compiler)
1266 goto fail_queues;
1267
1268 #define VSC_DRAW_STRM_SIZE(pitch) ((pitch) * 32 + 0x100) /* extra size to store VSC_SIZE */
1269 #define VSC_PRIM_STRM_SIZE(pitch) ((pitch) * 32)
1270
1271 device->vsc_draw_strm_pitch = 0x440 * 4;
1272 device->vsc_prim_strm_pitch = 0x1040 * 4;
1273
1274 result = tu_bo_init_new(device, &device->vsc_draw_strm, VSC_DRAW_STRM_SIZE(device->vsc_draw_strm_pitch));
1275 if (result != VK_SUCCESS)
1276 goto fail_vsc_data;
1277
1278 result = tu_bo_init_new(device, &device->vsc_prim_strm, VSC_PRIM_STRM_SIZE(device->vsc_prim_strm_pitch));
1279 if (result != VK_SUCCESS)
1280 goto fail_vsc_data2;
1281
1282 STATIC_ASSERT(sizeof(struct bcolor_entry) == 128);
1283 result = tu_bo_init_new(device, &device->border_color, sizeof(border_color));
1284 if (result != VK_SUCCESS)
1285 goto fail_border_color;
1286
1287 result = tu_bo_map(device, &device->border_color);
1288 if (result != VK_SUCCESS)
1289 goto fail_border_color_map;
1290
1291 memcpy(device->border_color.map, border_color, sizeof(border_color));
1292
1293 VkPipelineCacheCreateInfo ci;
1294 ci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
1295 ci.pNext = NULL;
1296 ci.flags = 0;
1297 ci.pInitialData = NULL;
1298 ci.initialDataSize = 0;
1299 VkPipelineCache pc;
1300 result =
1301 tu_CreatePipelineCache(tu_device_to_handle(device), &ci, NULL, &pc);
1302 if (result != VK_SUCCESS)
1303 goto fail_pipeline_cache;
1304
1305 device->mem_cache = tu_pipeline_cache_from_handle(pc);
1306
1307 for (unsigned i = 0; i < ARRAY_SIZE(device->scratch_bos); i++)
1308 mtx_init(&device->scratch_bos[i].construct_mtx, mtx_plain);
1309
1310 *pDevice = tu_device_to_handle(device);
1311 return VK_SUCCESS;
1312
1313 fail_pipeline_cache:
1314 fail_border_color_map:
1315 tu_bo_finish(device, &device->border_color);
1316
1317 fail_border_color:
1318 tu_bo_finish(device, &device->vsc_prim_strm);
1319
1320 fail_vsc_data2:
1321 tu_bo_finish(device, &device->vsc_draw_strm);
1322
1323 fail_vsc_data:
1324 ralloc_free(device->compiler);
1325
1326 fail_queues:
1327 for (unsigned i = 0; i < TU_MAX_QUEUE_FAMILIES; i++) {
1328 for (unsigned q = 0; q < device->queue_count[i]; q++)
1329 tu_queue_finish(&device->queues[i][q]);
1330 if (device->queue_count[i])
1331 vk_free(&device->alloc, device->queues[i]);
1332 }
1333
1334 vk_free(&device->alloc, device);
1335 return result;
1336 }
1337
1338 void
1339 tu_DestroyDevice(VkDevice _device, const VkAllocationCallbacks *pAllocator)
1340 {
1341 TU_FROM_HANDLE(tu_device, device, _device);
1342
1343 if (!device)
1344 return;
1345
1346 tu_bo_finish(device, &device->vsc_draw_strm);
1347 tu_bo_finish(device, &device->vsc_prim_strm);
1348
1349 for (unsigned i = 0; i < TU_MAX_QUEUE_FAMILIES; i++) {
1350 for (unsigned q = 0; q < device->queue_count[i]; q++)
1351 tu_queue_finish(&device->queues[i][q]);
1352 if (device->queue_count[i])
1353 vk_free(&device->alloc, device->queues[i]);
1354 }
1355
1356 for (unsigned i = 0; i < ARRAY_SIZE(device->scratch_bos); i++) {
1357 if (device->scratch_bos[i].initialized)
1358 tu_bo_finish(device, &device->scratch_bos[i].bo);
1359 }
1360
1361 ir3_compiler_destroy(device->compiler);
1362
1363 VkPipelineCache pc = tu_pipeline_cache_to_handle(device->mem_cache);
1364 tu_DestroyPipelineCache(tu_device_to_handle(device), pc, NULL);
1365
1366 vk_free(&device->alloc, device);
1367 }
1368
1369 VkResult
1370 _tu_device_set_lost(struct tu_device *device,
1371 const char *file, int line,
1372 const char *msg, ...)
1373 {
1374 /* Set the flag indicating that waits should return in finite time even
1375 * after device loss.
1376 */
1377 p_atomic_inc(&device->_lost);
1378
1379 /* TODO: Report the log message through VkDebugReportCallbackEXT instead */
1380 fprintf(stderr, "%s:%d: ", file, line);
1381 va_list ap;
1382 va_start(ap, msg);
1383 vfprintf(stderr, msg, ap);
1384 va_end(ap);
1385
1386 if (env_var_as_boolean("TU_ABORT_ON_DEVICE_LOSS", false))
1387 abort();
1388
1389 return VK_ERROR_DEVICE_LOST;
1390 }
1391
1392 VkResult
1393 tu_get_scratch_bo(struct tu_device *dev, uint64_t size, struct tu_bo **bo)
1394 {
1395 unsigned size_log2 = MAX2(util_logbase2_ceil64(size), MIN_SCRATCH_BO_SIZE_LOG2);
1396 unsigned index = size_log2 - MIN_SCRATCH_BO_SIZE_LOG2;
1397 assert(index < ARRAY_SIZE(dev->scratch_bos));
1398
1399 for (unsigned i = index; i < ARRAY_SIZE(dev->scratch_bos); i++) {
1400 if (p_atomic_read(&dev->scratch_bos[i].initialized)) {
1401 /* Fast path: just return the already-allocated BO. */
1402 *bo = &dev->scratch_bos[i].bo;
1403 return VK_SUCCESS;
1404 }
1405 }
1406
1407 /* Slow path: actually allocate the BO. We take a lock because the process
1408 * of allocating it is slow, and we don't want to block the CPU while it
1409 * finishes.
1410 */
1411 mtx_lock(&dev->scratch_bos[index].construct_mtx);
1412
1413 /* Another thread may have allocated it already while we were waiting on
1414 * the lock. We need to check this in order to avoid double-allocating.
1415 */
1416 if (dev->scratch_bos[index].initialized) {
1417 mtx_unlock(&dev->scratch_bos[index].construct_mtx);
1418 *bo = &dev->scratch_bos[index].bo;
1419 return VK_SUCCESS;
1420 }
1421
1422 unsigned bo_size = 1ull << size_log2;
1423 VkResult result = tu_bo_init_new(dev, &dev->scratch_bos[index].bo, bo_size);
1424 if (result != VK_SUCCESS) {
1425 mtx_unlock(&dev->scratch_bos[index].construct_mtx);
1426 return result;
1427 }
1428
1429 p_atomic_set(&dev->scratch_bos[index].initialized, true);
1430
1431 mtx_unlock(&dev->scratch_bos[index].construct_mtx);
1432
1433 *bo = &dev->scratch_bos[index].bo;
1434 return VK_SUCCESS;
1435 }
1436
1437 VkResult
1438 tu_EnumerateInstanceLayerProperties(uint32_t *pPropertyCount,
1439 VkLayerProperties *pProperties)
1440 {
1441 *pPropertyCount = 0;
1442 return VK_SUCCESS;
1443 }
1444
1445 VkResult
1446 tu_EnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice,
1447 uint32_t *pPropertyCount,
1448 VkLayerProperties *pProperties)
1449 {
1450 *pPropertyCount = 0;
1451 return VK_SUCCESS;
1452 }
1453
1454 void
1455 tu_GetDeviceQueue2(VkDevice _device,
1456 const VkDeviceQueueInfo2 *pQueueInfo,
1457 VkQueue *pQueue)
1458 {
1459 TU_FROM_HANDLE(tu_device, device, _device);
1460 struct tu_queue *queue;
1461
1462 queue =
1463 &device->queues[pQueueInfo->queueFamilyIndex][pQueueInfo->queueIndex];
1464 if (pQueueInfo->flags != queue->flags) {
1465 /* From the Vulkan 1.1.70 spec:
1466 *
1467 * "The queue returned by vkGetDeviceQueue2 must have the same
1468 * flags value from this structure as that used at device
1469 * creation time in a VkDeviceQueueCreateInfo instance. If no
1470 * matching flags were specified at device creation time then
1471 * pQueue will return VK_NULL_HANDLE."
1472 */
1473 *pQueue = VK_NULL_HANDLE;
1474 return;
1475 }
1476
1477 *pQueue = tu_queue_to_handle(queue);
1478 }
1479
1480 void
1481 tu_GetDeviceQueue(VkDevice _device,
1482 uint32_t queueFamilyIndex,
1483 uint32_t queueIndex,
1484 VkQueue *pQueue)
1485 {
1486 const VkDeviceQueueInfo2 info =
1487 (VkDeviceQueueInfo2) { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
1488 .queueFamilyIndex = queueFamilyIndex,
1489 .queueIndex = queueIndex };
1490
1491 tu_GetDeviceQueue2(_device, &info, pQueue);
1492 }
1493
1494 static VkResult
1495 tu_get_semaphore_syncobjs(const VkSemaphore *sems,
1496 uint32_t sem_count,
1497 bool wait,
1498 struct drm_msm_gem_submit_syncobj **out,
1499 uint32_t *out_count)
1500 {
1501 uint32_t syncobj_count = 0;
1502 struct drm_msm_gem_submit_syncobj *syncobjs;
1503
1504 for (uint32_t i = 0; i < sem_count; ++i) {
1505 TU_FROM_HANDLE(tu_semaphore, sem, sems[i]);
1506
1507 struct tu_semaphore_part *part =
1508 sem->temporary.kind != TU_SEMAPHORE_NONE ?
1509 &sem->temporary : &sem->permanent;
1510
1511 if (part->kind == TU_SEMAPHORE_SYNCOBJ)
1512 ++syncobj_count;
1513 }
1514
1515 *out = NULL;
1516 *out_count = syncobj_count;
1517 if (!syncobj_count)
1518 return VK_SUCCESS;
1519
1520 *out = syncobjs = calloc(syncobj_count, sizeof (*syncobjs));
1521 if (!syncobjs)
1522 return VK_ERROR_OUT_OF_HOST_MEMORY;
1523
1524 for (uint32_t i = 0, j = 0; i < sem_count; ++i) {
1525 TU_FROM_HANDLE(tu_semaphore, sem, sems[i]);
1526
1527 struct tu_semaphore_part *part =
1528 sem->temporary.kind != TU_SEMAPHORE_NONE ?
1529 &sem->temporary : &sem->permanent;
1530
1531 if (part->kind == TU_SEMAPHORE_SYNCOBJ) {
1532 syncobjs[j].handle = part->syncobj;
1533 syncobjs[j].flags = wait ? MSM_SUBMIT_SYNCOBJ_RESET : 0;
1534 ++j;
1535 }
1536 }
1537
1538 return VK_SUCCESS;
1539 }
1540
1541
1542 static void
1543 tu_semaphores_remove_temp(struct tu_device *device,
1544 const VkSemaphore *sems,
1545 uint32_t sem_count)
1546 {
1547 for (uint32_t i = 0; i < sem_count; ++i) {
1548 TU_FROM_HANDLE(tu_semaphore, sem, sems[i]);
1549 tu_semaphore_remove_temp(device, sem);
1550 }
1551 }
1552
1553 VkResult
1554 tu_QueueSubmit(VkQueue _queue,
1555 uint32_t submitCount,
1556 const VkSubmitInfo *pSubmits,
1557 VkFence _fence)
1558 {
1559 TU_FROM_HANDLE(tu_queue, queue, _queue);
1560 VkResult result;
1561
1562 for (uint32_t i = 0; i < submitCount; ++i) {
1563 const VkSubmitInfo *submit = pSubmits + i;
1564 const bool last_submit = (i == submitCount - 1);
1565 struct drm_msm_gem_submit_syncobj *in_syncobjs = NULL, *out_syncobjs = NULL;
1566 uint32_t nr_in_syncobjs, nr_out_syncobjs;
1567 struct tu_bo_list bo_list;
1568 tu_bo_list_init(&bo_list);
1569
1570 result = tu_get_semaphore_syncobjs(pSubmits[i].pWaitSemaphores,
1571 pSubmits[i].waitSemaphoreCount,
1572 false, &in_syncobjs, &nr_in_syncobjs);
1573 if (result != VK_SUCCESS) {
1574 return tu_device_set_lost(queue->device,
1575 "failed to allocate space for semaphore submission\n");
1576 }
1577
1578 result = tu_get_semaphore_syncobjs(pSubmits[i].pSignalSemaphores,
1579 pSubmits[i].signalSemaphoreCount,
1580 false, &out_syncobjs, &nr_out_syncobjs);
1581 if (result != VK_SUCCESS) {
1582 free(in_syncobjs);
1583 return tu_device_set_lost(queue->device,
1584 "failed to allocate space for semaphore submission\n");
1585 }
1586
1587 uint32_t entry_count = 0;
1588 for (uint32_t j = 0; j < submit->commandBufferCount; ++j) {
1589 TU_FROM_HANDLE(tu_cmd_buffer, cmdbuf, submit->pCommandBuffers[j]);
1590 entry_count += cmdbuf->cs.entry_count;
1591 }
1592
1593 struct drm_msm_gem_submit_cmd cmds[entry_count];
1594 uint32_t entry_idx = 0;
1595 for (uint32_t j = 0; j < submit->commandBufferCount; ++j) {
1596 TU_FROM_HANDLE(tu_cmd_buffer, cmdbuf, submit->pCommandBuffers[j]);
1597 struct tu_cs *cs = &cmdbuf->cs;
1598 for (unsigned i = 0; i < cs->entry_count; ++i, ++entry_idx) {
1599 cmds[entry_idx].type = MSM_SUBMIT_CMD_BUF;
1600 cmds[entry_idx].submit_idx =
1601 tu_bo_list_add(&bo_list, cs->entries[i].bo,
1602 MSM_SUBMIT_BO_READ | MSM_SUBMIT_BO_DUMP);
1603 cmds[entry_idx].submit_offset = cs->entries[i].offset;
1604 cmds[entry_idx].size = cs->entries[i].size;
1605 cmds[entry_idx].pad = 0;
1606 cmds[entry_idx].nr_relocs = 0;
1607 cmds[entry_idx].relocs = 0;
1608 }
1609
1610 tu_bo_list_merge(&bo_list, &cmdbuf->bo_list);
1611 }
1612
1613 uint32_t flags = MSM_PIPE_3D0;
1614 if (nr_in_syncobjs) {
1615 flags |= MSM_SUBMIT_SYNCOBJ_IN;
1616 }
1617 if (nr_out_syncobjs) {
1618 flags |= MSM_SUBMIT_SYNCOBJ_OUT;
1619 }
1620
1621 if (last_submit) {
1622 flags |= MSM_SUBMIT_FENCE_FD_OUT;
1623 }
1624
1625 struct drm_msm_gem_submit req = {
1626 .flags = flags,
1627 .queueid = queue->msm_queue_id,
1628 .bos = (uint64_t)(uintptr_t) bo_list.bo_infos,
1629 .nr_bos = bo_list.count,
1630 .cmds = (uint64_t)(uintptr_t)cmds,
1631 .nr_cmds = entry_count,
1632 .in_syncobjs = (uint64_t)(uintptr_t)in_syncobjs,
1633 .out_syncobjs = (uint64_t)(uintptr_t)out_syncobjs,
1634 .nr_in_syncobjs = nr_in_syncobjs,
1635 .nr_out_syncobjs = nr_out_syncobjs,
1636 .syncobj_stride = sizeof(struct drm_msm_gem_submit_syncobj),
1637 };
1638
1639 int ret = drmCommandWriteRead(queue->device->physical_device->local_fd,
1640 DRM_MSM_GEM_SUBMIT,
1641 &req, sizeof(req));
1642 if (ret) {
1643 free(in_syncobjs);
1644 free(out_syncobjs);
1645 return tu_device_set_lost(queue->device, "submit failed: %s\n",
1646 strerror(errno));
1647 }
1648
1649 tu_bo_list_destroy(&bo_list);
1650 free(in_syncobjs);
1651 free(out_syncobjs);
1652
1653 tu_semaphores_remove_temp(queue->device, pSubmits[i].pWaitSemaphores,
1654 pSubmits[i].waitSemaphoreCount);
1655 if (last_submit) {
1656 /* no need to merge fences as queue execution is serialized */
1657 tu_fence_update_fd(&queue->submit_fence, req.fence_fd);
1658 } else if (last_submit) {
1659 close(req.fence_fd);
1660 }
1661 }
1662
1663 if (_fence != VK_NULL_HANDLE) {
1664 TU_FROM_HANDLE(tu_fence, fence, _fence);
1665 tu_fence_copy(fence, &queue->submit_fence);
1666 }
1667
1668 return VK_SUCCESS;
1669 }
1670
1671 VkResult
1672 tu_QueueWaitIdle(VkQueue _queue)
1673 {
1674 TU_FROM_HANDLE(tu_queue, queue, _queue);
1675
1676 if (tu_device_is_lost(queue->device))
1677 return VK_ERROR_DEVICE_LOST;
1678
1679 tu_fence_wait_idle(&queue->submit_fence);
1680
1681 return VK_SUCCESS;
1682 }
1683
1684 VkResult
1685 tu_DeviceWaitIdle(VkDevice _device)
1686 {
1687 TU_FROM_HANDLE(tu_device, device, _device);
1688
1689 if (tu_device_is_lost(device))
1690 return VK_ERROR_DEVICE_LOST;
1691
1692 for (unsigned i = 0; i < TU_MAX_QUEUE_FAMILIES; i++) {
1693 for (unsigned q = 0; q < device->queue_count[i]; q++) {
1694 tu_QueueWaitIdle(tu_queue_to_handle(&device->queues[i][q]));
1695 }
1696 }
1697 return VK_SUCCESS;
1698 }
1699
1700 VkResult
1701 tu_EnumerateInstanceExtensionProperties(const char *pLayerName,
1702 uint32_t *pPropertyCount,
1703 VkExtensionProperties *pProperties)
1704 {
1705 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
1706
1707 /* We spport no lyaers */
1708 if (pLayerName)
1709 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
1710
1711 for (int i = 0; i < TU_INSTANCE_EXTENSION_COUNT; i++) {
1712 if (tu_instance_extensions_supported.extensions[i]) {
1713 vk_outarray_append(&out, prop) { *prop = tu_instance_extensions[i]; }
1714 }
1715 }
1716
1717 return vk_outarray_status(&out);
1718 }
1719
1720 VkResult
1721 tu_EnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,
1722 const char *pLayerName,
1723 uint32_t *pPropertyCount,
1724 VkExtensionProperties *pProperties)
1725 {
1726 /* We spport no lyaers */
1727 TU_FROM_HANDLE(tu_physical_device, device, physicalDevice);
1728 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
1729
1730 /* We spport no lyaers */
1731 if (pLayerName)
1732 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
1733
1734 for (int i = 0; i < TU_DEVICE_EXTENSION_COUNT; i++) {
1735 if (device->supported_extensions.extensions[i]) {
1736 vk_outarray_append(&out, prop) { *prop = tu_device_extensions[i]; }
1737 }
1738 }
1739
1740 return vk_outarray_status(&out);
1741 }
1742
1743 PFN_vkVoidFunction
1744 tu_GetInstanceProcAddr(VkInstance _instance, const char *pName)
1745 {
1746 TU_FROM_HANDLE(tu_instance, instance, _instance);
1747
1748 return tu_lookup_entrypoint_checked(
1749 pName, instance ? instance->api_version : 0,
1750 instance ? &instance->enabled_extensions : NULL, NULL);
1751 }
1752
1753 /* The loader wants us to expose a second GetInstanceProcAddr function
1754 * to work around certain LD_PRELOAD issues seen in apps.
1755 */
1756 PUBLIC
1757 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL
1758 vk_icdGetInstanceProcAddr(VkInstance instance, const char *pName);
1759
1760 PUBLIC
1761 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL
1762 vk_icdGetInstanceProcAddr(VkInstance instance, const char *pName)
1763 {
1764 return tu_GetInstanceProcAddr(instance, pName);
1765 }
1766
1767 PFN_vkVoidFunction
1768 tu_GetDeviceProcAddr(VkDevice _device, const char *pName)
1769 {
1770 TU_FROM_HANDLE(tu_device, device, _device);
1771
1772 return tu_lookup_entrypoint_checked(pName, device->instance->api_version,
1773 &device->instance->enabled_extensions,
1774 &device->enabled_extensions);
1775 }
1776
1777 static VkResult
1778 tu_alloc_memory(struct tu_device *device,
1779 const VkMemoryAllocateInfo *pAllocateInfo,
1780 const VkAllocationCallbacks *pAllocator,
1781 VkDeviceMemory *pMem)
1782 {
1783 struct tu_device_memory *mem;
1784 VkResult result;
1785
1786 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
1787
1788 if (pAllocateInfo->allocationSize == 0) {
1789 /* Apparently, this is allowed */
1790 *pMem = VK_NULL_HANDLE;
1791 return VK_SUCCESS;
1792 }
1793
1794 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
1795 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1796 if (mem == NULL)
1797 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1798
1799 const VkImportMemoryFdInfoKHR *fd_info =
1800 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
1801 if (fd_info && !fd_info->handleType)
1802 fd_info = NULL;
1803
1804 if (fd_info) {
1805 assert(fd_info->handleType ==
1806 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
1807 fd_info->handleType ==
1808 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1809
1810 /*
1811 * TODO Importing the same fd twice gives us the same handle without
1812 * reference counting. We need to maintain a per-instance handle-to-bo
1813 * table and add reference count to tu_bo.
1814 */
1815 result = tu_bo_init_dmabuf(device, &mem->bo,
1816 pAllocateInfo->allocationSize, fd_info->fd);
1817 if (result == VK_SUCCESS) {
1818 /* take ownership and close the fd */
1819 close(fd_info->fd);
1820 }
1821 } else {
1822 result =
1823 tu_bo_init_new(device, &mem->bo, pAllocateInfo->allocationSize);
1824 }
1825
1826 if (result != VK_SUCCESS) {
1827 vk_free2(&device->alloc, pAllocator, mem);
1828 return result;
1829 }
1830
1831 mem->size = pAllocateInfo->allocationSize;
1832 mem->type_index = pAllocateInfo->memoryTypeIndex;
1833
1834 mem->map = NULL;
1835 mem->user_ptr = NULL;
1836
1837 *pMem = tu_device_memory_to_handle(mem);
1838
1839 return VK_SUCCESS;
1840 }
1841
1842 VkResult
1843 tu_AllocateMemory(VkDevice _device,
1844 const VkMemoryAllocateInfo *pAllocateInfo,
1845 const VkAllocationCallbacks *pAllocator,
1846 VkDeviceMemory *pMem)
1847 {
1848 TU_FROM_HANDLE(tu_device, device, _device);
1849 return tu_alloc_memory(device, pAllocateInfo, pAllocator, pMem);
1850 }
1851
1852 void
1853 tu_FreeMemory(VkDevice _device,
1854 VkDeviceMemory _mem,
1855 const VkAllocationCallbacks *pAllocator)
1856 {
1857 TU_FROM_HANDLE(tu_device, device, _device);
1858 TU_FROM_HANDLE(tu_device_memory, mem, _mem);
1859
1860 if (mem == NULL)
1861 return;
1862
1863 tu_bo_finish(device, &mem->bo);
1864 vk_free2(&device->alloc, pAllocator, mem);
1865 }
1866
1867 VkResult
1868 tu_MapMemory(VkDevice _device,
1869 VkDeviceMemory _memory,
1870 VkDeviceSize offset,
1871 VkDeviceSize size,
1872 VkMemoryMapFlags flags,
1873 void **ppData)
1874 {
1875 TU_FROM_HANDLE(tu_device, device, _device);
1876 TU_FROM_HANDLE(tu_device_memory, mem, _memory);
1877 VkResult result;
1878
1879 if (mem == NULL) {
1880 *ppData = NULL;
1881 return VK_SUCCESS;
1882 }
1883
1884 if (mem->user_ptr) {
1885 *ppData = mem->user_ptr;
1886 } else if (!mem->map) {
1887 result = tu_bo_map(device, &mem->bo);
1888 if (result != VK_SUCCESS)
1889 return result;
1890 *ppData = mem->map = mem->bo.map;
1891 } else
1892 *ppData = mem->map;
1893
1894 if (*ppData) {
1895 *ppData += offset;
1896 return VK_SUCCESS;
1897 }
1898
1899 return vk_error(device->instance, VK_ERROR_MEMORY_MAP_FAILED);
1900 }
1901
1902 void
1903 tu_UnmapMemory(VkDevice _device, VkDeviceMemory _memory)
1904 {
1905 /* I do not see any unmapping done by the freedreno Gallium driver. */
1906 }
1907
1908 VkResult
1909 tu_FlushMappedMemoryRanges(VkDevice _device,
1910 uint32_t memoryRangeCount,
1911 const VkMappedMemoryRange *pMemoryRanges)
1912 {
1913 return VK_SUCCESS;
1914 }
1915
1916 VkResult
1917 tu_InvalidateMappedMemoryRanges(VkDevice _device,
1918 uint32_t memoryRangeCount,
1919 const VkMappedMemoryRange *pMemoryRanges)
1920 {
1921 return VK_SUCCESS;
1922 }
1923
1924 void
1925 tu_GetBufferMemoryRequirements(VkDevice _device,
1926 VkBuffer _buffer,
1927 VkMemoryRequirements *pMemoryRequirements)
1928 {
1929 TU_FROM_HANDLE(tu_buffer, buffer, _buffer);
1930
1931 pMemoryRequirements->memoryTypeBits = 1;
1932 pMemoryRequirements->alignment = 64;
1933 pMemoryRequirements->size =
1934 align64(buffer->size, pMemoryRequirements->alignment);
1935 }
1936
1937 void
1938 tu_GetBufferMemoryRequirements2(
1939 VkDevice device,
1940 const VkBufferMemoryRequirementsInfo2 *pInfo,
1941 VkMemoryRequirements2 *pMemoryRequirements)
1942 {
1943 tu_GetBufferMemoryRequirements(device, pInfo->buffer,
1944 &pMemoryRequirements->memoryRequirements);
1945 }
1946
1947 void
1948 tu_GetImageMemoryRequirements(VkDevice _device,
1949 VkImage _image,
1950 VkMemoryRequirements *pMemoryRequirements)
1951 {
1952 TU_FROM_HANDLE(tu_image, image, _image);
1953
1954 pMemoryRequirements->memoryTypeBits = 1;
1955 pMemoryRequirements->size = image->layout.size;
1956 pMemoryRequirements->alignment = image->layout.base_align;
1957 }
1958
1959 void
1960 tu_GetImageMemoryRequirements2(VkDevice device,
1961 const VkImageMemoryRequirementsInfo2 *pInfo,
1962 VkMemoryRequirements2 *pMemoryRequirements)
1963 {
1964 tu_GetImageMemoryRequirements(device, pInfo->image,
1965 &pMemoryRequirements->memoryRequirements);
1966 }
1967
1968 void
1969 tu_GetImageSparseMemoryRequirements(
1970 VkDevice device,
1971 VkImage image,
1972 uint32_t *pSparseMemoryRequirementCount,
1973 VkSparseImageMemoryRequirements *pSparseMemoryRequirements)
1974 {
1975 tu_stub();
1976 }
1977
1978 void
1979 tu_GetImageSparseMemoryRequirements2(
1980 VkDevice device,
1981 const VkImageSparseMemoryRequirementsInfo2 *pInfo,
1982 uint32_t *pSparseMemoryRequirementCount,
1983 VkSparseImageMemoryRequirements2 *pSparseMemoryRequirements)
1984 {
1985 tu_stub();
1986 }
1987
1988 void
1989 tu_GetDeviceMemoryCommitment(VkDevice device,
1990 VkDeviceMemory memory,
1991 VkDeviceSize *pCommittedMemoryInBytes)
1992 {
1993 *pCommittedMemoryInBytes = 0;
1994 }
1995
1996 VkResult
1997 tu_BindBufferMemory2(VkDevice device,
1998 uint32_t bindInfoCount,
1999 const VkBindBufferMemoryInfo *pBindInfos)
2000 {
2001 for (uint32_t i = 0; i < bindInfoCount; ++i) {
2002 TU_FROM_HANDLE(tu_device_memory, mem, pBindInfos[i].memory);
2003 TU_FROM_HANDLE(tu_buffer, buffer, pBindInfos[i].buffer);
2004
2005 if (mem) {
2006 buffer->bo = &mem->bo;
2007 buffer->bo_offset = pBindInfos[i].memoryOffset;
2008 } else {
2009 buffer->bo = NULL;
2010 }
2011 }
2012 return VK_SUCCESS;
2013 }
2014
2015 VkResult
2016 tu_BindBufferMemory(VkDevice device,
2017 VkBuffer buffer,
2018 VkDeviceMemory memory,
2019 VkDeviceSize memoryOffset)
2020 {
2021 const VkBindBufferMemoryInfo info = {
2022 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
2023 .buffer = buffer,
2024 .memory = memory,
2025 .memoryOffset = memoryOffset
2026 };
2027
2028 return tu_BindBufferMemory2(device, 1, &info);
2029 }
2030
2031 VkResult
2032 tu_BindImageMemory2(VkDevice device,
2033 uint32_t bindInfoCount,
2034 const VkBindImageMemoryInfo *pBindInfos)
2035 {
2036 for (uint32_t i = 0; i < bindInfoCount; ++i) {
2037 TU_FROM_HANDLE(tu_image, image, pBindInfos[i].image);
2038 TU_FROM_HANDLE(tu_device_memory, mem, pBindInfos[i].memory);
2039
2040 if (mem) {
2041 image->bo = &mem->bo;
2042 image->bo_offset = pBindInfos[i].memoryOffset;
2043 } else {
2044 image->bo = NULL;
2045 image->bo_offset = 0;
2046 }
2047 }
2048
2049 return VK_SUCCESS;
2050 }
2051
2052 VkResult
2053 tu_BindImageMemory(VkDevice device,
2054 VkImage image,
2055 VkDeviceMemory memory,
2056 VkDeviceSize memoryOffset)
2057 {
2058 const VkBindImageMemoryInfo info = {
2059 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
2060 .image = image,
2061 .memory = memory,
2062 .memoryOffset = memoryOffset
2063 };
2064
2065 return tu_BindImageMemory2(device, 1, &info);
2066 }
2067
2068 VkResult
2069 tu_QueueBindSparse(VkQueue _queue,
2070 uint32_t bindInfoCount,
2071 const VkBindSparseInfo *pBindInfo,
2072 VkFence _fence)
2073 {
2074 return VK_SUCCESS;
2075 }
2076
2077 // Queue semaphore functions
2078
2079
2080 static void
2081 tu_semaphore_part_destroy(struct tu_device *device,
2082 struct tu_semaphore_part *part)
2083 {
2084 switch(part->kind) {
2085 case TU_SEMAPHORE_NONE:
2086 break;
2087 case TU_SEMAPHORE_SYNCOBJ:
2088 drmSyncobjDestroy(device->physical_device->local_fd, part->syncobj);
2089 break;
2090 }
2091 part->kind = TU_SEMAPHORE_NONE;
2092 }
2093
2094 static void
2095 tu_semaphore_remove_temp(struct tu_device *device,
2096 struct tu_semaphore *sem)
2097 {
2098 if (sem->temporary.kind != TU_SEMAPHORE_NONE) {
2099 tu_semaphore_part_destroy(device, &sem->temporary);
2100 }
2101 }
2102
2103 VkResult
2104 tu_CreateSemaphore(VkDevice _device,
2105 const VkSemaphoreCreateInfo *pCreateInfo,
2106 const VkAllocationCallbacks *pAllocator,
2107 VkSemaphore *pSemaphore)
2108 {
2109 TU_FROM_HANDLE(tu_device, device, _device);
2110
2111 struct tu_semaphore *sem =
2112 vk_alloc2(&device->alloc, pAllocator, sizeof(*sem), 8,
2113 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2114 if (!sem)
2115 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2116
2117 const VkExportSemaphoreCreateInfo *export =
2118 vk_find_struct_const(pCreateInfo->pNext, EXPORT_SEMAPHORE_CREATE_INFO);
2119 VkExternalSemaphoreHandleTypeFlags handleTypes =
2120 export ? export->handleTypes : 0;
2121
2122 sem->permanent.kind = TU_SEMAPHORE_NONE;
2123 sem->temporary.kind = TU_SEMAPHORE_NONE;
2124
2125 if (handleTypes) {
2126 if (drmSyncobjCreate(device->physical_device->local_fd, 0, &sem->permanent.syncobj) < 0) {
2127 vk_free2(&device->alloc, pAllocator, sem);
2128 return VK_ERROR_OUT_OF_HOST_MEMORY;
2129 }
2130 sem->permanent.kind = TU_SEMAPHORE_SYNCOBJ;
2131 }
2132 *pSemaphore = tu_semaphore_to_handle(sem);
2133 return VK_SUCCESS;
2134 }
2135
2136 void
2137 tu_DestroySemaphore(VkDevice _device,
2138 VkSemaphore _semaphore,
2139 const VkAllocationCallbacks *pAllocator)
2140 {
2141 TU_FROM_HANDLE(tu_device, device, _device);
2142 TU_FROM_HANDLE(tu_semaphore, sem, _semaphore);
2143 if (!_semaphore)
2144 return;
2145
2146 tu_semaphore_part_destroy(device, &sem->permanent);
2147 tu_semaphore_part_destroy(device, &sem->temporary);
2148
2149 vk_free2(&device->alloc, pAllocator, sem);
2150 }
2151
2152 VkResult
2153 tu_CreateEvent(VkDevice _device,
2154 const VkEventCreateInfo *pCreateInfo,
2155 const VkAllocationCallbacks *pAllocator,
2156 VkEvent *pEvent)
2157 {
2158 TU_FROM_HANDLE(tu_device, device, _device);
2159 struct tu_event *event =
2160 vk_alloc2(&device->alloc, pAllocator, sizeof(*event), 8,
2161 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2162
2163 if (!event)
2164 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2165
2166 VkResult result = tu_bo_init_new(device, &event->bo, 0x1000);
2167 if (result != VK_SUCCESS)
2168 goto fail_alloc;
2169
2170 result = tu_bo_map(device, &event->bo);
2171 if (result != VK_SUCCESS)
2172 goto fail_map;
2173
2174 *pEvent = tu_event_to_handle(event);
2175
2176 return VK_SUCCESS;
2177
2178 fail_map:
2179 tu_bo_finish(device, &event->bo);
2180 fail_alloc:
2181 vk_free2(&device->alloc, pAllocator, event);
2182 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2183 }
2184
2185 void
2186 tu_DestroyEvent(VkDevice _device,
2187 VkEvent _event,
2188 const VkAllocationCallbacks *pAllocator)
2189 {
2190 TU_FROM_HANDLE(tu_device, device, _device);
2191 TU_FROM_HANDLE(tu_event, event, _event);
2192
2193 if (!event)
2194 return;
2195
2196 tu_bo_finish(device, &event->bo);
2197 vk_free2(&device->alloc, pAllocator, event);
2198 }
2199
2200 VkResult
2201 tu_GetEventStatus(VkDevice _device, VkEvent _event)
2202 {
2203 TU_FROM_HANDLE(tu_event, event, _event);
2204
2205 if (*(uint64_t*) event->bo.map == 1)
2206 return VK_EVENT_SET;
2207 return VK_EVENT_RESET;
2208 }
2209
2210 VkResult
2211 tu_SetEvent(VkDevice _device, VkEvent _event)
2212 {
2213 TU_FROM_HANDLE(tu_event, event, _event);
2214 *(uint64_t*) event->bo.map = 1;
2215
2216 return VK_SUCCESS;
2217 }
2218
2219 VkResult
2220 tu_ResetEvent(VkDevice _device, VkEvent _event)
2221 {
2222 TU_FROM_HANDLE(tu_event, event, _event);
2223 *(uint64_t*) event->bo.map = 0;
2224
2225 return VK_SUCCESS;
2226 }
2227
2228 VkResult
2229 tu_CreateBuffer(VkDevice _device,
2230 const VkBufferCreateInfo *pCreateInfo,
2231 const VkAllocationCallbacks *pAllocator,
2232 VkBuffer *pBuffer)
2233 {
2234 TU_FROM_HANDLE(tu_device, device, _device);
2235 struct tu_buffer *buffer;
2236
2237 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2238
2239 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2240 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2241 if (buffer == NULL)
2242 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2243
2244 buffer->size = pCreateInfo->size;
2245 buffer->usage = pCreateInfo->usage;
2246 buffer->flags = pCreateInfo->flags;
2247
2248 *pBuffer = tu_buffer_to_handle(buffer);
2249
2250 return VK_SUCCESS;
2251 }
2252
2253 void
2254 tu_DestroyBuffer(VkDevice _device,
2255 VkBuffer _buffer,
2256 const VkAllocationCallbacks *pAllocator)
2257 {
2258 TU_FROM_HANDLE(tu_device, device, _device);
2259 TU_FROM_HANDLE(tu_buffer, buffer, _buffer);
2260
2261 if (!buffer)
2262 return;
2263
2264 vk_free2(&device->alloc, pAllocator, buffer);
2265 }
2266
2267 VkResult
2268 tu_CreateFramebuffer(VkDevice _device,
2269 const VkFramebufferCreateInfo *pCreateInfo,
2270 const VkAllocationCallbacks *pAllocator,
2271 VkFramebuffer *pFramebuffer)
2272 {
2273 TU_FROM_HANDLE(tu_device, device, _device);
2274 struct tu_framebuffer *framebuffer;
2275
2276 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
2277
2278 size_t size = sizeof(*framebuffer) + sizeof(struct tu_attachment_info) *
2279 pCreateInfo->attachmentCount;
2280 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
2281 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2282 if (framebuffer == NULL)
2283 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2284
2285 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2286 framebuffer->width = pCreateInfo->width;
2287 framebuffer->height = pCreateInfo->height;
2288 framebuffer->layers = pCreateInfo->layers;
2289 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2290 VkImageView _iview = pCreateInfo->pAttachments[i];
2291 struct tu_image_view *iview = tu_image_view_from_handle(_iview);
2292 framebuffer->attachments[i].attachment = iview;
2293 }
2294
2295 *pFramebuffer = tu_framebuffer_to_handle(framebuffer);
2296 return VK_SUCCESS;
2297 }
2298
2299 void
2300 tu_DestroyFramebuffer(VkDevice _device,
2301 VkFramebuffer _fb,
2302 const VkAllocationCallbacks *pAllocator)
2303 {
2304 TU_FROM_HANDLE(tu_device, device, _device);
2305 TU_FROM_HANDLE(tu_framebuffer, fb, _fb);
2306
2307 if (!fb)
2308 return;
2309 vk_free2(&device->alloc, pAllocator, fb);
2310 }
2311
2312 static void
2313 tu_init_sampler(struct tu_device *device,
2314 struct tu_sampler *sampler,
2315 const VkSamplerCreateInfo *pCreateInfo)
2316 {
2317 const struct VkSamplerReductionModeCreateInfo *reduction =
2318 vk_find_struct_const(pCreateInfo->pNext, SAMPLER_REDUCTION_MODE_CREATE_INFO);
2319 const struct VkSamplerYcbcrConversionInfo *ycbcr_conversion =
2320 vk_find_struct_const(pCreateInfo->pNext, SAMPLER_YCBCR_CONVERSION_INFO);
2321
2322 unsigned aniso = pCreateInfo->anisotropyEnable ?
2323 util_last_bit(MIN2((uint32_t)pCreateInfo->maxAnisotropy >> 1, 8)) : 0;
2324 bool miplinear = (pCreateInfo->mipmapMode == VK_SAMPLER_MIPMAP_MODE_LINEAR);
2325 float min_lod = CLAMP(pCreateInfo->minLod, 0.0f, 4095.0f / 256.0f);
2326 float max_lod = CLAMP(pCreateInfo->maxLod, 0.0f, 4095.0f / 256.0f);
2327
2328 sampler->descriptor[0] =
2329 COND(miplinear, A6XX_TEX_SAMP_0_MIPFILTER_LINEAR_NEAR) |
2330 A6XX_TEX_SAMP_0_XY_MAG(tu6_tex_filter(pCreateInfo->magFilter, aniso)) |
2331 A6XX_TEX_SAMP_0_XY_MIN(tu6_tex_filter(pCreateInfo->minFilter, aniso)) |
2332 A6XX_TEX_SAMP_0_ANISO(aniso) |
2333 A6XX_TEX_SAMP_0_WRAP_S(tu6_tex_wrap(pCreateInfo->addressModeU)) |
2334 A6XX_TEX_SAMP_0_WRAP_T(tu6_tex_wrap(pCreateInfo->addressModeV)) |
2335 A6XX_TEX_SAMP_0_WRAP_R(tu6_tex_wrap(pCreateInfo->addressModeW)) |
2336 A6XX_TEX_SAMP_0_LOD_BIAS(pCreateInfo->mipLodBias);
2337 sampler->descriptor[1] =
2338 /* COND(!cso->seamless_cube_map, A6XX_TEX_SAMP_1_CUBEMAPSEAMLESSFILTOFF) | */
2339 COND(pCreateInfo->unnormalizedCoordinates, A6XX_TEX_SAMP_1_UNNORM_COORDS) |
2340 A6XX_TEX_SAMP_1_MIN_LOD(min_lod) |
2341 A6XX_TEX_SAMP_1_MAX_LOD(max_lod) |
2342 COND(pCreateInfo->compareEnable,
2343 A6XX_TEX_SAMP_1_COMPARE_FUNC(tu6_compare_func(pCreateInfo->compareOp)));
2344 /* This is an offset into the border_color BO, which we fill with all the
2345 * possible Vulkan border colors in the correct order, so we can just use
2346 * the Vulkan enum with no translation necessary.
2347 */
2348 sampler->descriptor[2] =
2349 A6XX_TEX_SAMP_2_BCOLOR_OFFSET((unsigned) pCreateInfo->borderColor *
2350 sizeof(struct bcolor_entry));
2351 sampler->descriptor[3] = 0;
2352
2353 if (reduction) {
2354 sampler->descriptor[2] |= A6XX_TEX_SAMP_2_REDUCTION_MODE(
2355 tu6_reduction_mode(reduction->reductionMode));
2356 }
2357
2358 sampler->ycbcr_sampler = ycbcr_conversion ?
2359 tu_sampler_ycbcr_conversion_from_handle(ycbcr_conversion->conversion) : NULL;
2360
2361 if (sampler->ycbcr_sampler &&
2362 sampler->ycbcr_sampler->chroma_filter == VK_FILTER_LINEAR) {
2363 sampler->descriptor[2] |= A6XX_TEX_SAMP_2_CHROMA_LINEAR;
2364 }
2365
2366 /* TODO:
2367 * A6XX_TEX_SAMP_1_MIPFILTER_LINEAR_FAR disables mipmapping, but vk has no NONE mipfilter?
2368 */
2369 }
2370
2371 VkResult
2372 tu_CreateSampler(VkDevice _device,
2373 const VkSamplerCreateInfo *pCreateInfo,
2374 const VkAllocationCallbacks *pAllocator,
2375 VkSampler *pSampler)
2376 {
2377 TU_FROM_HANDLE(tu_device, device, _device);
2378 struct tu_sampler *sampler;
2379
2380 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
2381
2382 sampler = vk_alloc2(&device->alloc, pAllocator, sizeof(*sampler), 8,
2383 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2384 if (!sampler)
2385 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2386
2387 tu_init_sampler(device, sampler, pCreateInfo);
2388 *pSampler = tu_sampler_to_handle(sampler);
2389
2390 return VK_SUCCESS;
2391 }
2392
2393 void
2394 tu_DestroySampler(VkDevice _device,
2395 VkSampler _sampler,
2396 const VkAllocationCallbacks *pAllocator)
2397 {
2398 TU_FROM_HANDLE(tu_device, device, _device);
2399 TU_FROM_HANDLE(tu_sampler, sampler, _sampler);
2400
2401 if (!sampler)
2402 return;
2403 vk_free2(&device->alloc, pAllocator, sampler);
2404 }
2405
2406 /* vk_icd.h does not declare this function, so we declare it here to
2407 * suppress Wmissing-prototypes.
2408 */
2409 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2410 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
2411
2412 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2413 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
2414 {
2415 /* For the full details on loader interface versioning, see
2416 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2417 * What follows is a condensed summary, to help you navigate the large and
2418 * confusing official doc.
2419 *
2420 * - Loader interface v0 is incompatible with later versions. We don't
2421 * support it.
2422 *
2423 * - In loader interface v1:
2424 * - The first ICD entrypoint called by the loader is
2425 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2426 * entrypoint.
2427 * - The ICD must statically expose no other Vulkan symbol unless it
2428 * is linked with -Bsymbolic.
2429 * - Each dispatchable Vulkan handle created by the ICD must be
2430 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2431 * ICD must initialize VK_LOADER_DATA.loadMagic to
2432 * ICD_LOADER_MAGIC.
2433 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2434 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2435 * such loader-managed surfaces.
2436 *
2437 * - Loader interface v2 differs from v1 in:
2438 * - The first ICD entrypoint called by the loader is
2439 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
2440 * statically expose this entrypoint.
2441 *
2442 * - Loader interface v3 differs from v2 in:
2443 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
2444 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
2445 * because the loader no longer does so.
2446 */
2447 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
2448 return VK_SUCCESS;
2449 }
2450
2451 VkResult
2452 tu_GetMemoryFdKHR(VkDevice _device,
2453 const VkMemoryGetFdInfoKHR *pGetFdInfo,
2454 int *pFd)
2455 {
2456 TU_FROM_HANDLE(tu_device, device, _device);
2457 TU_FROM_HANDLE(tu_device_memory, memory, pGetFdInfo->memory);
2458
2459 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
2460
2461 /* At the moment, we support only the below handle types. */
2462 assert(pGetFdInfo->handleType ==
2463 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2464 pGetFdInfo->handleType ==
2465 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2466
2467 int prime_fd = tu_bo_export_dmabuf(device, &memory->bo);
2468 if (prime_fd < 0)
2469 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
2470
2471 *pFd = prime_fd;
2472 return VK_SUCCESS;
2473 }
2474
2475 VkResult
2476 tu_GetMemoryFdPropertiesKHR(VkDevice _device,
2477 VkExternalMemoryHandleTypeFlagBits handleType,
2478 int fd,
2479 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
2480 {
2481 assert(handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2482 pMemoryFdProperties->memoryTypeBits = 1;
2483 return VK_SUCCESS;
2484 }
2485
2486 VkResult
2487 tu_ImportFenceFdKHR(VkDevice _device,
2488 const VkImportFenceFdInfoKHR *pImportFenceFdInfo)
2489 {
2490 tu_stub();
2491
2492 return VK_SUCCESS;
2493 }
2494
2495 VkResult
2496 tu_GetFenceFdKHR(VkDevice _device,
2497 const VkFenceGetFdInfoKHR *pGetFdInfo,
2498 int *pFd)
2499 {
2500 tu_stub();
2501
2502 return VK_SUCCESS;
2503 }
2504
2505 VkResult
2506 tu_ImportSemaphoreFdKHR(VkDevice _device,
2507 const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo)
2508 {
2509 TU_FROM_HANDLE(tu_device, device, _device);
2510 TU_FROM_HANDLE(tu_semaphore, sem, pImportSemaphoreFdInfo->semaphore);
2511 int ret;
2512 struct tu_semaphore_part *dst = NULL;
2513
2514 if (pImportSemaphoreFdInfo->flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT) {
2515 dst = &sem->temporary;
2516 } else {
2517 dst = &sem->permanent;
2518 }
2519
2520 uint32_t syncobj = dst->kind == TU_SEMAPHORE_SYNCOBJ ? dst->syncobj : 0;
2521
2522 switch(pImportSemaphoreFdInfo->handleType) {
2523 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT: {
2524 uint32_t old_syncobj = syncobj;
2525 ret = drmSyncobjFDToHandle(device->physical_device->local_fd, pImportSemaphoreFdInfo->fd, &syncobj);
2526 if (ret == 0) {
2527 close(pImportSemaphoreFdInfo->fd);
2528 if (old_syncobj)
2529 drmSyncobjDestroy(device->physical_device->local_fd, old_syncobj);
2530 }
2531 break;
2532 }
2533 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT: {
2534 if (!syncobj) {
2535 ret = drmSyncobjCreate(device->physical_device->local_fd, 0, &syncobj);
2536 if (ret)
2537 break;
2538 }
2539 if (pImportSemaphoreFdInfo->fd == -1) {
2540 ret = drmSyncobjSignal(device->physical_device->local_fd, &syncobj, 1);
2541 } else {
2542 ret = drmSyncobjImportSyncFile(device->physical_device->local_fd, syncobj, pImportSemaphoreFdInfo->fd);
2543 }
2544 if (!ret)
2545 close(pImportSemaphoreFdInfo->fd);
2546 break;
2547 }
2548 default:
2549 unreachable("Unhandled semaphore handle type");
2550 }
2551
2552 if (ret) {
2553 return VK_ERROR_INVALID_EXTERNAL_HANDLE;
2554 }
2555 dst->syncobj = syncobj;
2556 dst->kind = TU_SEMAPHORE_SYNCOBJ;
2557
2558 return VK_SUCCESS;
2559 }
2560
2561 VkResult
2562 tu_GetSemaphoreFdKHR(VkDevice _device,
2563 const VkSemaphoreGetFdInfoKHR *pGetFdInfo,
2564 int *pFd)
2565 {
2566 TU_FROM_HANDLE(tu_device, device, _device);
2567 TU_FROM_HANDLE(tu_semaphore, sem, pGetFdInfo->semaphore);
2568 int ret;
2569 uint32_t syncobj_handle;
2570
2571 if (sem->temporary.kind != TU_SEMAPHORE_NONE) {
2572 assert(sem->temporary.kind == TU_SEMAPHORE_SYNCOBJ);
2573 syncobj_handle = sem->temporary.syncobj;
2574 } else {
2575 assert(sem->permanent.kind == TU_SEMAPHORE_SYNCOBJ);
2576 syncobj_handle = sem->permanent.syncobj;
2577 }
2578
2579 switch(pGetFdInfo->handleType) {
2580 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
2581 ret = drmSyncobjHandleToFD(device->physical_device->local_fd, syncobj_handle, pFd);
2582 break;
2583 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
2584 ret = drmSyncobjExportSyncFile(device->physical_device->local_fd, syncobj_handle, pFd);
2585 if (!ret) {
2586 if (sem->temporary.kind != TU_SEMAPHORE_NONE) {
2587 tu_semaphore_part_destroy(device, &sem->temporary);
2588 } else {
2589 drmSyncobjReset(device->physical_device->local_fd, &syncobj_handle, 1);
2590 }
2591 }
2592 break;
2593 default:
2594 unreachable("Unhandled semaphore handle type");
2595 }
2596
2597 if (ret)
2598 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
2599 return VK_SUCCESS;
2600 }
2601
2602
2603 static bool tu_has_syncobj(struct tu_physical_device *pdev)
2604 {
2605 uint64_t value;
2606 if (drmGetCap(pdev->local_fd, DRM_CAP_SYNCOBJ, &value))
2607 return false;
2608 return value && pdev->msm_major_version == 1 && pdev->msm_minor_version >= 6;
2609 }
2610
2611 void
2612 tu_GetPhysicalDeviceExternalSemaphoreProperties(
2613 VkPhysicalDevice physicalDevice,
2614 const VkPhysicalDeviceExternalSemaphoreInfo *pExternalSemaphoreInfo,
2615 VkExternalSemaphoreProperties *pExternalSemaphoreProperties)
2616 {
2617 TU_FROM_HANDLE(tu_physical_device, pdev, physicalDevice);
2618
2619 if (tu_has_syncobj(pdev) &&
2620 (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT ||
2621 pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT)) {
2622 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
2623 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
2624 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
2625 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
2626 } else {
2627 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
2628 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
2629 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
2630 }
2631 }
2632
2633 void
2634 tu_GetPhysicalDeviceExternalFenceProperties(
2635 VkPhysicalDevice physicalDevice,
2636 const VkPhysicalDeviceExternalFenceInfo *pExternalFenceInfo,
2637 VkExternalFenceProperties *pExternalFenceProperties)
2638 {
2639 pExternalFenceProperties->exportFromImportedHandleTypes = 0;
2640 pExternalFenceProperties->compatibleHandleTypes = 0;
2641 pExternalFenceProperties->externalFenceFeatures = 0;
2642 }
2643
2644 VkResult
2645 tu_CreateDebugReportCallbackEXT(
2646 VkInstance _instance,
2647 const VkDebugReportCallbackCreateInfoEXT *pCreateInfo,
2648 const VkAllocationCallbacks *pAllocator,
2649 VkDebugReportCallbackEXT *pCallback)
2650 {
2651 TU_FROM_HANDLE(tu_instance, instance, _instance);
2652 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
2653 pCreateInfo, pAllocator,
2654 &instance->alloc, pCallback);
2655 }
2656
2657 void
2658 tu_DestroyDebugReportCallbackEXT(VkInstance _instance,
2659 VkDebugReportCallbackEXT _callback,
2660 const VkAllocationCallbacks *pAllocator)
2661 {
2662 TU_FROM_HANDLE(tu_instance, instance, _instance);
2663 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
2664 _callback, pAllocator, &instance->alloc);
2665 }
2666
2667 void
2668 tu_DebugReportMessageEXT(VkInstance _instance,
2669 VkDebugReportFlagsEXT flags,
2670 VkDebugReportObjectTypeEXT objectType,
2671 uint64_t object,
2672 size_t location,
2673 int32_t messageCode,
2674 const char *pLayerPrefix,
2675 const char *pMessage)
2676 {
2677 TU_FROM_HANDLE(tu_instance, instance, _instance);
2678 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
2679 object, location, messageCode, pLayerPrefix, pMessage);
2680 }
2681
2682 void
2683 tu_GetDeviceGroupPeerMemoryFeatures(
2684 VkDevice device,
2685 uint32_t heapIndex,
2686 uint32_t localDeviceIndex,
2687 uint32_t remoteDeviceIndex,
2688 VkPeerMemoryFeatureFlags *pPeerMemoryFeatures)
2689 {
2690 assert(localDeviceIndex == remoteDeviceIndex);
2691
2692 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
2693 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
2694 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
2695 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
2696 }
2697
2698 void tu_GetPhysicalDeviceMultisamplePropertiesEXT(
2699 VkPhysicalDevice physicalDevice,
2700 VkSampleCountFlagBits samples,
2701 VkMultisamplePropertiesEXT* pMultisampleProperties)
2702 {
2703 TU_FROM_HANDLE(tu_physical_device, pdevice, physicalDevice);
2704
2705 if (samples <= VK_SAMPLE_COUNT_4_BIT && pdevice->supported_extensions.EXT_sample_locations)
2706 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 1, 1 };
2707 else
2708 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 0, 0 };
2709 }