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