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