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