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