fdf051bcce9ed80c5c2bb22bd821332212d0c4df
[mesa.git] / src / amd / vulkan / radv_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 DEALINGS
25 * IN THE SOFTWARE.
26 */
27
28 #include <stdbool.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include "radv_debug.h"
33 #include "radv_private.h"
34 #include "radv_shader.h"
35 #include "radv_cs.h"
36 #include "util/disk_cache.h"
37 #include "util/strtod.h"
38 #include "vk_util.h"
39 #include <xf86drm.h>
40 #include <amdgpu.h>
41 #include <amdgpu_drm.h>
42 #include "winsys/amdgpu/radv_amdgpu_winsys_public.h"
43 #include "ac_llvm_util.h"
44 #include "vk_format.h"
45 #include "sid.h"
46 #include "git_sha1.h"
47 #include "gfx9d.h"
48 #include "util/build_id.h"
49 #include "util/debug.h"
50 #include "util/mesa-sha1.h"
51
52 static int
53 radv_device_get_cache_uuid(enum radeon_family family, void *uuid)
54 {
55 struct mesa_sha1 ctx;
56 unsigned char sha1[20];
57 unsigned ptr_size = sizeof(void*);
58
59 memset(uuid, 0, VK_UUID_SIZE);
60 _mesa_sha1_init(&ctx);
61
62 if (!disk_cache_get_function_identifier(radv_device_get_cache_uuid, &ctx) ||
63 !disk_cache_get_function_identifier(LLVMInitializeAMDGPUTargetInfo, &ctx))
64 return -1;
65
66 _mesa_sha1_update(&ctx, &family, sizeof(family));
67 _mesa_sha1_update(&ctx, &ptr_size, sizeof(ptr_size));
68 _mesa_sha1_final(&ctx, sha1);
69
70 memcpy(uuid, sha1, VK_UUID_SIZE);
71 return 0;
72 }
73
74 static void
75 radv_get_driver_uuid(void *uuid)
76 {
77 ac_compute_driver_uuid(uuid, VK_UUID_SIZE);
78 }
79
80 static void
81 radv_get_device_uuid(struct radeon_info *info, void *uuid)
82 {
83 ac_compute_device_uuid(info, uuid, VK_UUID_SIZE);
84 }
85
86 static void
87 radv_get_device_name(enum radeon_family family, char *name, size_t name_len)
88 {
89 const char *chip_string;
90 char llvm_string[32] = {};
91
92 switch (family) {
93 case CHIP_TAHITI: chip_string = "AMD RADV TAHITI"; break;
94 case CHIP_PITCAIRN: chip_string = "AMD RADV PITCAIRN"; break;
95 case CHIP_VERDE: chip_string = "AMD RADV CAPE VERDE"; break;
96 case CHIP_OLAND: chip_string = "AMD RADV OLAND"; break;
97 case CHIP_HAINAN: chip_string = "AMD RADV HAINAN"; break;
98 case CHIP_BONAIRE: chip_string = "AMD RADV BONAIRE"; break;
99 case CHIP_KAVERI: chip_string = "AMD RADV KAVERI"; break;
100 case CHIP_KABINI: chip_string = "AMD RADV KABINI"; break;
101 case CHIP_HAWAII: chip_string = "AMD RADV HAWAII"; break;
102 case CHIP_MULLINS: chip_string = "AMD RADV MULLINS"; break;
103 case CHIP_TONGA: chip_string = "AMD RADV TONGA"; break;
104 case CHIP_ICELAND: chip_string = "AMD RADV ICELAND"; break;
105 case CHIP_CARRIZO: chip_string = "AMD RADV CARRIZO"; break;
106 case CHIP_FIJI: chip_string = "AMD RADV FIJI"; break;
107 case CHIP_POLARIS10: chip_string = "AMD RADV POLARIS10"; break;
108 case CHIP_POLARIS11: chip_string = "AMD RADV POLARIS11"; break;
109 case CHIP_POLARIS12: chip_string = "AMD RADV POLARIS12"; break;
110 case CHIP_STONEY: chip_string = "AMD RADV STONEY"; break;
111 case CHIP_VEGAM: chip_string = "AMD RADV VEGA M"; break;
112 case CHIP_VEGA10: chip_string = "AMD RADV VEGA10"; break;
113 case CHIP_VEGA12: chip_string = "AMD RADV VEGA12"; break;
114 case CHIP_RAVEN: chip_string = "AMD RADV RAVEN"; break;
115 case CHIP_RAVEN2: chip_string = "AMD RADV RAVEN2"; break;
116 default: chip_string = "AMD RADV unknown"; break;
117 }
118
119 snprintf(llvm_string, sizeof(llvm_string),
120 " (LLVM %i.%i.%i)", (HAVE_LLVM >> 8) & 0xff,
121 HAVE_LLVM & 0xff, MESA_LLVM_VERSION_PATCH);
122 snprintf(name, name_len, "%s%s", chip_string, llvm_string);
123 }
124
125 static uint64_t
126 radv_get_visible_vram_size(struct radv_physical_device *device)
127 {
128 return MIN2(device->rad_info.vram_size, device->rad_info.vram_vis_size);
129 }
130
131 static uint64_t
132 radv_get_vram_size(struct radv_physical_device *device)
133 {
134 return device->rad_info.vram_size - radv_get_visible_vram_size(device);
135 }
136
137 static void
138 radv_physical_device_init_mem_types(struct radv_physical_device *device)
139 {
140 STATIC_ASSERT(RADV_MEM_HEAP_COUNT <= VK_MAX_MEMORY_HEAPS);
141 uint64_t visible_vram_size = radv_get_visible_vram_size(device);
142 uint64_t vram_size = radv_get_vram_size(device);
143 int vram_index = -1, visible_vram_index = -1, gart_index = -1;
144 device->memory_properties.memoryHeapCount = 0;
145 if (vram_size > 0) {
146 vram_index = device->memory_properties.memoryHeapCount++;
147 device->memory_properties.memoryHeaps[vram_index] = (VkMemoryHeap) {
148 .size = vram_size,
149 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
150 };
151 }
152 if (visible_vram_size) {
153 visible_vram_index = device->memory_properties.memoryHeapCount++;
154 device->memory_properties.memoryHeaps[visible_vram_index] = (VkMemoryHeap) {
155 .size = visible_vram_size,
156 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
157 };
158 }
159 if (device->rad_info.gart_size > 0) {
160 gart_index = device->memory_properties.memoryHeapCount++;
161 device->memory_properties.memoryHeaps[gart_index] = (VkMemoryHeap) {
162 .size = device->rad_info.gart_size,
163 .flags = device->rad_info.has_dedicated_vram ? 0 : VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
164 };
165 }
166
167 STATIC_ASSERT(RADV_MEM_TYPE_COUNT <= VK_MAX_MEMORY_TYPES);
168 unsigned type_count = 0;
169 if (vram_index >= 0) {
170 device->mem_type_indices[type_count] = RADV_MEM_TYPE_VRAM;
171 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
172 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
173 .heapIndex = vram_index,
174 };
175 }
176 if (gart_index >= 0) {
177 device->mem_type_indices[type_count] = RADV_MEM_TYPE_GTT_WRITE_COMBINE;
178 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
179 .propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
180 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
181 (device->rad_info.has_dedicated_vram ? 0 : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
182 .heapIndex = gart_index,
183 };
184 }
185 if (visible_vram_index >= 0) {
186 device->mem_type_indices[type_count] = RADV_MEM_TYPE_VRAM_CPU_ACCESS;
187 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
188 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
189 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
190 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
191 .heapIndex = visible_vram_index,
192 };
193 }
194 if (gart_index >= 0) {
195 device->mem_type_indices[type_count] = RADV_MEM_TYPE_GTT_CACHED;
196 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
197 .propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
198 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
199 VK_MEMORY_PROPERTY_HOST_CACHED_BIT |
200 (device->rad_info.has_dedicated_vram ? 0 : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
201 .heapIndex = gart_index,
202 };
203 }
204 device->memory_properties.memoryTypeCount = type_count;
205 }
206
207 static void
208 radv_handle_env_var_force_family(struct radv_physical_device *device)
209 {
210 const char *family = getenv("RADV_FORCE_FAMILY");
211 unsigned i;
212
213 if (!family)
214 return;
215
216 for (i = CHIP_TAHITI; i < CHIP_LAST; i++) {
217 if (!strcmp(family, ac_get_llvm_processor_name(i))) {
218 /* Override family and chip_class. */
219 device->rad_info.family = i;
220
221 if (i >= CHIP_VEGA10)
222 device->rad_info.chip_class = GFX9;
223 else if (i >= CHIP_TONGA)
224 device->rad_info.chip_class = VI;
225 else if (i >= CHIP_BONAIRE)
226 device->rad_info.chip_class = CIK;
227 else
228 device->rad_info.chip_class = SI;
229
230 return;
231 }
232 }
233
234 fprintf(stderr, "radv: Unknown family: %s\n", family);
235 exit(1);
236 }
237
238 static VkResult
239 radv_physical_device_init(struct radv_physical_device *device,
240 struct radv_instance *instance,
241 drmDevicePtr drm_device)
242 {
243 const char *path = drm_device->nodes[DRM_NODE_RENDER];
244 VkResult result;
245 drmVersionPtr version;
246 int fd;
247 int master_fd = -1;
248
249 fd = open(path, O_RDWR | O_CLOEXEC);
250 if (fd < 0) {
251 if (instance->debug_flags & RADV_DEBUG_STARTUP)
252 radv_logi("Could not open device '%s'", path);
253
254 return vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
255 }
256
257 version = drmGetVersion(fd);
258 if (!version) {
259 close(fd);
260
261 if (instance->debug_flags & RADV_DEBUG_STARTUP)
262 radv_logi("Could not get the kernel driver version for device '%s'", path);
263
264 return vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
265 "failed to get version %s: %m", path);
266 }
267
268 if (strcmp(version->name, "amdgpu")) {
269 drmFreeVersion(version);
270 close(fd);
271
272 if (instance->debug_flags & RADV_DEBUG_STARTUP)
273 radv_logi("Device '%s' is not using the amdgpu kernel driver.", path);
274
275 return VK_ERROR_INCOMPATIBLE_DRIVER;
276 }
277 drmFreeVersion(version);
278
279 if (instance->debug_flags & RADV_DEBUG_STARTUP)
280 radv_logi("Found compatible device '%s'.", path);
281
282 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
283 device->instance = instance;
284
285 device->ws = radv_amdgpu_winsys_create(fd, instance->debug_flags,
286 instance->perftest_flags);
287 if (!device->ws) {
288 result = vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
289 goto fail;
290 }
291
292 if (instance->enabled_extensions.KHR_display) {
293 master_fd = open(drm_device->nodes[DRM_NODE_PRIMARY], O_RDWR | O_CLOEXEC);
294 if (master_fd >= 0) {
295 uint32_t accel_working = 0;
296 struct drm_amdgpu_info request = {
297 .return_pointer = (uintptr_t)&accel_working,
298 .return_size = sizeof(accel_working),
299 .query = AMDGPU_INFO_ACCEL_WORKING
300 };
301
302 if (drmCommandWrite(master_fd, DRM_AMDGPU_INFO, &request, sizeof (struct drm_amdgpu_info)) < 0 || !accel_working) {
303 close(master_fd);
304 master_fd = -1;
305 }
306 }
307 }
308
309 device->master_fd = master_fd;
310 device->local_fd = fd;
311 device->ws->query_info(device->ws, &device->rad_info);
312
313 radv_handle_env_var_force_family(device);
314
315 radv_get_device_name(device->rad_info.family, device->name, sizeof(device->name));
316
317 if (radv_device_get_cache_uuid(device->rad_info.family, device->cache_uuid)) {
318 device->ws->destroy(device->ws);
319 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
320 "cannot generate UUID");
321 goto fail;
322 }
323
324 /* These flags affect shader compilation. */
325 uint64_t shader_env_flags =
326 (device->instance->perftest_flags & RADV_PERFTEST_SISCHED ? 0x1 : 0) |
327 (device->instance->debug_flags & RADV_DEBUG_UNSAFE_MATH ? 0x2 : 0);
328
329 /* The gpu id is already embedded in the uuid so we just pass "radv"
330 * when creating the cache.
331 */
332 char buf[VK_UUID_SIZE * 2 + 1];
333 disk_cache_format_hex_id(buf, device->cache_uuid, VK_UUID_SIZE * 2);
334 device->disk_cache = disk_cache_create(device->name, buf, shader_env_flags);
335
336 if (device->rad_info.chip_class < VI ||
337 device->rad_info.chip_class > GFX9)
338 fprintf(stderr, "WARNING: radv is not a conformant vulkan implementation, testing use only.\n");
339
340 radv_get_driver_uuid(&device->device_uuid);
341 radv_get_device_uuid(&device->rad_info, &device->device_uuid);
342
343 if (device->rad_info.family == CHIP_STONEY ||
344 device->rad_info.chip_class >= GFX9) {
345 device->has_rbplus = true;
346 device->rbplus_allowed = device->rad_info.family == CHIP_STONEY ||
347 device->rad_info.family == CHIP_VEGA12 ||
348 device->rad_info.family == CHIP_RAVEN ||
349 device->rad_info.family == CHIP_RAVEN2;
350 }
351
352 /* The mere presence of CLEAR_STATE in the IB causes random GPU hangs
353 * on SI.
354 */
355 device->has_clear_state = device->rad_info.chip_class >= CIK;
356
357 device->cpdma_prefetch_writes_memory = device->rad_info.chip_class <= VI;
358
359 /* Vega10/Raven need a special workaround for a hardware bug. */
360 device->has_scissor_bug = device->rad_info.family == CHIP_VEGA10 ||
361 device->rad_info.family == CHIP_RAVEN;
362
363 /* Out-of-order primitive rasterization. */
364 device->has_out_of_order_rast = device->rad_info.chip_class >= VI &&
365 device->rad_info.max_se >= 2;
366 device->out_of_order_rast_allowed = device->has_out_of_order_rast &&
367 !(device->instance->debug_flags & RADV_DEBUG_NO_OUT_OF_ORDER);
368
369 device->dcc_msaa_allowed =
370 (device->instance->perftest_flags & RADV_PERFTEST_DCC_MSAA);
371
372 radv_physical_device_init_mem_types(device);
373 radv_fill_device_extension_table(device, &device->supported_extensions);
374
375 device->bus_info = *drm_device->businfo.pci;
376
377 if ((device->instance->debug_flags & RADV_DEBUG_INFO))
378 ac_print_gpu_info(&device->rad_info);
379
380 /* The WSI is structured as a layer on top of the driver, so this has
381 * to be the last part of initialization (at least until we get other
382 * semi-layers).
383 */
384 result = radv_init_wsi(device);
385 if (result != VK_SUCCESS) {
386 device->ws->destroy(device->ws);
387 vk_error(instance, result);
388 goto fail;
389 }
390
391 return VK_SUCCESS;
392
393 fail:
394 close(fd);
395 if (master_fd != -1)
396 close(master_fd);
397 return result;
398 }
399
400 static void
401 radv_physical_device_finish(struct radv_physical_device *device)
402 {
403 radv_finish_wsi(device);
404 device->ws->destroy(device->ws);
405 disk_cache_destroy(device->disk_cache);
406 close(device->local_fd);
407 if (device->master_fd != -1)
408 close(device->master_fd);
409 }
410
411 static void *
412 default_alloc_func(void *pUserData, size_t size, size_t align,
413 VkSystemAllocationScope allocationScope)
414 {
415 return malloc(size);
416 }
417
418 static void *
419 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
420 size_t align, VkSystemAllocationScope allocationScope)
421 {
422 return realloc(pOriginal, size);
423 }
424
425 static void
426 default_free_func(void *pUserData, void *pMemory)
427 {
428 free(pMemory);
429 }
430
431 static const VkAllocationCallbacks default_alloc = {
432 .pUserData = NULL,
433 .pfnAllocation = default_alloc_func,
434 .pfnReallocation = default_realloc_func,
435 .pfnFree = default_free_func,
436 };
437
438 static const struct debug_control radv_debug_options[] = {
439 {"nofastclears", RADV_DEBUG_NO_FAST_CLEARS},
440 {"nodcc", RADV_DEBUG_NO_DCC},
441 {"shaders", RADV_DEBUG_DUMP_SHADERS},
442 {"nocache", RADV_DEBUG_NO_CACHE},
443 {"shaderstats", RADV_DEBUG_DUMP_SHADER_STATS},
444 {"nohiz", RADV_DEBUG_NO_HIZ},
445 {"nocompute", RADV_DEBUG_NO_COMPUTE_QUEUE},
446 {"unsafemath", RADV_DEBUG_UNSAFE_MATH},
447 {"allbos", RADV_DEBUG_ALL_BOS},
448 {"noibs", RADV_DEBUG_NO_IBS},
449 {"spirv", RADV_DEBUG_DUMP_SPIRV},
450 {"vmfaults", RADV_DEBUG_VM_FAULTS},
451 {"zerovram", RADV_DEBUG_ZERO_VRAM},
452 {"syncshaders", RADV_DEBUG_SYNC_SHADERS},
453 {"nosisched", RADV_DEBUG_NO_SISCHED},
454 {"preoptir", RADV_DEBUG_PREOPTIR},
455 {"nodynamicbounds", RADV_DEBUG_NO_DYNAMIC_BOUNDS},
456 {"nooutoforder", RADV_DEBUG_NO_OUT_OF_ORDER},
457 {"info", RADV_DEBUG_INFO},
458 {"errors", RADV_DEBUG_ERRORS},
459 {"startup", RADV_DEBUG_STARTUP},
460 {"checkir", RADV_DEBUG_CHECKIR},
461 {"nothreadllvm", RADV_DEBUG_NOTHREADLLVM},
462 {"nobinning", RADV_DEBUG_NOBINNING},
463 {NULL, 0}
464 };
465
466 const char *
467 radv_get_debug_option_name(int id)
468 {
469 assert(id < ARRAY_SIZE(radv_debug_options) - 1);
470 return radv_debug_options[id].string;
471 }
472
473 static const struct debug_control radv_perftest_options[] = {
474 {"nobatchchain", RADV_PERFTEST_NO_BATCHCHAIN},
475 {"sisched", RADV_PERFTEST_SISCHED},
476 {"localbos", RADV_PERFTEST_LOCAL_BOS},
477 {"dccmsaa", RADV_PERFTEST_DCC_MSAA},
478 {NULL, 0}
479 };
480
481 const char *
482 radv_get_perftest_option_name(int id)
483 {
484 assert(id < ARRAY_SIZE(radv_perftest_options) - 1);
485 return radv_perftest_options[id].string;
486 }
487
488 static void
489 radv_handle_per_app_options(struct radv_instance *instance,
490 const VkApplicationInfo *info)
491 {
492 const char *name = info ? info->pApplicationName : NULL;
493
494 if (!name)
495 return;
496
497 if (!strcmp(name, "Talos - Linux - 32bit") ||
498 !strcmp(name, "Talos - Linux - 64bit")) {
499 if (!(instance->debug_flags & RADV_DEBUG_NO_SISCHED)) {
500 /* Force enable LLVM sisched for Talos because it looks
501 * safe and it gives few more FPS.
502 */
503 instance->perftest_flags |= RADV_PERFTEST_SISCHED;
504 }
505 } else if (!strcmp(name, "DOOM_VFR")) {
506 /* Work around a Doom VFR game bug */
507 instance->debug_flags |= RADV_DEBUG_NO_DYNAMIC_BOUNDS;
508 }
509 }
510
511 static int radv_get_instance_extension_index(const char *name)
512 {
513 for (unsigned i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; ++i) {
514 if (strcmp(name, radv_instance_extensions[i].extensionName) == 0)
515 return i;
516 }
517 return -1;
518 }
519
520
521 VkResult radv_CreateInstance(
522 const VkInstanceCreateInfo* pCreateInfo,
523 const VkAllocationCallbacks* pAllocator,
524 VkInstance* pInstance)
525 {
526 struct radv_instance *instance;
527 VkResult result;
528
529 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
530
531 uint32_t client_version;
532 if (pCreateInfo->pApplicationInfo &&
533 pCreateInfo->pApplicationInfo->apiVersion != 0) {
534 client_version = pCreateInfo->pApplicationInfo->apiVersion;
535 } else {
536 client_version = VK_API_VERSION_1_0;
537 }
538
539 instance = vk_zalloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
540 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
541 if (!instance)
542 return vk_error(NULL, VK_ERROR_OUT_OF_HOST_MEMORY);
543
544 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
545
546 if (pAllocator)
547 instance->alloc = *pAllocator;
548 else
549 instance->alloc = default_alloc;
550
551 instance->apiVersion = client_version;
552 instance->physicalDeviceCount = -1;
553
554 instance->debug_flags = parse_debug_string(getenv("RADV_DEBUG"),
555 radv_debug_options);
556
557 instance->perftest_flags = parse_debug_string(getenv("RADV_PERFTEST"),
558 radv_perftest_options);
559
560
561 if (instance->debug_flags & RADV_DEBUG_STARTUP)
562 radv_logi("Created an instance");
563
564 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
565 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
566 int index = radv_get_instance_extension_index(ext_name);
567
568 if (index < 0 || !radv_supported_instance_extensions.extensions[index]) {
569 vk_free2(&default_alloc, pAllocator, instance);
570 return vk_error(instance, VK_ERROR_EXTENSION_NOT_PRESENT);
571 }
572
573 instance->enabled_extensions.extensions[index] = true;
574 }
575
576 result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
577 if (result != VK_SUCCESS) {
578 vk_free2(&default_alloc, pAllocator, instance);
579 return vk_error(instance, result);
580 }
581
582 _mesa_locale_init();
583
584 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
585
586 radv_handle_per_app_options(instance, pCreateInfo->pApplicationInfo);
587
588 *pInstance = radv_instance_to_handle(instance);
589
590 return VK_SUCCESS;
591 }
592
593 void radv_DestroyInstance(
594 VkInstance _instance,
595 const VkAllocationCallbacks* pAllocator)
596 {
597 RADV_FROM_HANDLE(radv_instance, instance, _instance);
598
599 if (!instance)
600 return;
601
602 for (int i = 0; i < instance->physicalDeviceCount; ++i) {
603 radv_physical_device_finish(instance->physicalDevices + i);
604 }
605
606 VG(VALGRIND_DESTROY_MEMPOOL(instance));
607
608 _mesa_locale_fini();
609
610 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
611
612 vk_free(&instance->alloc, instance);
613 }
614
615 static VkResult
616 radv_enumerate_devices(struct radv_instance *instance)
617 {
618 /* TODO: Check for more devices ? */
619 drmDevicePtr devices[8];
620 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
621 int max_devices;
622
623 instance->physicalDeviceCount = 0;
624
625 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
626
627 if (instance->debug_flags & RADV_DEBUG_STARTUP)
628 radv_logi("Found %d drm nodes", max_devices);
629
630 if (max_devices < 1)
631 return vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
632
633 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
634 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
635 devices[i]->bustype == DRM_BUS_PCI &&
636 devices[i]->deviceinfo.pci->vendor_id == ATI_VENDOR_ID) {
637
638 result = radv_physical_device_init(instance->physicalDevices +
639 instance->physicalDeviceCount,
640 instance,
641 devices[i]);
642 if (result == VK_SUCCESS)
643 ++instance->physicalDeviceCount;
644 else if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
645 break;
646 }
647 }
648 drmFreeDevices(devices, max_devices);
649
650 return result;
651 }
652
653 VkResult radv_EnumeratePhysicalDevices(
654 VkInstance _instance,
655 uint32_t* pPhysicalDeviceCount,
656 VkPhysicalDevice* pPhysicalDevices)
657 {
658 RADV_FROM_HANDLE(radv_instance, instance, _instance);
659 VkResult result;
660
661 if (instance->physicalDeviceCount < 0) {
662 result = radv_enumerate_devices(instance);
663 if (result != VK_SUCCESS &&
664 result != VK_ERROR_INCOMPATIBLE_DRIVER)
665 return result;
666 }
667
668 if (!pPhysicalDevices) {
669 *pPhysicalDeviceCount = instance->physicalDeviceCount;
670 } else {
671 *pPhysicalDeviceCount = MIN2(*pPhysicalDeviceCount, instance->physicalDeviceCount);
672 for (unsigned i = 0; i < *pPhysicalDeviceCount; ++i)
673 pPhysicalDevices[i] = radv_physical_device_to_handle(instance->physicalDevices + i);
674 }
675
676 return *pPhysicalDeviceCount < instance->physicalDeviceCount ? VK_INCOMPLETE
677 : VK_SUCCESS;
678 }
679
680 VkResult radv_EnumeratePhysicalDeviceGroups(
681 VkInstance _instance,
682 uint32_t* pPhysicalDeviceGroupCount,
683 VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties)
684 {
685 RADV_FROM_HANDLE(radv_instance, instance, _instance);
686 VkResult result;
687
688 if (instance->physicalDeviceCount < 0) {
689 result = radv_enumerate_devices(instance);
690 if (result != VK_SUCCESS &&
691 result != VK_ERROR_INCOMPATIBLE_DRIVER)
692 return result;
693 }
694
695 if (!pPhysicalDeviceGroupProperties) {
696 *pPhysicalDeviceGroupCount = instance->physicalDeviceCount;
697 } else {
698 *pPhysicalDeviceGroupCount = MIN2(*pPhysicalDeviceGroupCount, instance->physicalDeviceCount);
699 for (unsigned i = 0; i < *pPhysicalDeviceGroupCount; ++i) {
700 pPhysicalDeviceGroupProperties[i].physicalDeviceCount = 1;
701 pPhysicalDeviceGroupProperties[i].physicalDevices[0] = radv_physical_device_to_handle(instance->physicalDevices + i);
702 pPhysicalDeviceGroupProperties[i].subsetAllocation = false;
703 }
704 }
705 return *pPhysicalDeviceGroupCount < instance->physicalDeviceCount ? VK_INCOMPLETE
706 : VK_SUCCESS;
707 }
708
709 void radv_GetPhysicalDeviceFeatures(
710 VkPhysicalDevice physicalDevice,
711 VkPhysicalDeviceFeatures* pFeatures)
712 {
713 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
714 memset(pFeatures, 0, sizeof(*pFeatures));
715
716 *pFeatures = (VkPhysicalDeviceFeatures) {
717 .robustBufferAccess = true,
718 .fullDrawIndexUint32 = true,
719 .imageCubeArray = true,
720 .independentBlend = true,
721 .geometryShader = true,
722 .tessellationShader = true,
723 .sampleRateShading = true,
724 .dualSrcBlend = true,
725 .logicOp = true,
726 .multiDrawIndirect = true,
727 .drawIndirectFirstInstance = true,
728 .depthClamp = true,
729 .depthBiasClamp = true,
730 .fillModeNonSolid = true,
731 .depthBounds = true,
732 .wideLines = true,
733 .largePoints = true,
734 .alphaToOne = true,
735 .multiViewport = true,
736 .samplerAnisotropy = true,
737 .textureCompressionETC2 = pdevice->rad_info.chip_class >= GFX9 ||
738 pdevice->rad_info.family == CHIP_STONEY,
739 .textureCompressionASTC_LDR = false,
740 .textureCompressionBC = true,
741 .occlusionQueryPrecise = true,
742 .pipelineStatisticsQuery = true,
743 .vertexPipelineStoresAndAtomics = true,
744 .fragmentStoresAndAtomics = true,
745 .shaderTessellationAndGeometryPointSize = true,
746 .shaderImageGatherExtended = true,
747 .shaderStorageImageExtendedFormats = true,
748 .shaderStorageImageMultisample = pdevice->rad_info.chip_class >= VI,
749 .shaderUniformBufferArrayDynamicIndexing = true,
750 .shaderSampledImageArrayDynamicIndexing = true,
751 .shaderStorageBufferArrayDynamicIndexing = true,
752 .shaderStorageImageArrayDynamicIndexing = true,
753 .shaderStorageImageReadWithoutFormat = true,
754 .shaderStorageImageWriteWithoutFormat = true,
755 .shaderClipDistance = true,
756 .shaderCullDistance = true,
757 .shaderFloat64 = true,
758 .shaderInt64 = true,
759 .shaderInt16 = pdevice->rad_info.chip_class >= GFX9,
760 .sparseBinding = true,
761 .variableMultisampleRate = true,
762 .inheritedQueries = true,
763 };
764 }
765
766 void radv_GetPhysicalDeviceFeatures2(
767 VkPhysicalDevice physicalDevice,
768 VkPhysicalDeviceFeatures2 *pFeatures)
769 {
770 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
771 vk_foreach_struct(ext, pFeatures->pNext) {
772 switch (ext->sType) {
773 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES: {
774 VkPhysicalDeviceVariablePointerFeatures *features = (void *)ext;
775 features->variablePointersStorageBuffer = true;
776 features->variablePointers = true;
777 break;
778 }
779 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
780 VkPhysicalDeviceMultiviewFeatures *features = (VkPhysicalDeviceMultiviewFeatures*)ext;
781 features->multiview = true;
782 features->multiviewGeometryShader = true;
783 features->multiviewTessellationShader = true;
784 break;
785 }
786 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES: {
787 VkPhysicalDeviceShaderDrawParameterFeatures *features =
788 (VkPhysicalDeviceShaderDrawParameterFeatures*)ext;
789 features->shaderDrawParameters = true;
790 break;
791 }
792 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
793 VkPhysicalDeviceProtectedMemoryFeatures *features =
794 (VkPhysicalDeviceProtectedMemoryFeatures*)ext;
795 features->protectedMemory = false;
796 break;
797 }
798 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES: {
799 VkPhysicalDevice16BitStorageFeatures *features =
800 (VkPhysicalDevice16BitStorageFeatures*)ext;
801 bool enabled = pdevice->rad_info.chip_class >= VI;
802 features->storageBuffer16BitAccess = enabled;
803 features->uniformAndStorageBuffer16BitAccess = enabled;
804 features->storagePushConstant16 = enabled;
805 features->storageInputOutput16 = enabled;
806 break;
807 }
808 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
809 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
810 (VkPhysicalDeviceSamplerYcbcrConversionFeatures*)ext;
811 features->samplerYcbcrConversion = false;
812 break;
813 }
814 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT: {
815 VkPhysicalDeviceDescriptorIndexingFeaturesEXT *features =
816 (VkPhysicalDeviceDescriptorIndexingFeaturesEXT*)ext;
817 features->shaderInputAttachmentArrayDynamicIndexing = true;
818 features->shaderUniformTexelBufferArrayDynamicIndexing = true;
819 features->shaderStorageTexelBufferArrayDynamicIndexing = true;
820 features->shaderUniformBufferArrayNonUniformIndexing = false;
821 features->shaderSampledImageArrayNonUniformIndexing = false;
822 features->shaderStorageBufferArrayNonUniformIndexing = false;
823 features->shaderStorageImageArrayNonUniformIndexing = false;
824 features->shaderInputAttachmentArrayNonUniformIndexing = false;
825 features->shaderUniformTexelBufferArrayNonUniformIndexing = false;
826 features->shaderStorageTexelBufferArrayNonUniformIndexing = false;
827 features->descriptorBindingUniformBufferUpdateAfterBind = true;
828 features->descriptorBindingSampledImageUpdateAfterBind = true;
829 features->descriptorBindingStorageImageUpdateAfterBind = true;
830 features->descriptorBindingStorageBufferUpdateAfterBind = true;
831 features->descriptorBindingUniformTexelBufferUpdateAfterBind = true;
832 features->descriptorBindingStorageTexelBufferUpdateAfterBind = true;
833 features->descriptorBindingUpdateUnusedWhilePending = true;
834 features->descriptorBindingPartiallyBound = true;
835 features->descriptorBindingVariableDescriptorCount = true;
836 features->runtimeDescriptorArray = true;
837 break;
838 }
839 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT: {
840 VkPhysicalDeviceConditionalRenderingFeaturesEXT *features =
841 (VkPhysicalDeviceConditionalRenderingFeaturesEXT*)ext;
842 features->conditionalRendering = true;
843 features->inheritedConditionalRendering = false;
844 break;
845 }
846 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
847 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
848 (VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
849 features->vertexAttributeInstanceRateDivisor = VK_TRUE;
850 features->vertexAttributeInstanceRateZeroDivisor = VK_TRUE;
851 break;
852 }
853 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT: {
854 VkPhysicalDeviceTransformFeedbackFeaturesEXT *features =
855 (VkPhysicalDeviceTransformFeedbackFeaturesEXT*)ext;
856 features->transformFeedback = true;
857 features->geometryStreams = true;
858 break;
859 }
860 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT: {
861 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *features =
862 (VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *)ext;
863 features->scalarBlockLayout = pdevice->rad_info.chip_class >= CIK;
864 break;
865 }
866 default:
867 break;
868 }
869 }
870 return radv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
871 }
872
873 void radv_GetPhysicalDeviceProperties(
874 VkPhysicalDevice physicalDevice,
875 VkPhysicalDeviceProperties* pProperties)
876 {
877 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
878 VkSampleCountFlags sample_counts = 0xf;
879
880 /* make sure that the entire descriptor set is addressable with a signed
881 * 32-bit int. So the sum of all limits scaled by descriptor size has to
882 * be at most 2 GiB. the combined image & samples object count as one of
883 * both. This limit is for the pipeline layout, not for the set layout, but
884 * there is no set limit, so we just set a pipeline limit. I don't think
885 * any app is going to hit this soon. */
886 size_t max_descriptor_set_size = ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS) /
887 (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
888 32 /* storage buffer, 32 due to potential space wasted on alignment */ +
889 32 /* sampler, largest when combined with image */ +
890 64 /* sampled image */ +
891 64 /* storage image */);
892
893 VkPhysicalDeviceLimits limits = {
894 .maxImageDimension1D = (1 << 14),
895 .maxImageDimension2D = (1 << 14),
896 .maxImageDimension3D = (1 << 11),
897 .maxImageDimensionCube = (1 << 14),
898 .maxImageArrayLayers = (1 << 11),
899 .maxTexelBufferElements = 128 * 1024 * 1024,
900 .maxUniformBufferRange = UINT32_MAX,
901 .maxStorageBufferRange = UINT32_MAX,
902 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
903 .maxMemoryAllocationCount = UINT32_MAX,
904 .maxSamplerAllocationCount = 64 * 1024,
905 .bufferImageGranularity = 64, /* A cache line */
906 .sparseAddressSpaceSize = 0xffffffffu, /* buffer max size */
907 .maxBoundDescriptorSets = MAX_SETS,
908 .maxPerStageDescriptorSamplers = max_descriptor_set_size,
909 .maxPerStageDescriptorUniformBuffers = max_descriptor_set_size,
910 .maxPerStageDescriptorStorageBuffers = max_descriptor_set_size,
911 .maxPerStageDescriptorSampledImages = max_descriptor_set_size,
912 .maxPerStageDescriptorStorageImages = max_descriptor_set_size,
913 .maxPerStageDescriptorInputAttachments = max_descriptor_set_size,
914 .maxPerStageResources = max_descriptor_set_size,
915 .maxDescriptorSetSamplers = max_descriptor_set_size,
916 .maxDescriptorSetUniformBuffers = max_descriptor_set_size,
917 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS,
918 .maxDescriptorSetStorageBuffers = max_descriptor_set_size,
919 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS,
920 .maxDescriptorSetSampledImages = max_descriptor_set_size,
921 .maxDescriptorSetStorageImages = max_descriptor_set_size,
922 .maxDescriptorSetInputAttachments = max_descriptor_set_size,
923 .maxVertexInputAttributes = 32,
924 .maxVertexInputBindings = 32,
925 .maxVertexInputAttributeOffset = 2047,
926 .maxVertexInputBindingStride = 2048,
927 .maxVertexOutputComponents = 128,
928 .maxTessellationGenerationLevel = 64,
929 .maxTessellationPatchSize = 32,
930 .maxTessellationControlPerVertexInputComponents = 128,
931 .maxTessellationControlPerVertexOutputComponents = 128,
932 .maxTessellationControlPerPatchOutputComponents = 120,
933 .maxTessellationControlTotalOutputComponents = 4096,
934 .maxTessellationEvaluationInputComponents = 128,
935 .maxTessellationEvaluationOutputComponents = 128,
936 .maxGeometryShaderInvocations = 127,
937 .maxGeometryInputComponents = 64,
938 .maxGeometryOutputComponents = 128,
939 .maxGeometryOutputVertices = 256,
940 .maxGeometryTotalOutputComponents = 1024,
941 .maxFragmentInputComponents = 128,
942 .maxFragmentOutputAttachments = 8,
943 .maxFragmentDualSrcAttachments = 1,
944 .maxFragmentCombinedOutputResources = 8,
945 .maxComputeSharedMemorySize = 32768,
946 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
947 .maxComputeWorkGroupInvocations = 2048,
948 .maxComputeWorkGroupSize = {
949 2048,
950 2048,
951 2048
952 },
953 .subPixelPrecisionBits = 8,
954 .subTexelPrecisionBits = 8,
955 .mipmapPrecisionBits = 8,
956 .maxDrawIndexedIndexValue = UINT32_MAX,
957 .maxDrawIndirectCount = UINT32_MAX,
958 .maxSamplerLodBias = 16,
959 .maxSamplerAnisotropy = 16,
960 .maxViewports = MAX_VIEWPORTS,
961 .maxViewportDimensions = { (1 << 14), (1 << 14) },
962 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
963 .viewportSubPixelBits = 8,
964 .minMemoryMapAlignment = 4096, /* A page */
965 .minTexelBufferOffsetAlignment = 1,
966 .minUniformBufferOffsetAlignment = 4,
967 .minStorageBufferOffsetAlignment = 4,
968 .minTexelOffset = -32,
969 .maxTexelOffset = 31,
970 .minTexelGatherOffset = -32,
971 .maxTexelGatherOffset = 31,
972 .minInterpolationOffset = -2,
973 .maxInterpolationOffset = 2,
974 .subPixelInterpolationOffsetBits = 8,
975 .maxFramebufferWidth = (1 << 14),
976 .maxFramebufferHeight = (1 << 14),
977 .maxFramebufferLayers = (1 << 10),
978 .framebufferColorSampleCounts = sample_counts,
979 .framebufferDepthSampleCounts = sample_counts,
980 .framebufferStencilSampleCounts = sample_counts,
981 .framebufferNoAttachmentsSampleCounts = sample_counts,
982 .maxColorAttachments = MAX_RTS,
983 .sampledImageColorSampleCounts = sample_counts,
984 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
985 .sampledImageDepthSampleCounts = sample_counts,
986 .sampledImageStencilSampleCounts = sample_counts,
987 .storageImageSampleCounts = pdevice->rad_info.chip_class >= VI ? sample_counts : VK_SAMPLE_COUNT_1_BIT,
988 .maxSampleMaskWords = 1,
989 .timestampComputeAndGraphics = true,
990 .timestampPeriod = 1000000.0 / pdevice->rad_info.clock_crystal_freq,
991 .maxClipDistances = 8,
992 .maxCullDistances = 8,
993 .maxCombinedClipAndCullDistances = 8,
994 .discreteQueuePriorities = 2,
995 .pointSizeRange = { 0.125, 255.875 },
996 .lineWidthRange = { 0.0, 7.9921875 },
997 .pointSizeGranularity = (1.0 / 8.0),
998 .lineWidthGranularity = (1.0 / 128.0),
999 .strictLines = false, /* FINISHME */
1000 .standardSampleLocations = true,
1001 .optimalBufferCopyOffsetAlignment = 128,
1002 .optimalBufferCopyRowPitchAlignment = 128,
1003 .nonCoherentAtomSize = 64,
1004 };
1005
1006 *pProperties = (VkPhysicalDeviceProperties) {
1007 .apiVersion = radv_physical_device_api_version(pdevice),
1008 .driverVersion = vk_get_driver_version(),
1009 .vendorID = ATI_VENDOR_ID,
1010 .deviceID = pdevice->rad_info.pci_id,
1011 .deviceType = pdevice->rad_info.has_dedicated_vram ? VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU : VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1012 .limits = limits,
1013 .sparseProperties = {0},
1014 };
1015
1016 strcpy(pProperties->deviceName, pdevice->name);
1017 memcpy(pProperties->pipelineCacheUUID, pdevice->cache_uuid, VK_UUID_SIZE);
1018 }
1019
1020 void radv_GetPhysicalDeviceProperties2(
1021 VkPhysicalDevice physicalDevice,
1022 VkPhysicalDeviceProperties2 *pProperties)
1023 {
1024 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1025 radv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
1026
1027 vk_foreach_struct(ext, pProperties->pNext) {
1028 switch (ext->sType) {
1029 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
1030 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
1031 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
1032 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
1033 break;
1034 }
1035 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1036 VkPhysicalDeviceIDProperties *properties = (VkPhysicalDeviceIDProperties*)ext;
1037 memcpy(properties->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1038 memcpy(properties->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1039 properties->deviceLUIDValid = false;
1040 break;
1041 }
1042 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1043 VkPhysicalDeviceMultiviewProperties *properties = (VkPhysicalDeviceMultiviewProperties*)ext;
1044 properties->maxMultiviewViewCount = MAX_VIEWS;
1045 properties->maxMultiviewInstanceIndex = INT_MAX;
1046 break;
1047 }
1048 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
1049 VkPhysicalDevicePointClippingProperties *properties =
1050 (VkPhysicalDevicePointClippingProperties*)ext;
1051 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
1052 break;
1053 }
1054 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DISCARD_RECTANGLE_PROPERTIES_EXT: {
1055 VkPhysicalDeviceDiscardRectanglePropertiesEXT *properties =
1056 (VkPhysicalDeviceDiscardRectanglePropertiesEXT*)ext;
1057 properties->maxDiscardRectangles = MAX_DISCARD_RECTANGLES;
1058 break;
1059 }
1060 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT: {
1061 VkPhysicalDeviceExternalMemoryHostPropertiesEXT *properties =
1062 (VkPhysicalDeviceExternalMemoryHostPropertiesEXT *) ext;
1063 properties->minImportedHostPointerAlignment = 4096;
1064 break;
1065 }
1066 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
1067 VkPhysicalDeviceSubgroupProperties *properties =
1068 (VkPhysicalDeviceSubgroupProperties*)ext;
1069 properties->subgroupSize = 64;
1070 properties->supportedStages = VK_SHADER_STAGE_ALL;
1071 properties->supportedOperations =
1072 VK_SUBGROUP_FEATURE_BASIC_BIT |
1073 VK_SUBGROUP_FEATURE_BALLOT_BIT |
1074 VK_SUBGROUP_FEATURE_QUAD_BIT |
1075 VK_SUBGROUP_FEATURE_VOTE_BIT;
1076 if (pdevice->rad_info.chip_class >= VI) {
1077 properties->supportedOperations |=
1078 VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1079 VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1080 VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT;
1081 }
1082 properties->quadOperationsInAllStages = true;
1083 break;
1084 }
1085 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1086 VkPhysicalDeviceMaintenance3Properties *properties =
1087 (VkPhysicalDeviceMaintenance3Properties*)ext;
1088 /* Make sure everything is addressable by a signed 32-bit int, and
1089 * our largest descriptors are 96 bytes. */
1090 properties->maxPerSetDescriptors = (1ull << 31) / 96;
1091 /* Our buffer size fields allow only this much */
1092 properties->maxMemoryAllocationSize = 0xFFFFFFFFull;
1093 break;
1094 }
1095 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT: {
1096 VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *properties =
1097 (VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *)ext;
1098 /* GFX6-8 only support single channel min/max filter. */
1099 properties->filterMinmaxImageComponentMapping = pdevice->rad_info.chip_class >= GFX9;
1100 properties->filterMinmaxSingleComponentFormats = true;
1101 break;
1102 }
1103 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_AMD: {
1104 VkPhysicalDeviceShaderCorePropertiesAMD *properties =
1105 (VkPhysicalDeviceShaderCorePropertiesAMD *)ext;
1106
1107 /* Shader engines. */
1108 properties->shaderEngineCount =
1109 pdevice->rad_info.max_se;
1110 properties->shaderArraysPerEngineCount =
1111 pdevice->rad_info.max_sh_per_se;
1112 properties->computeUnitsPerShaderArray =
1113 pdevice->rad_info.num_good_cu_per_sh;
1114 properties->simdPerComputeUnit = 4;
1115 properties->wavefrontsPerSimd =
1116 pdevice->rad_info.family == CHIP_TONGA ||
1117 pdevice->rad_info.family == CHIP_ICELAND ||
1118 pdevice->rad_info.family == CHIP_POLARIS10 ||
1119 pdevice->rad_info.family == CHIP_POLARIS11 ||
1120 pdevice->rad_info.family == CHIP_POLARIS12 ||
1121 pdevice->rad_info.family == CHIP_VEGAM ? 8 : 10;
1122 properties->wavefrontSize = 64;
1123
1124 /* SGPR. */
1125 properties->sgprsPerSimd =
1126 radv_get_num_physical_sgprs(pdevice);
1127 properties->minSgprAllocation =
1128 pdevice->rad_info.chip_class >= VI ? 16 : 8;
1129 properties->maxSgprAllocation =
1130 pdevice->rad_info.family == CHIP_TONGA ||
1131 pdevice->rad_info.family == CHIP_ICELAND ? 96 : 104;
1132 properties->sgprAllocationGranularity =
1133 pdevice->rad_info.chip_class >= VI ? 16 : 8;
1134
1135 /* VGPR. */
1136 properties->vgprsPerSimd = RADV_NUM_PHYSICAL_VGPRS;
1137 properties->minVgprAllocation = 4;
1138 properties->maxVgprAllocation = 256;
1139 properties->vgprAllocationGranularity = 4;
1140 break;
1141 }
1142 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
1143 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *properties =
1144 (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
1145 properties->maxVertexAttribDivisor = UINT32_MAX;
1146 break;
1147 }
1148 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES_EXT: {
1149 VkPhysicalDeviceDescriptorIndexingPropertiesEXT *properties =
1150 (VkPhysicalDeviceDescriptorIndexingPropertiesEXT*)ext;
1151 properties->maxUpdateAfterBindDescriptorsInAllPools = UINT32_MAX / 64;
1152 properties->shaderUniformBufferArrayNonUniformIndexingNative = false;
1153 properties->shaderSampledImageArrayNonUniformIndexingNative = false;
1154 properties->shaderStorageBufferArrayNonUniformIndexingNative = false;
1155 properties->shaderStorageImageArrayNonUniformIndexingNative = false;
1156 properties->shaderInputAttachmentArrayNonUniformIndexingNative = false;
1157 properties->robustBufferAccessUpdateAfterBind = false;
1158 properties->quadDivergentImplicitLod = false;
1159
1160 size_t max_descriptor_set_size = ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS) /
1161 (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
1162 32 /* storage buffer, 32 due to potential space wasted on alignment */ +
1163 32 /* sampler, largest when combined with image */ +
1164 64 /* sampled image */ +
1165 64 /* storage image */);
1166 properties->maxPerStageDescriptorUpdateAfterBindSamplers = max_descriptor_set_size;
1167 properties->maxPerStageDescriptorUpdateAfterBindUniformBuffers = max_descriptor_set_size;
1168 properties->maxPerStageDescriptorUpdateAfterBindStorageBuffers = max_descriptor_set_size;
1169 properties->maxPerStageDescriptorUpdateAfterBindSampledImages = max_descriptor_set_size;
1170 properties->maxPerStageDescriptorUpdateAfterBindStorageImages = max_descriptor_set_size;
1171 properties->maxPerStageDescriptorUpdateAfterBindInputAttachments = max_descriptor_set_size;
1172 properties->maxPerStageUpdateAfterBindResources = max_descriptor_set_size;
1173 properties->maxDescriptorSetUpdateAfterBindSamplers = max_descriptor_set_size;
1174 properties->maxDescriptorSetUpdateAfterBindUniformBuffers = max_descriptor_set_size;
1175 properties->maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS;
1176 properties->maxDescriptorSetUpdateAfterBindStorageBuffers = max_descriptor_set_size;
1177 properties->maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS;
1178 properties->maxDescriptorSetUpdateAfterBindSampledImages = max_descriptor_set_size;
1179 properties->maxDescriptorSetUpdateAfterBindStorageImages = max_descriptor_set_size;
1180 properties->maxDescriptorSetUpdateAfterBindInputAttachments = max_descriptor_set_size;
1181 break;
1182 }
1183 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES: {
1184 VkPhysicalDeviceProtectedMemoryProperties *properties =
1185 (VkPhysicalDeviceProtectedMemoryProperties *)ext;
1186 properties->protectedNoFault = false;
1187 break;
1188 }
1189 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT: {
1190 VkPhysicalDeviceConservativeRasterizationPropertiesEXT *properties =
1191 (VkPhysicalDeviceConservativeRasterizationPropertiesEXT *)ext;
1192 properties->primitiveOverestimationSize = 0;
1193 properties->maxExtraPrimitiveOverestimationSize = 0;
1194 properties->extraPrimitiveOverestimationSizeGranularity = 0;
1195 properties->primitiveUnderestimation = VK_FALSE;
1196 properties->conservativePointAndLineRasterization = VK_FALSE;
1197 properties->degenerateTrianglesRasterized = VK_FALSE;
1198 properties->degenerateLinesRasterized = VK_FALSE;
1199 properties->fullyCoveredFragmentShaderInputVariable = VK_FALSE;
1200 properties->conservativeRasterizationPostDepthCoverage = VK_FALSE;
1201 break;
1202 }
1203 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT: {
1204 VkPhysicalDevicePCIBusInfoPropertiesEXT *properties =
1205 (VkPhysicalDevicePCIBusInfoPropertiesEXT *)ext;
1206 properties->pciDomain = pdevice->bus_info.domain;
1207 properties->pciBus = pdevice->bus_info.bus;
1208 properties->pciDevice = pdevice->bus_info.dev;
1209 properties->pciFunction = pdevice->bus_info.func;
1210 break;
1211 }
1212 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR: {
1213 VkPhysicalDeviceDriverPropertiesKHR *driver_props =
1214 (VkPhysicalDeviceDriverPropertiesKHR *) ext;
1215
1216 driver_props->driverID = VK_DRIVER_ID_MESA_RADV_KHR;
1217 memset(driver_props->driverName, 0, VK_MAX_DRIVER_NAME_SIZE_KHR);
1218 strcpy(driver_props->driverName, "radv");
1219
1220 memset(driver_props->driverInfo, 0, VK_MAX_DRIVER_INFO_SIZE_KHR);
1221 snprintf(driver_props->driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR,
1222 "Mesa " PACKAGE_VERSION MESA_GIT_SHA1
1223 " (LLVM %d.%d.%d)",
1224 (HAVE_LLVM >> 8) & 0xff, HAVE_LLVM & 0xff,
1225 MESA_LLVM_VERSION_PATCH);
1226
1227 driver_props->conformanceVersion = (VkConformanceVersionKHR) {
1228 .major = 1,
1229 .minor = 1,
1230 .subminor = 2,
1231 .patch = 0,
1232 };
1233 break;
1234 }
1235 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT: {
1236 VkPhysicalDeviceTransformFeedbackPropertiesEXT *properties =
1237 (VkPhysicalDeviceTransformFeedbackPropertiesEXT *)ext;
1238 properties->maxTransformFeedbackStreams = MAX_SO_STREAMS;
1239 properties->maxTransformFeedbackBuffers = MAX_SO_BUFFERS;
1240 properties->maxTransformFeedbackBufferSize = UINT32_MAX;
1241 properties->maxTransformFeedbackStreamDataSize = 512;
1242 properties->maxTransformFeedbackBufferDataSize = UINT32_MAX;
1243 properties->maxTransformFeedbackBufferDataStride = 512;
1244 properties->transformFeedbackQueries = true;
1245 properties->transformFeedbackStreamsLinesTriangles = false;
1246 properties->transformFeedbackRasterizationStreamSelect = false;
1247 properties->transformFeedbackDraw = true;
1248 break;
1249 }
1250 default:
1251 break;
1252 }
1253 }
1254 }
1255
1256 static void radv_get_physical_device_queue_family_properties(
1257 struct radv_physical_device* pdevice,
1258 uint32_t* pCount,
1259 VkQueueFamilyProperties** pQueueFamilyProperties)
1260 {
1261 int num_queue_families = 1;
1262 int idx;
1263 if (pdevice->rad_info.num_compute_rings > 0 &&
1264 !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE))
1265 num_queue_families++;
1266
1267 if (pQueueFamilyProperties == NULL) {
1268 *pCount = num_queue_families;
1269 return;
1270 }
1271
1272 if (!*pCount)
1273 return;
1274
1275 idx = 0;
1276 if (*pCount >= 1) {
1277 *pQueueFamilyProperties[idx] = (VkQueueFamilyProperties) {
1278 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
1279 VK_QUEUE_COMPUTE_BIT |
1280 VK_QUEUE_TRANSFER_BIT |
1281 VK_QUEUE_SPARSE_BINDING_BIT,
1282 .queueCount = 1,
1283 .timestampValidBits = 64,
1284 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
1285 };
1286 idx++;
1287 }
1288
1289 if (pdevice->rad_info.num_compute_rings > 0 &&
1290 !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE)) {
1291 if (*pCount > idx) {
1292 *pQueueFamilyProperties[idx] = (VkQueueFamilyProperties) {
1293 .queueFlags = VK_QUEUE_COMPUTE_BIT |
1294 VK_QUEUE_TRANSFER_BIT |
1295 VK_QUEUE_SPARSE_BINDING_BIT,
1296 .queueCount = pdevice->rad_info.num_compute_rings,
1297 .timestampValidBits = 64,
1298 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
1299 };
1300 idx++;
1301 }
1302 }
1303 *pCount = idx;
1304 }
1305
1306 void radv_GetPhysicalDeviceQueueFamilyProperties(
1307 VkPhysicalDevice physicalDevice,
1308 uint32_t* pCount,
1309 VkQueueFamilyProperties* pQueueFamilyProperties)
1310 {
1311 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1312 if (!pQueueFamilyProperties) {
1313 radv_get_physical_device_queue_family_properties(pdevice, pCount, NULL);
1314 return;
1315 }
1316 VkQueueFamilyProperties *properties[] = {
1317 pQueueFamilyProperties + 0,
1318 pQueueFamilyProperties + 1,
1319 pQueueFamilyProperties + 2,
1320 };
1321 radv_get_physical_device_queue_family_properties(pdevice, pCount, properties);
1322 assert(*pCount <= 3);
1323 }
1324
1325 void radv_GetPhysicalDeviceQueueFamilyProperties2(
1326 VkPhysicalDevice physicalDevice,
1327 uint32_t* pCount,
1328 VkQueueFamilyProperties2 *pQueueFamilyProperties)
1329 {
1330 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1331 if (!pQueueFamilyProperties) {
1332 radv_get_physical_device_queue_family_properties(pdevice, pCount, NULL);
1333 return;
1334 }
1335 VkQueueFamilyProperties *properties[] = {
1336 &pQueueFamilyProperties[0].queueFamilyProperties,
1337 &pQueueFamilyProperties[1].queueFamilyProperties,
1338 &pQueueFamilyProperties[2].queueFamilyProperties,
1339 };
1340 radv_get_physical_device_queue_family_properties(pdevice, pCount, properties);
1341 assert(*pCount <= 3);
1342 }
1343
1344 void radv_GetPhysicalDeviceMemoryProperties(
1345 VkPhysicalDevice physicalDevice,
1346 VkPhysicalDeviceMemoryProperties *pMemoryProperties)
1347 {
1348 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
1349
1350 *pMemoryProperties = physical_device->memory_properties;
1351 }
1352
1353 static void
1354 radv_get_memory_budget_properties(VkPhysicalDevice physicalDevice,
1355 VkPhysicalDeviceMemoryBudgetPropertiesEXT *memoryBudget)
1356 {
1357 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
1358 VkPhysicalDeviceMemoryProperties *memory_properties = &device->memory_properties;
1359 uint64_t visible_vram_size = radv_get_visible_vram_size(device);
1360 uint64_t vram_size = radv_get_vram_size(device);
1361 uint64_t gtt_size = device->rad_info.gart_size;
1362 uint64_t heap_budget, heap_usage;
1363
1364 /* For all memory heaps, the computation of budget is as follow:
1365 * heap_budget = heap_size - global_heap_usage + app_heap_usage
1366 *
1367 * The Vulkan spec 1.1.97 says that the budget should include any
1368 * currently allocated device memory.
1369 *
1370 * Note that the application heap usages are not really accurate (eg.
1371 * in presence of shared buffers).
1372 */
1373 if (vram_size) {
1374 heap_usage = device->ws->query_value(device->ws,
1375 RADEON_ALLOCATED_VRAM);
1376
1377 heap_budget = vram_size -
1378 device->ws->query_value(device->ws, RADEON_VRAM_USAGE) +
1379 heap_usage;
1380
1381 memoryBudget->heapBudget[RADV_MEM_HEAP_VRAM] = heap_budget;
1382 memoryBudget->heapUsage[RADV_MEM_HEAP_VRAM] = heap_usage;
1383 }
1384
1385 if (visible_vram_size) {
1386 heap_usage = device->ws->query_value(device->ws,
1387 RADEON_ALLOCATED_VRAM_VIS);
1388
1389 heap_budget = visible_vram_size -
1390 device->ws->query_value(device->ws, RADEON_VRAM_VIS_USAGE) +
1391 heap_usage;
1392
1393 memoryBudget->heapBudget[RADV_MEM_HEAP_VRAM_CPU_ACCESS] = heap_budget;
1394 memoryBudget->heapUsage[RADV_MEM_HEAP_VRAM_CPU_ACCESS] = heap_usage;
1395 }
1396
1397 if (gtt_size) {
1398 heap_usage = device->ws->query_value(device->ws,
1399 RADEON_ALLOCATED_GTT);
1400
1401 heap_budget = gtt_size -
1402 device->ws->query_value(device->ws, RADEON_GTT_USAGE) +
1403 heap_usage;
1404
1405 memoryBudget->heapBudget[RADV_MEM_HEAP_GTT] = heap_budget;
1406 memoryBudget->heapUsage[RADV_MEM_HEAP_GTT] = heap_usage;
1407 }
1408
1409 /* The heapBudget and heapUsage values must be zero for array elements
1410 * greater than or equal to
1411 * VkPhysicalDeviceMemoryProperties::memoryHeapCount.
1412 */
1413 for (uint32_t i = memory_properties->memoryHeapCount; i < VK_MAX_MEMORY_HEAPS; i++) {
1414 memoryBudget->heapBudget[i] = 0;
1415 memoryBudget->heapUsage[i] = 0;
1416 }
1417 }
1418
1419 void radv_GetPhysicalDeviceMemoryProperties2(
1420 VkPhysicalDevice physicalDevice,
1421 VkPhysicalDeviceMemoryProperties2 *pMemoryProperties)
1422 {
1423 radv_GetPhysicalDeviceMemoryProperties(physicalDevice,
1424 &pMemoryProperties->memoryProperties);
1425
1426 VkPhysicalDeviceMemoryBudgetPropertiesEXT *memory_budget =
1427 vk_find_struct(pMemoryProperties->pNext,
1428 PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT);
1429 if (memory_budget)
1430 radv_get_memory_budget_properties(physicalDevice, memory_budget);
1431 }
1432
1433 VkResult radv_GetMemoryHostPointerPropertiesEXT(
1434 VkDevice _device,
1435 VkExternalMemoryHandleTypeFlagBits handleType,
1436 const void *pHostPointer,
1437 VkMemoryHostPointerPropertiesEXT *pMemoryHostPointerProperties)
1438 {
1439 RADV_FROM_HANDLE(radv_device, device, _device);
1440
1441 switch (handleType)
1442 {
1443 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT: {
1444 const struct radv_physical_device *physical_device = device->physical_device;
1445 uint32_t memoryTypeBits = 0;
1446 for (int i = 0; i < physical_device->memory_properties.memoryTypeCount; i++) {
1447 if (physical_device->mem_type_indices[i] == RADV_MEM_TYPE_GTT_CACHED) {
1448 memoryTypeBits = (1 << i);
1449 break;
1450 }
1451 }
1452 pMemoryHostPointerProperties->memoryTypeBits = memoryTypeBits;
1453 return VK_SUCCESS;
1454 }
1455 default:
1456 return VK_ERROR_INVALID_EXTERNAL_HANDLE;
1457 }
1458 }
1459
1460 static enum radeon_ctx_priority
1461 radv_get_queue_global_priority(const VkDeviceQueueGlobalPriorityCreateInfoEXT *pObj)
1462 {
1463 /* Default to MEDIUM when a specific global priority isn't requested */
1464 if (!pObj)
1465 return RADEON_CTX_PRIORITY_MEDIUM;
1466
1467 switch(pObj->globalPriority) {
1468 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
1469 return RADEON_CTX_PRIORITY_REALTIME;
1470 case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
1471 return RADEON_CTX_PRIORITY_HIGH;
1472 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
1473 return RADEON_CTX_PRIORITY_MEDIUM;
1474 case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
1475 return RADEON_CTX_PRIORITY_LOW;
1476 default:
1477 unreachable("Illegal global priority value");
1478 return RADEON_CTX_PRIORITY_INVALID;
1479 }
1480 }
1481
1482 static int
1483 radv_queue_init(struct radv_device *device, struct radv_queue *queue,
1484 uint32_t queue_family_index, int idx,
1485 VkDeviceQueueCreateFlags flags,
1486 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority)
1487 {
1488 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1489 queue->device = device;
1490 queue->queue_family_index = queue_family_index;
1491 queue->queue_idx = idx;
1492 queue->priority = radv_get_queue_global_priority(global_priority);
1493 queue->flags = flags;
1494
1495 queue->hw_ctx = device->ws->ctx_create(device->ws, queue->priority);
1496 if (!queue->hw_ctx)
1497 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1498
1499 return VK_SUCCESS;
1500 }
1501
1502 static void
1503 radv_queue_finish(struct radv_queue *queue)
1504 {
1505 if (queue->hw_ctx)
1506 queue->device->ws->ctx_destroy(queue->hw_ctx);
1507
1508 if (queue->initial_full_flush_preamble_cs)
1509 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
1510 if (queue->initial_preamble_cs)
1511 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
1512 if (queue->continue_preamble_cs)
1513 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
1514 if (queue->descriptor_bo)
1515 queue->device->ws->buffer_destroy(queue->descriptor_bo);
1516 if (queue->scratch_bo)
1517 queue->device->ws->buffer_destroy(queue->scratch_bo);
1518 if (queue->esgs_ring_bo)
1519 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
1520 if (queue->gsvs_ring_bo)
1521 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
1522 if (queue->tess_rings_bo)
1523 queue->device->ws->buffer_destroy(queue->tess_rings_bo);
1524 if (queue->compute_scratch_bo)
1525 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
1526 }
1527
1528 static void
1529 radv_bo_list_init(struct radv_bo_list *bo_list)
1530 {
1531 pthread_mutex_init(&bo_list->mutex, NULL);
1532 bo_list->list.count = bo_list->capacity = 0;
1533 bo_list->list.bos = NULL;
1534 }
1535
1536 static void
1537 radv_bo_list_finish(struct radv_bo_list *bo_list)
1538 {
1539 free(bo_list->list.bos);
1540 pthread_mutex_destroy(&bo_list->mutex);
1541 }
1542
1543 static VkResult radv_bo_list_add(struct radv_device *device,
1544 struct radeon_winsys_bo *bo)
1545 {
1546 struct radv_bo_list *bo_list = &device->bo_list;
1547
1548 if (unlikely(!device->use_global_bo_list))
1549 return VK_SUCCESS;
1550
1551 pthread_mutex_lock(&bo_list->mutex);
1552 if (bo_list->list.count == bo_list->capacity) {
1553 unsigned capacity = MAX2(4, bo_list->capacity * 2);
1554 void *data = realloc(bo_list->list.bos, capacity * sizeof(struct radeon_winsys_bo*));
1555
1556 if (!data) {
1557 pthread_mutex_unlock(&bo_list->mutex);
1558 return VK_ERROR_OUT_OF_HOST_MEMORY;
1559 }
1560
1561 bo_list->list.bos = (struct radeon_winsys_bo**)data;
1562 bo_list->capacity = capacity;
1563 }
1564
1565 bo_list->list.bos[bo_list->list.count++] = bo;
1566 pthread_mutex_unlock(&bo_list->mutex);
1567 return VK_SUCCESS;
1568 }
1569
1570 static void radv_bo_list_remove(struct radv_device *device,
1571 struct radeon_winsys_bo *bo)
1572 {
1573 struct radv_bo_list *bo_list = &device->bo_list;
1574
1575 if (unlikely(!device->use_global_bo_list))
1576 return;
1577
1578 pthread_mutex_lock(&bo_list->mutex);
1579 for(unsigned i = 0; i < bo_list->list.count; ++i) {
1580 if (bo_list->list.bos[i] == bo) {
1581 bo_list->list.bos[i] = bo_list->list.bos[bo_list->list.count - 1];
1582 --bo_list->list.count;
1583 break;
1584 }
1585 }
1586 pthread_mutex_unlock(&bo_list->mutex);
1587 }
1588
1589 static void
1590 radv_device_init_gs_info(struct radv_device *device)
1591 {
1592 device->gs_table_depth = ac_get_gs_table_depth(device->physical_device->rad_info.chip_class,
1593 device->physical_device->rad_info.family);
1594 }
1595
1596 static int radv_get_device_extension_index(const char *name)
1597 {
1598 for (unsigned i = 0; i < RADV_DEVICE_EXTENSION_COUNT; ++i) {
1599 if (strcmp(name, radv_device_extensions[i].extensionName) == 0)
1600 return i;
1601 }
1602 return -1;
1603 }
1604
1605 static int
1606 radv_get_int_debug_option(const char *name, int default_value)
1607 {
1608 const char *str;
1609 int result;
1610
1611 str = getenv(name);
1612 if (!str) {
1613 result = default_value;
1614 } else {
1615 char *endptr;
1616
1617 result = strtol(str, &endptr, 0);
1618 if (str == endptr) {
1619 /* No digits founs. */
1620 result = default_value;
1621 }
1622 }
1623
1624 return result;
1625 }
1626
1627 VkResult radv_CreateDevice(
1628 VkPhysicalDevice physicalDevice,
1629 const VkDeviceCreateInfo* pCreateInfo,
1630 const VkAllocationCallbacks* pAllocator,
1631 VkDevice* pDevice)
1632 {
1633 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
1634 VkResult result;
1635 struct radv_device *device;
1636
1637 bool keep_shader_info = false;
1638
1639 /* Check enabled features */
1640 if (pCreateInfo->pEnabledFeatures) {
1641 VkPhysicalDeviceFeatures supported_features;
1642 radv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1643 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
1644 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
1645 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1646 for (uint32_t i = 0; i < num_features; i++) {
1647 if (enabled_feature[i] && !supported_feature[i])
1648 return vk_error(physical_device->instance, VK_ERROR_FEATURE_NOT_PRESENT);
1649 }
1650 }
1651
1652 device = vk_zalloc2(&physical_device->instance->alloc, pAllocator,
1653 sizeof(*device), 8,
1654 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1655 if (!device)
1656 return vk_error(physical_device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1657
1658 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1659 device->instance = physical_device->instance;
1660 device->physical_device = physical_device;
1661
1662 device->ws = physical_device->ws;
1663 if (pAllocator)
1664 device->alloc = *pAllocator;
1665 else
1666 device->alloc = physical_device->instance->alloc;
1667
1668 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1669 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
1670 int index = radv_get_device_extension_index(ext_name);
1671 if (index < 0 || !physical_device->supported_extensions.extensions[index]) {
1672 vk_free(&device->alloc, device);
1673 return vk_error(physical_device->instance, VK_ERROR_EXTENSION_NOT_PRESENT);
1674 }
1675
1676 device->enabled_extensions.extensions[index] = true;
1677 }
1678
1679 keep_shader_info = device->enabled_extensions.AMD_shader_info;
1680
1681 /* With update after bind we can't attach bo's to the command buffer
1682 * from the descriptor set anymore, so we have to use a global BO list.
1683 */
1684 device->use_global_bo_list =
1685 device->enabled_extensions.EXT_descriptor_indexing;
1686
1687 mtx_init(&device->shader_slab_mutex, mtx_plain);
1688 list_inithead(&device->shader_slabs);
1689
1690 radv_bo_list_init(&device->bo_list);
1691
1692 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
1693 const VkDeviceQueueCreateInfo *queue_create = &pCreateInfo->pQueueCreateInfos[i];
1694 uint32_t qfi = queue_create->queueFamilyIndex;
1695 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority =
1696 vk_find_struct_const(queue_create->pNext, DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
1697
1698 assert(!global_priority || device->physical_device->rad_info.has_ctx_priority);
1699
1700 device->queues[qfi] = vk_alloc(&device->alloc,
1701 queue_create->queueCount * sizeof(struct radv_queue), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1702 if (!device->queues[qfi]) {
1703 result = VK_ERROR_OUT_OF_HOST_MEMORY;
1704 goto fail;
1705 }
1706
1707 memset(device->queues[qfi], 0, queue_create->queueCount * sizeof(struct radv_queue));
1708
1709 device->queue_count[qfi] = queue_create->queueCount;
1710
1711 for (unsigned q = 0; q < queue_create->queueCount; q++) {
1712 result = radv_queue_init(device, &device->queues[qfi][q],
1713 qfi, q, queue_create->flags,
1714 global_priority);
1715 if (result != VK_SUCCESS)
1716 goto fail;
1717 }
1718 }
1719
1720 device->pbb_allowed = device->physical_device->rad_info.chip_class >= GFX9 &&
1721 !(device->instance->debug_flags & RADV_DEBUG_NOBINNING);
1722
1723 /* Disabled and not implemented for now. */
1724 device->dfsm_allowed = device->pbb_allowed &&
1725 (device->physical_device->rad_info.family == CHIP_RAVEN ||
1726 device->physical_device->rad_info.family == CHIP_RAVEN2);
1727
1728 #ifdef ANDROID
1729 device->always_use_syncobj = device->physical_device->rad_info.has_syncobj_wait_for_submit;
1730 #endif
1731
1732 /* The maximum number of scratch waves. Scratch space isn't divided
1733 * evenly between CUs. The number is only a function of the number of CUs.
1734 * We can decrease the constant to decrease the scratch buffer size.
1735 *
1736 * sctx->scratch_waves must be >= the maximum possible size of
1737 * 1 threadgroup, so that the hw doesn't hang from being unable
1738 * to start any.
1739 *
1740 * The recommended value is 4 per CU at most. Higher numbers don't
1741 * bring much benefit, but they still occupy chip resources (think
1742 * async compute). I've seen ~2% performance difference between 4 and 32.
1743 */
1744 uint32_t max_threads_per_block = 2048;
1745 device->scratch_waves = MAX2(32 * physical_device->rad_info.num_good_compute_units,
1746 max_threads_per_block / 64);
1747
1748 device->dispatch_initiator = S_00B800_COMPUTE_SHADER_EN(1);
1749
1750 if (device->physical_device->rad_info.chip_class >= CIK) {
1751 /* If the KMD allows it (there is a KMD hw register for it),
1752 * allow launching waves out-of-order.
1753 */
1754 device->dispatch_initiator |= S_00B800_ORDER_MODE(1);
1755 }
1756
1757 radv_device_init_gs_info(device);
1758
1759 device->tess_offchip_block_dw_size =
1760 device->physical_device->rad_info.family == CHIP_HAWAII ? 4096 : 8192;
1761 device->has_distributed_tess =
1762 device->physical_device->rad_info.chip_class >= VI &&
1763 device->physical_device->rad_info.max_se >= 2;
1764
1765 if (getenv("RADV_TRACE_FILE")) {
1766 const char *filename = getenv("RADV_TRACE_FILE");
1767
1768 keep_shader_info = true;
1769
1770 if (!radv_init_trace(device))
1771 goto fail;
1772
1773 fprintf(stderr, "*****************************************************************************\n");
1774 fprintf(stderr, "* WARNING: RADV_TRACE_FILE is costly and should only be used for debugging! *\n");
1775 fprintf(stderr, "*****************************************************************************\n");
1776
1777 fprintf(stderr, "Trace file will be dumped to %s\n", filename);
1778 radv_dump_enabled_options(device, stderr);
1779 }
1780
1781 device->keep_shader_info = keep_shader_info;
1782
1783 result = radv_device_init_meta(device);
1784 if (result != VK_SUCCESS)
1785 goto fail;
1786
1787 radv_device_init_msaa(device);
1788
1789 for (int family = 0; family < RADV_MAX_QUEUE_FAMILIES; ++family) {
1790 device->empty_cs[family] = device->ws->cs_create(device->ws, family);
1791 switch (family) {
1792 case RADV_QUEUE_GENERAL:
1793 radeon_emit(device->empty_cs[family], PKT3(PKT3_CONTEXT_CONTROL, 1, 0));
1794 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_LOAD_ENABLE(1));
1795 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_SHADOW_ENABLE(1));
1796 break;
1797 case RADV_QUEUE_COMPUTE:
1798 radeon_emit(device->empty_cs[family], PKT3(PKT3_NOP, 0, 0));
1799 radeon_emit(device->empty_cs[family], 0);
1800 break;
1801 }
1802 device->ws->cs_finalize(device->empty_cs[family]);
1803 }
1804
1805 if (device->physical_device->rad_info.chip_class >= CIK)
1806 cik_create_gfx_config(device);
1807
1808 VkPipelineCacheCreateInfo ci;
1809 ci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
1810 ci.pNext = NULL;
1811 ci.flags = 0;
1812 ci.pInitialData = NULL;
1813 ci.initialDataSize = 0;
1814 VkPipelineCache pc;
1815 result = radv_CreatePipelineCache(radv_device_to_handle(device),
1816 &ci, NULL, &pc);
1817 if (result != VK_SUCCESS)
1818 goto fail_meta;
1819
1820 device->mem_cache = radv_pipeline_cache_from_handle(pc);
1821
1822 device->force_aniso =
1823 MIN2(16, radv_get_int_debug_option("RADV_TEX_ANISO", -1));
1824 if (device->force_aniso >= 0) {
1825 fprintf(stderr, "radv: Forcing anisotropy filter to %ix\n",
1826 1 << util_logbase2(device->force_aniso));
1827 }
1828
1829 *pDevice = radv_device_to_handle(device);
1830 return VK_SUCCESS;
1831
1832 fail_meta:
1833 radv_device_finish_meta(device);
1834 fail:
1835 radv_bo_list_finish(&device->bo_list);
1836
1837 if (device->trace_bo)
1838 device->ws->buffer_destroy(device->trace_bo);
1839
1840 if (device->gfx_init)
1841 device->ws->buffer_destroy(device->gfx_init);
1842
1843 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
1844 for (unsigned q = 0; q < device->queue_count[i]; q++)
1845 radv_queue_finish(&device->queues[i][q]);
1846 if (device->queue_count[i])
1847 vk_free(&device->alloc, device->queues[i]);
1848 }
1849
1850 vk_free(&device->alloc, device);
1851 return result;
1852 }
1853
1854 void radv_DestroyDevice(
1855 VkDevice _device,
1856 const VkAllocationCallbacks* pAllocator)
1857 {
1858 RADV_FROM_HANDLE(radv_device, device, _device);
1859
1860 if (!device)
1861 return;
1862
1863 if (device->trace_bo)
1864 device->ws->buffer_destroy(device->trace_bo);
1865
1866 if (device->gfx_init)
1867 device->ws->buffer_destroy(device->gfx_init);
1868
1869 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
1870 for (unsigned q = 0; q < device->queue_count[i]; q++)
1871 radv_queue_finish(&device->queues[i][q]);
1872 if (device->queue_count[i])
1873 vk_free(&device->alloc, device->queues[i]);
1874 if (device->empty_cs[i])
1875 device->ws->cs_destroy(device->empty_cs[i]);
1876 }
1877 radv_device_finish_meta(device);
1878
1879 VkPipelineCache pc = radv_pipeline_cache_to_handle(device->mem_cache);
1880 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
1881
1882 radv_destroy_shader_slabs(device);
1883
1884 radv_bo_list_finish(&device->bo_list);
1885 vk_free(&device->alloc, device);
1886 }
1887
1888 VkResult radv_EnumerateInstanceLayerProperties(
1889 uint32_t* pPropertyCount,
1890 VkLayerProperties* pProperties)
1891 {
1892 if (pProperties == NULL) {
1893 *pPropertyCount = 0;
1894 return VK_SUCCESS;
1895 }
1896
1897 /* None supported at this time */
1898 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
1899 }
1900
1901 VkResult radv_EnumerateDeviceLayerProperties(
1902 VkPhysicalDevice physicalDevice,
1903 uint32_t* pPropertyCount,
1904 VkLayerProperties* pProperties)
1905 {
1906 if (pProperties == NULL) {
1907 *pPropertyCount = 0;
1908 return VK_SUCCESS;
1909 }
1910
1911 /* None supported at this time */
1912 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
1913 }
1914
1915 void radv_GetDeviceQueue2(
1916 VkDevice _device,
1917 const VkDeviceQueueInfo2* pQueueInfo,
1918 VkQueue* pQueue)
1919 {
1920 RADV_FROM_HANDLE(radv_device, device, _device);
1921 struct radv_queue *queue;
1922
1923 queue = &device->queues[pQueueInfo->queueFamilyIndex][pQueueInfo->queueIndex];
1924 if (pQueueInfo->flags != queue->flags) {
1925 /* From the Vulkan 1.1.70 spec:
1926 *
1927 * "The queue returned by vkGetDeviceQueue2 must have the same
1928 * flags value from this structure as that used at device
1929 * creation time in a VkDeviceQueueCreateInfo instance. If no
1930 * matching flags were specified at device creation time then
1931 * pQueue will return VK_NULL_HANDLE."
1932 */
1933 *pQueue = VK_NULL_HANDLE;
1934 return;
1935 }
1936
1937 *pQueue = radv_queue_to_handle(queue);
1938 }
1939
1940 void radv_GetDeviceQueue(
1941 VkDevice _device,
1942 uint32_t queueFamilyIndex,
1943 uint32_t queueIndex,
1944 VkQueue* pQueue)
1945 {
1946 const VkDeviceQueueInfo2 info = (VkDeviceQueueInfo2) {
1947 .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
1948 .queueFamilyIndex = queueFamilyIndex,
1949 .queueIndex = queueIndex
1950 };
1951
1952 radv_GetDeviceQueue2(_device, &info, pQueue);
1953 }
1954
1955 static void
1956 fill_geom_tess_rings(struct radv_queue *queue,
1957 uint32_t *map,
1958 bool add_sample_positions,
1959 uint32_t esgs_ring_size,
1960 struct radeon_winsys_bo *esgs_ring_bo,
1961 uint32_t gsvs_ring_size,
1962 struct radeon_winsys_bo *gsvs_ring_bo,
1963 uint32_t tess_factor_ring_size,
1964 uint32_t tess_offchip_ring_offset,
1965 uint32_t tess_offchip_ring_size,
1966 struct radeon_winsys_bo *tess_rings_bo)
1967 {
1968 uint32_t *desc = &map[4];
1969
1970 if (esgs_ring_bo) {
1971 uint64_t esgs_va = radv_buffer_get_va(esgs_ring_bo);
1972
1973 /* stride 0, num records - size, add tid, swizzle, elsize4,
1974 index stride 64 */
1975 desc[0] = esgs_va;
1976 desc[1] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32) |
1977 S_008F04_STRIDE(0) |
1978 S_008F04_SWIZZLE_ENABLE(true);
1979 desc[2] = esgs_ring_size;
1980 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
1981 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
1982 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
1983 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
1984 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
1985 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
1986 S_008F0C_ELEMENT_SIZE(1) |
1987 S_008F0C_INDEX_STRIDE(3) |
1988 S_008F0C_ADD_TID_ENABLE(true);
1989
1990 /* GS entry for ES->GS ring */
1991 /* stride 0, num records - size, elsize0,
1992 index stride 0 */
1993 desc[4] = esgs_va;
1994 desc[5] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32)|
1995 S_008F04_STRIDE(0) |
1996 S_008F04_SWIZZLE_ENABLE(false);
1997 desc[6] = esgs_ring_size;
1998 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
1999 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2000 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2001 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2002 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2003 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2004 S_008F0C_ELEMENT_SIZE(0) |
2005 S_008F0C_INDEX_STRIDE(0) |
2006 S_008F0C_ADD_TID_ENABLE(false);
2007 }
2008
2009 desc += 8;
2010
2011 if (gsvs_ring_bo) {
2012 uint64_t gsvs_va = radv_buffer_get_va(gsvs_ring_bo);
2013
2014 /* VS entry for GS->VS ring */
2015 /* stride 0, num records - size, elsize0,
2016 index stride 0 */
2017 desc[0] = gsvs_va;
2018 desc[1] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32)|
2019 S_008F04_STRIDE(0) |
2020 S_008F04_SWIZZLE_ENABLE(false);
2021 desc[2] = gsvs_ring_size;
2022 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2023 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2024 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2025 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2026 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2027 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2028 S_008F0C_ELEMENT_SIZE(0) |
2029 S_008F0C_INDEX_STRIDE(0) |
2030 S_008F0C_ADD_TID_ENABLE(false);
2031
2032 /* stride gsvs_itemsize, num records 64
2033 elsize 4, index stride 16 */
2034 /* shader will patch stride and desc[2] */
2035 desc[4] = gsvs_va;
2036 desc[5] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32)|
2037 S_008F04_STRIDE(0) |
2038 S_008F04_SWIZZLE_ENABLE(true);
2039 desc[6] = 0;
2040 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2041 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2042 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2043 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2044 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2045 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2046 S_008F0C_ELEMENT_SIZE(1) |
2047 S_008F0C_INDEX_STRIDE(1) |
2048 S_008F0C_ADD_TID_ENABLE(true);
2049 }
2050
2051 desc += 8;
2052
2053 if (tess_rings_bo) {
2054 uint64_t tess_va = radv_buffer_get_va(tess_rings_bo);
2055 uint64_t tess_offchip_va = tess_va + tess_offchip_ring_offset;
2056
2057 desc[0] = tess_va;
2058 desc[1] = S_008F04_BASE_ADDRESS_HI(tess_va >> 32) |
2059 S_008F04_STRIDE(0) |
2060 S_008F04_SWIZZLE_ENABLE(false);
2061 desc[2] = tess_factor_ring_size;
2062 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2063 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2064 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2065 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2066 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2067 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2068 S_008F0C_ELEMENT_SIZE(0) |
2069 S_008F0C_INDEX_STRIDE(0) |
2070 S_008F0C_ADD_TID_ENABLE(false);
2071
2072 desc[4] = tess_offchip_va;
2073 desc[5] = S_008F04_BASE_ADDRESS_HI(tess_offchip_va >> 32) |
2074 S_008F04_STRIDE(0) |
2075 S_008F04_SWIZZLE_ENABLE(false);
2076 desc[6] = tess_offchip_ring_size;
2077 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2078 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2079 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2080 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2081 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2082 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2083 S_008F0C_ELEMENT_SIZE(0) |
2084 S_008F0C_INDEX_STRIDE(0) |
2085 S_008F0C_ADD_TID_ENABLE(false);
2086 }
2087
2088 desc += 8;
2089
2090 if (add_sample_positions) {
2091 /* add sample positions after all rings */
2092 memcpy(desc, queue->device->sample_locations_1x, 8);
2093 desc += 2;
2094 memcpy(desc, queue->device->sample_locations_2x, 16);
2095 desc += 4;
2096 memcpy(desc, queue->device->sample_locations_4x, 32);
2097 desc += 8;
2098 memcpy(desc, queue->device->sample_locations_8x, 64);
2099 }
2100 }
2101
2102 static unsigned
2103 radv_get_hs_offchip_param(struct radv_device *device, uint32_t *max_offchip_buffers_p)
2104 {
2105 bool double_offchip_buffers = device->physical_device->rad_info.chip_class >= CIK &&
2106 device->physical_device->rad_info.family != CHIP_CARRIZO &&
2107 device->physical_device->rad_info.family != CHIP_STONEY;
2108 unsigned max_offchip_buffers_per_se = double_offchip_buffers ? 128 : 64;
2109 unsigned max_offchip_buffers;
2110 unsigned offchip_granularity;
2111 unsigned hs_offchip_param;
2112
2113 /*
2114 * Per RadeonSI:
2115 * This must be one less than the maximum number due to a hw limitation.
2116 * Various hardware bugs in SI, CIK, and GFX9 need this.
2117 *
2118 * Per AMDVLK:
2119 * Vega10 should limit max_offchip_buffers to 508 (4 * 127).
2120 * Gfx7 should limit max_offchip_buffers to 508
2121 * Gfx6 should limit max_offchip_buffers to 126 (2 * 63)
2122 *
2123 * Follow AMDVLK here.
2124 */
2125 if (device->physical_device->rad_info.family == CHIP_VEGA10 ||
2126 device->physical_device->rad_info.chip_class == CIK ||
2127 device->physical_device->rad_info.chip_class == SI)
2128 --max_offchip_buffers_per_se;
2129
2130 max_offchip_buffers = max_offchip_buffers_per_se *
2131 device->physical_device->rad_info.max_se;
2132
2133 /* Hawaii has a bug with offchip buffers > 256 that can be worked
2134 * around by setting 4K granularity.
2135 */
2136 if (device->tess_offchip_block_dw_size == 4096) {
2137 assert(device->physical_device->rad_info.family == CHIP_HAWAII);
2138 offchip_granularity = V_03093C_X_4K_DWORDS;
2139 } else {
2140 assert(device->tess_offchip_block_dw_size == 8192);
2141 offchip_granularity = V_03093C_X_8K_DWORDS;
2142 }
2143
2144 switch (device->physical_device->rad_info.chip_class) {
2145 case SI:
2146 max_offchip_buffers = MIN2(max_offchip_buffers, 126);
2147 break;
2148 case CIK:
2149 case VI:
2150 case GFX9:
2151 default:
2152 max_offchip_buffers = MIN2(max_offchip_buffers, 508);
2153 break;
2154 }
2155
2156 *max_offchip_buffers_p = max_offchip_buffers;
2157 if (device->physical_device->rad_info.chip_class >= CIK) {
2158 if (device->physical_device->rad_info.chip_class >= VI)
2159 --max_offchip_buffers;
2160 hs_offchip_param =
2161 S_03093C_OFFCHIP_BUFFERING(max_offchip_buffers) |
2162 S_03093C_OFFCHIP_GRANULARITY(offchip_granularity);
2163 } else {
2164 hs_offchip_param =
2165 S_0089B0_OFFCHIP_BUFFERING(max_offchip_buffers);
2166 }
2167 return hs_offchip_param;
2168 }
2169
2170 static void
2171 radv_emit_gs_ring_sizes(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2172 struct radeon_winsys_bo *esgs_ring_bo,
2173 uint32_t esgs_ring_size,
2174 struct radeon_winsys_bo *gsvs_ring_bo,
2175 uint32_t gsvs_ring_size)
2176 {
2177 if (!esgs_ring_bo && !gsvs_ring_bo)
2178 return;
2179
2180 if (esgs_ring_bo)
2181 radv_cs_add_buffer(queue->device->ws, cs, esgs_ring_bo);
2182
2183 if (gsvs_ring_bo)
2184 radv_cs_add_buffer(queue->device->ws, cs, gsvs_ring_bo);
2185
2186 if (queue->device->physical_device->rad_info.chip_class >= CIK) {
2187 radeon_set_uconfig_reg_seq(cs, R_030900_VGT_ESGS_RING_SIZE, 2);
2188 radeon_emit(cs, esgs_ring_size >> 8);
2189 radeon_emit(cs, gsvs_ring_size >> 8);
2190 } else {
2191 radeon_set_config_reg_seq(cs, R_0088C8_VGT_ESGS_RING_SIZE, 2);
2192 radeon_emit(cs, esgs_ring_size >> 8);
2193 radeon_emit(cs, gsvs_ring_size >> 8);
2194 }
2195 }
2196
2197 static void
2198 radv_emit_tess_factor_ring(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2199 unsigned hs_offchip_param, unsigned tf_ring_size,
2200 struct radeon_winsys_bo *tess_rings_bo)
2201 {
2202 uint64_t tf_va;
2203
2204 if (!tess_rings_bo)
2205 return;
2206
2207 tf_va = radv_buffer_get_va(tess_rings_bo);
2208
2209 radv_cs_add_buffer(queue->device->ws, cs, tess_rings_bo);
2210
2211 if (queue->device->physical_device->rad_info.chip_class >= CIK) {
2212 radeon_set_uconfig_reg(cs, R_030938_VGT_TF_RING_SIZE,
2213 S_030938_SIZE(tf_ring_size / 4));
2214 radeon_set_uconfig_reg(cs, R_030940_VGT_TF_MEMORY_BASE,
2215 tf_va >> 8);
2216 if (queue->device->physical_device->rad_info.chip_class >= GFX9) {
2217 radeon_set_uconfig_reg(cs, R_030944_VGT_TF_MEMORY_BASE_HI,
2218 S_030944_BASE_HI(tf_va >> 40));
2219 }
2220 radeon_set_uconfig_reg(cs, R_03093C_VGT_HS_OFFCHIP_PARAM,
2221 hs_offchip_param);
2222 } else {
2223 radeon_set_config_reg(cs, R_008988_VGT_TF_RING_SIZE,
2224 S_008988_SIZE(tf_ring_size / 4));
2225 radeon_set_config_reg(cs, R_0089B8_VGT_TF_MEMORY_BASE,
2226 tf_va >> 8);
2227 radeon_set_config_reg(cs, R_0089B0_VGT_HS_OFFCHIP_PARAM,
2228 hs_offchip_param);
2229 }
2230 }
2231
2232 static void
2233 radv_emit_compute_scratch(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2234 struct radeon_winsys_bo *compute_scratch_bo)
2235 {
2236 uint64_t scratch_va;
2237
2238 if (!compute_scratch_bo)
2239 return;
2240
2241 scratch_va = radv_buffer_get_va(compute_scratch_bo);
2242
2243 radv_cs_add_buffer(queue->device->ws, cs, compute_scratch_bo);
2244
2245 radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0, 2);
2246 radeon_emit(cs, scratch_va);
2247 radeon_emit(cs, S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
2248 S_008F04_SWIZZLE_ENABLE(1));
2249 }
2250
2251 static void
2252 radv_emit_global_shader_pointers(struct radv_queue *queue,
2253 struct radeon_cmdbuf *cs,
2254 struct radeon_winsys_bo *descriptor_bo)
2255 {
2256 uint64_t va;
2257
2258 if (!descriptor_bo)
2259 return;
2260
2261 va = radv_buffer_get_va(descriptor_bo);
2262
2263 radv_cs_add_buffer(queue->device->ws, cs, descriptor_bo);
2264
2265 if (queue->device->physical_device->rad_info.chip_class >= GFX9) {
2266 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
2267 R_00B130_SPI_SHADER_USER_DATA_VS_0,
2268 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
2269 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
2270
2271 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
2272 radv_emit_shader_pointer(queue->device, cs, regs[i],
2273 va, true);
2274 }
2275 } else {
2276 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
2277 R_00B130_SPI_SHADER_USER_DATA_VS_0,
2278 R_00B230_SPI_SHADER_USER_DATA_GS_0,
2279 R_00B330_SPI_SHADER_USER_DATA_ES_0,
2280 R_00B430_SPI_SHADER_USER_DATA_HS_0,
2281 R_00B530_SPI_SHADER_USER_DATA_LS_0};
2282
2283 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
2284 radv_emit_shader_pointer(queue->device, cs, regs[i],
2285 va, true);
2286 }
2287 }
2288 }
2289
2290 static void
2291 radv_init_graphics_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
2292 {
2293 struct radv_device *device = queue->device;
2294
2295 if (device->gfx_init) {
2296 uint64_t va = radv_buffer_get_va(device->gfx_init);
2297
2298 radeon_emit(cs, PKT3(PKT3_INDIRECT_BUFFER_CIK, 2, 0));
2299 radeon_emit(cs, va);
2300 radeon_emit(cs, va >> 32);
2301 radeon_emit(cs, device->gfx_init_size_dw & 0xffff);
2302
2303 radv_cs_add_buffer(device->ws, cs, device->gfx_init);
2304 } else {
2305 struct radv_physical_device *physical_device = device->physical_device;
2306 si_emit_graphics(physical_device, cs);
2307 }
2308 }
2309
2310 static void
2311 radv_init_compute_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
2312 {
2313 struct radv_physical_device *physical_device = queue->device->physical_device;
2314 si_emit_compute(physical_device, cs);
2315 }
2316
2317 static VkResult
2318 radv_get_preamble_cs(struct radv_queue *queue,
2319 uint32_t scratch_size,
2320 uint32_t compute_scratch_size,
2321 uint32_t esgs_ring_size,
2322 uint32_t gsvs_ring_size,
2323 bool needs_tess_rings,
2324 bool needs_sample_positions,
2325 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
2326 struct radeon_cmdbuf **initial_preamble_cs,
2327 struct radeon_cmdbuf **continue_preamble_cs)
2328 {
2329 struct radeon_winsys_bo *scratch_bo = NULL;
2330 struct radeon_winsys_bo *descriptor_bo = NULL;
2331 struct radeon_winsys_bo *compute_scratch_bo = NULL;
2332 struct radeon_winsys_bo *esgs_ring_bo = NULL;
2333 struct radeon_winsys_bo *gsvs_ring_bo = NULL;
2334 struct radeon_winsys_bo *tess_rings_bo = NULL;
2335 struct radeon_cmdbuf *dest_cs[3] = {0};
2336 bool add_tess_rings = false, add_sample_positions = false;
2337 unsigned tess_factor_ring_size = 0, tess_offchip_ring_size = 0;
2338 unsigned max_offchip_buffers;
2339 unsigned hs_offchip_param = 0;
2340 unsigned tess_offchip_ring_offset;
2341 uint32_t ring_bo_flags = RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING;
2342 if (!queue->has_tess_rings) {
2343 if (needs_tess_rings)
2344 add_tess_rings = true;
2345 }
2346 if (!queue->has_sample_positions) {
2347 if (needs_sample_positions)
2348 add_sample_positions = true;
2349 }
2350 tess_factor_ring_size = 32768 * queue->device->physical_device->rad_info.max_se;
2351 hs_offchip_param = radv_get_hs_offchip_param(queue->device,
2352 &max_offchip_buffers);
2353 tess_offchip_ring_offset = align(tess_factor_ring_size, 64 * 1024);
2354 tess_offchip_ring_size = max_offchip_buffers *
2355 queue->device->tess_offchip_block_dw_size * 4;
2356
2357 if (scratch_size <= queue->scratch_size &&
2358 compute_scratch_size <= queue->compute_scratch_size &&
2359 esgs_ring_size <= queue->esgs_ring_size &&
2360 gsvs_ring_size <= queue->gsvs_ring_size &&
2361 !add_tess_rings && !add_sample_positions &&
2362 queue->initial_preamble_cs) {
2363 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
2364 *initial_preamble_cs = queue->initial_preamble_cs;
2365 *continue_preamble_cs = queue->continue_preamble_cs;
2366 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
2367 *continue_preamble_cs = NULL;
2368 return VK_SUCCESS;
2369 }
2370
2371 if (scratch_size > queue->scratch_size) {
2372 scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
2373 scratch_size,
2374 4096,
2375 RADEON_DOMAIN_VRAM,
2376 ring_bo_flags,
2377 RADV_BO_PRIORITY_SCRATCH);
2378 if (!scratch_bo)
2379 goto fail;
2380 } else
2381 scratch_bo = queue->scratch_bo;
2382
2383 if (compute_scratch_size > queue->compute_scratch_size) {
2384 compute_scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
2385 compute_scratch_size,
2386 4096,
2387 RADEON_DOMAIN_VRAM,
2388 ring_bo_flags,
2389 RADV_BO_PRIORITY_SCRATCH);
2390 if (!compute_scratch_bo)
2391 goto fail;
2392
2393 } else
2394 compute_scratch_bo = queue->compute_scratch_bo;
2395
2396 if (esgs_ring_size > queue->esgs_ring_size) {
2397 esgs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
2398 esgs_ring_size,
2399 4096,
2400 RADEON_DOMAIN_VRAM,
2401 ring_bo_flags,
2402 RADV_BO_PRIORITY_SCRATCH);
2403 if (!esgs_ring_bo)
2404 goto fail;
2405 } else {
2406 esgs_ring_bo = queue->esgs_ring_bo;
2407 esgs_ring_size = queue->esgs_ring_size;
2408 }
2409
2410 if (gsvs_ring_size > queue->gsvs_ring_size) {
2411 gsvs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
2412 gsvs_ring_size,
2413 4096,
2414 RADEON_DOMAIN_VRAM,
2415 ring_bo_flags,
2416 RADV_BO_PRIORITY_SCRATCH);
2417 if (!gsvs_ring_bo)
2418 goto fail;
2419 } else {
2420 gsvs_ring_bo = queue->gsvs_ring_bo;
2421 gsvs_ring_size = queue->gsvs_ring_size;
2422 }
2423
2424 if (add_tess_rings) {
2425 tess_rings_bo = queue->device->ws->buffer_create(queue->device->ws,
2426 tess_offchip_ring_offset + tess_offchip_ring_size,
2427 256,
2428 RADEON_DOMAIN_VRAM,
2429 ring_bo_flags,
2430 RADV_BO_PRIORITY_SCRATCH);
2431 if (!tess_rings_bo)
2432 goto fail;
2433 } else {
2434 tess_rings_bo = queue->tess_rings_bo;
2435 }
2436
2437 if (scratch_bo != queue->scratch_bo ||
2438 esgs_ring_bo != queue->esgs_ring_bo ||
2439 gsvs_ring_bo != queue->gsvs_ring_bo ||
2440 tess_rings_bo != queue->tess_rings_bo ||
2441 add_sample_positions) {
2442 uint32_t size = 0;
2443 if (gsvs_ring_bo || esgs_ring_bo ||
2444 tess_rings_bo || add_sample_positions) {
2445 size = 112; /* 2 dword + 2 padding + 4 dword * 6 */
2446 if (add_sample_positions)
2447 size += 128; /* 64+32+16+8 = 120 bytes */
2448 }
2449 else if (scratch_bo)
2450 size = 8; /* 2 dword */
2451
2452 descriptor_bo = queue->device->ws->buffer_create(queue->device->ws,
2453 size,
2454 4096,
2455 RADEON_DOMAIN_VRAM,
2456 RADEON_FLAG_CPU_ACCESS |
2457 RADEON_FLAG_NO_INTERPROCESS_SHARING |
2458 RADEON_FLAG_READ_ONLY,
2459 RADV_BO_PRIORITY_DESCRIPTOR);
2460 if (!descriptor_bo)
2461 goto fail;
2462 } else
2463 descriptor_bo = queue->descriptor_bo;
2464
2465 if (descriptor_bo != queue->descriptor_bo) {
2466 uint32_t *map = (uint32_t*)queue->device->ws->buffer_map(descriptor_bo);
2467
2468 if (scratch_bo) {
2469 uint64_t scratch_va = radv_buffer_get_va(scratch_bo);
2470 uint32_t rsrc1 = S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
2471 S_008F04_SWIZZLE_ENABLE(1);
2472 map[0] = scratch_va;
2473 map[1] = rsrc1;
2474 }
2475
2476 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo || add_sample_positions)
2477 fill_geom_tess_rings(queue, map, add_sample_positions,
2478 esgs_ring_size, esgs_ring_bo,
2479 gsvs_ring_size, gsvs_ring_bo,
2480 tess_factor_ring_size,
2481 tess_offchip_ring_offset,
2482 tess_offchip_ring_size,
2483 tess_rings_bo);
2484
2485 queue->device->ws->buffer_unmap(descriptor_bo);
2486 }
2487
2488 for(int i = 0; i < 3; ++i) {
2489 struct radeon_cmdbuf *cs = NULL;
2490 cs = queue->device->ws->cs_create(queue->device->ws,
2491 queue->queue_family_index ? RING_COMPUTE : RING_GFX);
2492 if (!cs)
2493 goto fail;
2494
2495 dest_cs[i] = cs;
2496
2497 if (scratch_bo)
2498 radv_cs_add_buffer(queue->device->ws, cs, scratch_bo);
2499
2500 /* Emit initial configuration. */
2501 switch (queue->queue_family_index) {
2502 case RADV_QUEUE_GENERAL:
2503 radv_init_graphics_state(cs, queue);
2504 break;
2505 case RADV_QUEUE_COMPUTE:
2506 radv_init_compute_state(cs, queue);
2507 break;
2508 case RADV_QUEUE_TRANSFER:
2509 break;
2510 }
2511
2512 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo) {
2513 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
2514 radeon_emit(cs, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
2515 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
2516 radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
2517 }
2518
2519 radv_emit_gs_ring_sizes(queue, cs, esgs_ring_bo, esgs_ring_size,
2520 gsvs_ring_bo, gsvs_ring_size);
2521 radv_emit_tess_factor_ring(queue, cs, hs_offchip_param,
2522 tess_factor_ring_size, tess_rings_bo);
2523 radv_emit_global_shader_pointers(queue, cs, descriptor_bo);
2524 radv_emit_compute_scratch(queue, cs, compute_scratch_bo);
2525
2526 if (i == 0) {
2527 si_cs_emit_cache_flush(cs,
2528 queue->device->physical_device->rad_info.chip_class,
2529 NULL, 0,
2530 queue->queue_family_index == RING_COMPUTE &&
2531 queue->device->physical_device->rad_info.chip_class >= CIK,
2532 (queue->queue_family_index == RADV_QUEUE_COMPUTE ? RADV_CMD_FLAG_CS_PARTIAL_FLUSH : (RADV_CMD_FLAG_CS_PARTIAL_FLUSH | RADV_CMD_FLAG_PS_PARTIAL_FLUSH)) |
2533 RADV_CMD_FLAG_INV_ICACHE |
2534 RADV_CMD_FLAG_INV_SMEM_L1 |
2535 RADV_CMD_FLAG_INV_VMEM_L1 |
2536 RADV_CMD_FLAG_INV_GLOBAL_L2 |
2537 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
2538 } else if (i == 1) {
2539 si_cs_emit_cache_flush(cs,
2540 queue->device->physical_device->rad_info.chip_class,
2541 NULL, 0,
2542 queue->queue_family_index == RING_COMPUTE &&
2543 queue->device->physical_device->rad_info.chip_class >= CIK,
2544 RADV_CMD_FLAG_INV_ICACHE |
2545 RADV_CMD_FLAG_INV_SMEM_L1 |
2546 RADV_CMD_FLAG_INV_VMEM_L1 |
2547 RADV_CMD_FLAG_INV_GLOBAL_L2 |
2548 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
2549 }
2550
2551 if (!queue->device->ws->cs_finalize(cs))
2552 goto fail;
2553 }
2554
2555 if (queue->initial_full_flush_preamble_cs)
2556 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
2557
2558 if (queue->initial_preamble_cs)
2559 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
2560
2561 if (queue->continue_preamble_cs)
2562 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
2563
2564 queue->initial_full_flush_preamble_cs = dest_cs[0];
2565 queue->initial_preamble_cs = dest_cs[1];
2566 queue->continue_preamble_cs = dest_cs[2];
2567
2568 if (scratch_bo != queue->scratch_bo) {
2569 if (queue->scratch_bo)
2570 queue->device->ws->buffer_destroy(queue->scratch_bo);
2571 queue->scratch_bo = scratch_bo;
2572 queue->scratch_size = scratch_size;
2573 }
2574
2575 if (compute_scratch_bo != queue->compute_scratch_bo) {
2576 if (queue->compute_scratch_bo)
2577 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
2578 queue->compute_scratch_bo = compute_scratch_bo;
2579 queue->compute_scratch_size = compute_scratch_size;
2580 }
2581
2582 if (esgs_ring_bo != queue->esgs_ring_bo) {
2583 if (queue->esgs_ring_bo)
2584 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
2585 queue->esgs_ring_bo = esgs_ring_bo;
2586 queue->esgs_ring_size = esgs_ring_size;
2587 }
2588
2589 if (gsvs_ring_bo != queue->gsvs_ring_bo) {
2590 if (queue->gsvs_ring_bo)
2591 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
2592 queue->gsvs_ring_bo = gsvs_ring_bo;
2593 queue->gsvs_ring_size = gsvs_ring_size;
2594 }
2595
2596 if (tess_rings_bo != queue->tess_rings_bo) {
2597 queue->tess_rings_bo = tess_rings_bo;
2598 queue->has_tess_rings = true;
2599 }
2600
2601 if (descriptor_bo != queue->descriptor_bo) {
2602 if (queue->descriptor_bo)
2603 queue->device->ws->buffer_destroy(queue->descriptor_bo);
2604
2605 queue->descriptor_bo = descriptor_bo;
2606 }
2607
2608 if (add_sample_positions)
2609 queue->has_sample_positions = true;
2610
2611 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
2612 *initial_preamble_cs = queue->initial_preamble_cs;
2613 *continue_preamble_cs = queue->continue_preamble_cs;
2614 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
2615 *continue_preamble_cs = NULL;
2616 return VK_SUCCESS;
2617 fail:
2618 for (int i = 0; i < ARRAY_SIZE(dest_cs); ++i)
2619 if (dest_cs[i])
2620 queue->device->ws->cs_destroy(dest_cs[i]);
2621 if (descriptor_bo && descriptor_bo != queue->descriptor_bo)
2622 queue->device->ws->buffer_destroy(descriptor_bo);
2623 if (scratch_bo && scratch_bo != queue->scratch_bo)
2624 queue->device->ws->buffer_destroy(scratch_bo);
2625 if (compute_scratch_bo && compute_scratch_bo != queue->compute_scratch_bo)
2626 queue->device->ws->buffer_destroy(compute_scratch_bo);
2627 if (esgs_ring_bo && esgs_ring_bo != queue->esgs_ring_bo)
2628 queue->device->ws->buffer_destroy(esgs_ring_bo);
2629 if (gsvs_ring_bo && gsvs_ring_bo != queue->gsvs_ring_bo)
2630 queue->device->ws->buffer_destroy(gsvs_ring_bo);
2631 if (tess_rings_bo && tess_rings_bo != queue->tess_rings_bo)
2632 queue->device->ws->buffer_destroy(tess_rings_bo);
2633 return vk_error(queue->device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
2634 }
2635
2636 static VkResult radv_alloc_sem_counts(struct radv_instance *instance,
2637 struct radv_winsys_sem_counts *counts,
2638 int num_sems,
2639 const VkSemaphore *sems,
2640 VkFence _fence,
2641 bool reset_temp)
2642 {
2643 int syncobj_idx = 0, sem_idx = 0;
2644
2645 if (num_sems == 0 && _fence == VK_NULL_HANDLE)
2646 return VK_SUCCESS;
2647
2648 for (uint32_t i = 0; i < num_sems; i++) {
2649 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
2650
2651 if (sem->temp_syncobj || sem->syncobj)
2652 counts->syncobj_count++;
2653 else
2654 counts->sem_count++;
2655 }
2656
2657 if (_fence != VK_NULL_HANDLE) {
2658 RADV_FROM_HANDLE(radv_fence, fence, _fence);
2659 if (fence->temp_syncobj || fence->syncobj)
2660 counts->syncobj_count++;
2661 }
2662
2663 if (counts->syncobj_count) {
2664 counts->syncobj = (uint32_t *)malloc(sizeof(uint32_t) * counts->syncobj_count);
2665 if (!counts->syncobj)
2666 return vk_error(instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2667 }
2668
2669 if (counts->sem_count) {
2670 counts->sem = (struct radeon_winsys_sem **)malloc(sizeof(struct radeon_winsys_sem *) * counts->sem_count);
2671 if (!counts->sem) {
2672 free(counts->syncobj);
2673 return vk_error(instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2674 }
2675 }
2676
2677 for (uint32_t i = 0; i < num_sems; i++) {
2678 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
2679
2680 if (sem->temp_syncobj) {
2681 counts->syncobj[syncobj_idx++] = sem->temp_syncobj;
2682 }
2683 else if (sem->syncobj)
2684 counts->syncobj[syncobj_idx++] = sem->syncobj;
2685 else {
2686 assert(sem->sem);
2687 counts->sem[sem_idx++] = sem->sem;
2688 }
2689 }
2690
2691 if (_fence != VK_NULL_HANDLE) {
2692 RADV_FROM_HANDLE(radv_fence, fence, _fence);
2693 if (fence->temp_syncobj)
2694 counts->syncobj[syncobj_idx++] = fence->temp_syncobj;
2695 else if (fence->syncobj)
2696 counts->syncobj[syncobj_idx++] = fence->syncobj;
2697 }
2698
2699 return VK_SUCCESS;
2700 }
2701
2702 static void
2703 radv_free_sem_info(struct radv_winsys_sem_info *sem_info)
2704 {
2705 free(sem_info->wait.syncobj);
2706 free(sem_info->wait.sem);
2707 free(sem_info->signal.syncobj);
2708 free(sem_info->signal.sem);
2709 }
2710
2711
2712 static void radv_free_temp_syncobjs(struct radv_device *device,
2713 int num_sems,
2714 const VkSemaphore *sems)
2715 {
2716 for (uint32_t i = 0; i < num_sems; i++) {
2717 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
2718
2719 if (sem->temp_syncobj) {
2720 device->ws->destroy_syncobj(device->ws, sem->temp_syncobj);
2721 sem->temp_syncobj = 0;
2722 }
2723 }
2724 }
2725
2726 static VkResult
2727 radv_alloc_sem_info(struct radv_instance *instance,
2728 struct radv_winsys_sem_info *sem_info,
2729 int num_wait_sems,
2730 const VkSemaphore *wait_sems,
2731 int num_signal_sems,
2732 const VkSemaphore *signal_sems,
2733 VkFence fence)
2734 {
2735 VkResult ret;
2736 memset(sem_info, 0, sizeof(*sem_info));
2737
2738 ret = radv_alloc_sem_counts(instance, &sem_info->wait, num_wait_sems, wait_sems, VK_NULL_HANDLE, true);
2739 if (ret)
2740 return ret;
2741 ret = radv_alloc_sem_counts(instance, &sem_info->signal, num_signal_sems, signal_sems, fence, false);
2742 if (ret)
2743 radv_free_sem_info(sem_info);
2744
2745 /* caller can override these */
2746 sem_info->cs_emit_wait = true;
2747 sem_info->cs_emit_signal = true;
2748 return ret;
2749 }
2750
2751 /* Signals fence as soon as all the work currently put on queue is done. */
2752 static VkResult radv_signal_fence(struct radv_queue *queue,
2753 struct radv_fence *fence)
2754 {
2755 int ret;
2756 VkResult result;
2757 struct radv_winsys_sem_info sem_info;
2758
2759 result = radv_alloc_sem_info(queue->device->instance, &sem_info, 0, NULL, 0, NULL,
2760 radv_fence_to_handle(fence));
2761 if (result != VK_SUCCESS)
2762 return result;
2763
2764 ret = queue->device->ws->cs_submit(queue->hw_ctx, queue->queue_idx,
2765 &queue->device->empty_cs[queue->queue_family_index],
2766 1, NULL, NULL, &sem_info, NULL,
2767 false, fence->fence);
2768 radv_free_sem_info(&sem_info);
2769
2770 if (ret)
2771 return vk_error(queue->device->instance, VK_ERROR_DEVICE_LOST);
2772
2773 return VK_SUCCESS;
2774 }
2775
2776 VkResult radv_QueueSubmit(
2777 VkQueue _queue,
2778 uint32_t submitCount,
2779 const VkSubmitInfo* pSubmits,
2780 VkFence _fence)
2781 {
2782 RADV_FROM_HANDLE(radv_queue, queue, _queue);
2783 RADV_FROM_HANDLE(radv_fence, fence, _fence);
2784 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
2785 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
2786 int ret;
2787 uint32_t max_cs_submission = queue->device->trace_bo ? 1 : UINT32_MAX;
2788 uint32_t scratch_size = 0;
2789 uint32_t compute_scratch_size = 0;
2790 uint32_t esgs_ring_size = 0, gsvs_ring_size = 0;
2791 struct radeon_cmdbuf *initial_preamble_cs = NULL, *initial_flush_preamble_cs = NULL, *continue_preamble_cs = NULL;
2792 VkResult result;
2793 bool fence_emitted = false;
2794 bool tess_rings_needed = false;
2795 bool sample_positions_needed = false;
2796
2797 /* Do this first so failing to allocate scratch buffers can't result in
2798 * partially executed submissions. */
2799 for (uint32_t i = 0; i < submitCount; i++) {
2800 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
2801 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
2802 pSubmits[i].pCommandBuffers[j]);
2803
2804 scratch_size = MAX2(scratch_size, cmd_buffer->scratch_size_needed);
2805 compute_scratch_size = MAX2(compute_scratch_size,
2806 cmd_buffer->compute_scratch_size_needed);
2807 esgs_ring_size = MAX2(esgs_ring_size, cmd_buffer->esgs_ring_size_needed);
2808 gsvs_ring_size = MAX2(gsvs_ring_size, cmd_buffer->gsvs_ring_size_needed);
2809 tess_rings_needed |= cmd_buffer->tess_rings_needed;
2810 sample_positions_needed |= cmd_buffer->sample_positions_needed;
2811 }
2812 }
2813
2814 result = radv_get_preamble_cs(queue, scratch_size, compute_scratch_size,
2815 esgs_ring_size, gsvs_ring_size, tess_rings_needed,
2816 sample_positions_needed, &initial_flush_preamble_cs,
2817 &initial_preamble_cs, &continue_preamble_cs);
2818 if (result != VK_SUCCESS)
2819 return result;
2820
2821 for (uint32_t i = 0; i < submitCount; i++) {
2822 struct radeon_cmdbuf **cs_array;
2823 bool do_flush = !i || pSubmits[i].pWaitDstStageMask;
2824 bool can_patch = true;
2825 uint32_t advance;
2826 struct radv_winsys_sem_info sem_info;
2827
2828 result = radv_alloc_sem_info(queue->device->instance,
2829 &sem_info,
2830 pSubmits[i].waitSemaphoreCount,
2831 pSubmits[i].pWaitSemaphores,
2832 pSubmits[i].signalSemaphoreCount,
2833 pSubmits[i].pSignalSemaphores,
2834 _fence);
2835 if (result != VK_SUCCESS)
2836 return result;
2837
2838 if (!pSubmits[i].commandBufferCount) {
2839 if (pSubmits[i].waitSemaphoreCount || pSubmits[i].signalSemaphoreCount) {
2840 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx,
2841 &queue->device->empty_cs[queue->queue_family_index],
2842 1, NULL, NULL,
2843 &sem_info, NULL,
2844 false, base_fence);
2845 if (ret) {
2846 radv_loge("failed to submit CS %d\n", i);
2847 abort();
2848 }
2849 fence_emitted = true;
2850 }
2851 radv_free_sem_info(&sem_info);
2852 continue;
2853 }
2854
2855 cs_array = malloc(sizeof(struct radeon_cmdbuf *) *
2856 (pSubmits[i].commandBufferCount));
2857
2858 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
2859 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
2860 pSubmits[i].pCommandBuffers[j]);
2861 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
2862
2863 cs_array[j] = cmd_buffer->cs;
2864 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
2865 can_patch = false;
2866
2867 cmd_buffer->status = RADV_CMD_BUFFER_STATUS_PENDING;
2868 }
2869
2870 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j += advance) {
2871 struct radeon_cmdbuf *initial_preamble = (do_flush && !j) ? initial_flush_preamble_cs : initial_preamble_cs;
2872 const struct radv_winsys_bo_list *bo_list = NULL;
2873
2874 advance = MIN2(max_cs_submission,
2875 pSubmits[i].commandBufferCount - j);
2876
2877 if (queue->device->trace_bo)
2878 *queue->device->trace_id_ptr = 0;
2879
2880 sem_info.cs_emit_wait = j == 0;
2881 sem_info.cs_emit_signal = j + advance == pSubmits[i].commandBufferCount;
2882
2883 if (unlikely(queue->device->use_global_bo_list)) {
2884 pthread_mutex_lock(&queue->device->bo_list.mutex);
2885 bo_list = &queue->device->bo_list.list;
2886 }
2887
2888 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, cs_array + j,
2889 advance, initial_preamble, continue_preamble_cs,
2890 &sem_info, bo_list,
2891 can_patch, base_fence);
2892
2893 if (unlikely(queue->device->use_global_bo_list))
2894 pthread_mutex_unlock(&queue->device->bo_list.mutex);
2895
2896 if (ret) {
2897 radv_loge("failed to submit CS %d\n", i);
2898 abort();
2899 }
2900 fence_emitted = true;
2901 if (queue->device->trace_bo) {
2902 radv_check_gpu_hangs(queue, cs_array[j]);
2903 }
2904 }
2905
2906 radv_free_temp_syncobjs(queue->device,
2907 pSubmits[i].waitSemaphoreCount,
2908 pSubmits[i].pWaitSemaphores);
2909 radv_free_sem_info(&sem_info);
2910 free(cs_array);
2911 }
2912
2913 if (fence) {
2914 if (!fence_emitted) {
2915 result = radv_signal_fence(queue, fence);
2916 if (result != VK_SUCCESS)
2917 return result;
2918 }
2919 fence->submitted = true;
2920 }
2921
2922 return VK_SUCCESS;
2923 }
2924
2925 VkResult radv_QueueWaitIdle(
2926 VkQueue _queue)
2927 {
2928 RADV_FROM_HANDLE(radv_queue, queue, _queue);
2929
2930 queue->device->ws->ctx_wait_idle(queue->hw_ctx,
2931 radv_queue_family_to_ring(queue->queue_family_index),
2932 queue->queue_idx);
2933 return VK_SUCCESS;
2934 }
2935
2936 VkResult radv_DeviceWaitIdle(
2937 VkDevice _device)
2938 {
2939 RADV_FROM_HANDLE(radv_device, device, _device);
2940
2941 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
2942 for (unsigned q = 0; q < device->queue_count[i]; q++) {
2943 radv_QueueWaitIdle(radv_queue_to_handle(&device->queues[i][q]));
2944 }
2945 }
2946 return VK_SUCCESS;
2947 }
2948
2949 VkResult radv_EnumerateInstanceExtensionProperties(
2950 const char* pLayerName,
2951 uint32_t* pPropertyCount,
2952 VkExtensionProperties* pProperties)
2953 {
2954 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
2955
2956 for (int i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; i++) {
2957 if (radv_supported_instance_extensions.extensions[i]) {
2958 vk_outarray_append(&out, prop) {
2959 *prop = radv_instance_extensions[i];
2960 }
2961 }
2962 }
2963
2964 return vk_outarray_status(&out);
2965 }
2966
2967 VkResult radv_EnumerateDeviceExtensionProperties(
2968 VkPhysicalDevice physicalDevice,
2969 const char* pLayerName,
2970 uint32_t* pPropertyCount,
2971 VkExtensionProperties* pProperties)
2972 {
2973 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
2974 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
2975
2976 for (int i = 0; i < RADV_DEVICE_EXTENSION_COUNT; i++) {
2977 if (device->supported_extensions.extensions[i]) {
2978 vk_outarray_append(&out, prop) {
2979 *prop = radv_device_extensions[i];
2980 }
2981 }
2982 }
2983
2984 return vk_outarray_status(&out);
2985 }
2986
2987 PFN_vkVoidFunction radv_GetInstanceProcAddr(
2988 VkInstance _instance,
2989 const char* pName)
2990 {
2991 RADV_FROM_HANDLE(radv_instance, instance, _instance);
2992
2993 return radv_lookup_entrypoint_checked(pName,
2994 instance ? instance->apiVersion : 0,
2995 instance ? &instance->enabled_extensions : NULL,
2996 NULL);
2997 }
2998
2999 /* The loader wants us to expose a second GetInstanceProcAddr function
3000 * to work around certain LD_PRELOAD issues seen in apps.
3001 */
3002 PUBLIC
3003 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
3004 VkInstance instance,
3005 const char* pName);
3006
3007 PUBLIC
3008 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
3009 VkInstance instance,
3010 const char* pName)
3011 {
3012 return radv_GetInstanceProcAddr(instance, pName);
3013 }
3014
3015 PFN_vkVoidFunction radv_GetDeviceProcAddr(
3016 VkDevice _device,
3017 const char* pName)
3018 {
3019 RADV_FROM_HANDLE(radv_device, device, _device);
3020
3021 return radv_lookup_entrypoint_checked(pName,
3022 device->instance->apiVersion,
3023 &device->instance->enabled_extensions,
3024 &device->enabled_extensions);
3025 }
3026
3027 bool radv_get_memory_fd(struct radv_device *device,
3028 struct radv_device_memory *memory,
3029 int *pFD)
3030 {
3031 struct radeon_bo_metadata metadata;
3032
3033 if (memory->image) {
3034 radv_init_metadata(device, memory->image, &metadata);
3035 device->ws->buffer_set_metadata(memory->bo, &metadata);
3036 }
3037
3038 return device->ws->buffer_get_fd(device->ws, memory->bo,
3039 pFD);
3040 }
3041
3042 static VkResult radv_alloc_memory(struct radv_device *device,
3043 const VkMemoryAllocateInfo* pAllocateInfo,
3044 const VkAllocationCallbacks* pAllocator,
3045 VkDeviceMemory* pMem)
3046 {
3047 struct radv_device_memory *mem;
3048 VkResult result;
3049 enum radeon_bo_domain domain;
3050 uint32_t flags = 0;
3051 enum radv_mem_type mem_type_index = device->physical_device->mem_type_indices[pAllocateInfo->memoryTypeIndex];
3052
3053 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
3054
3055 if (pAllocateInfo->allocationSize == 0) {
3056 /* Apparently, this is allowed */
3057 *pMem = VK_NULL_HANDLE;
3058 return VK_SUCCESS;
3059 }
3060
3061 const VkImportMemoryFdInfoKHR *import_info =
3062 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
3063 const VkMemoryDedicatedAllocateInfo *dedicate_info =
3064 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);
3065 const VkExportMemoryAllocateInfo *export_info =
3066 vk_find_struct_const(pAllocateInfo->pNext, EXPORT_MEMORY_ALLOCATE_INFO);
3067 const VkImportMemoryHostPointerInfoEXT *host_ptr_info =
3068 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_HOST_POINTER_INFO_EXT);
3069
3070 const struct wsi_memory_allocate_info *wsi_info =
3071 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
3072
3073 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
3074 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3075 if (mem == NULL)
3076 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3077
3078 if (wsi_info && wsi_info->implicit_sync)
3079 flags |= RADEON_FLAG_IMPLICIT_SYNC;
3080
3081 if (dedicate_info) {
3082 mem->image = radv_image_from_handle(dedicate_info->image);
3083 mem->buffer = radv_buffer_from_handle(dedicate_info->buffer);
3084 } else {
3085 mem->image = NULL;
3086 mem->buffer = NULL;
3087 }
3088
3089 mem->user_ptr = NULL;
3090
3091 if (import_info) {
3092 assert(import_info->handleType ==
3093 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
3094 import_info->handleType ==
3095 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
3096 mem->bo = device->ws->buffer_from_fd(device->ws, import_info->fd,
3097 RADV_BO_PRIORITY_DEFAULT, NULL, NULL);
3098 if (!mem->bo) {
3099 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
3100 goto fail;
3101 } else {
3102 close(import_info->fd);
3103 }
3104 } else if (host_ptr_info) {
3105 assert(host_ptr_info->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
3106 assert(mem_type_index == RADV_MEM_TYPE_GTT_CACHED);
3107 mem->bo = device->ws->buffer_from_ptr(device->ws, host_ptr_info->pHostPointer,
3108 pAllocateInfo->allocationSize,
3109 RADV_BO_PRIORITY_DEFAULT);
3110 if (!mem->bo) {
3111 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
3112 goto fail;
3113 } else {
3114 mem->user_ptr = host_ptr_info->pHostPointer;
3115 }
3116 } else {
3117 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
3118 if (mem_type_index == RADV_MEM_TYPE_GTT_WRITE_COMBINE ||
3119 mem_type_index == RADV_MEM_TYPE_GTT_CACHED)
3120 domain = RADEON_DOMAIN_GTT;
3121 else
3122 domain = RADEON_DOMAIN_VRAM;
3123
3124 if (mem_type_index == RADV_MEM_TYPE_VRAM)
3125 flags |= RADEON_FLAG_NO_CPU_ACCESS;
3126 else
3127 flags |= RADEON_FLAG_CPU_ACCESS;
3128
3129 if (mem_type_index == RADV_MEM_TYPE_GTT_WRITE_COMBINE)
3130 flags |= RADEON_FLAG_GTT_WC;
3131
3132 if (!dedicate_info && !import_info && (!export_info || !export_info->handleTypes))
3133 flags |= RADEON_FLAG_NO_INTERPROCESS_SHARING;
3134
3135 mem->bo = device->ws->buffer_create(device->ws, alloc_size, device->physical_device->rad_info.max_alignment,
3136 domain, flags, RADV_BO_PRIORITY_DEFAULT);
3137
3138 if (!mem->bo) {
3139 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
3140 goto fail;
3141 }
3142 mem->type_index = mem_type_index;
3143 }
3144
3145 result = radv_bo_list_add(device, mem->bo);
3146 if (result != VK_SUCCESS)
3147 goto fail_bo;
3148
3149 *pMem = radv_device_memory_to_handle(mem);
3150
3151 return VK_SUCCESS;
3152
3153 fail_bo:
3154 device->ws->buffer_destroy(mem->bo);
3155 fail:
3156 vk_free2(&device->alloc, pAllocator, mem);
3157
3158 return result;
3159 }
3160
3161 VkResult radv_AllocateMemory(
3162 VkDevice _device,
3163 const VkMemoryAllocateInfo* pAllocateInfo,
3164 const VkAllocationCallbacks* pAllocator,
3165 VkDeviceMemory* pMem)
3166 {
3167 RADV_FROM_HANDLE(radv_device, device, _device);
3168 return radv_alloc_memory(device, pAllocateInfo, pAllocator, pMem);
3169 }
3170
3171 void radv_FreeMemory(
3172 VkDevice _device,
3173 VkDeviceMemory _mem,
3174 const VkAllocationCallbacks* pAllocator)
3175 {
3176 RADV_FROM_HANDLE(radv_device, device, _device);
3177 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
3178
3179 if (mem == NULL)
3180 return;
3181
3182 radv_bo_list_remove(device, mem->bo);
3183 device->ws->buffer_destroy(mem->bo);
3184 mem->bo = NULL;
3185
3186 vk_free2(&device->alloc, pAllocator, mem);
3187 }
3188
3189 VkResult radv_MapMemory(
3190 VkDevice _device,
3191 VkDeviceMemory _memory,
3192 VkDeviceSize offset,
3193 VkDeviceSize size,
3194 VkMemoryMapFlags flags,
3195 void** ppData)
3196 {
3197 RADV_FROM_HANDLE(radv_device, device, _device);
3198 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
3199
3200 if (mem == NULL) {
3201 *ppData = NULL;
3202 return VK_SUCCESS;
3203 }
3204
3205 if (mem->user_ptr)
3206 *ppData = mem->user_ptr;
3207 else
3208 *ppData = device->ws->buffer_map(mem->bo);
3209
3210 if (*ppData) {
3211 *ppData += offset;
3212 return VK_SUCCESS;
3213 }
3214
3215 return vk_error(device->instance, VK_ERROR_MEMORY_MAP_FAILED);
3216 }
3217
3218 void radv_UnmapMemory(
3219 VkDevice _device,
3220 VkDeviceMemory _memory)
3221 {
3222 RADV_FROM_HANDLE(radv_device, device, _device);
3223 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
3224
3225 if (mem == NULL)
3226 return;
3227
3228 if (mem->user_ptr == NULL)
3229 device->ws->buffer_unmap(mem->bo);
3230 }
3231
3232 VkResult radv_FlushMappedMemoryRanges(
3233 VkDevice _device,
3234 uint32_t memoryRangeCount,
3235 const VkMappedMemoryRange* pMemoryRanges)
3236 {
3237 return VK_SUCCESS;
3238 }
3239
3240 VkResult radv_InvalidateMappedMemoryRanges(
3241 VkDevice _device,
3242 uint32_t memoryRangeCount,
3243 const VkMappedMemoryRange* pMemoryRanges)
3244 {
3245 return VK_SUCCESS;
3246 }
3247
3248 void radv_GetBufferMemoryRequirements(
3249 VkDevice _device,
3250 VkBuffer _buffer,
3251 VkMemoryRequirements* pMemoryRequirements)
3252 {
3253 RADV_FROM_HANDLE(radv_device, device, _device);
3254 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
3255
3256 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
3257
3258 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
3259 pMemoryRequirements->alignment = 4096;
3260 else
3261 pMemoryRequirements->alignment = 16;
3262
3263 pMemoryRequirements->size = align64(buffer->size, pMemoryRequirements->alignment);
3264 }
3265
3266 void radv_GetBufferMemoryRequirements2(
3267 VkDevice device,
3268 const VkBufferMemoryRequirementsInfo2 *pInfo,
3269 VkMemoryRequirements2 *pMemoryRequirements)
3270 {
3271 radv_GetBufferMemoryRequirements(device, pInfo->buffer,
3272 &pMemoryRequirements->memoryRequirements);
3273 RADV_FROM_HANDLE(radv_buffer, buffer, pInfo->buffer);
3274 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
3275 switch (ext->sType) {
3276 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
3277 VkMemoryDedicatedRequirements *req =
3278 (VkMemoryDedicatedRequirements *) ext;
3279 req->requiresDedicatedAllocation = buffer->shareable;
3280 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
3281 break;
3282 }
3283 default:
3284 break;
3285 }
3286 }
3287 }
3288
3289 void radv_GetImageMemoryRequirements(
3290 VkDevice _device,
3291 VkImage _image,
3292 VkMemoryRequirements* pMemoryRequirements)
3293 {
3294 RADV_FROM_HANDLE(radv_device, device, _device);
3295 RADV_FROM_HANDLE(radv_image, image, _image);
3296
3297 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
3298
3299 pMemoryRequirements->size = image->size;
3300 pMemoryRequirements->alignment = image->alignment;
3301 }
3302
3303 void radv_GetImageMemoryRequirements2(
3304 VkDevice device,
3305 const VkImageMemoryRequirementsInfo2 *pInfo,
3306 VkMemoryRequirements2 *pMemoryRequirements)
3307 {
3308 radv_GetImageMemoryRequirements(device, pInfo->image,
3309 &pMemoryRequirements->memoryRequirements);
3310
3311 RADV_FROM_HANDLE(radv_image, image, pInfo->image);
3312
3313 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
3314 switch (ext->sType) {
3315 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
3316 VkMemoryDedicatedRequirements *req =
3317 (VkMemoryDedicatedRequirements *) ext;
3318 req->requiresDedicatedAllocation = image->shareable;
3319 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
3320 break;
3321 }
3322 default:
3323 break;
3324 }
3325 }
3326 }
3327
3328 void radv_GetImageSparseMemoryRequirements(
3329 VkDevice device,
3330 VkImage image,
3331 uint32_t* pSparseMemoryRequirementCount,
3332 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
3333 {
3334 stub();
3335 }
3336
3337 void radv_GetImageSparseMemoryRequirements2(
3338 VkDevice device,
3339 const VkImageSparseMemoryRequirementsInfo2 *pInfo,
3340 uint32_t* pSparseMemoryRequirementCount,
3341 VkSparseImageMemoryRequirements2 *pSparseMemoryRequirements)
3342 {
3343 stub();
3344 }
3345
3346 void radv_GetDeviceMemoryCommitment(
3347 VkDevice device,
3348 VkDeviceMemory memory,
3349 VkDeviceSize* pCommittedMemoryInBytes)
3350 {
3351 *pCommittedMemoryInBytes = 0;
3352 }
3353
3354 VkResult radv_BindBufferMemory2(VkDevice device,
3355 uint32_t bindInfoCount,
3356 const VkBindBufferMemoryInfo *pBindInfos)
3357 {
3358 for (uint32_t i = 0; i < bindInfoCount; ++i) {
3359 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
3360 RADV_FROM_HANDLE(radv_buffer, buffer, pBindInfos[i].buffer);
3361
3362 if (mem) {
3363 buffer->bo = mem->bo;
3364 buffer->offset = pBindInfos[i].memoryOffset;
3365 } else {
3366 buffer->bo = NULL;
3367 }
3368 }
3369 return VK_SUCCESS;
3370 }
3371
3372 VkResult radv_BindBufferMemory(
3373 VkDevice device,
3374 VkBuffer buffer,
3375 VkDeviceMemory memory,
3376 VkDeviceSize memoryOffset)
3377 {
3378 const VkBindBufferMemoryInfo info = {
3379 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
3380 .buffer = buffer,
3381 .memory = memory,
3382 .memoryOffset = memoryOffset
3383 };
3384
3385 return radv_BindBufferMemory2(device, 1, &info);
3386 }
3387
3388 VkResult radv_BindImageMemory2(VkDevice device,
3389 uint32_t bindInfoCount,
3390 const VkBindImageMemoryInfo *pBindInfos)
3391 {
3392 for (uint32_t i = 0; i < bindInfoCount; ++i) {
3393 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
3394 RADV_FROM_HANDLE(radv_image, image, pBindInfos[i].image);
3395
3396 if (mem) {
3397 image->bo = mem->bo;
3398 image->offset = pBindInfos[i].memoryOffset;
3399 } else {
3400 image->bo = NULL;
3401 image->offset = 0;
3402 }
3403 }
3404 return VK_SUCCESS;
3405 }
3406
3407
3408 VkResult radv_BindImageMemory(
3409 VkDevice device,
3410 VkImage image,
3411 VkDeviceMemory memory,
3412 VkDeviceSize memoryOffset)
3413 {
3414 const VkBindImageMemoryInfo info = {
3415 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
3416 .image = image,
3417 .memory = memory,
3418 .memoryOffset = memoryOffset
3419 };
3420
3421 return radv_BindImageMemory2(device, 1, &info);
3422 }
3423
3424
3425 static void
3426 radv_sparse_buffer_bind_memory(struct radv_device *device,
3427 const VkSparseBufferMemoryBindInfo *bind)
3428 {
3429 RADV_FROM_HANDLE(radv_buffer, buffer, bind->buffer);
3430
3431 for (uint32_t i = 0; i < bind->bindCount; ++i) {
3432 struct radv_device_memory *mem = NULL;
3433
3434 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
3435 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
3436
3437 device->ws->buffer_virtual_bind(buffer->bo,
3438 bind->pBinds[i].resourceOffset,
3439 bind->pBinds[i].size,
3440 mem ? mem->bo : NULL,
3441 bind->pBinds[i].memoryOffset);
3442 }
3443 }
3444
3445 static void
3446 radv_sparse_image_opaque_bind_memory(struct radv_device *device,
3447 const VkSparseImageOpaqueMemoryBindInfo *bind)
3448 {
3449 RADV_FROM_HANDLE(radv_image, image, bind->image);
3450
3451 for (uint32_t i = 0; i < bind->bindCount; ++i) {
3452 struct radv_device_memory *mem = NULL;
3453
3454 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
3455 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
3456
3457 device->ws->buffer_virtual_bind(image->bo,
3458 bind->pBinds[i].resourceOffset,
3459 bind->pBinds[i].size,
3460 mem ? mem->bo : NULL,
3461 bind->pBinds[i].memoryOffset);
3462 }
3463 }
3464
3465 VkResult radv_QueueBindSparse(
3466 VkQueue _queue,
3467 uint32_t bindInfoCount,
3468 const VkBindSparseInfo* pBindInfo,
3469 VkFence _fence)
3470 {
3471 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3472 RADV_FROM_HANDLE(radv_queue, queue, _queue);
3473 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
3474 bool fence_emitted = false;
3475 VkResult result;
3476 int ret;
3477
3478 for (uint32_t i = 0; i < bindInfoCount; ++i) {
3479 struct radv_winsys_sem_info sem_info;
3480 for (uint32_t j = 0; j < pBindInfo[i].bufferBindCount; ++j) {
3481 radv_sparse_buffer_bind_memory(queue->device,
3482 pBindInfo[i].pBufferBinds + j);
3483 }
3484
3485 for (uint32_t j = 0; j < pBindInfo[i].imageOpaqueBindCount; ++j) {
3486 radv_sparse_image_opaque_bind_memory(queue->device,
3487 pBindInfo[i].pImageOpaqueBinds + j);
3488 }
3489
3490 VkResult result;
3491 result = radv_alloc_sem_info(queue->device->instance,
3492 &sem_info,
3493 pBindInfo[i].waitSemaphoreCount,
3494 pBindInfo[i].pWaitSemaphores,
3495 pBindInfo[i].signalSemaphoreCount,
3496 pBindInfo[i].pSignalSemaphores,
3497 _fence);
3498 if (result != VK_SUCCESS)
3499 return result;
3500
3501 if (pBindInfo[i].waitSemaphoreCount || pBindInfo[i].signalSemaphoreCount) {
3502 ret = queue->device->ws->cs_submit(queue->hw_ctx, queue->queue_idx,
3503 &queue->device->empty_cs[queue->queue_family_index],
3504 1, NULL, NULL,
3505 &sem_info, NULL,
3506 false, base_fence);
3507 if (ret) {
3508 radv_loge("failed to submit CS %d\n", i);
3509 abort();
3510 }
3511
3512 fence_emitted = true;
3513 if (fence)
3514 fence->submitted = true;
3515 }
3516
3517 radv_free_sem_info(&sem_info);
3518
3519 }
3520
3521 if (fence) {
3522 if (!fence_emitted) {
3523 result = radv_signal_fence(queue, fence);
3524 if (result != VK_SUCCESS)
3525 return result;
3526 }
3527 fence->submitted = true;
3528 }
3529
3530 return VK_SUCCESS;
3531 }
3532
3533 VkResult radv_CreateFence(
3534 VkDevice _device,
3535 const VkFenceCreateInfo* pCreateInfo,
3536 const VkAllocationCallbacks* pAllocator,
3537 VkFence* pFence)
3538 {
3539 RADV_FROM_HANDLE(radv_device, device, _device);
3540 const VkExportFenceCreateInfo *export =
3541 vk_find_struct_const(pCreateInfo->pNext, EXPORT_FENCE_CREATE_INFO);
3542 VkExternalFenceHandleTypeFlags handleTypes =
3543 export ? export->handleTypes : 0;
3544
3545 struct radv_fence *fence = vk_alloc2(&device->alloc, pAllocator,
3546 sizeof(*fence), 8,
3547 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3548
3549 if (!fence)
3550 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3551
3552 fence->fence_wsi = NULL;
3553 fence->submitted = false;
3554 fence->signalled = !!(pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT);
3555 fence->temp_syncobj = 0;
3556 if (device->always_use_syncobj || handleTypes) {
3557 int ret = device->ws->create_syncobj(device->ws, &fence->syncobj);
3558 if (ret) {
3559 vk_free2(&device->alloc, pAllocator, fence);
3560 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3561 }
3562 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
3563 device->ws->signal_syncobj(device->ws, fence->syncobj);
3564 }
3565 fence->fence = NULL;
3566 } else {
3567 fence->fence = device->ws->create_fence();
3568 if (!fence->fence) {
3569 vk_free2(&device->alloc, pAllocator, fence);
3570 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3571 }
3572 fence->syncobj = 0;
3573 }
3574
3575 *pFence = radv_fence_to_handle(fence);
3576
3577 return VK_SUCCESS;
3578 }
3579
3580 void radv_DestroyFence(
3581 VkDevice _device,
3582 VkFence _fence,
3583 const VkAllocationCallbacks* pAllocator)
3584 {
3585 RADV_FROM_HANDLE(radv_device, device, _device);
3586 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3587
3588 if (!fence)
3589 return;
3590
3591 if (fence->temp_syncobj)
3592 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
3593 if (fence->syncobj)
3594 device->ws->destroy_syncobj(device->ws, fence->syncobj);
3595 if (fence->fence)
3596 device->ws->destroy_fence(fence->fence);
3597 if (fence->fence_wsi)
3598 fence->fence_wsi->destroy(fence->fence_wsi);
3599 vk_free2(&device->alloc, pAllocator, fence);
3600 }
3601
3602
3603 static uint64_t radv_get_current_time()
3604 {
3605 struct timespec tv;
3606 clock_gettime(CLOCK_MONOTONIC, &tv);
3607 return tv.tv_nsec + tv.tv_sec*1000000000ull;
3608 }
3609
3610 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
3611 {
3612 uint64_t current_time = radv_get_current_time();
3613
3614 timeout = MIN2(UINT64_MAX - current_time, timeout);
3615
3616 return current_time + timeout;
3617 }
3618
3619
3620 static bool radv_all_fences_plain_and_submitted(uint32_t fenceCount, const VkFence *pFences)
3621 {
3622 for (uint32_t i = 0; i < fenceCount; ++i) {
3623 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
3624 if (fence->fence == NULL || fence->syncobj ||
3625 fence->temp_syncobj ||
3626 (!fence->signalled && !fence->submitted))
3627 return false;
3628 }
3629 return true;
3630 }
3631
3632 static bool radv_all_fences_syncobj(uint32_t fenceCount, const VkFence *pFences)
3633 {
3634 for (uint32_t i = 0; i < fenceCount; ++i) {
3635 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
3636 if (fence->syncobj == 0 && fence->temp_syncobj == 0)
3637 return false;
3638 }
3639 return true;
3640 }
3641
3642 VkResult radv_WaitForFences(
3643 VkDevice _device,
3644 uint32_t fenceCount,
3645 const VkFence* pFences,
3646 VkBool32 waitAll,
3647 uint64_t timeout)
3648 {
3649 RADV_FROM_HANDLE(radv_device, device, _device);
3650 timeout = radv_get_absolute_timeout(timeout);
3651
3652 if (device->always_use_syncobj &&
3653 radv_all_fences_syncobj(fenceCount, pFences))
3654 {
3655 uint32_t *handles = malloc(sizeof(uint32_t) * fenceCount);
3656 if (!handles)
3657 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3658
3659 for (uint32_t i = 0; i < fenceCount; ++i) {
3660 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
3661 handles[i] = fence->temp_syncobj ? fence->temp_syncobj : fence->syncobj;
3662 }
3663
3664 bool success = device->ws->wait_syncobj(device->ws, handles, fenceCount, waitAll, timeout);
3665
3666 free(handles);
3667 return success ? VK_SUCCESS : VK_TIMEOUT;
3668 }
3669
3670 if (!waitAll && fenceCount > 1) {
3671 /* Not doing this by default for waitAll, due to needing to allocate twice. */
3672 if (device->physical_device->rad_info.drm_minor >= 10 && radv_all_fences_plain_and_submitted(fenceCount, pFences)) {
3673 uint32_t wait_count = 0;
3674 struct radeon_winsys_fence **fences = malloc(sizeof(struct radeon_winsys_fence *) * fenceCount);
3675 if (!fences)
3676 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3677
3678 for (uint32_t i = 0; i < fenceCount; ++i) {
3679 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
3680
3681 if (fence->signalled) {
3682 free(fences);
3683 return VK_SUCCESS;
3684 }
3685
3686 fences[wait_count++] = fence->fence;
3687 }
3688
3689 bool success = device->ws->fences_wait(device->ws, fences, wait_count,
3690 waitAll, timeout - radv_get_current_time());
3691
3692 free(fences);
3693 return success ? VK_SUCCESS : VK_TIMEOUT;
3694 }
3695
3696 while(radv_get_current_time() <= timeout) {
3697 for (uint32_t i = 0; i < fenceCount; ++i) {
3698 if (radv_GetFenceStatus(_device, pFences[i]) == VK_SUCCESS)
3699 return VK_SUCCESS;
3700 }
3701 }
3702 return VK_TIMEOUT;
3703 }
3704
3705 for (uint32_t i = 0; i < fenceCount; ++i) {
3706 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
3707 bool expired = false;
3708
3709 if (fence->temp_syncobj) {
3710 if (!device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, timeout))
3711 return VK_TIMEOUT;
3712 continue;
3713 }
3714
3715 if (fence->syncobj) {
3716 if (!device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, timeout))
3717 return VK_TIMEOUT;
3718 continue;
3719 }
3720
3721 if (fence->signalled)
3722 continue;
3723
3724 if (fence->fence) {
3725 if (!fence->submitted) {
3726 while(radv_get_current_time() <= timeout &&
3727 !fence->submitted)
3728 /* Do nothing */;
3729
3730 if (!fence->submitted)
3731 return VK_TIMEOUT;
3732
3733 /* Recheck as it may have been set by
3734 * submitting operations. */
3735
3736 if (fence->signalled)
3737 continue;
3738 }
3739
3740 expired = device->ws->fence_wait(device->ws,
3741 fence->fence,
3742 true, timeout);
3743 if (!expired)
3744 return VK_TIMEOUT;
3745 }
3746
3747 if (fence->fence_wsi) {
3748 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, timeout);
3749 if (result != VK_SUCCESS)
3750 return result;
3751 }
3752
3753 fence->signalled = true;
3754 }
3755
3756 return VK_SUCCESS;
3757 }
3758
3759 VkResult radv_ResetFences(VkDevice _device,
3760 uint32_t fenceCount,
3761 const VkFence *pFences)
3762 {
3763 RADV_FROM_HANDLE(radv_device, device, _device);
3764
3765 for (unsigned i = 0; i < fenceCount; ++i) {
3766 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
3767 fence->submitted = fence->signalled = false;
3768
3769 /* Per spec, we first restore the permanent payload, and then reset, so
3770 * having a temp syncobj should not skip resetting the permanent syncobj. */
3771 if (fence->temp_syncobj) {
3772 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
3773 fence->temp_syncobj = 0;
3774 }
3775
3776 if (fence->syncobj) {
3777 device->ws->reset_syncobj(device->ws, fence->syncobj);
3778 }
3779 }
3780
3781 return VK_SUCCESS;
3782 }
3783
3784 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
3785 {
3786 RADV_FROM_HANDLE(radv_device, device, _device);
3787 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3788
3789 if (fence->temp_syncobj) {
3790 bool success = device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, 0);
3791 return success ? VK_SUCCESS : VK_NOT_READY;
3792 }
3793
3794 if (fence->syncobj) {
3795 bool success = device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, 0);
3796 return success ? VK_SUCCESS : VK_NOT_READY;
3797 }
3798
3799 if (fence->signalled)
3800 return VK_SUCCESS;
3801 if (!fence->submitted)
3802 return VK_NOT_READY;
3803 if (fence->fence) {
3804 if (!device->ws->fence_wait(device->ws, fence->fence, false, 0))
3805 return VK_NOT_READY;
3806 }
3807 if (fence->fence_wsi) {
3808 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, 0);
3809
3810 if (result != VK_SUCCESS) {
3811 if (result == VK_TIMEOUT)
3812 return VK_NOT_READY;
3813 return result;
3814 }
3815 }
3816 return VK_SUCCESS;
3817 }
3818
3819
3820 // Queue semaphore functions
3821
3822 VkResult radv_CreateSemaphore(
3823 VkDevice _device,
3824 const VkSemaphoreCreateInfo* pCreateInfo,
3825 const VkAllocationCallbacks* pAllocator,
3826 VkSemaphore* pSemaphore)
3827 {
3828 RADV_FROM_HANDLE(radv_device, device, _device);
3829 const VkExportSemaphoreCreateInfo *export =
3830 vk_find_struct_const(pCreateInfo->pNext, EXPORT_SEMAPHORE_CREATE_INFO);
3831 VkExternalSemaphoreHandleTypeFlags handleTypes =
3832 export ? export->handleTypes : 0;
3833
3834 struct radv_semaphore *sem = vk_alloc2(&device->alloc, pAllocator,
3835 sizeof(*sem), 8,
3836 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3837 if (!sem)
3838 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3839
3840 sem->temp_syncobj = 0;
3841 /* create a syncobject if we are going to export this semaphore */
3842 if (device->always_use_syncobj || handleTypes) {
3843 assert (device->physical_device->rad_info.has_syncobj);
3844 int ret = device->ws->create_syncobj(device->ws, &sem->syncobj);
3845 if (ret) {
3846 vk_free2(&device->alloc, pAllocator, sem);
3847 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3848 }
3849 sem->sem = NULL;
3850 } else {
3851 sem->sem = device->ws->create_sem(device->ws);
3852 if (!sem->sem) {
3853 vk_free2(&device->alloc, pAllocator, sem);
3854 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3855 }
3856 sem->syncobj = 0;
3857 }
3858
3859 *pSemaphore = radv_semaphore_to_handle(sem);
3860 return VK_SUCCESS;
3861 }
3862
3863 void radv_DestroySemaphore(
3864 VkDevice _device,
3865 VkSemaphore _semaphore,
3866 const VkAllocationCallbacks* pAllocator)
3867 {
3868 RADV_FROM_HANDLE(radv_device, device, _device);
3869 RADV_FROM_HANDLE(radv_semaphore, sem, _semaphore);
3870 if (!_semaphore)
3871 return;
3872
3873 if (sem->syncobj)
3874 device->ws->destroy_syncobj(device->ws, sem->syncobj);
3875 else
3876 device->ws->destroy_sem(sem->sem);
3877 vk_free2(&device->alloc, pAllocator, sem);
3878 }
3879
3880 VkResult radv_CreateEvent(
3881 VkDevice _device,
3882 const VkEventCreateInfo* pCreateInfo,
3883 const VkAllocationCallbacks* pAllocator,
3884 VkEvent* pEvent)
3885 {
3886 RADV_FROM_HANDLE(radv_device, device, _device);
3887 struct radv_event *event = vk_alloc2(&device->alloc, pAllocator,
3888 sizeof(*event), 8,
3889 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3890
3891 if (!event)
3892 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3893
3894 event->bo = device->ws->buffer_create(device->ws, 8, 8,
3895 RADEON_DOMAIN_GTT,
3896 RADEON_FLAG_VA_UNCACHED | RADEON_FLAG_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING,
3897 RADV_BO_PRIORITY_FENCE);
3898 if (!event->bo) {
3899 vk_free2(&device->alloc, pAllocator, event);
3900 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
3901 }
3902
3903 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
3904
3905 *pEvent = radv_event_to_handle(event);
3906
3907 return VK_SUCCESS;
3908 }
3909
3910 void radv_DestroyEvent(
3911 VkDevice _device,
3912 VkEvent _event,
3913 const VkAllocationCallbacks* pAllocator)
3914 {
3915 RADV_FROM_HANDLE(radv_device, device, _device);
3916 RADV_FROM_HANDLE(radv_event, event, _event);
3917
3918 if (!event)
3919 return;
3920 device->ws->buffer_destroy(event->bo);
3921 vk_free2(&device->alloc, pAllocator, event);
3922 }
3923
3924 VkResult radv_GetEventStatus(
3925 VkDevice _device,
3926 VkEvent _event)
3927 {
3928 RADV_FROM_HANDLE(radv_event, event, _event);
3929
3930 if (*event->map == 1)
3931 return VK_EVENT_SET;
3932 return VK_EVENT_RESET;
3933 }
3934
3935 VkResult radv_SetEvent(
3936 VkDevice _device,
3937 VkEvent _event)
3938 {
3939 RADV_FROM_HANDLE(radv_event, event, _event);
3940 *event->map = 1;
3941
3942 return VK_SUCCESS;
3943 }
3944
3945 VkResult radv_ResetEvent(
3946 VkDevice _device,
3947 VkEvent _event)
3948 {
3949 RADV_FROM_HANDLE(radv_event, event, _event);
3950 *event->map = 0;
3951
3952 return VK_SUCCESS;
3953 }
3954
3955 VkResult radv_CreateBuffer(
3956 VkDevice _device,
3957 const VkBufferCreateInfo* pCreateInfo,
3958 const VkAllocationCallbacks* pAllocator,
3959 VkBuffer* pBuffer)
3960 {
3961 RADV_FROM_HANDLE(radv_device, device, _device);
3962 struct radv_buffer *buffer;
3963
3964 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
3965
3966 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
3967 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3968 if (buffer == NULL)
3969 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3970
3971 buffer->size = pCreateInfo->size;
3972 buffer->usage = pCreateInfo->usage;
3973 buffer->bo = NULL;
3974 buffer->offset = 0;
3975 buffer->flags = pCreateInfo->flags;
3976
3977 buffer->shareable = vk_find_struct_const(pCreateInfo->pNext,
3978 EXTERNAL_MEMORY_BUFFER_CREATE_INFO) != NULL;
3979
3980 if (pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) {
3981 buffer->bo = device->ws->buffer_create(device->ws,
3982 align64(buffer->size, 4096),
3983 4096, 0, RADEON_FLAG_VIRTUAL,
3984 RADV_BO_PRIORITY_VIRTUAL);
3985 if (!buffer->bo) {
3986 vk_free2(&device->alloc, pAllocator, buffer);
3987 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
3988 }
3989 }
3990
3991 *pBuffer = radv_buffer_to_handle(buffer);
3992
3993 return VK_SUCCESS;
3994 }
3995
3996 void radv_DestroyBuffer(
3997 VkDevice _device,
3998 VkBuffer _buffer,
3999 const VkAllocationCallbacks* pAllocator)
4000 {
4001 RADV_FROM_HANDLE(radv_device, device, _device);
4002 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
4003
4004 if (!buffer)
4005 return;
4006
4007 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
4008 device->ws->buffer_destroy(buffer->bo);
4009
4010 vk_free2(&device->alloc, pAllocator, buffer);
4011 }
4012
4013 static inline unsigned
4014 si_tile_mode_index(const struct radv_image *image, unsigned level, bool stencil)
4015 {
4016 if (stencil)
4017 return image->surface.u.legacy.stencil_tiling_index[level];
4018 else
4019 return image->surface.u.legacy.tiling_index[level];
4020 }
4021
4022 static uint32_t radv_surface_max_layer_count(struct radv_image_view *iview)
4023 {
4024 return iview->type == VK_IMAGE_VIEW_TYPE_3D ? iview->extent.depth : (iview->base_layer + iview->layer_count);
4025 }
4026
4027 static uint32_t
4028 radv_init_dcc_control_reg(struct radv_device *device,
4029 struct radv_image_view *iview)
4030 {
4031 unsigned max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_256B;
4032 unsigned min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_32B;
4033 unsigned max_compressed_block_size;
4034 unsigned independent_64b_blocks;
4035
4036 if (!radv_image_has_dcc(iview->image))
4037 return 0;
4038
4039 if (iview->image->info.samples > 1) {
4040 if (iview->image->surface.bpe == 1)
4041 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
4042 else if (iview->image->surface.bpe == 2)
4043 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
4044 }
4045
4046 if (!device->physical_device->rad_info.has_dedicated_vram) {
4047 /* amdvlk: [min-compressed-block-size] should be set to 32 for
4048 * dGPU and 64 for APU because all of our APUs to date use
4049 * DIMMs which have a request granularity size of 64B while all
4050 * other chips have a 32B request size.
4051 */
4052 min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_64B;
4053 }
4054
4055 if (iview->image->usage & (VK_IMAGE_USAGE_SAMPLED_BIT |
4056 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
4057 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) {
4058 /* If this DCC image is potentially going to be used in texture
4059 * fetches, we need some special settings.
4060 */
4061 independent_64b_blocks = 1;
4062 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
4063 } else {
4064 /* MAX_UNCOMPRESSED_BLOCK_SIZE must be >=
4065 * MAX_COMPRESSED_BLOCK_SIZE. Set MAX_COMPRESSED_BLOCK_SIZE as
4066 * big as possible for better compression state.
4067 */
4068 independent_64b_blocks = 0;
4069 max_compressed_block_size = max_uncompressed_block_size;
4070 }
4071
4072 return S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
4073 S_028C78_MAX_COMPRESSED_BLOCK_SIZE(max_compressed_block_size) |
4074 S_028C78_MIN_COMPRESSED_BLOCK_SIZE(min_compressed_block_size) |
4075 S_028C78_INDEPENDENT_64B_BLOCKS(independent_64b_blocks);
4076 }
4077
4078 static void
4079 radv_initialise_color_surface(struct radv_device *device,
4080 struct radv_color_buffer_info *cb,
4081 struct radv_image_view *iview)
4082 {
4083 const struct vk_format_description *desc;
4084 unsigned ntype, format, swap, endian;
4085 unsigned blend_clamp = 0, blend_bypass = 0;
4086 uint64_t va;
4087 const struct radeon_surf *surf = &iview->image->surface;
4088
4089 desc = vk_format_description(iview->vk_format);
4090
4091 memset(cb, 0, sizeof(*cb));
4092
4093 /* Intensity is implemented as Red, so treat it that way. */
4094 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1);
4095
4096 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
4097
4098 cb->cb_color_base = va >> 8;
4099
4100 if (device->physical_device->rad_info.chip_class >= GFX9) {
4101 struct gfx9_surf_meta_flags meta;
4102 if (iview->image->dcc_offset)
4103 meta = iview->image->surface.u.gfx9.dcc;
4104 else
4105 meta = iview->image->surface.u.gfx9.cmask;
4106
4107 cb->cb_color_attrib |= S_028C74_COLOR_SW_MODE(iview->image->surface.u.gfx9.surf.swizzle_mode) |
4108 S_028C74_FMASK_SW_MODE(iview->image->surface.u.gfx9.fmask.swizzle_mode) |
4109 S_028C74_RB_ALIGNED(meta.rb_aligned) |
4110 S_028C74_PIPE_ALIGNED(meta.pipe_aligned);
4111
4112 cb->cb_color_base += iview->image->surface.u.gfx9.surf_offset >> 8;
4113 cb->cb_color_base |= iview->image->surface.tile_swizzle;
4114 } else {
4115 const struct legacy_surf_level *level_info = &surf->u.legacy.level[iview->base_mip];
4116 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
4117
4118 cb->cb_color_base += level_info->offset >> 8;
4119 if (level_info->mode == RADEON_SURF_MODE_2D)
4120 cb->cb_color_base |= iview->image->surface.tile_swizzle;
4121
4122 pitch_tile_max = level_info->nblk_x / 8 - 1;
4123 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
4124 tile_mode_index = si_tile_mode_index(iview->image, iview->base_mip, false);
4125
4126 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
4127 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
4128 cb->cb_color_cmask_slice = iview->image->cmask.slice_tile_max;
4129
4130 cb->cb_color_attrib |= S_028C74_TILE_MODE_INDEX(tile_mode_index);
4131
4132 if (radv_image_has_fmask(iview->image)) {
4133 if (device->physical_device->rad_info.chip_class >= CIK)
4134 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(iview->image->fmask.pitch_in_pixels / 8 - 1);
4135 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(iview->image->fmask.tile_mode_index);
4136 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(iview->image->fmask.slice_tile_max);
4137 } else {
4138 /* This must be set for fast clear to work without FMASK. */
4139 if (device->physical_device->rad_info.chip_class >= CIK)
4140 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
4141 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
4142 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
4143 }
4144 }
4145
4146 /* CMASK variables */
4147 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
4148 va += iview->image->cmask.offset;
4149 cb->cb_color_cmask = va >> 8;
4150
4151 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
4152 va += iview->image->dcc_offset;
4153 cb->cb_dcc_base = va >> 8;
4154 cb->cb_dcc_base |= iview->image->surface.tile_swizzle;
4155
4156 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
4157 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
4158 S_028C6C_SLICE_MAX(max_slice);
4159
4160 if (iview->image->info.samples > 1) {
4161 unsigned log_samples = util_logbase2(iview->image->info.samples);
4162
4163 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
4164 S_028C74_NUM_FRAGMENTS(log_samples);
4165 }
4166
4167 if (radv_image_has_fmask(iview->image)) {
4168 va = radv_buffer_get_va(iview->bo) + iview->image->offset + iview->image->fmask.offset;
4169 cb->cb_color_fmask = va >> 8;
4170 cb->cb_color_fmask |= iview->image->fmask.tile_swizzle;
4171 } else {
4172 cb->cb_color_fmask = cb->cb_color_base;
4173 }
4174
4175 ntype = radv_translate_color_numformat(iview->vk_format,
4176 desc,
4177 vk_format_get_first_non_void_channel(iview->vk_format));
4178 format = radv_translate_colorformat(iview->vk_format);
4179 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
4180 radv_finishme("Illegal color\n");
4181 swap = radv_translate_colorswap(iview->vk_format, FALSE);
4182 endian = radv_colorformat_endian_swap(format);
4183
4184 /* blend clamp should be set for all NORM/SRGB types */
4185 if (ntype == V_028C70_NUMBER_UNORM ||
4186 ntype == V_028C70_NUMBER_SNORM ||
4187 ntype == V_028C70_NUMBER_SRGB)
4188 blend_clamp = 1;
4189
4190 /* set blend bypass according to docs if SINT/UINT or
4191 8/24 COLOR variants */
4192 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
4193 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
4194 format == V_028C70_COLOR_X24_8_32_FLOAT) {
4195 blend_clamp = 0;
4196 blend_bypass = 1;
4197 }
4198 #if 0
4199 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
4200 (format == V_028C70_COLOR_8 ||
4201 format == V_028C70_COLOR_8_8 ||
4202 format == V_028C70_COLOR_8_8_8_8))
4203 ->color_is_int8 = true;
4204 #endif
4205 cb->cb_color_info = S_028C70_FORMAT(format) |
4206 S_028C70_COMP_SWAP(swap) |
4207 S_028C70_BLEND_CLAMP(blend_clamp) |
4208 S_028C70_BLEND_BYPASS(blend_bypass) |
4209 S_028C70_SIMPLE_FLOAT(1) |
4210 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
4211 ntype != V_028C70_NUMBER_SNORM &&
4212 ntype != V_028C70_NUMBER_SRGB &&
4213 format != V_028C70_COLOR_8_24 &&
4214 format != V_028C70_COLOR_24_8) |
4215 S_028C70_NUMBER_TYPE(ntype) |
4216 S_028C70_ENDIAN(endian);
4217 if (radv_image_has_fmask(iview->image)) {
4218 cb->cb_color_info |= S_028C70_COMPRESSION(1);
4219 if (device->physical_device->rad_info.chip_class == SI) {
4220 unsigned fmask_bankh = util_logbase2(iview->image->fmask.bank_height);
4221 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
4222 }
4223 }
4224
4225 if (radv_image_has_cmask(iview->image) &&
4226 !(device->instance->debug_flags & RADV_DEBUG_NO_FAST_CLEARS))
4227 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
4228
4229 if (radv_dcc_enabled(iview->image, iview->base_mip))
4230 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
4231
4232 cb->cb_dcc_control = radv_init_dcc_control_reg(device, iview);
4233
4234 /* This must be set for fast clear to work without FMASK. */
4235 if (!radv_image_has_fmask(iview->image) &&
4236 device->physical_device->rad_info.chip_class == SI) {
4237 unsigned bankh = util_logbase2(iview->image->surface.u.legacy.bankh);
4238 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
4239 }
4240
4241 if (device->physical_device->rad_info.chip_class >= GFX9) {
4242 unsigned mip0_depth = iview->image->type == VK_IMAGE_TYPE_3D ?
4243 (iview->extent.depth - 1) : (iview->image->info.array_size - 1);
4244
4245 cb->cb_color_view |= S_028C6C_MIP_LEVEL(iview->base_mip);
4246 cb->cb_color_attrib |= S_028C74_MIP0_DEPTH(mip0_depth) |
4247 S_028C74_RESOURCE_TYPE(iview->image->surface.u.gfx9.resource_type);
4248 cb->cb_color_attrib2 = S_028C68_MIP0_WIDTH(iview->extent.width - 1) |
4249 S_028C68_MIP0_HEIGHT(iview->extent.height - 1) |
4250 S_028C68_MAX_MIP(iview->image->info.levels - 1);
4251 }
4252 }
4253
4254 static unsigned
4255 radv_calc_decompress_on_z_planes(struct radv_device *device,
4256 struct radv_image_view *iview)
4257 {
4258 unsigned max_zplanes = 0;
4259
4260 assert(radv_image_is_tc_compat_htile(iview->image));
4261
4262 if (device->physical_device->rad_info.chip_class >= GFX9) {
4263 /* Default value for 32-bit depth surfaces. */
4264 max_zplanes = 4;
4265
4266 if (iview->vk_format == VK_FORMAT_D16_UNORM &&
4267 iview->image->info.samples > 1)
4268 max_zplanes = 2;
4269
4270 max_zplanes = max_zplanes + 1;
4271 } else {
4272 if (iview->vk_format == VK_FORMAT_D16_UNORM) {
4273 /* Do not enable Z plane compression for 16-bit depth
4274 * surfaces because isn't supported on GFX8. Only
4275 * 32-bit depth surfaces are supported by the hardware.
4276 * This allows to maintain shader compatibility and to
4277 * reduce the number of depth decompressions.
4278 */
4279 max_zplanes = 1;
4280 } else {
4281 if (iview->image->info.samples <= 1)
4282 max_zplanes = 5;
4283 else if (iview->image->info.samples <= 4)
4284 max_zplanes = 3;
4285 else
4286 max_zplanes = 2;
4287 }
4288 }
4289
4290 return max_zplanes;
4291 }
4292
4293 static void
4294 radv_initialise_ds_surface(struct radv_device *device,
4295 struct radv_ds_buffer_info *ds,
4296 struct radv_image_view *iview)
4297 {
4298 unsigned level = iview->base_mip;
4299 unsigned format, stencil_format;
4300 uint64_t va, s_offs, z_offs;
4301 bool stencil_only = false;
4302 memset(ds, 0, sizeof(*ds));
4303 switch (iview->image->vk_format) {
4304 case VK_FORMAT_D24_UNORM_S8_UINT:
4305 case VK_FORMAT_X8_D24_UNORM_PACK32:
4306 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
4307 ds->offset_scale = 2.0f;
4308 break;
4309 case VK_FORMAT_D16_UNORM:
4310 case VK_FORMAT_D16_UNORM_S8_UINT:
4311 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
4312 ds->offset_scale = 4.0f;
4313 break;
4314 case VK_FORMAT_D32_SFLOAT:
4315 case VK_FORMAT_D32_SFLOAT_S8_UINT:
4316 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
4317 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
4318 ds->offset_scale = 1.0f;
4319 break;
4320 case VK_FORMAT_S8_UINT:
4321 stencil_only = true;
4322 break;
4323 default:
4324 break;
4325 }
4326
4327 format = radv_translate_dbformat(iview->image->vk_format);
4328 stencil_format = iview->image->surface.has_stencil ?
4329 V_028044_STENCIL_8 : V_028044_STENCIL_INVALID;
4330
4331 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
4332 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
4333 S_028008_SLICE_MAX(max_slice);
4334
4335 ds->db_htile_data_base = 0;
4336 ds->db_htile_surface = 0;
4337
4338 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
4339 s_offs = z_offs = va;
4340
4341 if (device->physical_device->rad_info.chip_class >= GFX9) {
4342 assert(iview->image->surface.u.gfx9.surf_offset == 0);
4343 s_offs += iview->image->surface.u.gfx9.stencil_offset;
4344
4345 ds->db_z_info = S_028038_FORMAT(format) |
4346 S_028038_NUM_SAMPLES(util_logbase2(iview->image->info.samples)) |
4347 S_028038_SW_MODE(iview->image->surface.u.gfx9.surf.swizzle_mode) |
4348 S_028038_MAXMIP(iview->image->info.levels - 1) |
4349 S_028038_ZRANGE_PRECISION(1);
4350 ds->db_stencil_info = S_02803C_FORMAT(stencil_format) |
4351 S_02803C_SW_MODE(iview->image->surface.u.gfx9.stencil.swizzle_mode);
4352
4353 ds->db_z_info2 = S_028068_EPITCH(iview->image->surface.u.gfx9.surf.epitch);
4354 ds->db_stencil_info2 = S_02806C_EPITCH(iview->image->surface.u.gfx9.stencil.epitch);
4355 ds->db_depth_view |= S_028008_MIPID(level);
4356
4357 ds->db_depth_size = S_02801C_X_MAX(iview->image->info.width - 1) |
4358 S_02801C_Y_MAX(iview->image->info.height - 1);
4359
4360 if (radv_htile_enabled(iview->image, level)) {
4361 ds->db_z_info |= S_028038_TILE_SURFACE_ENABLE(1);
4362
4363 if (radv_image_is_tc_compat_htile(iview->image)) {
4364 unsigned max_zplanes =
4365 radv_calc_decompress_on_z_planes(device, iview);
4366
4367 ds->db_z_info |= S_028038_DECOMPRESS_ON_N_ZPLANES(max_zplanes) |
4368 S_028038_ITERATE_FLUSH(1);
4369 ds->db_stencil_info |= S_02803C_ITERATE_FLUSH(1);
4370 }
4371
4372 if (!iview->image->surface.has_stencil)
4373 /* Use all of the htile_buffer for depth if there's no stencil. */
4374 ds->db_stencil_info |= S_02803C_TILE_STENCIL_DISABLE(1);
4375 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
4376 iview->image->htile_offset;
4377 ds->db_htile_data_base = va >> 8;
4378 ds->db_htile_surface = S_028ABC_FULL_CACHE(1) |
4379 S_028ABC_PIPE_ALIGNED(iview->image->surface.u.gfx9.htile.pipe_aligned) |
4380 S_028ABC_RB_ALIGNED(iview->image->surface.u.gfx9.htile.rb_aligned);
4381 }
4382 } else {
4383 const struct legacy_surf_level *level_info = &iview->image->surface.u.legacy.level[level];
4384
4385 if (stencil_only)
4386 level_info = &iview->image->surface.u.legacy.stencil_level[level];
4387
4388 z_offs += iview->image->surface.u.legacy.level[level].offset;
4389 s_offs += iview->image->surface.u.legacy.stencil_level[level].offset;
4390
4391 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(!radv_image_is_tc_compat_htile(iview->image));
4392 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
4393 ds->db_stencil_info = S_028044_FORMAT(stencil_format);
4394
4395 if (iview->image->info.samples > 1)
4396 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->info.samples));
4397
4398 if (device->physical_device->rad_info.chip_class >= CIK) {
4399 struct radeon_info *info = &device->physical_device->rad_info;
4400 unsigned tiling_index = iview->image->surface.u.legacy.tiling_index[level];
4401 unsigned stencil_index = iview->image->surface.u.legacy.stencil_tiling_index[level];
4402 unsigned macro_index = iview->image->surface.u.legacy.macro_tile_index;
4403 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
4404 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
4405 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
4406
4407 if (stencil_only)
4408 tile_mode = stencil_tile_mode;
4409
4410 ds->db_depth_info |=
4411 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
4412 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
4413 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
4414 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
4415 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
4416 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
4417 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
4418 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
4419 } else {
4420 unsigned tile_mode_index = si_tile_mode_index(iview->image, level, false);
4421 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
4422 tile_mode_index = si_tile_mode_index(iview->image, level, true);
4423 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
4424 if (stencil_only)
4425 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
4426 }
4427
4428 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
4429 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
4430 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
4431
4432 if (radv_htile_enabled(iview->image, level)) {
4433 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1);
4434
4435 if (!iview->image->surface.has_stencil &&
4436 !radv_image_is_tc_compat_htile(iview->image))
4437 /* Use all of the htile_buffer for depth if there's no stencil. */
4438 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
4439
4440 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
4441 iview->image->htile_offset;
4442 ds->db_htile_data_base = va >> 8;
4443 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
4444
4445 if (radv_image_is_tc_compat_htile(iview->image)) {
4446 unsigned max_zplanes =
4447 radv_calc_decompress_on_z_planes(device, iview);
4448
4449 ds->db_htile_surface |= S_028ABC_TC_COMPATIBLE(1);
4450 ds->db_z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
4451 }
4452 }
4453 }
4454
4455 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
4456 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
4457 }
4458
4459 VkResult radv_CreateFramebuffer(
4460 VkDevice _device,
4461 const VkFramebufferCreateInfo* pCreateInfo,
4462 const VkAllocationCallbacks* pAllocator,
4463 VkFramebuffer* pFramebuffer)
4464 {
4465 RADV_FROM_HANDLE(radv_device, device, _device);
4466 struct radv_framebuffer *framebuffer;
4467
4468 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
4469
4470 size_t size = sizeof(*framebuffer) +
4471 sizeof(struct radv_attachment_info) * pCreateInfo->attachmentCount;
4472 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
4473 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4474 if (framebuffer == NULL)
4475 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4476
4477 framebuffer->attachment_count = pCreateInfo->attachmentCount;
4478 framebuffer->width = pCreateInfo->width;
4479 framebuffer->height = pCreateInfo->height;
4480 framebuffer->layers = pCreateInfo->layers;
4481 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
4482 VkImageView _iview = pCreateInfo->pAttachments[i];
4483 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
4484 framebuffer->attachments[i].attachment = iview;
4485 if (iview->aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) {
4486 radv_initialise_color_surface(device, &framebuffer->attachments[i].cb, iview);
4487 } else if (iview->aspect_mask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
4488 radv_initialise_ds_surface(device, &framebuffer->attachments[i].ds, iview);
4489 }
4490 framebuffer->width = MIN2(framebuffer->width, iview->extent.width);
4491 framebuffer->height = MIN2(framebuffer->height, iview->extent.height);
4492 framebuffer->layers = MIN2(framebuffer->layers, radv_surface_max_layer_count(iview));
4493 }
4494
4495 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
4496 return VK_SUCCESS;
4497 }
4498
4499 void radv_DestroyFramebuffer(
4500 VkDevice _device,
4501 VkFramebuffer _fb,
4502 const VkAllocationCallbacks* pAllocator)
4503 {
4504 RADV_FROM_HANDLE(radv_device, device, _device);
4505 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
4506
4507 if (!fb)
4508 return;
4509 vk_free2(&device->alloc, pAllocator, fb);
4510 }
4511
4512 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
4513 {
4514 switch (address_mode) {
4515 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
4516 return V_008F30_SQ_TEX_WRAP;
4517 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
4518 return V_008F30_SQ_TEX_MIRROR;
4519 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
4520 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
4521 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
4522 return V_008F30_SQ_TEX_CLAMP_BORDER;
4523 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
4524 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
4525 default:
4526 unreachable("illegal tex wrap mode");
4527 break;
4528 }
4529 }
4530
4531 static unsigned
4532 radv_tex_compare(VkCompareOp op)
4533 {
4534 switch (op) {
4535 case VK_COMPARE_OP_NEVER:
4536 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
4537 case VK_COMPARE_OP_LESS:
4538 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
4539 case VK_COMPARE_OP_EQUAL:
4540 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
4541 case VK_COMPARE_OP_LESS_OR_EQUAL:
4542 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
4543 case VK_COMPARE_OP_GREATER:
4544 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
4545 case VK_COMPARE_OP_NOT_EQUAL:
4546 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
4547 case VK_COMPARE_OP_GREATER_OR_EQUAL:
4548 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
4549 case VK_COMPARE_OP_ALWAYS:
4550 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
4551 default:
4552 unreachable("illegal compare mode");
4553 break;
4554 }
4555 }
4556
4557 static unsigned
4558 radv_tex_filter(VkFilter filter, unsigned max_ansio)
4559 {
4560 switch (filter) {
4561 case VK_FILTER_NEAREST:
4562 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
4563 V_008F38_SQ_TEX_XY_FILTER_POINT);
4564 case VK_FILTER_LINEAR:
4565 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
4566 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
4567 case VK_FILTER_CUBIC_IMG:
4568 default:
4569 fprintf(stderr, "illegal texture filter");
4570 return 0;
4571 }
4572 }
4573
4574 static unsigned
4575 radv_tex_mipfilter(VkSamplerMipmapMode mode)
4576 {
4577 switch (mode) {
4578 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
4579 return V_008F38_SQ_TEX_Z_FILTER_POINT;
4580 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
4581 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
4582 default:
4583 return V_008F38_SQ_TEX_Z_FILTER_NONE;
4584 }
4585 }
4586
4587 static unsigned
4588 radv_tex_bordercolor(VkBorderColor bcolor)
4589 {
4590 switch (bcolor) {
4591 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
4592 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
4593 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
4594 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
4595 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
4596 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
4597 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
4598 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
4599 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
4600 default:
4601 break;
4602 }
4603 return 0;
4604 }
4605
4606 static unsigned
4607 radv_tex_aniso_filter(unsigned filter)
4608 {
4609 if (filter < 2)
4610 return 0;
4611 if (filter < 4)
4612 return 1;
4613 if (filter < 8)
4614 return 2;
4615 if (filter < 16)
4616 return 3;
4617 return 4;
4618 }
4619
4620 static unsigned
4621 radv_tex_filter_mode(VkSamplerReductionModeEXT mode)
4622 {
4623 switch (mode) {
4624 case VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT:
4625 return V_008F30_SQ_IMG_FILTER_MODE_BLEND;
4626 case VK_SAMPLER_REDUCTION_MODE_MIN_EXT:
4627 return V_008F30_SQ_IMG_FILTER_MODE_MIN;
4628 case VK_SAMPLER_REDUCTION_MODE_MAX_EXT:
4629 return V_008F30_SQ_IMG_FILTER_MODE_MAX;
4630 default:
4631 break;
4632 }
4633 return 0;
4634 }
4635
4636 static uint32_t
4637 radv_get_max_anisotropy(struct radv_device *device,
4638 const VkSamplerCreateInfo *pCreateInfo)
4639 {
4640 if (device->force_aniso >= 0)
4641 return device->force_aniso;
4642
4643 if (pCreateInfo->anisotropyEnable &&
4644 pCreateInfo->maxAnisotropy > 1.0f)
4645 return (uint32_t)pCreateInfo->maxAnisotropy;
4646
4647 return 0;
4648 }
4649
4650 static void
4651 radv_init_sampler(struct radv_device *device,
4652 struct radv_sampler *sampler,
4653 const VkSamplerCreateInfo *pCreateInfo)
4654 {
4655 uint32_t max_aniso = radv_get_max_anisotropy(device, pCreateInfo);
4656 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
4657 bool is_vi = (device->physical_device->rad_info.chip_class >= VI);
4658 unsigned filter_mode = V_008F30_SQ_IMG_FILTER_MODE_BLEND;
4659
4660 const struct VkSamplerReductionModeCreateInfoEXT *sampler_reduction =
4661 vk_find_struct_const(pCreateInfo->pNext,
4662 SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT);
4663 if (sampler_reduction)
4664 filter_mode = radv_tex_filter_mode(sampler_reduction->reductionMode);
4665
4666 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
4667 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
4668 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
4669 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
4670 S_008F30_DEPTH_COMPARE_FUNC(radv_tex_compare(pCreateInfo->compareOp)) |
4671 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
4672 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
4673 S_008F30_ANISO_BIAS(max_aniso_ratio) |
4674 S_008F30_DISABLE_CUBE_WRAP(0) |
4675 S_008F30_COMPAT_MODE(is_vi) |
4676 S_008F30_FILTER_MODE(filter_mode));
4677 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
4678 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
4679 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
4680 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
4681 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
4682 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
4683 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
4684 S_008F38_MIP_POINT_PRECLAMP(0) |
4685 S_008F38_DISABLE_LSB_CEIL(device->physical_device->rad_info.chip_class <= VI) |
4686 S_008F38_FILTER_PREC_FIX(1) |
4687 S_008F38_ANISO_OVERRIDE(is_vi));
4688 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(0) |
4689 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(pCreateInfo->borderColor)));
4690 }
4691
4692 VkResult radv_CreateSampler(
4693 VkDevice _device,
4694 const VkSamplerCreateInfo* pCreateInfo,
4695 const VkAllocationCallbacks* pAllocator,
4696 VkSampler* pSampler)
4697 {
4698 RADV_FROM_HANDLE(radv_device, device, _device);
4699 struct radv_sampler *sampler;
4700
4701 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
4702
4703 sampler = vk_alloc2(&device->alloc, pAllocator, sizeof(*sampler), 8,
4704 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4705 if (!sampler)
4706 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4707
4708 radv_init_sampler(device, sampler, pCreateInfo);
4709 *pSampler = radv_sampler_to_handle(sampler);
4710
4711 return VK_SUCCESS;
4712 }
4713
4714 void radv_DestroySampler(
4715 VkDevice _device,
4716 VkSampler _sampler,
4717 const VkAllocationCallbacks* pAllocator)
4718 {
4719 RADV_FROM_HANDLE(radv_device, device, _device);
4720 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
4721
4722 if (!sampler)
4723 return;
4724 vk_free2(&device->alloc, pAllocator, sampler);
4725 }
4726
4727 /* vk_icd.h does not declare this function, so we declare it here to
4728 * suppress Wmissing-prototypes.
4729 */
4730 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
4731 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
4732
4733 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
4734 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
4735 {
4736 /* For the full details on loader interface versioning, see
4737 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
4738 * What follows is a condensed summary, to help you navigate the large and
4739 * confusing official doc.
4740 *
4741 * - Loader interface v0 is incompatible with later versions. We don't
4742 * support it.
4743 *
4744 * - In loader interface v1:
4745 * - The first ICD entrypoint called by the loader is
4746 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
4747 * entrypoint.
4748 * - The ICD must statically expose no other Vulkan symbol unless it is
4749 * linked with -Bsymbolic.
4750 * - Each dispatchable Vulkan handle created by the ICD must be
4751 * a pointer to a struct whose first member is VK_LOADER_DATA. The
4752 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
4753 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
4754 * vkDestroySurfaceKHR(). The ICD must be capable of working with
4755 * such loader-managed surfaces.
4756 *
4757 * - Loader interface v2 differs from v1 in:
4758 * - The first ICD entrypoint called by the loader is
4759 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
4760 * statically expose this entrypoint.
4761 *
4762 * - Loader interface v3 differs from v2 in:
4763 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
4764 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
4765 * because the loader no longer does so.
4766 */
4767 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
4768 return VK_SUCCESS;
4769 }
4770
4771 VkResult radv_GetMemoryFdKHR(VkDevice _device,
4772 const VkMemoryGetFdInfoKHR *pGetFdInfo,
4773 int *pFD)
4774 {
4775 RADV_FROM_HANDLE(radv_device, device, _device);
4776 RADV_FROM_HANDLE(radv_device_memory, memory, pGetFdInfo->memory);
4777
4778 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
4779
4780 /* At the moment, we support only the below handle types. */
4781 assert(pGetFdInfo->handleType ==
4782 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
4783 pGetFdInfo->handleType ==
4784 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
4785
4786 bool ret = radv_get_memory_fd(device, memory, pFD);
4787 if (ret == false)
4788 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
4789 return VK_SUCCESS;
4790 }
4791
4792 VkResult radv_GetMemoryFdPropertiesKHR(VkDevice _device,
4793 VkExternalMemoryHandleTypeFlagBits handleType,
4794 int fd,
4795 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
4796 {
4797 RADV_FROM_HANDLE(radv_device, device, _device);
4798
4799 switch (handleType) {
4800 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
4801 pMemoryFdProperties->memoryTypeBits = (1 << RADV_MEM_TYPE_COUNT) - 1;
4802 return VK_SUCCESS;
4803
4804 default:
4805 /* The valid usage section for this function says:
4806 *
4807 * "handleType must not be one of the handle types defined as
4808 * opaque."
4809 *
4810 * So opaque handle types fall into the default "unsupported" case.
4811 */
4812 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
4813 }
4814 }
4815
4816 static VkResult radv_import_opaque_fd(struct radv_device *device,
4817 int fd,
4818 uint32_t *syncobj)
4819 {
4820 uint32_t syncobj_handle = 0;
4821 int ret = device->ws->import_syncobj(device->ws, fd, &syncobj_handle);
4822 if (ret != 0)
4823 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
4824
4825 if (*syncobj)
4826 device->ws->destroy_syncobj(device->ws, *syncobj);
4827
4828 *syncobj = syncobj_handle;
4829 close(fd);
4830
4831 return VK_SUCCESS;
4832 }
4833
4834 static VkResult radv_import_sync_fd(struct radv_device *device,
4835 int fd,
4836 uint32_t *syncobj)
4837 {
4838 /* If we create a syncobj we do it locally so that if we have an error, we don't
4839 * leave a syncobj in an undetermined state in the fence. */
4840 uint32_t syncobj_handle = *syncobj;
4841 if (!syncobj_handle) {
4842 int ret = device->ws->create_syncobj(device->ws, &syncobj_handle);
4843 if (ret) {
4844 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
4845 }
4846 }
4847
4848 if (fd == -1) {
4849 device->ws->signal_syncobj(device->ws, syncobj_handle);
4850 } else {
4851 int ret = device->ws->import_syncobj_from_sync_file(device->ws, syncobj_handle, fd);
4852 if (ret != 0)
4853 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
4854 }
4855
4856 *syncobj = syncobj_handle;
4857 if (fd != -1)
4858 close(fd);
4859
4860 return VK_SUCCESS;
4861 }
4862
4863 VkResult radv_ImportSemaphoreFdKHR(VkDevice _device,
4864 const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo)
4865 {
4866 RADV_FROM_HANDLE(radv_device, device, _device);
4867 RADV_FROM_HANDLE(radv_semaphore, sem, pImportSemaphoreFdInfo->semaphore);
4868 uint32_t *syncobj_dst = NULL;
4869
4870 if (pImportSemaphoreFdInfo->flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT) {
4871 syncobj_dst = &sem->temp_syncobj;
4872 } else {
4873 syncobj_dst = &sem->syncobj;
4874 }
4875
4876 switch(pImportSemaphoreFdInfo->handleType) {
4877 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
4878 return radv_import_opaque_fd(device, pImportSemaphoreFdInfo->fd, syncobj_dst);
4879 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
4880 return radv_import_sync_fd(device, pImportSemaphoreFdInfo->fd, syncobj_dst);
4881 default:
4882 unreachable("Unhandled semaphore handle type");
4883 }
4884 }
4885
4886 VkResult radv_GetSemaphoreFdKHR(VkDevice _device,
4887 const VkSemaphoreGetFdInfoKHR *pGetFdInfo,
4888 int *pFd)
4889 {
4890 RADV_FROM_HANDLE(radv_device, device, _device);
4891 RADV_FROM_HANDLE(radv_semaphore, sem, pGetFdInfo->semaphore);
4892 int ret;
4893 uint32_t syncobj_handle;
4894
4895 if (sem->temp_syncobj)
4896 syncobj_handle = sem->temp_syncobj;
4897 else
4898 syncobj_handle = sem->syncobj;
4899
4900 switch(pGetFdInfo->handleType) {
4901 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
4902 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
4903 break;
4904 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
4905 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
4906 if (!ret) {
4907 if (sem->temp_syncobj) {
4908 close (sem->temp_syncobj);
4909 sem->temp_syncobj = 0;
4910 } else {
4911 device->ws->reset_syncobj(device->ws, syncobj_handle);
4912 }
4913 }
4914 break;
4915 default:
4916 unreachable("Unhandled semaphore handle type");
4917 }
4918
4919 if (ret)
4920 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
4921 return VK_SUCCESS;
4922 }
4923
4924 void radv_GetPhysicalDeviceExternalSemaphoreProperties(
4925 VkPhysicalDevice physicalDevice,
4926 const VkPhysicalDeviceExternalSemaphoreInfo *pExternalSemaphoreInfo,
4927 VkExternalSemaphoreProperties *pExternalSemaphoreProperties)
4928 {
4929 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
4930
4931 /* Require has_syncobj_wait_for_submit for the syncobj signal ioctl introduced at virtually the same time */
4932 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
4933 (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT ||
4934 pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT)) {
4935 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
4936 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
4937 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
4938 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
4939 } else if (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) {
4940 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
4941 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
4942 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
4943 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
4944 } else {
4945 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
4946 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
4947 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
4948 }
4949 }
4950
4951 VkResult radv_ImportFenceFdKHR(VkDevice _device,
4952 const VkImportFenceFdInfoKHR *pImportFenceFdInfo)
4953 {
4954 RADV_FROM_HANDLE(radv_device, device, _device);
4955 RADV_FROM_HANDLE(radv_fence, fence, pImportFenceFdInfo->fence);
4956 uint32_t *syncobj_dst = NULL;
4957
4958
4959 if (pImportFenceFdInfo->flags & VK_FENCE_IMPORT_TEMPORARY_BIT) {
4960 syncobj_dst = &fence->temp_syncobj;
4961 } else {
4962 syncobj_dst = &fence->syncobj;
4963 }
4964
4965 switch(pImportFenceFdInfo->handleType) {
4966 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
4967 return radv_import_opaque_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
4968 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
4969 return radv_import_sync_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
4970 default:
4971 unreachable("Unhandled fence handle type");
4972 }
4973 }
4974
4975 VkResult radv_GetFenceFdKHR(VkDevice _device,
4976 const VkFenceGetFdInfoKHR *pGetFdInfo,
4977 int *pFd)
4978 {
4979 RADV_FROM_HANDLE(radv_device, device, _device);
4980 RADV_FROM_HANDLE(radv_fence, fence, pGetFdInfo->fence);
4981 int ret;
4982 uint32_t syncobj_handle;
4983
4984 if (fence->temp_syncobj)
4985 syncobj_handle = fence->temp_syncobj;
4986 else
4987 syncobj_handle = fence->syncobj;
4988
4989 switch(pGetFdInfo->handleType) {
4990 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
4991 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
4992 break;
4993 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
4994 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
4995 if (!ret) {
4996 if (fence->temp_syncobj) {
4997 close (fence->temp_syncobj);
4998 fence->temp_syncobj = 0;
4999 } else {
5000 device->ws->reset_syncobj(device->ws, syncobj_handle);
5001 }
5002 }
5003 break;
5004 default:
5005 unreachable("Unhandled fence handle type");
5006 }
5007
5008 if (ret)
5009 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5010 return VK_SUCCESS;
5011 }
5012
5013 void radv_GetPhysicalDeviceExternalFenceProperties(
5014 VkPhysicalDevice physicalDevice,
5015 const VkPhysicalDeviceExternalFenceInfo *pExternalFenceInfo,
5016 VkExternalFenceProperties *pExternalFenceProperties)
5017 {
5018 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
5019
5020 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
5021 (pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT ||
5022 pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT)) {
5023 pExternalFenceProperties->exportFromImportedHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
5024 pExternalFenceProperties->compatibleHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
5025 pExternalFenceProperties->externalFenceFeatures = VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT |
5026 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
5027 } else {
5028 pExternalFenceProperties->exportFromImportedHandleTypes = 0;
5029 pExternalFenceProperties->compatibleHandleTypes = 0;
5030 pExternalFenceProperties->externalFenceFeatures = 0;
5031 }
5032 }
5033
5034 VkResult
5035 radv_CreateDebugReportCallbackEXT(VkInstance _instance,
5036 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
5037 const VkAllocationCallbacks* pAllocator,
5038 VkDebugReportCallbackEXT* pCallback)
5039 {
5040 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5041 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
5042 pCreateInfo, pAllocator, &instance->alloc,
5043 pCallback);
5044 }
5045
5046 void
5047 radv_DestroyDebugReportCallbackEXT(VkInstance _instance,
5048 VkDebugReportCallbackEXT _callback,
5049 const VkAllocationCallbacks* pAllocator)
5050 {
5051 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5052 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
5053 _callback, pAllocator, &instance->alloc);
5054 }
5055
5056 void
5057 radv_DebugReportMessageEXT(VkInstance _instance,
5058 VkDebugReportFlagsEXT flags,
5059 VkDebugReportObjectTypeEXT objectType,
5060 uint64_t object,
5061 size_t location,
5062 int32_t messageCode,
5063 const char* pLayerPrefix,
5064 const char* pMessage)
5065 {
5066 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5067 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
5068 object, location, messageCode, pLayerPrefix, pMessage);
5069 }
5070
5071 void
5072 radv_GetDeviceGroupPeerMemoryFeatures(
5073 VkDevice device,
5074 uint32_t heapIndex,
5075 uint32_t localDeviceIndex,
5076 uint32_t remoteDeviceIndex,
5077 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
5078 {
5079 assert(localDeviceIndex == remoteDeviceIndex);
5080
5081 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
5082 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
5083 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
5084 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
5085 }
5086
5087 static const VkTimeDomainEXT radv_time_domains[] = {
5088 VK_TIME_DOMAIN_DEVICE_EXT,
5089 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
5090 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
5091 };
5092
5093 VkResult radv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
5094 VkPhysicalDevice physicalDevice,
5095 uint32_t *pTimeDomainCount,
5096 VkTimeDomainEXT *pTimeDomains)
5097 {
5098 int d;
5099 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
5100
5101 for (d = 0; d < ARRAY_SIZE(radv_time_domains); d++) {
5102 vk_outarray_append(&out, i) {
5103 *i = radv_time_domains[d];
5104 }
5105 }
5106
5107 return vk_outarray_status(&out);
5108 }
5109
5110 static uint64_t
5111 radv_clock_gettime(clockid_t clock_id)
5112 {
5113 struct timespec current;
5114 int ret;
5115
5116 ret = clock_gettime(clock_id, &current);
5117 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
5118 ret = clock_gettime(CLOCK_MONOTONIC, &current);
5119 if (ret < 0)
5120 return 0;
5121
5122 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
5123 }
5124
5125 VkResult radv_GetCalibratedTimestampsEXT(
5126 VkDevice _device,
5127 uint32_t timestampCount,
5128 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
5129 uint64_t *pTimestamps,
5130 uint64_t *pMaxDeviation)
5131 {
5132 RADV_FROM_HANDLE(radv_device, device, _device);
5133 uint32_t clock_crystal_freq = device->physical_device->rad_info.clock_crystal_freq;
5134 int d;
5135 uint64_t begin, end;
5136 uint64_t max_clock_period = 0;
5137
5138 begin = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
5139
5140 for (d = 0; d < timestampCount; d++) {
5141 switch (pTimestampInfos[d].timeDomain) {
5142 case VK_TIME_DOMAIN_DEVICE_EXT:
5143 pTimestamps[d] = device->ws->query_value(device->ws,
5144 RADEON_TIMESTAMP);
5145 uint64_t device_period = DIV_ROUND_UP(1000000, clock_crystal_freq);
5146 max_clock_period = MAX2(max_clock_period, device_period);
5147 break;
5148 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
5149 pTimestamps[d] = radv_clock_gettime(CLOCK_MONOTONIC);
5150 max_clock_period = MAX2(max_clock_period, 1);
5151 break;
5152
5153 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
5154 pTimestamps[d] = begin;
5155 break;
5156 default:
5157 pTimestamps[d] = 0;
5158 break;
5159 }
5160 }
5161
5162 end = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
5163
5164 /*
5165 * The maximum deviation is the sum of the interval over which we
5166 * perform the sampling and the maximum period of any sampled
5167 * clock. That's because the maximum skew between any two sampled
5168 * clock edges is when the sampled clock with the largest period is
5169 * sampled at the end of that period but right at the beginning of the
5170 * sampling interval and some other clock is sampled right at the
5171 * begining of its sampling period and right at the end of the
5172 * sampling interval. Let's assume the GPU has the longest clock
5173 * period and that the application is sampling GPU and monotonic:
5174 *
5175 * s e
5176 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
5177 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
5178 *
5179 * g
5180 * 0 1 2 3
5181 * GPU -----_____-----_____-----_____-----_____
5182 *
5183 * m
5184 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
5185 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
5186 *
5187 * Interval <----------------->
5188 * Deviation <-------------------------->
5189 *
5190 * s = read(raw) 2
5191 * g = read(GPU) 1
5192 * m = read(monotonic) 2
5193 * e = read(raw) b
5194 *
5195 * We round the sample interval up by one tick to cover sampling error
5196 * in the interval clock
5197 */
5198
5199 uint64_t sample_interval = end - begin + 1;
5200
5201 *pMaxDeviation = sample_interval + max_clock_period;
5202
5203 return VK_SUCCESS;
5204 }