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