radv: print a warning when RADV_TRAP_HANDLER is used
[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 "dirent.h"
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <linux/audit.h>
32 #include <linux/bpf.h>
33 #include <linux/filter.h>
34 #include <linux/seccomp.h>
35 #include <linux/unistd.h>
36 #include <stdatomic.h>
37 #include <stdbool.h>
38 #include <stddef.h>
39 #include <stdio.h>
40 #include <string.h>
41 #include <sys/prctl.h>
42 #include <sys/wait.h>
43 #include <unistd.h>
44 #include <fcntl.h>
45
46 #include "radv_debug.h"
47 #include "radv_private.h"
48 #include "radv_shader.h"
49 #include "radv_cs.h"
50 #include "util/disk_cache.h"
51 #include "vk_util.h"
52 #include <xf86drm.h>
53 #include <amdgpu.h>
54 #include "drm-uapi/amdgpu_drm.h"
55 #include "winsys/amdgpu/radv_amdgpu_winsys_public.h"
56 #include "winsys/null/radv_null_winsys_public.h"
57 #include "ac_llvm_util.h"
58 #include "vk_format.h"
59 #include "sid.h"
60 #include "git_sha1.h"
61 #include "util/build_id.h"
62 #include "util/debug.h"
63 #include "util/mesa-sha1.h"
64 #include "util/timespec.h"
65 #include "util/u_atomic.h"
66 #include "compiler/glsl_types.h"
67 #include "util/driconf.h"
68
69 static struct radv_timeline_point *
70 radv_timeline_find_point_at_least_locked(struct radv_device *device,
71 struct radv_timeline *timeline,
72 uint64_t p);
73
74 static struct radv_timeline_point *
75 radv_timeline_add_point_locked(struct radv_device *device,
76 struct radv_timeline *timeline,
77 uint64_t p);
78
79 static void
80 radv_timeline_trigger_waiters_locked(struct radv_timeline *timeline,
81 struct list_head *processing_list);
82
83 static
84 void radv_destroy_semaphore_part(struct radv_device *device,
85 struct radv_semaphore_part *part);
86
87 static VkResult
88 radv_create_pthread_cond(pthread_cond_t *cond);
89
90 uint64_t radv_get_current_time(void)
91 {
92 struct timespec tv;
93 clock_gettime(CLOCK_MONOTONIC, &tv);
94 return tv.tv_nsec + tv.tv_sec*1000000000ull;
95 }
96
97 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
98 {
99 uint64_t current_time = radv_get_current_time();
100
101 timeout = MIN2(UINT64_MAX - current_time, timeout);
102
103 return current_time + timeout;
104 }
105
106 static int
107 radv_device_get_cache_uuid(enum radeon_family family, void *uuid)
108 {
109 struct mesa_sha1 ctx;
110 unsigned char sha1[20];
111 unsigned ptr_size = sizeof(void*);
112
113 memset(uuid, 0, VK_UUID_SIZE);
114 _mesa_sha1_init(&ctx);
115
116 if (!disk_cache_get_function_identifier(radv_device_get_cache_uuid, &ctx) ||
117 !disk_cache_get_function_identifier(LLVMInitializeAMDGPUTargetInfo, &ctx))
118 return -1;
119
120 _mesa_sha1_update(&ctx, &family, sizeof(family));
121 _mesa_sha1_update(&ctx, &ptr_size, sizeof(ptr_size));
122 _mesa_sha1_final(&ctx, sha1);
123
124 memcpy(uuid, sha1, VK_UUID_SIZE);
125 return 0;
126 }
127
128 static void
129 radv_get_driver_uuid(void *uuid)
130 {
131 ac_compute_driver_uuid(uuid, VK_UUID_SIZE);
132 }
133
134 static void
135 radv_get_device_uuid(struct radeon_info *info, void *uuid)
136 {
137 ac_compute_device_uuid(info, uuid, VK_UUID_SIZE);
138 }
139
140 static uint64_t
141 radv_get_visible_vram_size(struct radv_physical_device *device)
142 {
143 return MIN2(device->rad_info.vram_size, device->rad_info.vram_vis_size);
144 }
145
146 static uint64_t
147 radv_get_vram_size(struct radv_physical_device *device)
148 {
149 return device->rad_info.vram_size - radv_get_visible_vram_size(device);
150 }
151
152 static void
153 radv_physical_device_init_mem_types(struct radv_physical_device *device)
154 {
155 uint64_t visible_vram_size = radv_get_visible_vram_size(device);
156 uint64_t vram_size = radv_get_vram_size(device);
157 int vram_index = -1, visible_vram_index = -1, gart_index = -1;
158 device->memory_properties.memoryHeapCount = 0;
159 if (vram_size > 0) {
160 vram_index = device->memory_properties.memoryHeapCount++;
161 device->memory_properties.memoryHeaps[vram_index] = (VkMemoryHeap) {
162 .size = vram_size,
163 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
164 };
165 }
166
167 if (device->rad_info.gart_size > 0) {
168 gart_index = device->memory_properties.memoryHeapCount++;
169 device->memory_properties.memoryHeaps[gart_index] = (VkMemoryHeap) {
170 .size = device->rad_info.gart_size,
171 .flags = 0,
172 };
173 }
174
175 if (visible_vram_size) {
176 visible_vram_index = device->memory_properties.memoryHeapCount++;
177 device->memory_properties.memoryHeaps[visible_vram_index] = (VkMemoryHeap) {
178 .size = visible_vram_size,
179 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
180 };
181 }
182
183 unsigned type_count = 0;
184
185 if (vram_index >= 0 || visible_vram_index >= 0) {
186 device->memory_domains[type_count] = RADEON_DOMAIN_VRAM;
187 device->memory_flags[type_count] = RADEON_FLAG_NO_CPU_ACCESS;
188 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
189 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
190 .heapIndex = vram_index >= 0 ? vram_index : visible_vram_index,
191 };
192 }
193
194 if (gart_index >= 0) {
195 device->memory_domains[type_count] = RADEON_DOMAIN_GTT;
196 device->memory_flags[type_count] = RADEON_FLAG_GTT_WC | RADEON_FLAG_CPU_ACCESS;
197 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
198 .propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
199 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
200 .heapIndex = gart_index,
201 };
202 }
203 if (visible_vram_index >= 0) {
204 device->memory_domains[type_count] = RADEON_DOMAIN_VRAM;
205 device->memory_flags[type_count] = RADEON_FLAG_CPU_ACCESS;
206 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
207 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
208 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
209 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
210 .heapIndex = visible_vram_index,
211 };
212 }
213
214 if (gart_index >= 0) {
215 device->memory_domains[type_count] = RADEON_DOMAIN_GTT;
216 device->memory_flags[type_count] = RADEON_FLAG_CPU_ACCESS;
217 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
218 .propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
219 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
220 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
221 .heapIndex = gart_index,
222 };
223 }
224 device->memory_properties.memoryTypeCount = type_count;
225
226 if (device->rad_info.has_l2_uncached) {
227 for (int i = 0; i < device->memory_properties.memoryTypeCount; i++) {
228 VkMemoryType mem_type = device->memory_properties.memoryTypes[i];
229
230 if ((mem_type.propertyFlags & (VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
231 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) ||
232 mem_type.propertyFlags == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
233
234 VkMemoryPropertyFlags property_flags = mem_type.propertyFlags |
235 VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD |
236 VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD;
237
238 device->memory_domains[type_count] = device->memory_domains[i];
239 device->memory_flags[type_count] = device->memory_flags[i] | RADEON_FLAG_VA_UNCACHED;
240 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
241 .propertyFlags = property_flags,
242 .heapIndex = mem_type.heapIndex,
243 };
244 }
245 }
246 device->memory_properties.memoryTypeCount = type_count;
247 }
248 }
249
250 static const char *
251 radv_get_compiler_string(struct radv_physical_device *pdevice)
252 {
253 if (!pdevice->use_llvm) {
254 /* Some games like SotTR apply shader workarounds if the LLVM
255 * version is too old or if the LLVM version string is
256 * missing. This gives 2-5% performance with SotTR and ACO.
257 */
258 if (driQueryOptionb(&pdevice->instance->dri_options,
259 "radv_report_llvm9_version_string")) {
260 return "ACO/LLVM 9.0.1";
261 }
262
263 return "ACO";
264 }
265
266 return "LLVM " MESA_LLVM_VERSION_STRING;
267 }
268
269 static VkResult
270 radv_physical_device_try_create(struct radv_instance *instance,
271 drmDevicePtr drm_device,
272 struct radv_physical_device **device_out)
273 {
274 VkResult result;
275 int fd = -1;
276 int master_fd = -1;
277
278 if (drm_device) {
279 const char *path = drm_device->nodes[DRM_NODE_RENDER];
280 drmVersionPtr version;
281
282 fd = open(path, O_RDWR | O_CLOEXEC);
283 if (fd < 0) {
284 if (instance->debug_flags & RADV_DEBUG_STARTUP)
285 radv_logi("Could not open device '%s'", path);
286
287 return vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
288 }
289
290 version = drmGetVersion(fd);
291 if (!version) {
292 close(fd);
293
294 if (instance->debug_flags & RADV_DEBUG_STARTUP)
295 radv_logi("Could not get the kernel driver version for device '%s'", path);
296
297 return vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
298 "failed to get version %s: %m", path);
299 }
300
301 if (strcmp(version->name, "amdgpu")) {
302 drmFreeVersion(version);
303 close(fd);
304
305 if (instance->debug_flags & RADV_DEBUG_STARTUP)
306 radv_logi("Device '%s' is not using the amdgpu kernel driver.", path);
307
308 return VK_ERROR_INCOMPATIBLE_DRIVER;
309 }
310 drmFreeVersion(version);
311
312 if (instance->debug_flags & RADV_DEBUG_STARTUP)
313 radv_logi("Found compatible device '%s'.", path);
314 }
315
316 struct radv_physical_device *device =
317 vk_zalloc2(&instance->alloc, NULL, sizeof(*device), 8,
318 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
319 if (!device) {
320 result = vk_error(instance, VK_ERROR_OUT_OF_HOST_MEMORY);
321 goto fail_fd;
322 }
323
324 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
325 device->instance = instance;
326
327 if (drm_device) {
328 device->ws = radv_amdgpu_winsys_create(fd, instance->debug_flags,
329 instance->perftest_flags);
330 } else {
331 device->ws = radv_null_winsys_create();
332 }
333
334 if (!device->ws) {
335 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
336 "failed to initialize winsys");
337 goto fail_alloc;
338 }
339
340 if (drm_device && instance->enabled_extensions.KHR_display) {
341 master_fd = open(drm_device->nodes[DRM_NODE_PRIMARY], O_RDWR | O_CLOEXEC);
342 if (master_fd >= 0) {
343 uint32_t accel_working = 0;
344 struct drm_amdgpu_info request = {
345 .return_pointer = (uintptr_t)&accel_working,
346 .return_size = sizeof(accel_working),
347 .query = AMDGPU_INFO_ACCEL_WORKING
348 };
349
350 if (drmCommandWrite(master_fd, DRM_AMDGPU_INFO, &request, sizeof (struct drm_amdgpu_info)) < 0 || !accel_working) {
351 close(master_fd);
352 master_fd = -1;
353 }
354 }
355 }
356
357 device->master_fd = master_fd;
358 device->local_fd = fd;
359 device->ws->query_info(device->ws, &device->rad_info);
360
361 device->use_llvm = instance->debug_flags & RADV_DEBUG_LLVM;
362
363 snprintf(device->name, sizeof(device->name),
364 "AMD RADV %s (%s)",
365 device->rad_info.name, radv_get_compiler_string(device));
366
367 if (radv_device_get_cache_uuid(device->rad_info.family, device->cache_uuid)) {
368 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
369 "cannot generate UUID");
370 goto fail_wsi;
371 }
372
373 /* These flags affect shader compilation. */
374 uint64_t shader_env_flags = (device->use_llvm ? 0 : 0x2);
375
376 /* The gpu id is already embedded in the uuid so we just pass "radv"
377 * when creating the cache.
378 */
379 char buf[VK_UUID_SIZE * 2 + 1];
380 disk_cache_format_hex_id(buf, device->cache_uuid, VK_UUID_SIZE * 2);
381 device->disk_cache = disk_cache_create(device->name, buf, shader_env_flags);
382
383 if (device->rad_info.chip_class < GFX8)
384 fprintf(stderr, "WARNING: radv is not a conformant vulkan implementation, testing use only.\n");
385
386 radv_get_driver_uuid(&device->driver_uuid);
387 radv_get_device_uuid(&device->rad_info, &device->device_uuid);
388
389 device->out_of_order_rast_allowed = device->rad_info.has_out_of_order_rast &&
390 !(device->instance->debug_flags & RADV_DEBUG_NO_OUT_OF_ORDER);
391
392 device->dcc_msaa_allowed =
393 (device->instance->perftest_flags & RADV_PERFTEST_DCC_MSAA);
394
395 device->use_ngg = device->rad_info.chip_class >= GFX10 &&
396 device->rad_info.family != CHIP_NAVI14 &&
397 !(device->instance->debug_flags & RADV_DEBUG_NO_NGG);
398
399 /* TODO: Implement NGG GS with ACO. */
400 device->use_ngg_gs = device->use_ngg && device->use_llvm;
401 device->use_ngg_streamout = false;
402
403 /* Determine the number of threads per wave for all stages. */
404 device->cs_wave_size = 64;
405 device->ps_wave_size = 64;
406 device->ge_wave_size = 64;
407
408 if (device->rad_info.chip_class >= GFX10) {
409 if (device->instance->perftest_flags & RADV_PERFTEST_CS_WAVE_32)
410 device->cs_wave_size = 32;
411
412 /* For pixel shaders, wave64 is recommanded. */
413 if (device->instance->perftest_flags & RADV_PERFTEST_PS_WAVE_32)
414 device->ps_wave_size = 32;
415
416 if (device->instance->perftest_flags & RADV_PERFTEST_GE_WAVE_32)
417 device->ge_wave_size = 32;
418 }
419
420 radv_physical_device_init_mem_types(device);
421
422 radv_physical_device_get_supported_extensions(device,
423 &device->supported_extensions);
424
425 if (drm_device)
426 device->bus_info = *drm_device->businfo.pci;
427
428 if ((device->instance->debug_flags & RADV_DEBUG_INFO))
429 ac_print_gpu_info(&device->rad_info);
430
431 /* The WSI is structured as a layer on top of the driver, so this has
432 * to be the last part of initialization (at least until we get other
433 * semi-layers).
434 */
435 result = radv_init_wsi(device);
436 if (result != VK_SUCCESS) {
437 vk_error(instance, result);
438 goto fail_disk_cache;
439 }
440
441 *device_out = device;
442
443 return VK_SUCCESS;
444
445 fail_disk_cache:
446 disk_cache_destroy(device->disk_cache);
447 fail_wsi:
448 device->ws->destroy(device->ws);
449 fail_alloc:
450 vk_free(&instance->alloc, device);
451 fail_fd:
452 if (fd != -1)
453 close(fd);
454 if (master_fd != -1)
455 close(master_fd);
456 return result;
457 }
458
459 static void
460 radv_physical_device_destroy(struct radv_physical_device *device)
461 {
462 radv_finish_wsi(device);
463 device->ws->destroy(device->ws);
464 disk_cache_destroy(device->disk_cache);
465 close(device->local_fd);
466 if (device->master_fd != -1)
467 close(device->master_fd);
468 vk_free(&device->instance->alloc, device);
469 }
470
471 static void *
472 default_alloc_func(void *pUserData, size_t size, size_t align,
473 VkSystemAllocationScope allocationScope)
474 {
475 return malloc(size);
476 }
477
478 static void *
479 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
480 size_t align, VkSystemAllocationScope allocationScope)
481 {
482 return realloc(pOriginal, size);
483 }
484
485 static void
486 default_free_func(void *pUserData, void *pMemory)
487 {
488 free(pMemory);
489 }
490
491 static const VkAllocationCallbacks default_alloc = {
492 .pUserData = NULL,
493 .pfnAllocation = default_alloc_func,
494 .pfnReallocation = default_realloc_func,
495 .pfnFree = default_free_func,
496 };
497
498 static const struct debug_control radv_debug_options[] = {
499 {"nofastclears", RADV_DEBUG_NO_FAST_CLEARS},
500 {"nodcc", RADV_DEBUG_NO_DCC},
501 {"shaders", RADV_DEBUG_DUMP_SHADERS},
502 {"nocache", RADV_DEBUG_NO_CACHE},
503 {"shaderstats", RADV_DEBUG_DUMP_SHADER_STATS},
504 {"nohiz", RADV_DEBUG_NO_HIZ},
505 {"nocompute", RADV_DEBUG_NO_COMPUTE_QUEUE},
506 {"allbos", RADV_DEBUG_ALL_BOS},
507 {"noibs", RADV_DEBUG_NO_IBS},
508 {"spirv", RADV_DEBUG_DUMP_SPIRV},
509 {"vmfaults", RADV_DEBUG_VM_FAULTS},
510 {"zerovram", RADV_DEBUG_ZERO_VRAM},
511 {"syncshaders", RADV_DEBUG_SYNC_SHADERS},
512 {"preoptir", RADV_DEBUG_PREOPTIR},
513 {"nodynamicbounds", RADV_DEBUG_NO_DYNAMIC_BOUNDS},
514 {"nooutoforder", RADV_DEBUG_NO_OUT_OF_ORDER},
515 {"info", RADV_DEBUG_INFO},
516 {"errors", RADV_DEBUG_ERRORS},
517 {"startup", RADV_DEBUG_STARTUP},
518 {"checkir", RADV_DEBUG_CHECKIR},
519 {"nothreadllvm", RADV_DEBUG_NOTHREADLLVM},
520 {"nobinning", RADV_DEBUG_NOBINNING},
521 {"nongg", RADV_DEBUG_NO_NGG},
522 {"allentrypoints", RADV_DEBUG_ALL_ENTRYPOINTS},
523 {"metashaders", RADV_DEBUG_DUMP_META_SHADERS},
524 {"nomemorycache", RADV_DEBUG_NO_MEMORY_CACHE},
525 {"llvm", RADV_DEBUG_LLVM},
526 {"forcecompress", RADV_DEBUG_FORCE_COMPRESS},
527 {NULL, 0}
528 };
529
530 const char *
531 radv_get_debug_option_name(int id)
532 {
533 assert(id < ARRAY_SIZE(radv_debug_options) - 1);
534 return radv_debug_options[id].string;
535 }
536
537 static const struct debug_control radv_perftest_options[] = {
538 {"localbos", RADV_PERFTEST_LOCAL_BOS},
539 {"dccmsaa", RADV_PERFTEST_DCC_MSAA},
540 {"bolist", RADV_PERFTEST_BO_LIST},
541 {"tccompatcmask", RADV_PERFTEST_TC_COMPAT_CMASK},
542 {"cswave32", RADV_PERFTEST_CS_WAVE_32},
543 {"pswave32", RADV_PERFTEST_PS_WAVE_32},
544 {"gewave32", RADV_PERFTEST_GE_WAVE_32},
545 {"dfsm", RADV_PERFTEST_DFSM},
546 {NULL, 0}
547 };
548
549 const char *
550 radv_get_perftest_option_name(int id)
551 {
552 assert(id < ARRAY_SIZE(radv_perftest_options) - 1);
553 return radv_perftest_options[id].string;
554 }
555
556 static void
557 radv_handle_per_app_options(struct radv_instance *instance,
558 const VkApplicationInfo *info)
559 {
560 const char *name = info ? info->pApplicationName : NULL;
561 const char *engine_name = info ? info->pEngineName : NULL;
562
563 if (name) {
564 if (!strcmp(name, "DOOM_VFR")) {
565 /* Work around a Doom VFR game bug */
566 instance->debug_flags |= RADV_DEBUG_NO_DYNAMIC_BOUNDS;
567 } else if (!strcmp(name, "Fledge")) {
568 /*
569 * Zero VRAM for "The Surge 2"
570 *
571 * This avoid a hang when when rendering any level. Likely
572 * uninitialized data in an indirect draw.
573 */
574 instance->debug_flags |= RADV_DEBUG_ZERO_VRAM;
575 } else if (!strcmp(name, "No Man's Sky")) {
576 /* Work around a NMS game bug */
577 instance->debug_flags |= RADV_DEBUG_DISCARD_TO_DEMOTE;
578 } else if (!strcmp(name, "DOOMEternal")) {
579 /* Zero VRAM for Doom Eternal to fix rendering issues. */
580 instance->debug_flags |= RADV_DEBUG_ZERO_VRAM;
581 } else if (!strcmp(name, "Red Dead Redemption 2")) {
582 /* Work around a RDR2 game bug */
583 instance->debug_flags |= RADV_DEBUG_DISCARD_TO_DEMOTE;
584 }
585 }
586
587 if (engine_name) {
588 if (!strcmp(engine_name, "vkd3d")) {
589 /* Zero VRAM for all VKD3D (DX12->VK) games to fix
590 * rendering issues.
591 */
592 instance->debug_flags |= RADV_DEBUG_ZERO_VRAM;
593 } else if (!strcmp(engine_name, "Quantic Dream Engine")) {
594 /* Fix various artifacts in Detroit: Become Human */
595 instance->debug_flags |= RADV_DEBUG_ZERO_VRAM |
596 RADV_DEBUG_DISCARD_TO_DEMOTE;
597 }
598 }
599
600 instance->enable_mrt_output_nan_fixup =
601 driQueryOptionb(&instance->dri_options,
602 "radv_enable_mrt_output_nan_fixup");
603
604 if (driQueryOptionb(&instance->dri_options, "radv_no_dynamic_bounds"))
605 instance->debug_flags |= RADV_DEBUG_NO_DYNAMIC_BOUNDS;
606 }
607
608 static const char radv_dri_options_xml[] =
609 DRI_CONF_BEGIN
610 DRI_CONF_SECTION_PERFORMANCE
611 DRI_CONF_ADAPTIVE_SYNC("true")
612 DRI_CONF_VK_X11_OVERRIDE_MIN_IMAGE_COUNT(0)
613 DRI_CONF_VK_X11_STRICT_IMAGE_COUNT("false")
614 DRI_CONF_VK_X11_ENSURE_MIN_IMAGE_COUNT("false")
615 DRI_CONF_RADV_REPORT_LLVM9_VERSION_STRING("false")
616 DRI_CONF_RADV_ENABLE_MRT_OUTPUT_NAN_FIXUP("false")
617 DRI_CONF_RADV_NO_DYNAMIC_BOUNDS("false")
618 DRI_CONF_RADV_OVERRIDE_UNIFORM_OFFSET_ALIGNMENT(0)
619 DRI_CONF_SECTION_END
620
621 DRI_CONF_SECTION_DEBUG
622 DRI_CONF_VK_WSI_FORCE_BGRA8_UNORM_FIRST("false")
623 DRI_CONF_SECTION_END
624 DRI_CONF_END;
625
626 static void radv_init_dri_options(struct radv_instance *instance)
627 {
628 driParseOptionInfo(&instance->available_dri_options, radv_dri_options_xml);
629 driParseConfigFiles(&instance->dri_options,
630 &instance->available_dri_options,
631 0, "radv", NULL,
632 instance->applicationName,
633 instance->applicationVersion,
634 instance->engineName,
635 instance->engineVersion);
636 }
637
638 VkResult radv_CreateInstance(
639 const VkInstanceCreateInfo* pCreateInfo,
640 const VkAllocationCallbacks* pAllocator,
641 VkInstance* pInstance)
642 {
643 struct radv_instance *instance;
644 VkResult result;
645
646 instance = vk_zalloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
647 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
648 if (!instance)
649 return vk_error(NULL, VK_ERROR_OUT_OF_HOST_MEMORY);
650
651 vk_object_base_init(NULL, &instance->base, VK_OBJECT_TYPE_INSTANCE);
652
653 if (pAllocator)
654 instance->alloc = *pAllocator;
655 else
656 instance->alloc = default_alloc;
657
658 if (pCreateInfo->pApplicationInfo) {
659 const VkApplicationInfo *app = pCreateInfo->pApplicationInfo;
660
661 instance->applicationName =
662 vk_strdup(&instance->alloc, app->pApplicationName,
663 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
664 instance->applicationVersion = app->applicationVersion;
665
666 instance->engineName =
667 vk_strdup(&instance->alloc, app->pEngineName,
668 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
669 instance->engineVersion = app->engineVersion;
670 instance->apiVersion = app->apiVersion;
671 }
672
673 if (instance->apiVersion == 0)
674 instance->apiVersion = VK_API_VERSION_1_0;
675
676 instance->debug_flags = parse_debug_string(getenv("RADV_DEBUG"),
677 radv_debug_options);
678
679 const char *radv_perftest_str = getenv("RADV_PERFTEST");
680 instance->perftest_flags = parse_debug_string(radv_perftest_str,
681 radv_perftest_options);
682
683 if (radv_perftest_str) {
684 /* Output warnings for famous RADV_PERFTEST options that no
685 * longer exist or are deprecated.
686 */
687 if (strstr(radv_perftest_str, "aco")) {
688 fprintf(stderr, "*******************************************************************************\n");
689 fprintf(stderr, "* WARNING: Unknown option RADV_PERFTEST='aco'. ACO is enabled by default now. *\n");
690 fprintf(stderr, "*******************************************************************************\n");
691 }
692 if (strstr(radv_perftest_str, "llvm")) {
693 fprintf(stderr, "*********************************************************************************\n");
694 fprintf(stderr, "* WARNING: Unknown option 'RADV_PERFTEST=llvm'. Did you mean 'RADV_DEBUG=llvm'? *\n");
695 fprintf(stderr, "*********************************************************************************\n");
696 abort();
697 }
698 }
699
700 if (instance->debug_flags & RADV_DEBUG_STARTUP)
701 radv_logi("Created an instance");
702
703 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
704 int idx;
705 for (idx = 0; idx < RADV_INSTANCE_EXTENSION_COUNT; idx++) {
706 if (!strcmp(pCreateInfo->ppEnabledExtensionNames[i],
707 radv_instance_extensions[idx].extensionName))
708 break;
709 }
710
711 if (idx >= RADV_INSTANCE_EXTENSION_COUNT ||
712 !radv_instance_extensions_supported.extensions[idx]) {
713 vk_object_base_finish(&instance->base);
714 vk_free2(&default_alloc, pAllocator, instance);
715 return vk_error(instance, VK_ERROR_EXTENSION_NOT_PRESENT);
716 }
717
718 instance->enabled_extensions.extensions[idx] = true;
719 }
720
721 bool unchecked = instance->debug_flags & RADV_DEBUG_ALL_ENTRYPOINTS;
722
723 for (unsigned i = 0; i < ARRAY_SIZE(instance->dispatch.entrypoints); i++) {
724 /* Vulkan requires that entrypoints for extensions which have
725 * not been enabled must not be advertised.
726 */
727 if (!unchecked &&
728 !radv_instance_entrypoint_is_enabled(i, instance->apiVersion,
729 &instance->enabled_extensions)) {
730 instance->dispatch.entrypoints[i] = NULL;
731 } else {
732 instance->dispatch.entrypoints[i] =
733 radv_instance_dispatch_table.entrypoints[i];
734 }
735 }
736
737 for (unsigned i = 0; i < ARRAY_SIZE(instance->physical_device_dispatch.entrypoints); i++) {
738 /* Vulkan requires that entrypoints for extensions which have
739 * not been enabled must not be advertised.
740 */
741 if (!unchecked &&
742 !radv_physical_device_entrypoint_is_enabled(i, instance->apiVersion,
743 &instance->enabled_extensions)) {
744 instance->physical_device_dispatch.entrypoints[i] = NULL;
745 } else {
746 instance->physical_device_dispatch.entrypoints[i] =
747 radv_physical_device_dispatch_table.entrypoints[i];
748 }
749 }
750
751 for (unsigned i = 0; i < ARRAY_SIZE(instance->device_dispatch.entrypoints); i++) {
752 /* Vulkan requires that entrypoints for extensions which have
753 * not been enabled must not be advertised.
754 */
755 if (!unchecked &&
756 !radv_device_entrypoint_is_enabled(i, instance->apiVersion,
757 &instance->enabled_extensions, NULL)) {
758 instance->device_dispatch.entrypoints[i] = NULL;
759 } else {
760 instance->device_dispatch.entrypoints[i] =
761 radv_device_dispatch_table.entrypoints[i];
762 }
763 }
764
765 instance->physical_devices_enumerated = false;
766 list_inithead(&instance->physical_devices);
767
768 result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
769 if (result != VK_SUCCESS) {
770 vk_object_base_finish(&instance->base);
771 vk_free2(&default_alloc, pAllocator, instance);
772 return vk_error(instance, result);
773 }
774
775 glsl_type_singleton_init_or_ref();
776
777 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
778
779 radv_init_dri_options(instance);
780 radv_handle_per_app_options(instance, pCreateInfo->pApplicationInfo);
781
782 *pInstance = radv_instance_to_handle(instance);
783
784 return VK_SUCCESS;
785 }
786
787 void radv_DestroyInstance(
788 VkInstance _instance,
789 const VkAllocationCallbacks* pAllocator)
790 {
791 RADV_FROM_HANDLE(radv_instance, instance, _instance);
792
793 if (!instance)
794 return;
795
796 list_for_each_entry_safe(struct radv_physical_device, pdevice,
797 &instance->physical_devices, link) {
798 radv_physical_device_destroy(pdevice);
799 }
800
801 vk_free(&instance->alloc, instance->engineName);
802 vk_free(&instance->alloc, instance->applicationName);
803
804 VG(VALGRIND_DESTROY_MEMPOOL(instance));
805
806 glsl_type_singleton_decref();
807
808 driDestroyOptionCache(&instance->dri_options);
809 driDestroyOptionInfo(&instance->available_dri_options);
810
811 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
812
813 vk_object_base_finish(&instance->base);
814 vk_free(&instance->alloc, instance);
815 }
816
817 static VkResult
818 radv_enumerate_physical_devices(struct radv_instance *instance)
819 {
820 if (instance->physical_devices_enumerated)
821 return VK_SUCCESS;
822
823 instance->physical_devices_enumerated = true;
824
825 /* TODO: Check for more devices ? */
826 drmDevicePtr devices[8];
827 VkResult result = VK_SUCCESS;
828 int max_devices;
829
830 if (getenv("RADV_FORCE_FAMILY")) {
831 /* When RADV_FORCE_FAMILY is set, the driver creates a nul
832 * device that allows to test the compiler without having an
833 * AMDGPU instance.
834 */
835 struct radv_physical_device *pdevice;
836
837 result = radv_physical_device_try_create(instance, NULL, &pdevice);
838 if (result != VK_SUCCESS)
839 return result;
840
841 list_addtail(&pdevice->link, &instance->physical_devices);
842 return VK_SUCCESS;
843 }
844
845 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
846
847 if (instance->debug_flags & RADV_DEBUG_STARTUP)
848 radv_logi("Found %d drm nodes", max_devices);
849
850 if (max_devices < 1)
851 return vk_error(instance, VK_SUCCESS);
852
853 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
854 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
855 devices[i]->bustype == DRM_BUS_PCI &&
856 devices[i]->deviceinfo.pci->vendor_id == ATI_VENDOR_ID) {
857
858 struct radv_physical_device *pdevice;
859 result = radv_physical_device_try_create(instance, devices[i],
860 &pdevice);
861 /* Incompatible DRM device, skip. */
862 if (result == VK_ERROR_INCOMPATIBLE_DRIVER) {
863 result = VK_SUCCESS;
864 continue;
865 }
866
867 /* Error creating the physical device, report the error. */
868 if (result != VK_SUCCESS)
869 break;
870
871 list_addtail(&pdevice->link, &instance->physical_devices);
872 }
873 }
874 drmFreeDevices(devices, max_devices);
875
876 /* If we successfully enumerated any devices, call it success */
877 return result;
878 }
879
880 VkResult radv_EnumeratePhysicalDevices(
881 VkInstance _instance,
882 uint32_t* pPhysicalDeviceCount,
883 VkPhysicalDevice* pPhysicalDevices)
884 {
885 RADV_FROM_HANDLE(radv_instance, instance, _instance);
886 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
887
888 VkResult result = radv_enumerate_physical_devices(instance);
889 if (result != VK_SUCCESS)
890 return result;
891
892 list_for_each_entry(struct radv_physical_device, pdevice,
893 &instance->physical_devices, link) {
894 vk_outarray_append(&out, i) {
895 *i = radv_physical_device_to_handle(pdevice);
896 }
897 }
898
899 return vk_outarray_status(&out);
900 }
901
902 VkResult radv_EnumeratePhysicalDeviceGroups(
903 VkInstance _instance,
904 uint32_t* pPhysicalDeviceGroupCount,
905 VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties)
906 {
907 RADV_FROM_HANDLE(radv_instance, instance, _instance);
908 VK_OUTARRAY_MAKE(out, pPhysicalDeviceGroupProperties,
909 pPhysicalDeviceGroupCount);
910
911 VkResult result = radv_enumerate_physical_devices(instance);
912 if (result != VK_SUCCESS)
913 return result;
914
915 list_for_each_entry(struct radv_physical_device, pdevice,
916 &instance->physical_devices, link) {
917 vk_outarray_append(&out, p) {
918 p->physicalDeviceCount = 1;
919 memset(p->physicalDevices, 0, sizeof(p->physicalDevices));
920 p->physicalDevices[0] = radv_physical_device_to_handle(pdevice);
921 p->subsetAllocation = false;
922 }
923 }
924
925 return vk_outarray_status(&out);
926 }
927
928 void radv_GetPhysicalDeviceFeatures(
929 VkPhysicalDevice physicalDevice,
930 VkPhysicalDeviceFeatures* pFeatures)
931 {
932 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
933 memset(pFeatures, 0, sizeof(*pFeatures));
934
935 *pFeatures = (VkPhysicalDeviceFeatures) {
936 .robustBufferAccess = true,
937 .fullDrawIndexUint32 = true,
938 .imageCubeArray = true,
939 .independentBlend = true,
940 .geometryShader = true,
941 .tessellationShader = true,
942 .sampleRateShading = true,
943 .dualSrcBlend = true,
944 .logicOp = true,
945 .multiDrawIndirect = true,
946 .drawIndirectFirstInstance = true,
947 .depthClamp = true,
948 .depthBiasClamp = true,
949 .fillModeNonSolid = true,
950 .depthBounds = true,
951 .wideLines = true,
952 .largePoints = true,
953 .alphaToOne = true,
954 .multiViewport = true,
955 .samplerAnisotropy = true,
956 .textureCompressionETC2 = radv_device_supports_etc(pdevice),
957 .textureCompressionASTC_LDR = false,
958 .textureCompressionBC = true,
959 .occlusionQueryPrecise = true,
960 .pipelineStatisticsQuery = true,
961 .vertexPipelineStoresAndAtomics = true,
962 .fragmentStoresAndAtomics = true,
963 .shaderTessellationAndGeometryPointSize = true,
964 .shaderImageGatherExtended = true,
965 .shaderStorageImageExtendedFormats = true,
966 .shaderStorageImageMultisample = true,
967 .shaderUniformBufferArrayDynamicIndexing = true,
968 .shaderSampledImageArrayDynamicIndexing = true,
969 .shaderStorageBufferArrayDynamicIndexing = true,
970 .shaderStorageImageArrayDynamicIndexing = true,
971 .shaderStorageImageReadWithoutFormat = true,
972 .shaderStorageImageWriteWithoutFormat = true,
973 .shaderClipDistance = true,
974 .shaderCullDistance = true,
975 .shaderFloat64 = true,
976 .shaderInt64 = true,
977 .shaderInt16 = true,
978 .sparseBinding = true,
979 .variableMultisampleRate = true,
980 .shaderResourceMinLod = true,
981 .inheritedQueries = true,
982 };
983 }
984
985 static void
986 radv_get_physical_device_features_1_1(struct radv_physical_device *pdevice,
987 VkPhysicalDeviceVulkan11Features *f)
988 {
989 assert(f->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
990
991 f->storageBuffer16BitAccess = true;
992 f->uniformAndStorageBuffer16BitAccess = true;
993 f->storagePushConstant16 = true;
994 f->storageInputOutput16 = pdevice->rad_info.has_packed_math_16bit && (LLVM_VERSION_MAJOR >= 9 || !pdevice->use_llvm);
995 f->multiview = true;
996 f->multiviewGeometryShader = true;
997 f->multiviewTessellationShader = true;
998 f->variablePointersStorageBuffer = true;
999 f->variablePointers = true;
1000 f->protectedMemory = false;
1001 f->samplerYcbcrConversion = true;
1002 f->shaderDrawParameters = true;
1003 }
1004
1005 static void
1006 radv_get_physical_device_features_1_2(struct radv_physical_device *pdevice,
1007 VkPhysicalDeviceVulkan12Features *f)
1008 {
1009 assert(f->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES);
1010
1011 f->samplerMirrorClampToEdge = true;
1012 f->drawIndirectCount = true;
1013 f->storageBuffer8BitAccess = true;
1014 f->uniformAndStorageBuffer8BitAccess = true;
1015 f->storagePushConstant8 = true;
1016 f->shaderBufferInt64Atomics = LLVM_VERSION_MAJOR >= 9 || !pdevice->use_llvm;
1017 f->shaderSharedInt64Atomics = LLVM_VERSION_MAJOR >= 9 || !pdevice->use_llvm;
1018 f->shaderFloat16 = pdevice->rad_info.has_packed_math_16bit;
1019 f->shaderInt8 = true;
1020
1021 f->descriptorIndexing = true;
1022 f->shaderInputAttachmentArrayDynamicIndexing = true;
1023 f->shaderUniformTexelBufferArrayDynamicIndexing = true;
1024 f->shaderStorageTexelBufferArrayDynamicIndexing = true;
1025 f->shaderUniformBufferArrayNonUniformIndexing = true;
1026 f->shaderSampledImageArrayNonUniformIndexing = true;
1027 f->shaderStorageBufferArrayNonUniformIndexing = true;
1028 f->shaderStorageImageArrayNonUniformIndexing = true;
1029 f->shaderInputAttachmentArrayNonUniformIndexing = true;
1030 f->shaderUniformTexelBufferArrayNonUniformIndexing = true;
1031 f->shaderStorageTexelBufferArrayNonUniformIndexing = true;
1032 f->descriptorBindingUniformBufferUpdateAfterBind = true;
1033 f->descriptorBindingSampledImageUpdateAfterBind = true;
1034 f->descriptorBindingStorageImageUpdateAfterBind = true;
1035 f->descriptorBindingStorageBufferUpdateAfterBind = true;
1036 f->descriptorBindingUniformTexelBufferUpdateAfterBind = true;
1037 f->descriptorBindingStorageTexelBufferUpdateAfterBind = true;
1038 f->descriptorBindingUpdateUnusedWhilePending = true;
1039 f->descriptorBindingPartiallyBound = true;
1040 f->descriptorBindingVariableDescriptorCount = true;
1041 f->runtimeDescriptorArray = true;
1042
1043 f->samplerFilterMinmax = true;
1044 f->scalarBlockLayout = pdevice->rad_info.chip_class >= GFX7;
1045 f->imagelessFramebuffer = true;
1046 f->uniformBufferStandardLayout = true;
1047 f->shaderSubgroupExtendedTypes = true;
1048 f->separateDepthStencilLayouts = true;
1049 f->hostQueryReset = true;
1050 f->timelineSemaphore = pdevice->rad_info.has_syncobj_wait_for_submit;
1051 f->bufferDeviceAddress = true;
1052 f->bufferDeviceAddressCaptureReplay = false;
1053 f->bufferDeviceAddressMultiDevice = false;
1054 f->vulkanMemoryModel = true;
1055 f->vulkanMemoryModelDeviceScope = true;
1056 f->vulkanMemoryModelAvailabilityVisibilityChains = false;
1057 f->shaderOutputViewportIndex = true;
1058 f->shaderOutputLayer = true;
1059 f->subgroupBroadcastDynamicId = true;
1060 }
1061
1062 void radv_GetPhysicalDeviceFeatures2(
1063 VkPhysicalDevice physicalDevice,
1064 VkPhysicalDeviceFeatures2 *pFeatures)
1065 {
1066 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1067 radv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
1068
1069 VkPhysicalDeviceVulkan11Features core_1_1 = {
1070 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES,
1071 };
1072 radv_get_physical_device_features_1_1(pdevice, &core_1_1);
1073
1074 VkPhysicalDeviceVulkan12Features core_1_2 = {
1075 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES,
1076 };
1077 radv_get_physical_device_features_1_2(pdevice, &core_1_2);
1078
1079 #define CORE_FEATURE(major, minor, feature) \
1080 features->feature = core_##major##_##minor.feature
1081
1082 vk_foreach_struct(ext, pFeatures->pNext) {
1083 switch (ext->sType) {
1084 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES: {
1085 VkPhysicalDeviceVariablePointersFeatures *features = (void *)ext;
1086 CORE_FEATURE(1, 1, variablePointersStorageBuffer);
1087 CORE_FEATURE(1, 1, variablePointers);
1088 break;
1089 }
1090 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
1091 VkPhysicalDeviceMultiviewFeatures *features = (VkPhysicalDeviceMultiviewFeatures*)ext;
1092 CORE_FEATURE(1, 1, multiview);
1093 CORE_FEATURE(1, 1, multiviewGeometryShader);
1094 CORE_FEATURE(1, 1, multiviewTessellationShader);
1095 break;
1096 }
1097 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES: {
1098 VkPhysicalDeviceShaderDrawParametersFeatures *features =
1099 (VkPhysicalDeviceShaderDrawParametersFeatures*)ext;
1100 CORE_FEATURE(1, 1, shaderDrawParameters);
1101 break;
1102 }
1103 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
1104 VkPhysicalDeviceProtectedMemoryFeatures *features =
1105 (VkPhysicalDeviceProtectedMemoryFeatures*)ext;
1106 CORE_FEATURE(1, 1, protectedMemory);
1107 break;
1108 }
1109 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES: {
1110 VkPhysicalDevice16BitStorageFeatures *features =
1111 (VkPhysicalDevice16BitStorageFeatures*)ext;
1112 CORE_FEATURE(1, 1, storageBuffer16BitAccess);
1113 CORE_FEATURE(1, 1, uniformAndStorageBuffer16BitAccess);
1114 CORE_FEATURE(1, 1, storagePushConstant16);
1115 CORE_FEATURE(1, 1, storageInputOutput16);
1116 break;
1117 }
1118 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
1119 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
1120 (VkPhysicalDeviceSamplerYcbcrConversionFeatures*)ext;
1121 CORE_FEATURE(1, 1, samplerYcbcrConversion);
1122 break;
1123 }
1124 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES: {
1125 VkPhysicalDeviceDescriptorIndexingFeatures *features =
1126 (VkPhysicalDeviceDescriptorIndexingFeatures*)ext;
1127 CORE_FEATURE(1, 2, shaderInputAttachmentArrayDynamicIndexing);
1128 CORE_FEATURE(1, 2, shaderUniformTexelBufferArrayDynamicIndexing);
1129 CORE_FEATURE(1, 2, shaderStorageTexelBufferArrayDynamicIndexing);
1130 CORE_FEATURE(1, 2, shaderUniformBufferArrayNonUniformIndexing);
1131 CORE_FEATURE(1, 2, shaderSampledImageArrayNonUniformIndexing);
1132 CORE_FEATURE(1, 2, shaderStorageBufferArrayNonUniformIndexing);
1133 CORE_FEATURE(1, 2, shaderStorageImageArrayNonUniformIndexing);
1134 CORE_FEATURE(1, 2, shaderInputAttachmentArrayNonUniformIndexing);
1135 CORE_FEATURE(1, 2, shaderUniformTexelBufferArrayNonUniformIndexing);
1136 CORE_FEATURE(1, 2, shaderStorageTexelBufferArrayNonUniformIndexing);
1137 CORE_FEATURE(1, 2, descriptorBindingUniformBufferUpdateAfterBind);
1138 CORE_FEATURE(1, 2, descriptorBindingSampledImageUpdateAfterBind);
1139 CORE_FEATURE(1, 2, descriptorBindingStorageImageUpdateAfterBind);
1140 CORE_FEATURE(1, 2, descriptorBindingStorageBufferUpdateAfterBind);
1141 CORE_FEATURE(1, 2, descriptorBindingUniformTexelBufferUpdateAfterBind);
1142 CORE_FEATURE(1, 2, descriptorBindingStorageTexelBufferUpdateAfterBind);
1143 CORE_FEATURE(1, 2, descriptorBindingUpdateUnusedWhilePending);
1144 CORE_FEATURE(1, 2, descriptorBindingPartiallyBound);
1145 CORE_FEATURE(1, 2, descriptorBindingVariableDescriptorCount);
1146 CORE_FEATURE(1, 2, runtimeDescriptorArray);
1147 break;
1148 }
1149 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT: {
1150 VkPhysicalDeviceConditionalRenderingFeaturesEXT *features =
1151 (VkPhysicalDeviceConditionalRenderingFeaturesEXT*)ext;
1152 features->conditionalRendering = true;
1153 features->inheritedConditionalRendering = false;
1154 break;
1155 }
1156 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
1157 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
1158 (VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
1159 features->vertexAttributeInstanceRateDivisor = true;
1160 features->vertexAttributeInstanceRateZeroDivisor = true;
1161 break;
1162 }
1163 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT: {
1164 VkPhysicalDeviceTransformFeedbackFeaturesEXT *features =
1165 (VkPhysicalDeviceTransformFeedbackFeaturesEXT*)ext;
1166 features->transformFeedback = true;
1167 features->geometryStreams = !pdevice->use_ngg_streamout;
1168 break;
1169 }
1170 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES: {
1171 VkPhysicalDeviceScalarBlockLayoutFeatures *features =
1172 (VkPhysicalDeviceScalarBlockLayoutFeatures *)ext;
1173 CORE_FEATURE(1, 2, scalarBlockLayout);
1174 break;
1175 }
1176 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT: {
1177 VkPhysicalDeviceMemoryPriorityFeaturesEXT *features =
1178 (VkPhysicalDeviceMemoryPriorityFeaturesEXT *)ext;
1179 features->memoryPriority = true;
1180 break;
1181 }
1182 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT: {
1183 VkPhysicalDeviceBufferDeviceAddressFeaturesEXT *features =
1184 (VkPhysicalDeviceBufferDeviceAddressFeaturesEXT *)ext;
1185 features->bufferDeviceAddress = true;
1186 features->bufferDeviceAddressCaptureReplay = false;
1187 features->bufferDeviceAddressMultiDevice = false;
1188 break;
1189 }
1190 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES: {
1191 VkPhysicalDeviceBufferDeviceAddressFeatures *features =
1192 (VkPhysicalDeviceBufferDeviceAddressFeatures *)ext;
1193 CORE_FEATURE(1, 2, bufferDeviceAddress);
1194 CORE_FEATURE(1, 2, bufferDeviceAddressCaptureReplay);
1195 CORE_FEATURE(1, 2, bufferDeviceAddressMultiDevice);
1196 break;
1197 }
1198 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT: {
1199 VkPhysicalDeviceDepthClipEnableFeaturesEXT *features =
1200 (VkPhysicalDeviceDepthClipEnableFeaturesEXT *)ext;
1201 features->depthClipEnable = true;
1202 break;
1203 }
1204 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES: {
1205 VkPhysicalDeviceHostQueryResetFeatures *features =
1206 (VkPhysicalDeviceHostQueryResetFeatures *)ext;
1207 CORE_FEATURE(1, 2, hostQueryReset);
1208 break;
1209 }
1210 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES: {
1211 VkPhysicalDevice8BitStorageFeatures *features =
1212 (VkPhysicalDevice8BitStorageFeatures *)ext;
1213 CORE_FEATURE(1, 2, storageBuffer8BitAccess);
1214 CORE_FEATURE(1, 2, uniformAndStorageBuffer8BitAccess);
1215 CORE_FEATURE(1, 2, storagePushConstant8);
1216 break;
1217 }
1218 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES: {
1219 VkPhysicalDeviceShaderFloat16Int8Features *features =
1220 (VkPhysicalDeviceShaderFloat16Int8Features*)ext;
1221 CORE_FEATURE(1, 2, shaderFloat16);
1222 CORE_FEATURE(1, 2, shaderInt8);
1223 break;
1224 }
1225 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES: {
1226 VkPhysicalDeviceShaderAtomicInt64Features *features =
1227 (VkPhysicalDeviceShaderAtomicInt64Features *)ext;
1228 CORE_FEATURE(1, 2, shaderBufferInt64Atomics);
1229 CORE_FEATURE(1, 2, shaderSharedInt64Atomics);
1230 break;
1231 }
1232 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT: {
1233 VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT *features =
1234 (VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT *)ext;
1235 features->shaderDemoteToHelperInvocation = LLVM_VERSION_MAJOR >= 9 || !pdevice->use_llvm;
1236 break;
1237 }
1238 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES_EXT: {
1239 VkPhysicalDeviceInlineUniformBlockFeaturesEXT *features =
1240 (VkPhysicalDeviceInlineUniformBlockFeaturesEXT *)ext;
1241
1242 features->inlineUniformBlock = true;
1243 features->descriptorBindingInlineUniformBlockUpdateAfterBind = true;
1244 break;
1245 }
1246 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV: {
1247 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *features =
1248 (VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *)ext;
1249 features->computeDerivativeGroupQuads = false;
1250 features->computeDerivativeGroupLinear = true;
1251 break;
1252 }
1253 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_IMAGE_ARRAYS_FEATURES_EXT: {
1254 VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *features =
1255 (VkPhysicalDeviceYcbcrImageArraysFeaturesEXT*)ext;
1256 features->ycbcrImageArrays = true;
1257 break;
1258 }
1259 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES: {
1260 VkPhysicalDeviceUniformBufferStandardLayoutFeatures *features =
1261 (VkPhysicalDeviceUniformBufferStandardLayoutFeatures *)ext;
1262 CORE_FEATURE(1, 2, uniformBufferStandardLayout);
1263 break;
1264 }
1265 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INDEX_TYPE_UINT8_FEATURES_EXT: {
1266 VkPhysicalDeviceIndexTypeUint8FeaturesEXT *features =
1267 (VkPhysicalDeviceIndexTypeUint8FeaturesEXT *)ext;
1268 features->indexTypeUint8 = pdevice->rad_info.chip_class >= GFX8;
1269 break;
1270 }
1271 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGELESS_FRAMEBUFFER_FEATURES: {
1272 VkPhysicalDeviceImagelessFramebufferFeatures *features =
1273 (VkPhysicalDeviceImagelessFramebufferFeatures *)ext;
1274 CORE_FEATURE(1, 2, imagelessFramebuffer);
1275 break;
1276 }
1277 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR: {
1278 VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR *features =
1279 (VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR *)ext;
1280 features->pipelineExecutableInfo = true;
1281 break;
1282 }
1283 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR: {
1284 VkPhysicalDeviceShaderClockFeaturesKHR *features =
1285 (VkPhysicalDeviceShaderClockFeaturesKHR *)ext;
1286 features->shaderSubgroupClock = true;
1287 features->shaderDeviceClock = pdevice->rad_info.chip_class >= GFX8;
1288 break;
1289 }
1290 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_FEATURES_EXT: {
1291 VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT *features =
1292 (VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT *)ext;
1293 features->texelBufferAlignment = true;
1294 break;
1295 }
1296 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES: {
1297 VkPhysicalDeviceTimelineSemaphoreFeatures *features =
1298 (VkPhysicalDeviceTimelineSemaphoreFeatures *) ext;
1299 CORE_FEATURE(1, 2, timelineSemaphore);
1300 break;
1301 }
1302 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT: {
1303 VkPhysicalDeviceSubgroupSizeControlFeaturesEXT *features =
1304 (VkPhysicalDeviceSubgroupSizeControlFeaturesEXT *)ext;
1305 features->subgroupSizeControl = true;
1306 features->computeFullSubgroups = true;
1307 break;
1308 }
1309 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COHERENT_MEMORY_FEATURES_AMD: {
1310 VkPhysicalDeviceCoherentMemoryFeaturesAMD *features =
1311 (VkPhysicalDeviceCoherentMemoryFeaturesAMD *)ext;
1312 features->deviceCoherentMemory = pdevice->rad_info.has_l2_uncached;
1313 break;
1314 }
1315 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_EXTENDED_TYPES_FEATURES: {
1316 VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures *features =
1317 (VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures *)ext;
1318 CORE_FEATURE(1, 2, shaderSubgroupExtendedTypes);
1319 break;
1320 }
1321 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SEPARATE_DEPTH_STENCIL_LAYOUTS_FEATURES_KHR: {
1322 VkPhysicalDeviceSeparateDepthStencilLayoutsFeaturesKHR *features =
1323 (VkPhysicalDeviceSeparateDepthStencilLayoutsFeaturesKHR *)ext;
1324 CORE_FEATURE(1, 2, separateDepthStencilLayouts);
1325 break;
1326 }
1327 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES: {
1328 radv_get_physical_device_features_1_1(pdevice, (void *)ext);
1329 break;
1330 }
1331 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES: {
1332 radv_get_physical_device_features_1_2(pdevice, (void *)ext);
1333 break;
1334 }
1335 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINE_RASTERIZATION_FEATURES_EXT: {
1336 VkPhysicalDeviceLineRasterizationFeaturesEXT *features =
1337 (VkPhysicalDeviceLineRasterizationFeaturesEXT *)ext;
1338 features->rectangularLines = false;
1339 features->bresenhamLines = true;
1340 features->smoothLines = false;
1341 features->stippledRectangularLines = false;
1342 features->stippledBresenhamLines = true;
1343 features->stippledSmoothLines = false;
1344 break;
1345 }
1346 case VK_STRUCTURE_TYPE_DEVICE_MEMORY_OVERALLOCATION_CREATE_INFO_AMD: {
1347 VkDeviceMemoryOverallocationCreateInfoAMD *features =
1348 (VkDeviceMemoryOverallocationCreateInfoAMD *)ext;
1349 features->overallocationBehavior = true;
1350 break;
1351 }
1352 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT: {
1353 VkPhysicalDeviceRobustness2FeaturesEXT *features =
1354 (VkPhysicalDeviceRobustness2FeaturesEXT *)ext;
1355 features->robustBufferAccess2 = true;
1356 features->robustImageAccess2 = true;
1357 features->nullDescriptor = true;
1358 break;
1359 }
1360 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT: {
1361 VkPhysicalDeviceCustomBorderColorFeaturesEXT *features =
1362 (VkPhysicalDeviceCustomBorderColorFeaturesEXT *)ext;
1363 features->customBorderColors = true;
1364 features->customBorderColorWithoutFormat = true;
1365 break;
1366 }
1367 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIVATE_DATA_FEATURES_EXT: {
1368 VkPhysicalDevicePrivateDataFeaturesEXT *features =
1369 (VkPhysicalDevicePrivateDataFeaturesEXT *)ext;
1370 features->privateData = true;
1371 break;
1372 }
1373 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES_EXT: {
1374 VkPhysicalDevicePipelineCreationCacheControlFeaturesEXT *features =
1375 (VkPhysicalDevicePipelineCreationCacheControlFeaturesEXT *)ext;
1376 features-> pipelineCreationCacheControl = true;
1377 break;
1378 }
1379 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES_KHR: {
1380 VkPhysicalDeviceVulkanMemoryModelFeaturesKHR *features =
1381 (VkPhysicalDeviceVulkanMemoryModelFeaturesKHR *)ext;
1382 CORE_FEATURE(1, 2, vulkanMemoryModel);
1383 CORE_FEATURE(1, 2, vulkanMemoryModelDeviceScope);
1384 CORE_FEATURE(1, 2, vulkanMemoryModelAvailabilityVisibilityChains);
1385 break;
1386 }
1387 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT: {
1388 VkPhysicalDeviceExtendedDynamicStateFeaturesEXT *features =
1389 (VkPhysicalDeviceExtendedDynamicStateFeaturesEXT *) ext;
1390 features->extendedDynamicState = true;
1391 break;
1392 }
1393 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_ROBUSTNESS_FEATURES_EXT: {
1394 VkPhysicalDeviceImageRobustnessFeaturesEXT *features =
1395 (VkPhysicalDeviceImageRobustnessFeaturesEXT *)ext;
1396 features->robustImageAccess = true;
1397 break;
1398 }
1399 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT: {
1400 VkPhysicalDeviceShaderAtomicFloatFeaturesEXT *features =
1401 (VkPhysicalDeviceShaderAtomicFloatFeaturesEXT *)ext;
1402 features->shaderBufferFloat32Atomics = true;
1403 features->shaderBufferFloat32AtomicAdd = false;
1404 features->shaderBufferFloat64Atomics = true;
1405 features->shaderBufferFloat64AtomicAdd = false;
1406 features->shaderSharedFloat32Atomics = true;
1407 features->shaderSharedFloat32AtomicAdd = pdevice->rad_info.chip_class >= GFX8 &&
1408 (!pdevice->use_llvm || LLVM_VERSION_MAJOR >= 10);
1409 features->shaderSharedFloat64Atomics = true;
1410 features->shaderSharedFloat64AtomicAdd = false;
1411 features->shaderImageFloat32Atomics = true;
1412 features->shaderImageFloat32AtomicAdd = false;
1413 features->sparseImageFloat32Atomics = false;
1414 features->sparseImageFloat32AtomicAdd = false;
1415 break;
1416 }
1417 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_4444_FORMATS_FEATURES_EXT: {
1418 VkPhysicalDevice4444FormatsFeaturesEXT *features =
1419 (VkPhysicalDevice4444FormatsFeaturesEXT *)ext;
1420 features->formatA4R4G4B4 = true;
1421 features->formatA4B4G4R4 = true;
1422 break;
1423 }
1424 default:
1425 break;
1426 }
1427 }
1428 #undef CORE_FEATURE
1429 }
1430
1431 static size_t
1432 radv_max_descriptor_set_size()
1433 {
1434 /* make sure that the entire descriptor set is addressable with a signed
1435 * 32-bit int. So the sum of all limits scaled by descriptor size has to
1436 * be at most 2 GiB. the combined image & samples object count as one of
1437 * both. This limit is for the pipeline layout, not for the set layout, but
1438 * there is no set limit, so we just set a pipeline limit. I don't think
1439 * any app is going to hit this soon. */
1440 return ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS
1441 - MAX_INLINE_UNIFORM_BLOCK_SIZE * MAX_INLINE_UNIFORM_BLOCK_COUNT) /
1442 (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
1443 32 /* storage buffer, 32 due to potential space wasted on alignment */ +
1444 32 /* sampler, largest when combined with image */ +
1445 64 /* sampled image */ +
1446 64 /* storage image */);
1447 }
1448
1449 static uint32_t
1450 radv_uniform_buffer_offset_alignment(const struct radv_physical_device *pdevice)
1451 {
1452 uint32_t uniform_offset_alignment = driQueryOptioni(&pdevice->instance->dri_options,
1453 "radv_override_uniform_offset_alignment");
1454 if (!util_is_power_of_two_or_zero(uniform_offset_alignment)) {
1455 fprintf(stderr, "ERROR: invalid radv_override_uniform_offset_alignment setting %d:"
1456 "not a power of two\n", uniform_offset_alignment);
1457 uniform_offset_alignment = 0;
1458 }
1459
1460 /* Take at least the hardware limit. */
1461 return MAX2(uniform_offset_alignment, 4);
1462 }
1463
1464 void radv_GetPhysicalDeviceProperties(
1465 VkPhysicalDevice physicalDevice,
1466 VkPhysicalDeviceProperties* pProperties)
1467 {
1468 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1469 VkSampleCountFlags sample_counts = 0xf;
1470
1471 size_t max_descriptor_set_size = radv_max_descriptor_set_size();
1472
1473 VkPhysicalDeviceLimits limits = {
1474 .maxImageDimension1D = (1 << 14),
1475 .maxImageDimension2D = (1 << 14),
1476 .maxImageDimension3D = (1 << 11),
1477 .maxImageDimensionCube = (1 << 14),
1478 .maxImageArrayLayers = (1 << 11),
1479 .maxTexelBufferElements = UINT32_MAX,
1480 .maxUniformBufferRange = UINT32_MAX,
1481 .maxStorageBufferRange = UINT32_MAX,
1482 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
1483 .maxMemoryAllocationCount = UINT32_MAX,
1484 .maxSamplerAllocationCount = 64 * 1024,
1485 .bufferImageGranularity = 64, /* A cache line */
1486 .sparseAddressSpaceSize = RADV_MAX_MEMORY_ALLOCATION_SIZE, /* buffer max size */
1487 .maxBoundDescriptorSets = MAX_SETS,
1488 .maxPerStageDescriptorSamplers = max_descriptor_set_size,
1489 .maxPerStageDescriptorUniformBuffers = max_descriptor_set_size,
1490 .maxPerStageDescriptorStorageBuffers = max_descriptor_set_size,
1491 .maxPerStageDescriptorSampledImages = max_descriptor_set_size,
1492 .maxPerStageDescriptorStorageImages = max_descriptor_set_size,
1493 .maxPerStageDescriptorInputAttachments = max_descriptor_set_size,
1494 .maxPerStageResources = max_descriptor_set_size,
1495 .maxDescriptorSetSamplers = max_descriptor_set_size,
1496 .maxDescriptorSetUniformBuffers = max_descriptor_set_size,
1497 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS,
1498 .maxDescriptorSetStorageBuffers = max_descriptor_set_size,
1499 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS,
1500 .maxDescriptorSetSampledImages = max_descriptor_set_size,
1501 .maxDescriptorSetStorageImages = max_descriptor_set_size,
1502 .maxDescriptorSetInputAttachments = max_descriptor_set_size,
1503 .maxVertexInputAttributes = MAX_VERTEX_ATTRIBS,
1504 .maxVertexInputBindings = MAX_VBS,
1505 .maxVertexInputAttributeOffset = 2047,
1506 .maxVertexInputBindingStride = 2048,
1507 .maxVertexOutputComponents = 128,
1508 .maxTessellationGenerationLevel = 64,
1509 .maxTessellationPatchSize = 32,
1510 .maxTessellationControlPerVertexInputComponents = 128,
1511 .maxTessellationControlPerVertexOutputComponents = 128,
1512 .maxTessellationControlPerPatchOutputComponents = 120,
1513 .maxTessellationControlTotalOutputComponents = 4096,
1514 .maxTessellationEvaluationInputComponents = 128,
1515 .maxTessellationEvaluationOutputComponents = 128,
1516 .maxGeometryShaderInvocations = 127,
1517 .maxGeometryInputComponents = 64,
1518 .maxGeometryOutputComponents = 128,
1519 .maxGeometryOutputVertices = 256,
1520 .maxGeometryTotalOutputComponents = 1024,
1521 .maxFragmentInputComponents = 128,
1522 .maxFragmentOutputAttachments = 8,
1523 .maxFragmentDualSrcAttachments = 1,
1524 .maxFragmentCombinedOutputResources = 8,
1525 .maxComputeSharedMemorySize = 32768,
1526 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
1527 .maxComputeWorkGroupInvocations = 1024,
1528 .maxComputeWorkGroupSize = {
1529 1024,
1530 1024,
1531 1024
1532 },
1533 .subPixelPrecisionBits = 8,
1534 .subTexelPrecisionBits = 8,
1535 .mipmapPrecisionBits = 8,
1536 .maxDrawIndexedIndexValue = UINT32_MAX,
1537 .maxDrawIndirectCount = UINT32_MAX,
1538 .maxSamplerLodBias = 16,
1539 .maxSamplerAnisotropy = 16,
1540 .maxViewports = MAX_VIEWPORTS,
1541 .maxViewportDimensions = { (1 << 14), (1 << 14) },
1542 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
1543 .viewportSubPixelBits = 8,
1544 .minMemoryMapAlignment = 4096, /* A page */
1545 .minTexelBufferOffsetAlignment = 4,
1546 .minUniformBufferOffsetAlignment = radv_uniform_buffer_offset_alignment(pdevice),
1547 .minStorageBufferOffsetAlignment = 4,
1548 .minTexelOffset = -32,
1549 .maxTexelOffset = 31,
1550 .minTexelGatherOffset = -32,
1551 .maxTexelGatherOffset = 31,
1552 .minInterpolationOffset = -2,
1553 .maxInterpolationOffset = 2,
1554 .subPixelInterpolationOffsetBits = 8,
1555 .maxFramebufferWidth = (1 << 14),
1556 .maxFramebufferHeight = (1 << 14),
1557 .maxFramebufferLayers = (1 << 10),
1558 .framebufferColorSampleCounts = sample_counts,
1559 .framebufferDepthSampleCounts = sample_counts,
1560 .framebufferStencilSampleCounts = sample_counts,
1561 .framebufferNoAttachmentsSampleCounts = sample_counts,
1562 .maxColorAttachments = MAX_RTS,
1563 .sampledImageColorSampleCounts = sample_counts,
1564 .sampledImageIntegerSampleCounts = sample_counts,
1565 .sampledImageDepthSampleCounts = sample_counts,
1566 .sampledImageStencilSampleCounts = sample_counts,
1567 .storageImageSampleCounts = sample_counts,
1568 .maxSampleMaskWords = 1,
1569 .timestampComputeAndGraphics = true,
1570 .timestampPeriod = 1000000.0 / pdevice->rad_info.clock_crystal_freq,
1571 .maxClipDistances = 8,
1572 .maxCullDistances = 8,
1573 .maxCombinedClipAndCullDistances = 8,
1574 .discreteQueuePriorities = 2,
1575 .pointSizeRange = { 0.0, 8191.875 },
1576 .lineWidthRange = { 0.0, 8191.875 },
1577 .pointSizeGranularity = (1.0 / 8.0),
1578 .lineWidthGranularity = (1.0 / 8.0),
1579 .strictLines = false, /* FINISHME */
1580 .standardSampleLocations = true,
1581 .optimalBufferCopyOffsetAlignment = 128,
1582 .optimalBufferCopyRowPitchAlignment = 128,
1583 .nonCoherentAtomSize = 64,
1584 };
1585
1586 *pProperties = (VkPhysicalDeviceProperties) {
1587 .apiVersion = radv_physical_device_api_version(pdevice),
1588 .driverVersion = vk_get_driver_version(),
1589 .vendorID = ATI_VENDOR_ID,
1590 .deviceID = pdevice->rad_info.pci_id,
1591 .deviceType = pdevice->rad_info.has_dedicated_vram ? VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU : VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1592 .limits = limits,
1593 .sparseProperties = {0},
1594 };
1595
1596 strcpy(pProperties->deviceName, pdevice->name);
1597 memcpy(pProperties->pipelineCacheUUID, pdevice->cache_uuid, VK_UUID_SIZE);
1598 }
1599
1600 static void
1601 radv_get_physical_device_properties_1_1(struct radv_physical_device *pdevice,
1602 VkPhysicalDeviceVulkan11Properties *p)
1603 {
1604 assert(p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES);
1605
1606 memcpy(p->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1607 memcpy(p->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1608 memset(p->deviceLUID, 0, VK_LUID_SIZE);
1609 /* The LUID is for Windows. */
1610 p->deviceLUIDValid = false;
1611 p->deviceNodeMask = 0;
1612
1613 p->subgroupSize = RADV_SUBGROUP_SIZE;
1614 p->subgroupSupportedStages = VK_SHADER_STAGE_ALL_GRAPHICS |
1615 VK_SHADER_STAGE_COMPUTE_BIT;
1616 p->subgroupSupportedOperations = VK_SUBGROUP_FEATURE_BASIC_BIT |
1617 VK_SUBGROUP_FEATURE_VOTE_BIT |
1618 VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1619 VK_SUBGROUP_FEATURE_BALLOT_BIT |
1620 VK_SUBGROUP_FEATURE_CLUSTERED_BIT |
1621 VK_SUBGROUP_FEATURE_QUAD_BIT |
1622 VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1623 VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT;
1624 p->subgroupQuadOperationsInAllStages = true;
1625
1626 p->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
1627 p->maxMultiviewViewCount = MAX_VIEWS;
1628 p->maxMultiviewInstanceIndex = INT_MAX;
1629 p->protectedNoFault = false;
1630 p->maxPerSetDescriptors = RADV_MAX_PER_SET_DESCRIPTORS;
1631 p->maxMemoryAllocationSize = RADV_MAX_MEMORY_ALLOCATION_SIZE;
1632 }
1633
1634 static void
1635 radv_get_physical_device_properties_1_2(struct radv_physical_device *pdevice,
1636 VkPhysicalDeviceVulkan12Properties *p)
1637 {
1638 assert(p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES);
1639
1640 p->driverID = VK_DRIVER_ID_MESA_RADV;
1641 snprintf(p->driverName, VK_MAX_DRIVER_NAME_SIZE, "radv");
1642 snprintf(p->driverInfo, VK_MAX_DRIVER_INFO_SIZE,
1643 "Mesa " PACKAGE_VERSION MESA_GIT_SHA1 " (%s)",
1644 radv_get_compiler_string(pdevice));
1645 p->conformanceVersion = (VkConformanceVersion) {
1646 .major = 1,
1647 .minor = 2,
1648 .subminor = 3,
1649 .patch = 0,
1650 };
1651
1652 /* On AMD hardware, denormals and rounding modes for fp16/fp64 are
1653 * controlled by the same config register.
1654 */
1655 if (pdevice->rad_info.has_packed_math_16bit) {
1656 p->denormBehaviorIndependence = VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR;
1657 p->roundingModeIndependence = VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR;
1658 } else {
1659 p->denormBehaviorIndependence = VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR;
1660 p->roundingModeIndependence = VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR;
1661 }
1662
1663 /* With LLVM, do not allow both preserving and flushing denorms because
1664 * different shaders in the same pipeline can have different settings and
1665 * this won't work for merged shaders. To make it work, this requires LLVM
1666 * support for changing the register. The same logic applies for the
1667 * rounding modes because they are configured with the same config
1668 * register.
1669 */
1670 p->shaderDenormFlushToZeroFloat32 = true;
1671 p->shaderDenormPreserveFloat32 = !pdevice->use_llvm;
1672 p->shaderRoundingModeRTEFloat32 = true;
1673 p->shaderRoundingModeRTZFloat32 = !pdevice->use_llvm;
1674 p->shaderSignedZeroInfNanPreserveFloat32 = true;
1675
1676 p->shaderDenormFlushToZeroFloat16 = pdevice->rad_info.has_packed_math_16bit && !pdevice->use_llvm;
1677 p->shaderDenormPreserveFloat16 = pdevice->rad_info.has_packed_math_16bit;
1678 p->shaderRoundingModeRTEFloat16 = pdevice->rad_info.has_packed_math_16bit;
1679 p->shaderRoundingModeRTZFloat16 = pdevice->rad_info.has_packed_math_16bit && !pdevice->use_llvm;
1680 p->shaderSignedZeroInfNanPreserveFloat16 = pdevice->rad_info.has_packed_math_16bit;
1681
1682 p->shaderDenormFlushToZeroFloat64 = pdevice->rad_info.chip_class >= GFX8 && !pdevice->use_llvm;
1683 p->shaderDenormPreserveFloat64 = pdevice->rad_info.chip_class >= GFX8;
1684 p->shaderRoundingModeRTEFloat64 = pdevice->rad_info.chip_class >= GFX8;
1685 p->shaderRoundingModeRTZFloat64 = pdevice->rad_info.chip_class >= GFX8 && !pdevice->use_llvm;
1686 p->shaderSignedZeroInfNanPreserveFloat64 = pdevice->rad_info.chip_class >= GFX8;
1687
1688 p->maxUpdateAfterBindDescriptorsInAllPools = UINT32_MAX / 64;
1689 p->shaderUniformBufferArrayNonUniformIndexingNative = false;
1690 p->shaderSampledImageArrayNonUniformIndexingNative = false;
1691 p->shaderStorageBufferArrayNonUniformIndexingNative = false;
1692 p->shaderStorageImageArrayNonUniformIndexingNative = false;
1693 p->shaderInputAttachmentArrayNonUniformIndexingNative = false;
1694 p->robustBufferAccessUpdateAfterBind = false;
1695 p->quadDivergentImplicitLod = false;
1696
1697 size_t max_descriptor_set_size = ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS -
1698 MAX_INLINE_UNIFORM_BLOCK_SIZE * MAX_INLINE_UNIFORM_BLOCK_COUNT) /
1699 (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
1700 32 /* storage buffer, 32 due to potential space wasted on alignment */ +
1701 32 /* sampler, largest when combined with image */ +
1702 64 /* sampled image */ +
1703 64 /* storage image */);
1704 p->maxPerStageDescriptorUpdateAfterBindSamplers = max_descriptor_set_size;
1705 p->maxPerStageDescriptorUpdateAfterBindUniformBuffers = max_descriptor_set_size;
1706 p->maxPerStageDescriptorUpdateAfterBindStorageBuffers = max_descriptor_set_size;
1707 p->maxPerStageDescriptorUpdateAfterBindSampledImages = max_descriptor_set_size;
1708 p->maxPerStageDescriptorUpdateAfterBindStorageImages = max_descriptor_set_size;
1709 p->maxPerStageDescriptorUpdateAfterBindInputAttachments = max_descriptor_set_size;
1710 p->maxPerStageUpdateAfterBindResources = max_descriptor_set_size;
1711 p->maxDescriptorSetUpdateAfterBindSamplers = max_descriptor_set_size;
1712 p->maxDescriptorSetUpdateAfterBindUniformBuffers = max_descriptor_set_size;
1713 p->maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS;
1714 p->maxDescriptorSetUpdateAfterBindStorageBuffers = max_descriptor_set_size;
1715 p->maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS;
1716 p->maxDescriptorSetUpdateAfterBindSampledImages = max_descriptor_set_size;
1717 p->maxDescriptorSetUpdateAfterBindStorageImages = max_descriptor_set_size;
1718 p->maxDescriptorSetUpdateAfterBindInputAttachments = max_descriptor_set_size;
1719
1720 /* We support all of the depth resolve modes */
1721 p->supportedDepthResolveModes = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR |
1722 VK_RESOLVE_MODE_AVERAGE_BIT_KHR |
1723 VK_RESOLVE_MODE_MIN_BIT_KHR |
1724 VK_RESOLVE_MODE_MAX_BIT_KHR;
1725
1726 /* Average doesn't make sense for stencil so we don't support that */
1727 p->supportedStencilResolveModes = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR |
1728 VK_RESOLVE_MODE_MIN_BIT_KHR |
1729 VK_RESOLVE_MODE_MAX_BIT_KHR;
1730
1731 p->independentResolveNone = true;
1732 p->independentResolve = true;
1733
1734 /* GFX6-8 only support single channel min/max filter. */
1735 p->filterMinmaxImageComponentMapping = pdevice->rad_info.chip_class >= GFX9;
1736 p->filterMinmaxSingleComponentFormats = true;
1737
1738 p->maxTimelineSemaphoreValueDifference = UINT64_MAX;
1739
1740 p->framebufferIntegerColorSampleCounts = VK_SAMPLE_COUNT_1_BIT;
1741 }
1742
1743 void radv_GetPhysicalDeviceProperties2(
1744 VkPhysicalDevice physicalDevice,
1745 VkPhysicalDeviceProperties2 *pProperties)
1746 {
1747 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1748 radv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
1749
1750 VkPhysicalDeviceVulkan11Properties core_1_1 = {
1751 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES,
1752 };
1753 radv_get_physical_device_properties_1_1(pdevice, &core_1_1);
1754
1755 VkPhysicalDeviceVulkan12Properties core_1_2 = {
1756 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES,
1757 };
1758 radv_get_physical_device_properties_1_2(pdevice, &core_1_2);
1759
1760 #define CORE_RENAMED_PROPERTY(major, minor, ext_property, core_property) \
1761 memcpy(&properties->ext_property, &core_##major##_##minor.core_property, \
1762 sizeof(core_##major##_##minor.core_property))
1763
1764 #define CORE_PROPERTY(major, minor, property) \
1765 CORE_RENAMED_PROPERTY(major, minor, property, property)
1766
1767 vk_foreach_struct(ext, pProperties->pNext) {
1768 switch (ext->sType) {
1769 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
1770 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
1771 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
1772 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
1773 break;
1774 }
1775 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1776 VkPhysicalDeviceIDProperties *properties = (VkPhysicalDeviceIDProperties*)ext;
1777 CORE_PROPERTY(1, 1, deviceUUID);
1778 CORE_PROPERTY(1, 1, driverUUID);
1779 CORE_PROPERTY(1, 1, deviceLUID);
1780 CORE_PROPERTY(1, 1, deviceLUIDValid);
1781 break;
1782 }
1783 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1784 VkPhysicalDeviceMultiviewProperties *properties = (VkPhysicalDeviceMultiviewProperties*)ext;
1785 CORE_PROPERTY(1, 1, maxMultiviewViewCount);
1786 CORE_PROPERTY(1, 1, maxMultiviewInstanceIndex);
1787 break;
1788 }
1789 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
1790 VkPhysicalDevicePointClippingProperties *properties =
1791 (VkPhysicalDevicePointClippingProperties*)ext;
1792 CORE_PROPERTY(1, 1, pointClippingBehavior);
1793 break;
1794 }
1795 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DISCARD_RECTANGLE_PROPERTIES_EXT: {
1796 VkPhysicalDeviceDiscardRectanglePropertiesEXT *properties =
1797 (VkPhysicalDeviceDiscardRectanglePropertiesEXT*)ext;
1798 properties->maxDiscardRectangles = MAX_DISCARD_RECTANGLES;
1799 break;
1800 }
1801 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT: {
1802 VkPhysicalDeviceExternalMemoryHostPropertiesEXT *properties =
1803 (VkPhysicalDeviceExternalMemoryHostPropertiesEXT *) ext;
1804 properties->minImportedHostPointerAlignment = 4096;
1805 break;
1806 }
1807 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
1808 VkPhysicalDeviceSubgroupProperties *properties =
1809 (VkPhysicalDeviceSubgroupProperties*)ext;
1810 CORE_PROPERTY(1, 1, subgroupSize);
1811 CORE_RENAMED_PROPERTY(1, 1, supportedStages,
1812 subgroupSupportedStages);
1813 CORE_RENAMED_PROPERTY(1, 1, supportedOperations,
1814 subgroupSupportedOperations);
1815 CORE_RENAMED_PROPERTY(1, 1, quadOperationsInAllStages,
1816 subgroupQuadOperationsInAllStages);
1817 break;
1818 }
1819 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1820 VkPhysicalDeviceMaintenance3Properties *properties =
1821 (VkPhysicalDeviceMaintenance3Properties*)ext;
1822 CORE_PROPERTY(1, 1, maxPerSetDescriptors);
1823 CORE_PROPERTY(1, 1, maxMemoryAllocationSize);
1824 break;
1825 }
1826 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES: {
1827 VkPhysicalDeviceSamplerFilterMinmaxProperties *properties =
1828 (VkPhysicalDeviceSamplerFilterMinmaxProperties *)ext;
1829 CORE_PROPERTY(1, 2, filterMinmaxImageComponentMapping);
1830 CORE_PROPERTY(1, 2, filterMinmaxSingleComponentFormats);
1831 break;
1832 }
1833 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_AMD: {
1834 VkPhysicalDeviceShaderCorePropertiesAMD *properties =
1835 (VkPhysicalDeviceShaderCorePropertiesAMD *)ext;
1836
1837 /* Shader engines. */
1838 properties->shaderEngineCount =
1839 pdevice->rad_info.max_se;
1840 properties->shaderArraysPerEngineCount =
1841 pdevice->rad_info.max_sh_per_se;
1842 properties->computeUnitsPerShaderArray =
1843 pdevice->rad_info.min_good_cu_per_sa;
1844 properties->simdPerComputeUnit =
1845 pdevice->rad_info.num_simd_per_compute_unit;
1846 properties->wavefrontsPerSimd =
1847 pdevice->rad_info.max_wave64_per_simd;
1848 properties->wavefrontSize = 64;
1849
1850 /* SGPR. */
1851 properties->sgprsPerSimd =
1852 pdevice->rad_info.num_physical_sgprs_per_simd;
1853 properties->minSgprAllocation =
1854 pdevice->rad_info.min_sgpr_alloc;
1855 properties->maxSgprAllocation =
1856 pdevice->rad_info.max_sgpr_alloc;
1857 properties->sgprAllocationGranularity =
1858 pdevice->rad_info.sgpr_alloc_granularity;
1859
1860 /* VGPR. */
1861 properties->vgprsPerSimd =
1862 pdevice->rad_info.num_physical_wave64_vgprs_per_simd;
1863 properties->minVgprAllocation =
1864 pdevice->rad_info.min_wave64_vgpr_alloc;
1865 properties->maxVgprAllocation =
1866 pdevice->rad_info.max_vgpr_alloc;
1867 properties->vgprAllocationGranularity =
1868 pdevice->rad_info.wave64_vgpr_alloc_granularity;
1869 break;
1870 }
1871 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_2_AMD: {
1872 VkPhysicalDeviceShaderCoreProperties2AMD *properties =
1873 (VkPhysicalDeviceShaderCoreProperties2AMD *)ext;
1874
1875 properties->shaderCoreFeatures = 0;
1876 properties->activeComputeUnitCount =
1877 pdevice->rad_info.num_good_compute_units;
1878 break;
1879 }
1880 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
1881 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *properties =
1882 (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
1883 properties->maxVertexAttribDivisor = UINT32_MAX;
1884 break;
1885 }
1886 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES: {
1887 VkPhysicalDeviceDescriptorIndexingProperties *properties =
1888 (VkPhysicalDeviceDescriptorIndexingProperties*)ext;
1889 CORE_PROPERTY(1, 2, maxUpdateAfterBindDescriptorsInAllPools);
1890 CORE_PROPERTY(1, 2, shaderUniformBufferArrayNonUniformIndexingNative);
1891 CORE_PROPERTY(1, 2, shaderSampledImageArrayNonUniformIndexingNative);
1892 CORE_PROPERTY(1, 2, shaderStorageBufferArrayNonUniformIndexingNative);
1893 CORE_PROPERTY(1, 2, shaderStorageImageArrayNonUniformIndexingNative);
1894 CORE_PROPERTY(1, 2, shaderInputAttachmentArrayNonUniformIndexingNative);
1895 CORE_PROPERTY(1, 2, robustBufferAccessUpdateAfterBind);
1896 CORE_PROPERTY(1, 2, quadDivergentImplicitLod);
1897 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindSamplers);
1898 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindUniformBuffers);
1899 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindStorageBuffers);
1900 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindSampledImages);
1901 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindStorageImages);
1902 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindInputAttachments);
1903 CORE_PROPERTY(1, 2, maxPerStageUpdateAfterBindResources);
1904 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindSamplers);
1905 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindUniformBuffers);
1906 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindUniformBuffersDynamic);
1907 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindStorageBuffers);
1908 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindStorageBuffersDynamic);
1909 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindSampledImages);
1910 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindStorageImages);
1911 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindInputAttachments);
1912 break;
1913 }
1914 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES: {
1915 VkPhysicalDeviceProtectedMemoryProperties *properties =
1916 (VkPhysicalDeviceProtectedMemoryProperties *)ext;
1917 CORE_PROPERTY(1, 1, protectedNoFault);
1918 break;
1919 }
1920 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT: {
1921 VkPhysicalDeviceConservativeRasterizationPropertiesEXT *properties =
1922 (VkPhysicalDeviceConservativeRasterizationPropertiesEXT *)ext;
1923 properties->primitiveOverestimationSize = 0;
1924 properties->maxExtraPrimitiveOverestimationSize = 0;
1925 properties->extraPrimitiveOverestimationSizeGranularity = 0;
1926 properties->primitiveUnderestimation = false;
1927 properties->conservativePointAndLineRasterization = false;
1928 properties->degenerateTrianglesRasterized = false;
1929 properties->degenerateLinesRasterized = false;
1930 properties->fullyCoveredFragmentShaderInputVariable = false;
1931 properties->conservativeRasterizationPostDepthCoverage = false;
1932 break;
1933 }
1934 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT: {
1935 VkPhysicalDevicePCIBusInfoPropertiesEXT *properties =
1936 (VkPhysicalDevicePCIBusInfoPropertiesEXT *)ext;
1937 properties->pciDomain = pdevice->bus_info.domain;
1938 properties->pciBus = pdevice->bus_info.bus;
1939 properties->pciDevice = pdevice->bus_info.dev;
1940 properties->pciFunction = pdevice->bus_info.func;
1941 break;
1942 }
1943 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES: {
1944 VkPhysicalDeviceDriverProperties *properties =
1945 (VkPhysicalDeviceDriverProperties *) ext;
1946 CORE_PROPERTY(1, 2, driverID);
1947 CORE_PROPERTY(1, 2, driverName);
1948 CORE_PROPERTY(1, 2, driverInfo);
1949 CORE_PROPERTY(1, 2, conformanceVersion);
1950 break;
1951 }
1952 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT: {
1953 VkPhysicalDeviceTransformFeedbackPropertiesEXT *properties =
1954 (VkPhysicalDeviceTransformFeedbackPropertiesEXT *)ext;
1955 properties->maxTransformFeedbackStreams = MAX_SO_STREAMS;
1956 properties->maxTransformFeedbackBuffers = MAX_SO_BUFFERS;
1957 properties->maxTransformFeedbackBufferSize = UINT32_MAX;
1958 properties->maxTransformFeedbackStreamDataSize = 512;
1959 properties->maxTransformFeedbackBufferDataSize = UINT32_MAX;
1960 properties->maxTransformFeedbackBufferDataStride = 512;
1961 properties->transformFeedbackQueries = !pdevice->use_ngg_streamout;
1962 properties->transformFeedbackStreamsLinesTriangles = !pdevice->use_ngg_streamout;
1963 properties->transformFeedbackRasterizationStreamSelect = false;
1964 properties->transformFeedbackDraw = true;
1965 break;
1966 }
1967 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_PROPERTIES_EXT: {
1968 VkPhysicalDeviceInlineUniformBlockPropertiesEXT *props =
1969 (VkPhysicalDeviceInlineUniformBlockPropertiesEXT *)ext;
1970
1971 props->maxInlineUniformBlockSize = MAX_INLINE_UNIFORM_BLOCK_SIZE;
1972 props->maxPerStageDescriptorInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_SIZE * MAX_SETS;
1973 props->maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_SIZE * MAX_SETS;
1974 props->maxDescriptorSetInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_COUNT;
1975 props->maxDescriptorSetUpdateAfterBindInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_COUNT;
1976 break;
1977 }
1978 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT: {
1979 VkPhysicalDeviceSampleLocationsPropertiesEXT *properties =
1980 (VkPhysicalDeviceSampleLocationsPropertiesEXT *)ext;
1981 properties->sampleLocationSampleCounts = VK_SAMPLE_COUNT_2_BIT |
1982 VK_SAMPLE_COUNT_4_BIT |
1983 VK_SAMPLE_COUNT_8_BIT;
1984 properties->maxSampleLocationGridSize = (VkExtent2D){ 2 , 2 };
1985 properties->sampleLocationCoordinateRange[0] = 0.0f;
1986 properties->sampleLocationCoordinateRange[1] = 0.9375f;
1987 properties->sampleLocationSubPixelBits = 4;
1988 properties->variableSampleLocations = false;
1989 break;
1990 }
1991 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES: {
1992 VkPhysicalDeviceDepthStencilResolveProperties *properties =
1993 (VkPhysicalDeviceDepthStencilResolveProperties *)ext;
1994 CORE_PROPERTY(1, 2, supportedDepthResolveModes);
1995 CORE_PROPERTY(1, 2, supportedStencilResolveModes);
1996 CORE_PROPERTY(1, 2, independentResolveNone);
1997 CORE_PROPERTY(1, 2, independentResolve);
1998 break;
1999 }
2000 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_PROPERTIES_EXT: {
2001 VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT *properties =
2002 (VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT *)ext;
2003 properties->storageTexelBufferOffsetAlignmentBytes = 4;
2004 properties->storageTexelBufferOffsetSingleTexelAlignment = true;
2005 properties->uniformTexelBufferOffsetAlignmentBytes = 4;
2006 properties->uniformTexelBufferOffsetSingleTexelAlignment = true;
2007 break;
2008 }
2009 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES : {
2010 VkPhysicalDeviceFloatControlsProperties *properties =
2011 (VkPhysicalDeviceFloatControlsProperties *)ext;
2012 CORE_PROPERTY(1, 2, denormBehaviorIndependence);
2013 CORE_PROPERTY(1, 2, roundingModeIndependence);
2014 CORE_PROPERTY(1, 2, shaderDenormFlushToZeroFloat16);
2015 CORE_PROPERTY(1, 2, shaderDenormPreserveFloat16);
2016 CORE_PROPERTY(1, 2, shaderRoundingModeRTEFloat16);
2017 CORE_PROPERTY(1, 2, shaderRoundingModeRTZFloat16);
2018 CORE_PROPERTY(1, 2, shaderSignedZeroInfNanPreserveFloat16);
2019 CORE_PROPERTY(1, 2, shaderDenormFlushToZeroFloat32);
2020 CORE_PROPERTY(1, 2, shaderDenormPreserveFloat32);
2021 CORE_PROPERTY(1, 2, shaderRoundingModeRTEFloat32);
2022 CORE_PROPERTY(1, 2, shaderRoundingModeRTZFloat32);
2023 CORE_PROPERTY(1, 2, shaderSignedZeroInfNanPreserveFloat32);
2024 CORE_PROPERTY(1, 2, shaderDenormFlushToZeroFloat64);
2025 CORE_PROPERTY(1, 2, shaderDenormPreserveFloat64);
2026 CORE_PROPERTY(1, 2, shaderRoundingModeRTEFloat64);
2027 CORE_PROPERTY(1, 2, shaderRoundingModeRTZFloat64);
2028 CORE_PROPERTY(1, 2, shaderSignedZeroInfNanPreserveFloat64);
2029 break;
2030 }
2031 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_PROPERTIES: {
2032 VkPhysicalDeviceTimelineSemaphoreProperties *properties =
2033 (VkPhysicalDeviceTimelineSemaphoreProperties *) ext;
2034 CORE_PROPERTY(1, 2, maxTimelineSemaphoreValueDifference);
2035 break;
2036 }
2037 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES_EXT: {
2038 VkPhysicalDeviceSubgroupSizeControlPropertiesEXT *props =
2039 (VkPhysicalDeviceSubgroupSizeControlPropertiesEXT *)ext;
2040 props->minSubgroupSize = 64;
2041 props->maxSubgroupSize = 64;
2042 props->maxComputeWorkgroupSubgroups = UINT32_MAX;
2043 props->requiredSubgroupSizeStages = 0;
2044
2045 if (pdevice->rad_info.chip_class >= GFX10) {
2046 /* Only GFX10+ supports wave32. */
2047 props->minSubgroupSize = 32;
2048 props->requiredSubgroupSizeStages = VK_SHADER_STAGE_COMPUTE_BIT;
2049 }
2050 break;
2051 }
2052 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES:
2053 radv_get_physical_device_properties_1_1(pdevice, (void *)ext);
2054 break;
2055 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES:
2056 radv_get_physical_device_properties_1_2(pdevice, (void *)ext);
2057 break;
2058 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINE_RASTERIZATION_PROPERTIES_EXT: {
2059 VkPhysicalDeviceLineRasterizationPropertiesEXT *props =
2060 (VkPhysicalDeviceLineRasterizationPropertiesEXT *)ext;
2061 props->lineSubPixelPrecisionBits = 4;
2062 break;
2063 }
2064 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_PROPERTIES_EXT: {
2065 VkPhysicalDeviceRobustness2PropertiesEXT *properties =
2066 (VkPhysicalDeviceRobustness2PropertiesEXT *)ext;
2067 properties->robustStorageBufferAccessSizeAlignment = 4;
2068 properties->robustUniformBufferAccessSizeAlignment = 4;
2069 break;
2070 }
2071 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_PROPERTIES_EXT: {
2072 VkPhysicalDeviceCustomBorderColorPropertiesEXT *props =
2073 (VkPhysicalDeviceCustomBorderColorPropertiesEXT *)ext;
2074 props->maxCustomBorderColorSamplers = RADV_BORDER_COLOR_COUNT;
2075 break;
2076 }
2077 default:
2078 break;
2079 }
2080 }
2081 }
2082
2083 static void radv_get_physical_device_queue_family_properties(
2084 struct radv_physical_device* pdevice,
2085 uint32_t* pCount,
2086 VkQueueFamilyProperties** pQueueFamilyProperties)
2087 {
2088 int num_queue_families = 1;
2089 int idx;
2090 if (pdevice->rad_info.num_rings[RING_COMPUTE] > 0 &&
2091 !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE))
2092 num_queue_families++;
2093
2094 if (pQueueFamilyProperties == NULL) {
2095 *pCount = num_queue_families;
2096 return;
2097 }
2098
2099 if (!*pCount)
2100 return;
2101
2102 idx = 0;
2103 if (*pCount >= 1) {
2104 *pQueueFamilyProperties[idx] = (VkQueueFamilyProperties) {
2105 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
2106 VK_QUEUE_COMPUTE_BIT |
2107 VK_QUEUE_TRANSFER_BIT |
2108 VK_QUEUE_SPARSE_BINDING_BIT,
2109 .queueCount = 1,
2110 .timestampValidBits = 64,
2111 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
2112 };
2113 idx++;
2114 }
2115
2116 if (pdevice->rad_info.num_rings[RING_COMPUTE] > 0 &&
2117 !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE)) {
2118 if (*pCount > idx) {
2119 *pQueueFamilyProperties[idx] = (VkQueueFamilyProperties) {
2120 .queueFlags = VK_QUEUE_COMPUTE_BIT |
2121 VK_QUEUE_TRANSFER_BIT |
2122 VK_QUEUE_SPARSE_BINDING_BIT,
2123 .queueCount = pdevice->rad_info.num_rings[RING_COMPUTE],
2124 .timestampValidBits = 64,
2125 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
2126 };
2127 idx++;
2128 }
2129 }
2130 *pCount = idx;
2131 }
2132
2133 void radv_GetPhysicalDeviceQueueFamilyProperties(
2134 VkPhysicalDevice physicalDevice,
2135 uint32_t* pCount,
2136 VkQueueFamilyProperties* pQueueFamilyProperties)
2137 {
2138 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
2139 if (!pQueueFamilyProperties) {
2140 radv_get_physical_device_queue_family_properties(pdevice, pCount, NULL);
2141 return;
2142 }
2143 VkQueueFamilyProperties *properties[] = {
2144 pQueueFamilyProperties + 0,
2145 pQueueFamilyProperties + 1,
2146 pQueueFamilyProperties + 2,
2147 };
2148 radv_get_physical_device_queue_family_properties(pdevice, pCount, properties);
2149 assert(*pCount <= 3);
2150 }
2151
2152 void radv_GetPhysicalDeviceQueueFamilyProperties2(
2153 VkPhysicalDevice physicalDevice,
2154 uint32_t* pCount,
2155 VkQueueFamilyProperties2 *pQueueFamilyProperties)
2156 {
2157 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
2158 if (!pQueueFamilyProperties) {
2159 radv_get_physical_device_queue_family_properties(pdevice, pCount, NULL);
2160 return;
2161 }
2162 VkQueueFamilyProperties *properties[] = {
2163 &pQueueFamilyProperties[0].queueFamilyProperties,
2164 &pQueueFamilyProperties[1].queueFamilyProperties,
2165 &pQueueFamilyProperties[2].queueFamilyProperties,
2166 };
2167 radv_get_physical_device_queue_family_properties(pdevice, pCount, properties);
2168 assert(*pCount <= 3);
2169 }
2170
2171 void radv_GetPhysicalDeviceMemoryProperties(
2172 VkPhysicalDevice physicalDevice,
2173 VkPhysicalDeviceMemoryProperties *pMemoryProperties)
2174 {
2175 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
2176
2177 *pMemoryProperties = physical_device->memory_properties;
2178 }
2179
2180 static void
2181 radv_get_memory_budget_properties(VkPhysicalDevice physicalDevice,
2182 VkPhysicalDeviceMemoryBudgetPropertiesEXT *memoryBudget)
2183 {
2184 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
2185 VkPhysicalDeviceMemoryProperties *memory_properties = &device->memory_properties;
2186 uint64_t visible_vram_size = radv_get_visible_vram_size(device);
2187 uint64_t vram_size = radv_get_vram_size(device);
2188 uint64_t gtt_size = device->rad_info.gart_size;
2189 uint64_t heap_budget, heap_usage;
2190
2191 /* For all memory heaps, the computation of budget is as follow:
2192 * heap_budget = heap_size - global_heap_usage + app_heap_usage
2193 *
2194 * The Vulkan spec 1.1.97 says that the budget should include any
2195 * currently allocated device memory.
2196 *
2197 * Note that the application heap usages are not really accurate (eg.
2198 * in presence of shared buffers).
2199 */
2200 for (int i = 0; i < device->memory_properties.memoryTypeCount; i++) {
2201 uint32_t heap_index = device->memory_properties.memoryTypes[i].heapIndex;
2202
2203 if ((device->memory_domains[i] & RADEON_DOMAIN_VRAM) && (device->memory_flags[i] & RADEON_FLAG_NO_CPU_ACCESS)) {
2204 heap_usage = device->ws->query_value(device->ws,
2205 RADEON_ALLOCATED_VRAM);
2206
2207 heap_budget = vram_size -
2208 device->ws->query_value(device->ws, RADEON_VRAM_USAGE) +
2209 heap_usage;
2210
2211 memoryBudget->heapBudget[heap_index] = heap_budget;
2212 memoryBudget->heapUsage[heap_index] = heap_usage;
2213 } else if (device->memory_domains[i] & RADEON_DOMAIN_VRAM) {
2214 heap_usage = device->ws->query_value(device->ws,
2215 RADEON_ALLOCATED_VRAM_VIS);
2216
2217 heap_budget = visible_vram_size -
2218 device->ws->query_value(device->ws, RADEON_VRAM_VIS_USAGE) +
2219 heap_usage;
2220
2221 memoryBudget->heapBudget[heap_index] = heap_budget;
2222 memoryBudget->heapUsage[heap_index] = heap_usage;
2223 } else {
2224 assert(device->memory_domains[i] & RADEON_DOMAIN_GTT);
2225
2226 heap_usage = device->ws->query_value(device->ws,
2227 RADEON_ALLOCATED_GTT);
2228
2229 heap_budget = gtt_size -
2230 device->ws->query_value(device->ws, RADEON_GTT_USAGE) +
2231 heap_usage;
2232
2233 memoryBudget->heapBudget[heap_index] = heap_budget;
2234 memoryBudget->heapUsage[heap_index] = heap_usage;
2235 }
2236 }
2237
2238 /* The heapBudget and heapUsage values must be zero for array elements
2239 * greater than or equal to
2240 * VkPhysicalDeviceMemoryProperties::memoryHeapCount.
2241 */
2242 for (uint32_t i = memory_properties->memoryHeapCount; i < VK_MAX_MEMORY_HEAPS; i++) {
2243 memoryBudget->heapBudget[i] = 0;
2244 memoryBudget->heapUsage[i] = 0;
2245 }
2246 }
2247
2248 void radv_GetPhysicalDeviceMemoryProperties2(
2249 VkPhysicalDevice physicalDevice,
2250 VkPhysicalDeviceMemoryProperties2 *pMemoryProperties)
2251 {
2252 radv_GetPhysicalDeviceMemoryProperties(physicalDevice,
2253 &pMemoryProperties->memoryProperties);
2254
2255 VkPhysicalDeviceMemoryBudgetPropertiesEXT *memory_budget =
2256 vk_find_struct(pMemoryProperties->pNext,
2257 PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT);
2258 if (memory_budget)
2259 radv_get_memory_budget_properties(physicalDevice, memory_budget);
2260 }
2261
2262 VkResult radv_GetMemoryHostPointerPropertiesEXT(
2263 VkDevice _device,
2264 VkExternalMemoryHandleTypeFlagBits handleType,
2265 const void *pHostPointer,
2266 VkMemoryHostPointerPropertiesEXT *pMemoryHostPointerProperties)
2267 {
2268 RADV_FROM_HANDLE(radv_device, device, _device);
2269
2270 switch (handleType)
2271 {
2272 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT: {
2273 const struct radv_physical_device *physical_device = device->physical_device;
2274 uint32_t memoryTypeBits = 0;
2275 for (int i = 0; i < physical_device->memory_properties.memoryTypeCount; i++) {
2276 if (physical_device->memory_domains[i] == RADEON_DOMAIN_GTT &&
2277 !(physical_device->memory_flags[i] & RADEON_FLAG_GTT_WC)) {
2278 memoryTypeBits = (1 << i);
2279 break;
2280 }
2281 }
2282 pMemoryHostPointerProperties->memoryTypeBits = memoryTypeBits;
2283 return VK_SUCCESS;
2284 }
2285 default:
2286 return VK_ERROR_INVALID_EXTERNAL_HANDLE;
2287 }
2288 }
2289
2290 static enum radeon_ctx_priority
2291 radv_get_queue_global_priority(const VkDeviceQueueGlobalPriorityCreateInfoEXT *pObj)
2292 {
2293 /* Default to MEDIUM when a specific global priority isn't requested */
2294 if (!pObj)
2295 return RADEON_CTX_PRIORITY_MEDIUM;
2296
2297 switch(pObj->globalPriority) {
2298 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
2299 return RADEON_CTX_PRIORITY_REALTIME;
2300 case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
2301 return RADEON_CTX_PRIORITY_HIGH;
2302 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
2303 return RADEON_CTX_PRIORITY_MEDIUM;
2304 case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
2305 return RADEON_CTX_PRIORITY_LOW;
2306 default:
2307 unreachable("Illegal global priority value");
2308 return RADEON_CTX_PRIORITY_INVALID;
2309 }
2310 }
2311
2312 static int
2313 radv_queue_init(struct radv_device *device, struct radv_queue *queue,
2314 uint32_t queue_family_index, int idx,
2315 VkDeviceQueueCreateFlags flags,
2316 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority)
2317 {
2318 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
2319 queue->device = device;
2320 queue->queue_family_index = queue_family_index;
2321 queue->queue_idx = idx;
2322 queue->priority = radv_get_queue_global_priority(global_priority);
2323 queue->flags = flags;
2324 queue->hw_ctx = NULL;
2325
2326 VkResult result = device->ws->ctx_create(device->ws, queue->priority, &queue->hw_ctx);
2327 if (result != VK_SUCCESS)
2328 return vk_error(device->instance, result);
2329
2330 list_inithead(&queue->pending_submissions);
2331 pthread_mutex_init(&queue->pending_mutex, NULL);
2332
2333 pthread_mutex_init(&queue->thread_mutex, NULL);
2334 queue->thread_submission = NULL;
2335 queue->thread_running = queue->thread_exit = false;
2336 result = radv_create_pthread_cond(&queue->thread_cond);
2337 if (result != VK_SUCCESS)
2338 return vk_error(device->instance, result);
2339
2340 return VK_SUCCESS;
2341 }
2342
2343 static void
2344 radv_queue_finish(struct radv_queue *queue)
2345 {
2346 if (queue->thread_running) {
2347 p_atomic_set(&queue->thread_exit, true);
2348 pthread_cond_broadcast(&queue->thread_cond);
2349 pthread_join(queue->submission_thread, NULL);
2350 }
2351 pthread_cond_destroy(&queue->thread_cond);
2352 pthread_mutex_destroy(&queue->pending_mutex);
2353 pthread_mutex_destroy(&queue->thread_mutex);
2354
2355 if (queue->hw_ctx)
2356 queue->device->ws->ctx_destroy(queue->hw_ctx);
2357
2358 if (queue->initial_full_flush_preamble_cs)
2359 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
2360 if (queue->initial_preamble_cs)
2361 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
2362 if (queue->continue_preamble_cs)
2363 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
2364 if (queue->descriptor_bo)
2365 queue->device->ws->buffer_destroy(queue->descriptor_bo);
2366 if (queue->scratch_bo)
2367 queue->device->ws->buffer_destroy(queue->scratch_bo);
2368 if (queue->esgs_ring_bo)
2369 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
2370 if (queue->gsvs_ring_bo)
2371 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
2372 if (queue->tess_rings_bo)
2373 queue->device->ws->buffer_destroy(queue->tess_rings_bo);
2374 if (queue->gds_bo)
2375 queue->device->ws->buffer_destroy(queue->gds_bo);
2376 if (queue->gds_oa_bo)
2377 queue->device->ws->buffer_destroy(queue->gds_oa_bo);
2378 if (queue->compute_scratch_bo)
2379 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
2380 }
2381
2382 static void
2383 radv_bo_list_init(struct radv_bo_list *bo_list)
2384 {
2385 pthread_mutex_init(&bo_list->mutex, NULL);
2386 bo_list->list.count = bo_list->capacity = 0;
2387 bo_list->list.bos = NULL;
2388 }
2389
2390 static void
2391 radv_bo_list_finish(struct radv_bo_list *bo_list)
2392 {
2393 free(bo_list->list.bos);
2394 pthread_mutex_destroy(&bo_list->mutex);
2395 }
2396
2397 VkResult radv_bo_list_add(struct radv_device *device,
2398 struct radeon_winsys_bo *bo)
2399 {
2400 struct radv_bo_list *bo_list = &device->bo_list;
2401
2402 if (bo->is_local)
2403 return VK_SUCCESS;
2404
2405 if (unlikely(!device->use_global_bo_list))
2406 return VK_SUCCESS;
2407
2408 pthread_mutex_lock(&bo_list->mutex);
2409 if (bo_list->list.count == bo_list->capacity) {
2410 unsigned capacity = MAX2(4, bo_list->capacity * 2);
2411 void *data = realloc(bo_list->list.bos, capacity * sizeof(struct radeon_winsys_bo*));
2412
2413 if (!data) {
2414 pthread_mutex_unlock(&bo_list->mutex);
2415 return VK_ERROR_OUT_OF_HOST_MEMORY;
2416 }
2417
2418 bo_list->list.bos = (struct radeon_winsys_bo**)data;
2419 bo_list->capacity = capacity;
2420 }
2421
2422 bo_list->list.bos[bo_list->list.count++] = bo;
2423 pthread_mutex_unlock(&bo_list->mutex);
2424 return VK_SUCCESS;
2425 }
2426
2427 void radv_bo_list_remove(struct radv_device *device,
2428 struct radeon_winsys_bo *bo)
2429 {
2430 struct radv_bo_list *bo_list = &device->bo_list;
2431
2432 if (bo->is_local)
2433 return;
2434
2435 if (unlikely(!device->use_global_bo_list))
2436 return;
2437
2438 pthread_mutex_lock(&bo_list->mutex);
2439 /* Loop the list backwards so we find the most recently added
2440 * memory first. */
2441 for(unsigned i = bo_list->list.count; i-- > 0;) {
2442 if (bo_list->list.bos[i] == bo) {
2443 bo_list->list.bos[i] = bo_list->list.bos[bo_list->list.count - 1];
2444 --bo_list->list.count;
2445 break;
2446 }
2447 }
2448 pthread_mutex_unlock(&bo_list->mutex);
2449 }
2450
2451 static void
2452 radv_device_init_gs_info(struct radv_device *device)
2453 {
2454 device->gs_table_depth = ac_get_gs_table_depth(device->physical_device->rad_info.chip_class,
2455 device->physical_device->rad_info.family);
2456 }
2457
2458 static int radv_get_device_extension_index(const char *name)
2459 {
2460 for (unsigned i = 0; i < RADV_DEVICE_EXTENSION_COUNT; ++i) {
2461 if (strcmp(name, radv_device_extensions[i].extensionName) == 0)
2462 return i;
2463 }
2464 return -1;
2465 }
2466
2467 static int
2468 radv_get_int_debug_option(const char *name, int default_value)
2469 {
2470 const char *str;
2471 int result;
2472
2473 str = getenv(name);
2474 if (!str) {
2475 result = default_value;
2476 } else {
2477 char *endptr;
2478
2479 result = strtol(str, &endptr, 0);
2480 if (str == endptr) {
2481 /* No digits founs. */
2482 result = default_value;
2483 }
2484 }
2485
2486 return result;
2487 }
2488
2489 static void
2490 radv_device_init_dispatch(struct radv_device *device)
2491 {
2492 const struct radv_instance *instance = device->physical_device->instance;
2493 const struct radv_device_dispatch_table *dispatch_table_layer = NULL;
2494 bool unchecked = instance->debug_flags & RADV_DEBUG_ALL_ENTRYPOINTS;
2495 int radv_thread_trace = radv_get_int_debug_option("RADV_THREAD_TRACE", -1);
2496
2497 if (radv_thread_trace >= 0) {
2498 /* Use device entrypoints from the SQTT layer if enabled. */
2499 dispatch_table_layer = &sqtt_device_dispatch_table;
2500 }
2501
2502 for (unsigned i = 0; i < ARRAY_SIZE(device->dispatch.entrypoints); i++) {
2503 /* Vulkan requires that entrypoints for extensions which have not been
2504 * enabled must not be advertised.
2505 */
2506 if (!unchecked &&
2507 !radv_device_entrypoint_is_enabled(i, instance->apiVersion,
2508 &instance->enabled_extensions,
2509 &device->enabled_extensions)) {
2510 device->dispatch.entrypoints[i] = NULL;
2511 } else if (dispatch_table_layer &&
2512 dispatch_table_layer->entrypoints[i]) {
2513 device->dispatch.entrypoints[i] =
2514 dispatch_table_layer->entrypoints[i];
2515 } else {
2516 device->dispatch.entrypoints[i] =
2517 radv_device_dispatch_table.entrypoints[i];
2518 }
2519 }
2520 }
2521
2522 static VkResult
2523 radv_create_pthread_cond(pthread_cond_t *cond)
2524 {
2525 pthread_condattr_t condattr;
2526 if (pthread_condattr_init(&condattr)) {
2527 return VK_ERROR_INITIALIZATION_FAILED;
2528 }
2529
2530 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)) {
2531 pthread_condattr_destroy(&condattr);
2532 return VK_ERROR_INITIALIZATION_FAILED;
2533 }
2534 if (pthread_cond_init(cond, &condattr)) {
2535 pthread_condattr_destroy(&condattr);
2536 return VK_ERROR_INITIALIZATION_FAILED;
2537 }
2538 pthread_condattr_destroy(&condattr);
2539 return VK_SUCCESS;
2540 }
2541
2542 static VkResult
2543 check_physical_device_features(VkPhysicalDevice physicalDevice,
2544 const VkPhysicalDeviceFeatures *features)
2545 {
2546 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
2547 VkPhysicalDeviceFeatures supported_features;
2548 radv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
2549 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
2550 VkBool32 *enabled_feature = (VkBool32 *)features;
2551 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
2552 for (uint32_t i = 0; i < num_features; i++) {
2553 if (enabled_feature[i] && !supported_feature[i])
2554 return vk_error(physical_device->instance, VK_ERROR_FEATURE_NOT_PRESENT);
2555 }
2556
2557 return VK_SUCCESS;
2558 }
2559
2560 static VkResult radv_device_init_border_color(struct radv_device *device)
2561 {
2562 device->border_color_data.bo =
2563 device->ws->buffer_create(device->ws,
2564 RADV_BORDER_COLOR_BUFFER_SIZE,
2565 4096,
2566 RADEON_DOMAIN_VRAM,
2567 RADEON_FLAG_CPU_ACCESS |
2568 RADEON_FLAG_READ_ONLY |
2569 RADEON_FLAG_NO_INTERPROCESS_SHARING,
2570 RADV_BO_PRIORITY_SHADER);
2571
2572 if (device->border_color_data.bo == NULL)
2573 return vk_error(device->physical_device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
2574
2575 device->border_color_data.colors_gpu_ptr =
2576 device->ws->buffer_map(device->border_color_data.bo);
2577 if (!device->border_color_data.colors_gpu_ptr)
2578 return vk_error(device->physical_device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
2579 pthread_mutex_init(&device->border_color_data.mutex, NULL);
2580
2581 return VK_SUCCESS;
2582 }
2583
2584 static void radv_device_finish_border_color(struct radv_device *device)
2585 {
2586 if (device->border_color_data.bo) {
2587 device->ws->buffer_destroy(device->border_color_data.bo);
2588
2589 pthread_mutex_destroy(&device->border_color_data.mutex);
2590 }
2591 }
2592
2593 VkResult
2594 _radv_device_set_lost(struct radv_device *device,
2595 const char *file, int line,
2596 const char *msg, ...)
2597 {
2598 VkResult err;
2599 va_list ap;
2600
2601 p_atomic_inc(&device->lost);
2602
2603 va_start(ap, msg);
2604 err = __vk_errorv(device->physical_device->instance, device,
2605 VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
2606 VK_ERROR_DEVICE_LOST, file, line, msg, ap);
2607 va_end(ap);
2608
2609 return err;
2610 }
2611
2612 VkResult radv_CreateDevice(
2613 VkPhysicalDevice physicalDevice,
2614 const VkDeviceCreateInfo* pCreateInfo,
2615 const VkAllocationCallbacks* pAllocator,
2616 VkDevice* pDevice)
2617 {
2618 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
2619 VkResult result;
2620 struct radv_device *device;
2621
2622 bool keep_shader_info = false;
2623 bool robust_buffer_access = false;
2624 bool overallocation_disallowed = false;
2625 bool custom_border_colors = false;
2626
2627 /* Check enabled features */
2628 if (pCreateInfo->pEnabledFeatures) {
2629 result = check_physical_device_features(physicalDevice,
2630 pCreateInfo->pEnabledFeatures);
2631 if (result != VK_SUCCESS)
2632 return result;
2633
2634 if (pCreateInfo->pEnabledFeatures->robustBufferAccess)
2635 robust_buffer_access = true;
2636 }
2637
2638 vk_foreach_struct_const(ext, pCreateInfo->pNext) {
2639 switch (ext->sType) {
2640 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2: {
2641 const VkPhysicalDeviceFeatures2 *features = (const void *)ext;
2642 result = check_physical_device_features(physicalDevice,
2643 &features->features);
2644 if (result != VK_SUCCESS)
2645 return result;
2646
2647 if (features->features.robustBufferAccess)
2648 robust_buffer_access = true;
2649 break;
2650 }
2651 case VK_STRUCTURE_TYPE_DEVICE_MEMORY_OVERALLOCATION_CREATE_INFO_AMD: {
2652 const VkDeviceMemoryOverallocationCreateInfoAMD *overallocation = (const void *)ext;
2653 if (overallocation->overallocationBehavior == VK_MEMORY_OVERALLOCATION_BEHAVIOR_DISALLOWED_AMD)
2654 overallocation_disallowed = true;
2655 break;
2656 }
2657 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT: {
2658 const VkPhysicalDeviceCustomBorderColorFeaturesEXT *border_color_features = (const void *)ext;
2659 custom_border_colors = border_color_features->customBorderColors;
2660 break;
2661 }
2662 default:
2663 break;
2664 }
2665 }
2666
2667 device = vk_zalloc2(&physical_device->instance->alloc, pAllocator,
2668 sizeof(*device), 8,
2669 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2670 if (!device)
2671 return vk_error(physical_device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2672
2673 vk_device_init(&device->vk, pCreateInfo,
2674 &physical_device->instance->alloc, pAllocator);
2675
2676 device->instance = physical_device->instance;
2677 device->physical_device = physical_device;
2678
2679 device->ws = physical_device->ws;
2680
2681 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
2682 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
2683 int index = radv_get_device_extension_index(ext_name);
2684 if (index < 0 || !physical_device->supported_extensions.extensions[index]) {
2685 vk_free(&device->vk.alloc, device);
2686 return vk_error(physical_device->instance, VK_ERROR_EXTENSION_NOT_PRESENT);
2687 }
2688
2689 device->enabled_extensions.extensions[index] = true;
2690 }
2691
2692 radv_device_init_dispatch(device);
2693
2694 keep_shader_info = device->enabled_extensions.AMD_shader_info;
2695
2696 /* With update after bind we can't attach bo's to the command buffer
2697 * from the descriptor set anymore, so we have to use a global BO list.
2698 */
2699 device->use_global_bo_list =
2700 (device->instance->perftest_flags & RADV_PERFTEST_BO_LIST) ||
2701 device->enabled_extensions.EXT_descriptor_indexing ||
2702 device->enabled_extensions.EXT_buffer_device_address ||
2703 device->enabled_extensions.KHR_buffer_device_address;
2704
2705 device->robust_buffer_access = robust_buffer_access;
2706
2707 mtx_init(&device->shader_slab_mutex, mtx_plain);
2708 list_inithead(&device->shader_slabs);
2709
2710 device->overallocation_disallowed = overallocation_disallowed;
2711 mtx_init(&device->overallocation_mutex, mtx_plain);
2712
2713 radv_bo_list_init(&device->bo_list);
2714
2715 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
2716 const VkDeviceQueueCreateInfo *queue_create = &pCreateInfo->pQueueCreateInfos[i];
2717 uint32_t qfi = queue_create->queueFamilyIndex;
2718 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority =
2719 vk_find_struct_const(queue_create->pNext, DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
2720
2721 assert(!global_priority || device->physical_device->rad_info.has_ctx_priority);
2722
2723 device->queues[qfi] = vk_alloc(&device->vk.alloc,
2724 queue_create->queueCount * sizeof(struct radv_queue), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2725 if (!device->queues[qfi]) {
2726 result = VK_ERROR_OUT_OF_HOST_MEMORY;
2727 goto fail;
2728 }
2729
2730 memset(device->queues[qfi], 0, queue_create->queueCount * sizeof(struct radv_queue));
2731
2732 device->queue_count[qfi] = queue_create->queueCount;
2733
2734 for (unsigned q = 0; q < queue_create->queueCount; q++) {
2735 result = radv_queue_init(device, &device->queues[qfi][q],
2736 qfi, q, queue_create->flags,
2737 global_priority);
2738 if (result != VK_SUCCESS)
2739 goto fail;
2740 }
2741 }
2742
2743 device->pbb_allowed = device->physical_device->rad_info.chip_class >= GFX9 &&
2744 !(device->instance->debug_flags & RADV_DEBUG_NOBINNING);
2745
2746 /* Disable DFSM by default. As of 2019-09-15 Talos on Low is still 3% slower on Raven. */
2747 device->dfsm_allowed = device->pbb_allowed &&
2748 (device->instance->perftest_flags & RADV_PERFTEST_DFSM);
2749
2750 device->always_use_syncobj = device->physical_device->rad_info.has_syncobj_wait_for_submit;
2751
2752 /* The maximum number of scratch waves. Scratch space isn't divided
2753 * evenly between CUs. The number is only a function of the number of CUs.
2754 * We can decrease the constant to decrease the scratch buffer size.
2755 *
2756 * sctx->scratch_waves must be >= the maximum possible size of
2757 * 1 threadgroup, so that the hw doesn't hang from being unable
2758 * to start any.
2759 *
2760 * The recommended value is 4 per CU at most. Higher numbers don't
2761 * bring much benefit, but they still occupy chip resources (think
2762 * async compute). I've seen ~2% performance difference between 4 and 32.
2763 */
2764 uint32_t max_threads_per_block = 2048;
2765 device->scratch_waves = MAX2(32 * physical_device->rad_info.num_good_compute_units,
2766 max_threads_per_block / 64);
2767
2768 device->dispatch_initiator = S_00B800_COMPUTE_SHADER_EN(1);
2769
2770 if (device->physical_device->rad_info.chip_class >= GFX7) {
2771 /* If the KMD allows it (there is a KMD hw register for it),
2772 * allow launching waves out-of-order.
2773 */
2774 device->dispatch_initiator |= S_00B800_ORDER_MODE(1);
2775 }
2776
2777 radv_device_init_gs_info(device);
2778
2779 device->tess_offchip_block_dw_size =
2780 device->physical_device->rad_info.family == CHIP_HAWAII ? 4096 : 8192;
2781
2782 if (getenv("RADV_TRACE_FILE")) {
2783 const char *filename = getenv("RADV_TRACE_FILE");
2784
2785 keep_shader_info = true;
2786
2787 if (!radv_init_trace(device))
2788 goto fail;
2789
2790 fprintf(stderr, "*****************************************************************************\n");
2791 fprintf(stderr, "* WARNING: RADV_TRACE_FILE is costly and should only be used for debugging! *\n");
2792 fprintf(stderr, "*****************************************************************************\n");
2793
2794 fprintf(stderr, "Trace file will be dumped to %s\n", filename);
2795 radv_dump_enabled_options(device, stderr);
2796 }
2797
2798 int radv_thread_trace = radv_get_int_debug_option("RADV_THREAD_TRACE", -1);
2799 if (radv_thread_trace >= 0) {
2800 fprintf(stderr, "*************************************************\n");
2801 fprintf(stderr, "* WARNING: Thread trace support is experimental *\n");
2802 fprintf(stderr, "*************************************************\n");
2803
2804 if (device->physical_device->rad_info.chip_class < GFX8) {
2805 fprintf(stderr, "GPU hardware not supported: refer to "
2806 "the RGP documentation for the list of "
2807 "supported GPUs!\n");
2808 abort();
2809 }
2810
2811 /* Default buffer size set to 1MB per SE. */
2812 device->thread_trace_buffer_size =
2813 radv_get_int_debug_option("RADV_THREAD_TRACE_BUFFER_SIZE", 1024 * 1024);
2814 device->thread_trace_start_frame = radv_thread_trace;
2815
2816 if (!radv_thread_trace_init(device))
2817 goto fail;
2818 }
2819
2820 if (getenv("RADV_TRAP_HANDLER")) {
2821 /* TODO: Add support for more hardware. */
2822 assert(device->physical_device->rad_info.chip_class == GFX8);
2823
2824 fprintf(stderr, "**********************************************************************\n");
2825 fprintf(stderr, "* WARNING: RADV_TRAP_HANDLER is experimental and only for debugging! *\n");
2826 fprintf(stderr, "**********************************************************************\n");
2827
2828 /* To get the disassembly of the faulty shaders, we have to
2829 * keep some shader info around.
2830 */
2831 keep_shader_info = true;
2832
2833 if (!radv_trap_handler_init(device))
2834 goto fail;
2835 }
2836
2837 device->keep_shader_info = keep_shader_info;
2838 result = radv_device_init_meta(device);
2839 if (result != VK_SUCCESS)
2840 goto fail;
2841
2842 radv_device_init_msaa(device);
2843
2844 /* If the border color extension is enabled, let's create the buffer we need. */
2845 if (custom_border_colors) {
2846 result = radv_device_init_border_color(device);
2847 if (result != VK_SUCCESS)
2848 goto fail;
2849 }
2850
2851 for (int family = 0; family < RADV_MAX_QUEUE_FAMILIES; ++family) {
2852 device->empty_cs[family] = device->ws->cs_create(device->ws, family);
2853 if (!device->empty_cs[family])
2854 goto fail;
2855
2856 switch (family) {
2857 case RADV_QUEUE_GENERAL:
2858 radeon_emit(device->empty_cs[family], PKT3(PKT3_CONTEXT_CONTROL, 1, 0));
2859 radeon_emit(device->empty_cs[family], CC0_UPDATE_LOAD_ENABLES(1));
2860 radeon_emit(device->empty_cs[family], CC1_UPDATE_SHADOW_ENABLES(1));
2861 break;
2862 case RADV_QUEUE_COMPUTE:
2863 radeon_emit(device->empty_cs[family], PKT3(PKT3_NOP, 0, 0));
2864 radeon_emit(device->empty_cs[family], 0);
2865 break;
2866 }
2867
2868 result = device->ws->cs_finalize(device->empty_cs[family]);
2869 if (result != VK_SUCCESS)
2870 goto fail;
2871 }
2872
2873 if (device->physical_device->rad_info.chip_class >= GFX7)
2874 cik_create_gfx_config(device);
2875
2876 VkPipelineCacheCreateInfo ci;
2877 ci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
2878 ci.pNext = NULL;
2879 ci.flags = 0;
2880 ci.pInitialData = NULL;
2881 ci.initialDataSize = 0;
2882 VkPipelineCache pc;
2883 result = radv_CreatePipelineCache(radv_device_to_handle(device),
2884 &ci, NULL, &pc);
2885 if (result != VK_SUCCESS)
2886 goto fail_meta;
2887
2888 device->mem_cache = radv_pipeline_cache_from_handle(pc);
2889
2890 result = radv_create_pthread_cond(&device->timeline_cond);
2891 if (result != VK_SUCCESS)
2892 goto fail_mem_cache;
2893
2894 device->force_aniso =
2895 MIN2(16, radv_get_int_debug_option("RADV_TEX_ANISO", -1));
2896 if (device->force_aniso >= 0) {
2897 fprintf(stderr, "radv: Forcing anisotropy filter to %ix\n",
2898 1 << util_logbase2(device->force_aniso));
2899 }
2900
2901 *pDevice = radv_device_to_handle(device);
2902 return VK_SUCCESS;
2903
2904 fail_mem_cache:
2905 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
2906 fail_meta:
2907 radv_device_finish_meta(device);
2908 fail:
2909 radv_bo_list_finish(&device->bo_list);
2910
2911 radv_thread_trace_finish(device);
2912
2913 radv_trap_handler_finish(device);
2914
2915 if (device->trace_bo)
2916 device->ws->buffer_destroy(device->trace_bo);
2917
2918 if (device->gfx_init)
2919 device->ws->buffer_destroy(device->gfx_init);
2920
2921 radv_device_finish_border_color(device);
2922
2923 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
2924 for (unsigned q = 0; q < device->queue_count[i]; q++)
2925 radv_queue_finish(&device->queues[i][q]);
2926 if (device->queue_count[i])
2927 vk_free(&device->vk.alloc, device->queues[i]);
2928 }
2929
2930 vk_free(&device->vk.alloc, device);
2931 return result;
2932 }
2933
2934 void radv_DestroyDevice(
2935 VkDevice _device,
2936 const VkAllocationCallbacks* pAllocator)
2937 {
2938 RADV_FROM_HANDLE(radv_device, device, _device);
2939
2940 if (!device)
2941 return;
2942
2943 if (device->trace_bo)
2944 device->ws->buffer_destroy(device->trace_bo);
2945
2946 if (device->gfx_init)
2947 device->ws->buffer_destroy(device->gfx_init);
2948
2949 radv_device_finish_border_color(device);
2950
2951 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
2952 for (unsigned q = 0; q < device->queue_count[i]; q++)
2953 radv_queue_finish(&device->queues[i][q]);
2954 if (device->queue_count[i])
2955 vk_free(&device->vk.alloc, device->queues[i]);
2956 if (device->empty_cs[i])
2957 device->ws->cs_destroy(device->empty_cs[i]);
2958 }
2959 radv_device_finish_meta(device);
2960
2961 VkPipelineCache pc = radv_pipeline_cache_to_handle(device->mem_cache);
2962 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
2963
2964 radv_trap_handler_finish(device);
2965
2966 radv_destroy_shader_slabs(device);
2967
2968 pthread_cond_destroy(&device->timeline_cond);
2969 radv_bo_list_finish(&device->bo_list);
2970
2971 radv_thread_trace_finish(device);
2972
2973 vk_free(&device->vk.alloc, device);
2974 }
2975
2976 VkResult radv_EnumerateInstanceLayerProperties(
2977 uint32_t* pPropertyCount,
2978 VkLayerProperties* pProperties)
2979 {
2980 if (pProperties == NULL) {
2981 *pPropertyCount = 0;
2982 return VK_SUCCESS;
2983 }
2984
2985 /* None supported at this time */
2986 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
2987 }
2988
2989 VkResult radv_EnumerateDeviceLayerProperties(
2990 VkPhysicalDevice physicalDevice,
2991 uint32_t* pPropertyCount,
2992 VkLayerProperties* pProperties)
2993 {
2994 if (pProperties == NULL) {
2995 *pPropertyCount = 0;
2996 return VK_SUCCESS;
2997 }
2998
2999 /* None supported at this time */
3000 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
3001 }
3002
3003 void radv_GetDeviceQueue2(
3004 VkDevice _device,
3005 const VkDeviceQueueInfo2* pQueueInfo,
3006 VkQueue* pQueue)
3007 {
3008 RADV_FROM_HANDLE(radv_device, device, _device);
3009 struct radv_queue *queue;
3010
3011 queue = &device->queues[pQueueInfo->queueFamilyIndex][pQueueInfo->queueIndex];
3012 if (pQueueInfo->flags != queue->flags) {
3013 /* From the Vulkan 1.1.70 spec:
3014 *
3015 * "The queue returned by vkGetDeviceQueue2 must have the same
3016 * flags value from this structure as that used at device
3017 * creation time in a VkDeviceQueueCreateInfo instance. If no
3018 * matching flags were specified at device creation time then
3019 * pQueue will return VK_NULL_HANDLE."
3020 */
3021 *pQueue = VK_NULL_HANDLE;
3022 return;
3023 }
3024
3025 *pQueue = radv_queue_to_handle(queue);
3026 }
3027
3028 void radv_GetDeviceQueue(
3029 VkDevice _device,
3030 uint32_t queueFamilyIndex,
3031 uint32_t queueIndex,
3032 VkQueue* pQueue)
3033 {
3034 const VkDeviceQueueInfo2 info = (VkDeviceQueueInfo2) {
3035 .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
3036 .queueFamilyIndex = queueFamilyIndex,
3037 .queueIndex = queueIndex
3038 };
3039
3040 radv_GetDeviceQueue2(_device, &info, pQueue);
3041 }
3042
3043 static void
3044 fill_geom_tess_rings(struct radv_queue *queue,
3045 uint32_t *map,
3046 bool add_sample_positions,
3047 uint32_t esgs_ring_size,
3048 struct radeon_winsys_bo *esgs_ring_bo,
3049 uint32_t gsvs_ring_size,
3050 struct radeon_winsys_bo *gsvs_ring_bo,
3051 uint32_t tess_factor_ring_size,
3052 uint32_t tess_offchip_ring_offset,
3053 uint32_t tess_offchip_ring_size,
3054 struct radeon_winsys_bo *tess_rings_bo)
3055 {
3056 uint32_t *desc = &map[4];
3057
3058 if (esgs_ring_bo) {
3059 uint64_t esgs_va = radv_buffer_get_va(esgs_ring_bo);
3060
3061 /* stride 0, num records - size, add tid, swizzle, elsize4,
3062 index stride 64 */
3063 desc[0] = esgs_va;
3064 desc[1] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32) |
3065 S_008F04_SWIZZLE_ENABLE(true);
3066 desc[2] = esgs_ring_size;
3067 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3068 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3069 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3070 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
3071 S_008F0C_INDEX_STRIDE(3) |
3072 S_008F0C_ADD_TID_ENABLE(1);
3073
3074 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3075 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3076 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3077 S_008F0C_RESOURCE_LEVEL(1);
3078 } else {
3079 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3080 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
3081 S_008F0C_ELEMENT_SIZE(1);
3082 }
3083
3084 /* GS entry for ES->GS ring */
3085 /* stride 0, num records - size, elsize0,
3086 index stride 0 */
3087 desc[4] = esgs_va;
3088 desc[5] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32);
3089 desc[6] = esgs_ring_size;
3090 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3091 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3092 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3093 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3094
3095 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3096 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3097 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3098 S_008F0C_RESOURCE_LEVEL(1);
3099 } else {
3100 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3101 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3102 }
3103 }
3104
3105 desc += 8;
3106
3107 if (gsvs_ring_bo) {
3108 uint64_t gsvs_va = radv_buffer_get_va(gsvs_ring_bo);
3109
3110 /* VS entry for GS->VS ring */
3111 /* stride 0, num records - size, elsize0,
3112 index stride 0 */
3113 desc[0] = gsvs_va;
3114 desc[1] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32);
3115 desc[2] = gsvs_ring_size;
3116 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3117 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3118 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3119 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3120
3121 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3122 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3123 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3124 S_008F0C_RESOURCE_LEVEL(1);
3125 } else {
3126 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3127 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3128 }
3129
3130 /* stride gsvs_itemsize, num records 64
3131 elsize 4, index stride 16 */
3132 /* shader will patch stride and desc[2] */
3133 desc[4] = gsvs_va;
3134 desc[5] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32) |
3135 S_008F04_SWIZZLE_ENABLE(1);
3136 desc[6] = 0;
3137 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3138 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3139 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3140 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
3141 S_008F0C_INDEX_STRIDE(1) |
3142 S_008F0C_ADD_TID_ENABLE(true);
3143
3144 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3145 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3146 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3147 S_008F0C_RESOURCE_LEVEL(1);
3148 } else {
3149 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3150 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
3151 S_008F0C_ELEMENT_SIZE(1);
3152 }
3153
3154 }
3155
3156 desc += 8;
3157
3158 if (tess_rings_bo) {
3159 uint64_t tess_va = radv_buffer_get_va(tess_rings_bo);
3160 uint64_t tess_offchip_va = tess_va + tess_offchip_ring_offset;
3161
3162 desc[0] = tess_va;
3163 desc[1] = S_008F04_BASE_ADDRESS_HI(tess_va >> 32);
3164 desc[2] = tess_factor_ring_size;
3165 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3166 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3167 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3168 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3169
3170 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3171 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3172 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_RAW) |
3173 S_008F0C_RESOURCE_LEVEL(1);
3174 } else {
3175 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3176 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3177 }
3178
3179 desc[4] = tess_offchip_va;
3180 desc[5] = S_008F04_BASE_ADDRESS_HI(tess_offchip_va >> 32);
3181 desc[6] = tess_offchip_ring_size;
3182 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3183 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3184 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3185 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3186
3187 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3188 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3189 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_RAW) |
3190 S_008F0C_RESOURCE_LEVEL(1);
3191 } else {
3192 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3193 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3194 }
3195 }
3196
3197 desc += 8;
3198
3199 if (add_sample_positions) {
3200 /* add sample positions after all rings */
3201 memcpy(desc, queue->device->sample_locations_1x, 8);
3202 desc += 2;
3203 memcpy(desc, queue->device->sample_locations_2x, 16);
3204 desc += 4;
3205 memcpy(desc, queue->device->sample_locations_4x, 32);
3206 desc += 8;
3207 memcpy(desc, queue->device->sample_locations_8x, 64);
3208 }
3209 }
3210
3211 static unsigned
3212 radv_get_hs_offchip_param(struct radv_device *device, uint32_t *max_offchip_buffers_p)
3213 {
3214 bool double_offchip_buffers = device->physical_device->rad_info.chip_class >= GFX7 &&
3215 device->physical_device->rad_info.family != CHIP_CARRIZO &&
3216 device->physical_device->rad_info.family != CHIP_STONEY;
3217 unsigned max_offchip_buffers_per_se = double_offchip_buffers ? 128 : 64;
3218 unsigned max_offchip_buffers;
3219 unsigned offchip_granularity;
3220 unsigned hs_offchip_param;
3221
3222 /*
3223 * Per RadeonSI:
3224 * This must be one less than the maximum number due to a hw limitation.
3225 * Various hardware bugs need thGFX7
3226 *
3227 * Per AMDVLK:
3228 * Vega10 should limit max_offchip_buffers to 508 (4 * 127).
3229 * Gfx7 should limit max_offchip_buffers to 508
3230 * Gfx6 should limit max_offchip_buffers to 126 (2 * 63)
3231 *
3232 * Follow AMDVLK here.
3233 */
3234 if (device->physical_device->rad_info.chip_class >= GFX10) {
3235 max_offchip_buffers_per_se = 256;
3236 } else if (device->physical_device->rad_info.family == CHIP_VEGA10 ||
3237 device->physical_device->rad_info.chip_class == GFX7 ||
3238 device->physical_device->rad_info.chip_class == GFX6)
3239 --max_offchip_buffers_per_se;
3240
3241 max_offchip_buffers = max_offchip_buffers_per_se *
3242 device->physical_device->rad_info.max_se;
3243
3244 /* Hawaii has a bug with offchip buffers > 256 that can be worked
3245 * around by setting 4K granularity.
3246 */
3247 if (device->tess_offchip_block_dw_size == 4096) {
3248 assert(device->physical_device->rad_info.family == CHIP_HAWAII);
3249 offchip_granularity = V_03093C_X_4K_DWORDS;
3250 } else {
3251 assert(device->tess_offchip_block_dw_size == 8192);
3252 offchip_granularity = V_03093C_X_8K_DWORDS;
3253 }
3254
3255 switch (device->physical_device->rad_info.chip_class) {
3256 case GFX6:
3257 max_offchip_buffers = MIN2(max_offchip_buffers, 126);
3258 break;
3259 case GFX7:
3260 case GFX8:
3261 case GFX9:
3262 max_offchip_buffers = MIN2(max_offchip_buffers, 508);
3263 break;
3264 case GFX10:
3265 break;
3266 default:
3267 break;
3268 }
3269
3270 *max_offchip_buffers_p = max_offchip_buffers;
3271 if (device->physical_device->rad_info.chip_class >= GFX10_3) {
3272 hs_offchip_param = S_03093C_OFFCHIP_BUFFERING_GFX103(max_offchip_buffers - 1) |
3273 S_03093C_OFFCHIP_GRANULARITY_GFX103(offchip_granularity);
3274 } else if (device->physical_device->rad_info.chip_class >= GFX7) {
3275 if (device->physical_device->rad_info.chip_class >= GFX8)
3276 --max_offchip_buffers;
3277 hs_offchip_param =
3278 S_03093C_OFFCHIP_BUFFERING(max_offchip_buffers) |
3279 S_03093C_OFFCHIP_GRANULARITY(offchip_granularity);
3280 } else {
3281 hs_offchip_param =
3282 S_0089B0_OFFCHIP_BUFFERING(max_offchip_buffers);
3283 }
3284 return hs_offchip_param;
3285 }
3286
3287 static void
3288 radv_emit_gs_ring_sizes(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3289 struct radeon_winsys_bo *esgs_ring_bo,
3290 uint32_t esgs_ring_size,
3291 struct radeon_winsys_bo *gsvs_ring_bo,
3292 uint32_t gsvs_ring_size)
3293 {
3294 if (!esgs_ring_bo && !gsvs_ring_bo)
3295 return;
3296
3297 if (esgs_ring_bo)
3298 radv_cs_add_buffer(queue->device->ws, cs, esgs_ring_bo);
3299
3300 if (gsvs_ring_bo)
3301 radv_cs_add_buffer(queue->device->ws, cs, gsvs_ring_bo);
3302
3303 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
3304 radeon_set_uconfig_reg_seq(cs, R_030900_VGT_ESGS_RING_SIZE, 2);
3305 radeon_emit(cs, esgs_ring_size >> 8);
3306 radeon_emit(cs, gsvs_ring_size >> 8);
3307 } else {
3308 radeon_set_config_reg_seq(cs, R_0088C8_VGT_ESGS_RING_SIZE, 2);
3309 radeon_emit(cs, esgs_ring_size >> 8);
3310 radeon_emit(cs, gsvs_ring_size >> 8);
3311 }
3312 }
3313
3314 static void
3315 radv_emit_tess_factor_ring(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3316 unsigned hs_offchip_param, unsigned tf_ring_size,
3317 struct radeon_winsys_bo *tess_rings_bo)
3318 {
3319 uint64_t tf_va;
3320
3321 if (!tess_rings_bo)
3322 return;
3323
3324 tf_va = radv_buffer_get_va(tess_rings_bo);
3325
3326 radv_cs_add_buffer(queue->device->ws, cs, tess_rings_bo);
3327
3328 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
3329 radeon_set_uconfig_reg(cs, R_030938_VGT_TF_RING_SIZE,
3330 S_030938_SIZE(tf_ring_size / 4));
3331 radeon_set_uconfig_reg(cs, R_030940_VGT_TF_MEMORY_BASE,
3332 tf_va >> 8);
3333
3334 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3335 radeon_set_uconfig_reg(cs, R_030984_VGT_TF_MEMORY_BASE_HI_UMD,
3336 S_030984_BASE_HI(tf_va >> 40));
3337 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
3338 radeon_set_uconfig_reg(cs, R_030944_VGT_TF_MEMORY_BASE_HI,
3339 S_030944_BASE_HI(tf_va >> 40));
3340 }
3341 radeon_set_uconfig_reg(cs, R_03093C_VGT_HS_OFFCHIP_PARAM,
3342 hs_offchip_param);
3343 } else {
3344 radeon_set_config_reg(cs, R_008988_VGT_TF_RING_SIZE,
3345 S_008988_SIZE(tf_ring_size / 4));
3346 radeon_set_config_reg(cs, R_0089B8_VGT_TF_MEMORY_BASE,
3347 tf_va >> 8);
3348 radeon_set_config_reg(cs, R_0089B0_VGT_HS_OFFCHIP_PARAM,
3349 hs_offchip_param);
3350 }
3351 }
3352
3353 static void
3354 radv_emit_graphics_scratch(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3355 uint32_t size_per_wave, uint32_t waves,
3356 struct radeon_winsys_bo *scratch_bo)
3357 {
3358 if (queue->queue_family_index != RADV_QUEUE_GENERAL)
3359 return;
3360
3361 if (!scratch_bo)
3362 return;
3363
3364 radv_cs_add_buffer(queue->device->ws, cs, scratch_bo);
3365
3366 radeon_set_context_reg(cs, R_0286E8_SPI_TMPRING_SIZE,
3367 S_0286E8_WAVES(waves) |
3368 S_0286E8_WAVESIZE(round_up_u32(size_per_wave, 1024)));
3369 }
3370
3371 static void
3372 radv_emit_compute_scratch(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3373 uint32_t size_per_wave, uint32_t waves,
3374 struct radeon_winsys_bo *compute_scratch_bo)
3375 {
3376 uint64_t scratch_va;
3377
3378 if (!compute_scratch_bo)
3379 return;
3380
3381 scratch_va = radv_buffer_get_va(compute_scratch_bo);
3382
3383 radv_cs_add_buffer(queue->device->ws, cs, compute_scratch_bo);
3384
3385 radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0, 2);
3386 radeon_emit(cs, scratch_va);
3387 radeon_emit(cs, S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
3388 S_008F04_SWIZZLE_ENABLE(1));
3389
3390 radeon_set_sh_reg(cs, R_00B860_COMPUTE_TMPRING_SIZE,
3391 S_00B860_WAVES(waves) |
3392 S_00B860_WAVESIZE(round_up_u32(size_per_wave, 1024)));
3393 }
3394
3395 static void
3396 radv_emit_global_shader_pointers(struct radv_queue *queue,
3397 struct radeon_cmdbuf *cs,
3398 struct radeon_winsys_bo *descriptor_bo)
3399 {
3400 uint64_t va;
3401
3402 if (!descriptor_bo)
3403 return;
3404
3405 va = radv_buffer_get_va(descriptor_bo);
3406
3407 radv_cs_add_buffer(queue->device->ws, cs, descriptor_bo);
3408
3409 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3410 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3411 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3412 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
3413 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
3414
3415 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3416 radv_emit_shader_pointer(queue->device, cs, regs[i],
3417 va, true);
3418 }
3419 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
3420 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3421 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3422 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
3423 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
3424
3425 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3426 radv_emit_shader_pointer(queue->device, cs, regs[i],
3427 va, true);
3428 }
3429 } else {
3430 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3431 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3432 R_00B230_SPI_SHADER_USER_DATA_GS_0,
3433 R_00B330_SPI_SHADER_USER_DATA_ES_0,
3434 R_00B430_SPI_SHADER_USER_DATA_HS_0,
3435 R_00B530_SPI_SHADER_USER_DATA_LS_0};
3436
3437 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3438 radv_emit_shader_pointer(queue->device, cs, regs[i],
3439 va, true);
3440 }
3441 }
3442 }
3443
3444 static void
3445 radv_emit_trap_handler(struct radv_queue *queue,
3446 struct radeon_cmdbuf *cs,
3447 struct radeon_winsys_bo *tma_bo)
3448 {
3449 struct radv_device *device = queue->device;
3450 struct radeon_winsys_bo *tba_bo;
3451 uint64_t tba_va, tma_va;
3452
3453 if (!device->trap_handler_shader || !tma_bo)
3454 return;
3455
3456 tba_bo = device->trap_handler_shader->bo;
3457
3458 tba_va = radv_buffer_get_va(tba_bo) + device->trap_handler_shader->bo_offset;
3459 tma_va = radv_buffer_get_va(tma_bo);
3460
3461 radv_cs_add_buffer(queue->device->ws, cs, tba_bo);
3462 radv_cs_add_buffer(queue->device->ws, cs, tma_bo);
3463
3464 if (queue->queue_family_index == RADV_QUEUE_GENERAL) {
3465 uint32_t regs[] = {R_00B000_SPI_SHADER_TBA_LO_PS,
3466 R_00B100_SPI_SHADER_TBA_LO_VS,
3467 R_00B200_SPI_SHADER_TBA_LO_GS,
3468 R_00B300_SPI_SHADER_TBA_LO_ES,
3469 R_00B400_SPI_SHADER_TBA_LO_HS,
3470 R_00B500_SPI_SHADER_TBA_LO_LS};
3471
3472 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3473 radeon_set_sh_reg_seq(cs, regs[i], 4);
3474 radeon_emit(cs, tba_va >> 8);
3475 radeon_emit(cs, tba_va >> 40);
3476 radeon_emit(cs, tma_va >> 8);
3477 radeon_emit(cs, tma_va >> 40);
3478 }
3479 } else {
3480 radeon_set_sh_reg_seq(cs, R_00B838_COMPUTE_TBA_LO, 4);
3481 radeon_emit(cs, tba_va >> 8);
3482 radeon_emit(cs, tba_va >> 40);
3483 radeon_emit(cs, tma_va >> 8);
3484 radeon_emit(cs, tma_va >> 40);
3485 }
3486 }
3487
3488 static void
3489 radv_init_graphics_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
3490 {
3491 struct radv_device *device = queue->device;
3492
3493 if (device->gfx_init) {
3494 uint64_t va = radv_buffer_get_va(device->gfx_init);
3495
3496 radeon_emit(cs, PKT3(PKT3_INDIRECT_BUFFER_CIK, 2, 0));
3497 radeon_emit(cs, va);
3498 radeon_emit(cs, va >> 32);
3499 radeon_emit(cs, device->gfx_init_size_dw & 0xffff);
3500
3501 radv_cs_add_buffer(device->ws, cs, device->gfx_init);
3502 } else {
3503 si_emit_graphics(device, cs);
3504 }
3505 }
3506
3507 static void
3508 radv_init_compute_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
3509 {
3510 si_emit_compute(queue->device, cs);
3511 }
3512
3513 static VkResult
3514 radv_get_preamble_cs(struct radv_queue *queue,
3515 uint32_t scratch_size_per_wave,
3516 uint32_t scratch_waves,
3517 uint32_t compute_scratch_size_per_wave,
3518 uint32_t compute_scratch_waves,
3519 uint32_t esgs_ring_size,
3520 uint32_t gsvs_ring_size,
3521 bool needs_tess_rings,
3522 bool needs_gds,
3523 bool needs_gds_oa,
3524 bool needs_sample_positions,
3525 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
3526 struct radeon_cmdbuf **initial_preamble_cs,
3527 struct radeon_cmdbuf **continue_preamble_cs)
3528 {
3529 struct radeon_winsys_bo *scratch_bo = NULL;
3530 struct radeon_winsys_bo *descriptor_bo = NULL;
3531 struct radeon_winsys_bo *compute_scratch_bo = NULL;
3532 struct radeon_winsys_bo *esgs_ring_bo = NULL;
3533 struct radeon_winsys_bo *gsvs_ring_bo = NULL;
3534 struct radeon_winsys_bo *tess_rings_bo = NULL;
3535 struct radeon_winsys_bo *gds_bo = NULL;
3536 struct radeon_winsys_bo *gds_oa_bo = NULL;
3537 struct radeon_cmdbuf *dest_cs[3] = {0};
3538 bool add_tess_rings = false, add_gds = false, add_gds_oa = false, add_sample_positions = false;
3539 unsigned tess_factor_ring_size = 0, tess_offchip_ring_size = 0;
3540 unsigned max_offchip_buffers;
3541 unsigned hs_offchip_param = 0;
3542 unsigned tess_offchip_ring_offset;
3543 uint32_t ring_bo_flags = RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING;
3544 if (!queue->has_tess_rings) {
3545 if (needs_tess_rings)
3546 add_tess_rings = true;
3547 }
3548 if (!queue->has_gds) {
3549 if (needs_gds)
3550 add_gds = true;
3551 }
3552 if (!queue->has_gds_oa) {
3553 if (needs_gds_oa)
3554 add_gds_oa = true;
3555 }
3556 if (!queue->has_sample_positions) {
3557 if (needs_sample_positions)
3558 add_sample_positions = true;
3559 }
3560 tess_factor_ring_size = 32768 * queue->device->physical_device->rad_info.max_se;
3561 hs_offchip_param = radv_get_hs_offchip_param(queue->device,
3562 &max_offchip_buffers);
3563 tess_offchip_ring_offset = align(tess_factor_ring_size, 64 * 1024);
3564 tess_offchip_ring_size = max_offchip_buffers *
3565 queue->device->tess_offchip_block_dw_size * 4;
3566
3567 scratch_size_per_wave = MAX2(scratch_size_per_wave, queue->scratch_size_per_wave);
3568 if (scratch_size_per_wave)
3569 scratch_waves = MIN2(scratch_waves, UINT32_MAX / scratch_size_per_wave);
3570 else
3571 scratch_waves = 0;
3572
3573 compute_scratch_size_per_wave = MAX2(compute_scratch_size_per_wave, queue->compute_scratch_size_per_wave);
3574 if (compute_scratch_size_per_wave)
3575 compute_scratch_waves = MIN2(compute_scratch_waves, UINT32_MAX / compute_scratch_size_per_wave);
3576 else
3577 compute_scratch_waves = 0;
3578
3579 if (scratch_size_per_wave <= queue->scratch_size_per_wave &&
3580 scratch_waves <= queue->scratch_waves &&
3581 compute_scratch_size_per_wave <= queue->compute_scratch_size_per_wave &&
3582 compute_scratch_waves <= queue->compute_scratch_waves &&
3583 esgs_ring_size <= queue->esgs_ring_size &&
3584 gsvs_ring_size <= queue->gsvs_ring_size &&
3585 !add_tess_rings && !add_gds && !add_gds_oa && !add_sample_positions &&
3586 queue->initial_preamble_cs) {
3587 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
3588 *initial_preamble_cs = queue->initial_preamble_cs;
3589 *continue_preamble_cs = queue->continue_preamble_cs;
3590 if (!scratch_size_per_wave && !compute_scratch_size_per_wave &&
3591 !esgs_ring_size && !gsvs_ring_size && !needs_tess_rings &&
3592 !needs_gds && !needs_gds_oa && !needs_sample_positions)
3593 *continue_preamble_cs = NULL;
3594 return VK_SUCCESS;
3595 }
3596
3597 uint32_t scratch_size = scratch_size_per_wave * scratch_waves;
3598 uint32_t queue_scratch_size = queue->scratch_size_per_wave * queue->scratch_waves;
3599 if (scratch_size > queue_scratch_size) {
3600 scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
3601 scratch_size,
3602 4096,
3603 RADEON_DOMAIN_VRAM,
3604 ring_bo_flags,
3605 RADV_BO_PRIORITY_SCRATCH);
3606 if (!scratch_bo)
3607 goto fail;
3608 } else
3609 scratch_bo = queue->scratch_bo;
3610
3611 uint32_t compute_scratch_size = compute_scratch_size_per_wave * compute_scratch_waves;
3612 uint32_t compute_queue_scratch_size = queue->compute_scratch_size_per_wave * queue->compute_scratch_waves;
3613 if (compute_scratch_size > compute_queue_scratch_size) {
3614 compute_scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
3615 compute_scratch_size,
3616 4096,
3617 RADEON_DOMAIN_VRAM,
3618 ring_bo_flags,
3619 RADV_BO_PRIORITY_SCRATCH);
3620 if (!compute_scratch_bo)
3621 goto fail;
3622
3623 } else
3624 compute_scratch_bo = queue->compute_scratch_bo;
3625
3626 if (esgs_ring_size > queue->esgs_ring_size) {
3627 esgs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
3628 esgs_ring_size,
3629 4096,
3630 RADEON_DOMAIN_VRAM,
3631 ring_bo_flags,
3632 RADV_BO_PRIORITY_SCRATCH);
3633 if (!esgs_ring_bo)
3634 goto fail;
3635 } else {
3636 esgs_ring_bo = queue->esgs_ring_bo;
3637 esgs_ring_size = queue->esgs_ring_size;
3638 }
3639
3640 if (gsvs_ring_size > queue->gsvs_ring_size) {
3641 gsvs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
3642 gsvs_ring_size,
3643 4096,
3644 RADEON_DOMAIN_VRAM,
3645 ring_bo_flags,
3646 RADV_BO_PRIORITY_SCRATCH);
3647 if (!gsvs_ring_bo)
3648 goto fail;
3649 } else {
3650 gsvs_ring_bo = queue->gsvs_ring_bo;
3651 gsvs_ring_size = queue->gsvs_ring_size;
3652 }
3653
3654 if (add_tess_rings) {
3655 tess_rings_bo = queue->device->ws->buffer_create(queue->device->ws,
3656 tess_offchip_ring_offset + tess_offchip_ring_size,
3657 256,
3658 RADEON_DOMAIN_VRAM,
3659 ring_bo_flags,
3660 RADV_BO_PRIORITY_SCRATCH);
3661 if (!tess_rings_bo)
3662 goto fail;
3663 } else {
3664 tess_rings_bo = queue->tess_rings_bo;
3665 }
3666
3667 if (add_gds) {
3668 assert(queue->device->physical_device->rad_info.chip_class >= GFX10);
3669
3670 /* 4 streamout GDS counters.
3671 * We need 256B (64 dw) of GDS, otherwise streamout hangs.
3672 */
3673 gds_bo = queue->device->ws->buffer_create(queue->device->ws,
3674 256, 4,
3675 RADEON_DOMAIN_GDS,
3676 ring_bo_flags,
3677 RADV_BO_PRIORITY_SCRATCH);
3678 if (!gds_bo)
3679 goto fail;
3680 } else {
3681 gds_bo = queue->gds_bo;
3682 }
3683
3684 if (add_gds_oa) {
3685 assert(queue->device->physical_device->rad_info.chip_class >= GFX10);
3686
3687 gds_oa_bo = queue->device->ws->buffer_create(queue->device->ws,
3688 4, 1,
3689 RADEON_DOMAIN_OA,
3690 ring_bo_flags,
3691 RADV_BO_PRIORITY_SCRATCH);
3692 if (!gds_oa_bo)
3693 goto fail;
3694 } else {
3695 gds_oa_bo = queue->gds_oa_bo;
3696 }
3697
3698 if (scratch_bo != queue->scratch_bo ||
3699 esgs_ring_bo != queue->esgs_ring_bo ||
3700 gsvs_ring_bo != queue->gsvs_ring_bo ||
3701 tess_rings_bo != queue->tess_rings_bo ||
3702 add_sample_positions) {
3703 uint32_t size = 0;
3704 if (gsvs_ring_bo || esgs_ring_bo ||
3705 tess_rings_bo || add_sample_positions) {
3706 size = 112; /* 2 dword + 2 padding + 4 dword * 6 */
3707 if (add_sample_positions)
3708 size += 128; /* 64+32+16+8 = 120 bytes */
3709 }
3710 else if (scratch_bo)
3711 size = 8; /* 2 dword */
3712
3713 descriptor_bo = queue->device->ws->buffer_create(queue->device->ws,
3714 size,
3715 4096,
3716 RADEON_DOMAIN_VRAM,
3717 RADEON_FLAG_CPU_ACCESS |
3718 RADEON_FLAG_NO_INTERPROCESS_SHARING |
3719 RADEON_FLAG_READ_ONLY,
3720 RADV_BO_PRIORITY_DESCRIPTOR);
3721 if (!descriptor_bo)
3722 goto fail;
3723 } else
3724 descriptor_bo = queue->descriptor_bo;
3725
3726 if (descriptor_bo != queue->descriptor_bo) {
3727 uint32_t *map = (uint32_t*)queue->device->ws->buffer_map(descriptor_bo);
3728 if (!map)
3729 goto fail;
3730
3731 if (scratch_bo) {
3732 uint64_t scratch_va = radv_buffer_get_va(scratch_bo);
3733 uint32_t rsrc1 = S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
3734 S_008F04_SWIZZLE_ENABLE(1);
3735 map[0] = scratch_va;
3736 map[1] = rsrc1;
3737 }
3738
3739 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo || add_sample_positions)
3740 fill_geom_tess_rings(queue, map, add_sample_positions,
3741 esgs_ring_size, esgs_ring_bo,
3742 gsvs_ring_size, gsvs_ring_bo,
3743 tess_factor_ring_size,
3744 tess_offchip_ring_offset,
3745 tess_offchip_ring_size,
3746 tess_rings_bo);
3747
3748 queue->device->ws->buffer_unmap(descriptor_bo);
3749 }
3750
3751 for(int i = 0; i < 3; ++i) {
3752 struct radeon_cmdbuf *cs = NULL;
3753 cs = queue->device->ws->cs_create(queue->device->ws,
3754 queue->queue_family_index ? RING_COMPUTE : RING_GFX);
3755 if (!cs)
3756 goto fail;
3757
3758 dest_cs[i] = cs;
3759
3760 if (scratch_bo)
3761 radv_cs_add_buffer(queue->device->ws, cs, scratch_bo);
3762
3763 /* Emit initial configuration. */
3764 switch (queue->queue_family_index) {
3765 case RADV_QUEUE_GENERAL:
3766 radv_init_graphics_state(cs, queue);
3767 break;
3768 case RADV_QUEUE_COMPUTE:
3769 radv_init_compute_state(cs, queue);
3770 break;
3771 case RADV_QUEUE_TRANSFER:
3772 break;
3773 }
3774
3775 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo) {
3776 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3777 radeon_emit(cs, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
3778
3779 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3780 radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
3781 }
3782
3783 radv_emit_gs_ring_sizes(queue, cs, esgs_ring_bo, esgs_ring_size,
3784 gsvs_ring_bo, gsvs_ring_size);
3785 radv_emit_tess_factor_ring(queue, cs, hs_offchip_param,
3786 tess_factor_ring_size, tess_rings_bo);
3787 radv_emit_global_shader_pointers(queue, cs, descriptor_bo);
3788 radv_emit_compute_scratch(queue, cs, compute_scratch_size_per_wave,
3789 compute_scratch_waves, compute_scratch_bo);
3790 radv_emit_graphics_scratch(queue, cs, scratch_size_per_wave,
3791 scratch_waves, scratch_bo);
3792 radv_emit_trap_handler(queue, cs, queue->device->tma_bo);
3793
3794 if (gds_bo)
3795 radv_cs_add_buffer(queue->device->ws, cs, gds_bo);
3796 if (gds_oa_bo)
3797 radv_cs_add_buffer(queue->device->ws, cs, gds_oa_bo);
3798
3799 if (queue->device->trace_bo)
3800 radv_cs_add_buffer(queue->device->ws, cs, queue->device->trace_bo);
3801
3802 if (queue->device->border_color_data.bo)
3803 radv_cs_add_buffer(queue->device->ws, cs,
3804 queue->device->border_color_data.bo);
3805
3806 if (i == 0) {
3807 si_cs_emit_cache_flush(cs,
3808 queue->device->physical_device->rad_info.chip_class,
3809 NULL, 0,
3810 queue->queue_family_index == RING_COMPUTE &&
3811 queue->device->physical_device->rad_info.chip_class >= GFX7,
3812 (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)) |
3813 RADV_CMD_FLAG_INV_ICACHE |
3814 RADV_CMD_FLAG_INV_SCACHE |
3815 RADV_CMD_FLAG_INV_VCACHE |
3816 RADV_CMD_FLAG_INV_L2 |
3817 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
3818 } else if (i == 1) {
3819 si_cs_emit_cache_flush(cs,
3820 queue->device->physical_device->rad_info.chip_class,
3821 NULL, 0,
3822 queue->queue_family_index == RING_COMPUTE &&
3823 queue->device->physical_device->rad_info.chip_class >= GFX7,
3824 RADV_CMD_FLAG_INV_ICACHE |
3825 RADV_CMD_FLAG_INV_SCACHE |
3826 RADV_CMD_FLAG_INV_VCACHE |
3827 RADV_CMD_FLAG_INV_L2 |
3828 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
3829 }
3830
3831 if (queue->device->ws->cs_finalize(cs) != VK_SUCCESS)
3832 goto fail;
3833 }
3834
3835 if (queue->initial_full_flush_preamble_cs)
3836 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
3837
3838 if (queue->initial_preamble_cs)
3839 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
3840
3841 if (queue->continue_preamble_cs)
3842 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
3843
3844 queue->initial_full_flush_preamble_cs = dest_cs[0];
3845 queue->initial_preamble_cs = dest_cs[1];
3846 queue->continue_preamble_cs = dest_cs[2];
3847
3848 if (scratch_bo != queue->scratch_bo) {
3849 if (queue->scratch_bo)
3850 queue->device->ws->buffer_destroy(queue->scratch_bo);
3851 queue->scratch_bo = scratch_bo;
3852 }
3853 queue->scratch_size_per_wave = scratch_size_per_wave;
3854 queue->scratch_waves = scratch_waves;
3855
3856 if (compute_scratch_bo != queue->compute_scratch_bo) {
3857 if (queue->compute_scratch_bo)
3858 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
3859 queue->compute_scratch_bo = compute_scratch_bo;
3860 }
3861 queue->compute_scratch_size_per_wave = compute_scratch_size_per_wave;
3862 queue->compute_scratch_waves = compute_scratch_waves;
3863
3864 if (esgs_ring_bo != queue->esgs_ring_bo) {
3865 if (queue->esgs_ring_bo)
3866 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
3867 queue->esgs_ring_bo = esgs_ring_bo;
3868 queue->esgs_ring_size = esgs_ring_size;
3869 }
3870
3871 if (gsvs_ring_bo != queue->gsvs_ring_bo) {
3872 if (queue->gsvs_ring_bo)
3873 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
3874 queue->gsvs_ring_bo = gsvs_ring_bo;
3875 queue->gsvs_ring_size = gsvs_ring_size;
3876 }
3877
3878 if (tess_rings_bo != queue->tess_rings_bo) {
3879 queue->tess_rings_bo = tess_rings_bo;
3880 queue->has_tess_rings = true;
3881 }
3882
3883 if (gds_bo != queue->gds_bo) {
3884 queue->gds_bo = gds_bo;
3885 queue->has_gds = true;
3886 }
3887
3888 if (gds_oa_bo != queue->gds_oa_bo) {
3889 queue->gds_oa_bo = gds_oa_bo;
3890 queue->has_gds_oa = true;
3891 }
3892
3893 if (descriptor_bo != queue->descriptor_bo) {
3894 if (queue->descriptor_bo)
3895 queue->device->ws->buffer_destroy(queue->descriptor_bo);
3896
3897 queue->descriptor_bo = descriptor_bo;
3898 }
3899
3900 if (add_sample_positions)
3901 queue->has_sample_positions = true;
3902
3903 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
3904 *initial_preamble_cs = queue->initial_preamble_cs;
3905 *continue_preamble_cs = queue->continue_preamble_cs;
3906 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
3907 *continue_preamble_cs = NULL;
3908 return VK_SUCCESS;
3909 fail:
3910 for (int i = 0; i < ARRAY_SIZE(dest_cs); ++i)
3911 if (dest_cs[i])
3912 queue->device->ws->cs_destroy(dest_cs[i]);
3913 if (descriptor_bo && descriptor_bo != queue->descriptor_bo)
3914 queue->device->ws->buffer_destroy(descriptor_bo);
3915 if (scratch_bo && scratch_bo != queue->scratch_bo)
3916 queue->device->ws->buffer_destroy(scratch_bo);
3917 if (compute_scratch_bo && compute_scratch_bo != queue->compute_scratch_bo)
3918 queue->device->ws->buffer_destroy(compute_scratch_bo);
3919 if (esgs_ring_bo && esgs_ring_bo != queue->esgs_ring_bo)
3920 queue->device->ws->buffer_destroy(esgs_ring_bo);
3921 if (gsvs_ring_bo && gsvs_ring_bo != queue->gsvs_ring_bo)
3922 queue->device->ws->buffer_destroy(gsvs_ring_bo);
3923 if (tess_rings_bo && tess_rings_bo != queue->tess_rings_bo)
3924 queue->device->ws->buffer_destroy(tess_rings_bo);
3925 if (gds_bo && gds_bo != queue->gds_bo)
3926 queue->device->ws->buffer_destroy(gds_bo);
3927 if (gds_oa_bo && gds_oa_bo != queue->gds_oa_bo)
3928 queue->device->ws->buffer_destroy(gds_oa_bo);
3929
3930 return vk_error(queue->device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
3931 }
3932
3933 static VkResult radv_alloc_sem_counts(struct radv_device *device,
3934 struct radv_winsys_sem_counts *counts,
3935 int num_sems,
3936 struct radv_semaphore_part **sems,
3937 const uint64_t *timeline_values,
3938 VkFence _fence,
3939 bool is_signal)
3940 {
3941 int syncobj_idx = 0, non_reset_idx = 0, sem_idx = 0, timeline_idx = 0;
3942
3943 if (num_sems == 0 && _fence == VK_NULL_HANDLE)
3944 return VK_SUCCESS;
3945
3946 for (uint32_t i = 0; i < num_sems; i++) {
3947 switch(sems[i]->kind) {
3948 case RADV_SEMAPHORE_SYNCOBJ:
3949 counts->syncobj_count++;
3950 counts->syncobj_reset_count++;
3951 break;
3952 case RADV_SEMAPHORE_WINSYS:
3953 counts->sem_count++;
3954 break;
3955 case RADV_SEMAPHORE_NONE:
3956 break;
3957 case RADV_SEMAPHORE_TIMELINE:
3958 counts->syncobj_count++;
3959 break;
3960 case RADV_SEMAPHORE_TIMELINE_SYNCOBJ:
3961 counts->timeline_syncobj_count++;
3962 break;
3963 }
3964 }
3965
3966 if (_fence != VK_NULL_HANDLE) {
3967 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3968
3969 struct radv_fence_part *part =
3970 fence->temporary.kind != RADV_FENCE_NONE ?
3971 &fence->temporary : &fence->permanent;
3972 if (part->kind == RADV_FENCE_SYNCOBJ)
3973 counts->syncobj_count++;
3974 }
3975
3976 if (counts->syncobj_count || counts->timeline_syncobj_count) {
3977 counts->points = (uint64_t *)malloc(
3978 sizeof(*counts->syncobj) * counts->syncobj_count +
3979 (sizeof(*counts->syncobj) + sizeof(*counts->points)) * counts->timeline_syncobj_count);
3980 if (!counts->points)
3981 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3982 counts->syncobj = (uint32_t*)(counts->points + counts->timeline_syncobj_count);
3983 }
3984
3985 if (counts->sem_count) {
3986 counts->sem = (struct radeon_winsys_sem **)malloc(sizeof(struct radeon_winsys_sem *) * counts->sem_count);
3987 if (!counts->sem) {
3988 free(counts->syncobj);
3989 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3990 }
3991 }
3992
3993 non_reset_idx = counts->syncobj_reset_count;
3994
3995 for (uint32_t i = 0; i < num_sems; i++) {
3996 switch(sems[i]->kind) {
3997 case RADV_SEMAPHORE_NONE:
3998 unreachable("Empty semaphore");
3999 break;
4000 case RADV_SEMAPHORE_SYNCOBJ:
4001 counts->syncobj[syncobj_idx++] = sems[i]->syncobj;
4002 break;
4003 case RADV_SEMAPHORE_WINSYS:
4004 counts->sem[sem_idx++] = sems[i]->ws_sem;
4005 break;
4006 case RADV_SEMAPHORE_TIMELINE: {
4007 pthread_mutex_lock(&sems[i]->timeline.mutex);
4008 struct radv_timeline_point *point = NULL;
4009 if (is_signal) {
4010 point = radv_timeline_add_point_locked(device, &sems[i]->timeline, timeline_values[i]);
4011 } else {
4012 point = radv_timeline_find_point_at_least_locked(device, &sems[i]->timeline, timeline_values[i]);
4013 }
4014
4015 pthread_mutex_unlock(&sems[i]->timeline.mutex);
4016
4017 if (point) {
4018 counts->syncobj[non_reset_idx++] = point->syncobj;
4019 } else {
4020 /* Explicitly remove the semaphore so we might not find
4021 * a point later post-submit. */
4022 sems[i] = NULL;
4023 }
4024 break;
4025 }
4026 case RADV_SEMAPHORE_TIMELINE_SYNCOBJ:
4027 counts->syncobj[counts->syncobj_count + timeline_idx] = sems[i]->syncobj;
4028 counts->points[timeline_idx] = timeline_values[i];
4029 ++timeline_idx;
4030 break;
4031 }
4032 }
4033
4034 if (_fence != VK_NULL_HANDLE) {
4035 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4036
4037 struct radv_fence_part *part =
4038 fence->temporary.kind != RADV_FENCE_NONE ?
4039 &fence->temporary : &fence->permanent;
4040 if (part->kind == RADV_FENCE_SYNCOBJ)
4041 counts->syncobj[non_reset_idx++] = part->syncobj;
4042 }
4043
4044 assert(MAX2(syncobj_idx, non_reset_idx) <= counts->syncobj_count);
4045 counts->syncobj_count = MAX2(syncobj_idx, non_reset_idx);
4046
4047 return VK_SUCCESS;
4048 }
4049
4050 static void
4051 radv_free_sem_info(struct radv_winsys_sem_info *sem_info)
4052 {
4053 free(sem_info->wait.points);
4054 free(sem_info->wait.sem);
4055 free(sem_info->signal.points);
4056 free(sem_info->signal.sem);
4057 }
4058
4059
4060 static void radv_free_temp_syncobjs(struct radv_device *device,
4061 int num_sems,
4062 struct radv_semaphore_part *sems)
4063 {
4064 for (uint32_t i = 0; i < num_sems; i++) {
4065 radv_destroy_semaphore_part(device, sems + i);
4066 }
4067 }
4068
4069 static VkResult
4070 radv_alloc_sem_info(struct radv_device *device,
4071 struct radv_winsys_sem_info *sem_info,
4072 int num_wait_sems,
4073 struct radv_semaphore_part **wait_sems,
4074 const uint64_t *wait_values,
4075 int num_signal_sems,
4076 struct radv_semaphore_part **signal_sems,
4077 const uint64_t *signal_values,
4078 VkFence fence)
4079 {
4080 VkResult ret;
4081 memset(sem_info, 0, sizeof(*sem_info));
4082
4083 ret = radv_alloc_sem_counts(device, &sem_info->wait, num_wait_sems, wait_sems, wait_values, VK_NULL_HANDLE, false);
4084 if (ret)
4085 return ret;
4086 ret = radv_alloc_sem_counts(device, &sem_info->signal, num_signal_sems, signal_sems, signal_values, fence, true);
4087 if (ret)
4088 radv_free_sem_info(sem_info);
4089
4090 /* caller can override these */
4091 sem_info->cs_emit_wait = true;
4092 sem_info->cs_emit_signal = true;
4093 return ret;
4094 }
4095
4096 static void
4097 radv_finalize_timelines(struct radv_device *device,
4098 uint32_t num_wait_sems,
4099 struct radv_semaphore_part **wait_sems,
4100 const uint64_t *wait_values,
4101 uint32_t num_signal_sems,
4102 struct radv_semaphore_part **signal_sems,
4103 const uint64_t *signal_values,
4104 struct list_head *processing_list)
4105 {
4106 for (uint32_t i = 0; i < num_wait_sems; ++i) {
4107 if (wait_sems[i] && wait_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4108 pthread_mutex_lock(&wait_sems[i]->timeline.mutex);
4109 struct radv_timeline_point *point =
4110 radv_timeline_find_point_at_least_locked(device, &wait_sems[i]->timeline, wait_values[i]);
4111 point->wait_count -= 2;
4112 pthread_mutex_unlock(&wait_sems[i]->timeline.mutex);
4113 }
4114 }
4115 for (uint32_t i = 0; i < num_signal_sems; ++i) {
4116 if (signal_sems[i] && signal_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4117 pthread_mutex_lock(&signal_sems[i]->timeline.mutex);
4118 struct radv_timeline_point *point =
4119 radv_timeline_find_point_at_least_locked(device, &signal_sems[i]->timeline, signal_values[i]);
4120 signal_sems[i]->timeline.highest_submitted =
4121 MAX2(signal_sems[i]->timeline.highest_submitted, point->value);
4122 point->wait_count -= 2;
4123 radv_timeline_trigger_waiters_locked(&signal_sems[i]->timeline, processing_list);
4124 pthread_mutex_unlock(&signal_sems[i]->timeline.mutex);
4125 } else if (signal_sems[i] && signal_sems[i]->kind == RADV_SEMAPHORE_TIMELINE_SYNCOBJ) {
4126 signal_sems[i]->timeline_syncobj.max_point =
4127 MAX2(signal_sems[i]->timeline_syncobj.max_point, signal_values[i]);
4128 }
4129 }
4130 }
4131
4132 static VkResult
4133 radv_sparse_buffer_bind_memory(struct radv_device *device,
4134 const VkSparseBufferMemoryBindInfo *bind)
4135 {
4136 RADV_FROM_HANDLE(radv_buffer, buffer, bind->buffer);
4137 VkResult result;
4138
4139 for (uint32_t i = 0; i < bind->bindCount; ++i) {
4140 struct radv_device_memory *mem = NULL;
4141
4142 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
4143 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
4144
4145 result = device->ws->buffer_virtual_bind(buffer->bo,
4146 bind->pBinds[i].resourceOffset,
4147 bind->pBinds[i].size,
4148 mem ? mem->bo : NULL,
4149 bind->pBinds[i].memoryOffset);
4150 if (result != VK_SUCCESS)
4151 return result;
4152 }
4153
4154 return VK_SUCCESS;
4155 }
4156
4157 static VkResult
4158 radv_sparse_image_opaque_bind_memory(struct radv_device *device,
4159 const VkSparseImageOpaqueMemoryBindInfo *bind)
4160 {
4161 RADV_FROM_HANDLE(radv_image, image, bind->image);
4162 VkResult result;
4163
4164 for (uint32_t i = 0; i < bind->bindCount; ++i) {
4165 struct radv_device_memory *mem = NULL;
4166
4167 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
4168 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
4169
4170 result = device->ws->buffer_virtual_bind(image->bo,
4171 bind->pBinds[i].resourceOffset,
4172 bind->pBinds[i].size,
4173 mem ? mem->bo : NULL,
4174 bind->pBinds[i].memoryOffset);
4175 if (result != VK_SUCCESS)
4176 return result;
4177 }
4178
4179 return VK_SUCCESS;
4180 }
4181
4182 static VkResult
4183 radv_get_preambles(struct radv_queue *queue,
4184 const VkCommandBuffer *cmd_buffers,
4185 uint32_t cmd_buffer_count,
4186 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
4187 struct radeon_cmdbuf **initial_preamble_cs,
4188 struct radeon_cmdbuf **continue_preamble_cs)
4189 {
4190 uint32_t scratch_size_per_wave = 0, waves_wanted = 0;
4191 uint32_t compute_scratch_size_per_wave = 0, compute_waves_wanted = 0;
4192 uint32_t esgs_ring_size = 0, gsvs_ring_size = 0;
4193 bool tess_rings_needed = false;
4194 bool gds_needed = false;
4195 bool gds_oa_needed = false;
4196 bool sample_positions_needed = false;
4197
4198 for (uint32_t j = 0; j < cmd_buffer_count; j++) {
4199 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
4200 cmd_buffers[j]);
4201
4202 scratch_size_per_wave = MAX2(scratch_size_per_wave, cmd_buffer->scratch_size_per_wave_needed);
4203 waves_wanted = MAX2(waves_wanted, cmd_buffer->scratch_waves_wanted);
4204 compute_scratch_size_per_wave = MAX2(compute_scratch_size_per_wave,
4205 cmd_buffer->compute_scratch_size_per_wave_needed);
4206 compute_waves_wanted = MAX2(compute_waves_wanted,
4207 cmd_buffer->compute_scratch_waves_wanted);
4208 esgs_ring_size = MAX2(esgs_ring_size, cmd_buffer->esgs_ring_size_needed);
4209 gsvs_ring_size = MAX2(gsvs_ring_size, cmd_buffer->gsvs_ring_size_needed);
4210 tess_rings_needed |= cmd_buffer->tess_rings_needed;
4211 gds_needed |= cmd_buffer->gds_needed;
4212 gds_oa_needed |= cmd_buffer->gds_oa_needed;
4213 sample_positions_needed |= cmd_buffer->sample_positions_needed;
4214 }
4215
4216 return radv_get_preamble_cs(queue, scratch_size_per_wave, waves_wanted,
4217 compute_scratch_size_per_wave, compute_waves_wanted,
4218 esgs_ring_size, gsvs_ring_size, tess_rings_needed,
4219 gds_needed, gds_oa_needed, sample_positions_needed,
4220 initial_full_flush_preamble_cs,
4221 initial_preamble_cs, continue_preamble_cs);
4222 }
4223
4224 struct radv_deferred_queue_submission {
4225 struct radv_queue *queue;
4226 VkCommandBuffer *cmd_buffers;
4227 uint32_t cmd_buffer_count;
4228
4229 /* Sparse bindings that happen on a queue. */
4230 VkSparseBufferMemoryBindInfo *buffer_binds;
4231 uint32_t buffer_bind_count;
4232 VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
4233 uint32_t image_opaque_bind_count;
4234
4235 bool flush_caches;
4236 VkShaderStageFlags wait_dst_stage_mask;
4237 struct radv_semaphore_part **wait_semaphores;
4238 uint32_t wait_semaphore_count;
4239 struct radv_semaphore_part **signal_semaphores;
4240 uint32_t signal_semaphore_count;
4241 VkFence fence;
4242
4243 uint64_t *wait_values;
4244 uint64_t *signal_values;
4245
4246 struct radv_semaphore_part *temporary_semaphore_parts;
4247 uint32_t temporary_semaphore_part_count;
4248
4249 struct list_head queue_pending_list;
4250 uint32_t submission_wait_count;
4251 struct radv_timeline_waiter *wait_nodes;
4252
4253 struct list_head processing_list;
4254 };
4255
4256 struct radv_queue_submission {
4257 const VkCommandBuffer *cmd_buffers;
4258 uint32_t cmd_buffer_count;
4259
4260 /* Sparse bindings that happen on a queue. */
4261 const VkSparseBufferMemoryBindInfo *buffer_binds;
4262 uint32_t buffer_bind_count;
4263 const VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
4264 uint32_t image_opaque_bind_count;
4265
4266 bool flush_caches;
4267 VkPipelineStageFlags wait_dst_stage_mask;
4268 const VkSemaphore *wait_semaphores;
4269 uint32_t wait_semaphore_count;
4270 const VkSemaphore *signal_semaphores;
4271 uint32_t signal_semaphore_count;
4272 VkFence fence;
4273
4274 const uint64_t *wait_values;
4275 uint32_t wait_value_count;
4276 const uint64_t *signal_values;
4277 uint32_t signal_value_count;
4278 };
4279
4280 static VkResult
4281 radv_queue_trigger_submission(struct radv_deferred_queue_submission *submission,
4282 uint32_t decrement,
4283 struct list_head *processing_list);
4284
4285 static VkResult
4286 radv_create_deferred_submission(struct radv_queue *queue,
4287 const struct radv_queue_submission *submission,
4288 struct radv_deferred_queue_submission **out)
4289 {
4290 struct radv_deferred_queue_submission *deferred = NULL;
4291 size_t size = sizeof(struct radv_deferred_queue_submission);
4292
4293 uint32_t temporary_count = 0;
4294 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4295 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
4296 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE)
4297 ++temporary_count;
4298 }
4299
4300 size += submission->cmd_buffer_count * sizeof(VkCommandBuffer);
4301 size += submission->buffer_bind_count * sizeof(VkSparseBufferMemoryBindInfo);
4302 size += submission->image_opaque_bind_count * sizeof(VkSparseImageOpaqueMemoryBindInfo);
4303 size += submission->wait_semaphore_count * sizeof(struct radv_semaphore_part *);
4304 size += temporary_count * sizeof(struct radv_semaphore_part);
4305 size += submission->signal_semaphore_count * sizeof(struct radv_semaphore_part *);
4306 size += submission->wait_value_count * sizeof(uint64_t);
4307 size += submission->signal_value_count * sizeof(uint64_t);
4308 size += submission->wait_semaphore_count * sizeof(struct radv_timeline_waiter);
4309
4310 deferred = calloc(1, size);
4311 if (!deferred)
4312 return VK_ERROR_OUT_OF_HOST_MEMORY;
4313
4314 deferred->queue = queue;
4315
4316 deferred->cmd_buffers = (void*)(deferred + 1);
4317 deferred->cmd_buffer_count = submission->cmd_buffer_count;
4318 memcpy(deferred->cmd_buffers, submission->cmd_buffers,
4319 submission->cmd_buffer_count * sizeof(*deferred->cmd_buffers));
4320
4321 deferred->buffer_binds = (void*)(deferred->cmd_buffers + submission->cmd_buffer_count);
4322 deferred->buffer_bind_count = submission->buffer_bind_count;
4323 memcpy(deferred->buffer_binds, submission->buffer_binds,
4324 submission->buffer_bind_count * sizeof(*deferred->buffer_binds));
4325
4326 deferred->image_opaque_binds = (void*)(deferred->buffer_binds + submission->buffer_bind_count);
4327 deferred->image_opaque_bind_count = submission->image_opaque_bind_count;
4328 memcpy(deferred->image_opaque_binds, submission->image_opaque_binds,
4329 submission->image_opaque_bind_count * sizeof(*deferred->image_opaque_binds));
4330
4331 deferred->flush_caches = submission->flush_caches;
4332 deferred->wait_dst_stage_mask = submission->wait_dst_stage_mask;
4333
4334 deferred->wait_semaphores = (void*)(deferred->image_opaque_binds + deferred->image_opaque_bind_count);
4335 deferred->wait_semaphore_count = submission->wait_semaphore_count;
4336
4337 deferred->signal_semaphores = (void*)(deferred->wait_semaphores + deferred->wait_semaphore_count);
4338 deferred->signal_semaphore_count = submission->signal_semaphore_count;
4339
4340 deferred->fence = submission->fence;
4341
4342 deferred->temporary_semaphore_parts = (void*)(deferred->signal_semaphores + deferred->signal_semaphore_count);
4343 deferred->temporary_semaphore_part_count = temporary_count;
4344
4345 uint32_t temporary_idx = 0;
4346 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4347 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
4348 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE) {
4349 deferred->wait_semaphores[i] = &deferred->temporary_semaphore_parts[temporary_idx];
4350 deferred->temporary_semaphore_parts[temporary_idx] = semaphore->temporary;
4351 semaphore->temporary.kind = RADV_SEMAPHORE_NONE;
4352 ++temporary_idx;
4353 } else
4354 deferred->wait_semaphores[i] = &semaphore->permanent;
4355 }
4356
4357 for (uint32_t i = 0; i < submission->signal_semaphore_count; ++i) {
4358 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->signal_semaphores[i]);
4359 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE) {
4360 deferred->signal_semaphores[i] = &semaphore->temporary;
4361 } else {
4362 deferred->signal_semaphores[i] = &semaphore->permanent;
4363 }
4364 }
4365
4366 deferred->wait_values = (void*)(deferred->temporary_semaphore_parts + temporary_count);
4367 memcpy(deferred->wait_values, submission->wait_values, submission->wait_value_count * sizeof(uint64_t));
4368 deferred->signal_values = deferred->wait_values + submission->wait_value_count;
4369 memcpy(deferred->signal_values, submission->signal_values, submission->signal_value_count * sizeof(uint64_t));
4370
4371 deferred->wait_nodes = (void*)(deferred->signal_values + submission->signal_value_count);
4372 /* This is worst-case. radv_queue_enqueue_submission will fill in further, but this
4373 * ensure the submission is not accidentally triggered early when adding wait timelines. */
4374 deferred->submission_wait_count = 1 + submission->wait_semaphore_count;
4375
4376 *out = deferred;
4377 return VK_SUCCESS;
4378 }
4379
4380 static VkResult
4381 radv_queue_enqueue_submission(struct radv_deferred_queue_submission *submission,
4382 struct list_head *processing_list)
4383 {
4384 uint32_t wait_cnt = 0;
4385 struct radv_timeline_waiter *waiter = submission->wait_nodes;
4386 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4387 if (submission->wait_semaphores[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4388 pthread_mutex_lock(&submission->wait_semaphores[i]->timeline.mutex);
4389 if (submission->wait_semaphores[i]->timeline.highest_submitted < submission->wait_values[i]) {
4390 ++wait_cnt;
4391 waiter->value = submission->wait_values[i];
4392 waiter->submission = submission;
4393 list_addtail(&waiter->list, &submission->wait_semaphores[i]->timeline.waiters);
4394 ++waiter;
4395 }
4396 pthread_mutex_unlock(&submission->wait_semaphores[i]->timeline.mutex);
4397 }
4398 }
4399
4400 pthread_mutex_lock(&submission->queue->pending_mutex);
4401
4402 bool is_first = list_is_empty(&submission->queue->pending_submissions);
4403 list_addtail(&submission->queue_pending_list, &submission->queue->pending_submissions);
4404
4405 pthread_mutex_unlock(&submission->queue->pending_mutex);
4406
4407 /* If there is already a submission in the queue, that will decrement the counter by 1 when
4408 * submitted, but if the queue was empty, we decrement ourselves as there is no previous
4409 * submission. */
4410 uint32_t decrement = submission->wait_semaphore_count - wait_cnt + (is_first ? 1 : 0);
4411 return radv_queue_trigger_submission(submission, decrement, processing_list);
4412 }
4413
4414 static void
4415 radv_queue_submission_update_queue(struct radv_deferred_queue_submission *submission,
4416 struct list_head *processing_list)
4417 {
4418 pthread_mutex_lock(&submission->queue->pending_mutex);
4419 list_del(&submission->queue_pending_list);
4420
4421 /* trigger the next submission in the queue. */
4422 if (!list_is_empty(&submission->queue->pending_submissions)) {
4423 struct radv_deferred_queue_submission *next_submission =
4424 list_first_entry(&submission->queue->pending_submissions,
4425 struct radv_deferred_queue_submission,
4426 queue_pending_list);
4427 radv_queue_trigger_submission(next_submission, 1, processing_list);
4428 }
4429 pthread_mutex_unlock(&submission->queue->pending_mutex);
4430
4431 pthread_cond_broadcast(&submission->queue->device->timeline_cond);
4432 }
4433
4434 static VkResult
4435 radv_queue_submit_deferred(struct radv_deferred_queue_submission *submission,
4436 struct list_head *processing_list)
4437 {
4438 RADV_FROM_HANDLE(radv_fence, fence, submission->fence);
4439 struct radv_queue *queue = submission->queue;
4440 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
4441 uint32_t max_cs_submission = queue->device->trace_bo ? 1 : RADV_MAX_IBS_PER_SUBMIT;
4442 struct radeon_winsys_fence *base_fence = NULL;
4443 bool do_flush = submission->flush_caches || submission->wait_dst_stage_mask;
4444 bool can_patch = true;
4445 uint32_t advance;
4446 struct radv_winsys_sem_info sem_info;
4447 VkResult result;
4448 struct radeon_cmdbuf *initial_preamble_cs = NULL;
4449 struct radeon_cmdbuf *initial_flush_preamble_cs = NULL;
4450 struct radeon_cmdbuf *continue_preamble_cs = NULL;
4451
4452 if (fence) {
4453 /* Under most circumstances, out fences won't be temporary.
4454 * However, the spec does allow it for opaque_fd.
4455 *
4456 * From the Vulkan 1.0.53 spec:
4457 *
4458 * "If the import is temporary, the implementation must
4459 * restore the semaphore to its prior permanent state after
4460 * submitting the next semaphore wait operation."
4461 */
4462 struct radv_fence_part *part =
4463 fence->temporary.kind != RADV_FENCE_NONE ?
4464 &fence->temporary : &fence->permanent;
4465 if (part->kind == RADV_FENCE_WINSYS)
4466 base_fence = part->fence;
4467 }
4468
4469 result = radv_get_preambles(queue, submission->cmd_buffers,
4470 submission->cmd_buffer_count,
4471 &initial_preamble_cs,
4472 &initial_flush_preamble_cs,
4473 &continue_preamble_cs);
4474 if (result != VK_SUCCESS)
4475 goto fail;
4476
4477 result = radv_alloc_sem_info(queue->device,
4478 &sem_info,
4479 submission->wait_semaphore_count,
4480 submission->wait_semaphores,
4481 submission->wait_values,
4482 submission->signal_semaphore_count,
4483 submission->signal_semaphores,
4484 submission->signal_values,
4485 submission->fence);
4486 if (result != VK_SUCCESS)
4487 goto fail;
4488
4489 for (uint32_t i = 0; i < submission->buffer_bind_count; ++i) {
4490 result = radv_sparse_buffer_bind_memory(queue->device,
4491 submission->buffer_binds + i);
4492 if (result != VK_SUCCESS)
4493 goto fail;
4494 }
4495
4496 for (uint32_t i = 0; i < submission->image_opaque_bind_count; ++i) {
4497 result = radv_sparse_image_opaque_bind_memory(queue->device,
4498 submission->image_opaque_binds + i);
4499 if (result != VK_SUCCESS)
4500 goto fail;
4501 }
4502
4503 if (!submission->cmd_buffer_count) {
4504 result = queue->device->ws->cs_submit(ctx, queue->queue_idx,
4505 &queue->device->empty_cs[queue->queue_family_index],
4506 1, NULL, NULL,
4507 &sem_info, NULL,
4508 false, base_fence);
4509 if (result != VK_SUCCESS)
4510 goto fail;
4511 } else {
4512 struct radeon_cmdbuf **cs_array = malloc(sizeof(struct radeon_cmdbuf *) *
4513 (submission->cmd_buffer_count));
4514
4515 for (uint32_t j = 0; j < submission->cmd_buffer_count; j++) {
4516 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, submission->cmd_buffers[j]);
4517 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
4518
4519 cs_array[j] = cmd_buffer->cs;
4520 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
4521 can_patch = false;
4522
4523 cmd_buffer->status = RADV_CMD_BUFFER_STATUS_PENDING;
4524 }
4525
4526 for (uint32_t j = 0; j < submission->cmd_buffer_count; j += advance) {
4527 struct radeon_cmdbuf *initial_preamble = (do_flush && !j) ? initial_flush_preamble_cs : initial_preamble_cs;
4528 const struct radv_winsys_bo_list *bo_list = NULL;
4529
4530 advance = MIN2(max_cs_submission,
4531 submission->cmd_buffer_count - j);
4532
4533 if (queue->device->trace_bo)
4534 *queue->device->trace_id_ptr = 0;
4535
4536 sem_info.cs_emit_wait = j == 0;
4537 sem_info.cs_emit_signal = j + advance == submission->cmd_buffer_count;
4538
4539 if (unlikely(queue->device->use_global_bo_list)) {
4540 pthread_mutex_lock(&queue->device->bo_list.mutex);
4541 bo_list = &queue->device->bo_list.list;
4542 }
4543
4544 result = queue->device->ws->cs_submit(ctx, queue->queue_idx, cs_array + j,
4545 advance, initial_preamble, continue_preamble_cs,
4546 &sem_info, bo_list,
4547 can_patch, base_fence);
4548
4549 if (unlikely(queue->device->use_global_bo_list))
4550 pthread_mutex_unlock(&queue->device->bo_list.mutex);
4551
4552 if (result != VK_SUCCESS)
4553 goto fail;
4554
4555 if (queue->device->trace_bo) {
4556 radv_check_gpu_hangs(queue, cs_array[j]);
4557 }
4558
4559 if (queue->device->tma_bo) {
4560 radv_check_trap_handler(queue);
4561 }
4562 }
4563
4564 free(cs_array);
4565 }
4566
4567 radv_free_temp_syncobjs(queue->device,
4568 submission->temporary_semaphore_part_count,
4569 submission->temporary_semaphore_parts);
4570 radv_finalize_timelines(queue->device,
4571 submission->wait_semaphore_count,
4572 submission->wait_semaphores,
4573 submission->wait_values,
4574 submission->signal_semaphore_count,
4575 submission->signal_semaphores,
4576 submission->signal_values,
4577 processing_list);
4578 /* Has to happen after timeline finalization to make sure the
4579 * condition variable is only triggered when timelines and queue have
4580 * been updated. */
4581 radv_queue_submission_update_queue(submission, processing_list);
4582 radv_free_sem_info(&sem_info);
4583 free(submission);
4584 return VK_SUCCESS;
4585
4586 fail:
4587 if (result != VK_SUCCESS && result != VK_ERROR_DEVICE_LOST) {
4588 /* When something bad happened during the submission, such as
4589 * an out of memory issue, it might be hard to recover from
4590 * this inconsistent state. To avoid this sort of problem, we
4591 * assume that we are in a really bad situation and return
4592 * VK_ERROR_DEVICE_LOST to ensure the clients do not attempt
4593 * to submit the same job again to this device.
4594 */
4595 result = radv_device_set_lost(queue->device, "vkQueueSubmit() failed");
4596 }
4597
4598 radv_free_temp_syncobjs(queue->device,
4599 submission->temporary_semaphore_part_count,
4600 submission->temporary_semaphore_parts);
4601 free(submission);
4602 return result;
4603 }
4604
4605 static VkResult
4606 radv_process_submissions(struct list_head *processing_list)
4607 {
4608 while(!list_is_empty(processing_list)) {
4609 struct radv_deferred_queue_submission *submission =
4610 list_first_entry(processing_list, struct radv_deferred_queue_submission, processing_list);
4611 list_del(&submission->processing_list);
4612
4613 VkResult result = radv_queue_submit_deferred(submission, processing_list);
4614 if (result != VK_SUCCESS)
4615 return result;
4616 }
4617 return VK_SUCCESS;
4618 }
4619
4620 static VkResult
4621 wait_for_submission_timelines_available(struct radv_deferred_queue_submission *submission,
4622 uint64_t timeout)
4623 {
4624 struct radv_device *device = submission->queue->device;
4625 uint32_t syncobj_count = 0;
4626 uint32_t syncobj_idx = 0;
4627
4628 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4629 if (submission->wait_semaphores[i]->kind != RADV_SEMAPHORE_TIMELINE_SYNCOBJ)
4630 continue;
4631
4632 if (submission->wait_semaphores[i]->timeline_syncobj.max_point >= submission->wait_values[i])
4633 continue;
4634 ++syncobj_count;
4635 }
4636
4637 if (!syncobj_count)
4638 return VK_SUCCESS;
4639
4640 uint64_t *points = malloc((sizeof(uint64_t) + sizeof(uint32_t)) * syncobj_count);
4641 if (!points)
4642 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4643
4644 uint32_t *syncobj = (uint32_t*)(points + syncobj_count);
4645
4646 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4647 if (submission->wait_semaphores[i]->kind != RADV_SEMAPHORE_TIMELINE_SYNCOBJ)
4648 continue;
4649
4650 if (submission->wait_semaphores[i]->timeline_syncobj.max_point >= submission->wait_values[i])
4651 continue;
4652
4653 syncobj[syncobj_idx] = submission->wait_semaphores[i]->syncobj;
4654 points[syncobj_idx] = submission->wait_values[i];
4655 ++syncobj_idx;
4656 }
4657 bool success = device->ws->wait_timeline_syncobj(device->ws, syncobj, points, syncobj_idx, true, true, timeout);
4658
4659 free(points);
4660 return success ? VK_SUCCESS : VK_TIMEOUT;
4661 }
4662
4663 static void* radv_queue_submission_thread_run(void *q)
4664 {
4665 struct radv_queue *queue = q;
4666
4667 pthread_mutex_lock(&queue->thread_mutex);
4668 while (!p_atomic_read(&queue->thread_exit)) {
4669 struct radv_deferred_queue_submission *submission = queue->thread_submission;
4670 struct list_head processing_list;
4671 VkResult result = VK_SUCCESS;
4672 if (!submission) {
4673 pthread_cond_wait(&queue->thread_cond, &queue->thread_mutex);
4674 continue;
4675 }
4676 pthread_mutex_unlock(&queue->thread_mutex);
4677
4678 /* Wait at most 5 seconds so we have a chance to notice shutdown when
4679 * a semaphore never gets signaled. If it takes longer we just retry
4680 * the wait next iteration. */
4681 result = wait_for_submission_timelines_available(submission,
4682 radv_get_absolute_timeout(5000000000));
4683 if (result != VK_SUCCESS) {
4684 pthread_mutex_lock(&queue->thread_mutex);
4685 continue;
4686 }
4687
4688 /* The lock isn't held but nobody will add one until we finish
4689 * the current submission. */
4690 p_atomic_set(&queue->thread_submission, NULL);
4691
4692 list_inithead(&processing_list);
4693 list_addtail(&submission->processing_list, &processing_list);
4694 result = radv_process_submissions(&processing_list);
4695
4696 pthread_mutex_lock(&queue->thread_mutex);
4697 }
4698 pthread_mutex_unlock(&queue->thread_mutex);
4699 return NULL;
4700 }
4701
4702 static VkResult
4703 radv_queue_trigger_submission(struct radv_deferred_queue_submission *submission,
4704 uint32_t decrement,
4705 struct list_head *processing_list)
4706 {
4707 struct radv_queue *queue = submission->queue;
4708 int ret;
4709 if (p_atomic_add_return(&submission->submission_wait_count, -decrement))
4710 return VK_SUCCESS;
4711
4712 if (wait_for_submission_timelines_available(submission, radv_get_absolute_timeout(0)) == VK_SUCCESS) {
4713 list_addtail(&submission->processing_list, processing_list);
4714 return VK_SUCCESS;
4715 }
4716
4717 pthread_mutex_lock(&queue->thread_mutex);
4718
4719 /* A submission can only be ready for the thread if it doesn't have
4720 * any predecessors in the same queue, so there can only be one such
4721 * submission at a time. */
4722 assert(queue->thread_submission == NULL);
4723
4724 /* Only start the thread on demand to save resources for the many games
4725 * which only use binary semaphores. */
4726 if (!queue->thread_running) {
4727 ret = pthread_create(&queue->submission_thread, NULL,
4728 radv_queue_submission_thread_run, queue);
4729 if (ret) {
4730 pthread_mutex_unlock(&queue->thread_mutex);
4731 return vk_errorf(queue->device->instance,
4732 VK_ERROR_DEVICE_LOST,
4733 "Failed to start submission thread");
4734 }
4735 queue->thread_running = true;
4736 }
4737
4738 queue->thread_submission = submission;
4739 pthread_mutex_unlock(&queue->thread_mutex);
4740
4741 pthread_cond_signal(&queue->thread_cond);
4742 return VK_SUCCESS;
4743 }
4744
4745 static VkResult radv_queue_submit(struct radv_queue *queue,
4746 const struct radv_queue_submission *submission)
4747 {
4748 struct radv_deferred_queue_submission *deferred = NULL;
4749
4750 VkResult result = radv_create_deferred_submission(queue, submission, &deferred);
4751 if (result != VK_SUCCESS)
4752 return result;
4753
4754 struct list_head processing_list;
4755 list_inithead(&processing_list);
4756
4757 result = radv_queue_enqueue_submission(deferred, &processing_list);
4758 if (result != VK_SUCCESS) {
4759 /* If anything is in the list we leak. */
4760 assert(list_is_empty(&processing_list));
4761 return result;
4762 }
4763 return radv_process_submissions(&processing_list);
4764 }
4765
4766 bool
4767 radv_queue_internal_submit(struct radv_queue *queue, struct radeon_cmdbuf *cs)
4768 {
4769 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
4770 struct radv_winsys_sem_info sem_info;
4771 VkResult result;
4772
4773 result = radv_alloc_sem_info(queue->device, &sem_info, 0, NULL, 0, 0,
4774 0, NULL, VK_NULL_HANDLE);
4775 if (result != VK_SUCCESS)
4776 return false;
4777
4778 result = queue->device->ws->cs_submit(ctx, queue->queue_idx, &cs, 1,
4779 NULL, NULL, &sem_info, NULL,
4780 false, NULL);
4781 radv_free_sem_info(&sem_info);
4782 if (result != VK_SUCCESS)
4783 return false;
4784
4785 return true;
4786
4787 }
4788
4789 /* Signals fence as soon as all the work currently put on queue is done. */
4790 static VkResult radv_signal_fence(struct radv_queue *queue,
4791 VkFence fence)
4792 {
4793 return radv_queue_submit(queue, &(struct radv_queue_submission) {
4794 .fence = fence
4795 });
4796 }
4797
4798 static bool radv_submit_has_effects(const VkSubmitInfo *info)
4799 {
4800 return info->commandBufferCount ||
4801 info->waitSemaphoreCount ||
4802 info->signalSemaphoreCount;
4803 }
4804
4805 VkResult radv_QueueSubmit(
4806 VkQueue _queue,
4807 uint32_t submitCount,
4808 const VkSubmitInfo* pSubmits,
4809 VkFence fence)
4810 {
4811 RADV_FROM_HANDLE(radv_queue, queue, _queue);
4812 VkResult result;
4813 uint32_t fence_idx = 0;
4814 bool flushed_caches = false;
4815
4816 if (radv_device_is_lost(queue->device))
4817 return VK_ERROR_DEVICE_LOST;
4818
4819 if (fence != VK_NULL_HANDLE) {
4820 for (uint32_t i = 0; i < submitCount; ++i)
4821 if (radv_submit_has_effects(pSubmits + i))
4822 fence_idx = i;
4823 } else
4824 fence_idx = UINT32_MAX;
4825
4826 for (uint32_t i = 0; i < submitCount; i++) {
4827 if (!radv_submit_has_effects(pSubmits + i) && fence_idx != i)
4828 continue;
4829
4830 VkPipelineStageFlags wait_dst_stage_mask = 0;
4831 for (unsigned j = 0; j < pSubmits[i].waitSemaphoreCount; ++j) {
4832 wait_dst_stage_mask |= pSubmits[i].pWaitDstStageMask[j];
4833 }
4834
4835 const VkTimelineSemaphoreSubmitInfo *timeline_info =
4836 vk_find_struct_const(pSubmits[i].pNext, TIMELINE_SEMAPHORE_SUBMIT_INFO);
4837
4838 result = radv_queue_submit(queue, &(struct radv_queue_submission) {
4839 .cmd_buffers = pSubmits[i].pCommandBuffers,
4840 .cmd_buffer_count = pSubmits[i].commandBufferCount,
4841 .wait_dst_stage_mask = wait_dst_stage_mask,
4842 .flush_caches = !flushed_caches,
4843 .wait_semaphores = pSubmits[i].pWaitSemaphores,
4844 .wait_semaphore_count = pSubmits[i].waitSemaphoreCount,
4845 .signal_semaphores = pSubmits[i].pSignalSemaphores,
4846 .signal_semaphore_count = pSubmits[i].signalSemaphoreCount,
4847 .fence = i == fence_idx ? fence : VK_NULL_HANDLE,
4848 .wait_values = timeline_info ? timeline_info->pWaitSemaphoreValues : NULL,
4849 .wait_value_count = timeline_info && timeline_info->pWaitSemaphoreValues ? timeline_info->waitSemaphoreValueCount : 0,
4850 .signal_values = timeline_info ? timeline_info->pSignalSemaphoreValues : NULL,
4851 .signal_value_count = timeline_info && timeline_info->pSignalSemaphoreValues ? timeline_info->signalSemaphoreValueCount : 0,
4852 });
4853 if (result != VK_SUCCESS)
4854 return result;
4855
4856 flushed_caches = true;
4857 }
4858
4859 if (fence != VK_NULL_HANDLE && !submitCount) {
4860 result = radv_signal_fence(queue, fence);
4861 if (result != VK_SUCCESS)
4862 return result;
4863 }
4864
4865 return VK_SUCCESS;
4866 }
4867
4868 static const char *
4869 radv_get_queue_family_name(struct radv_queue *queue)
4870 {
4871 switch (queue->queue_family_index) {
4872 case RADV_QUEUE_GENERAL:
4873 return "graphics";
4874 case RADV_QUEUE_COMPUTE:
4875 return "compute";
4876 case RADV_QUEUE_TRANSFER:
4877 return "transfer";
4878 default:
4879 unreachable("Unknown queue family");
4880 }
4881 }
4882
4883 VkResult radv_QueueWaitIdle(
4884 VkQueue _queue)
4885 {
4886 RADV_FROM_HANDLE(radv_queue, queue, _queue);
4887
4888 if (radv_device_is_lost(queue->device))
4889 return VK_ERROR_DEVICE_LOST;
4890
4891 pthread_mutex_lock(&queue->pending_mutex);
4892 while (!list_is_empty(&queue->pending_submissions)) {
4893 pthread_cond_wait(&queue->device->timeline_cond, &queue->pending_mutex);
4894 }
4895 pthread_mutex_unlock(&queue->pending_mutex);
4896
4897 if (!queue->device->ws->ctx_wait_idle(queue->hw_ctx,
4898 radv_queue_family_to_ring(queue->queue_family_index),
4899 queue->queue_idx)) {
4900 return radv_device_set_lost(queue->device,
4901 "Failed to wait for a '%s' queue "
4902 "to be idle. GPU hang ?",
4903 radv_get_queue_family_name(queue));
4904 }
4905
4906 return VK_SUCCESS;
4907 }
4908
4909 VkResult radv_DeviceWaitIdle(
4910 VkDevice _device)
4911 {
4912 RADV_FROM_HANDLE(radv_device, device, _device);
4913
4914 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
4915 for (unsigned q = 0; q < device->queue_count[i]; q++) {
4916 VkResult result =
4917 radv_QueueWaitIdle(radv_queue_to_handle(&device->queues[i][q]));
4918
4919 if (result != VK_SUCCESS)
4920 return result;
4921 }
4922 }
4923 return VK_SUCCESS;
4924 }
4925
4926 VkResult radv_EnumerateInstanceExtensionProperties(
4927 const char* pLayerName,
4928 uint32_t* pPropertyCount,
4929 VkExtensionProperties* pProperties)
4930 {
4931 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
4932
4933 for (int i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; i++) {
4934 if (radv_instance_extensions_supported.extensions[i]) {
4935 vk_outarray_append(&out, prop) {
4936 *prop = radv_instance_extensions[i];
4937 }
4938 }
4939 }
4940
4941 return vk_outarray_status(&out);
4942 }
4943
4944 VkResult radv_EnumerateDeviceExtensionProperties(
4945 VkPhysicalDevice physicalDevice,
4946 const char* pLayerName,
4947 uint32_t* pPropertyCount,
4948 VkExtensionProperties* pProperties)
4949 {
4950 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
4951 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
4952
4953 for (int i = 0; i < RADV_DEVICE_EXTENSION_COUNT; i++) {
4954 if (device->supported_extensions.extensions[i]) {
4955 vk_outarray_append(&out, prop) {
4956 *prop = radv_device_extensions[i];
4957 }
4958 }
4959 }
4960
4961 return vk_outarray_status(&out);
4962 }
4963
4964 PFN_vkVoidFunction radv_GetInstanceProcAddr(
4965 VkInstance _instance,
4966 const char* pName)
4967 {
4968 RADV_FROM_HANDLE(radv_instance, instance, _instance);
4969
4970 /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
4971 * when we have to return valid function pointers, NULL, or it's left
4972 * undefined. See the table for exact details.
4973 */
4974 if (pName == NULL)
4975 return NULL;
4976
4977 #define LOOKUP_RADV_ENTRYPOINT(entrypoint) \
4978 if (strcmp(pName, "vk" #entrypoint) == 0) \
4979 return (PFN_vkVoidFunction)radv_##entrypoint
4980
4981 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
4982 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceLayerProperties);
4983 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceVersion);
4984 LOOKUP_RADV_ENTRYPOINT(CreateInstance);
4985
4986 /* GetInstanceProcAddr() can also be called with a NULL instance.
4987 * See https://gitlab.khronos.org/vulkan/vulkan/issues/2057
4988 */
4989 LOOKUP_RADV_ENTRYPOINT(GetInstanceProcAddr);
4990
4991 #undef LOOKUP_RADV_ENTRYPOINT
4992
4993 if (instance == NULL)
4994 return NULL;
4995
4996 int idx = radv_get_instance_entrypoint_index(pName);
4997 if (idx >= 0)
4998 return instance->dispatch.entrypoints[idx];
4999
5000 idx = radv_get_physical_device_entrypoint_index(pName);
5001 if (idx >= 0)
5002 return instance->physical_device_dispatch.entrypoints[idx];
5003
5004 idx = radv_get_device_entrypoint_index(pName);
5005 if (idx >= 0)
5006 return instance->device_dispatch.entrypoints[idx];
5007
5008 return NULL;
5009 }
5010
5011 /* The loader wants us to expose a second GetInstanceProcAddr function
5012 * to work around certain LD_PRELOAD issues seen in apps.
5013 */
5014 PUBLIC
5015 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
5016 VkInstance instance,
5017 const char* pName);
5018
5019 PUBLIC
5020 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
5021 VkInstance instance,
5022 const char* pName)
5023 {
5024 return radv_GetInstanceProcAddr(instance, pName);
5025 }
5026
5027 PUBLIC
5028 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
5029 VkInstance _instance,
5030 const char* pName);
5031
5032 PUBLIC
5033 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
5034 VkInstance _instance,
5035 const char* pName)
5036 {
5037 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5038
5039 if (!pName || !instance)
5040 return NULL;
5041
5042 int idx = radv_get_physical_device_entrypoint_index(pName);
5043 if (idx < 0)
5044 return NULL;
5045
5046 return instance->physical_device_dispatch.entrypoints[idx];
5047 }
5048
5049 PFN_vkVoidFunction radv_GetDeviceProcAddr(
5050 VkDevice _device,
5051 const char* pName)
5052 {
5053 RADV_FROM_HANDLE(radv_device, device, _device);
5054
5055 if (!device || !pName)
5056 return NULL;
5057
5058 int idx = radv_get_device_entrypoint_index(pName);
5059 if (idx < 0)
5060 return NULL;
5061
5062 return device->dispatch.entrypoints[idx];
5063 }
5064
5065 bool radv_get_memory_fd(struct radv_device *device,
5066 struct radv_device_memory *memory,
5067 int *pFD)
5068 {
5069 struct radeon_bo_metadata metadata;
5070
5071 if (memory->image) {
5072 if (memory->image->tiling != VK_IMAGE_TILING_LINEAR)
5073 radv_init_metadata(device, memory->image, &metadata);
5074 device->ws->buffer_set_metadata(memory->bo, &metadata);
5075 }
5076
5077 return device->ws->buffer_get_fd(device->ws, memory->bo,
5078 pFD);
5079 }
5080
5081
5082 void
5083 radv_free_memory(struct radv_device *device,
5084 const VkAllocationCallbacks* pAllocator,
5085 struct radv_device_memory *mem)
5086 {
5087 if (mem == NULL)
5088 return;
5089
5090 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
5091 if (mem->android_hardware_buffer)
5092 AHardwareBuffer_release(mem->android_hardware_buffer);
5093 #endif
5094
5095 if (mem->bo) {
5096 if (device->overallocation_disallowed) {
5097 mtx_lock(&device->overallocation_mutex);
5098 device->allocated_memory_size[mem->heap_index] -= mem->alloc_size;
5099 mtx_unlock(&device->overallocation_mutex);
5100 }
5101
5102 radv_bo_list_remove(device, mem->bo);
5103 device->ws->buffer_destroy(mem->bo);
5104 mem->bo = NULL;
5105 }
5106
5107 vk_object_base_finish(&mem->base);
5108 vk_free2(&device->vk.alloc, pAllocator, mem);
5109 }
5110
5111 static VkResult radv_alloc_memory(struct radv_device *device,
5112 const VkMemoryAllocateInfo* pAllocateInfo,
5113 const VkAllocationCallbacks* pAllocator,
5114 VkDeviceMemory* pMem)
5115 {
5116 struct radv_device_memory *mem;
5117 VkResult result;
5118 enum radeon_bo_domain domain;
5119 uint32_t flags = 0;
5120
5121 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
5122
5123 const VkImportMemoryFdInfoKHR *import_info =
5124 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
5125 const VkMemoryDedicatedAllocateInfo *dedicate_info =
5126 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);
5127 const VkExportMemoryAllocateInfo *export_info =
5128 vk_find_struct_const(pAllocateInfo->pNext, EXPORT_MEMORY_ALLOCATE_INFO);
5129 const struct VkImportAndroidHardwareBufferInfoANDROID *ahb_import_info =
5130 vk_find_struct_const(pAllocateInfo->pNext,
5131 IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID);
5132 const VkImportMemoryHostPointerInfoEXT *host_ptr_info =
5133 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_HOST_POINTER_INFO_EXT);
5134
5135 const struct wsi_memory_allocate_info *wsi_info =
5136 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
5137
5138 if (pAllocateInfo->allocationSize == 0 && !ahb_import_info &&
5139 !(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID))) {
5140 /* Apparently, this is allowed */
5141 *pMem = VK_NULL_HANDLE;
5142 return VK_SUCCESS;
5143 }
5144
5145 mem = vk_zalloc2(&device->vk.alloc, pAllocator, sizeof(*mem), 8,
5146 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5147 if (mem == NULL)
5148 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5149
5150 vk_object_base_init(&device->vk, &mem->base,
5151 VK_OBJECT_TYPE_DEVICE_MEMORY);
5152
5153 if (wsi_info && wsi_info->implicit_sync)
5154 flags |= RADEON_FLAG_IMPLICIT_SYNC;
5155
5156 if (dedicate_info) {
5157 mem->image = radv_image_from_handle(dedicate_info->image);
5158 mem->buffer = radv_buffer_from_handle(dedicate_info->buffer);
5159 } else {
5160 mem->image = NULL;
5161 mem->buffer = NULL;
5162 }
5163
5164 float priority_float = 0.5;
5165 const struct VkMemoryPriorityAllocateInfoEXT *priority_ext =
5166 vk_find_struct_const(pAllocateInfo->pNext,
5167 MEMORY_PRIORITY_ALLOCATE_INFO_EXT);
5168 if (priority_ext)
5169 priority_float = priority_ext->priority;
5170
5171 unsigned priority = MIN2(RADV_BO_PRIORITY_APPLICATION_MAX - 1,
5172 (int)(priority_float * RADV_BO_PRIORITY_APPLICATION_MAX));
5173
5174 mem->user_ptr = NULL;
5175 mem->bo = NULL;
5176
5177 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
5178 mem->android_hardware_buffer = NULL;
5179 #endif
5180
5181 if (ahb_import_info) {
5182 result = radv_import_ahb_memory(device, mem, priority, ahb_import_info);
5183 if (result != VK_SUCCESS)
5184 goto fail;
5185 } else if(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)) {
5186 result = radv_create_ahb_memory(device, mem, priority, pAllocateInfo);
5187 if (result != VK_SUCCESS)
5188 goto fail;
5189 } else if (import_info) {
5190 assert(import_info->handleType ==
5191 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
5192 import_info->handleType ==
5193 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
5194 mem->bo = device->ws->buffer_from_fd(device->ws, import_info->fd,
5195 priority, NULL);
5196 if (!mem->bo) {
5197 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
5198 goto fail;
5199 } else {
5200 close(import_info->fd);
5201 }
5202
5203 if (mem->image && mem->image->plane_count == 1 &&
5204 !vk_format_is_depth_or_stencil(mem->image->vk_format)) {
5205 struct radeon_bo_metadata metadata;
5206 device->ws->buffer_get_metadata(mem->bo, &metadata);
5207
5208 struct radv_image_create_info create_info = {
5209 .no_metadata_planes = true,
5210 .bo_metadata = &metadata
5211 };
5212
5213 /* This gives a basic ability to import radeonsi images
5214 * that don't have DCC. This is not guaranteed by any
5215 * spec and can be removed after we support modifiers. */
5216 result = radv_image_create_layout(device, create_info, mem->image);
5217 if (result != VK_SUCCESS) {
5218 device->ws->buffer_destroy(mem->bo);
5219 goto fail;
5220 }
5221 }
5222 } else if (host_ptr_info) {
5223 assert(host_ptr_info->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
5224 mem->bo = device->ws->buffer_from_ptr(device->ws, host_ptr_info->pHostPointer,
5225 pAllocateInfo->allocationSize,
5226 priority);
5227 if (!mem->bo) {
5228 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
5229 goto fail;
5230 } else {
5231 mem->user_ptr = host_ptr_info->pHostPointer;
5232 }
5233 } else {
5234 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
5235 uint32_t heap_index;
5236
5237 heap_index = device->physical_device->memory_properties.memoryTypes[pAllocateInfo->memoryTypeIndex].heapIndex;
5238 domain = device->physical_device->memory_domains[pAllocateInfo->memoryTypeIndex];
5239 flags |= device->physical_device->memory_flags[pAllocateInfo->memoryTypeIndex];
5240
5241 if (!dedicate_info && !import_info && (!export_info || !export_info->handleTypes)) {
5242 flags |= RADEON_FLAG_NO_INTERPROCESS_SHARING;
5243 if (device->use_global_bo_list) {
5244 flags |= RADEON_FLAG_PREFER_LOCAL_BO;
5245 }
5246 }
5247
5248 if (device->overallocation_disallowed) {
5249 uint64_t total_size =
5250 device->physical_device->memory_properties.memoryHeaps[heap_index].size;
5251
5252 mtx_lock(&device->overallocation_mutex);
5253 if (device->allocated_memory_size[heap_index] + alloc_size > total_size) {
5254 mtx_unlock(&device->overallocation_mutex);
5255 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
5256 goto fail;
5257 }
5258 device->allocated_memory_size[heap_index] += alloc_size;
5259 mtx_unlock(&device->overallocation_mutex);
5260 }
5261
5262 mem->bo = device->ws->buffer_create(device->ws, alloc_size, device->physical_device->rad_info.max_alignment,
5263 domain, flags, priority);
5264
5265 if (!mem->bo) {
5266 if (device->overallocation_disallowed) {
5267 mtx_lock(&device->overallocation_mutex);
5268 device->allocated_memory_size[heap_index] -= alloc_size;
5269 mtx_unlock(&device->overallocation_mutex);
5270 }
5271 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
5272 goto fail;
5273 }
5274
5275 mem->heap_index = heap_index;
5276 mem->alloc_size = alloc_size;
5277 }
5278
5279 if (!wsi_info) {
5280 result = radv_bo_list_add(device, mem->bo);
5281 if (result != VK_SUCCESS)
5282 goto fail;
5283 }
5284
5285 *pMem = radv_device_memory_to_handle(mem);
5286
5287 return VK_SUCCESS;
5288
5289 fail:
5290 radv_free_memory(device, pAllocator,mem);
5291
5292 return result;
5293 }
5294
5295 VkResult radv_AllocateMemory(
5296 VkDevice _device,
5297 const VkMemoryAllocateInfo* pAllocateInfo,
5298 const VkAllocationCallbacks* pAllocator,
5299 VkDeviceMemory* pMem)
5300 {
5301 RADV_FROM_HANDLE(radv_device, device, _device);
5302 return radv_alloc_memory(device, pAllocateInfo, pAllocator, pMem);
5303 }
5304
5305 void radv_FreeMemory(
5306 VkDevice _device,
5307 VkDeviceMemory _mem,
5308 const VkAllocationCallbacks* pAllocator)
5309 {
5310 RADV_FROM_HANDLE(radv_device, device, _device);
5311 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
5312
5313 radv_free_memory(device, pAllocator, mem);
5314 }
5315
5316 VkResult radv_MapMemory(
5317 VkDevice _device,
5318 VkDeviceMemory _memory,
5319 VkDeviceSize offset,
5320 VkDeviceSize size,
5321 VkMemoryMapFlags flags,
5322 void** ppData)
5323 {
5324 RADV_FROM_HANDLE(radv_device, device, _device);
5325 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
5326
5327 if (mem == NULL) {
5328 *ppData = NULL;
5329 return VK_SUCCESS;
5330 }
5331
5332 if (mem->user_ptr)
5333 *ppData = mem->user_ptr;
5334 else
5335 *ppData = device->ws->buffer_map(mem->bo);
5336
5337 if (*ppData) {
5338 *ppData += offset;
5339 return VK_SUCCESS;
5340 }
5341
5342 return vk_error(device->instance, VK_ERROR_MEMORY_MAP_FAILED);
5343 }
5344
5345 void radv_UnmapMemory(
5346 VkDevice _device,
5347 VkDeviceMemory _memory)
5348 {
5349 RADV_FROM_HANDLE(radv_device, device, _device);
5350 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
5351
5352 if (mem == NULL)
5353 return;
5354
5355 if (mem->user_ptr == NULL)
5356 device->ws->buffer_unmap(mem->bo);
5357 }
5358
5359 VkResult radv_FlushMappedMemoryRanges(
5360 VkDevice _device,
5361 uint32_t memoryRangeCount,
5362 const VkMappedMemoryRange* pMemoryRanges)
5363 {
5364 return VK_SUCCESS;
5365 }
5366
5367 VkResult radv_InvalidateMappedMemoryRanges(
5368 VkDevice _device,
5369 uint32_t memoryRangeCount,
5370 const VkMappedMemoryRange* pMemoryRanges)
5371 {
5372 return VK_SUCCESS;
5373 }
5374
5375 void radv_GetBufferMemoryRequirements(
5376 VkDevice _device,
5377 VkBuffer _buffer,
5378 VkMemoryRequirements* pMemoryRequirements)
5379 {
5380 RADV_FROM_HANDLE(radv_device, device, _device);
5381 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
5382
5383 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
5384
5385 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
5386 pMemoryRequirements->alignment = 4096;
5387 else
5388 pMemoryRequirements->alignment = 16;
5389
5390 pMemoryRequirements->size = align64(buffer->size, pMemoryRequirements->alignment);
5391 }
5392
5393 void radv_GetBufferMemoryRequirements2(
5394 VkDevice device,
5395 const VkBufferMemoryRequirementsInfo2 *pInfo,
5396 VkMemoryRequirements2 *pMemoryRequirements)
5397 {
5398 radv_GetBufferMemoryRequirements(device, pInfo->buffer,
5399 &pMemoryRequirements->memoryRequirements);
5400 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
5401 switch (ext->sType) {
5402 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
5403 VkMemoryDedicatedRequirements *req =
5404 (VkMemoryDedicatedRequirements *) ext;
5405 req->requiresDedicatedAllocation = false;
5406 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
5407 break;
5408 }
5409 default:
5410 break;
5411 }
5412 }
5413 }
5414
5415 void radv_GetImageMemoryRequirements(
5416 VkDevice _device,
5417 VkImage _image,
5418 VkMemoryRequirements* pMemoryRequirements)
5419 {
5420 RADV_FROM_HANDLE(radv_device, device, _device);
5421 RADV_FROM_HANDLE(radv_image, image, _image);
5422
5423 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
5424
5425 pMemoryRequirements->size = image->size;
5426 pMemoryRequirements->alignment = image->alignment;
5427 }
5428
5429 void radv_GetImageMemoryRequirements2(
5430 VkDevice device,
5431 const VkImageMemoryRequirementsInfo2 *pInfo,
5432 VkMemoryRequirements2 *pMemoryRequirements)
5433 {
5434 radv_GetImageMemoryRequirements(device, pInfo->image,
5435 &pMemoryRequirements->memoryRequirements);
5436
5437 RADV_FROM_HANDLE(radv_image, image, pInfo->image);
5438
5439 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
5440 switch (ext->sType) {
5441 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
5442 VkMemoryDedicatedRequirements *req =
5443 (VkMemoryDedicatedRequirements *) ext;
5444 req->requiresDedicatedAllocation = image->shareable &&
5445 image->tiling != VK_IMAGE_TILING_LINEAR;
5446 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
5447 break;
5448 }
5449 default:
5450 break;
5451 }
5452 }
5453 }
5454
5455 void radv_GetImageSparseMemoryRequirements(
5456 VkDevice device,
5457 VkImage image,
5458 uint32_t* pSparseMemoryRequirementCount,
5459 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
5460 {
5461 stub();
5462 }
5463
5464 void radv_GetImageSparseMemoryRequirements2(
5465 VkDevice device,
5466 const VkImageSparseMemoryRequirementsInfo2 *pInfo,
5467 uint32_t* pSparseMemoryRequirementCount,
5468 VkSparseImageMemoryRequirements2 *pSparseMemoryRequirements)
5469 {
5470 stub();
5471 }
5472
5473 void radv_GetDeviceMemoryCommitment(
5474 VkDevice device,
5475 VkDeviceMemory memory,
5476 VkDeviceSize* pCommittedMemoryInBytes)
5477 {
5478 *pCommittedMemoryInBytes = 0;
5479 }
5480
5481 VkResult radv_BindBufferMemory2(VkDevice device,
5482 uint32_t bindInfoCount,
5483 const VkBindBufferMemoryInfo *pBindInfos)
5484 {
5485 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5486 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
5487 RADV_FROM_HANDLE(radv_buffer, buffer, pBindInfos[i].buffer);
5488
5489 if (mem) {
5490 buffer->bo = mem->bo;
5491 buffer->offset = pBindInfos[i].memoryOffset;
5492 } else {
5493 buffer->bo = NULL;
5494 }
5495 }
5496 return VK_SUCCESS;
5497 }
5498
5499 VkResult radv_BindBufferMemory(
5500 VkDevice device,
5501 VkBuffer buffer,
5502 VkDeviceMemory memory,
5503 VkDeviceSize memoryOffset)
5504 {
5505 const VkBindBufferMemoryInfo info = {
5506 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
5507 .buffer = buffer,
5508 .memory = memory,
5509 .memoryOffset = memoryOffset
5510 };
5511
5512 return radv_BindBufferMemory2(device, 1, &info);
5513 }
5514
5515 VkResult radv_BindImageMemory2(VkDevice device,
5516 uint32_t bindInfoCount,
5517 const VkBindImageMemoryInfo *pBindInfos)
5518 {
5519 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5520 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
5521 RADV_FROM_HANDLE(radv_image, image, pBindInfos[i].image);
5522
5523 if (mem) {
5524 image->bo = mem->bo;
5525 image->offset = pBindInfos[i].memoryOffset;
5526 } else {
5527 image->bo = NULL;
5528 image->offset = 0;
5529 }
5530 }
5531 return VK_SUCCESS;
5532 }
5533
5534
5535 VkResult radv_BindImageMemory(
5536 VkDevice device,
5537 VkImage image,
5538 VkDeviceMemory memory,
5539 VkDeviceSize memoryOffset)
5540 {
5541 const VkBindImageMemoryInfo info = {
5542 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
5543 .image = image,
5544 .memory = memory,
5545 .memoryOffset = memoryOffset
5546 };
5547
5548 return radv_BindImageMemory2(device, 1, &info);
5549 }
5550
5551 static bool radv_sparse_bind_has_effects(const VkBindSparseInfo *info)
5552 {
5553 return info->bufferBindCount ||
5554 info->imageOpaqueBindCount ||
5555 info->imageBindCount ||
5556 info->waitSemaphoreCount ||
5557 info->signalSemaphoreCount;
5558 }
5559
5560 VkResult radv_QueueBindSparse(
5561 VkQueue _queue,
5562 uint32_t bindInfoCount,
5563 const VkBindSparseInfo* pBindInfo,
5564 VkFence fence)
5565 {
5566 RADV_FROM_HANDLE(radv_queue, queue, _queue);
5567 VkResult result;
5568 uint32_t fence_idx = 0;
5569
5570 if (radv_device_is_lost(queue->device))
5571 return VK_ERROR_DEVICE_LOST;
5572
5573 if (fence != VK_NULL_HANDLE) {
5574 for (uint32_t i = 0; i < bindInfoCount; ++i)
5575 if (radv_sparse_bind_has_effects(pBindInfo + i))
5576 fence_idx = i;
5577 } else
5578 fence_idx = UINT32_MAX;
5579
5580 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5581 if (i != fence_idx && !radv_sparse_bind_has_effects(pBindInfo + i))
5582 continue;
5583
5584 const VkTimelineSemaphoreSubmitInfo *timeline_info =
5585 vk_find_struct_const(pBindInfo[i].pNext, TIMELINE_SEMAPHORE_SUBMIT_INFO);
5586
5587 VkResult result = radv_queue_submit(queue, &(struct radv_queue_submission) {
5588 .buffer_binds = pBindInfo[i].pBufferBinds,
5589 .buffer_bind_count = pBindInfo[i].bufferBindCount,
5590 .image_opaque_binds = pBindInfo[i].pImageOpaqueBinds,
5591 .image_opaque_bind_count = pBindInfo[i].imageOpaqueBindCount,
5592 .wait_semaphores = pBindInfo[i].pWaitSemaphores,
5593 .wait_semaphore_count = pBindInfo[i].waitSemaphoreCount,
5594 .signal_semaphores = pBindInfo[i].pSignalSemaphores,
5595 .signal_semaphore_count = pBindInfo[i].signalSemaphoreCount,
5596 .fence = i == fence_idx ? fence : VK_NULL_HANDLE,
5597 .wait_values = timeline_info ? timeline_info->pWaitSemaphoreValues : NULL,
5598 .wait_value_count = timeline_info && timeline_info->pWaitSemaphoreValues ? timeline_info->waitSemaphoreValueCount : 0,
5599 .signal_values = timeline_info ? timeline_info->pSignalSemaphoreValues : NULL,
5600 .signal_value_count = timeline_info && timeline_info->pSignalSemaphoreValues ? timeline_info->signalSemaphoreValueCount : 0,
5601 });
5602
5603 if (result != VK_SUCCESS)
5604 return result;
5605 }
5606
5607 if (fence != VK_NULL_HANDLE && !bindInfoCount) {
5608 result = radv_signal_fence(queue, fence);
5609 if (result != VK_SUCCESS)
5610 return result;
5611 }
5612
5613 return VK_SUCCESS;
5614 }
5615
5616 static void
5617 radv_destroy_fence_part(struct radv_device *device,
5618 struct radv_fence_part *part)
5619 {
5620 switch (part->kind) {
5621 case RADV_FENCE_NONE:
5622 break;
5623 case RADV_FENCE_WINSYS:
5624 device->ws->destroy_fence(part->fence);
5625 break;
5626 case RADV_FENCE_SYNCOBJ:
5627 device->ws->destroy_syncobj(device->ws, part->syncobj);
5628 break;
5629 case RADV_FENCE_WSI:
5630 part->fence_wsi->destroy(part->fence_wsi);
5631 break;
5632 default:
5633 unreachable("Invalid fence type");
5634 }
5635
5636 part->kind = RADV_FENCE_NONE;
5637 }
5638
5639 static void
5640 radv_destroy_fence(struct radv_device *device,
5641 const VkAllocationCallbacks *pAllocator,
5642 struct radv_fence *fence)
5643 {
5644 radv_destroy_fence_part(device, &fence->temporary);
5645 radv_destroy_fence_part(device, &fence->permanent);
5646
5647 vk_object_base_finish(&fence->base);
5648 vk_free2(&device->vk.alloc, pAllocator, fence);
5649 }
5650
5651 VkResult radv_CreateFence(
5652 VkDevice _device,
5653 const VkFenceCreateInfo* pCreateInfo,
5654 const VkAllocationCallbacks* pAllocator,
5655 VkFence* pFence)
5656 {
5657 RADV_FROM_HANDLE(radv_device, device, _device);
5658 const VkExportFenceCreateInfo *export =
5659 vk_find_struct_const(pCreateInfo->pNext, EXPORT_FENCE_CREATE_INFO);
5660 VkExternalFenceHandleTypeFlags handleTypes =
5661 export ? export->handleTypes : 0;
5662 struct radv_fence *fence;
5663
5664 fence = vk_zalloc2(&device->vk.alloc, pAllocator, sizeof(*fence), 8,
5665 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5666 if (!fence)
5667 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5668
5669 vk_object_base_init(&device->vk, &fence->base, VK_OBJECT_TYPE_FENCE);
5670
5671 if (device->always_use_syncobj || handleTypes) {
5672 fence->permanent.kind = RADV_FENCE_SYNCOBJ;
5673
5674 bool create_signaled = false;
5675 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT)
5676 create_signaled = true;
5677
5678 int ret = device->ws->create_syncobj(device->ws, create_signaled,
5679 &fence->permanent.syncobj);
5680 if (ret) {
5681 radv_destroy_fence(device, pAllocator, fence);
5682 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5683 }
5684 } else {
5685 fence->permanent.kind = RADV_FENCE_WINSYS;
5686
5687 fence->permanent.fence = device->ws->create_fence();
5688 if (!fence->permanent.fence) {
5689 vk_free2(&device->vk.alloc, pAllocator, fence);
5690 radv_destroy_fence(device, pAllocator, fence);
5691 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5692 }
5693 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT)
5694 device->ws->signal_fence(fence->permanent.fence);
5695 }
5696
5697 *pFence = radv_fence_to_handle(fence);
5698
5699 return VK_SUCCESS;
5700 }
5701
5702
5703 void radv_DestroyFence(
5704 VkDevice _device,
5705 VkFence _fence,
5706 const VkAllocationCallbacks* pAllocator)
5707 {
5708 RADV_FROM_HANDLE(radv_device, device, _device);
5709 RADV_FROM_HANDLE(radv_fence, fence, _fence);
5710
5711 if (!fence)
5712 return;
5713
5714 radv_destroy_fence(device, pAllocator, fence);
5715 }
5716
5717 static bool radv_all_fences_plain_and_submitted(struct radv_device *device,
5718 uint32_t fenceCount, const VkFence *pFences)
5719 {
5720 for (uint32_t i = 0; i < fenceCount; ++i) {
5721 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5722
5723 struct radv_fence_part *part =
5724 fence->temporary.kind != RADV_FENCE_NONE ?
5725 &fence->temporary : &fence->permanent;
5726 if (part->kind != RADV_FENCE_WINSYS ||
5727 !device->ws->is_fence_waitable(part->fence))
5728 return false;
5729 }
5730 return true;
5731 }
5732
5733 static bool radv_all_fences_syncobj(uint32_t fenceCount, const VkFence *pFences)
5734 {
5735 for (uint32_t i = 0; i < fenceCount; ++i) {
5736 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5737
5738 struct radv_fence_part *part =
5739 fence->temporary.kind != RADV_FENCE_NONE ?
5740 &fence->temporary : &fence->permanent;
5741 if (part->kind != RADV_FENCE_SYNCOBJ)
5742 return false;
5743 }
5744 return true;
5745 }
5746
5747 VkResult radv_WaitForFences(
5748 VkDevice _device,
5749 uint32_t fenceCount,
5750 const VkFence* pFences,
5751 VkBool32 waitAll,
5752 uint64_t timeout)
5753 {
5754 RADV_FROM_HANDLE(radv_device, device, _device);
5755
5756 if (radv_device_is_lost(device))
5757 return VK_ERROR_DEVICE_LOST;
5758
5759 timeout = radv_get_absolute_timeout(timeout);
5760
5761 if (device->always_use_syncobj &&
5762 radv_all_fences_syncobj(fenceCount, pFences))
5763 {
5764 uint32_t *handles = malloc(sizeof(uint32_t) * fenceCount);
5765 if (!handles)
5766 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5767
5768 for (uint32_t i = 0; i < fenceCount; ++i) {
5769 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5770
5771 struct radv_fence_part *part =
5772 fence->temporary.kind != RADV_FENCE_NONE ?
5773 &fence->temporary : &fence->permanent;
5774
5775 assert(part->kind == RADV_FENCE_SYNCOBJ);
5776 handles[i] = part->syncobj;
5777 }
5778
5779 bool success = device->ws->wait_syncobj(device->ws, handles, fenceCount, waitAll, timeout);
5780
5781 free(handles);
5782 return success ? VK_SUCCESS : VK_TIMEOUT;
5783 }
5784
5785 if (!waitAll && fenceCount > 1) {
5786 /* Not doing this by default for waitAll, due to needing to allocate twice. */
5787 if (device->physical_device->rad_info.drm_minor >= 10 && radv_all_fences_plain_and_submitted(device, fenceCount, pFences)) {
5788 uint32_t wait_count = 0;
5789 struct radeon_winsys_fence **fences = malloc(sizeof(struct radeon_winsys_fence *) * fenceCount);
5790 if (!fences)
5791 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5792
5793 for (uint32_t i = 0; i < fenceCount; ++i) {
5794 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5795
5796 struct radv_fence_part *part =
5797 fence->temporary.kind != RADV_FENCE_NONE ?
5798 &fence->temporary : &fence->permanent;
5799 assert(part->kind == RADV_FENCE_WINSYS);
5800
5801 if (device->ws->fence_wait(device->ws, part->fence, false, 0)) {
5802 free(fences);
5803 return VK_SUCCESS;
5804 }
5805
5806 fences[wait_count++] = part->fence;
5807 }
5808
5809 bool success = device->ws->fences_wait(device->ws, fences, wait_count,
5810 waitAll, timeout - radv_get_current_time());
5811
5812 free(fences);
5813 return success ? VK_SUCCESS : VK_TIMEOUT;
5814 }
5815
5816 while(radv_get_current_time() <= timeout) {
5817 for (uint32_t i = 0; i < fenceCount; ++i) {
5818 if (radv_GetFenceStatus(_device, pFences[i]) == VK_SUCCESS)
5819 return VK_SUCCESS;
5820 }
5821 }
5822 return VK_TIMEOUT;
5823 }
5824
5825 for (uint32_t i = 0; i < fenceCount; ++i) {
5826 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5827 bool expired = false;
5828
5829 struct radv_fence_part *part =
5830 fence->temporary.kind != RADV_FENCE_NONE ?
5831 &fence->temporary : &fence->permanent;
5832
5833 switch (part->kind) {
5834 case RADV_FENCE_NONE:
5835 break;
5836 case RADV_FENCE_WINSYS:
5837 if (!device->ws->is_fence_waitable(part->fence)) {
5838 while (!device->ws->is_fence_waitable(part->fence) &&
5839 radv_get_current_time() <= timeout)
5840 /* Do nothing */;
5841 }
5842
5843 expired = device->ws->fence_wait(device->ws,
5844 part->fence,
5845 true, timeout);
5846 if (!expired)
5847 return VK_TIMEOUT;
5848 break;
5849 case RADV_FENCE_SYNCOBJ:
5850 if (!device->ws->wait_syncobj(device->ws,
5851 &part->syncobj, 1, true,
5852 timeout))
5853 return VK_TIMEOUT;
5854 break;
5855 case RADV_FENCE_WSI: {
5856 VkResult result = part->fence_wsi->wait(part->fence_wsi, timeout);
5857 if (result != VK_SUCCESS)
5858 return result;
5859 break;
5860 }
5861 default:
5862 unreachable("Invalid fence type");
5863 }
5864 }
5865
5866 return VK_SUCCESS;
5867 }
5868
5869 VkResult radv_ResetFences(VkDevice _device,
5870 uint32_t fenceCount,
5871 const VkFence *pFences)
5872 {
5873 RADV_FROM_HANDLE(radv_device, device, _device);
5874
5875 for (unsigned i = 0; i < fenceCount; ++i) {
5876 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5877
5878 /* From the Vulkan 1.0.53 spec:
5879 *
5880 * "If any member of pFences currently has its payload
5881 * imported with temporary permanence, that fence’s prior
5882 * permanent payload is irst restored. The remaining
5883 * operations described therefore operate on the restored
5884 * payload."
5885 */
5886 if (fence->temporary.kind != RADV_FENCE_NONE)
5887 radv_destroy_fence_part(device, &fence->temporary);
5888
5889 struct radv_fence_part *part = &fence->permanent;
5890
5891 switch (part->kind) {
5892 case RADV_FENCE_WSI:
5893 device->ws->reset_fence(part->fence);
5894 break;
5895 case RADV_FENCE_SYNCOBJ:
5896 device->ws->reset_syncobj(device->ws, part->syncobj);
5897 break;
5898 default:
5899 unreachable("Invalid fence type");
5900 }
5901 }
5902
5903 return VK_SUCCESS;
5904 }
5905
5906 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
5907 {
5908 RADV_FROM_HANDLE(radv_device, device, _device);
5909 RADV_FROM_HANDLE(radv_fence, fence, _fence);
5910
5911 struct radv_fence_part *part =
5912 fence->temporary.kind != RADV_FENCE_NONE ?
5913 &fence->temporary : &fence->permanent;
5914
5915 if (radv_device_is_lost(device))
5916 return VK_ERROR_DEVICE_LOST;
5917
5918 switch (part->kind) {
5919 case RADV_FENCE_NONE:
5920 break;
5921 case RADV_FENCE_WINSYS:
5922 if (!device->ws->fence_wait(device->ws, part->fence, false, 0))
5923 return VK_NOT_READY;
5924 break;
5925 case RADV_FENCE_SYNCOBJ: {
5926 bool success = device->ws->wait_syncobj(device->ws,
5927 &part->syncobj, 1, true, 0);
5928 if (!success)
5929 return VK_NOT_READY;
5930 break;
5931 }
5932 case RADV_FENCE_WSI: {
5933 VkResult result = part->fence_wsi->wait(part->fence_wsi, 0);
5934 if (result != VK_SUCCESS) {
5935 if (result == VK_TIMEOUT)
5936 return VK_NOT_READY;
5937 return result;
5938 }
5939 break;
5940 }
5941 default:
5942 unreachable("Invalid fence type");
5943 }
5944
5945 return VK_SUCCESS;
5946 }
5947
5948
5949 // Queue semaphore functions
5950
5951 static void
5952 radv_create_timeline(struct radv_timeline *timeline, uint64_t value)
5953 {
5954 timeline->highest_signaled = value;
5955 timeline->highest_submitted = value;
5956 list_inithead(&timeline->points);
5957 list_inithead(&timeline->free_points);
5958 list_inithead(&timeline->waiters);
5959 pthread_mutex_init(&timeline->mutex, NULL);
5960 }
5961
5962 static void
5963 radv_destroy_timeline(struct radv_device *device,
5964 struct radv_timeline *timeline)
5965 {
5966 list_for_each_entry_safe(struct radv_timeline_point, point,
5967 &timeline->free_points, list) {
5968 list_del(&point->list);
5969 device->ws->destroy_syncobj(device->ws, point->syncobj);
5970 free(point);
5971 }
5972 list_for_each_entry_safe(struct radv_timeline_point, point,
5973 &timeline->points, list) {
5974 list_del(&point->list);
5975 device->ws->destroy_syncobj(device->ws, point->syncobj);
5976 free(point);
5977 }
5978 pthread_mutex_destroy(&timeline->mutex);
5979 }
5980
5981 static void
5982 radv_timeline_gc_locked(struct radv_device *device,
5983 struct radv_timeline *timeline)
5984 {
5985 list_for_each_entry_safe(struct radv_timeline_point, point,
5986 &timeline->points, list) {
5987 if (point->wait_count || point->value > timeline->highest_submitted)
5988 return;
5989
5990 if (device->ws->wait_syncobj(device->ws, &point->syncobj, 1, true, 0)) {
5991 timeline->highest_signaled = point->value;
5992 list_del(&point->list);
5993 list_add(&point->list, &timeline->free_points);
5994 }
5995 }
5996 }
5997
5998 static struct radv_timeline_point *
5999 radv_timeline_find_point_at_least_locked(struct radv_device *device,
6000 struct radv_timeline *timeline,
6001 uint64_t p)
6002 {
6003 radv_timeline_gc_locked(device, timeline);
6004
6005 if (p <= timeline->highest_signaled)
6006 return NULL;
6007
6008 list_for_each_entry(struct radv_timeline_point, point,
6009 &timeline->points, list) {
6010 if (point->value >= p) {
6011 ++point->wait_count;
6012 return point;
6013 }
6014 }
6015 return NULL;
6016 }
6017
6018 static struct radv_timeline_point *
6019 radv_timeline_add_point_locked(struct radv_device *device,
6020 struct radv_timeline *timeline,
6021 uint64_t p)
6022 {
6023 radv_timeline_gc_locked(device, timeline);
6024
6025 struct radv_timeline_point *ret = NULL;
6026 struct radv_timeline_point *prev = NULL;
6027 int r;
6028
6029 if (p <= timeline->highest_signaled)
6030 return NULL;
6031
6032 list_for_each_entry(struct radv_timeline_point, point,
6033 &timeline->points, list) {
6034 if (point->value == p) {
6035 return NULL;
6036 }
6037
6038 if (point->value < p)
6039 prev = point;
6040 }
6041
6042 if (list_is_empty(&timeline->free_points)) {
6043 ret = malloc(sizeof(struct radv_timeline_point));
6044 r = device->ws->create_syncobj(device->ws, false, &ret->syncobj);
6045 if (r) {
6046 free(ret);
6047 return NULL;
6048 }
6049 } else {
6050 ret = list_first_entry(&timeline->free_points, struct radv_timeline_point, list);
6051 list_del(&ret->list);
6052
6053 device->ws->reset_syncobj(device->ws, ret->syncobj);
6054 }
6055
6056 ret->value = p;
6057 ret->wait_count = 1;
6058
6059 if (prev) {
6060 list_add(&ret->list, &prev->list);
6061 } else {
6062 list_addtail(&ret->list, &timeline->points);
6063 }
6064 return ret;
6065 }
6066
6067
6068 static VkResult
6069 radv_timeline_wait(struct radv_device *device,
6070 struct radv_timeline *timeline,
6071 uint64_t value,
6072 uint64_t abs_timeout)
6073 {
6074 pthread_mutex_lock(&timeline->mutex);
6075
6076 while(timeline->highest_submitted < value) {
6077 struct timespec abstime;
6078 timespec_from_nsec(&abstime, abs_timeout);
6079
6080 pthread_cond_timedwait(&device->timeline_cond, &timeline->mutex, &abstime);
6081
6082 if (radv_get_current_time() >= abs_timeout && timeline->highest_submitted < value) {
6083 pthread_mutex_unlock(&timeline->mutex);
6084 return VK_TIMEOUT;
6085 }
6086 }
6087
6088 struct radv_timeline_point *point = radv_timeline_find_point_at_least_locked(device, timeline, value);
6089 pthread_mutex_unlock(&timeline->mutex);
6090 if (!point)
6091 return VK_SUCCESS;
6092
6093 bool success = device->ws->wait_syncobj(device->ws, &point->syncobj, 1, true, abs_timeout);
6094
6095 pthread_mutex_lock(&timeline->mutex);
6096 point->wait_count--;
6097 pthread_mutex_unlock(&timeline->mutex);
6098 return success ? VK_SUCCESS : VK_TIMEOUT;
6099 }
6100
6101 static void
6102 radv_timeline_trigger_waiters_locked(struct radv_timeline *timeline,
6103 struct list_head *processing_list)
6104 {
6105 list_for_each_entry_safe(struct radv_timeline_waiter, waiter,
6106 &timeline->waiters, list) {
6107 if (waiter->value > timeline->highest_submitted)
6108 continue;
6109
6110 radv_queue_trigger_submission(waiter->submission, 1, processing_list);
6111 list_del(&waiter->list);
6112 }
6113 }
6114
6115 static
6116 void radv_destroy_semaphore_part(struct radv_device *device,
6117 struct radv_semaphore_part *part)
6118 {
6119 switch(part->kind) {
6120 case RADV_SEMAPHORE_NONE:
6121 break;
6122 case RADV_SEMAPHORE_WINSYS:
6123 device->ws->destroy_sem(part->ws_sem);
6124 break;
6125 case RADV_SEMAPHORE_TIMELINE:
6126 radv_destroy_timeline(device, &part->timeline);
6127 break;
6128 case RADV_SEMAPHORE_SYNCOBJ:
6129 case RADV_SEMAPHORE_TIMELINE_SYNCOBJ:
6130 device->ws->destroy_syncobj(device->ws, part->syncobj);
6131 break;
6132 }
6133 part->kind = RADV_SEMAPHORE_NONE;
6134 }
6135
6136 static VkSemaphoreTypeKHR
6137 radv_get_semaphore_type(const void *pNext, uint64_t *initial_value)
6138 {
6139 const VkSemaphoreTypeCreateInfo *type_info =
6140 vk_find_struct_const(pNext, SEMAPHORE_TYPE_CREATE_INFO);
6141
6142 if (!type_info)
6143 return VK_SEMAPHORE_TYPE_BINARY;
6144
6145 if (initial_value)
6146 *initial_value = type_info->initialValue;
6147 return type_info->semaphoreType;
6148 }
6149
6150 static void
6151 radv_destroy_semaphore(struct radv_device *device,
6152 const VkAllocationCallbacks *pAllocator,
6153 struct radv_semaphore *sem)
6154 {
6155 radv_destroy_semaphore_part(device, &sem->temporary);
6156 radv_destroy_semaphore_part(device, &sem->permanent);
6157 vk_object_base_finish(&sem->base);
6158 vk_free2(&device->vk.alloc, pAllocator, sem);
6159 }
6160
6161 VkResult radv_CreateSemaphore(
6162 VkDevice _device,
6163 const VkSemaphoreCreateInfo* pCreateInfo,
6164 const VkAllocationCallbacks* pAllocator,
6165 VkSemaphore* pSemaphore)
6166 {
6167 RADV_FROM_HANDLE(radv_device, device, _device);
6168 const VkExportSemaphoreCreateInfo *export =
6169 vk_find_struct_const(pCreateInfo->pNext, EXPORT_SEMAPHORE_CREATE_INFO);
6170 VkExternalSemaphoreHandleTypeFlags handleTypes =
6171 export ? export->handleTypes : 0;
6172 uint64_t initial_value = 0;
6173 VkSemaphoreTypeKHR type = radv_get_semaphore_type(pCreateInfo->pNext, &initial_value);
6174
6175 struct radv_semaphore *sem = vk_alloc2(&device->vk.alloc, pAllocator,
6176 sizeof(*sem), 8,
6177 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6178 if (!sem)
6179 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6180
6181 vk_object_base_init(&device->vk, &sem->base,
6182 VK_OBJECT_TYPE_SEMAPHORE);
6183
6184 sem->temporary.kind = RADV_SEMAPHORE_NONE;
6185 sem->permanent.kind = RADV_SEMAPHORE_NONE;
6186
6187 if (type == VK_SEMAPHORE_TYPE_TIMELINE &&
6188 device->physical_device->rad_info.has_timeline_syncobj) {
6189 int ret = device->ws->create_syncobj(device->ws, false, &sem->permanent.syncobj);
6190 if (ret) {
6191 radv_destroy_semaphore(device, pAllocator, sem);
6192 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6193 }
6194 device->ws->signal_syncobj(device->ws, sem->permanent.syncobj, initial_value);
6195 sem->permanent.timeline_syncobj.max_point = initial_value;
6196 sem->permanent.kind = RADV_SEMAPHORE_TIMELINE_SYNCOBJ;
6197 } else if (type == VK_SEMAPHORE_TYPE_TIMELINE) {
6198 radv_create_timeline(&sem->permanent.timeline, initial_value);
6199 sem->permanent.kind = RADV_SEMAPHORE_TIMELINE;
6200 } else if (device->always_use_syncobj || handleTypes) {
6201 assert (device->physical_device->rad_info.has_syncobj);
6202 int ret = device->ws->create_syncobj(device->ws, false,
6203 &sem->permanent.syncobj);
6204 if (ret) {
6205 radv_destroy_semaphore(device, pAllocator, sem);
6206 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6207 }
6208 sem->permanent.kind = RADV_SEMAPHORE_SYNCOBJ;
6209 } else {
6210 sem->permanent.ws_sem = device->ws->create_sem(device->ws);
6211 if (!sem->permanent.ws_sem) {
6212 radv_destroy_semaphore(device, pAllocator, sem);
6213 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6214 }
6215 sem->permanent.kind = RADV_SEMAPHORE_WINSYS;
6216 }
6217
6218 *pSemaphore = radv_semaphore_to_handle(sem);
6219 return VK_SUCCESS;
6220 }
6221
6222 void radv_DestroySemaphore(
6223 VkDevice _device,
6224 VkSemaphore _semaphore,
6225 const VkAllocationCallbacks* pAllocator)
6226 {
6227 RADV_FROM_HANDLE(radv_device, device, _device);
6228 RADV_FROM_HANDLE(radv_semaphore, sem, _semaphore);
6229 if (!_semaphore)
6230 return;
6231
6232 radv_destroy_semaphore(device, pAllocator, sem);
6233 }
6234
6235 VkResult
6236 radv_GetSemaphoreCounterValue(VkDevice _device,
6237 VkSemaphore _semaphore,
6238 uint64_t* pValue)
6239 {
6240 RADV_FROM_HANDLE(radv_device, device, _device);
6241 RADV_FROM_HANDLE(radv_semaphore, semaphore, _semaphore);
6242
6243 if (radv_device_is_lost(device))
6244 return VK_ERROR_DEVICE_LOST;
6245
6246 struct radv_semaphore_part *part =
6247 semaphore->temporary.kind != RADV_SEMAPHORE_NONE ? &semaphore->temporary : &semaphore->permanent;
6248
6249 switch (part->kind) {
6250 case RADV_SEMAPHORE_TIMELINE: {
6251 pthread_mutex_lock(&part->timeline.mutex);
6252 radv_timeline_gc_locked(device, &part->timeline);
6253 *pValue = part->timeline.highest_signaled;
6254 pthread_mutex_unlock(&part->timeline.mutex);
6255 return VK_SUCCESS;
6256 }
6257 case RADV_SEMAPHORE_TIMELINE_SYNCOBJ: {
6258 return device->ws->query_syncobj(device->ws, part->syncobj, pValue);
6259 }
6260 case RADV_SEMAPHORE_NONE:
6261 case RADV_SEMAPHORE_SYNCOBJ:
6262 case RADV_SEMAPHORE_WINSYS:
6263 unreachable("Invalid semaphore type");
6264 }
6265 unreachable("Unhandled semaphore type");
6266 }
6267
6268
6269 static VkResult
6270 radv_wait_timelines(struct radv_device *device,
6271 const VkSemaphoreWaitInfo* pWaitInfo,
6272 uint64_t abs_timeout)
6273 {
6274 if ((pWaitInfo->flags & VK_SEMAPHORE_WAIT_ANY_BIT_KHR) && pWaitInfo->semaphoreCount > 1) {
6275 for (;;) {
6276 for(uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
6277 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
6278 VkResult result = radv_timeline_wait(device, &semaphore->permanent.timeline, pWaitInfo->pValues[i], 0);
6279
6280 if (result == VK_SUCCESS)
6281 return VK_SUCCESS;
6282 }
6283 if (radv_get_current_time() > abs_timeout)
6284 return VK_TIMEOUT;
6285 }
6286 }
6287
6288 for(uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
6289 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
6290 VkResult result = radv_timeline_wait(device, &semaphore->permanent.timeline, pWaitInfo->pValues[i], abs_timeout);
6291
6292 if (result != VK_SUCCESS)
6293 return result;
6294 }
6295 return VK_SUCCESS;
6296 }
6297 VkResult
6298 radv_WaitSemaphores(VkDevice _device,
6299 const VkSemaphoreWaitInfo* pWaitInfo,
6300 uint64_t timeout)
6301 {
6302 RADV_FROM_HANDLE(radv_device, device, _device);
6303
6304 if (radv_device_is_lost(device))
6305 return VK_ERROR_DEVICE_LOST;
6306
6307 uint64_t abs_timeout = radv_get_absolute_timeout(timeout);
6308
6309 if (radv_semaphore_from_handle(pWaitInfo->pSemaphores[0])->permanent.kind == RADV_SEMAPHORE_TIMELINE)
6310 return radv_wait_timelines(device, pWaitInfo, abs_timeout);
6311
6312 if (pWaitInfo->semaphoreCount > UINT32_MAX / sizeof(uint32_t))
6313 return vk_errorf(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY, "semaphoreCount integer overflow");
6314
6315 bool wait_all = !(pWaitInfo->flags & VK_SEMAPHORE_WAIT_ANY_BIT_KHR);
6316 uint32_t *handles = malloc(sizeof(*handles) * pWaitInfo->semaphoreCount);
6317 if (!handles)
6318 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6319
6320 for (uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
6321 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
6322 handles[i] = semaphore->permanent.syncobj;
6323 }
6324
6325 bool success = device->ws->wait_timeline_syncobj(device->ws, handles, pWaitInfo->pValues,
6326 pWaitInfo->semaphoreCount, wait_all, false,
6327 abs_timeout);
6328 free(handles);
6329 return success ? VK_SUCCESS : VK_TIMEOUT;
6330 }
6331
6332 VkResult
6333 radv_SignalSemaphore(VkDevice _device,
6334 const VkSemaphoreSignalInfo* pSignalInfo)
6335 {
6336 RADV_FROM_HANDLE(radv_device, device, _device);
6337 RADV_FROM_HANDLE(radv_semaphore, semaphore, pSignalInfo->semaphore);
6338
6339 struct radv_semaphore_part *part =
6340 semaphore->temporary.kind != RADV_SEMAPHORE_NONE ? &semaphore->temporary : &semaphore->permanent;
6341
6342 switch(part->kind) {
6343 case RADV_SEMAPHORE_TIMELINE: {
6344 pthread_mutex_lock(&part->timeline.mutex);
6345 radv_timeline_gc_locked(device, &part->timeline);
6346 part->timeline.highest_submitted = MAX2(part->timeline.highest_submitted, pSignalInfo->value);
6347 part->timeline.highest_signaled = MAX2(part->timeline.highest_signaled, pSignalInfo->value);
6348
6349 struct list_head processing_list;
6350 list_inithead(&processing_list);
6351 radv_timeline_trigger_waiters_locked(&part->timeline, &processing_list);
6352 pthread_mutex_unlock(&part->timeline.mutex);
6353
6354 VkResult result = radv_process_submissions(&processing_list);
6355
6356 /* This needs to happen after radv_process_submissions, so
6357 * that any submitted submissions that are now unblocked get
6358 * processed before we wake the application. This way we
6359 * ensure that any binary semaphores that are now unblocked
6360 * are usable by the application. */
6361 pthread_cond_broadcast(&device->timeline_cond);
6362
6363 return result;
6364 }
6365 case RADV_SEMAPHORE_TIMELINE_SYNCOBJ: {
6366 part->timeline_syncobj.max_point = MAX2(part->timeline_syncobj.max_point, pSignalInfo->value);
6367 device->ws->signal_syncobj(device->ws, part->syncobj, pSignalInfo->value);
6368 break;
6369 }
6370 case RADV_SEMAPHORE_NONE:
6371 case RADV_SEMAPHORE_SYNCOBJ:
6372 case RADV_SEMAPHORE_WINSYS:
6373 unreachable("Invalid semaphore type");
6374 }
6375 return VK_SUCCESS;
6376 }
6377
6378 static void radv_destroy_event(struct radv_device *device,
6379 const VkAllocationCallbacks* pAllocator,
6380 struct radv_event *event)
6381 {
6382 if (event->bo)
6383 device->ws->buffer_destroy(event->bo);
6384
6385 vk_object_base_finish(&event->base);
6386 vk_free2(&device->vk.alloc, pAllocator, event);
6387 }
6388
6389 VkResult radv_CreateEvent(
6390 VkDevice _device,
6391 const VkEventCreateInfo* pCreateInfo,
6392 const VkAllocationCallbacks* pAllocator,
6393 VkEvent* pEvent)
6394 {
6395 RADV_FROM_HANDLE(radv_device, device, _device);
6396 struct radv_event *event = vk_alloc2(&device->vk.alloc, pAllocator,
6397 sizeof(*event), 8,
6398 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6399
6400 if (!event)
6401 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6402
6403 vk_object_base_init(&device->vk, &event->base, VK_OBJECT_TYPE_EVENT);
6404
6405 event->bo = device->ws->buffer_create(device->ws, 8, 8,
6406 RADEON_DOMAIN_GTT,
6407 RADEON_FLAG_VA_UNCACHED | RADEON_FLAG_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING,
6408 RADV_BO_PRIORITY_FENCE);
6409 if (!event->bo) {
6410 radv_destroy_event(device, pAllocator, event);
6411 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6412 }
6413
6414 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
6415 if (!event->map) {
6416 radv_destroy_event(device, pAllocator, event);
6417 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6418 }
6419
6420 *pEvent = radv_event_to_handle(event);
6421
6422 return VK_SUCCESS;
6423 }
6424
6425 void radv_DestroyEvent(
6426 VkDevice _device,
6427 VkEvent _event,
6428 const VkAllocationCallbacks* pAllocator)
6429 {
6430 RADV_FROM_HANDLE(radv_device, device, _device);
6431 RADV_FROM_HANDLE(radv_event, event, _event);
6432
6433 if (!event)
6434 return;
6435
6436 radv_destroy_event(device, pAllocator, event);
6437 }
6438
6439 VkResult radv_GetEventStatus(
6440 VkDevice _device,
6441 VkEvent _event)
6442 {
6443 RADV_FROM_HANDLE(radv_device, device, _device);
6444 RADV_FROM_HANDLE(radv_event, event, _event);
6445
6446 if (radv_device_is_lost(device))
6447 return VK_ERROR_DEVICE_LOST;
6448
6449 if (*event->map == 1)
6450 return VK_EVENT_SET;
6451 return VK_EVENT_RESET;
6452 }
6453
6454 VkResult radv_SetEvent(
6455 VkDevice _device,
6456 VkEvent _event)
6457 {
6458 RADV_FROM_HANDLE(radv_event, event, _event);
6459 *event->map = 1;
6460
6461 return VK_SUCCESS;
6462 }
6463
6464 VkResult radv_ResetEvent(
6465 VkDevice _device,
6466 VkEvent _event)
6467 {
6468 RADV_FROM_HANDLE(radv_event, event, _event);
6469 *event->map = 0;
6470
6471 return VK_SUCCESS;
6472 }
6473
6474 static void
6475 radv_destroy_buffer(struct radv_device *device,
6476 const VkAllocationCallbacks *pAllocator,
6477 struct radv_buffer *buffer)
6478 {
6479 if ((buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) && buffer->bo)
6480 device->ws->buffer_destroy(buffer->bo);
6481
6482 vk_object_base_finish(&buffer->base);
6483 vk_free2(&device->vk.alloc, pAllocator, buffer);
6484 }
6485
6486 VkResult radv_CreateBuffer(
6487 VkDevice _device,
6488 const VkBufferCreateInfo* pCreateInfo,
6489 const VkAllocationCallbacks* pAllocator,
6490 VkBuffer* pBuffer)
6491 {
6492 RADV_FROM_HANDLE(radv_device, device, _device);
6493 struct radv_buffer *buffer;
6494
6495 if (pCreateInfo->size > RADV_MAX_MEMORY_ALLOCATION_SIZE)
6496 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
6497
6498 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
6499
6500 buffer = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*buffer), 8,
6501 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6502 if (buffer == NULL)
6503 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6504
6505 vk_object_base_init(&device->vk, &buffer->base, VK_OBJECT_TYPE_BUFFER);
6506
6507 buffer->size = pCreateInfo->size;
6508 buffer->usage = pCreateInfo->usage;
6509 buffer->bo = NULL;
6510 buffer->offset = 0;
6511 buffer->flags = pCreateInfo->flags;
6512
6513 buffer->shareable = vk_find_struct_const(pCreateInfo->pNext,
6514 EXTERNAL_MEMORY_BUFFER_CREATE_INFO) != NULL;
6515
6516 if (pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) {
6517 buffer->bo = device->ws->buffer_create(device->ws,
6518 align64(buffer->size, 4096),
6519 4096, 0, RADEON_FLAG_VIRTUAL,
6520 RADV_BO_PRIORITY_VIRTUAL);
6521 if (!buffer->bo) {
6522 radv_destroy_buffer(device, pAllocator, buffer);
6523 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6524 }
6525 }
6526
6527 *pBuffer = radv_buffer_to_handle(buffer);
6528
6529 return VK_SUCCESS;
6530 }
6531
6532 void radv_DestroyBuffer(
6533 VkDevice _device,
6534 VkBuffer _buffer,
6535 const VkAllocationCallbacks* pAllocator)
6536 {
6537 RADV_FROM_HANDLE(radv_device, device, _device);
6538 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
6539
6540 if (!buffer)
6541 return;
6542
6543 radv_destroy_buffer(device, pAllocator, buffer);
6544 }
6545
6546 VkDeviceAddress radv_GetBufferDeviceAddress(
6547 VkDevice device,
6548 const VkBufferDeviceAddressInfo* pInfo)
6549 {
6550 RADV_FROM_HANDLE(radv_buffer, buffer, pInfo->buffer);
6551 return radv_buffer_get_va(buffer->bo) + buffer->offset;
6552 }
6553
6554
6555 uint64_t radv_GetBufferOpaqueCaptureAddress(VkDevice device,
6556 const VkBufferDeviceAddressInfo* pInfo)
6557 {
6558 return 0;
6559 }
6560
6561 uint64_t radv_GetDeviceMemoryOpaqueCaptureAddress(VkDevice device,
6562 const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo)
6563 {
6564 return 0;
6565 }
6566
6567 static inline unsigned
6568 si_tile_mode_index(const struct radv_image_plane *plane, unsigned level, bool stencil)
6569 {
6570 if (stencil)
6571 return plane->surface.u.legacy.stencil_tiling_index[level];
6572 else
6573 return plane->surface.u.legacy.tiling_index[level];
6574 }
6575
6576 static uint32_t radv_surface_max_layer_count(struct radv_image_view *iview)
6577 {
6578 return iview->type == VK_IMAGE_VIEW_TYPE_3D ? iview->extent.depth : (iview->base_layer + iview->layer_count);
6579 }
6580
6581 static uint32_t
6582 radv_init_dcc_control_reg(struct radv_device *device,
6583 struct radv_image_view *iview)
6584 {
6585 unsigned max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_256B;
6586 unsigned min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_32B;
6587 unsigned max_compressed_block_size;
6588 unsigned independent_128b_blocks;
6589 unsigned independent_64b_blocks;
6590
6591 if (!radv_dcc_enabled(iview->image, iview->base_mip))
6592 return 0;
6593
6594 if (!device->physical_device->rad_info.has_dedicated_vram) {
6595 /* amdvlk: [min-compressed-block-size] should be set to 32 for
6596 * dGPU and 64 for APU because all of our APUs to date use
6597 * DIMMs which have a request granularity size of 64B while all
6598 * other chips have a 32B request size.
6599 */
6600 min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_64B;
6601 }
6602
6603 if (device->physical_device->rad_info.chip_class >= GFX10) {
6604 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
6605 independent_64b_blocks = 0;
6606 independent_128b_blocks = 1;
6607 } else {
6608 independent_128b_blocks = 0;
6609
6610 if (iview->image->info.samples > 1) {
6611 if (iview->image->planes[0].surface.bpe == 1)
6612 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
6613 else if (iview->image->planes[0].surface.bpe == 2)
6614 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
6615 }
6616
6617 if (iview->image->usage & (VK_IMAGE_USAGE_SAMPLED_BIT |
6618 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
6619 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) {
6620 /* If this DCC image is potentially going to be used in texture
6621 * fetches, we need some special settings.
6622 */
6623 independent_64b_blocks = 1;
6624 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
6625 } else {
6626 /* MAX_UNCOMPRESSED_BLOCK_SIZE must be >=
6627 * MAX_COMPRESSED_BLOCK_SIZE. Set MAX_COMPRESSED_BLOCK_SIZE as
6628 * big as possible for better compression state.
6629 */
6630 independent_64b_blocks = 0;
6631 max_compressed_block_size = max_uncompressed_block_size;
6632 }
6633 }
6634
6635 return S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
6636 S_028C78_MAX_COMPRESSED_BLOCK_SIZE(max_compressed_block_size) |
6637 S_028C78_MIN_COMPRESSED_BLOCK_SIZE(min_compressed_block_size) |
6638 S_028C78_INDEPENDENT_64B_BLOCKS(independent_64b_blocks) |
6639 S_028C78_INDEPENDENT_128B_BLOCKS(independent_128b_blocks);
6640 }
6641
6642 void
6643 radv_initialise_color_surface(struct radv_device *device,
6644 struct radv_color_buffer_info *cb,
6645 struct radv_image_view *iview)
6646 {
6647 const struct vk_format_description *desc;
6648 unsigned ntype, format, swap, endian;
6649 unsigned blend_clamp = 0, blend_bypass = 0;
6650 uint64_t va;
6651 const struct radv_image_plane *plane = &iview->image->planes[iview->plane_id];
6652 const struct radeon_surf *surf = &plane->surface;
6653
6654 desc = vk_format_description(iview->vk_format);
6655
6656 memset(cb, 0, sizeof(*cb));
6657
6658 /* Intensity is implemented as Red, so treat it that way. */
6659 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1);
6660
6661 va = radv_buffer_get_va(iview->bo) + iview->image->offset + plane->offset;
6662
6663 cb->cb_color_base = va >> 8;
6664
6665 if (device->physical_device->rad_info.chip_class >= GFX9) {
6666 if (device->physical_device->rad_info.chip_class >= GFX10) {
6667 cb->cb_color_attrib3 |= S_028EE0_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6668 S_028EE0_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
6669 S_028EE0_CMASK_PIPE_ALIGNED(1) |
6670 S_028EE0_DCC_PIPE_ALIGNED(surf->u.gfx9.dcc.pipe_aligned);
6671 } else {
6672 struct gfx9_surf_meta_flags meta = {
6673 .rb_aligned = 1,
6674 .pipe_aligned = 1,
6675 };
6676
6677 if (surf->dcc_offset)
6678 meta = surf->u.gfx9.dcc;
6679
6680 cb->cb_color_attrib |= S_028C74_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6681 S_028C74_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
6682 S_028C74_RB_ALIGNED(meta.rb_aligned) |
6683 S_028C74_PIPE_ALIGNED(meta.pipe_aligned);
6684 cb->cb_mrt_epitch = S_0287A0_EPITCH(surf->u.gfx9.surf.epitch);
6685 }
6686
6687 cb->cb_color_base += surf->u.gfx9.surf_offset >> 8;
6688 cb->cb_color_base |= surf->tile_swizzle;
6689 } else {
6690 const struct legacy_surf_level *level_info = &surf->u.legacy.level[iview->base_mip];
6691 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
6692
6693 cb->cb_color_base += level_info->offset >> 8;
6694 if (level_info->mode == RADEON_SURF_MODE_2D)
6695 cb->cb_color_base |= surf->tile_swizzle;
6696
6697 pitch_tile_max = level_info->nblk_x / 8 - 1;
6698 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
6699 tile_mode_index = si_tile_mode_index(plane, iview->base_mip, false);
6700
6701 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
6702 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
6703 cb->cb_color_cmask_slice = surf->u.legacy.cmask_slice_tile_max;
6704
6705 cb->cb_color_attrib |= S_028C74_TILE_MODE_INDEX(tile_mode_index);
6706
6707 if (radv_image_has_fmask(iview->image)) {
6708 if (device->physical_device->rad_info.chip_class >= GFX7)
6709 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(surf->u.legacy.fmask.pitch_in_pixels / 8 - 1);
6710 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(surf->u.legacy.fmask.tiling_index);
6711 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(surf->u.legacy.fmask.slice_tile_max);
6712 } else {
6713 /* This must be set for fast clear to work without FMASK. */
6714 if (device->physical_device->rad_info.chip_class >= GFX7)
6715 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
6716 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
6717 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
6718 }
6719 }
6720
6721 /* CMASK variables */
6722 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6723 va += surf->cmask_offset;
6724 cb->cb_color_cmask = va >> 8;
6725
6726 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6727 va += surf->dcc_offset;
6728
6729 if (radv_dcc_enabled(iview->image, iview->base_mip) &&
6730 device->physical_device->rad_info.chip_class <= GFX8)
6731 va += plane->surface.u.legacy.level[iview->base_mip].dcc_offset;
6732
6733 unsigned dcc_tile_swizzle = surf->tile_swizzle;
6734 dcc_tile_swizzle &= (surf->dcc_alignment - 1) >> 8;
6735
6736 cb->cb_dcc_base = va >> 8;
6737 cb->cb_dcc_base |= dcc_tile_swizzle;
6738
6739 /* GFX10 field has the same base shift as the GFX6 field. */
6740 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
6741 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
6742 S_028C6C_SLICE_MAX_GFX10(max_slice);
6743
6744 if (iview->image->info.samples > 1) {
6745 unsigned log_samples = util_logbase2(iview->image->info.samples);
6746
6747 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
6748 S_028C74_NUM_FRAGMENTS(log_samples);
6749 }
6750
6751 if (radv_image_has_fmask(iview->image)) {
6752 va = radv_buffer_get_va(iview->bo) + iview->image->offset + surf->fmask_offset;
6753 cb->cb_color_fmask = va >> 8;
6754 cb->cb_color_fmask |= surf->fmask_tile_swizzle;
6755 } else {
6756 cb->cb_color_fmask = cb->cb_color_base;
6757 }
6758
6759 ntype = radv_translate_color_numformat(iview->vk_format,
6760 desc,
6761 vk_format_get_first_non_void_channel(iview->vk_format));
6762 format = radv_translate_colorformat(iview->vk_format);
6763 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
6764 radv_finishme("Illegal color\n");
6765 swap = radv_translate_colorswap(iview->vk_format, false);
6766 endian = radv_colorformat_endian_swap(format);
6767
6768 /* blend clamp should be set for all NORM/SRGB types */
6769 if (ntype == V_028C70_NUMBER_UNORM ||
6770 ntype == V_028C70_NUMBER_SNORM ||
6771 ntype == V_028C70_NUMBER_SRGB)
6772 blend_clamp = 1;
6773
6774 /* set blend bypass according to docs if SINT/UINT or
6775 8/24 COLOR variants */
6776 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
6777 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
6778 format == V_028C70_COLOR_X24_8_32_FLOAT) {
6779 blend_clamp = 0;
6780 blend_bypass = 1;
6781 }
6782 #if 0
6783 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
6784 (format == V_028C70_COLOR_8 ||
6785 format == V_028C70_COLOR_8_8 ||
6786 format == V_028C70_COLOR_8_8_8_8))
6787 ->color_is_int8 = true;
6788 #endif
6789 cb->cb_color_info = S_028C70_FORMAT(format) |
6790 S_028C70_COMP_SWAP(swap) |
6791 S_028C70_BLEND_CLAMP(blend_clamp) |
6792 S_028C70_BLEND_BYPASS(blend_bypass) |
6793 S_028C70_SIMPLE_FLOAT(1) |
6794 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
6795 ntype != V_028C70_NUMBER_SNORM &&
6796 ntype != V_028C70_NUMBER_SRGB &&
6797 format != V_028C70_COLOR_8_24 &&
6798 format != V_028C70_COLOR_24_8) |
6799 S_028C70_NUMBER_TYPE(ntype) |
6800 S_028C70_ENDIAN(endian);
6801 if (radv_image_has_fmask(iview->image)) {
6802 cb->cb_color_info |= S_028C70_COMPRESSION(1);
6803 if (device->physical_device->rad_info.chip_class == GFX6) {
6804 unsigned fmask_bankh = util_logbase2(surf->u.legacy.fmask.bankh);
6805 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
6806 }
6807
6808 if (radv_image_is_tc_compat_cmask(iview->image)) {
6809 /* Allow the texture block to read FMASK directly
6810 * without decompressing it. This bit must be cleared
6811 * when performing FMASK_DECOMPRESS or DCC_COMPRESS,
6812 * otherwise the operation doesn't happen.
6813 */
6814 cb->cb_color_info |= S_028C70_FMASK_COMPRESS_1FRAG_ONLY(1);
6815
6816 /* Set CMASK into a tiling format that allows the
6817 * texture block to read it.
6818 */
6819 cb->cb_color_info |= S_028C70_CMASK_ADDR_TYPE(2);
6820 }
6821 }
6822
6823 if (radv_image_has_cmask(iview->image) &&
6824 !(device->instance->debug_flags & RADV_DEBUG_NO_FAST_CLEARS))
6825 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
6826
6827 if (radv_dcc_enabled(iview->image, iview->base_mip))
6828 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
6829
6830 cb->cb_dcc_control = radv_init_dcc_control_reg(device, iview);
6831
6832 /* This must be set for fast clear to work without FMASK. */
6833 if (!radv_image_has_fmask(iview->image) &&
6834 device->physical_device->rad_info.chip_class == GFX6) {
6835 unsigned bankh = util_logbase2(surf->u.legacy.bankh);
6836 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
6837 }
6838
6839 if (device->physical_device->rad_info.chip_class >= GFX9) {
6840 const struct vk_format_description *format_desc = vk_format_description(iview->image->vk_format);
6841
6842 unsigned mip0_depth = iview->image->type == VK_IMAGE_TYPE_3D ?
6843 (iview->extent.depth - 1) : (iview->image->info.array_size - 1);
6844 unsigned width = iview->extent.width / (iview->plane_id ? format_desc->width_divisor : 1);
6845 unsigned height = iview->extent.height / (iview->plane_id ? format_desc->height_divisor : 1);
6846
6847 if (device->physical_device->rad_info.chip_class >= GFX10) {
6848 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX10(iview->base_mip);
6849
6850 cb->cb_color_attrib3 |= S_028EE0_MIP0_DEPTH(mip0_depth) |
6851 S_028EE0_RESOURCE_TYPE(surf->u.gfx9.resource_type) |
6852 S_028EE0_RESOURCE_LEVEL(1);
6853 } else {
6854 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX9(iview->base_mip);
6855 cb->cb_color_attrib |= S_028C74_MIP0_DEPTH(mip0_depth) |
6856 S_028C74_RESOURCE_TYPE(surf->u.gfx9.resource_type);
6857 }
6858
6859 cb->cb_color_attrib2 = S_028C68_MIP0_WIDTH(width - 1) |
6860 S_028C68_MIP0_HEIGHT(height - 1) |
6861 S_028C68_MAX_MIP(iview->image->info.levels - 1);
6862 }
6863 }
6864
6865 static unsigned
6866 radv_calc_decompress_on_z_planes(struct radv_device *device,
6867 struct radv_image_view *iview)
6868 {
6869 unsigned max_zplanes = 0;
6870
6871 assert(radv_image_is_tc_compat_htile(iview->image));
6872
6873 if (device->physical_device->rad_info.chip_class >= GFX9) {
6874 /* Default value for 32-bit depth surfaces. */
6875 max_zplanes = 4;
6876
6877 if (iview->vk_format == VK_FORMAT_D16_UNORM &&
6878 iview->image->info.samples > 1)
6879 max_zplanes = 2;
6880
6881 max_zplanes = max_zplanes + 1;
6882 } else {
6883 if (iview->vk_format == VK_FORMAT_D16_UNORM) {
6884 /* Do not enable Z plane compression for 16-bit depth
6885 * surfaces because isn't supported on GFX8. Only
6886 * 32-bit depth surfaces are supported by the hardware.
6887 * This allows to maintain shader compatibility and to
6888 * reduce the number of depth decompressions.
6889 */
6890 max_zplanes = 1;
6891 } else {
6892 if (iview->image->info.samples <= 1)
6893 max_zplanes = 5;
6894 else if (iview->image->info.samples <= 4)
6895 max_zplanes = 3;
6896 else
6897 max_zplanes = 2;
6898 }
6899 }
6900
6901 return max_zplanes;
6902 }
6903
6904 void
6905 radv_initialise_ds_surface(struct radv_device *device,
6906 struct radv_ds_buffer_info *ds,
6907 struct radv_image_view *iview)
6908 {
6909 unsigned level = iview->base_mip;
6910 unsigned format, stencil_format;
6911 uint64_t va, s_offs, z_offs;
6912 bool stencil_only = false;
6913 const struct radv_image_plane *plane = &iview->image->planes[0];
6914 const struct radeon_surf *surf = &plane->surface;
6915
6916 assert(vk_format_get_plane_count(iview->image->vk_format) == 1);
6917
6918 memset(ds, 0, sizeof(*ds));
6919 switch (iview->image->vk_format) {
6920 case VK_FORMAT_D24_UNORM_S8_UINT:
6921 case VK_FORMAT_X8_D24_UNORM_PACK32:
6922 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
6923 ds->offset_scale = 2.0f;
6924 break;
6925 case VK_FORMAT_D16_UNORM:
6926 case VK_FORMAT_D16_UNORM_S8_UINT:
6927 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
6928 ds->offset_scale = 4.0f;
6929 break;
6930 case VK_FORMAT_D32_SFLOAT:
6931 case VK_FORMAT_D32_SFLOAT_S8_UINT:
6932 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
6933 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
6934 ds->offset_scale = 1.0f;
6935 break;
6936 case VK_FORMAT_S8_UINT:
6937 stencil_only = true;
6938 break;
6939 default:
6940 break;
6941 }
6942
6943 format = radv_translate_dbformat(iview->image->vk_format);
6944 stencil_format = surf->has_stencil ?
6945 V_028044_STENCIL_8 : V_028044_STENCIL_INVALID;
6946
6947 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
6948 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
6949 S_028008_SLICE_MAX(max_slice);
6950 if (device->physical_device->rad_info.chip_class >= GFX10) {
6951 ds->db_depth_view |= S_028008_SLICE_START_HI(iview->base_layer >> 11) |
6952 S_028008_SLICE_MAX_HI(max_slice >> 11);
6953 }
6954
6955 ds->db_htile_data_base = 0;
6956 ds->db_htile_surface = 0;
6957
6958 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6959 s_offs = z_offs = va;
6960
6961 if (device->physical_device->rad_info.chip_class >= GFX9) {
6962 assert(surf->u.gfx9.surf_offset == 0);
6963 s_offs += surf->u.gfx9.stencil_offset;
6964
6965 ds->db_z_info = S_028038_FORMAT(format) |
6966 S_028038_NUM_SAMPLES(util_logbase2(iview->image->info.samples)) |
6967 S_028038_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6968 S_028038_MAXMIP(iview->image->info.levels - 1) |
6969 S_028038_ZRANGE_PRECISION(1);
6970 ds->db_stencil_info = S_02803C_FORMAT(stencil_format) |
6971 S_02803C_SW_MODE(surf->u.gfx9.stencil.swizzle_mode);
6972
6973 if (device->physical_device->rad_info.chip_class == GFX9) {
6974 ds->db_z_info2 = S_028068_EPITCH(surf->u.gfx9.surf.epitch);
6975 ds->db_stencil_info2 = S_02806C_EPITCH(surf->u.gfx9.stencil.epitch);
6976 }
6977
6978 ds->db_depth_view |= S_028008_MIPID(level);
6979 ds->db_depth_size = S_02801C_X_MAX(iview->image->info.width - 1) |
6980 S_02801C_Y_MAX(iview->image->info.height - 1);
6981
6982 if (radv_htile_enabled(iview->image, level)) {
6983 ds->db_z_info |= S_028038_TILE_SURFACE_ENABLE(1);
6984
6985 if (radv_image_is_tc_compat_htile(iview->image)) {
6986 unsigned max_zplanes =
6987 radv_calc_decompress_on_z_planes(device, iview);
6988
6989 ds->db_z_info |= S_028038_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
6990
6991 if (device->physical_device->rad_info.chip_class >= GFX10) {
6992 ds->db_z_info |= S_028040_ITERATE_FLUSH(1);
6993 ds->db_stencil_info |= S_028044_ITERATE_FLUSH(1);
6994 } else {
6995 ds->db_z_info |= S_028038_ITERATE_FLUSH(1);
6996 ds->db_stencil_info |= S_02803C_ITERATE_FLUSH(1);
6997 }
6998 }
6999
7000 if (!surf->has_stencil)
7001 /* Use all of the htile_buffer for depth if there's no stencil. */
7002 ds->db_stencil_info |= S_02803C_TILE_STENCIL_DISABLE(1);
7003 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
7004 surf->htile_offset;
7005 ds->db_htile_data_base = va >> 8;
7006 ds->db_htile_surface = S_028ABC_FULL_CACHE(1) |
7007 S_028ABC_PIPE_ALIGNED(1);
7008
7009 if (device->physical_device->rad_info.chip_class == GFX9) {
7010 ds->db_htile_surface |= S_028ABC_RB_ALIGNED(1);
7011 }
7012 }
7013 } else {
7014 const struct legacy_surf_level *level_info = &surf->u.legacy.level[level];
7015
7016 if (stencil_only)
7017 level_info = &surf->u.legacy.stencil_level[level];
7018
7019 z_offs += surf->u.legacy.level[level].offset;
7020 s_offs += surf->u.legacy.stencil_level[level].offset;
7021
7022 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(!radv_image_is_tc_compat_htile(iview->image));
7023 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
7024 ds->db_stencil_info = S_028044_FORMAT(stencil_format);
7025
7026 if (iview->image->info.samples > 1)
7027 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->info.samples));
7028
7029 if (device->physical_device->rad_info.chip_class >= GFX7) {
7030 struct radeon_info *info = &device->physical_device->rad_info;
7031 unsigned tiling_index = surf->u.legacy.tiling_index[level];
7032 unsigned stencil_index = surf->u.legacy.stencil_tiling_index[level];
7033 unsigned macro_index = surf->u.legacy.macro_tile_index;
7034 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
7035 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
7036 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
7037
7038 if (stencil_only)
7039 tile_mode = stencil_tile_mode;
7040
7041 ds->db_depth_info |=
7042 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
7043 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
7044 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
7045 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
7046 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
7047 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
7048 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
7049 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
7050 } else {
7051 unsigned tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, false);
7052 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
7053 tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, true);
7054 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
7055 if (stencil_only)
7056 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
7057 }
7058
7059 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
7060 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
7061 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
7062
7063 if (radv_htile_enabled(iview->image, level)) {
7064 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1);
7065
7066 if (!surf->has_stencil &&
7067 !radv_image_is_tc_compat_htile(iview->image))
7068 /* Use all of the htile_buffer for depth if there's no stencil. */
7069 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
7070
7071 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
7072 surf->htile_offset;
7073 ds->db_htile_data_base = va >> 8;
7074 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
7075
7076 if (radv_image_is_tc_compat_htile(iview->image)) {
7077 unsigned max_zplanes =
7078 radv_calc_decompress_on_z_planes(device, iview);
7079
7080 ds->db_htile_surface |= S_028ABC_TC_COMPATIBLE(1);
7081 ds->db_z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
7082 }
7083 }
7084 }
7085
7086 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
7087 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
7088 }
7089
7090 VkResult radv_CreateFramebuffer(
7091 VkDevice _device,
7092 const VkFramebufferCreateInfo* pCreateInfo,
7093 const VkAllocationCallbacks* pAllocator,
7094 VkFramebuffer* pFramebuffer)
7095 {
7096 RADV_FROM_HANDLE(radv_device, device, _device);
7097 struct radv_framebuffer *framebuffer;
7098 const VkFramebufferAttachmentsCreateInfo *imageless_create_info =
7099 vk_find_struct_const(pCreateInfo->pNext,
7100 FRAMEBUFFER_ATTACHMENTS_CREATE_INFO);
7101
7102 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
7103
7104 size_t size = sizeof(*framebuffer);
7105 if (!imageless_create_info)
7106 size += sizeof(struct radv_image_view*) * pCreateInfo->attachmentCount;
7107 framebuffer = vk_alloc2(&device->vk.alloc, pAllocator, size, 8,
7108 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
7109 if (framebuffer == NULL)
7110 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
7111
7112 vk_object_base_init(&device->vk, &framebuffer->base,
7113 VK_OBJECT_TYPE_FRAMEBUFFER);
7114
7115 framebuffer->attachment_count = pCreateInfo->attachmentCount;
7116 framebuffer->width = pCreateInfo->width;
7117 framebuffer->height = pCreateInfo->height;
7118 framebuffer->layers = pCreateInfo->layers;
7119 if (imageless_create_info) {
7120 for (unsigned i = 0; i < imageless_create_info->attachmentImageInfoCount; ++i) {
7121 const VkFramebufferAttachmentImageInfo *attachment =
7122 imageless_create_info->pAttachmentImageInfos + i;
7123 framebuffer->width = MIN2(framebuffer->width, attachment->width);
7124 framebuffer->height = MIN2(framebuffer->height, attachment->height);
7125 framebuffer->layers = MIN2(framebuffer->layers, attachment->layerCount);
7126 }
7127 } else {
7128 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
7129 VkImageView _iview = pCreateInfo->pAttachments[i];
7130 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
7131 framebuffer->attachments[i] = iview;
7132 framebuffer->width = MIN2(framebuffer->width, iview->extent.width);
7133 framebuffer->height = MIN2(framebuffer->height, iview->extent.height);
7134 framebuffer->layers = MIN2(framebuffer->layers, radv_surface_max_layer_count(iview));
7135 }
7136 }
7137
7138 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
7139 return VK_SUCCESS;
7140 }
7141
7142 void radv_DestroyFramebuffer(
7143 VkDevice _device,
7144 VkFramebuffer _fb,
7145 const VkAllocationCallbacks* pAllocator)
7146 {
7147 RADV_FROM_HANDLE(radv_device, device, _device);
7148 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
7149
7150 if (!fb)
7151 return;
7152 vk_object_base_finish(&fb->base);
7153 vk_free2(&device->vk.alloc, pAllocator, fb);
7154 }
7155
7156 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
7157 {
7158 switch (address_mode) {
7159 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
7160 return V_008F30_SQ_TEX_WRAP;
7161 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
7162 return V_008F30_SQ_TEX_MIRROR;
7163 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
7164 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
7165 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
7166 return V_008F30_SQ_TEX_CLAMP_BORDER;
7167 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
7168 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
7169 default:
7170 unreachable("illegal tex wrap mode");
7171 break;
7172 }
7173 }
7174
7175 static unsigned
7176 radv_tex_compare(VkCompareOp op)
7177 {
7178 switch (op) {
7179 case VK_COMPARE_OP_NEVER:
7180 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
7181 case VK_COMPARE_OP_LESS:
7182 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
7183 case VK_COMPARE_OP_EQUAL:
7184 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
7185 case VK_COMPARE_OP_LESS_OR_EQUAL:
7186 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
7187 case VK_COMPARE_OP_GREATER:
7188 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
7189 case VK_COMPARE_OP_NOT_EQUAL:
7190 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
7191 case VK_COMPARE_OP_GREATER_OR_EQUAL:
7192 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
7193 case VK_COMPARE_OP_ALWAYS:
7194 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
7195 default:
7196 unreachable("illegal compare mode");
7197 break;
7198 }
7199 }
7200
7201 static unsigned
7202 radv_tex_filter(VkFilter filter, unsigned max_ansio)
7203 {
7204 switch (filter) {
7205 case VK_FILTER_NEAREST:
7206 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
7207 V_008F38_SQ_TEX_XY_FILTER_POINT);
7208 case VK_FILTER_LINEAR:
7209 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
7210 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
7211 case VK_FILTER_CUBIC_IMG:
7212 default:
7213 fprintf(stderr, "illegal texture filter");
7214 return 0;
7215 }
7216 }
7217
7218 static unsigned
7219 radv_tex_mipfilter(VkSamplerMipmapMode mode)
7220 {
7221 switch (mode) {
7222 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
7223 return V_008F38_SQ_TEX_Z_FILTER_POINT;
7224 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
7225 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
7226 default:
7227 return V_008F38_SQ_TEX_Z_FILTER_NONE;
7228 }
7229 }
7230
7231 static unsigned
7232 radv_tex_bordercolor(VkBorderColor bcolor)
7233 {
7234 switch (bcolor) {
7235 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
7236 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
7237 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
7238 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
7239 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
7240 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
7241 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
7242 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
7243 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
7244 case VK_BORDER_COLOR_FLOAT_CUSTOM_EXT:
7245 case VK_BORDER_COLOR_INT_CUSTOM_EXT:
7246 return V_008F3C_SQ_TEX_BORDER_COLOR_REGISTER;
7247 default:
7248 break;
7249 }
7250 return 0;
7251 }
7252
7253 static unsigned
7254 radv_tex_aniso_filter(unsigned filter)
7255 {
7256 if (filter < 2)
7257 return 0;
7258 if (filter < 4)
7259 return 1;
7260 if (filter < 8)
7261 return 2;
7262 if (filter < 16)
7263 return 3;
7264 return 4;
7265 }
7266
7267 static unsigned
7268 radv_tex_filter_mode(VkSamplerReductionMode mode)
7269 {
7270 switch (mode) {
7271 case VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT:
7272 return V_008F30_SQ_IMG_FILTER_MODE_BLEND;
7273 case VK_SAMPLER_REDUCTION_MODE_MIN_EXT:
7274 return V_008F30_SQ_IMG_FILTER_MODE_MIN;
7275 case VK_SAMPLER_REDUCTION_MODE_MAX_EXT:
7276 return V_008F30_SQ_IMG_FILTER_MODE_MAX;
7277 default:
7278 break;
7279 }
7280 return 0;
7281 }
7282
7283 static uint32_t
7284 radv_get_max_anisotropy(struct radv_device *device,
7285 const VkSamplerCreateInfo *pCreateInfo)
7286 {
7287 if (device->force_aniso >= 0)
7288 return device->force_aniso;
7289
7290 if (pCreateInfo->anisotropyEnable &&
7291 pCreateInfo->maxAnisotropy > 1.0f)
7292 return (uint32_t)pCreateInfo->maxAnisotropy;
7293
7294 return 0;
7295 }
7296
7297 static inline int S_FIXED(float value, unsigned frac_bits)
7298 {
7299 return value * (1 << frac_bits);
7300 }
7301
7302 static uint32_t radv_register_border_color(struct radv_device *device,
7303 VkClearColorValue value)
7304 {
7305 uint32_t slot;
7306
7307 pthread_mutex_lock(&device->border_color_data.mutex);
7308
7309 for (slot = 0; slot < RADV_BORDER_COLOR_COUNT; slot++) {
7310 if (!device->border_color_data.used[slot]) {
7311 /* Copy to the GPU wrt endian-ness. */
7312 util_memcpy_cpu_to_le32(&device->border_color_data.colors_gpu_ptr[slot],
7313 &value,
7314 sizeof(VkClearColorValue));
7315
7316 device->border_color_data.used[slot] = true;
7317 break;
7318 }
7319 }
7320
7321 pthread_mutex_unlock(&device->border_color_data.mutex);
7322
7323 return slot;
7324 }
7325
7326 static void radv_unregister_border_color(struct radv_device *device,
7327 uint32_t slot)
7328 {
7329 pthread_mutex_lock(&device->border_color_data.mutex);
7330
7331 device->border_color_data.used[slot] = false;
7332
7333 pthread_mutex_unlock(&device->border_color_data.mutex);
7334 }
7335
7336 static void
7337 radv_init_sampler(struct radv_device *device,
7338 struct radv_sampler *sampler,
7339 const VkSamplerCreateInfo *pCreateInfo)
7340 {
7341 uint32_t max_aniso = radv_get_max_anisotropy(device, pCreateInfo);
7342 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
7343 bool compat_mode = device->physical_device->rad_info.chip_class == GFX8 ||
7344 device->physical_device->rad_info.chip_class == GFX9;
7345 unsigned filter_mode = V_008F30_SQ_IMG_FILTER_MODE_BLEND;
7346 unsigned depth_compare_func = V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
7347 bool trunc_coord = pCreateInfo->minFilter == VK_FILTER_NEAREST && pCreateInfo->magFilter == VK_FILTER_NEAREST;
7348 bool uses_border_color = pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
7349 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
7350 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
7351 VkBorderColor border_color = uses_border_color ? pCreateInfo->borderColor : VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
7352 uint32_t border_color_ptr;
7353
7354 const struct VkSamplerReductionModeCreateInfo *sampler_reduction =
7355 vk_find_struct_const(pCreateInfo->pNext,
7356 SAMPLER_REDUCTION_MODE_CREATE_INFO);
7357 if (sampler_reduction)
7358 filter_mode = radv_tex_filter_mode(sampler_reduction->reductionMode);
7359
7360 if (pCreateInfo->compareEnable)
7361 depth_compare_func = radv_tex_compare(pCreateInfo->compareOp);
7362
7363 sampler->border_color_slot = RADV_BORDER_COLOR_COUNT;
7364
7365 if (border_color == VK_BORDER_COLOR_FLOAT_CUSTOM_EXT || border_color == VK_BORDER_COLOR_INT_CUSTOM_EXT) {
7366 const VkSamplerCustomBorderColorCreateInfoEXT *custom_border_color =
7367 vk_find_struct_const(pCreateInfo->pNext,
7368 SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT);
7369
7370 assert(custom_border_color);
7371
7372 sampler->border_color_slot =
7373 radv_register_border_color(device, custom_border_color->customBorderColor);
7374
7375 /* Did we fail to find a slot? */
7376 if (sampler->border_color_slot == RADV_BORDER_COLOR_COUNT) {
7377 fprintf(stderr, "WARNING: no free border color slots, defaulting to TRANS_BLACK.\n");
7378 border_color = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
7379 }
7380 }
7381
7382 /* If we don't have a custom color, set the ptr to 0 */
7383 border_color_ptr = sampler->border_color_slot != RADV_BORDER_COLOR_COUNT
7384 ? sampler->border_color_slot
7385 : 0;
7386
7387 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
7388 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
7389 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
7390 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
7391 S_008F30_DEPTH_COMPARE_FUNC(depth_compare_func) |
7392 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
7393 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
7394 S_008F30_ANISO_BIAS(max_aniso_ratio) |
7395 S_008F30_DISABLE_CUBE_WRAP(0) |
7396 S_008F30_COMPAT_MODE(compat_mode) |
7397 S_008F30_FILTER_MODE(filter_mode) |
7398 S_008F30_TRUNC_COORD(trunc_coord));
7399 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
7400 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
7401 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
7402 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
7403 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
7404 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
7405 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
7406 S_008F38_MIP_POINT_PRECLAMP(0));
7407 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(border_color_ptr) |
7408 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(border_color)));
7409
7410 if (device->physical_device->rad_info.chip_class >= GFX10) {
7411 sampler->state[2] |= S_008F38_ANISO_OVERRIDE_GFX10(1);
7412 } else {
7413 sampler->state[2] |=
7414 S_008F38_DISABLE_LSB_CEIL(device->physical_device->rad_info.chip_class <= GFX8) |
7415 S_008F38_FILTER_PREC_FIX(1) |
7416 S_008F38_ANISO_OVERRIDE_GFX6(device->physical_device->rad_info.chip_class >= GFX8);
7417 }
7418 }
7419
7420 VkResult radv_CreateSampler(
7421 VkDevice _device,
7422 const VkSamplerCreateInfo* pCreateInfo,
7423 const VkAllocationCallbacks* pAllocator,
7424 VkSampler* pSampler)
7425 {
7426 RADV_FROM_HANDLE(radv_device, device, _device);
7427 struct radv_sampler *sampler;
7428
7429 const struct VkSamplerYcbcrConversionInfo *ycbcr_conversion =
7430 vk_find_struct_const(pCreateInfo->pNext,
7431 SAMPLER_YCBCR_CONVERSION_INFO);
7432
7433 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
7434
7435 sampler = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*sampler), 8,
7436 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
7437 if (!sampler)
7438 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
7439
7440 vk_object_base_init(&device->vk, &sampler->base,
7441 VK_OBJECT_TYPE_SAMPLER);
7442
7443 radv_init_sampler(device, sampler, pCreateInfo);
7444
7445 sampler->ycbcr_sampler = ycbcr_conversion ? radv_sampler_ycbcr_conversion_from_handle(ycbcr_conversion->conversion): NULL;
7446 *pSampler = radv_sampler_to_handle(sampler);
7447
7448 return VK_SUCCESS;
7449 }
7450
7451 void radv_DestroySampler(
7452 VkDevice _device,
7453 VkSampler _sampler,
7454 const VkAllocationCallbacks* pAllocator)
7455 {
7456 RADV_FROM_HANDLE(radv_device, device, _device);
7457 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
7458
7459 if (!sampler)
7460 return;
7461
7462 if (sampler->border_color_slot != RADV_BORDER_COLOR_COUNT)
7463 radv_unregister_border_color(device, sampler->border_color_slot);
7464
7465 vk_object_base_finish(&sampler->base);
7466 vk_free2(&device->vk.alloc, pAllocator, sampler);
7467 }
7468
7469 /* vk_icd.h does not declare this function, so we declare it here to
7470 * suppress Wmissing-prototypes.
7471 */
7472 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
7473 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
7474
7475 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
7476 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
7477 {
7478 /* For the full details on loader interface versioning, see
7479 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
7480 * What follows is a condensed summary, to help you navigate the large and
7481 * confusing official doc.
7482 *
7483 * - Loader interface v0 is incompatible with later versions. We don't
7484 * support it.
7485 *
7486 * - In loader interface v1:
7487 * - The first ICD entrypoint called by the loader is
7488 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
7489 * entrypoint.
7490 * - The ICD must statically expose no other Vulkan symbol unless it is
7491 * linked with -Bsymbolic.
7492 * - Each dispatchable Vulkan handle created by the ICD must be
7493 * a pointer to a struct whose first member is VK_LOADER_DATA. The
7494 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
7495 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
7496 * vkDestroySurfaceKHR(). The ICD must be capable of working with
7497 * such loader-managed surfaces.
7498 *
7499 * - Loader interface v2 differs from v1 in:
7500 * - The first ICD entrypoint called by the loader is
7501 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
7502 * statically expose this entrypoint.
7503 *
7504 * - Loader interface v3 differs from v2 in:
7505 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
7506 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
7507 * because the loader no longer does so.
7508 */
7509 *pSupportedVersion = MIN2(*pSupportedVersion, 4u);
7510 return VK_SUCCESS;
7511 }
7512
7513 VkResult radv_GetMemoryFdKHR(VkDevice _device,
7514 const VkMemoryGetFdInfoKHR *pGetFdInfo,
7515 int *pFD)
7516 {
7517 RADV_FROM_HANDLE(radv_device, device, _device);
7518 RADV_FROM_HANDLE(radv_device_memory, memory, pGetFdInfo->memory);
7519
7520 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
7521
7522 /* At the moment, we support only the below handle types. */
7523 assert(pGetFdInfo->handleType ==
7524 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
7525 pGetFdInfo->handleType ==
7526 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
7527
7528 bool ret = radv_get_memory_fd(device, memory, pFD);
7529 if (ret == false)
7530 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
7531 return VK_SUCCESS;
7532 }
7533
7534 static uint32_t radv_compute_valid_memory_types_attempt(struct radv_physical_device *dev,
7535 enum radeon_bo_domain domains,
7536 enum radeon_bo_flag flags,
7537 enum radeon_bo_flag ignore_flags)
7538 {
7539 /* Don't count GTT/CPU as relevant:
7540 *
7541 * - We're not fully consistent between the two.
7542 * - Sometimes VRAM gets VRAM|GTT.
7543 */
7544 const enum radeon_bo_domain relevant_domains = RADEON_DOMAIN_VRAM |
7545 RADEON_DOMAIN_GDS |
7546 RADEON_DOMAIN_OA;
7547 uint32_t bits = 0;
7548 for (unsigned i = 0; i < dev->memory_properties.memoryTypeCount; ++i) {
7549 if ((domains & relevant_domains) != (dev->memory_domains[i] & relevant_domains))
7550 continue;
7551
7552 if ((flags & ~ignore_flags) != (dev->memory_flags[i] & ~ignore_flags))
7553 continue;
7554
7555 bits |= 1u << i;
7556 }
7557
7558 return bits;
7559 }
7560
7561 static uint32_t radv_compute_valid_memory_types(struct radv_physical_device *dev,
7562 enum radeon_bo_domain domains,
7563 enum radeon_bo_flag flags)
7564 {
7565 enum radeon_bo_flag ignore_flags = ~(RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_GTT_WC);
7566 uint32_t bits = radv_compute_valid_memory_types_attempt(dev, domains, flags, ignore_flags);
7567
7568 if (!bits) {
7569 ignore_flags |= RADEON_FLAG_NO_CPU_ACCESS;
7570 bits = radv_compute_valid_memory_types_attempt(dev, domains, flags, ignore_flags);
7571 }
7572
7573 return bits;
7574 }
7575 VkResult radv_GetMemoryFdPropertiesKHR(VkDevice _device,
7576 VkExternalMemoryHandleTypeFlagBits handleType,
7577 int fd,
7578 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
7579 {
7580 RADV_FROM_HANDLE(radv_device, device, _device);
7581
7582 switch (handleType) {
7583 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT: {
7584 enum radeon_bo_domain domains;
7585 enum radeon_bo_flag flags;
7586 if (!device->ws->buffer_get_flags_from_fd(device->ws, fd, &domains, &flags))
7587 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7588
7589 pMemoryFdProperties->memoryTypeBits = radv_compute_valid_memory_types(device->physical_device, domains, flags);
7590 return VK_SUCCESS;
7591 }
7592 default:
7593 /* The valid usage section for this function says:
7594 *
7595 * "handleType must not be one of the handle types defined as
7596 * opaque."
7597 *
7598 * So opaque handle types fall into the default "unsupported" case.
7599 */
7600 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7601 }
7602 }
7603
7604 static VkResult radv_import_opaque_fd(struct radv_device *device,
7605 int fd,
7606 uint32_t *syncobj)
7607 {
7608 uint32_t syncobj_handle = 0;
7609 int ret = device->ws->import_syncobj(device->ws, fd, &syncobj_handle);
7610 if (ret != 0)
7611 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7612
7613 if (*syncobj)
7614 device->ws->destroy_syncobj(device->ws, *syncobj);
7615
7616 *syncobj = syncobj_handle;
7617 close(fd);
7618
7619 return VK_SUCCESS;
7620 }
7621
7622 static VkResult radv_import_sync_fd(struct radv_device *device,
7623 int fd,
7624 uint32_t *syncobj)
7625 {
7626 /* If we create a syncobj we do it locally so that if we have an error, we don't
7627 * leave a syncobj in an undetermined state in the fence. */
7628 uint32_t syncobj_handle = *syncobj;
7629 if (!syncobj_handle) {
7630 bool create_signaled = fd == -1 ? true : false;
7631
7632 int ret = device->ws->create_syncobj(device->ws, create_signaled,
7633 &syncobj_handle);
7634 if (ret) {
7635 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
7636 }
7637 } else {
7638 if (fd == -1)
7639 device->ws->signal_syncobj(device->ws, syncobj_handle, 0);
7640 }
7641
7642 if (fd != -1) {
7643 int ret = device->ws->import_syncobj_from_sync_file(device->ws, syncobj_handle, fd);
7644 if (ret)
7645 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7646 close(fd);
7647 }
7648
7649 *syncobj = syncobj_handle;
7650
7651 return VK_SUCCESS;
7652 }
7653
7654 VkResult radv_ImportSemaphoreFdKHR(VkDevice _device,
7655 const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo)
7656 {
7657 RADV_FROM_HANDLE(radv_device, device, _device);
7658 RADV_FROM_HANDLE(radv_semaphore, sem, pImportSemaphoreFdInfo->semaphore);
7659 VkResult result;
7660 struct radv_semaphore_part *dst = NULL;
7661 bool timeline = sem->permanent.kind == RADV_SEMAPHORE_TIMELINE_SYNCOBJ;
7662
7663 if (pImportSemaphoreFdInfo->flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT) {
7664 assert(!timeline);
7665 dst = &sem->temporary;
7666 } else {
7667 dst = &sem->permanent;
7668 }
7669
7670 uint32_t syncobj = (dst->kind == RADV_SEMAPHORE_SYNCOBJ ||
7671 dst->kind == RADV_SEMAPHORE_TIMELINE_SYNCOBJ) ? dst->syncobj : 0;
7672
7673 switch(pImportSemaphoreFdInfo->handleType) {
7674 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
7675 result = radv_import_opaque_fd(device, pImportSemaphoreFdInfo->fd, &syncobj);
7676 break;
7677 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
7678 assert(!timeline);
7679 result = radv_import_sync_fd(device, pImportSemaphoreFdInfo->fd, &syncobj);
7680 break;
7681 default:
7682 unreachable("Unhandled semaphore handle type");
7683 }
7684
7685 if (result == VK_SUCCESS) {
7686 dst->syncobj = syncobj;
7687 dst->kind = RADV_SEMAPHORE_SYNCOBJ;
7688 if (timeline) {
7689 dst->kind = RADV_SEMAPHORE_TIMELINE_SYNCOBJ;
7690 dst->timeline_syncobj.max_point = 0;
7691 }
7692 }
7693
7694 return result;
7695 }
7696
7697 VkResult radv_GetSemaphoreFdKHR(VkDevice _device,
7698 const VkSemaphoreGetFdInfoKHR *pGetFdInfo,
7699 int *pFd)
7700 {
7701 RADV_FROM_HANDLE(radv_device, device, _device);
7702 RADV_FROM_HANDLE(radv_semaphore, sem, pGetFdInfo->semaphore);
7703 int ret;
7704 uint32_t syncobj_handle;
7705
7706 if (sem->temporary.kind != RADV_SEMAPHORE_NONE) {
7707 assert(sem->temporary.kind == RADV_SEMAPHORE_SYNCOBJ ||
7708 sem->temporary.kind == RADV_SEMAPHORE_TIMELINE_SYNCOBJ);
7709 syncobj_handle = sem->temporary.syncobj;
7710 } else {
7711 assert(sem->permanent.kind == RADV_SEMAPHORE_SYNCOBJ ||
7712 sem->permanent.kind == RADV_SEMAPHORE_TIMELINE_SYNCOBJ);
7713 syncobj_handle = sem->permanent.syncobj;
7714 }
7715
7716 switch(pGetFdInfo->handleType) {
7717 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
7718 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
7719 if (ret)
7720 return vk_error(device->instance, VK_ERROR_TOO_MANY_OBJECTS);
7721 break;
7722 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
7723 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
7724 if (ret)
7725 return vk_error(device->instance, VK_ERROR_TOO_MANY_OBJECTS);
7726
7727 if (sem->temporary.kind != RADV_SEMAPHORE_NONE) {
7728 radv_destroy_semaphore_part(device, &sem->temporary);
7729 } else {
7730 device->ws->reset_syncobj(device->ws, syncobj_handle);
7731 }
7732 break;
7733 default:
7734 unreachable("Unhandled semaphore handle type");
7735 }
7736
7737 return VK_SUCCESS;
7738 }
7739
7740 void radv_GetPhysicalDeviceExternalSemaphoreProperties(
7741 VkPhysicalDevice physicalDevice,
7742 const VkPhysicalDeviceExternalSemaphoreInfo *pExternalSemaphoreInfo,
7743 VkExternalSemaphoreProperties *pExternalSemaphoreProperties)
7744 {
7745 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
7746 VkSemaphoreTypeKHR type = radv_get_semaphore_type(pExternalSemaphoreInfo->pNext, NULL);
7747
7748 if (type == VK_SEMAPHORE_TYPE_TIMELINE && pdevice->rad_info.has_timeline_syncobj &&
7749 pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) {
7750 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7751 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7752 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7753 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7754 } else if (type == VK_SEMAPHORE_TYPE_TIMELINE) {
7755 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
7756 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
7757 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
7758
7759 /* Require has_syncobj_wait_for_submit for the syncobj signal ioctl introduced at virtually the same time */
7760 } else if (pdevice->rad_info.has_syncobj_wait_for_submit &&
7761 (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT ||
7762 pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT)) {
7763 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
7764 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
7765 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7766 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7767 } else if (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) {
7768 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7769 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7770 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7771 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7772 } else {
7773 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
7774 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
7775 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
7776 }
7777 }
7778
7779 VkResult radv_ImportFenceFdKHR(VkDevice _device,
7780 const VkImportFenceFdInfoKHR *pImportFenceFdInfo)
7781 {
7782 RADV_FROM_HANDLE(radv_device, device, _device);
7783 RADV_FROM_HANDLE(radv_fence, fence, pImportFenceFdInfo->fence);
7784 struct radv_fence_part *dst = NULL;
7785 VkResult result;
7786
7787 if (pImportFenceFdInfo->flags & VK_FENCE_IMPORT_TEMPORARY_BIT) {
7788 dst = &fence->temporary;
7789 } else {
7790 dst = &fence->permanent;
7791 }
7792
7793 uint32_t syncobj = dst->kind == RADV_FENCE_SYNCOBJ ? dst->syncobj : 0;
7794
7795 switch(pImportFenceFdInfo->handleType) {
7796 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
7797 result = radv_import_opaque_fd(device, pImportFenceFdInfo->fd, &syncobj);
7798 break;
7799 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
7800 result = radv_import_sync_fd(device, pImportFenceFdInfo->fd, &syncobj);
7801 break;
7802 default:
7803 unreachable("Unhandled fence handle type");
7804 }
7805
7806 if (result == VK_SUCCESS) {
7807 dst->syncobj = syncobj;
7808 dst->kind = RADV_FENCE_SYNCOBJ;
7809 }
7810
7811 return result;
7812 }
7813
7814 VkResult radv_GetFenceFdKHR(VkDevice _device,
7815 const VkFenceGetFdInfoKHR *pGetFdInfo,
7816 int *pFd)
7817 {
7818 RADV_FROM_HANDLE(radv_device, device, _device);
7819 RADV_FROM_HANDLE(radv_fence, fence, pGetFdInfo->fence);
7820 int ret;
7821
7822 struct radv_fence_part *part =
7823 fence->temporary.kind != RADV_FENCE_NONE ?
7824 &fence->temporary : &fence->permanent;
7825
7826 switch(pGetFdInfo->handleType) {
7827 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
7828 ret = device->ws->export_syncobj(device->ws, part->syncobj, pFd);
7829 if (ret)
7830 return vk_error(device->instance, VK_ERROR_TOO_MANY_OBJECTS);
7831 break;
7832 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
7833 ret = device->ws->export_syncobj_to_sync_file(device->ws,
7834 part->syncobj, pFd);
7835 if (ret)
7836 return vk_error(device->instance, VK_ERROR_TOO_MANY_OBJECTS);
7837
7838 if (part == &fence->temporary) {
7839 radv_destroy_fence_part(device, part);
7840 } else {
7841 device->ws->reset_syncobj(device->ws, part->syncobj);
7842 }
7843 break;
7844 default:
7845 unreachable("Unhandled fence handle type");
7846 }
7847
7848 return VK_SUCCESS;
7849 }
7850
7851 void radv_GetPhysicalDeviceExternalFenceProperties(
7852 VkPhysicalDevice physicalDevice,
7853 const VkPhysicalDeviceExternalFenceInfo *pExternalFenceInfo,
7854 VkExternalFenceProperties *pExternalFenceProperties)
7855 {
7856 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
7857
7858 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
7859 (pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT ||
7860 pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT)) {
7861 pExternalFenceProperties->exportFromImportedHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
7862 pExternalFenceProperties->compatibleHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
7863 pExternalFenceProperties->externalFenceFeatures = VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT |
7864 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7865 } else {
7866 pExternalFenceProperties->exportFromImportedHandleTypes = 0;
7867 pExternalFenceProperties->compatibleHandleTypes = 0;
7868 pExternalFenceProperties->externalFenceFeatures = 0;
7869 }
7870 }
7871
7872 VkResult
7873 radv_CreateDebugReportCallbackEXT(VkInstance _instance,
7874 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
7875 const VkAllocationCallbacks* pAllocator,
7876 VkDebugReportCallbackEXT* pCallback)
7877 {
7878 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7879 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
7880 pCreateInfo, pAllocator, &instance->alloc,
7881 pCallback);
7882 }
7883
7884 void
7885 radv_DestroyDebugReportCallbackEXT(VkInstance _instance,
7886 VkDebugReportCallbackEXT _callback,
7887 const VkAllocationCallbacks* pAllocator)
7888 {
7889 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7890 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
7891 _callback, pAllocator, &instance->alloc);
7892 }
7893
7894 void
7895 radv_DebugReportMessageEXT(VkInstance _instance,
7896 VkDebugReportFlagsEXT flags,
7897 VkDebugReportObjectTypeEXT objectType,
7898 uint64_t object,
7899 size_t location,
7900 int32_t messageCode,
7901 const char* pLayerPrefix,
7902 const char* pMessage)
7903 {
7904 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7905 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
7906 object, location, messageCode, pLayerPrefix, pMessage);
7907 }
7908
7909 void
7910 radv_GetDeviceGroupPeerMemoryFeatures(
7911 VkDevice device,
7912 uint32_t heapIndex,
7913 uint32_t localDeviceIndex,
7914 uint32_t remoteDeviceIndex,
7915 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
7916 {
7917 assert(localDeviceIndex == remoteDeviceIndex);
7918
7919 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
7920 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
7921 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
7922 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
7923 }
7924
7925 static const VkTimeDomainEXT radv_time_domains[] = {
7926 VK_TIME_DOMAIN_DEVICE_EXT,
7927 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
7928 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
7929 };
7930
7931 VkResult radv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
7932 VkPhysicalDevice physicalDevice,
7933 uint32_t *pTimeDomainCount,
7934 VkTimeDomainEXT *pTimeDomains)
7935 {
7936 int d;
7937 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
7938
7939 for (d = 0; d < ARRAY_SIZE(radv_time_domains); d++) {
7940 vk_outarray_append(&out, i) {
7941 *i = radv_time_domains[d];
7942 }
7943 }
7944
7945 return vk_outarray_status(&out);
7946 }
7947
7948 static uint64_t
7949 radv_clock_gettime(clockid_t clock_id)
7950 {
7951 struct timespec current;
7952 int ret;
7953
7954 ret = clock_gettime(clock_id, &current);
7955 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
7956 ret = clock_gettime(CLOCK_MONOTONIC, &current);
7957 if (ret < 0)
7958 return 0;
7959
7960 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
7961 }
7962
7963 VkResult radv_GetCalibratedTimestampsEXT(
7964 VkDevice _device,
7965 uint32_t timestampCount,
7966 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
7967 uint64_t *pTimestamps,
7968 uint64_t *pMaxDeviation)
7969 {
7970 RADV_FROM_HANDLE(radv_device, device, _device);
7971 uint32_t clock_crystal_freq = device->physical_device->rad_info.clock_crystal_freq;
7972 int d;
7973 uint64_t begin, end;
7974 uint64_t max_clock_period = 0;
7975
7976 begin = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
7977
7978 for (d = 0; d < timestampCount; d++) {
7979 switch (pTimestampInfos[d].timeDomain) {
7980 case VK_TIME_DOMAIN_DEVICE_EXT:
7981 pTimestamps[d] = device->ws->query_value(device->ws,
7982 RADEON_TIMESTAMP);
7983 uint64_t device_period = DIV_ROUND_UP(1000000, clock_crystal_freq);
7984 max_clock_period = MAX2(max_clock_period, device_period);
7985 break;
7986 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
7987 pTimestamps[d] = radv_clock_gettime(CLOCK_MONOTONIC);
7988 max_clock_period = MAX2(max_clock_period, 1);
7989 break;
7990
7991 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
7992 pTimestamps[d] = begin;
7993 break;
7994 default:
7995 pTimestamps[d] = 0;
7996 break;
7997 }
7998 }
7999
8000 end = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
8001
8002 /*
8003 * The maximum deviation is the sum of the interval over which we
8004 * perform the sampling and the maximum period of any sampled
8005 * clock. That's because the maximum skew between any two sampled
8006 * clock edges is when the sampled clock with the largest period is
8007 * sampled at the end of that period but right at the beginning of the
8008 * sampling interval and some other clock is sampled right at the
8009 * begining of its sampling period and right at the end of the
8010 * sampling interval. Let's assume the GPU has the longest clock
8011 * period and that the application is sampling GPU and monotonic:
8012 *
8013 * s e
8014 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
8015 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
8016 *
8017 * g
8018 * 0 1 2 3
8019 * GPU -----_____-----_____-----_____-----_____
8020 *
8021 * m
8022 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
8023 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
8024 *
8025 * Interval <----------------->
8026 * Deviation <-------------------------->
8027 *
8028 * s = read(raw) 2
8029 * g = read(GPU) 1
8030 * m = read(monotonic) 2
8031 * e = read(raw) b
8032 *
8033 * We round the sample interval up by one tick to cover sampling error
8034 * in the interval clock
8035 */
8036
8037 uint64_t sample_interval = end - begin + 1;
8038
8039 *pMaxDeviation = sample_interval + max_clock_period;
8040
8041 return VK_SUCCESS;
8042 }
8043
8044 void radv_GetPhysicalDeviceMultisamplePropertiesEXT(
8045 VkPhysicalDevice physicalDevice,
8046 VkSampleCountFlagBits samples,
8047 VkMultisamplePropertiesEXT* pMultisampleProperties)
8048 {
8049 if (samples & (VK_SAMPLE_COUNT_2_BIT |
8050 VK_SAMPLE_COUNT_4_BIT |
8051 VK_SAMPLE_COUNT_8_BIT)) {
8052 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 2, 2 };
8053 } else {
8054 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 0, 0 };
8055 }
8056 }
8057
8058 VkResult radv_CreatePrivateDataSlotEXT(
8059 VkDevice _device,
8060 const VkPrivateDataSlotCreateInfoEXT* pCreateInfo,
8061 const VkAllocationCallbacks* pAllocator,
8062 VkPrivateDataSlotEXT* pPrivateDataSlot)
8063 {
8064 RADV_FROM_HANDLE(radv_device, device, _device);
8065 return vk_private_data_slot_create(&device->vk, pCreateInfo, pAllocator,
8066 pPrivateDataSlot);
8067 }
8068
8069 void radv_DestroyPrivateDataSlotEXT(
8070 VkDevice _device,
8071 VkPrivateDataSlotEXT privateDataSlot,
8072 const VkAllocationCallbacks* pAllocator)
8073 {
8074 RADV_FROM_HANDLE(radv_device, device, _device);
8075 vk_private_data_slot_destroy(&device->vk, privateDataSlot, pAllocator);
8076 }
8077
8078 VkResult radv_SetPrivateDataEXT(
8079 VkDevice _device,
8080 VkObjectType objectType,
8081 uint64_t objectHandle,
8082 VkPrivateDataSlotEXT privateDataSlot,
8083 uint64_t data)
8084 {
8085 RADV_FROM_HANDLE(radv_device, device, _device);
8086 return vk_object_base_set_private_data(&device->vk, objectType,
8087 objectHandle, privateDataSlot,
8088 data);
8089 }
8090
8091 void radv_GetPrivateDataEXT(
8092 VkDevice _device,
8093 VkObjectType objectType,
8094 uint64_t objectHandle,
8095 VkPrivateDataSlotEXT privateDataSlot,
8096 uint64_t* pData)
8097 {
8098 RADV_FROM_HANDLE(radv_device, device, _device);
8099 vk_object_base_get_private_data(&device->vk, objectType, objectHandle,
8100 privateDataSlot, pData);
8101 }