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