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