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