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