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