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