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