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