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