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