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