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