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