radv: fix checking the return value of cs_finalize()
[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 if (!device->border_color_data.colors_gpu_ptr)
3016 return vk_error(device->physical_device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
3017 pthread_mutex_init(&device->border_color_data.mutex, NULL);
3018
3019 return VK_SUCCESS;
3020 }
3021
3022 static void radv_device_finish_border_color(struct radv_device *device)
3023 {
3024 if (device->border_color_data.bo) {
3025 device->ws->buffer_destroy(device->border_color_data.bo);
3026
3027 pthread_mutex_destroy(&device->border_color_data.mutex);
3028 }
3029 }
3030
3031 VkResult radv_CreateDevice(
3032 VkPhysicalDevice physicalDevice,
3033 const VkDeviceCreateInfo* pCreateInfo,
3034 const VkAllocationCallbacks* pAllocator,
3035 VkDevice* pDevice)
3036 {
3037 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
3038 VkResult result;
3039 struct radv_device *device;
3040
3041 bool keep_shader_info = false;
3042 bool robust_buffer_access = false;
3043 bool overallocation_disallowed = false;
3044 bool custom_border_colors = false;
3045
3046 /* Check enabled features */
3047 if (pCreateInfo->pEnabledFeatures) {
3048 result = check_physical_device_features(physicalDevice,
3049 pCreateInfo->pEnabledFeatures);
3050 if (result != VK_SUCCESS)
3051 return result;
3052
3053 if (pCreateInfo->pEnabledFeatures->robustBufferAccess)
3054 robust_buffer_access = true;
3055 }
3056
3057 vk_foreach_struct_const(ext, pCreateInfo->pNext) {
3058 switch (ext->sType) {
3059 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2: {
3060 const VkPhysicalDeviceFeatures2 *features = (const void *)ext;
3061 result = check_physical_device_features(physicalDevice,
3062 &features->features);
3063 if (result != VK_SUCCESS)
3064 return result;
3065
3066 if (features->features.robustBufferAccess)
3067 robust_buffer_access = true;
3068 break;
3069 }
3070 case VK_STRUCTURE_TYPE_DEVICE_MEMORY_OVERALLOCATION_CREATE_INFO_AMD: {
3071 const VkDeviceMemoryOverallocationCreateInfoAMD *overallocation = (const void *)ext;
3072 if (overallocation->overallocationBehavior == VK_MEMORY_OVERALLOCATION_BEHAVIOR_DISALLOWED_AMD)
3073 overallocation_disallowed = true;
3074 break;
3075 }
3076 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT: {
3077 const VkPhysicalDeviceCustomBorderColorFeaturesEXT *border_color_features = (const void *)ext;
3078 custom_border_colors = border_color_features->customBorderColors;
3079 break;
3080 }
3081 default:
3082 break;
3083 }
3084 }
3085
3086 device = vk_zalloc2(&physical_device->instance->alloc, pAllocator,
3087 sizeof(*device), 8,
3088 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
3089 if (!device)
3090 return vk_error(physical_device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3091
3092 vk_device_init(&device->vk, pCreateInfo,
3093 &physical_device->instance->alloc, pAllocator);
3094
3095 device->instance = physical_device->instance;
3096 device->physical_device = physical_device;
3097
3098 device->ws = physical_device->ws;
3099
3100 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
3101 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
3102 int index = radv_get_device_extension_index(ext_name);
3103 if (index < 0 || !physical_device->supported_extensions.extensions[index]) {
3104 vk_free(&device->vk.alloc, device);
3105 return vk_error(physical_device->instance, VK_ERROR_EXTENSION_NOT_PRESENT);
3106 }
3107
3108 device->enabled_extensions.extensions[index] = true;
3109 }
3110
3111 radv_device_init_dispatch(device);
3112
3113 keep_shader_info = device->enabled_extensions.AMD_shader_info;
3114
3115 /* With update after bind we can't attach bo's to the command buffer
3116 * from the descriptor set anymore, so we have to use a global BO list.
3117 */
3118 device->use_global_bo_list =
3119 (device->instance->perftest_flags & RADV_PERFTEST_BO_LIST) ||
3120 device->enabled_extensions.EXT_descriptor_indexing ||
3121 device->enabled_extensions.EXT_buffer_device_address ||
3122 device->enabled_extensions.KHR_buffer_device_address;
3123
3124 device->robust_buffer_access = robust_buffer_access;
3125
3126 mtx_init(&device->shader_slab_mutex, mtx_plain);
3127 list_inithead(&device->shader_slabs);
3128
3129 device->overallocation_disallowed = overallocation_disallowed;
3130 mtx_init(&device->overallocation_mutex, mtx_plain);
3131
3132 radv_bo_list_init(&device->bo_list);
3133
3134 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
3135 const VkDeviceQueueCreateInfo *queue_create = &pCreateInfo->pQueueCreateInfos[i];
3136 uint32_t qfi = queue_create->queueFamilyIndex;
3137 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority =
3138 vk_find_struct_const(queue_create->pNext, DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
3139
3140 assert(!global_priority || device->physical_device->rad_info.has_ctx_priority);
3141
3142 device->queues[qfi] = vk_alloc(&device->vk.alloc,
3143 queue_create->queueCount * sizeof(struct radv_queue), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
3144 if (!device->queues[qfi]) {
3145 result = VK_ERROR_OUT_OF_HOST_MEMORY;
3146 goto fail;
3147 }
3148
3149 memset(device->queues[qfi], 0, queue_create->queueCount * sizeof(struct radv_queue));
3150
3151 device->queue_count[qfi] = queue_create->queueCount;
3152
3153 for (unsigned q = 0; q < queue_create->queueCount; q++) {
3154 result = radv_queue_init(device, &device->queues[qfi][q],
3155 qfi, q, queue_create->flags,
3156 global_priority);
3157 if (result != VK_SUCCESS)
3158 goto fail;
3159 }
3160 }
3161
3162 device->pbb_allowed = device->physical_device->rad_info.chip_class >= GFX9 &&
3163 !(device->instance->debug_flags & RADV_DEBUG_NOBINNING);
3164
3165 /* Disable DFSM by default. As of 2019-09-15 Talos on Low is still 3% slower on Raven. */
3166 device->dfsm_allowed = device->pbb_allowed &&
3167 (device->instance->perftest_flags & RADV_PERFTEST_DFSM);
3168
3169 device->always_use_syncobj = device->physical_device->rad_info.has_syncobj_wait_for_submit;
3170
3171 /* The maximum number of scratch waves. Scratch space isn't divided
3172 * evenly between CUs. The number is only a function of the number of CUs.
3173 * We can decrease the constant to decrease the scratch buffer size.
3174 *
3175 * sctx->scratch_waves must be >= the maximum possible size of
3176 * 1 threadgroup, so that the hw doesn't hang from being unable
3177 * to start any.
3178 *
3179 * The recommended value is 4 per CU at most. Higher numbers don't
3180 * bring much benefit, but they still occupy chip resources (think
3181 * async compute). I've seen ~2% performance difference between 4 and 32.
3182 */
3183 uint32_t max_threads_per_block = 2048;
3184 device->scratch_waves = MAX2(32 * physical_device->rad_info.num_good_compute_units,
3185 max_threads_per_block / 64);
3186
3187 device->dispatch_initiator = S_00B800_COMPUTE_SHADER_EN(1);
3188
3189 if (device->physical_device->rad_info.chip_class >= GFX7) {
3190 /* If the KMD allows it (there is a KMD hw register for it),
3191 * allow launching waves out-of-order.
3192 */
3193 device->dispatch_initiator |= S_00B800_ORDER_MODE(1);
3194 }
3195
3196 radv_device_init_gs_info(device);
3197
3198 device->tess_offchip_block_dw_size =
3199 device->physical_device->rad_info.family == CHIP_HAWAII ? 4096 : 8192;
3200
3201 if (getenv("RADV_TRACE_FILE")) {
3202 const char *filename = getenv("RADV_TRACE_FILE");
3203
3204 keep_shader_info = true;
3205
3206 if (!radv_init_trace(device))
3207 goto fail;
3208
3209 fprintf(stderr, "*****************************************************************************\n");
3210 fprintf(stderr, "* WARNING: RADV_TRACE_FILE is costly and should only be used for debugging! *\n");
3211 fprintf(stderr, "*****************************************************************************\n");
3212
3213 fprintf(stderr, "Trace file will be dumped to %s\n", filename);
3214 radv_dump_enabled_options(device, stderr);
3215 }
3216
3217 int radv_thread_trace = radv_get_int_debug_option("RADV_THREAD_TRACE", -1);
3218 if (radv_thread_trace >= 0) {
3219 fprintf(stderr, "*************************************************\n");
3220 fprintf(stderr, "* WARNING: Thread trace support is experimental *\n");
3221 fprintf(stderr, "*************************************************\n");
3222
3223 if (device->physical_device->rad_info.chip_class < GFX8) {
3224 fprintf(stderr, "GPU hardware not supported: refer to "
3225 "the RGP documentation for the list of "
3226 "supported GPUs!\n");
3227 abort();
3228 }
3229
3230 /* Default buffer size set to 1MB per SE. */
3231 device->thread_trace_buffer_size =
3232 radv_get_int_debug_option("RADV_THREAD_TRACE_BUFFER_SIZE", 1024 * 1024);
3233 device->thread_trace_start_frame = radv_thread_trace;
3234
3235 if (!radv_thread_trace_init(device))
3236 goto fail;
3237 }
3238
3239 /* Temporarily disable secure compile while we create meta shaders, etc */
3240 uint8_t sc_threads = device->instance->num_sc_threads;
3241 if (sc_threads)
3242 device->instance->num_sc_threads = 0;
3243
3244 device->keep_shader_info = keep_shader_info;
3245 result = radv_device_init_meta(device);
3246 if (result != VK_SUCCESS)
3247 goto fail;
3248
3249 radv_device_init_msaa(device);
3250
3251 /* If the border color extension is enabled, let's create the buffer we need. */
3252 if (custom_border_colors) {
3253 result = radv_device_init_border_color(device);
3254 if (result != VK_SUCCESS)
3255 goto fail;
3256 }
3257
3258 for (int family = 0; family < RADV_MAX_QUEUE_FAMILIES; ++family) {
3259 device->empty_cs[family] = device->ws->cs_create(device->ws, family);
3260 switch (family) {
3261 case RADV_QUEUE_GENERAL:
3262 radeon_emit(device->empty_cs[family], PKT3(PKT3_CONTEXT_CONTROL, 1, 0));
3263 radeon_emit(device->empty_cs[family], CC0_UPDATE_LOAD_ENABLES(1));
3264 radeon_emit(device->empty_cs[family], CC1_UPDATE_SHADOW_ENABLES(1));
3265 break;
3266 case RADV_QUEUE_COMPUTE:
3267 radeon_emit(device->empty_cs[family], PKT3(PKT3_NOP, 0, 0));
3268 radeon_emit(device->empty_cs[family], 0);
3269 break;
3270 }
3271 device->ws->cs_finalize(device->empty_cs[family]);
3272 }
3273
3274 if (device->physical_device->rad_info.chip_class >= GFX7)
3275 cik_create_gfx_config(device);
3276
3277 VkPipelineCacheCreateInfo ci;
3278 ci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
3279 ci.pNext = NULL;
3280 ci.flags = 0;
3281 ci.pInitialData = NULL;
3282 ci.initialDataSize = 0;
3283 VkPipelineCache pc;
3284 result = radv_CreatePipelineCache(radv_device_to_handle(device),
3285 &ci, NULL, &pc);
3286 if (result != VK_SUCCESS)
3287 goto fail_meta;
3288
3289 device->mem_cache = radv_pipeline_cache_from_handle(pc);
3290
3291 result = radv_create_pthread_cond(&device->timeline_cond);
3292 if (result != VK_SUCCESS)
3293 goto fail_mem_cache;
3294
3295 device->force_aniso =
3296 MIN2(16, radv_get_int_debug_option("RADV_TEX_ANISO", -1));
3297 if (device->force_aniso >= 0) {
3298 fprintf(stderr, "radv: Forcing anisotropy filter to %ix\n",
3299 1 << util_logbase2(device->force_aniso));
3300 }
3301
3302 /* Fork device for secure compile as required */
3303 device->instance->num_sc_threads = sc_threads;
3304 if (radv_device_use_secure_compile(device->instance)) {
3305
3306 result = fork_secure_compile_idle_device(device);
3307 if (result != VK_SUCCESS)
3308 goto fail_meta;
3309 }
3310
3311 *pDevice = radv_device_to_handle(device);
3312 return VK_SUCCESS;
3313
3314 fail_mem_cache:
3315 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
3316 fail_meta:
3317 radv_device_finish_meta(device);
3318 fail:
3319 radv_bo_list_finish(&device->bo_list);
3320
3321 radv_thread_trace_finish(device);
3322
3323 if (device->trace_bo)
3324 device->ws->buffer_destroy(device->trace_bo);
3325
3326 if (device->gfx_init)
3327 device->ws->buffer_destroy(device->gfx_init);
3328
3329 radv_device_finish_border_color(device);
3330
3331 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
3332 for (unsigned q = 0; q < device->queue_count[i]; q++)
3333 radv_queue_finish(&device->queues[i][q]);
3334 if (device->queue_count[i])
3335 vk_free(&device->vk.alloc, device->queues[i]);
3336 }
3337
3338 vk_free(&device->vk.alloc, device);
3339 return result;
3340 }
3341
3342 void radv_DestroyDevice(
3343 VkDevice _device,
3344 const VkAllocationCallbacks* pAllocator)
3345 {
3346 RADV_FROM_HANDLE(radv_device, device, _device);
3347
3348 if (!device)
3349 return;
3350
3351 if (device->trace_bo)
3352 device->ws->buffer_destroy(device->trace_bo);
3353
3354 if (device->gfx_init)
3355 device->ws->buffer_destroy(device->gfx_init);
3356
3357 radv_device_finish_border_color(device);
3358
3359 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
3360 for (unsigned q = 0; q < device->queue_count[i]; q++)
3361 radv_queue_finish(&device->queues[i][q]);
3362 if (device->queue_count[i])
3363 vk_free(&device->vk.alloc, device->queues[i]);
3364 if (device->empty_cs[i])
3365 device->ws->cs_destroy(device->empty_cs[i]);
3366 }
3367 radv_device_finish_meta(device);
3368
3369 VkPipelineCache pc = radv_pipeline_cache_to_handle(device->mem_cache);
3370 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
3371
3372 radv_destroy_shader_slabs(device);
3373
3374 pthread_cond_destroy(&device->timeline_cond);
3375 radv_bo_list_finish(&device->bo_list);
3376
3377 radv_thread_trace_finish(device);
3378
3379 if (radv_device_use_secure_compile(device->instance)) {
3380 for (unsigned i = 0; i < device->instance->num_sc_threads; i++ ) {
3381 destroy_secure_compile_device(device, i);
3382 }
3383 }
3384
3385 if (device->sc_state) {
3386 free(device->sc_state->uid);
3387 vk_free(&device->vk.alloc, device->sc_state->secure_compile_processes);
3388 }
3389 vk_free(&device->vk.alloc, device->sc_state);
3390 vk_free(&device->vk.alloc, device);
3391 }
3392
3393 VkResult radv_EnumerateInstanceLayerProperties(
3394 uint32_t* pPropertyCount,
3395 VkLayerProperties* pProperties)
3396 {
3397 if (pProperties == NULL) {
3398 *pPropertyCount = 0;
3399 return VK_SUCCESS;
3400 }
3401
3402 /* None supported at this time */
3403 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
3404 }
3405
3406 VkResult radv_EnumerateDeviceLayerProperties(
3407 VkPhysicalDevice physicalDevice,
3408 uint32_t* pPropertyCount,
3409 VkLayerProperties* pProperties)
3410 {
3411 if (pProperties == NULL) {
3412 *pPropertyCount = 0;
3413 return VK_SUCCESS;
3414 }
3415
3416 /* None supported at this time */
3417 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
3418 }
3419
3420 void radv_GetDeviceQueue2(
3421 VkDevice _device,
3422 const VkDeviceQueueInfo2* pQueueInfo,
3423 VkQueue* pQueue)
3424 {
3425 RADV_FROM_HANDLE(radv_device, device, _device);
3426 struct radv_queue *queue;
3427
3428 queue = &device->queues[pQueueInfo->queueFamilyIndex][pQueueInfo->queueIndex];
3429 if (pQueueInfo->flags != queue->flags) {
3430 /* From the Vulkan 1.1.70 spec:
3431 *
3432 * "The queue returned by vkGetDeviceQueue2 must have the same
3433 * flags value from this structure as that used at device
3434 * creation time in a VkDeviceQueueCreateInfo instance. If no
3435 * matching flags were specified at device creation time then
3436 * pQueue will return VK_NULL_HANDLE."
3437 */
3438 *pQueue = VK_NULL_HANDLE;
3439 return;
3440 }
3441
3442 *pQueue = radv_queue_to_handle(queue);
3443 }
3444
3445 void radv_GetDeviceQueue(
3446 VkDevice _device,
3447 uint32_t queueFamilyIndex,
3448 uint32_t queueIndex,
3449 VkQueue* pQueue)
3450 {
3451 const VkDeviceQueueInfo2 info = (VkDeviceQueueInfo2) {
3452 .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
3453 .queueFamilyIndex = queueFamilyIndex,
3454 .queueIndex = queueIndex
3455 };
3456
3457 radv_GetDeviceQueue2(_device, &info, pQueue);
3458 }
3459
3460 static void
3461 fill_geom_tess_rings(struct radv_queue *queue,
3462 uint32_t *map,
3463 bool add_sample_positions,
3464 uint32_t esgs_ring_size,
3465 struct radeon_winsys_bo *esgs_ring_bo,
3466 uint32_t gsvs_ring_size,
3467 struct radeon_winsys_bo *gsvs_ring_bo,
3468 uint32_t tess_factor_ring_size,
3469 uint32_t tess_offchip_ring_offset,
3470 uint32_t tess_offchip_ring_size,
3471 struct radeon_winsys_bo *tess_rings_bo)
3472 {
3473 uint32_t *desc = &map[4];
3474
3475 if (esgs_ring_bo) {
3476 uint64_t esgs_va = radv_buffer_get_va(esgs_ring_bo);
3477
3478 /* stride 0, num records - size, add tid, swizzle, elsize4,
3479 index stride 64 */
3480 desc[0] = esgs_va;
3481 desc[1] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32) |
3482 S_008F04_SWIZZLE_ENABLE(true);
3483 desc[2] = esgs_ring_size;
3484 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3485 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3486 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3487 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
3488 S_008F0C_INDEX_STRIDE(3) |
3489 S_008F0C_ADD_TID_ENABLE(1);
3490
3491 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3492 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3493 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3494 S_008F0C_RESOURCE_LEVEL(1);
3495 } else {
3496 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3497 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
3498 S_008F0C_ELEMENT_SIZE(1);
3499 }
3500
3501 /* GS entry for ES->GS ring */
3502 /* stride 0, num records - size, elsize0,
3503 index stride 0 */
3504 desc[4] = esgs_va;
3505 desc[5] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32);
3506 desc[6] = esgs_ring_size;
3507 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3508 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3509 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3510 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3511
3512 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3513 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3514 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3515 S_008F0C_RESOURCE_LEVEL(1);
3516 } else {
3517 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3518 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3519 }
3520 }
3521
3522 desc += 8;
3523
3524 if (gsvs_ring_bo) {
3525 uint64_t gsvs_va = radv_buffer_get_va(gsvs_ring_bo);
3526
3527 /* VS entry for GS->VS ring */
3528 /* stride 0, num records - size, elsize0,
3529 index stride 0 */
3530 desc[0] = gsvs_va;
3531 desc[1] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32);
3532 desc[2] = gsvs_ring_size;
3533 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3534 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3535 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3536 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3537
3538 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3539 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3540 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3541 S_008F0C_RESOURCE_LEVEL(1);
3542 } else {
3543 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3544 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3545 }
3546
3547 /* stride gsvs_itemsize, num records 64
3548 elsize 4, index stride 16 */
3549 /* shader will patch stride and desc[2] */
3550 desc[4] = gsvs_va;
3551 desc[5] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32) |
3552 S_008F04_SWIZZLE_ENABLE(1);
3553 desc[6] = 0;
3554 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3555 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3556 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3557 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
3558 S_008F0C_INDEX_STRIDE(1) |
3559 S_008F0C_ADD_TID_ENABLE(true);
3560
3561 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3562 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3563 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3564 S_008F0C_RESOURCE_LEVEL(1);
3565 } else {
3566 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3567 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
3568 S_008F0C_ELEMENT_SIZE(1);
3569 }
3570
3571 }
3572
3573 desc += 8;
3574
3575 if (tess_rings_bo) {
3576 uint64_t tess_va = radv_buffer_get_va(tess_rings_bo);
3577 uint64_t tess_offchip_va = tess_va + tess_offchip_ring_offset;
3578
3579 desc[0] = tess_va;
3580 desc[1] = S_008F04_BASE_ADDRESS_HI(tess_va >> 32);
3581 desc[2] = tess_factor_ring_size;
3582 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3583 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3584 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3585 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3586
3587 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3588 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3589 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_RAW) |
3590 S_008F0C_RESOURCE_LEVEL(1);
3591 } else {
3592 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3593 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3594 }
3595
3596 desc[4] = tess_offchip_va;
3597 desc[5] = S_008F04_BASE_ADDRESS_HI(tess_offchip_va >> 32);
3598 desc[6] = tess_offchip_ring_size;
3599 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3600 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3601 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3602 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3603
3604 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3605 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3606 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_RAW) |
3607 S_008F0C_RESOURCE_LEVEL(1);
3608 } else {
3609 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3610 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3611 }
3612 }
3613
3614 desc += 8;
3615
3616 if (add_sample_positions) {
3617 /* add sample positions after all rings */
3618 memcpy(desc, queue->device->sample_locations_1x, 8);
3619 desc += 2;
3620 memcpy(desc, queue->device->sample_locations_2x, 16);
3621 desc += 4;
3622 memcpy(desc, queue->device->sample_locations_4x, 32);
3623 desc += 8;
3624 memcpy(desc, queue->device->sample_locations_8x, 64);
3625 }
3626 }
3627
3628 static unsigned
3629 radv_get_hs_offchip_param(struct radv_device *device, uint32_t *max_offchip_buffers_p)
3630 {
3631 bool double_offchip_buffers = device->physical_device->rad_info.chip_class >= GFX7 &&
3632 device->physical_device->rad_info.family != CHIP_CARRIZO &&
3633 device->physical_device->rad_info.family != CHIP_STONEY;
3634 unsigned max_offchip_buffers_per_se = double_offchip_buffers ? 128 : 64;
3635 unsigned max_offchip_buffers;
3636 unsigned offchip_granularity;
3637 unsigned hs_offchip_param;
3638
3639 /*
3640 * Per RadeonSI:
3641 * This must be one less than the maximum number due to a hw limitation.
3642 * Various hardware bugs need thGFX7
3643 *
3644 * Per AMDVLK:
3645 * Vega10 should limit max_offchip_buffers to 508 (4 * 127).
3646 * Gfx7 should limit max_offchip_buffers to 508
3647 * Gfx6 should limit max_offchip_buffers to 126 (2 * 63)
3648 *
3649 * Follow AMDVLK here.
3650 */
3651 if (device->physical_device->rad_info.chip_class >= GFX10) {
3652 max_offchip_buffers_per_se = 256;
3653 } else if (device->physical_device->rad_info.family == CHIP_VEGA10 ||
3654 device->physical_device->rad_info.chip_class == GFX7 ||
3655 device->physical_device->rad_info.chip_class == GFX6)
3656 --max_offchip_buffers_per_se;
3657
3658 max_offchip_buffers = max_offchip_buffers_per_se *
3659 device->physical_device->rad_info.max_se;
3660
3661 /* Hawaii has a bug with offchip buffers > 256 that can be worked
3662 * around by setting 4K granularity.
3663 */
3664 if (device->tess_offchip_block_dw_size == 4096) {
3665 assert(device->physical_device->rad_info.family == CHIP_HAWAII);
3666 offchip_granularity = V_03093C_X_4K_DWORDS;
3667 } else {
3668 assert(device->tess_offchip_block_dw_size == 8192);
3669 offchip_granularity = V_03093C_X_8K_DWORDS;
3670 }
3671
3672 switch (device->physical_device->rad_info.chip_class) {
3673 case GFX6:
3674 max_offchip_buffers = MIN2(max_offchip_buffers, 126);
3675 break;
3676 case GFX7:
3677 case GFX8:
3678 case GFX9:
3679 max_offchip_buffers = MIN2(max_offchip_buffers, 508);
3680 break;
3681 case GFX10:
3682 break;
3683 default:
3684 break;
3685 }
3686
3687 *max_offchip_buffers_p = max_offchip_buffers;
3688 if (device->physical_device->rad_info.chip_class >= GFX10_3) {
3689 hs_offchip_param = S_03093C_OFFCHIP_BUFFERING_GFX103(max_offchip_buffers - 1) |
3690 S_03093C_OFFCHIP_GRANULARITY_GFX103(offchip_granularity);
3691 } else if (device->physical_device->rad_info.chip_class >= GFX7) {
3692 if (device->physical_device->rad_info.chip_class >= GFX8)
3693 --max_offchip_buffers;
3694 hs_offchip_param =
3695 S_03093C_OFFCHIP_BUFFERING(max_offchip_buffers) |
3696 S_03093C_OFFCHIP_GRANULARITY(offchip_granularity);
3697 } else {
3698 hs_offchip_param =
3699 S_0089B0_OFFCHIP_BUFFERING(max_offchip_buffers);
3700 }
3701 return hs_offchip_param;
3702 }
3703
3704 static void
3705 radv_emit_gs_ring_sizes(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3706 struct radeon_winsys_bo *esgs_ring_bo,
3707 uint32_t esgs_ring_size,
3708 struct radeon_winsys_bo *gsvs_ring_bo,
3709 uint32_t gsvs_ring_size)
3710 {
3711 if (!esgs_ring_bo && !gsvs_ring_bo)
3712 return;
3713
3714 if (esgs_ring_bo)
3715 radv_cs_add_buffer(queue->device->ws, cs, esgs_ring_bo);
3716
3717 if (gsvs_ring_bo)
3718 radv_cs_add_buffer(queue->device->ws, cs, gsvs_ring_bo);
3719
3720 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
3721 radeon_set_uconfig_reg_seq(cs, R_030900_VGT_ESGS_RING_SIZE, 2);
3722 radeon_emit(cs, esgs_ring_size >> 8);
3723 radeon_emit(cs, gsvs_ring_size >> 8);
3724 } else {
3725 radeon_set_config_reg_seq(cs, R_0088C8_VGT_ESGS_RING_SIZE, 2);
3726 radeon_emit(cs, esgs_ring_size >> 8);
3727 radeon_emit(cs, gsvs_ring_size >> 8);
3728 }
3729 }
3730
3731 static void
3732 radv_emit_tess_factor_ring(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3733 unsigned hs_offchip_param, unsigned tf_ring_size,
3734 struct radeon_winsys_bo *tess_rings_bo)
3735 {
3736 uint64_t tf_va;
3737
3738 if (!tess_rings_bo)
3739 return;
3740
3741 tf_va = radv_buffer_get_va(tess_rings_bo);
3742
3743 radv_cs_add_buffer(queue->device->ws, cs, tess_rings_bo);
3744
3745 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
3746 radeon_set_uconfig_reg(cs, R_030938_VGT_TF_RING_SIZE,
3747 S_030938_SIZE(tf_ring_size / 4));
3748 radeon_set_uconfig_reg(cs, R_030940_VGT_TF_MEMORY_BASE,
3749 tf_va >> 8);
3750
3751 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3752 radeon_set_uconfig_reg(cs, R_030984_VGT_TF_MEMORY_BASE_HI_UMD,
3753 S_030984_BASE_HI(tf_va >> 40));
3754 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
3755 radeon_set_uconfig_reg(cs, R_030944_VGT_TF_MEMORY_BASE_HI,
3756 S_030944_BASE_HI(tf_va >> 40));
3757 }
3758 radeon_set_uconfig_reg(cs, R_03093C_VGT_HS_OFFCHIP_PARAM,
3759 hs_offchip_param);
3760 } else {
3761 radeon_set_config_reg(cs, R_008988_VGT_TF_RING_SIZE,
3762 S_008988_SIZE(tf_ring_size / 4));
3763 radeon_set_config_reg(cs, R_0089B8_VGT_TF_MEMORY_BASE,
3764 tf_va >> 8);
3765 radeon_set_config_reg(cs, R_0089B0_VGT_HS_OFFCHIP_PARAM,
3766 hs_offchip_param);
3767 }
3768 }
3769
3770 static void
3771 radv_emit_graphics_scratch(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3772 uint32_t size_per_wave, uint32_t waves,
3773 struct radeon_winsys_bo *scratch_bo)
3774 {
3775 if (queue->queue_family_index != RADV_QUEUE_GENERAL)
3776 return;
3777
3778 if (!scratch_bo)
3779 return;
3780
3781 radv_cs_add_buffer(queue->device->ws, cs, scratch_bo);
3782
3783 radeon_set_context_reg(cs, R_0286E8_SPI_TMPRING_SIZE,
3784 S_0286E8_WAVES(waves) |
3785 S_0286E8_WAVESIZE(round_up_u32(size_per_wave, 1024)));
3786 }
3787
3788 static void
3789 radv_emit_compute_scratch(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3790 uint32_t size_per_wave, uint32_t waves,
3791 struct radeon_winsys_bo *compute_scratch_bo)
3792 {
3793 uint64_t scratch_va;
3794
3795 if (!compute_scratch_bo)
3796 return;
3797
3798 scratch_va = radv_buffer_get_va(compute_scratch_bo);
3799
3800 radv_cs_add_buffer(queue->device->ws, cs, compute_scratch_bo);
3801
3802 radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0, 2);
3803 radeon_emit(cs, scratch_va);
3804 radeon_emit(cs, S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
3805 S_008F04_SWIZZLE_ENABLE(1));
3806
3807 radeon_set_sh_reg(cs, R_00B860_COMPUTE_TMPRING_SIZE,
3808 S_00B860_WAVES(waves) |
3809 S_00B860_WAVESIZE(round_up_u32(size_per_wave, 1024)));
3810 }
3811
3812 static void
3813 radv_emit_global_shader_pointers(struct radv_queue *queue,
3814 struct radeon_cmdbuf *cs,
3815 struct radeon_winsys_bo *descriptor_bo)
3816 {
3817 uint64_t va;
3818
3819 if (!descriptor_bo)
3820 return;
3821
3822 va = radv_buffer_get_va(descriptor_bo);
3823
3824 radv_cs_add_buffer(queue->device->ws, cs, descriptor_bo);
3825
3826 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3827 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3828 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3829 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
3830 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
3831
3832 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3833 radv_emit_shader_pointer(queue->device, cs, regs[i],
3834 va, true);
3835 }
3836 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
3837 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3838 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3839 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
3840 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
3841
3842 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3843 radv_emit_shader_pointer(queue->device, cs, regs[i],
3844 va, true);
3845 }
3846 } else {
3847 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3848 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3849 R_00B230_SPI_SHADER_USER_DATA_GS_0,
3850 R_00B330_SPI_SHADER_USER_DATA_ES_0,
3851 R_00B430_SPI_SHADER_USER_DATA_HS_0,
3852 R_00B530_SPI_SHADER_USER_DATA_LS_0};
3853
3854 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3855 radv_emit_shader_pointer(queue->device, cs, regs[i],
3856 va, true);
3857 }
3858 }
3859 }
3860
3861 static void
3862 radv_init_graphics_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
3863 {
3864 struct radv_device *device = queue->device;
3865
3866 if (device->gfx_init) {
3867 uint64_t va = radv_buffer_get_va(device->gfx_init);
3868
3869 radeon_emit(cs, PKT3(PKT3_INDIRECT_BUFFER_CIK, 2, 0));
3870 radeon_emit(cs, va);
3871 radeon_emit(cs, va >> 32);
3872 radeon_emit(cs, device->gfx_init_size_dw & 0xffff);
3873
3874 radv_cs_add_buffer(device->ws, cs, device->gfx_init);
3875 } else {
3876 si_emit_graphics(device, cs);
3877 }
3878 }
3879
3880 static void
3881 radv_init_compute_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
3882 {
3883 struct radv_physical_device *physical_device = queue->device->physical_device;
3884 si_emit_compute(physical_device, cs);
3885 }
3886
3887 static VkResult
3888 radv_get_preamble_cs(struct radv_queue *queue,
3889 uint32_t scratch_size_per_wave,
3890 uint32_t scratch_waves,
3891 uint32_t compute_scratch_size_per_wave,
3892 uint32_t compute_scratch_waves,
3893 uint32_t esgs_ring_size,
3894 uint32_t gsvs_ring_size,
3895 bool needs_tess_rings,
3896 bool needs_gds,
3897 bool needs_gds_oa,
3898 bool needs_sample_positions,
3899 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
3900 struct radeon_cmdbuf **initial_preamble_cs,
3901 struct radeon_cmdbuf **continue_preamble_cs)
3902 {
3903 struct radeon_winsys_bo *scratch_bo = NULL;
3904 struct radeon_winsys_bo *descriptor_bo = NULL;
3905 struct radeon_winsys_bo *compute_scratch_bo = NULL;
3906 struct radeon_winsys_bo *esgs_ring_bo = NULL;
3907 struct radeon_winsys_bo *gsvs_ring_bo = NULL;
3908 struct radeon_winsys_bo *tess_rings_bo = NULL;
3909 struct radeon_winsys_bo *gds_bo = NULL;
3910 struct radeon_winsys_bo *gds_oa_bo = NULL;
3911 struct radeon_cmdbuf *dest_cs[3] = {0};
3912 bool add_tess_rings = false, add_gds = false, add_gds_oa = false, add_sample_positions = false;
3913 unsigned tess_factor_ring_size = 0, tess_offchip_ring_size = 0;
3914 unsigned max_offchip_buffers;
3915 unsigned hs_offchip_param = 0;
3916 unsigned tess_offchip_ring_offset;
3917 uint32_t ring_bo_flags = RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING;
3918 if (!queue->has_tess_rings) {
3919 if (needs_tess_rings)
3920 add_tess_rings = true;
3921 }
3922 if (!queue->has_gds) {
3923 if (needs_gds)
3924 add_gds = true;
3925 }
3926 if (!queue->has_gds_oa) {
3927 if (needs_gds_oa)
3928 add_gds_oa = true;
3929 }
3930 if (!queue->has_sample_positions) {
3931 if (needs_sample_positions)
3932 add_sample_positions = true;
3933 }
3934 tess_factor_ring_size = 32768 * queue->device->physical_device->rad_info.max_se;
3935 hs_offchip_param = radv_get_hs_offchip_param(queue->device,
3936 &max_offchip_buffers);
3937 tess_offchip_ring_offset = align(tess_factor_ring_size, 64 * 1024);
3938 tess_offchip_ring_size = max_offchip_buffers *
3939 queue->device->tess_offchip_block_dw_size * 4;
3940
3941 scratch_size_per_wave = MAX2(scratch_size_per_wave, queue->scratch_size_per_wave);
3942 if (scratch_size_per_wave)
3943 scratch_waves = MIN2(scratch_waves, UINT32_MAX / scratch_size_per_wave);
3944 else
3945 scratch_waves = 0;
3946
3947 compute_scratch_size_per_wave = MAX2(compute_scratch_size_per_wave, queue->compute_scratch_size_per_wave);
3948 if (compute_scratch_size_per_wave)
3949 compute_scratch_waves = MIN2(compute_scratch_waves, UINT32_MAX / compute_scratch_size_per_wave);
3950 else
3951 compute_scratch_waves = 0;
3952
3953 if (scratch_size_per_wave <= queue->scratch_size_per_wave &&
3954 scratch_waves <= queue->scratch_waves &&
3955 compute_scratch_size_per_wave <= queue->compute_scratch_size_per_wave &&
3956 compute_scratch_waves <= queue->compute_scratch_waves &&
3957 esgs_ring_size <= queue->esgs_ring_size &&
3958 gsvs_ring_size <= queue->gsvs_ring_size &&
3959 !add_tess_rings && !add_gds && !add_gds_oa && !add_sample_positions &&
3960 queue->initial_preamble_cs) {
3961 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
3962 *initial_preamble_cs = queue->initial_preamble_cs;
3963 *continue_preamble_cs = queue->continue_preamble_cs;
3964 if (!scratch_size_per_wave && !compute_scratch_size_per_wave &&
3965 !esgs_ring_size && !gsvs_ring_size && !needs_tess_rings &&
3966 !needs_gds && !needs_gds_oa && !needs_sample_positions)
3967 *continue_preamble_cs = NULL;
3968 return VK_SUCCESS;
3969 }
3970
3971 uint32_t scratch_size = scratch_size_per_wave * scratch_waves;
3972 uint32_t queue_scratch_size = queue->scratch_size_per_wave * queue->scratch_waves;
3973 if (scratch_size > queue_scratch_size) {
3974 scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
3975 scratch_size,
3976 4096,
3977 RADEON_DOMAIN_VRAM,
3978 ring_bo_flags,
3979 RADV_BO_PRIORITY_SCRATCH);
3980 if (!scratch_bo)
3981 goto fail;
3982 } else
3983 scratch_bo = queue->scratch_bo;
3984
3985 uint32_t compute_scratch_size = compute_scratch_size_per_wave * compute_scratch_waves;
3986 uint32_t compute_queue_scratch_size = queue->compute_scratch_size_per_wave * queue->compute_scratch_waves;
3987 if (compute_scratch_size > compute_queue_scratch_size) {
3988 compute_scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
3989 compute_scratch_size,
3990 4096,
3991 RADEON_DOMAIN_VRAM,
3992 ring_bo_flags,
3993 RADV_BO_PRIORITY_SCRATCH);
3994 if (!compute_scratch_bo)
3995 goto fail;
3996
3997 } else
3998 compute_scratch_bo = queue->compute_scratch_bo;
3999
4000 if (esgs_ring_size > queue->esgs_ring_size) {
4001 esgs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
4002 esgs_ring_size,
4003 4096,
4004 RADEON_DOMAIN_VRAM,
4005 ring_bo_flags,
4006 RADV_BO_PRIORITY_SCRATCH);
4007 if (!esgs_ring_bo)
4008 goto fail;
4009 } else {
4010 esgs_ring_bo = queue->esgs_ring_bo;
4011 esgs_ring_size = queue->esgs_ring_size;
4012 }
4013
4014 if (gsvs_ring_size > queue->gsvs_ring_size) {
4015 gsvs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
4016 gsvs_ring_size,
4017 4096,
4018 RADEON_DOMAIN_VRAM,
4019 ring_bo_flags,
4020 RADV_BO_PRIORITY_SCRATCH);
4021 if (!gsvs_ring_bo)
4022 goto fail;
4023 } else {
4024 gsvs_ring_bo = queue->gsvs_ring_bo;
4025 gsvs_ring_size = queue->gsvs_ring_size;
4026 }
4027
4028 if (add_tess_rings) {
4029 tess_rings_bo = queue->device->ws->buffer_create(queue->device->ws,
4030 tess_offchip_ring_offset + tess_offchip_ring_size,
4031 256,
4032 RADEON_DOMAIN_VRAM,
4033 ring_bo_flags,
4034 RADV_BO_PRIORITY_SCRATCH);
4035 if (!tess_rings_bo)
4036 goto fail;
4037 } else {
4038 tess_rings_bo = queue->tess_rings_bo;
4039 }
4040
4041 if (add_gds) {
4042 assert(queue->device->physical_device->rad_info.chip_class >= GFX10);
4043
4044 /* 4 streamout GDS counters.
4045 * We need 256B (64 dw) of GDS, otherwise streamout hangs.
4046 */
4047 gds_bo = queue->device->ws->buffer_create(queue->device->ws,
4048 256, 4,
4049 RADEON_DOMAIN_GDS,
4050 ring_bo_flags,
4051 RADV_BO_PRIORITY_SCRATCH);
4052 if (!gds_bo)
4053 goto fail;
4054 } else {
4055 gds_bo = queue->gds_bo;
4056 }
4057
4058 if (add_gds_oa) {
4059 assert(queue->device->physical_device->rad_info.chip_class >= GFX10);
4060
4061 gds_oa_bo = queue->device->ws->buffer_create(queue->device->ws,
4062 4, 1,
4063 RADEON_DOMAIN_OA,
4064 ring_bo_flags,
4065 RADV_BO_PRIORITY_SCRATCH);
4066 if (!gds_oa_bo)
4067 goto fail;
4068 } else {
4069 gds_oa_bo = queue->gds_oa_bo;
4070 }
4071
4072 if (scratch_bo != queue->scratch_bo ||
4073 esgs_ring_bo != queue->esgs_ring_bo ||
4074 gsvs_ring_bo != queue->gsvs_ring_bo ||
4075 tess_rings_bo != queue->tess_rings_bo ||
4076 add_sample_positions) {
4077 uint32_t size = 0;
4078 if (gsvs_ring_bo || esgs_ring_bo ||
4079 tess_rings_bo || add_sample_positions) {
4080 size = 112; /* 2 dword + 2 padding + 4 dword * 6 */
4081 if (add_sample_positions)
4082 size += 128; /* 64+32+16+8 = 120 bytes */
4083 }
4084 else if (scratch_bo)
4085 size = 8; /* 2 dword */
4086
4087 descriptor_bo = queue->device->ws->buffer_create(queue->device->ws,
4088 size,
4089 4096,
4090 RADEON_DOMAIN_VRAM,
4091 RADEON_FLAG_CPU_ACCESS |
4092 RADEON_FLAG_NO_INTERPROCESS_SHARING |
4093 RADEON_FLAG_READ_ONLY,
4094 RADV_BO_PRIORITY_DESCRIPTOR);
4095 if (!descriptor_bo)
4096 goto fail;
4097 } else
4098 descriptor_bo = queue->descriptor_bo;
4099
4100 if (descriptor_bo != queue->descriptor_bo) {
4101 uint32_t *map = (uint32_t*)queue->device->ws->buffer_map(descriptor_bo);
4102 if (!map)
4103 goto fail;
4104
4105 if (scratch_bo) {
4106 uint64_t scratch_va = radv_buffer_get_va(scratch_bo);
4107 uint32_t rsrc1 = S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
4108 S_008F04_SWIZZLE_ENABLE(1);
4109 map[0] = scratch_va;
4110 map[1] = rsrc1;
4111 }
4112
4113 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo || add_sample_positions)
4114 fill_geom_tess_rings(queue, map, add_sample_positions,
4115 esgs_ring_size, esgs_ring_bo,
4116 gsvs_ring_size, gsvs_ring_bo,
4117 tess_factor_ring_size,
4118 tess_offchip_ring_offset,
4119 tess_offchip_ring_size,
4120 tess_rings_bo);
4121
4122 queue->device->ws->buffer_unmap(descriptor_bo);
4123 }
4124
4125 for(int i = 0; i < 3; ++i) {
4126 struct radeon_cmdbuf *cs = NULL;
4127 cs = queue->device->ws->cs_create(queue->device->ws,
4128 queue->queue_family_index ? RING_COMPUTE : RING_GFX);
4129 if (!cs)
4130 goto fail;
4131
4132 dest_cs[i] = cs;
4133
4134 if (scratch_bo)
4135 radv_cs_add_buffer(queue->device->ws, cs, scratch_bo);
4136
4137 /* Emit initial configuration. */
4138 switch (queue->queue_family_index) {
4139 case RADV_QUEUE_GENERAL:
4140 radv_init_graphics_state(cs, queue);
4141 break;
4142 case RADV_QUEUE_COMPUTE:
4143 radv_init_compute_state(cs, queue);
4144 break;
4145 case RADV_QUEUE_TRANSFER:
4146 break;
4147 }
4148
4149 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo) {
4150 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
4151 radeon_emit(cs, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
4152
4153 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
4154 radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
4155 }
4156
4157 radv_emit_gs_ring_sizes(queue, cs, esgs_ring_bo, esgs_ring_size,
4158 gsvs_ring_bo, gsvs_ring_size);
4159 radv_emit_tess_factor_ring(queue, cs, hs_offchip_param,
4160 tess_factor_ring_size, tess_rings_bo);
4161 radv_emit_global_shader_pointers(queue, cs, descriptor_bo);
4162 radv_emit_compute_scratch(queue, cs, compute_scratch_size_per_wave,
4163 compute_scratch_waves, compute_scratch_bo);
4164 radv_emit_graphics_scratch(queue, cs, scratch_size_per_wave,
4165 scratch_waves, scratch_bo);
4166
4167 if (gds_bo)
4168 radv_cs_add_buffer(queue->device->ws, cs, gds_bo);
4169 if (gds_oa_bo)
4170 radv_cs_add_buffer(queue->device->ws, cs, gds_oa_bo);
4171
4172 if (queue->device->trace_bo)
4173 radv_cs_add_buffer(queue->device->ws, cs, queue->device->trace_bo);
4174
4175 if (i == 0) {
4176 si_cs_emit_cache_flush(cs,
4177 queue->device->physical_device->rad_info.chip_class,
4178 NULL, 0,
4179 queue->queue_family_index == RING_COMPUTE &&
4180 queue->device->physical_device->rad_info.chip_class >= GFX7,
4181 (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)) |
4182 RADV_CMD_FLAG_INV_ICACHE |
4183 RADV_CMD_FLAG_INV_SCACHE |
4184 RADV_CMD_FLAG_INV_VCACHE |
4185 RADV_CMD_FLAG_INV_L2 |
4186 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
4187 } else if (i == 1) {
4188 si_cs_emit_cache_flush(cs,
4189 queue->device->physical_device->rad_info.chip_class,
4190 NULL, 0,
4191 queue->queue_family_index == RING_COMPUTE &&
4192 queue->device->physical_device->rad_info.chip_class >= GFX7,
4193 RADV_CMD_FLAG_INV_ICACHE |
4194 RADV_CMD_FLAG_INV_SCACHE |
4195 RADV_CMD_FLAG_INV_VCACHE |
4196 RADV_CMD_FLAG_INV_L2 |
4197 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
4198 }
4199
4200 if (queue->device->ws->cs_finalize(cs) != VK_SUCCESS)
4201 goto fail;
4202 }
4203
4204 if (queue->initial_full_flush_preamble_cs)
4205 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
4206
4207 if (queue->initial_preamble_cs)
4208 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
4209
4210 if (queue->continue_preamble_cs)
4211 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
4212
4213 queue->initial_full_flush_preamble_cs = dest_cs[0];
4214 queue->initial_preamble_cs = dest_cs[1];
4215 queue->continue_preamble_cs = dest_cs[2];
4216
4217 if (scratch_bo != queue->scratch_bo) {
4218 if (queue->scratch_bo)
4219 queue->device->ws->buffer_destroy(queue->scratch_bo);
4220 queue->scratch_bo = scratch_bo;
4221 }
4222 queue->scratch_size_per_wave = scratch_size_per_wave;
4223 queue->scratch_waves = scratch_waves;
4224
4225 if (compute_scratch_bo != queue->compute_scratch_bo) {
4226 if (queue->compute_scratch_bo)
4227 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
4228 queue->compute_scratch_bo = compute_scratch_bo;
4229 }
4230 queue->compute_scratch_size_per_wave = compute_scratch_size_per_wave;
4231 queue->compute_scratch_waves = compute_scratch_waves;
4232
4233 if (esgs_ring_bo != queue->esgs_ring_bo) {
4234 if (queue->esgs_ring_bo)
4235 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
4236 queue->esgs_ring_bo = esgs_ring_bo;
4237 queue->esgs_ring_size = esgs_ring_size;
4238 }
4239
4240 if (gsvs_ring_bo != queue->gsvs_ring_bo) {
4241 if (queue->gsvs_ring_bo)
4242 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
4243 queue->gsvs_ring_bo = gsvs_ring_bo;
4244 queue->gsvs_ring_size = gsvs_ring_size;
4245 }
4246
4247 if (tess_rings_bo != queue->tess_rings_bo) {
4248 queue->tess_rings_bo = tess_rings_bo;
4249 queue->has_tess_rings = true;
4250 }
4251
4252 if (gds_bo != queue->gds_bo) {
4253 queue->gds_bo = gds_bo;
4254 queue->has_gds = true;
4255 }
4256
4257 if (gds_oa_bo != queue->gds_oa_bo) {
4258 queue->gds_oa_bo = gds_oa_bo;
4259 queue->has_gds_oa = true;
4260 }
4261
4262 if (descriptor_bo != queue->descriptor_bo) {
4263 if (queue->descriptor_bo)
4264 queue->device->ws->buffer_destroy(queue->descriptor_bo);
4265
4266 queue->descriptor_bo = descriptor_bo;
4267 }
4268
4269 if (add_sample_positions)
4270 queue->has_sample_positions = true;
4271
4272 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
4273 *initial_preamble_cs = queue->initial_preamble_cs;
4274 *continue_preamble_cs = queue->continue_preamble_cs;
4275 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
4276 *continue_preamble_cs = NULL;
4277 return VK_SUCCESS;
4278 fail:
4279 for (int i = 0; i < ARRAY_SIZE(dest_cs); ++i)
4280 if (dest_cs[i])
4281 queue->device->ws->cs_destroy(dest_cs[i]);
4282 if (descriptor_bo && descriptor_bo != queue->descriptor_bo)
4283 queue->device->ws->buffer_destroy(descriptor_bo);
4284 if (scratch_bo && scratch_bo != queue->scratch_bo)
4285 queue->device->ws->buffer_destroy(scratch_bo);
4286 if (compute_scratch_bo && compute_scratch_bo != queue->compute_scratch_bo)
4287 queue->device->ws->buffer_destroy(compute_scratch_bo);
4288 if (esgs_ring_bo && esgs_ring_bo != queue->esgs_ring_bo)
4289 queue->device->ws->buffer_destroy(esgs_ring_bo);
4290 if (gsvs_ring_bo && gsvs_ring_bo != queue->gsvs_ring_bo)
4291 queue->device->ws->buffer_destroy(gsvs_ring_bo);
4292 if (tess_rings_bo && tess_rings_bo != queue->tess_rings_bo)
4293 queue->device->ws->buffer_destroy(tess_rings_bo);
4294 if (gds_bo && gds_bo != queue->gds_bo)
4295 queue->device->ws->buffer_destroy(gds_bo);
4296 if (gds_oa_bo && gds_oa_bo != queue->gds_oa_bo)
4297 queue->device->ws->buffer_destroy(gds_oa_bo);
4298
4299 return vk_error(queue->device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
4300 }
4301
4302 static VkResult radv_alloc_sem_counts(struct radv_device *device,
4303 struct radv_winsys_sem_counts *counts,
4304 int num_sems,
4305 struct radv_semaphore_part **sems,
4306 const uint64_t *timeline_values,
4307 VkFence _fence,
4308 bool is_signal)
4309 {
4310 int syncobj_idx = 0, sem_idx = 0;
4311
4312 if (num_sems == 0 && _fence == VK_NULL_HANDLE)
4313 return VK_SUCCESS;
4314
4315 for (uint32_t i = 0; i < num_sems; i++) {
4316 switch(sems[i]->kind) {
4317 case RADV_SEMAPHORE_SYNCOBJ:
4318 counts->syncobj_count++;
4319 break;
4320 case RADV_SEMAPHORE_WINSYS:
4321 counts->sem_count++;
4322 break;
4323 case RADV_SEMAPHORE_NONE:
4324 break;
4325 case RADV_SEMAPHORE_TIMELINE:
4326 counts->syncobj_count++;
4327 break;
4328 }
4329 }
4330
4331 if (_fence != VK_NULL_HANDLE) {
4332 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4333 if (fence->temp_syncobj || fence->syncobj)
4334 counts->syncobj_count++;
4335 }
4336
4337 if (counts->syncobj_count) {
4338 counts->syncobj = (uint32_t *)malloc(sizeof(uint32_t) * counts->syncobj_count);
4339 if (!counts->syncobj)
4340 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4341 }
4342
4343 if (counts->sem_count) {
4344 counts->sem = (struct radeon_winsys_sem **)malloc(sizeof(struct radeon_winsys_sem *) * counts->sem_count);
4345 if (!counts->sem) {
4346 free(counts->syncobj);
4347 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4348 }
4349 }
4350
4351 for (uint32_t i = 0; i < num_sems; i++) {
4352 switch(sems[i]->kind) {
4353 case RADV_SEMAPHORE_NONE:
4354 unreachable("Empty semaphore");
4355 break;
4356 case RADV_SEMAPHORE_SYNCOBJ:
4357 counts->syncobj[syncobj_idx++] = sems[i]->syncobj;
4358 break;
4359 case RADV_SEMAPHORE_WINSYS:
4360 counts->sem[sem_idx++] = sems[i]->ws_sem;
4361 break;
4362 case RADV_SEMAPHORE_TIMELINE: {
4363 pthread_mutex_lock(&sems[i]->timeline.mutex);
4364 struct radv_timeline_point *point = NULL;
4365 if (is_signal) {
4366 point = radv_timeline_add_point_locked(device, &sems[i]->timeline, timeline_values[i]);
4367 } else {
4368 point = radv_timeline_find_point_at_least_locked(device, &sems[i]->timeline, timeline_values[i]);
4369 }
4370
4371 pthread_mutex_unlock(&sems[i]->timeline.mutex);
4372
4373 if (point) {
4374 counts->syncobj[syncobj_idx++] = point->syncobj;
4375 } else {
4376 /* Explicitly remove the semaphore so we might not find
4377 * a point later post-submit. */
4378 sems[i] = NULL;
4379 }
4380 break;
4381 }
4382 }
4383 }
4384
4385 if (_fence != VK_NULL_HANDLE) {
4386 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4387 if (fence->temp_syncobj)
4388 counts->syncobj[syncobj_idx++] = fence->temp_syncobj;
4389 else if (fence->syncobj)
4390 counts->syncobj[syncobj_idx++] = fence->syncobj;
4391 }
4392
4393 assert(syncobj_idx <= counts->syncobj_count);
4394 counts->syncobj_count = syncobj_idx;
4395
4396 return VK_SUCCESS;
4397 }
4398
4399 static void
4400 radv_free_sem_info(struct radv_winsys_sem_info *sem_info)
4401 {
4402 free(sem_info->wait.syncobj);
4403 free(sem_info->wait.sem);
4404 free(sem_info->signal.syncobj);
4405 free(sem_info->signal.sem);
4406 }
4407
4408
4409 static void radv_free_temp_syncobjs(struct radv_device *device,
4410 int num_sems,
4411 struct radv_semaphore_part *sems)
4412 {
4413 for (uint32_t i = 0; i < num_sems; i++) {
4414 radv_destroy_semaphore_part(device, sems + i);
4415 }
4416 }
4417
4418 static VkResult
4419 radv_alloc_sem_info(struct radv_device *device,
4420 struct radv_winsys_sem_info *sem_info,
4421 int num_wait_sems,
4422 struct radv_semaphore_part **wait_sems,
4423 const uint64_t *wait_values,
4424 int num_signal_sems,
4425 struct radv_semaphore_part **signal_sems,
4426 const uint64_t *signal_values,
4427 VkFence fence)
4428 {
4429 VkResult ret;
4430 memset(sem_info, 0, sizeof(*sem_info));
4431
4432 ret = radv_alloc_sem_counts(device, &sem_info->wait, num_wait_sems, wait_sems, wait_values, VK_NULL_HANDLE, false);
4433 if (ret)
4434 return ret;
4435 ret = radv_alloc_sem_counts(device, &sem_info->signal, num_signal_sems, signal_sems, signal_values, fence, true);
4436 if (ret)
4437 radv_free_sem_info(sem_info);
4438
4439 /* caller can override these */
4440 sem_info->cs_emit_wait = true;
4441 sem_info->cs_emit_signal = true;
4442 return ret;
4443 }
4444
4445 static void
4446 radv_finalize_timelines(struct radv_device *device,
4447 uint32_t num_wait_sems,
4448 struct radv_semaphore_part **wait_sems,
4449 const uint64_t *wait_values,
4450 uint32_t num_signal_sems,
4451 struct radv_semaphore_part **signal_sems,
4452 const uint64_t *signal_values,
4453 struct list_head *processing_list)
4454 {
4455 for (uint32_t i = 0; i < num_wait_sems; ++i) {
4456 if (wait_sems[i] && wait_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4457 pthread_mutex_lock(&wait_sems[i]->timeline.mutex);
4458 struct radv_timeline_point *point =
4459 radv_timeline_find_point_at_least_locked(device, &wait_sems[i]->timeline, wait_values[i]);
4460 point->wait_count -= 2;
4461 pthread_mutex_unlock(&wait_sems[i]->timeline.mutex);
4462 }
4463 }
4464 for (uint32_t i = 0; i < num_signal_sems; ++i) {
4465 if (signal_sems[i] && signal_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4466 pthread_mutex_lock(&signal_sems[i]->timeline.mutex);
4467 struct radv_timeline_point *point =
4468 radv_timeline_find_point_at_least_locked(device, &signal_sems[i]->timeline, signal_values[i]);
4469 signal_sems[i]->timeline.highest_submitted =
4470 MAX2(signal_sems[i]->timeline.highest_submitted, point->value);
4471 point->wait_count -= 2;
4472 radv_timeline_trigger_waiters_locked(&signal_sems[i]->timeline, processing_list);
4473 pthread_mutex_unlock(&signal_sems[i]->timeline.mutex);
4474 }
4475 }
4476 }
4477
4478 static void
4479 radv_sparse_buffer_bind_memory(struct radv_device *device,
4480 const VkSparseBufferMemoryBindInfo *bind)
4481 {
4482 RADV_FROM_HANDLE(radv_buffer, buffer, bind->buffer);
4483
4484 for (uint32_t i = 0; i < bind->bindCount; ++i) {
4485 struct radv_device_memory *mem = NULL;
4486
4487 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
4488 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
4489
4490 device->ws->buffer_virtual_bind(buffer->bo,
4491 bind->pBinds[i].resourceOffset,
4492 bind->pBinds[i].size,
4493 mem ? mem->bo : NULL,
4494 bind->pBinds[i].memoryOffset);
4495 }
4496 }
4497
4498 static void
4499 radv_sparse_image_opaque_bind_memory(struct radv_device *device,
4500 const VkSparseImageOpaqueMemoryBindInfo *bind)
4501 {
4502 RADV_FROM_HANDLE(radv_image, image, bind->image);
4503
4504 for (uint32_t i = 0; i < bind->bindCount; ++i) {
4505 struct radv_device_memory *mem = NULL;
4506
4507 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
4508 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
4509
4510 device->ws->buffer_virtual_bind(image->bo,
4511 bind->pBinds[i].resourceOffset,
4512 bind->pBinds[i].size,
4513 mem ? mem->bo : NULL,
4514 bind->pBinds[i].memoryOffset);
4515 }
4516 }
4517
4518 static VkResult
4519 radv_get_preambles(struct radv_queue *queue,
4520 const VkCommandBuffer *cmd_buffers,
4521 uint32_t cmd_buffer_count,
4522 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
4523 struct radeon_cmdbuf **initial_preamble_cs,
4524 struct radeon_cmdbuf **continue_preamble_cs)
4525 {
4526 uint32_t scratch_size_per_wave = 0, waves_wanted = 0;
4527 uint32_t compute_scratch_size_per_wave = 0, compute_waves_wanted = 0;
4528 uint32_t esgs_ring_size = 0, gsvs_ring_size = 0;
4529 bool tess_rings_needed = false;
4530 bool gds_needed = false;
4531 bool gds_oa_needed = false;
4532 bool sample_positions_needed = false;
4533
4534 for (uint32_t j = 0; j < cmd_buffer_count; j++) {
4535 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
4536 cmd_buffers[j]);
4537
4538 scratch_size_per_wave = MAX2(scratch_size_per_wave, cmd_buffer->scratch_size_per_wave_needed);
4539 waves_wanted = MAX2(waves_wanted, cmd_buffer->scratch_waves_wanted);
4540 compute_scratch_size_per_wave = MAX2(compute_scratch_size_per_wave,
4541 cmd_buffer->compute_scratch_size_per_wave_needed);
4542 compute_waves_wanted = MAX2(compute_waves_wanted,
4543 cmd_buffer->compute_scratch_waves_wanted);
4544 esgs_ring_size = MAX2(esgs_ring_size, cmd_buffer->esgs_ring_size_needed);
4545 gsvs_ring_size = MAX2(gsvs_ring_size, cmd_buffer->gsvs_ring_size_needed);
4546 tess_rings_needed |= cmd_buffer->tess_rings_needed;
4547 gds_needed |= cmd_buffer->gds_needed;
4548 gds_oa_needed |= cmd_buffer->gds_oa_needed;
4549 sample_positions_needed |= cmd_buffer->sample_positions_needed;
4550 }
4551
4552 return radv_get_preamble_cs(queue, scratch_size_per_wave, waves_wanted,
4553 compute_scratch_size_per_wave, compute_waves_wanted,
4554 esgs_ring_size, gsvs_ring_size, tess_rings_needed,
4555 gds_needed, gds_oa_needed, sample_positions_needed,
4556 initial_full_flush_preamble_cs,
4557 initial_preamble_cs, continue_preamble_cs);
4558 }
4559
4560 struct radv_deferred_queue_submission {
4561 struct radv_queue *queue;
4562 VkCommandBuffer *cmd_buffers;
4563 uint32_t cmd_buffer_count;
4564
4565 /* Sparse bindings that happen on a queue. */
4566 VkSparseBufferMemoryBindInfo *buffer_binds;
4567 uint32_t buffer_bind_count;
4568 VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
4569 uint32_t image_opaque_bind_count;
4570
4571 bool flush_caches;
4572 VkShaderStageFlags wait_dst_stage_mask;
4573 struct radv_semaphore_part **wait_semaphores;
4574 uint32_t wait_semaphore_count;
4575 struct radv_semaphore_part **signal_semaphores;
4576 uint32_t signal_semaphore_count;
4577 VkFence fence;
4578
4579 uint64_t *wait_values;
4580 uint64_t *signal_values;
4581
4582 struct radv_semaphore_part *temporary_semaphore_parts;
4583 uint32_t temporary_semaphore_part_count;
4584
4585 struct list_head queue_pending_list;
4586 uint32_t submission_wait_count;
4587 struct radv_timeline_waiter *wait_nodes;
4588
4589 struct list_head processing_list;
4590 };
4591
4592 struct radv_queue_submission {
4593 const VkCommandBuffer *cmd_buffers;
4594 uint32_t cmd_buffer_count;
4595
4596 /* Sparse bindings that happen on a queue. */
4597 const VkSparseBufferMemoryBindInfo *buffer_binds;
4598 uint32_t buffer_bind_count;
4599 const VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
4600 uint32_t image_opaque_bind_count;
4601
4602 bool flush_caches;
4603 VkPipelineStageFlags wait_dst_stage_mask;
4604 const VkSemaphore *wait_semaphores;
4605 uint32_t wait_semaphore_count;
4606 const VkSemaphore *signal_semaphores;
4607 uint32_t signal_semaphore_count;
4608 VkFence fence;
4609
4610 const uint64_t *wait_values;
4611 uint32_t wait_value_count;
4612 const uint64_t *signal_values;
4613 uint32_t signal_value_count;
4614 };
4615
4616 static VkResult
4617 radv_create_deferred_submission(struct radv_queue *queue,
4618 const struct radv_queue_submission *submission,
4619 struct radv_deferred_queue_submission **out)
4620 {
4621 struct radv_deferred_queue_submission *deferred = NULL;
4622 size_t size = sizeof(struct radv_deferred_queue_submission);
4623
4624 uint32_t temporary_count = 0;
4625 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4626 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
4627 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE)
4628 ++temporary_count;
4629 }
4630
4631 size += submission->cmd_buffer_count * sizeof(VkCommandBuffer);
4632 size += submission->buffer_bind_count * sizeof(VkSparseBufferMemoryBindInfo);
4633 size += submission->image_opaque_bind_count * sizeof(VkSparseImageOpaqueMemoryBindInfo);
4634 size += submission->wait_semaphore_count * sizeof(struct radv_semaphore_part *);
4635 size += temporary_count * sizeof(struct radv_semaphore_part);
4636 size += submission->signal_semaphore_count * sizeof(struct radv_semaphore_part *);
4637 size += submission->wait_value_count * sizeof(uint64_t);
4638 size += submission->signal_value_count * sizeof(uint64_t);
4639 size += submission->wait_semaphore_count * sizeof(struct radv_timeline_waiter);
4640
4641 deferred = calloc(1, size);
4642 if (!deferred)
4643 return VK_ERROR_OUT_OF_HOST_MEMORY;
4644
4645 deferred->queue = queue;
4646
4647 deferred->cmd_buffers = (void*)(deferred + 1);
4648 deferred->cmd_buffer_count = submission->cmd_buffer_count;
4649 memcpy(deferred->cmd_buffers, submission->cmd_buffers,
4650 submission->cmd_buffer_count * sizeof(*deferred->cmd_buffers));
4651
4652 deferred->buffer_binds = (void*)(deferred->cmd_buffers + submission->cmd_buffer_count);
4653 deferred->buffer_bind_count = submission->buffer_bind_count;
4654 memcpy(deferred->buffer_binds, submission->buffer_binds,
4655 submission->buffer_bind_count * sizeof(*deferred->buffer_binds));
4656
4657 deferred->image_opaque_binds = (void*)(deferred->buffer_binds + submission->buffer_bind_count);
4658 deferred->image_opaque_bind_count = submission->image_opaque_bind_count;
4659 memcpy(deferred->image_opaque_binds, submission->image_opaque_binds,
4660 submission->image_opaque_bind_count * sizeof(*deferred->image_opaque_binds));
4661
4662 deferred->flush_caches = submission->flush_caches;
4663 deferred->wait_dst_stage_mask = submission->wait_dst_stage_mask;
4664
4665 deferred->wait_semaphores = (void*)(deferred->image_opaque_binds + deferred->image_opaque_bind_count);
4666 deferred->wait_semaphore_count = submission->wait_semaphore_count;
4667
4668 deferred->signal_semaphores = (void*)(deferred->wait_semaphores + deferred->wait_semaphore_count);
4669 deferred->signal_semaphore_count = submission->signal_semaphore_count;
4670
4671 deferred->fence = submission->fence;
4672
4673 deferred->temporary_semaphore_parts = (void*)(deferred->signal_semaphores + deferred->signal_semaphore_count);
4674 deferred->temporary_semaphore_part_count = temporary_count;
4675
4676 uint32_t temporary_idx = 0;
4677 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4678 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
4679 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE) {
4680 deferred->wait_semaphores[i] = &deferred->temporary_semaphore_parts[temporary_idx];
4681 deferred->temporary_semaphore_parts[temporary_idx] = semaphore->temporary;
4682 semaphore->temporary.kind = RADV_SEMAPHORE_NONE;
4683 ++temporary_idx;
4684 } else
4685 deferred->wait_semaphores[i] = &semaphore->permanent;
4686 }
4687
4688 for (uint32_t i = 0; i < submission->signal_semaphore_count; ++i) {
4689 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->signal_semaphores[i]);
4690 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE) {
4691 deferred->signal_semaphores[i] = &semaphore->temporary;
4692 } else {
4693 deferred->signal_semaphores[i] = &semaphore->permanent;
4694 }
4695 }
4696
4697 deferred->wait_values = (void*)(deferred->temporary_semaphore_parts + temporary_count);
4698 memcpy(deferred->wait_values, submission->wait_values, submission->wait_value_count * sizeof(uint64_t));
4699 deferred->signal_values = deferred->wait_values + submission->wait_value_count;
4700 memcpy(deferred->signal_values, submission->signal_values, submission->signal_value_count * sizeof(uint64_t));
4701
4702 deferred->wait_nodes = (void*)(deferred->signal_values + submission->signal_value_count);
4703 /* This is worst-case. radv_queue_enqueue_submission will fill in further, but this
4704 * ensure the submission is not accidentally triggered early when adding wait timelines. */
4705 deferred->submission_wait_count = 1 + submission->wait_semaphore_count;
4706
4707 *out = deferred;
4708 return VK_SUCCESS;
4709 }
4710
4711 static void
4712 radv_queue_enqueue_submission(struct radv_deferred_queue_submission *submission,
4713 struct list_head *processing_list)
4714 {
4715 uint32_t wait_cnt = 0;
4716 struct radv_timeline_waiter *waiter = submission->wait_nodes;
4717 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4718 if (submission->wait_semaphores[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4719 pthread_mutex_lock(&submission->wait_semaphores[i]->timeline.mutex);
4720 if (submission->wait_semaphores[i]->timeline.highest_submitted < submission->wait_values[i]) {
4721 ++wait_cnt;
4722 waiter->value = submission->wait_values[i];
4723 waiter->submission = submission;
4724 list_addtail(&waiter->list, &submission->wait_semaphores[i]->timeline.waiters);
4725 ++waiter;
4726 }
4727 pthread_mutex_unlock(&submission->wait_semaphores[i]->timeline.mutex);
4728 }
4729 }
4730
4731 pthread_mutex_lock(&submission->queue->pending_mutex);
4732
4733 bool is_first = list_is_empty(&submission->queue->pending_submissions);
4734 list_addtail(&submission->queue_pending_list, &submission->queue->pending_submissions);
4735
4736 pthread_mutex_unlock(&submission->queue->pending_mutex);
4737
4738 /* If there is already a submission in the queue, that will decrement the counter by 1 when
4739 * submitted, but if the queue was empty, we decrement ourselves as there is no previous
4740 * submission. */
4741 uint32_t decrement = submission->wait_semaphore_count - wait_cnt + (is_first ? 1 : 0);
4742 if (__atomic_sub_fetch(&submission->submission_wait_count, decrement, __ATOMIC_ACQ_REL) == 0) {
4743 list_addtail(&submission->processing_list, processing_list);
4744 }
4745 }
4746
4747 static void
4748 radv_queue_submission_update_queue(struct radv_deferred_queue_submission *submission,
4749 struct list_head *processing_list)
4750 {
4751 pthread_mutex_lock(&submission->queue->pending_mutex);
4752 list_del(&submission->queue_pending_list);
4753
4754 /* trigger the next submission in the queue. */
4755 if (!list_is_empty(&submission->queue->pending_submissions)) {
4756 struct radv_deferred_queue_submission *next_submission =
4757 list_first_entry(&submission->queue->pending_submissions,
4758 struct radv_deferred_queue_submission,
4759 queue_pending_list);
4760 if (p_atomic_dec_zero(&next_submission->submission_wait_count)) {
4761 list_addtail(&next_submission->processing_list, processing_list);
4762 }
4763 }
4764 pthread_mutex_unlock(&submission->queue->pending_mutex);
4765
4766 pthread_cond_broadcast(&submission->queue->device->timeline_cond);
4767 }
4768
4769 static VkResult
4770 radv_queue_submit_deferred(struct radv_deferred_queue_submission *submission,
4771 struct list_head *processing_list)
4772 {
4773 RADV_FROM_HANDLE(radv_fence, fence, submission->fence);
4774 struct radv_queue *queue = submission->queue;
4775 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
4776 uint32_t max_cs_submission = queue->device->trace_bo ? 1 : RADV_MAX_IBS_PER_SUBMIT;
4777 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
4778 bool do_flush = submission->flush_caches || submission->wait_dst_stage_mask;
4779 bool can_patch = true;
4780 uint32_t advance;
4781 struct radv_winsys_sem_info sem_info;
4782 VkResult result;
4783 int ret;
4784 struct radeon_cmdbuf *initial_preamble_cs = NULL;
4785 struct radeon_cmdbuf *initial_flush_preamble_cs = NULL;
4786 struct radeon_cmdbuf *continue_preamble_cs = NULL;
4787
4788 result = radv_get_preambles(queue, submission->cmd_buffers,
4789 submission->cmd_buffer_count,
4790 &initial_preamble_cs,
4791 &initial_flush_preamble_cs,
4792 &continue_preamble_cs);
4793 if (result != VK_SUCCESS)
4794 goto fail;
4795
4796 result = radv_alloc_sem_info(queue->device,
4797 &sem_info,
4798 submission->wait_semaphore_count,
4799 submission->wait_semaphores,
4800 submission->wait_values,
4801 submission->signal_semaphore_count,
4802 submission->signal_semaphores,
4803 submission->signal_values,
4804 submission->fence);
4805 if (result != VK_SUCCESS)
4806 goto fail;
4807
4808 for (uint32_t i = 0; i < submission->buffer_bind_count; ++i) {
4809 radv_sparse_buffer_bind_memory(queue->device,
4810 submission->buffer_binds + i);
4811 }
4812
4813 for (uint32_t i = 0; i < submission->image_opaque_bind_count; ++i) {
4814 radv_sparse_image_opaque_bind_memory(queue->device,
4815 submission->image_opaque_binds + i);
4816 }
4817
4818 if (!submission->cmd_buffer_count) {
4819 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx,
4820 &queue->device->empty_cs[queue->queue_family_index],
4821 1, NULL, NULL,
4822 &sem_info, NULL,
4823 false, base_fence);
4824 if (ret) {
4825 radv_loge("failed to submit CS\n");
4826 abort();
4827 }
4828
4829 goto success;
4830 } else {
4831 struct radeon_cmdbuf **cs_array = malloc(sizeof(struct radeon_cmdbuf *) *
4832 (submission->cmd_buffer_count));
4833
4834 for (uint32_t j = 0; j < submission->cmd_buffer_count; j++) {
4835 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, submission->cmd_buffers[j]);
4836 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
4837
4838 cs_array[j] = cmd_buffer->cs;
4839 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
4840 can_patch = false;
4841
4842 cmd_buffer->status = RADV_CMD_BUFFER_STATUS_PENDING;
4843 }
4844
4845 for (uint32_t j = 0; j < submission->cmd_buffer_count; j += advance) {
4846 struct radeon_cmdbuf *initial_preamble = (do_flush && !j) ? initial_flush_preamble_cs : initial_preamble_cs;
4847 const struct radv_winsys_bo_list *bo_list = NULL;
4848
4849 advance = MIN2(max_cs_submission,
4850 submission->cmd_buffer_count - j);
4851
4852 if (queue->device->trace_bo)
4853 *queue->device->trace_id_ptr = 0;
4854
4855 sem_info.cs_emit_wait = j == 0;
4856 sem_info.cs_emit_signal = j + advance == submission->cmd_buffer_count;
4857
4858 if (unlikely(queue->device->use_global_bo_list)) {
4859 pthread_mutex_lock(&queue->device->bo_list.mutex);
4860 bo_list = &queue->device->bo_list.list;
4861 }
4862
4863 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, cs_array + j,
4864 advance, initial_preamble, continue_preamble_cs,
4865 &sem_info, bo_list,
4866 can_patch, base_fence);
4867
4868 if (unlikely(queue->device->use_global_bo_list))
4869 pthread_mutex_unlock(&queue->device->bo_list.mutex);
4870
4871 if (ret) {
4872 radv_loge("failed to submit CS\n");
4873 abort();
4874 }
4875 if (queue->device->trace_bo) {
4876 radv_check_gpu_hangs(queue, cs_array[j]);
4877 }
4878 }
4879
4880 free(cs_array);
4881 }
4882
4883 success:
4884 radv_free_temp_syncobjs(queue->device,
4885 submission->temporary_semaphore_part_count,
4886 submission->temporary_semaphore_parts);
4887 radv_finalize_timelines(queue->device,
4888 submission->wait_semaphore_count,
4889 submission->wait_semaphores,
4890 submission->wait_values,
4891 submission->signal_semaphore_count,
4892 submission->signal_semaphores,
4893 submission->signal_values,
4894 processing_list);
4895 /* Has to happen after timeline finalization to make sure the
4896 * condition variable is only triggered when timelines and queue have
4897 * been updated. */
4898 radv_queue_submission_update_queue(submission, processing_list);
4899 radv_free_sem_info(&sem_info);
4900 free(submission);
4901 return VK_SUCCESS;
4902
4903 fail:
4904 radv_free_temp_syncobjs(queue->device,
4905 submission->temporary_semaphore_part_count,
4906 submission->temporary_semaphore_parts);
4907 free(submission);
4908 return VK_ERROR_DEVICE_LOST;
4909 }
4910
4911 static VkResult
4912 radv_process_submissions(struct list_head *processing_list)
4913 {
4914 while(!list_is_empty(processing_list)) {
4915 struct radv_deferred_queue_submission *submission =
4916 list_first_entry(processing_list, struct radv_deferred_queue_submission, processing_list);
4917 list_del(&submission->processing_list);
4918
4919 VkResult result = radv_queue_submit_deferred(submission, processing_list);
4920 if (result != VK_SUCCESS)
4921 return result;
4922 }
4923 return VK_SUCCESS;
4924 }
4925
4926 static VkResult radv_queue_submit(struct radv_queue *queue,
4927 const struct radv_queue_submission *submission)
4928 {
4929 struct radv_deferred_queue_submission *deferred = NULL;
4930
4931 VkResult result = radv_create_deferred_submission(queue, submission, &deferred);
4932 if (result != VK_SUCCESS)
4933 return result;
4934
4935 struct list_head processing_list;
4936 list_inithead(&processing_list);
4937
4938 radv_queue_enqueue_submission(deferred, &processing_list);
4939 return radv_process_submissions(&processing_list);
4940 }
4941
4942 bool
4943 radv_queue_internal_submit(struct radv_queue *queue, struct radeon_cmdbuf *cs)
4944 {
4945 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
4946 struct radv_winsys_sem_info sem_info;
4947 VkResult result;
4948 int ret;
4949
4950 result = radv_alloc_sem_info(queue->device, &sem_info, 0, NULL, 0, 0,
4951 0, NULL, VK_NULL_HANDLE);
4952 if (result != VK_SUCCESS)
4953 return false;
4954
4955 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, &cs, 1, NULL,
4956 NULL, &sem_info, NULL, false, NULL);
4957 radv_free_sem_info(&sem_info);
4958 return !ret;
4959 }
4960
4961 /* Signals fence as soon as all the work currently put on queue is done. */
4962 static VkResult radv_signal_fence(struct radv_queue *queue,
4963 VkFence fence)
4964 {
4965 return radv_queue_submit(queue, &(struct radv_queue_submission) {
4966 .fence = fence
4967 });
4968 }
4969
4970 static bool radv_submit_has_effects(const VkSubmitInfo *info)
4971 {
4972 return info->commandBufferCount ||
4973 info->waitSemaphoreCount ||
4974 info->signalSemaphoreCount;
4975 }
4976
4977 VkResult radv_QueueSubmit(
4978 VkQueue _queue,
4979 uint32_t submitCount,
4980 const VkSubmitInfo* pSubmits,
4981 VkFence fence)
4982 {
4983 RADV_FROM_HANDLE(radv_queue, queue, _queue);
4984 VkResult result;
4985 uint32_t fence_idx = 0;
4986 bool flushed_caches = false;
4987
4988 if (fence != VK_NULL_HANDLE) {
4989 for (uint32_t i = 0; i < submitCount; ++i)
4990 if (radv_submit_has_effects(pSubmits + i))
4991 fence_idx = i;
4992 } else
4993 fence_idx = UINT32_MAX;
4994
4995 for (uint32_t i = 0; i < submitCount; i++) {
4996 if (!radv_submit_has_effects(pSubmits + i) && fence_idx != i)
4997 continue;
4998
4999 VkPipelineStageFlags wait_dst_stage_mask = 0;
5000 for (unsigned j = 0; j < pSubmits[i].waitSemaphoreCount; ++j) {
5001 wait_dst_stage_mask |= pSubmits[i].pWaitDstStageMask[j];
5002 }
5003
5004 const VkTimelineSemaphoreSubmitInfo *timeline_info =
5005 vk_find_struct_const(pSubmits[i].pNext, TIMELINE_SEMAPHORE_SUBMIT_INFO);
5006
5007 result = radv_queue_submit(queue, &(struct radv_queue_submission) {
5008 .cmd_buffers = pSubmits[i].pCommandBuffers,
5009 .cmd_buffer_count = pSubmits[i].commandBufferCount,
5010 .wait_dst_stage_mask = wait_dst_stage_mask,
5011 .flush_caches = !flushed_caches,
5012 .wait_semaphores = pSubmits[i].pWaitSemaphores,
5013 .wait_semaphore_count = pSubmits[i].waitSemaphoreCount,
5014 .signal_semaphores = pSubmits[i].pSignalSemaphores,
5015 .signal_semaphore_count = pSubmits[i].signalSemaphoreCount,
5016 .fence = i == fence_idx ? fence : VK_NULL_HANDLE,
5017 .wait_values = timeline_info ? timeline_info->pWaitSemaphoreValues : NULL,
5018 .wait_value_count = timeline_info && timeline_info->pWaitSemaphoreValues ? timeline_info->waitSemaphoreValueCount : 0,
5019 .signal_values = timeline_info ? timeline_info->pSignalSemaphoreValues : NULL,
5020 .signal_value_count = timeline_info && timeline_info->pSignalSemaphoreValues ? timeline_info->signalSemaphoreValueCount : 0,
5021 });
5022 if (result != VK_SUCCESS)
5023 return result;
5024
5025 flushed_caches = true;
5026 }
5027
5028 if (fence != VK_NULL_HANDLE && !submitCount) {
5029 result = radv_signal_fence(queue, fence);
5030 if (result != VK_SUCCESS)
5031 return result;
5032 }
5033
5034 return VK_SUCCESS;
5035 }
5036
5037 VkResult radv_QueueWaitIdle(
5038 VkQueue _queue)
5039 {
5040 RADV_FROM_HANDLE(radv_queue, queue, _queue);
5041
5042 pthread_mutex_lock(&queue->pending_mutex);
5043 while (!list_is_empty(&queue->pending_submissions)) {
5044 pthread_cond_wait(&queue->device->timeline_cond, &queue->pending_mutex);
5045 }
5046 pthread_mutex_unlock(&queue->pending_mutex);
5047
5048 queue->device->ws->ctx_wait_idle(queue->hw_ctx,
5049 radv_queue_family_to_ring(queue->queue_family_index),
5050 queue->queue_idx);
5051 return VK_SUCCESS;
5052 }
5053
5054 VkResult radv_DeviceWaitIdle(
5055 VkDevice _device)
5056 {
5057 RADV_FROM_HANDLE(radv_device, device, _device);
5058
5059 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
5060 for (unsigned q = 0; q < device->queue_count[i]; q++) {
5061 radv_QueueWaitIdle(radv_queue_to_handle(&device->queues[i][q]));
5062 }
5063 }
5064 return VK_SUCCESS;
5065 }
5066
5067 VkResult radv_EnumerateInstanceExtensionProperties(
5068 const char* pLayerName,
5069 uint32_t* pPropertyCount,
5070 VkExtensionProperties* pProperties)
5071 {
5072 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
5073
5074 for (int i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; i++) {
5075 if (radv_instance_extensions_supported.extensions[i]) {
5076 vk_outarray_append(&out, prop) {
5077 *prop = radv_instance_extensions[i];
5078 }
5079 }
5080 }
5081
5082 return vk_outarray_status(&out);
5083 }
5084
5085 VkResult radv_EnumerateDeviceExtensionProperties(
5086 VkPhysicalDevice physicalDevice,
5087 const char* pLayerName,
5088 uint32_t* pPropertyCount,
5089 VkExtensionProperties* pProperties)
5090 {
5091 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
5092 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
5093
5094 for (int i = 0; i < RADV_DEVICE_EXTENSION_COUNT; i++) {
5095 if (device->supported_extensions.extensions[i]) {
5096 vk_outarray_append(&out, prop) {
5097 *prop = radv_device_extensions[i];
5098 }
5099 }
5100 }
5101
5102 return vk_outarray_status(&out);
5103 }
5104
5105 PFN_vkVoidFunction radv_GetInstanceProcAddr(
5106 VkInstance _instance,
5107 const char* pName)
5108 {
5109 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5110
5111 /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
5112 * when we have to return valid function pointers, NULL, or it's left
5113 * undefined. See the table for exact details.
5114 */
5115 if (pName == NULL)
5116 return NULL;
5117
5118 #define LOOKUP_RADV_ENTRYPOINT(entrypoint) \
5119 if (strcmp(pName, "vk" #entrypoint) == 0) \
5120 return (PFN_vkVoidFunction)radv_##entrypoint
5121
5122 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
5123 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceLayerProperties);
5124 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceVersion);
5125 LOOKUP_RADV_ENTRYPOINT(CreateInstance);
5126
5127 /* GetInstanceProcAddr() can also be called with a NULL instance.
5128 * See https://gitlab.khronos.org/vulkan/vulkan/issues/2057
5129 */
5130 LOOKUP_RADV_ENTRYPOINT(GetInstanceProcAddr);
5131
5132 #undef LOOKUP_RADV_ENTRYPOINT
5133
5134 if (instance == NULL)
5135 return NULL;
5136
5137 int idx = radv_get_instance_entrypoint_index(pName);
5138 if (idx >= 0)
5139 return instance->dispatch.entrypoints[idx];
5140
5141 idx = radv_get_physical_device_entrypoint_index(pName);
5142 if (idx >= 0)
5143 return instance->physical_device_dispatch.entrypoints[idx];
5144
5145 idx = radv_get_device_entrypoint_index(pName);
5146 if (idx >= 0)
5147 return instance->device_dispatch.entrypoints[idx];
5148
5149 return NULL;
5150 }
5151
5152 /* The loader wants us to expose a second GetInstanceProcAddr function
5153 * to work around certain LD_PRELOAD issues seen in apps.
5154 */
5155 PUBLIC
5156 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
5157 VkInstance instance,
5158 const char* pName);
5159
5160 PUBLIC
5161 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
5162 VkInstance instance,
5163 const char* pName)
5164 {
5165 return radv_GetInstanceProcAddr(instance, pName);
5166 }
5167
5168 PUBLIC
5169 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
5170 VkInstance _instance,
5171 const char* pName);
5172
5173 PUBLIC
5174 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
5175 VkInstance _instance,
5176 const char* pName)
5177 {
5178 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5179
5180 if (!pName || !instance)
5181 return NULL;
5182
5183 int idx = radv_get_physical_device_entrypoint_index(pName);
5184 if (idx < 0)
5185 return NULL;
5186
5187 return instance->physical_device_dispatch.entrypoints[idx];
5188 }
5189
5190 PFN_vkVoidFunction radv_GetDeviceProcAddr(
5191 VkDevice _device,
5192 const char* pName)
5193 {
5194 RADV_FROM_HANDLE(radv_device, device, _device);
5195
5196 if (!device || !pName)
5197 return NULL;
5198
5199 int idx = radv_get_device_entrypoint_index(pName);
5200 if (idx < 0)
5201 return NULL;
5202
5203 return device->dispatch.entrypoints[idx];
5204 }
5205
5206 bool radv_get_memory_fd(struct radv_device *device,
5207 struct radv_device_memory *memory,
5208 int *pFD)
5209 {
5210 struct radeon_bo_metadata metadata;
5211
5212 if (memory->image) {
5213 if (memory->image->tiling != VK_IMAGE_TILING_LINEAR)
5214 radv_init_metadata(device, memory->image, &metadata);
5215 device->ws->buffer_set_metadata(memory->bo, &metadata);
5216 }
5217
5218 return device->ws->buffer_get_fd(device->ws, memory->bo,
5219 pFD);
5220 }
5221
5222
5223 static void radv_free_memory(struct radv_device *device,
5224 const VkAllocationCallbacks* pAllocator,
5225 struct radv_device_memory *mem)
5226 {
5227 if (mem == NULL)
5228 return;
5229
5230 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
5231 if (mem->android_hardware_buffer)
5232 AHardwareBuffer_release(mem->android_hardware_buffer);
5233 #endif
5234
5235 if (mem->bo) {
5236 if (device->overallocation_disallowed) {
5237 mtx_lock(&device->overallocation_mutex);
5238 device->allocated_memory_size[mem->heap_index] -= mem->alloc_size;
5239 mtx_unlock(&device->overallocation_mutex);
5240 }
5241
5242 radv_bo_list_remove(device, mem->bo);
5243 device->ws->buffer_destroy(mem->bo);
5244 mem->bo = NULL;
5245 }
5246
5247 vk_object_base_finish(&mem->base);
5248 vk_free2(&device->vk.alloc, pAllocator, mem);
5249 }
5250
5251 static VkResult radv_alloc_memory(struct radv_device *device,
5252 const VkMemoryAllocateInfo* pAllocateInfo,
5253 const VkAllocationCallbacks* pAllocator,
5254 VkDeviceMemory* pMem)
5255 {
5256 struct radv_device_memory *mem;
5257 VkResult result;
5258 enum radeon_bo_domain domain;
5259 uint32_t flags = 0;
5260
5261 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
5262
5263 const VkImportMemoryFdInfoKHR *import_info =
5264 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
5265 const VkMemoryDedicatedAllocateInfo *dedicate_info =
5266 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);
5267 const VkExportMemoryAllocateInfo *export_info =
5268 vk_find_struct_const(pAllocateInfo->pNext, EXPORT_MEMORY_ALLOCATE_INFO);
5269 const struct VkImportAndroidHardwareBufferInfoANDROID *ahb_import_info =
5270 vk_find_struct_const(pAllocateInfo->pNext,
5271 IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID);
5272 const VkImportMemoryHostPointerInfoEXT *host_ptr_info =
5273 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_HOST_POINTER_INFO_EXT);
5274
5275 const struct wsi_memory_allocate_info *wsi_info =
5276 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
5277
5278 if (pAllocateInfo->allocationSize == 0 && !ahb_import_info &&
5279 !(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID))) {
5280 /* Apparently, this is allowed */
5281 *pMem = VK_NULL_HANDLE;
5282 return VK_SUCCESS;
5283 }
5284
5285 mem = vk_zalloc2(&device->vk.alloc, pAllocator, sizeof(*mem), 8,
5286 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5287 if (mem == NULL)
5288 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5289
5290 vk_object_base_init(&device->vk, &mem->base,
5291 VK_OBJECT_TYPE_DEVICE_MEMORY);
5292
5293 if (wsi_info && wsi_info->implicit_sync)
5294 flags |= RADEON_FLAG_IMPLICIT_SYNC;
5295
5296 if (dedicate_info) {
5297 mem->image = radv_image_from_handle(dedicate_info->image);
5298 mem->buffer = radv_buffer_from_handle(dedicate_info->buffer);
5299 } else {
5300 mem->image = NULL;
5301 mem->buffer = NULL;
5302 }
5303
5304 float priority_float = 0.5;
5305 const struct VkMemoryPriorityAllocateInfoEXT *priority_ext =
5306 vk_find_struct_const(pAllocateInfo->pNext,
5307 MEMORY_PRIORITY_ALLOCATE_INFO_EXT);
5308 if (priority_ext)
5309 priority_float = priority_ext->priority;
5310
5311 unsigned priority = MIN2(RADV_BO_PRIORITY_APPLICATION_MAX - 1,
5312 (int)(priority_float * RADV_BO_PRIORITY_APPLICATION_MAX));
5313
5314 mem->user_ptr = NULL;
5315 mem->bo = NULL;
5316
5317 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
5318 mem->android_hardware_buffer = NULL;
5319 #endif
5320
5321 if (ahb_import_info) {
5322 result = radv_import_ahb_memory(device, mem, priority, ahb_import_info);
5323 if (result != VK_SUCCESS)
5324 goto fail;
5325 } else if(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)) {
5326 result = radv_create_ahb_memory(device, mem, priority, pAllocateInfo);
5327 if (result != VK_SUCCESS)
5328 goto fail;
5329 } else if (import_info) {
5330 assert(import_info->handleType ==
5331 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
5332 import_info->handleType ==
5333 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
5334 mem->bo = device->ws->buffer_from_fd(device->ws, import_info->fd,
5335 priority, NULL);
5336 if (!mem->bo) {
5337 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
5338 goto fail;
5339 } else {
5340 close(import_info->fd);
5341 }
5342 } else if (host_ptr_info) {
5343 assert(host_ptr_info->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
5344 mem->bo = device->ws->buffer_from_ptr(device->ws, host_ptr_info->pHostPointer,
5345 pAllocateInfo->allocationSize,
5346 priority);
5347 if (!mem->bo) {
5348 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
5349 goto fail;
5350 } else {
5351 mem->user_ptr = host_ptr_info->pHostPointer;
5352 }
5353 } else {
5354 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
5355 uint32_t heap_index;
5356
5357 heap_index = device->physical_device->memory_properties.memoryTypes[pAllocateInfo->memoryTypeIndex].heapIndex;
5358 domain = device->physical_device->memory_domains[pAllocateInfo->memoryTypeIndex];
5359 flags |= device->physical_device->memory_flags[pAllocateInfo->memoryTypeIndex];
5360
5361 if (!dedicate_info && !import_info && (!export_info || !export_info->handleTypes)) {
5362 flags |= RADEON_FLAG_NO_INTERPROCESS_SHARING;
5363 if (device->use_global_bo_list) {
5364 flags |= RADEON_FLAG_PREFER_LOCAL_BO;
5365 }
5366 }
5367
5368 if (device->overallocation_disallowed) {
5369 uint64_t total_size =
5370 device->physical_device->memory_properties.memoryHeaps[heap_index].size;
5371
5372 mtx_lock(&device->overallocation_mutex);
5373 if (device->allocated_memory_size[heap_index] + alloc_size > total_size) {
5374 mtx_unlock(&device->overallocation_mutex);
5375 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
5376 goto fail;
5377 }
5378 device->allocated_memory_size[heap_index] += alloc_size;
5379 mtx_unlock(&device->overallocation_mutex);
5380 }
5381
5382 mem->bo = device->ws->buffer_create(device->ws, alloc_size, device->physical_device->rad_info.max_alignment,
5383 domain, flags, priority);
5384
5385 if (!mem->bo) {
5386 if (device->overallocation_disallowed) {
5387 mtx_lock(&device->overallocation_mutex);
5388 device->allocated_memory_size[heap_index] -= alloc_size;
5389 mtx_unlock(&device->overallocation_mutex);
5390 }
5391 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
5392 goto fail;
5393 }
5394
5395 mem->heap_index = heap_index;
5396 mem->alloc_size = alloc_size;
5397 }
5398
5399 if (!wsi_info) {
5400 result = radv_bo_list_add(device, mem->bo);
5401 if (result != VK_SUCCESS)
5402 goto fail;
5403 }
5404
5405 *pMem = radv_device_memory_to_handle(mem);
5406
5407 return VK_SUCCESS;
5408
5409 fail:
5410 radv_free_memory(device, pAllocator,mem);
5411
5412 return result;
5413 }
5414
5415 VkResult radv_AllocateMemory(
5416 VkDevice _device,
5417 const VkMemoryAllocateInfo* pAllocateInfo,
5418 const VkAllocationCallbacks* pAllocator,
5419 VkDeviceMemory* pMem)
5420 {
5421 RADV_FROM_HANDLE(radv_device, device, _device);
5422 return radv_alloc_memory(device, pAllocateInfo, pAllocator, pMem);
5423 }
5424
5425 void radv_FreeMemory(
5426 VkDevice _device,
5427 VkDeviceMemory _mem,
5428 const VkAllocationCallbacks* pAllocator)
5429 {
5430 RADV_FROM_HANDLE(radv_device, device, _device);
5431 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
5432
5433 radv_free_memory(device, pAllocator, mem);
5434 }
5435
5436 VkResult radv_MapMemory(
5437 VkDevice _device,
5438 VkDeviceMemory _memory,
5439 VkDeviceSize offset,
5440 VkDeviceSize size,
5441 VkMemoryMapFlags flags,
5442 void** ppData)
5443 {
5444 RADV_FROM_HANDLE(radv_device, device, _device);
5445 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
5446
5447 if (mem == NULL) {
5448 *ppData = NULL;
5449 return VK_SUCCESS;
5450 }
5451
5452 if (mem->user_ptr)
5453 *ppData = mem->user_ptr;
5454 else
5455 *ppData = device->ws->buffer_map(mem->bo);
5456
5457 if (*ppData) {
5458 *ppData += offset;
5459 return VK_SUCCESS;
5460 }
5461
5462 return vk_error(device->instance, VK_ERROR_MEMORY_MAP_FAILED);
5463 }
5464
5465 void radv_UnmapMemory(
5466 VkDevice _device,
5467 VkDeviceMemory _memory)
5468 {
5469 RADV_FROM_HANDLE(radv_device, device, _device);
5470 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
5471
5472 if (mem == NULL)
5473 return;
5474
5475 if (mem->user_ptr == NULL)
5476 device->ws->buffer_unmap(mem->bo);
5477 }
5478
5479 VkResult radv_FlushMappedMemoryRanges(
5480 VkDevice _device,
5481 uint32_t memoryRangeCount,
5482 const VkMappedMemoryRange* pMemoryRanges)
5483 {
5484 return VK_SUCCESS;
5485 }
5486
5487 VkResult radv_InvalidateMappedMemoryRanges(
5488 VkDevice _device,
5489 uint32_t memoryRangeCount,
5490 const VkMappedMemoryRange* pMemoryRanges)
5491 {
5492 return VK_SUCCESS;
5493 }
5494
5495 void radv_GetBufferMemoryRequirements(
5496 VkDevice _device,
5497 VkBuffer _buffer,
5498 VkMemoryRequirements* pMemoryRequirements)
5499 {
5500 RADV_FROM_HANDLE(radv_device, device, _device);
5501 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
5502
5503 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
5504
5505 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
5506 pMemoryRequirements->alignment = 4096;
5507 else
5508 pMemoryRequirements->alignment = 16;
5509
5510 pMemoryRequirements->size = align64(buffer->size, pMemoryRequirements->alignment);
5511 }
5512
5513 void radv_GetBufferMemoryRequirements2(
5514 VkDevice device,
5515 const VkBufferMemoryRequirementsInfo2 *pInfo,
5516 VkMemoryRequirements2 *pMemoryRequirements)
5517 {
5518 radv_GetBufferMemoryRequirements(device, pInfo->buffer,
5519 &pMemoryRequirements->memoryRequirements);
5520 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
5521 switch (ext->sType) {
5522 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
5523 VkMemoryDedicatedRequirements *req =
5524 (VkMemoryDedicatedRequirements *) ext;
5525 req->requiresDedicatedAllocation = false;
5526 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
5527 break;
5528 }
5529 default:
5530 break;
5531 }
5532 }
5533 }
5534
5535 void radv_GetImageMemoryRequirements(
5536 VkDevice _device,
5537 VkImage _image,
5538 VkMemoryRequirements* pMemoryRequirements)
5539 {
5540 RADV_FROM_HANDLE(radv_device, device, _device);
5541 RADV_FROM_HANDLE(radv_image, image, _image);
5542
5543 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
5544
5545 pMemoryRequirements->size = image->size;
5546 pMemoryRequirements->alignment = image->alignment;
5547 }
5548
5549 void radv_GetImageMemoryRequirements2(
5550 VkDevice device,
5551 const VkImageMemoryRequirementsInfo2 *pInfo,
5552 VkMemoryRequirements2 *pMemoryRequirements)
5553 {
5554 radv_GetImageMemoryRequirements(device, pInfo->image,
5555 &pMemoryRequirements->memoryRequirements);
5556
5557 RADV_FROM_HANDLE(radv_image, image, pInfo->image);
5558
5559 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
5560 switch (ext->sType) {
5561 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
5562 VkMemoryDedicatedRequirements *req =
5563 (VkMemoryDedicatedRequirements *) ext;
5564 req->requiresDedicatedAllocation = image->shareable &&
5565 image->tiling != VK_IMAGE_TILING_LINEAR;
5566 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
5567 break;
5568 }
5569 default:
5570 break;
5571 }
5572 }
5573 }
5574
5575 void radv_GetImageSparseMemoryRequirements(
5576 VkDevice device,
5577 VkImage image,
5578 uint32_t* pSparseMemoryRequirementCount,
5579 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
5580 {
5581 stub();
5582 }
5583
5584 void radv_GetImageSparseMemoryRequirements2(
5585 VkDevice device,
5586 const VkImageSparseMemoryRequirementsInfo2 *pInfo,
5587 uint32_t* pSparseMemoryRequirementCount,
5588 VkSparseImageMemoryRequirements2 *pSparseMemoryRequirements)
5589 {
5590 stub();
5591 }
5592
5593 void radv_GetDeviceMemoryCommitment(
5594 VkDevice device,
5595 VkDeviceMemory memory,
5596 VkDeviceSize* pCommittedMemoryInBytes)
5597 {
5598 *pCommittedMemoryInBytes = 0;
5599 }
5600
5601 VkResult radv_BindBufferMemory2(VkDevice device,
5602 uint32_t bindInfoCount,
5603 const VkBindBufferMemoryInfo *pBindInfos)
5604 {
5605 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5606 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
5607 RADV_FROM_HANDLE(radv_buffer, buffer, pBindInfos[i].buffer);
5608
5609 if (mem) {
5610 buffer->bo = mem->bo;
5611 buffer->offset = pBindInfos[i].memoryOffset;
5612 } else {
5613 buffer->bo = NULL;
5614 }
5615 }
5616 return VK_SUCCESS;
5617 }
5618
5619 VkResult radv_BindBufferMemory(
5620 VkDevice device,
5621 VkBuffer buffer,
5622 VkDeviceMemory memory,
5623 VkDeviceSize memoryOffset)
5624 {
5625 const VkBindBufferMemoryInfo info = {
5626 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
5627 .buffer = buffer,
5628 .memory = memory,
5629 .memoryOffset = memoryOffset
5630 };
5631
5632 return radv_BindBufferMemory2(device, 1, &info);
5633 }
5634
5635 VkResult radv_BindImageMemory2(VkDevice device,
5636 uint32_t bindInfoCount,
5637 const VkBindImageMemoryInfo *pBindInfos)
5638 {
5639 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5640 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
5641 RADV_FROM_HANDLE(radv_image, image, pBindInfos[i].image);
5642
5643 if (mem) {
5644 image->bo = mem->bo;
5645 image->offset = pBindInfos[i].memoryOffset;
5646 } else {
5647 image->bo = NULL;
5648 image->offset = 0;
5649 }
5650 }
5651 return VK_SUCCESS;
5652 }
5653
5654
5655 VkResult radv_BindImageMemory(
5656 VkDevice device,
5657 VkImage image,
5658 VkDeviceMemory memory,
5659 VkDeviceSize memoryOffset)
5660 {
5661 const VkBindImageMemoryInfo info = {
5662 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
5663 .image = image,
5664 .memory = memory,
5665 .memoryOffset = memoryOffset
5666 };
5667
5668 return radv_BindImageMemory2(device, 1, &info);
5669 }
5670
5671 static bool radv_sparse_bind_has_effects(const VkBindSparseInfo *info)
5672 {
5673 return info->bufferBindCount ||
5674 info->imageOpaqueBindCount ||
5675 info->imageBindCount ||
5676 info->waitSemaphoreCount ||
5677 info->signalSemaphoreCount;
5678 }
5679
5680 VkResult radv_QueueBindSparse(
5681 VkQueue _queue,
5682 uint32_t bindInfoCount,
5683 const VkBindSparseInfo* pBindInfo,
5684 VkFence fence)
5685 {
5686 RADV_FROM_HANDLE(radv_queue, queue, _queue);
5687 VkResult result;
5688 uint32_t fence_idx = 0;
5689
5690 if (fence != VK_NULL_HANDLE) {
5691 for (uint32_t i = 0; i < bindInfoCount; ++i)
5692 if (radv_sparse_bind_has_effects(pBindInfo + i))
5693 fence_idx = i;
5694 } else
5695 fence_idx = UINT32_MAX;
5696
5697 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5698 if (i != fence_idx && !radv_sparse_bind_has_effects(pBindInfo + i))
5699 continue;
5700
5701 const VkTimelineSemaphoreSubmitInfo *timeline_info =
5702 vk_find_struct_const(pBindInfo[i].pNext, TIMELINE_SEMAPHORE_SUBMIT_INFO);
5703
5704 VkResult result = radv_queue_submit(queue, &(struct radv_queue_submission) {
5705 .buffer_binds = pBindInfo[i].pBufferBinds,
5706 .buffer_bind_count = pBindInfo[i].bufferBindCount,
5707 .image_opaque_binds = pBindInfo[i].pImageOpaqueBinds,
5708 .image_opaque_bind_count = pBindInfo[i].imageOpaqueBindCount,
5709 .wait_semaphores = pBindInfo[i].pWaitSemaphores,
5710 .wait_semaphore_count = pBindInfo[i].waitSemaphoreCount,
5711 .signal_semaphores = pBindInfo[i].pSignalSemaphores,
5712 .signal_semaphore_count = pBindInfo[i].signalSemaphoreCount,
5713 .fence = i == fence_idx ? fence : VK_NULL_HANDLE,
5714 .wait_values = timeline_info ? timeline_info->pWaitSemaphoreValues : NULL,
5715 .wait_value_count = timeline_info && timeline_info->pWaitSemaphoreValues ? timeline_info->waitSemaphoreValueCount : 0,
5716 .signal_values = timeline_info ? timeline_info->pSignalSemaphoreValues : NULL,
5717 .signal_value_count = timeline_info && timeline_info->pSignalSemaphoreValues ? timeline_info->signalSemaphoreValueCount : 0,
5718 });
5719
5720 if (result != VK_SUCCESS)
5721 return result;
5722 }
5723
5724 if (fence != VK_NULL_HANDLE && !bindInfoCount) {
5725 result = radv_signal_fence(queue, fence);
5726 if (result != VK_SUCCESS)
5727 return result;
5728 }
5729
5730 return VK_SUCCESS;
5731 }
5732
5733 VkResult radv_CreateFence(
5734 VkDevice _device,
5735 const VkFenceCreateInfo* pCreateInfo,
5736 const VkAllocationCallbacks* pAllocator,
5737 VkFence* pFence)
5738 {
5739 RADV_FROM_HANDLE(radv_device, device, _device);
5740 const VkExportFenceCreateInfo *export =
5741 vk_find_struct_const(pCreateInfo->pNext, EXPORT_FENCE_CREATE_INFO);
5742 VkExternalFenceHandleTypeFlags handleTypes =
5743 export ? export->handleTypes : 0;
5744
5745 struct radv_fence *fence = vk_alloc2(&device->vk.alloc, pAllocator,
5746 sizeof(*fence), 8,
5747 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5748
5749 if (!fence)
5750 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5751
5752 vk_object_base_init(&device->vk, &fence->base, VK_OBJECT_TYPE_FENCE);
5753
5754 fence->fence_wsi = NULL;
5755 fence->temp_syncobj = 0;
5756 if (device->always_use_syncobj || handleTypes) {
5757 int ret = device->ws->create_syncobj(device->ws, &fence->syncobj);
5758 if (ret) {
5759 vk_free2(&device->vk.alloc, pAllocator, fence);
5760 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5761 }
5762 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
5763 device->ws->signal_syncobj(device->ws, fence->syncobj);
5764 }
5765 fence->fence = NULL;
5766 } else {
5767 fence->fence = device->ws->create_fence();
5768 if (!fence->fence) {
5769 vk_free2(&device->vk.alloc, pAllocator, fence);
5770 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5771 }
5772 fence->syncobj = 0;
5773 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT)
5774 device->ws->signal_fence(fence->fence);
5775 }
5776
5777 *pFence = radv_fence_to_handle(fence);
5778
5779 return VK_SUCCESS;
5780 }
5781
5782 void radv_DestroyFence(
5783 VkDevice _device,
5784 VkFence _fence,
5785 const VkAllocationCallbacks* pAllocator)
5786 {
5787 RADV_FROM_HANDLE(radv_device, device, _device);
5788 RADV_FROM_HANDLE(radv_fence, fence, _fence);
5789
5790 if (!fence)
5791 return;
5792
5793 if (fence->temp_syncobj)
5794 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
5795 if (fence->syncobj)
5796 device->ws->destroy_syncobj(device->ws, fence->syncobj);
5797 if (fence->fence)
5798 device->ws->destroy_fence(fence->fence);
5799 if (fence->fence_wsi)
5800 fence->fence_wsi->destroy(fence->fence_wsi);
5801
5802 vk_object_base_finish(&fence->base);
5803 vk_free2(&device->vk.alloc, pAllocator, fence);
5804 }
5805
5806
5807 uint64_t radv_get_current_time(void)
5808 {
5809 struct timespec tv;
5810 clock_gettime(CLOCK_MONOTONIC, &tv);
5811 return tv.tv_nsec + tv.tv_sec*1000000000ull;
5812 }
5813
5814 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
5815 {
5816 uint64_t current_time = radv_get_current_time();
5817
5818 timeout = MIN2(UINT64_MAX - current_time, timeout);
5819
5820 return current_time + timeout;
5821 }
5822
5823
5824 static bool radv_all_fences_plain_and_submitted(struct radv_device *device,
5825 uint32_t fenceCount, const VkFence *pFences)
5826 {
5827 for (uint32_t i = 0; i < fenceCount; ++i) {
5828 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5829 if (fence->fence == NULL || fence->syncobj ||
5830 fence->temp_syncobj || fence->fence_wsi ||
5831 (!device->ws->is_fence_waitable(fence->fence)))
5832 return false;
5833 }
5834 return true;
5835 }
5836
5837 static bool radv_all_fences_syncobj(uint32_t fenceCount, const VkFence *pFences)
5838 {
5839 for (uint32_t i = 0; i < fenceCount; ++i) {
5840 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5841 if (fence->syncobj == 0 && fence->temp_syncobj == 0)
5842 return false;
5843 }
5844 return true;
5845 }
5846
5847 VkResult radv_WaitForFences(
5848 VkDevice _device,
5849 uint32_t fenceCount,
5850 const VkFence* pFences,
5851 VkBool32 waitAll,
5852 uint64_t timeout)
5853 {
5854 RADV_FROM_HANDLE(radv_device, device, _device);
5855 timeout = radv_get_absolute_timeout(timeout);
5856
5857 if (device->always_use_syncobj &&
5858 radv_all_fences_syncobj(fenceCount, pFences))
5859 {
5860 uint32_t *handles = malloc(sizeof(uint32_t) * fenceCount);
5861 if (!handles)
5862 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5863
5864 for (uint32_t i = 0; i < fenceCount; ++i) {
5865 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5866 handles[i] = fence->temp_syncobj ? fence->temp_syncobj : fence->syncobj;
5867 }
5868
5869 bool success = device->ws->wait_syncobj(device->ws, handles, fenceCount, waitAll, timeout);
5870
5871 free(handles);
5872 return success ? VK_SUCCESS : VK_TIMEOUT;
5873 }
5874
5875 if (!waitAll && fenceCount > 1) {
5876 /* Not doing this by default for waitAll, due to needing to allocate twice. */
5877 if (device->physical_device->rad_info.drm_minor >= 10 && radv_all_fences_plain_and_submitted(device, fenceCount, pFences)) {
5878 uint32_t wait_count = 0;
5879 struct radeon_winsys_fence **fences = malloc(sizeof(struct radeon_winsys_fence *) * fenceCount);
5880 if (!fences)
5881 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5882
5883 for (uint32_t i = 0; i < fenceCount; ++i) {
5884 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5885
5886 if (device->ws->fence_wait(device->ws, fence->fence, false, 0)) {
5887 free(fences);
5888 return VK_SUCCESS;
5889 }
5890
5891 fences[wait_count++] = fence->fence;
5892 }
5893
5894 bool success = device->ws->fences_wait(device->ws, fences, wait_count,
5895 waitAll, timeout - radv_get_current_time());
5896
5897 free(fences);
5898 return success ? VK_SUCCESS : VK_TIMEOUT;
5899 }
5900
5901 while(radv_get_current_time() <= timeout) {
5902 for (uint32_t i = 0; i < fenceCount; ++i) {
5903 if (radv_GetFenceStatus(_device, pFences[i]) == VK_SUCCESS)
5904 return VK_SUCCESS;
5905 }
5906 }
5907 return VK_TIMEOUT;
5908 }
5909
5910 for (uint32_t i = 0; i < fenceCount; ++i) {
5911 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5912 bool expired = false;
5913
5914 if (fence->temp_syncobj) {
5915 if (!device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, timeout))
5916 return VK_TIMEOUT;
5917 continue;
5918 }
5919
5920 if (fence->syncobj) {
5921 if (!device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, timeout))
5922 return VK_TIMEOUT;
5923 continue;
5924 }
5925
5926 if (fence->fence) {
5927 if (!device->ws->is_fence_waitable(fence->fence)) {
5928 while(!device->ws->is_fence_waitable(fence->fence) &&
5929 radv_get_current_time() <= timeout)
5930 /* Do nothing */;
5931 }
5932
5933 expired = device->ws->fence_wait(device->ws,
5934 fence->fence,
5935 true, timeout);
5936 if (!expired)
5937 return VK_TIMEOUT;
5938 }
5939
5940 if (fence->fence_wsi) {
5941 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, timeout);
5942 if (result != VK_SUCCESS)
5943 return result;
5944 }
5945 }
5946
5947 return VK_SUCCESS;
5948 }
5949
5950 VkResult radv_ResetFences(VkDevice _device,
5951 uint32_t fenceCount,
5952 const VkFence *pFences)
5953 {
5954 RADV_FROM_HANDLE(radv_device, device, _device);
5955
5956 for (unsigned i = 0; i < fenceCount; ++i) {
5957 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5958 if (fence->fence)
5959 device->ws->reset_fence(fence->fence);
5960
5961 /* Per spec, we first restore the permanent payload, and then reset, so
5962 * having a temp syncobj should not skip resetting the permanent syncobj. */
5963 if (fence->temp_syncobj) {
5964 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
5965 fence->temp_syncobj = 0;
5966 }
5967
5968 if (fence->syncobj) {
5969 device->ws->reset_syncobj(device->ws, fence->syncobj);
5970 }
5971 }
5972
5973 return VK_SUCCESS;
5974 }
5975
5976 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
5977 {
5978 RADV_FROM_HANDLE(radv_device, device, _device);
5979 RADV_FROM_HANDLE(radv_fence, fence, _fence);
5980
5981 if (fence->temp_syncobj) {
5982 bool success = device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, 0);
5983 return success ? VK_SUCCESS : VK_NOT_READY;
5984 }
5985
5986 if (fence->syncobj) {
5987 bool success = device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, 0);
5988 return success ? VK_SUCCESS : VK_NOT_READY;
5989 }
5990
5991 if (fence->fence) {
5992 if (!device->ws->fence_wait(device->ws, fence->fence, false, 0))
5993 return VK_NOT_READY;
5994 }
5995 if (fence->fence_wsi) {
5996 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, 0);
5997
5998 if (result != VK_SUCCESS) {
5999 if (result == VK_TIMEOUT)
6000 return VK_NOT_READY;
6001 return result;
6002 }
6003 }
6004 return VK_SUCCESS;
6005 }
6006
6007
6008 // Queue semaphore functions
6009
6010 static void
6011 radv_create_timeline(struct radv_timeline *timeline, uint64_t value)
6012 {
6013 timeline->highest_signaled = value;
6014 timeline->highest_submitted = value;
6015 list_inithead(&timeline->points);
6016 list_inithead(&timeline->free_points);
6017 list_inithead(&timeline->waiters);
6018 pthread_mutex_init(&timeline->mutex, NULL);
6019 }
6020
6021 static void
6022 radv_destroy_timeline(struct radv_device *device,
6023 struct radv_timeline *timeline)
6024 {
6025 list_for_each_entry_safe(struct radv_timeline_point, point,
6026 &timeline->free_points, list) {
6027 list_del(&point->list);
6028 device->ws->destroy_syncobj(device->ws, point->syncobj);
6029 free(point);
6030 }
6031 list_for_each_entry_safe(struct radv_timeline_point, point,
6032 &timeline->points, list) {
6033 list_del(&point->list);
6034 device->ws->destroy_syncobj(device->ws, point->syncobj);
6035 free(point);
6036 }
6037 pthread_mutex_destroy(&timeline->mutex);
6038 }
6039
6040 static void
6041 radv_timeline_gc_locked(struct radv_device *device,
6042 struct radv_timeline *timeline)
6043 {
6044 list_for_each_entry_safe(struct radv_timeline_point, point,
6045 &timeline->points, list) {
6046 if (point->wait_count || point->value > timeline->highest_submitted)
6047 return;
6048
6049 if (device->ws->wait_syncobj(device->ws, &point->syncobj, 1, true, 0)) {
6050 timeline->highest_signaled = point->value;
6051 list_del(&point->list);
6052 list_add(&point->list, &timeline->free_points);
6053 }
6054 }
6055 }
6056
6057 static struct radv_timeline_point *
6058 radv_timeline_find_point_at_least_locked(struct radv_device *device,
6059 struct radv_timeline *timeline,
6060 uint64_t p)
6061 {
6062 radv_timeline_gc_locked(device, timeline);
6063
6064 if (p <= timeline->highest_signaled)
6065 return NULL;
6066
6067 list_for_each_entry(struct radv_timeline_point, point,
6068 &timeline->points, list) {
6069 if (point->value >= p) {
6070 ++point->wait_count;
6071 return point;
6072 }
6073 }
6074 return NULL;
6075 }
6076
6077 static struct radv_timeline_point *
6078 radv_timeline_add_point_locked(struct radv_device *device,
6079 struct radv_timeline *timeline,
6080 uint64_t p)
6081 {
6082 radv_timeline_gc_locked(device, timeline);
6083
6084 struct radv_timeline_point *ret = NULL;
6085 struct radv_timeline_point *prev = NULL;
6086
6087 if (p <= timeline->highest_signaled)
6088 return NULL;
6089
6090 list_for_each_entry(struct radv_timeline_point, point,
6091 &timeline->points, list) {
6092 if (point->value == p) {
6093 return NULL;
6094 }
6095
6096 if (point->value < p)
6097 prev = point;
6098 }
6099
6100 if (list_is_empty(&timeline->free_points)) {
6101 ret = malloc(sizeof(struct radv_timeline_point));
6102 device->ws->create_syncobj(device->ws, &ret->syncobj);
6103 } else {
6104 ret = list_first_entry(&timeline->free_points, struct radv_timeline_point, list);
6105 list_del(&ret->list);
6106
6107 device->ws->reset_syncobj(device->ws, ret->syncobj);
6108 }
6109
6110 ret->value = p;
6111 ret->wait_count = 1;
6112
6113 if (prev) {
6114 list_add(&ret->list, &prev->list);
6115 } else {
6116 list_addtail(&ret->list, &timeline->points);
6117 }
6118 return ret;
6119 }
6120
6121
6122 static VkResult
6123 radv_timeline_wait_locked(struct radv_device *device,
6124 struct radv_timeline *timeline,
6125 uint64_t value,
6126 uint64_t abs_timeout)
6127 {
6128 while(timeline->highest_submitted < value) {
6129 struct timespec abstime;
6130 timespec_from_nsec(&abstime, abs_timeout);
6131
6132 pthread_cond_timedwait(&device->timeline_cond, &timeline->mutex, &abstime);
6133
6134 if (radv_get_current_time() >= abs_timeout && timeline->highest_submitted < value)
6135 return VK_TIMEOUT;
6136 }
6137
6138 struct radv_timeline_point *point = radv_timeline_find_point_at_least_locked(device, timeline, value);
6139 if (!point)
6140 return VK_SUCCESS;
6141
6142 pthread_mutex_unlock(&timeline->mutex);
6143
6144 bool success = device->ws->wait_syncobj(device->ws, &point->syncobj, 1, true, abs_timeout);
6145
6146 pthread_mutex_lock(&timeline->mutex);
6147 point->wait_count--;
6148 return success ? VK_SUCCESS : VK_TIMEOUT;
6149 }
6150
6151 static void
6152 radv_timeline_trigger_waiters_locked(struct radv_timeline *timeline,
6153 struct list_head *processing_list)
6154 {
6155 list_for_each_entry_safe(struct radv_timeline_waiter, waiter,
6156 &timeline->waiters, list) {
6157 if (waiter->value > timeline->highest_submitted)
6158 continue;
6159
6160 if (p_atomic_dec_zero(&waiter->submission->submission_wait_count)) {
6161 list_addtail(&waiter->submission->processing_list, processing_list);
6162 }
6163 list_del(&waiter->list);
6164 }
6165 }
6166
6167 static
6168 void radv_destroy_semaphore_part(struct radv_device *device,
6169 struct radv_semaphore_part *part)
6170 {
6171 switch(part->kind) {
6172 case RADV_SEMAPHORE_NONE:
6173 break;
6174 case RADV_SEMAPHORE_WINSYS:
6175 device->ws->destroy_sem(part->ws_sem);
6176 break;
6177 case RADV_SEMAPHORE_TIMELINE:
6178 radv_destroy_timeline(device, &part->timeline);
6179 break;
6180 case RADV_SEMAPHORE_SYNCOBJ:
6181 device->ws->destroy_syncobj(device->ws, part->syncobj);
6182 break;
6183 }
6184 part->kind = RADV_SEMAPHORE_NONE;
6185 }
6186
6187 static VkSemaphoreTypeKHR
6188 radv_get_semaphore_type(const void *pNext, uint64_t *initial_value)
6189 {
6190 const VkSemaphoreTypeCreateInfo *type_info =
6191 vk_find_struct_const(pNext, SEMAPHORE_TYPE_CREATE_INFO);
6192
6193 if (!type_info)
6194 return VK_SEMAPHORE_TYPE_BINARY;
6195
6196 if (initial_value)
6197 *initial_value = type_info->initialValue;
6198 return type_info->semaphoreType;
6199 }
6200
6201 VkResult radv_CreateSemaphore(
6202 VkDevice _device,
6203 const VkSemaphoreCreateInfo* pCreateInfo,
6204 const VkAllocationCallbacks* pAllocator,
6205 VkSemaphore* pSemaphore)
6206 {
6207 RADV_FROM_HANDLE(radv_device, device, _device);
6208 const VkExportSemaphoreCreateInfo *export =
6209 vk_find_struct_const(pCreateInfo->pNext, EXPORT_SEMAPHORE_CREATE_INFO);
6210 VkExternalSemaphoreHandleTypeFlags handleTypes =
6211 export ? export->handleTypes : 0;
6212 uint64_t initial_value = 0;
6213 VkSemaphoreTypeKHR type = radv_get_semaphore_type(pCreateInfo->pNext, &initial_value);
6214
6215 struct radv_semaphore *sem = vk_alloc2(&device->vk.alloc, pAllocator,
6216 sizeof(*sem), 8,
6217 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6218 if (!sem)
6219 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6220
6221 vk_object_base_init(&device->vk, &sem->base,
6222 VK_OBJECT_TYPE_SEMAPHORE);
6223
6224 sem->temporary.kind = RADV_SEMAPHORE_NONE;
6225 sem->permanent.kind = RADV_SEMAPHORE_NONE;
6226
6227 if (type == VK_SEMAPHORE_TYPE_TIMELINE) {
6228 radv_create_timeline(&sem->permanent.timeline, initial_value);
6229 sem->permanent.kind = RADV_SEMAPHORE_TIMELINE;
6230 } else if (device->always_use_syncobj || handleTypes) {
6231 assert (device->physical_device->rad_info.has_syncobj);
6232 int ret = device->ws->create_syncobj(device->ws, &sem->permanent.syncobj);
6233 if (ret) {
6234 vk_free2(&device->vk.alloc, pAllocator, sem);
6235 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6236 }
6237 sem->permanent.kind = RADV_SEMAPHORE_SYNCOBJ;
6238 } else {
6239 sem->permanent.ws_sem = device->ws->create_sem(device->ws);
6240 if (!sem->permanent.ws_sem) {
6241 vk_free2(&device->vk.alloc, pAllocator, sem);
6242 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6243 }
6244 sem->permanent.kind = RADV_SEMAPHORE_WINSYS;
6245 }
6246
6247 *pSemaphore = radv_semaphore_to_handle(sem);
6248 return VK_SUCCESS;
6249 }
6250
6251 void radv_DestroySemaphore(
6252 VkDevice _device,
6253 VkSemaphore _semaphore,
6254 const VkAllocationCallbacks* pAllocator)
6255 {
6256 RADV_FROM_HANDLE(radv_device, device, _device);
6257 RADV_FROM_HANDLE(radv_semaphore, sem, _semaphore);
6258 if (!_semaphore)
6259 return;
6260
6261 radv_destroy_semaphore_part(device, &sem->temporary);
6262 radv_destroy_semaphore_part(device, &sem->permanent);
6263 vk_object_base_finish(&sem->base);
6264 vk_free2(&device->vk.alloc, pAllocator, sem);
6265 }
6266
6267 VkResult
6268 radv_GetSemaphoreCounterValue(VkDevice _device,
6269 VkSemaphore _semaphore,
6270 uint64_t* pValue)
6271 {
6272 RADV_FROM_HANDLE(radv_device, device, _device);
6273 RADV_FROM_HANDLE(radv_semaphore, semaphore, _semaphore);
6274
6275 struct radv_semaphore_part *part =
6276 semaphore->temporary.kind != RADV_SEMAPHORE_NONE ? &semaphore->temporary : &semaphore->permanent;
6277
6278 switch (part->kind) {
6279 case RADV_SEMAPHORE_TIMELINE: {
6280 pthread_mutex_lock(&part->timeline.mutex);
6281 radv_timeline_gc_locked(device, &part->timeline);
6282 *pValue = part->timeline.highest_signaled;
6283 pthread_mutex_unlock(&part->timeline.mutex);
6284 return VK_SUCCESS;
6285 }
6286 case RADV_SEMAPHORE_NONE:
6287 case RADV_SEMAPHORE_SYNCOBJ:
6288 case RADV_SEMAPHORE_WINSYS:
6289 unreachable("Invalid semaphore type");
6290 }
6291 unreachable("Unhandled semaphore type");
6292 }
6293
6294
6295 static VkResult
6296 radv_wait_timelines(struct radv_device *device,
6297 const VkSemaphoreWaitInfo* pWaitInfo,
6298 uint64_t abs_timeout)
6299 {
6300 if ((pWaitInfo->flags & VK_SEMAPHORE_WAIT_ANY_BIT_KHR) && pWaitInfo->semaphoreCount > 1) {
6301 for (;;) {
6302 for(uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
6303 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
6304 pthread_mutex_lock(&semaphore->permanent.timeline.mutex);
6305 VkResult result = radv_timeline_wait_locked(device, &semaphore->permanent.timeline, pWaitInfo->pValues[i], 0);
6306 pthread_mutex_unlock(&semaphore->permanent.timeline.mutex);
6307
6308 if (result == VK_SUCCESS)
6309 return VK_SUCCESS;
6310 }
6311 if (radv_get_current_time() > abs_timeout)
6312 return VK_TIMEOUT;
6313 }
6314 }
6315
6316 for(uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
6317 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
6318 pthread_mutex_lock(&semaphore->permanent.timeline.mutex);
6319 VkResult result = radv_timeline_wait_locked(device, &semaphore->permanent.timeline, pWaitInfo->pValues[i], abs_timeout);
6320 pthread_mutex_unlock(&semaphore->permanent.timeline.mutex);
6321
6322 if (result != VK_SUCCESS)
6323 return result;
6324 }
6325 return VK_SUCCESS;
6326 }
6327 VkResult
6328 radv_WaitSemaphores(VkDevice _device,
6329 const VkSemaphoreWaitInfo* pWaitInfo,
6330 uint64_t timeout)
6331 {
6332 RADV_FROM_HANDLE(radv_device, device, _device);
6333 uint64_t abs_timeout = radv_get_absolute_timeout(timeout);
6334 return radv_wait_timelines(device, pWaitInfo, abs_timeout);
6335 }
6336
6337 VkResult
6338 radv_SignalSemaphore(VkDevice _device,
6339 const VkSemaphoreSignalInfo* pSignalInfo)
6340 {
6341 RADV_FROM_HANDLE(radv_device, device, _device);
6342 RADV_FROM_HANDLE(radv_semaphore, semaphore, pSignalInfo->semaphore);
6343
6344 struct radv_semaphore_part *part =
6345 semaphore->temporary.kind != RADV_SEMAPHORE_NONE ? &semaphore->temporary : &semaphore->permanent;
6346
6347 switch(part->kind) {
6348 case RADV_SEMAPHORE_TIMELINE: {
6349 pthread_mutex_lock(&part->timeline.mutex);
6350 radv_timeline_gc_locked(device, &part->timeline);
6351 part->timeline.highest_submitted = MAX2(part->timeline.highest_submitted, pSignalInfo->value);
6352 part->timeline.highest_signaled = MAX2(part->timeline.highest_signaled, pSignalInfo->value);
6353
6354 struct list_head processing_list;
6355 list_inithead(&processing_list);
6356 radv_timeline_trigger_waiters_locked(&part->timeline, &processing_list);
6357 pthread_mutex_unlock(&part->timeline.mutex);
6358
6359 return radv_process_submissions(&processing_list);
6360 }
6361 case RADV_SEMAPHORE_NONE:
6362 case RADV_SEMAPHORE_SYNCOBJ:
6363 case RADV_SEMAPHORE_WINSYS:
6364 unreachable("Invalid semaphore type");
6365 }
6366 return VK_SUCCESS;
6367 }
6368
6369 static void radv_destroy_event(struct radv_device *device,
6370 const VkAllocationCallbacks* pAllocator,
6371 struct radv_event *event)
6372 {
6373 device->ws->buffer_destroy(event->bo);
6374 vk_object_base_finish(&event->base);
6375 vk_free2(&device->vk.alloc, pAllocator, event);
6376 }
6377
6378 VkResult radv_CreateEvent(
6379 VkDevice _device,
6380 const VkEventCreateInfo* pCreateInfo,
6381 const VkAllocationCallbacks* pAllocator,
6382 VkEvent* pEvent)
6383 {
6384 RADV_FROM_HANDLE(radv_device, device, _device);
6385 struct radv_event *event = vk_alloc2(&device->vk.alloc, pAllocator,
6386 sizeof(*event), 8,
6387 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6388
6389 if (!event)
6390 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6391
6392 vk_object_base_init(&device->vk, &event->base, VK_OBJECT_TYPE_EVENT);
6393
6394 event->bo = device->ws->buffer_create(device->ws, 8, 8,
6395 RADEON_DOMAIN_GTT,
6396 RADEON_FLAG_VA_UNCACHED | RADEON_FLAG_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING,
6397 RADV_BO_PRIORITY_FENCE);
6398 if (!event->bo) {
6399 vk_free2(&device->vk.alloc, pAllocator, event);
6400 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6401 }
6402
6403 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
6404 if (!event->map) {
6405 radv_destroy_event(device, pAllocator, event);
6406 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6407 }
6408
6409 *pEvent = radv_event_to_handle(event);
6410
6411 return VK_SUCCESS;
6412 }
6413
6414 void radv_DestroyEvent(
6415 VkDevice _device,
6416 VkEvent _event,
6417 const VkAllocationCallbacks* pAllocator)
6418 {
6419 RADV_FROM_HANDLE(radv_device, device, _device);
6420 RADV_FROM_HANDLE(radv_event, event, _event);
6421
6422 if (!event)
6423 return;
6424
6425 radv_destroy_event(device, pAllocator, event);
6426 }
6427
6428 VkResult radv_GetEventStatus(
6429 VkDevice _device,
6430 VkEvent _event)
6431 {
6432 RADV_FROM_HANDLE(radv_event, event, _event);
6433
6434 if (*event->map == 1)
6435 return VK_EVENT_SET;
6436 return VK_EVENT_RESET;
6437 }
6438
6439 VkResult radv_SetEvent(
6440 VkDevice _device,
6441 VkEvent _event)
6442 {
6443 RADV_FROM_HANDLE(radv_event, event, _event);
6444 *event->map = 1;
6445
6446 return VK_SUCCESS;
6447 }
6448
6449 VkResult radv_ResetEvent(
6450 VkDevice _device,
6451 VkEvent _event)
6452 {
6453 RADV_FROM_HANDLE(radv_event, event, _event);
6454 *event->map = 0;
6455
6456 return VK_SUCCESS;
6457 }
6458
6459 VkResult radv_CreateBuffer(
6460 VkDevice _device,
6461 const VkBufferCreateInfo* pCreateInfo,
6462 const VkAllocationCallbacks* pAllocator,
6463 VkBuffer* pBuffer)
6464 {
6465 RADV_FROM_HANDLE(radv_device, device, _device);
6466 struct radv_buffer *buffer;
6467
6468 if (pCreateInfo->size > RADV_MAX_MEMORY_ALLOCATION_SIZE)
6469 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
6470
6471 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
6472
6473 buffer = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*buffer), 8,
6474 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6475 if (buffer == NULL)
6476 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6477
6478 vk_object_base_init(&device->vk, &buffer->base, VK_OBJECT_TYPE_BUFFER);
6479
6480 buffer->size = pCreateInfo->size;
6481 buffer->usage = pCreateInfo->usage;
6482 buffer->bo = NULL;
6483 buffer->offset = 0;
6484 buffer->flags = pCreateInfo->flags;
6485
6486 buffer->shareable = vk_find_struct_const(pCreateInfo->pNext,
6487 EXTERNAL_MEMORY_BUFFER_CREATE_INFO) != NULL;
6488
6489 if (pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) {
6490 buffer->bo = device->ws->buffer_create(device->ws,
6491 align64(buffer->size, 4096),
6492 4096, 0, RADEON_FLAG_VIRTUAL,
6493 RADV_BO_PRIORITY_VIRTUAL);
6494 if (!buffer->bo) {
6495 vk_free2(&device->vk.alloc, pAllocator, buffer);
6496 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6497 }
6498 }
6499
6500 *pBuffer = radv_buffer_to_handle(buffer);
6501
6502 return VK_SUCCESS;
6503 }
6504
6505 void radv_DestroyBuffer(
6506 VkDevice _device,
6507 VkBuffer _buffer,
6508 const VkAllocationCallbacks* pAllocator)
6509 {
6510 RADV_FROM_HANDLE(radv_device, device, _device);
6511 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
6512
6513 if (!buffer)
6514 return;
6515
6516 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
6517 device->ws->buffer_destroy(buffer->bo);
6518
6519 vk_object_base_finish(&buffer->base);
6520 vk_free2(&device->vk.alloc, pAllocator, buffer);
6521 }
6522
6523 VkDeviceAddress radv_GetBufferDeviceAddress(
6524 VkDevice device,
6525 const VkBufferDeviceAddressInfo* pInfo)
6526 {
6527 RADV_FROM_HANDLE(radv_buffer, buffer, pInfo->buffer);
6528 return radv_buffer_get_va(buffer->bo) + buffer->offset;
6529 }
6530
6531
6532 uint64_t radv_GetBufferOpaqueCaptureAddress(VkDevice device,
6533 const VkBufferDeviceAddressInfo* pInfo)
6534 {
6535 return 0;
6536 }
6537
6538 uint64_t radv_GetDeviceMemoryOpaqueCaptureAddress(VkDevice device,
6539 const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo)
6540 {
6541 return 0;
6542 }
6543
6544 static inline unsigned
6545 si_tile_mode_index(const struct radv_image_plane *plane, unsigned level, bool stencil)
6546 {
6547 if (stencil)
6548 return plane->surface.u.legacy.stencil_tiling_index[level];
6549 else
6550 return plane->surface.u.legacy.tiling_index[level];
6551 }
6552
6553 static uint32_t radv_surface_max_layer_count(struct radv_image_view *iview)
6554 {
6555 return iview->type == VK_IMAGE_VIEW_TYPE_3D ? iview->extent.depth : (iview->base_layer + iview->layer_count);
6556 }
6557
6558 static uint32_t
6559 radv_init_dcc_control_reg(struct radv_device *device,
6560 struct radv_image_view *iview)
6561 {
6562 unsigned max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_256B;
6563 unsigned min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_32B;
6564 unsigned max_compressed_block_size;
6565 unsigned independent_128b_blocks;
6566 unsigned independent_64b_blocks;
6567
6568 if (!radv_dcc_enabled(iview->image, iview->base_mip))
6569 return 0;
6570
6571 if (!device->physical_device->rad_info.has_dedicated_vram) {
6572 /* amdvlk: [min-compressed-block-size] should be set to 32 for
6573 * dGPU and 64 for APU because all of our APUs to date use
6574 * DIMMs which have a request granularity size of 64B while all
6575 * other chips have a 32B request size.
6576 */
6577 min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_64B;
6578 }
6579
6580 if (device->physical_device->rad_info.chip_class >= GFX10) {
6581 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
6582 independent_64b_blocks = 0;
6583 independent_128b_blocks = 1;
6584 } else {
6585 independent_128b_blocks = 0;
6586
6587 if (iview->image->info.samples > 1) {
6588 if (iview->image->planes[0].surface.bpe == 1)
6589 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
6590 else if (iview->image->planes[0].surface.bpe == 2)
6591 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
6592 }
6593
6594 if (iview->image->usage & (VK_IMAGE_USAGE_SAMPLED_BIT |
6595 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
6596 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) {
6597 /* If this DCC image is potentially going to be used in texture
6598 * fetches, we need some special settings.
6599 */
6600 independent_64b_blocks = 1;
6601 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
6602 } else {
6603 /* MAX_UNCOMPRESSED_BLOCK_SIZE must be >=
6604 * MAX_COMPRESSED_BLOCK_SIZE. Set MAX_COMPRESSED_BLOCK_SIZE as
6605 * big as possible for better compression state.
6606 */
6607 independent_64b_blocks = 0;
6608 max_compressed_block_size = max_uncompressed_block_size;
6609 }
6610 }
6611
6612 return S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
6613 S_028C78_MAX_COMPRESSED_BLOCK_SIZE(max_compressed_block_size) |
6614 S_028C78_MIN_COMPRESSED_BLOCK_SIZE(min_compressed_block_size) |
6615 S_028C78_INDEPENDENT_64B_BLOCKS(independent_64b_blocks) |
6616 S_028C78_INDEPENDENT_128B_BLOCKS(independent_128b_blocks);
6617 }
6618
6619 void
6620 radv_initialise_color_surface(struct radv_device *device,
6621 struct radv_color_buffer_info *cb,
6622 struct radv_image_view *iview)
6623 {
6624 const struct vk_format_description *desc;
6625 unsigned ntype, format, swap, endian;
6626 unsigned blend_clamp = 0, blend_bypass = 0;
6627 uint64_t va;
6628 const struct radv_image_plane *plane = &iview->image->planes[iview->plane_id];
6629 const struct radeon_surf *surf = &plane->surface;
6630
6631 desc = vk_format_description(iview->vk_format);
6632
6633 memset(cb, 0, sizeof(*cb));
6634
6635 /* Intensity is implemented as Red, so treat it that way. */
6636 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1);
6637
6638 va = radv_buffer_get_va(iview->bo) + iview->image->offset + plane->offset;
6639
6640 cb->cb_color_base = va >> 8;
6641
6642 if (device->physical_device->rad_info.chip_class >= GFX9) {
6643 if (device->physical_device->rad_info.chip_class >= GFX10) {
6644 cb->cb_color_attrib3 |= S_028EE0_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6645 S_028EE0_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
6646 S_028EE0_CMASK_PIPE_ALIGNED(1) |
6647 S_028EE0_DCC_PIPE_ALIGNED(surf->u.gfx9.dcc.pipe_aligned);
6648 } else {
6649 struct gfx9_surf_meta_flags meta = {
6650 .rb_aligned = 1,
6651 .pipe_aligned = 1,
6652 };
6653
6654 if (surf->dcc_offset)
6655 meta = surf->u.gfx9.dcc;
6656
6657 cb->cb_color_attrib |= S_028C74_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6658 S_028C74_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
6659 S_028C74_RB_ALIGNED(meta.rb_aligned) |
6660 S_028C74_PIPE_ALIGNED(meta.pipe_aligned);
6661 cb->cb_mrt_epitch = S_0287A0_EPITCH(surf->u.gfx9.surf.epitch);
6662 }
6663
6664 cb->cb_color_base += surf->u.gfx9.surf_offset >> 8;
6665 cb->cb_color_base |= surf->tile_swizzle;
6666 } else {
6667 const struct legacy_surf_level *level_info = &surf->u.legacy.level[iview->base_mip];
6668 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
6669
6670 cb->cb_color_base += level_info->offset >> 8;
6671 if (level_info->mode == RADEON_SURF_MODE_2D)
6672 cb->cb_color_base |= surf->tile_swizzle;
6673
6674 pitch_tile_max = level_info->nblk_x / 8 - 1;
6675 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
6676 tile_mode_index = si_tile_mode_index(plane, iview->base_mip, false);
6677
6678 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
6679 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
6680 cb->cb_color_cmask_slice = surf->u.legacy.cmask_slice_tile_max;
6681
6682 cb->cb_color_attrib |= S_028C74_TILE_MODE_INDEX(tile_mode_index);
6683
6684 if (radv_image_has_fmask(iview->image)) {
6685 if (device->physical_device->rad_info.chip_class >= GFX7)
6686 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(surf->u.legacy.fmask.pitch_in_pixels / 8 - 1);
6687 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(surf->u.legacy.fmask.tiling_index);
6688 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(surf->u.legacy.fmask.slice_tile_max);
6689 } else {
6690 /* This must be set for fast clear to work without FMASK. */
6691 if (device->physical_device->rad_info.chip_class >= GFX7)
6692 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
6693 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
6694 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
6695 }
6696 }
6697
6698 /* CMASK variables */
6699 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6700 va += surf->cmask_offset;
6701 cb->cb_color_cmask = va >> 8;
6702
6703 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6704 va += surf->dcc_offset;
6705
6706 if (radv_dcc_enabled(iview->image, iview->base_mip) &&
6707 device->physical_device->rad_info.chip_class <= GFX8)
6708 va += plane->surface.u.legacy.level[iview->base_mip].dcc_offset;
6709
6710 unsigned dcc_tile_swizzle = surf->tile_swizzle;
6711 dcc_tile_swizzle &= (surf->dcc_alignment - 1) >> 8;
6712
6713 cb->cb_dcc_base = va >> 8;
6714 cb->cb_dcc_base |= dcc_tile_swizzle;
6715
6716 /* GFX10 field has the same base shift as the GFX6 field. */
6717 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
6718 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
6719 S_028C6C_SLICE_MAX_GFX10(max_slice);
6720
6721 if (iview->image->info.samples > 1) {
6722 unsigned log_samples = util_logbase2(iview->image->info.samples);
6723
6724 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
6725 S_028C74_NUM_FRAGMENTS(log_samples);
6726 }
6727
6728 if (radv_image_has_fmask(iview->image)) {
6729 va = radv_buffer_get_va(iview->bo) + iview->image->offset + surf->fmask_offset;
6730 cb->cb_color_fmask = va >> 8;
6731 cb->cb_color_fmask |= surf->fmask_tile_swizzle;
6732 } else {
6733 cb->cb_color_fmask = cb->cb_color_base;
6734 }
6735
6736 ntype = radv_translate_color_numformat(iview->vk_format,
6737 desc,
6738 vk_format_get_first_non_void_channel(iview->vk_format));
6739 format = radv_translate_colorformat(iview->vk_format);
6740 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
6741 radv_finishme("Illegal color\n");
6742 swap = radv_translate_colorswap(iview->vk_format, false);
6743 endian = radv_colorformat_endian_swap(format);
6744
6745 /* blend clamp should be set for all NORM/SRGB types */
6746 if (ntype == V_028C70_NUMBER_UNORM ||
6747 ntype == V_028C70_NUMBER_SNORM ||
6748 ntype == V_028C70_NUMBER_SRGB)
6749 blend_clamp = 1;
6750
6751 /* set blend bypass according to docs if SINT/UINT or
6752 8/24 COLOR variants */
6753 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
6754 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
6755 format == V_028C70_COLOR_X24_8_32_FLOAT) {
6756 blend_clamp = 0;
6757 blend_bypass = 1;
6758 }
6759 #if 0
6760 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
6761 (format == V_028C70_COLOR_8 ||
6762 format == V_028C70_COLOR_8_8 ||
6763 format == V_028C70_COLOR_8_8_8_8))
6764 ->color_is_int8 = true;
6765 #endif
6766 cb->cb_color_info = S_028C70_FORMAT(format) |
6767 S_028C70_COMP_SWAP(swap) |
6768 S_028C70_BLEND_CLAMP(blend_clamp) |
6769 S_028C70_BLEND_BYPASS(blend_bypass) |
6770 S_028C70_SIMPLE_FLOAT(1) |
6771 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
6772 ntype != V_028C70_NUMBER_SNORM &&
6773 ntype != V_028C70_NUMBER_SRGB &&
6774 format != V_028C70_COLOR_8_24 &&
6775 format != V_028C70_COLOR_24_8) |
6776 S_028C70_NUMBER_TYPE(ntype) |
6777 S_028C70_ENDIAN(endian);
6778 if (radv_image_has_fmask(iview->image)) {
6779 cb->cb_color_info |= S_028C70_COMPRESSION(1);
6780 if (device->physical_device->rad_info.chip_class == GFX6) {
6781 unsigned fmask_bankh = util_logbase2(surf->u.legacy.fmask.bankh);
6782 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
6783 }
6784
6785 if (radv_image_is_tc_compat_cmask(iview->image)) {
6786 /* Allow the texture block to read FMASK directly
6787 * without decompressing it. This bit must be cleared
6788 * when performing FMASK_DECOMPRESS or DCC_COMPRESS,
6789 * otherwise the operation doesn't happen.
6790 */
6791 cb->cb_color_info |= S_028C70_FMASK_COMPRESS_1FRAG_ONLY(1);
6792
6793 /* Set CMASK into a tiling format that allows the
6794 * texture block to read it.
6795 */
6796 cb->cb_color_info |= S_028C70_CMASK_ADDR_TYPE(2);
6797 }
6798 }
6799
6800 if (radv_image_has_cmask(iview->image) &&
6801 !(device->instance->debug_flags & RADV_DEBUG_NO_FAST_CLEARS))
6802 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
6803
6804 if (radv_dcc_enabled(iview->image, iview->base_mip))
6805 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
6806
6807 cb->cb_dcc_control = radv_init_dcc_control_reg(device, iview);
6808
6809 /* This must be set for fast clear to work without FMASK. */
6810 if (!radv_image_has_fmask(iview->image) &&
6811 device->physical_device->rad_info.chip_class == GFX6) {
6812 unsigned bankh = util_logbase2(surf->u.legacy.bankh);
6813 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
6814 }
6815
6816 if (device->physical_device->rad_info.chip_class >= GFX9) {
6817 const struct vk_format_description *format_desc = vk_format_description(iview->image->vk_format);
6818
6819 unsigned mip0_depth = iview->image->type == VK_IMAGE_TYPE_3D ?
6820 (iview->extent.depth - 1) : (iview->image->info.array_size - 1);
6821 unsigned width = iview->extent.width / (iview->plane_id ? format_desc->width_divisor : 1);
6822 unsigned height = iview->extent.height / (iview->plane_id ? format_desc->height_divisor : 1);
6823
6824 if (device->physical_device->rad_info.chip_class >= GFX10) {
6825 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX10(iview->base_mip);
6826
6827 cb->cb_color_attrib3 |= S_028EE0_MIP0_DEPTH(mip0_depth) |
6828 S_028EE0_RESOURCE_TYPE(surf->u.gfx9.resource_type) |
6829 S_028EE0_RESOURCE_LEVEL(1);
6830 } else {
6831 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX9(iview->base_mip);
6832 cb->cb_color_attrib |= S_028C74_MIP0_DEPTH(mip0_depth) |
6833 S_028C74_RESOURCE_TYPE(surf->u.gfx9.resource_type);
6834 }
6835
6836 cb->cb_color_attrib2 = S_028C68_MIP0_WIDTH(width - 1) |
6837 S_028C68_MIP0_HEIGHT(height - 1) |
6838 S_028C68_MAX_MIP(iview->image->info.levels - 1);
6839 }
6840 }
6841
6842 static unsigned
6843 radv_calc_decompress_on_z_planes(struct radv_device *device,
6844 struct radv_image_view *iview)
6845 {
6846 unsigned max_zplanes = 0;
6847
6848 assert(radv_image_is_tc_compat_htile(iview->image));
6849
6850 if (device->physical_device->rad_info.chip_class >= GFX9) {
6851 /* Default value for 32-bit depth surfaces. */
6852 max_zplanes = 4;
6853
6854 if (iview->vk_format == VK_FORMAT_D16_UNORM &&
6855 iview->image->info.samples > 1)
6856 max_zplanes = 2;
6857
6858 max_zplanes = max_zplanes + 1;
6859 } else {
6860 if (iview->vk_format == VK_FORMAT_D16_UNORM) {
6861 /* Do not enable Z plane compression for 16-bit depth
6862 * surfaces because isn't supported on GFX8. Only
6863 * 32-bit depth surfaces are supported by the hardware.
6864 * This allows to maintain shader compatibility and to
6865 * reduce the number of depth decompressions.
6866 */
6867 max_zplanes = 1;
6868 } else {
6869 if (iview->image->info.samples <= 1)
6870 max_zplanes = 5;
6871 else if (iview->image->info.samples <= 4)
6872 max_zplanes = 3;
6873 else
6874 max_zplanes = 2;
6875 }
6876 }
6877
6878 return max_zplanes;
6879 }
6880
6881 void
6882 radv_initialise_ds_surface(struct radv_device *device,
6883 struct radv_ds_buffer_info *ds,
6884 struct radv_image_view *iview)
6885 {
6886 unsigned level = iview->base_mip;
6887 unsigned format, stencil_format;
6888 uint64_t va, s_offs, z_offs;
6889 bool stencil_only = false;
6890 const struct radv_image_plane *plane = &iview->image->planes[0];
6891 const struct radeon_surf *surf = &plane->surface;
6892
6893 assert(vk_format_get_plane_count(iview->image->vk_format) == 1);
6894
6895 memset(ds, 0, sizeof(*ds));
6896 switch (iview->image->vk_format) {
6897 case VK_FORMAT_D24_UNORM_S8_UINT:
6898 case VK_FORMAT_X8_D24_UNORM_PACK32:
6899 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
6900 ds->offset_scale = 2.0f;
6901 break;
6902 case VK_FORMAT_D16_UNORM:
6903 case VK_FORMAT_D16_UNORM_S8_UINT:
6904 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
6905 ds->offset_scale = 4.0f;
6906 break;
6907 case VK_FORMAT_D32_SFLOAT:
6908 case VK_FORMAT_D32_SFLOAT_S8_UINT:
6909 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
6910 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
6911 ds->offset_scale = 1.0f;
6912 break;
6913 case VK_FORMAT_S8_UINT:
6914 stencil_only = true;
6915 break;
6916 default:
6917 break;
6918 }
6919
6920 format = radv_translate_dbformat(iview->image->vk_format);
6921 stencil_format = surf->has_stencil ?
6922 V_028044_STENCIL_8 : V_028044_STENCIL_INVALID;
6923
6924 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
6925 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
6926 S_028008_SLICE_MAX(max_slice);
6927 if (device->physical_device->rad_info.chip_class >= GFX10) {
6928 ds->db_depth_view |= S_028008_SLICE_START_HI(iview->base_layer >> 11) |
6929 S_028008_SLICE_MAX_HI(max_slice >> 11);
6930 }
6931
6932 ds->db_htile_data_base = 0;
6933 ds->db_htile_surface = 0;
6934
6935 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6936 s_offs = z_offs = va;
6937
6938 if (device->physical_device->rad_info.chip_class >= GFX9) {
6939 assert(surf->u.gfx9.surf_offset == 0);
6940 s_offs += surf->u.gfx9.stencil_offset;
6941
6942 ds->db_z_info = S_028038_FORMAT(format) |
6943 S_028038_NUM_SAMPLES(util_logbase2(iview->image->info.samples)) |
6944 S_028038_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6945 S_028038_MAXMIP(iview->image->info.levels - 1) |
6946 S_028038_ZRANGE_PRECISION(1);
6947 ds->db_stencil_info = S_02803C_FORMAT(stencil_format) |
6948 S_02803C_SW_MODE(surf->u.gfx9.stencil.swizzle_mode);
6949
6950 if (device->physical_device->rad_info.chip_class == GFX9) {
6951 ds->db_z_info2 = S_028068_EPITCH(surf->u.gfx9.surf.epitch);
6952 ds->db_stencil_info2 = S_02806C_EPITCH(surf->u.gfx9.stencil.epitch);
6953 }
6954
6955 ds->db_depth_view |= S_028008_MIPID(level);
6956 ds->db_depth_size = S_02801C_X_MAX(iview->image->info.width - 1) |
6957 S_02801C_Y_MAX(iview->image->info.height - 1);
6958
6959 if (radv_htile_enabled(iview->image, level)) {
6960 ds->db_z_info |= S_028038_TILE_SURFACE_ENABLE(1);
6961
6962 if (radv_image_is_tc_compat_htile(iview->image)) {
6963 unsigned max_zplanes =
6964 radv_calc_decompress_on_z_planes(device, iview);
6965
6966 ds->db_z_info |= S_028038_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
6967
6968 if (device->physical_device->rad_info.chip_class >= GFX10) {
6969 ds->db_z_info |= S_028040_ITERATE_FLUSH(1);
6970 ds->db_stencil_info |= S_028044_ITERATE_FLUSH(1);
6971 } else {
6972 ds->db_z_info |= S_028038_ITERATE_FLUSH(1);
6973 ds->db_stencil_info |= S_02803C_ITERATE_FLUSH(1);
6974 }
6975 }
6976
6977 if (!surf->has_stencil)
6978 /* Use all of the htile_buffer for depth if there's no stencil. */
6979 ds->db_stencil_info |= S_02803C_TILE_STENCIL_DISABLE(1);
6980 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
6981 surf->htile_offset;
6982 ds->db_htile_data_base = va >> 8;
6983 ds->db_htile_surface = S_028ABC_FULL_CACHE(1) |
6984 S_028ABC_PIPE_ALIGNED(1);
6985
6986 if (device->physical_device->rad_info.chip_class == GFX9) {
6987 ds->db_htile_surface |= S_028ABC_RB_ALIGNED(1);
6988 }
6989 }
6990 } else {
6991 const struct legacy_surf_level *level_info = &surf->u.legacy.level[level];
6992
6993 if (stencil_only)
6994 level_info = &surf->u.legacy.stencil_level[level];
6995
6996 z_offs += surf->u.legacy.level[level].offset;
6997 s_offs += surf->u.legacy.stencil_level[level].offset;
6998
6999 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(!radv_image_is_tc_compat_htile(iview->image));
7000 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
7001 ds->db_stencil_info = S_028044_FORMAT(stencil_format);
7002
7003 if (iview->image->info.samples > 1)
7004 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->info.samples));
7005
7006 if (device->physical_device->rad_info.chip_class >= GFX7) {
7007 struct radeon_info *info = &device->physical_device->rad_info;
7008 unsigned tiling_index = surf->u.legacy.tiling_index[level];
7009 unsigned stencil_index = surf->u.legacy.stencil_tiling_index[level];
7010 unsigned macro_index = surf->u.legacy.macro_tile_index;
7011 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
7012 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
7013 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
7014
7015 if (stencil_only)
7016 tile_mode = stencil_tile_mode;
7017
7018 ds->db_depth_info |=
7019 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
7020 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
7021 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
7022 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
7023 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
7024 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
7025 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
7026 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
7027 } else {
7028 unsigned tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, false);
7029 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
7030 tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, true);
7031 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
7032 if (stencil_only)
7033 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
7034 }
7035
7036 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
7037 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
7038 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
7039
7040 if (radv_htile_enabled(iview->image, level)) {
7041 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1);
7042
7043 if (!surf->has_stencil &&
7044 !radv_image_is_tc_compat_htile(iview->image))
7045 /* Use all of the htile_buffer for depth if there's no stencil. */
7046 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
7047
7048 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
7049 surf->htile_offset;
7050 ds->db_htile_data_base = va >> 8;
7051 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
7052
7053 if (radv_image_is_tc_compat_htile(iview->image)) {
7054 unsigned max_zplanes =
7055 radv_calc_decompress_on_z_planes(device, iview);
7056
7057 ds->db_htile_surface |= S_028ABC_TC_COMPATIBLE(1);
7058 ds->db_z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
7059 }
7060 }
7061 }
7062
7063 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
7064 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
7065 }
7066
7067 VkResult radv_CreateFramebuffer(
7068 VkDevice _device,
7069 const VkFramebufferCreateInfo* pCreateInfo,
7070 const VkAllocationCallbacks* pAllocator,
7071 VkFramebuffer* pFramebuffer)
7072 {
7073 RADV_FROM_HANDLE(radv_device, device, _device);
7074 struct radv_framebuffer *framebuffer;
7075 const VkFramebufferAttachmentsCreateInfo *imageless_create_info =
7076 vk_find_struct_const(pCreateInfo->pNext,
7077 FRAMEBUFFER_ATTACHMENTS_CREATE_INFO);
7078
7079 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
7080
7081 size_t size = sizeof(*framebuffer);
7082 if (!imageless_create_info)
7083 size += sizeof(struct radv_image_view*) * pCreateInfo->attachmentCount;
7084 framebuffer = vk_alloc2(&device->vk.alloc, pAllocator, size, 8,
7085 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
7086 if (framebuffer == NULL)
7087 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
7088
7089 vk_object_base_init(&device->vk, &framebuffer->base,
7090 VK_OBJECT_TYPE_FRAMEBUFFER);
7091
7092 framebuffer->attachment_count = pCreateInfo->attachmentCount;
7093 framebuffer->width = pCreateInfo->width;
7094 framebuffer->height = pCreateInfo->height;
7095 framebuffer->layers = pCreateInfo->layers;
7096 if (imageless_create_info) {
7097 for (unsigned i = 0; i < imageless_create_info->attachmentImageInfoCount; ++i) {
7098 const VkFramebufferAttachmentImageInfo *attachment =
7099 imageless_create_info->pAttachmentImageInfos + i;
7100 framebuffer->width = MIN2(framebuffer->width, attachment->width);
7101 framebuffer->height = MIN2(framebuffer->height, attachment->height);
7102 framebuffer->layers = MIN2(framebuffer->layers, attachment->layerCount);
7103 }
7104 } else {
7105 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
7106 VkImageView _iview = pCreateInfo->pAttachments[i];
7107 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
7108 framebuffer->attachments[i] = iview;
7109 framebuffer->width = MIN2(framebuffer->width, iview->extent.width);
7110 framebuffer->height = MIN2(framebuffer->height, iview->extent.height);
7111 framebuffer->layers = MIN2(framebuffer->layers, radv_surface_max_layer_count(iview));
7112 }
7113 }
7114
7115 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
7116 return VK_SUCCESS;
7117 }
7118
7119 void radv_DestroyFramebuffer(
7120 VkDevice _device,
7121 VkFramebuffer _fb,
7122 const VkAllocationCallbacks* pAllocator)
7123 {
7124 RADV_FROM_HANDLE(radv_device, device, _device);
7125 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
7126
7127 if (!fb)
7128 return;
7129 vk_object_base_finish(&fb->base);
7130 vk_free2(&device->vk.alloc, pAllocator, fb);
7131 }
7132
7133 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
7134 {
7135 switch (address_mode) {
7136 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
7137 return V_008F30_SQ_TEX_WRAP;
7138 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
7139 return V_008F30_SQ_TEX_MIRROR;
7140 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
7141 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
7142 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
7143 return V_008F30_SQ_TEX_CLAMP_BORDER;
7144 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
7145 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
7146 default:
7147 unreachable("illegal tex wrap mode");
7148 break;
7149 }
7150 }
7151
7152 static unsigned
7153 radv_tex_compare(VkCompareOp op)
7154 {
7155 switch (op) {
7156 case VK_COMPARE_OP_NEVER:
7157 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
7158 case VK_COMPARE_OP_LESS:
7159 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
7160 case VK_COMPARE_OP_EQUAL:
7161 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
7162 case VK_COMPARE_OP_LESS_OR_EQUAL:
7163 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
7164 case VK_COMPARE_OP_GREATER:
7165 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
7166 case VK_COMPARE_OP_NOT_EQUAL:
7167 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
7168 case VK_COMPARE_OP_GREATER_OR_EQUAL:
7169 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
7170 case VK_COMPARE_OP_ALWAYS:
7171 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
7172 default:
7173 unreachable("illegal compare mode");
7174 break;
7175 }
7176 }
7177
7178 static unsigned
7179 radv_tex_filter(VkFilter filter, unsigned max_ansio)
7180 {
7181 switch (filter) {
7182 case VK_FILTER_NEAREST:
7183 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
7184 V_008F38_SQ_TEX_XY_FILTER_POINT);
7185 case VK_FILTER_LINEAR:
7186 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
7187 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
7188 case VK_FILTER_CUBIC_IMG:
7189 default:
7190 fprintf(stderr, "illegal texture filter");
7191 return 0;
7192 }
7193 }
7194
7195 static unsigned
7196 radv_tex_mipfilter(VkSamplerMipmapMode mode)
7197 {
7198 switch (mode) {
7199 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
7200 return V_008F38_SQ_TEX_Z_FILTER_POINT;
7201 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
7202 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
7203 default:
7204 return V_008F38_SQ_TEX_Z_FILTER_NONE;
7205 }
7206 }
7207
7208 static unsigned
7209 radv_tex_bordercolor(VkBorderColor bcolor)
7210 {
7211 switch (bcolor) {
7212 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
7213 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
7214 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
7215 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
7216 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
7217 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
7218 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
7219 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
7220 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
7221 case VK_BORDER_COLOR_FLOAT_CUSTOM_EXT:
7222 case VK_BORDER_COLOR_INT_CUSTOM_EXT:
7223 return V_008F3C_SQ_TEX_BORDER_COLOR_REGISTER;
7224 default:
7225 break;
7226 }
7227 return 0;
7228 }
7229
7230 static unsigned
7231 radv_tex_aniso_filter(unsigned filter)
7232 {
7233 if (filter < 2)
7234 return 0;
7235 if (filter < 4)
7236 return 1;
7237 if (filter < 8)
7238 return 2;
7239 if (filter < 16)
7240 return 3;
7241 return 4;
7242 }
7243
7244 static unsigned
7245 radv_tex_filter_mode(VkSamplerReductionMode mode)
7246 {
7247 switch (mode) {
7248 case VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT:
7249 return V_008F30_SQ_IMG_FILTER_MODE_BLEND;
7250 case VK_SAMPLER_REDUCTION_MODE_MIN_EXT:
7251 return V_008F30_SQ_IMG_FILTER_MODE_MIN;
7252 case VK_SAMPLER_REDUCTION_MODE_MAX_EXT:
7253 return V_008F30_SQ_IMG_FILTER_MODE_MAX;
7254 default:
7255 break;
7256 }
7257 return 0;
7258 }
7259
7260 static uint32_t
7261 radv_get_max_anisotropy(struct radv_device *device,
7262 const VkSamplerCreateInfo *pCreateInfo)
7263 {
7264 if (device->force_aniso >= 0)
7265 return device->force_aniso;
7266
7267 if (pCreateInfo->anisotropyEnable &&
7268 pCreateInfo->maxAnisotropy > 1.0f)
7269 return (uint32_t)pCreateInfo->maxAnisotropy;
7270
7271 return 0;
7272 }
7273
7274 static inline int S_FIXED(float value, unsigned frac_bits)
7275 {
7276 return value * (1 << frac_bits);
7277 }
7278
7279 static uint32_t radv_register_border_color(struct radv_device *device,
7280 VkClearColorValue value)
7281 {
7282 uint32_t slot;
7283
7284 pthread_mutex_lock(&device->border_color_data.mutex);
7285
7286 for (slot = 0; slot < RADV_BORDER_COLOR_COUNT; slot++) {
7287 if (!device->border_color_data.used[slot]) {
7288 /* Copy to the GPU wrt endian-ness. */
7289 util_memcpy_cpu_to_le32(&device->border_color_data.colors_gpu_ptr[slot],
7290 &value,
7291 sizeof(VkClearColorValue));
7292
7293 device->border_color_data.used[slot] = true;
7294 break;
7295 }
7296 }
7297
7298 pthread_mutex_unlock(&device->border_color_data.mutex);
7299
7300 return slot;
7301 }
7302
7303 static void radv_unregister_border_color(struct radv_device *device,
7304 uint32_t slot)
7305 {
7306 pthread_mutex_lock(&device->border_color_data.mutex);
7307
7308 device->border_color_data.used[slot] = false;
7309
7310 pthread_mutex_unlock(&device->border_color_data.mutex);
7311 }
7312
7313 static void
7314 radv_init_sampler(struct radv_device *device,
7315 struct radv_sampler *sampler,
7316 const VkSamplerCreateInfo *pCreateInfo)
7317 {
7318 uint32_t max_aniso = radv_get_max_anisotropy(device, pCreateInfo);
7319 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
7320 bool compat_mode = device->physical_device->rad_info.chip_class == GFX8 ||
7321 device->physical_device->rad_info.chip_class == GFX9;
7322 unsigned filter_mode = V_008F30_SQ_IMG_FILTER_MODE_BLEND;
7323 unsigned depth_compare_func = V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
7324 bool trunc_coord = pCreateInfo->minFilter == VK_FILTER_NEAREST && pCreateInfo->magFilter == VK_FILTER_NEAREST;
7325 bool uses_border_color = pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
7326 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
7327 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
7328 VkBorderColor border_color = uses_border_color ? pCreateInfo->borderColor : VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
7329 uint32_t border_color_ptr;
7330
7331 const struct VkSamplerReductionModeCreateInfo *sampler_reduction =
7332 vk_find_struct_const(pCreateInfo->pNext,
7333 SAMPLER_REDUCTION_MODE_CREATE_INFO);
7334 if (sampler_reduction)
7335 filter_mode = radv_tex_filter_mode(sampler_reduction->reductionMode);
7336
7337 if (pCreateInfo->compareEnable)
7338 depth_compare_func = radv_tex_compare(pCreateInfo->compareOp);
7339
7340 sampler->border_color_slot = RADV_BORDER_COLOR_COUNT;
7341
7342 if (border_color == VK_BORDER_COLOR_FLOAT_CUSTOM_EXT || border_color == VK_BORDER_COLOR_INT_CUSTOM_EXT) {
7343 const VkSamplerCustomBorderColorCreateInfoEXT *custom_border_color =
7344 vk_find_struct_const(pCreateInfo->pNext,
7345 SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT);
7346
7347 assert(custom_border_color);
7348
7349 sampler->border_color_slot =
7350 radv_register_border_color(device, custom_border_color->customBorderColor);
7351
7352 /* Did we fail to find a slot? */
7353 if (sampler->border_color_slot == RADV_BORDER_COLOR_COUNT) {
7354 fprintf(stderr, "WARNING: no free border color slots, defaulting to TRANS_BLACK.\n");
7355 border_color = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
7356 }
7357 }
7358
7359 /* If we don't have a custom color, set the ptr to 0 */
7360 border_color_ptr = sampler->border_color_slot != RADV_BORDER_COLOR_COUNT
7361 ? sampler->border_color_slot
7362 : 0;
7363
7364 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
7365 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
7366 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
7367 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
7368 S_008F30_DEPTH_COMPARE_FUNC(depth_compare_func) |
7369 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
7370 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
7371 S_008F30_ANISO_BIAS(max_aniso_ratio) |
7372 S_008F30_DISABLE_CUBE_WRAP(0) |
7373 S_008F30_COMPAT_MODE(compat_mode) |
7374 S_008F30_FILTER_MODE(filter_mode) |
7375 S_008F30_TRUNC_COORD(trunc_coord));
7376 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
7377 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
7378 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
7379 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
7380 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
7381 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
7382 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
7383 S_008F38_MIP_POINT_PRECLAMP(0));
7384 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(border_color_ptr) |
7385 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(border_color)));
7386
7387 if (device->physical_device->rad_info.chip_class >= GFX10) {
7388 sampler->state[2] |= S_008F38_ANISO_OVERRIDE_GFX10(1);
7389 } else {
7390 sampler->state[2] |=
7391 S_008F38_DISABLE_LSB_CEIL(device->physical_device->rad_info.chip_class <= GFX8) |
7392 S_008F38_FILTER_PREC_FIX(1) |
7393 S_008F38_ANISO_OVERRIDE_GFX6(device->physical_device->rad_info.chip_class >= GFX8);
7394 }
7395 }
7396
7397 VkResult radv_CreateSampler(
7398 VkDevice _device,
7399 const VkSamplerCreateInfo* pCreateInfo,
7400 const VkAllocationCallbacks* pAllocator,
7401 VkSampler* pSampler)
7402 {
7403 RADV_FROM_HANDLE(radv_device, device, _device);
7404 struct radv_sampler *sampler;
7405
7406 const struct VkSamplerYcbcrConversionInfo *ycbcr_conversion =
7407 vk_find_struct_const(pCreateInfo->pNext,
7408 SAMPLER_YCBCR_CONVERSION_INFO);
7409
7410 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
7411
7412 sampler = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*sampler), 8,
7413 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
7414 if (!sampler)
7415 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
7416
7417 vk_object_base_init(&device->vk, &sampler->base,
7418 VK_OBJECT_TYPE_SAMPLER);
7419
7420 radv_init_sampler(device, sampler, pCreateInfo);
7421
7422 sampler->ycbcr_sampler = ycbcr_conversion ? radv_sampler_ycbcr_conversion_from_handle(ycbcr_conversion->conversion): NULL;
7423 *pSampler = radv_sampler_to_handle(sampler);
7424
7425 return VK_SUCCESS;
7426 }
7427
7428 void radv_DestroySampler(
7429 VkDevice _device,
7430 VkSampler _sampler,
7431 const VkAllocationCallbacks* pAllocator)
7432 {
7433 RADV_FROM_HANDLE(radv_device, device, _device);
7434 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
7435
7436 if (!sampler)
7437 return;
7438
7439 if (sampler->border_color_slot != RADV_BORDER_COLOR_COUNT)
7440 radv_unregister_border_color(device, sampler->border_color_slot);
7441
7442 vk_object_base_finish(&sampler->base);
7443 vk_free2(&device->vk.alloc, pAllocator, sampler);
7444 }
7445
7446 /* vk_icd.h does not declare this function, so we declare it here to
7447 * suppress Wmissing-prototypes.
7448 */
7449 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
7450 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
7451
7452 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
7453 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
7454 {
7455 /* For the full details on loader interface versioning, see
7456 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
7457 * What follows is a condensed summary, to help you navigate the large and
7458 * confusing official doc.
7459 *
7460 * - Loader interface v0 is incompatible with later versions. We don't
7461 * support it.
7462 *
7463 * - In loader interface v1:
7464 * - The first ICD entrypoint called by the loader is
7465 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
7466 * entrypoint.
7467 * - The ICD must statically expose no other Vulkan symbol unless it is
7468 * linked with -Bsymbolic.
7469 * - Each dispatchable Vulkan handle created by the ICD must be
7470 * a pointer to a struct whose first member is VK_LOADER_DATA. The
7471 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
7472 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
7473 * vkDestroySurfaceKHR(). The ICD must be capable of working with
7474 * such loader-managed surfaces.
7475 *
7476 * - Loader interface v2 differs from v1 in:
7477 * - The first ICD entrypoint called by the loader is
7478 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
7479 * statically expose this entrypoint.
7480 *
7481 * - Loader interface v3 differs from v2 in:
7482 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
7483 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
7484 * because the loader no longer does so.
7485 */
7486 *pSupportedVersion = MIN2(*pSupportedVersion, 4u);
7487 return VK_SUCCESS;
7488 }
7489
7490 VkResult radv_GetMemoryFdKHR(VkDevice _device,
7491 const VkMemoryGetFdInfoKHR *pGetFdInfo,
7492 int *pFD)
7493 {
7494 RADV_FROM_HANDLE(radv_device, device, _device);
7495 RADV_FROM_HANDLE(radv_device_memory, memory, pGetFdInfo->memory);
7496
7497 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
7498
7499 /* At the moment, we support only the below handle types. */
7500 assert(pGetFdInfo->handleType ==
7501 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
7502 pGetFdInfo->handleType ==
7503 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
7504
7505 bool ret = radv_get_memory_fd(device, memory, pFD);
7506 if (ret == false)
7507 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
7508 return VK_SUCCESS;
7509 }
7510
7511 static uint32_t radv_compute_valid_memory_types_attempt(struct radv_physical_device *dev,
7512 enum radeon_bo_domain domains,
7513 enum radeon_bo_flag flags,
7514 enum radeon_bo_flag ignore_flags)
7515 {
7516 /* Don't count GTT/CPU as relevant:
7517 *
7518 * - We're not fully consistent between the two.
7519 * - Sometimes VRAM gets VRAM|GTT.
7520 */
7521 const enum radeon_bo_domain relevant_domains = RADEON_DOMAIN_VRAM |
7522 RADEON_DOMAIN_GDS |
7523 RADEON_DOMAIN_OA;
7524 uint32_t bits = 0;
7525 for (unsigned i = 0; i < dev->memory_properties.memoryTypeCount; ++i) {
7526 if ((domains & relevant_domains) != (dev->memory_domains[i] & relevant_domains))
7527 continue;
7528
7529 if ((flags & ~ignore_flags) != (dev->memory_flags[i] & ~ignore_flags))
7530 continue;
7531
7532 bits |= 1u << i;
7533 }
7534
7535 return bits;
7536 }
7537
7538 static uint32_t radv_compute_valid_memory_types(struct radv_physical_device *dev,
7539 enum radeon_bo_domain domains,
7540 enum radeon_bo_flag flags)
7541 {
7542 enum radeon_bo_flag ignore_flags = ~(RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_GTT_WC);
7543 uint32_t bits = radv_compute_valid_memory_types_attempt(dev, domains, flags, ignore_flags);
7544
7545 if (!bits) {
7546 ignore_flags |= RADEON_FLAG_NO_CPU_ACCESS;
7547 bits = radv_compute_valid_memory_types_attempt(dev, domains, flags, ignore_flags);
7548 }
7549
7550 return bits;
7551 }
7552 VkResult radv_GetMemoryFdPropertiesKHR(VkDevice _device,
7553 VkExternalMemoryHandleTypeFlagBits handleType,
7554 int fd,
7555 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
7556 {
7557 RADV_FROM_HANDLE(radv_device, device, _device);
7558
7559 switch (handleType) {
7560 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT: {
7561 enum radeon_bo_domain domains;
7562 enum radeon_bo_flag flags;
7563 if (!device->ws->buffer_get_flags_from_fd(device->ws, fd, &domains, &flags))
7564 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7565
7566 pMemoryFdProperties->memoryTypeBits = radv_compute_valid_memory_types(device->physical_device, domains, flags);
7567 return VK_SUCCESS;
7568 }
7569 default:
7570 /* The valid usage section for this function says:
7571 *
7572 * "handleType must not be one of the handle types defined as
7573 * opaque."
7574 *
7575 * So opaque handle types fall into the default "unsupported" case.
7576 */
7577 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7578 }
7579 }
7580
7581 static VkResult radv_import_opaque_fd(struct radv_device *device,
7582 int fd,
7583 uint32_t *syncobj)
7584 {
7585 uint32_t syncobj_handle = 0;
7586 int ret = device->ws->import_syncobj(device->ws, fd, &syncobj_handle);
7587 if (ret != 0)
7588 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7589
7590 if (*syncobj)
7591 device->ws->destroy_syncobj(device->ws, *syncobj);
7592
7593 *syncobj = syncobj_handle;
7594 close(fd);
7595
7596 return VK_SUCCESS;
7597 }
7598
7599 static VkResult radv_import_sync_fd(struct radv_device *device,
7600 int fd,
7601 uint32_t *syncobj)
7602 {
7603 /* If we create a syncobj we do it locally so that if we have an error, we don't
7604 * leave a syncobj in an undetermined state in the fence. */
7605 uint32_t syncobj_handle = *syncobj;
7606 if (!syncobj_handle) {
7607 int ret = device->ws->create_syncobj(device->ws, &syncobj_handle);
7608 if (ret) {
7609 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7610 }
7611 }
7612
7613 if (fd == -1) {
7614 device->ws->signal_syncobj(device->ws, syncobj_handle);
7615 } else {
7616 int ret = device->ws->import_syncobj_from_sync_file(device->ws, syncobj_handle, fd);
7617 if (ret != 0)
7618 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7619 }
7620
7621 *syncobj = syncobj_handle;
7622 if (fd != -1)
7623 close(fd);
7624
7625 return VK_SUCCESS;
7626 }
7627
7628 VkResult radv_ImportSemaphoreFdKHR(VkDevice _device,
7629 const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo)
7630 {
7631 RADV_FROM_HANDLE(radv_device, device, _device);
7632 RADV_FROM_HANDLE(radv_semaphore, sem, pImportSemaphoreFdInfo->semaphore);
7633 VkResult result;
7634 struct radv_semaphore_part *dst = NULL;
7635
7636 if (pImportSemaphoreFdInfo->flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT) {
7637 dst = &sem->temporary;
7638 } else {
7639 dst = &sem->permanent;
7640 }
7641
7642 uint32_t syncobj = dst->kind == RADV_SEMAPHORE_SYNCOBJ ? dst->syncobj : 0;
7643
7644 switch(pImportSemaphoreFdInfo->handleType) {
7645 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
7646 result = radv_import_opaque_fd(device, pImportSemaphoreFdInfo->fd, &syncobj);
7647 break;
7648 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
7649 result = radv_import_sync_fd(device, pImportSemaphoreFdInfo->fd, &syncobj);
7650 break;
7651 default:
7652 unreachable("Unhandled semaphore handle type");
7653 }
7654
7655 if (result == VK_SUCCESS) {
7656 dst->syncobj = syncobj;
7657 dst->kind = RADV_SEMAPHORE_SYNCOBJ;
7658 }
7659
7660 return result;
7661 }
7662
7663 VkResult radv_GetSemaphoreFdKHR(VkDevice _device,
7664 const VkSemaphoreGetFdInfoKHR *pGetFdInfo,
7665 int *pFd)
7666 {
7667 RADV_FROM_HANDLE(radv_device, device, _device);
7668 RADV_FROM_HANDLE(radv_semaphore, sem, pGetFdInfo->semaphore);
7669 int ret;
7670 uint32_t syncobj_handle;
7671
7672 if (sem->temporary.kind != RADV_SEMAPHORE_NONE) {
7673 assert(sem->temporary.kind == RADV_SEMAPHORE_SYNCOBJ);
7674 syncobj_handle = sem->temporary.syncobj;
7675 } else {
7676 assert(sem->permanent.kind == RADV_SEMAPHORE_SYNCOBJ);
7677 syncobj_handle = sem->permanent.syncobj;
7678 }
7679
7680 switch(pGetFdInfo->handleType) {
7681 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
7682 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
7683 break;
7684 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
7685 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
7686 if (!ret) {
7687 if (sem->temporary.kind != RADV_SEMAPHORE_NONE) {
7688 radv_destroy_semaphore_part(device, &sem->temporary);
7689 } else {
7690 device->ws->reset_syncobj(device->ws, syncobj_handle);
7691 }
7692 }
7693 break;
7694 default:
7695 unreachable("Unhandled semaphore handle type");
7696 }
7697
7698 if (ret)
7699 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7700 return VK_SUCCESS;
7701 }
7702
7703 void radv_GetPhysicalDeviceExternalSemaphoreProperties(
7704 VkPhysicalDevice physicalDevice,
7705 const VkPhysicalDeviceExternalSemaphoreInfo *pExternalSemaphoreInfo,
7706 VkExternalSemaphoreProperties *pExternalSemaphoreProperties)
7707 {
7708 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
7709 VkSemaphoreTypeKHR type = radv_get_semaphore_type(pExternalSemaphoreInfo->pNext, NULL);
7710
7711 if (type == VK_SEMAPHORE_TYPE_TIMELINE) {
7712 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
7713 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
7714 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
7715
7716 /* Require has_syncobj_wait_for_submit for the syncobj signal ioctl introduced at virtually the same time */
7717 } else if (pdevice->rad_info.has_syncobj_wait_for_submit &&
7718 (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT ||
7719 pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT)) {
7720 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
7721 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
7722 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7723 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7724 } else if (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) {
7725 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7726 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7727 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7728 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7729 } else {
7730 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
7731 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
7732 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
7733 }
7734 }
7735
7736 VkResult radv_ImportFenceFdKHR(VkDevice _device,
7737 const VkImportFenceFdInfoKHR *pImportFenceFdInfo)
7738 {
7739 RADV_FROM_HANDLE(radv_device, device, _device);
7740 RADV_FROM_HANDLE(radv_fence, fence, pImportFenceFdInfo->fence);
7741 uint32_t *syncobj_dst = NULL;
7742
7743
7744 if (pImportFenceFdInfo->flags & VK_FENCE_IMPORT_TEMPORARY_BIT) {
7745 syncobj_dst = &fence->temp_syncobj;
7746 } else {
7747 syncobj_dst = &fence->syncobj;
7748 }
7749
7750 switch(pImportFenceFdInfo->handleType) {
7751 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
7752 return radv_import_opaque_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
7753 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
7754 return radv_import_sync_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
7755 default:
7756 unreachable("Unhandled fence handle type");
7757 }
7758 }
7759
7760 VkResult radv_GetFenceFdKHR(VkDevice _device,
7761 const VkFenceGetFdInfoKHR *pGetFdInfo,
7762 int *pFd)
7763 {
7764 RADV_FROM_HANDLE(radv_device, device, _device);
7765 RADV_FROM_HANDLE(radv_fence, fence, pGetFdInfo->fence);
7766 int ret;
7767 uint32_t syncobj_handle;
7768
7769 if (fence->temp_syncobj)
7770 syncobj_handle = fence->temp_syncobj;
7771 else
7772 syncobj_handle = fence->syncobj;
7773
7774 switch(pGetFdInfo->handleType) {
7775 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
7776 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
7777 break;
7778 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
7779 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
7780 if (!ret) {
7781 if (fence->temp_syncobj) {
7782 close (fence->temp_syncobj);
7783 fence->temp_syncobj = 0;
7784 } else {
7785 device->ws->reset_syncobj(device->ws, syncobj_handle);
7786 }
7787 }
7788 break;
7789 default:
7790 unreachable("Unhandled fence handle type");
7791 }
7792
7793 if (ret)
7794 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7795 return VK_SUCCESS;
7796 }
7797
7798 void radv_GetPhysicalDeviceExternalFenceProperties(
7799 VkPhysicalDevice physicalDevice,
7800 const VkPhysicalDeviceExternalFenceInfo *pExternalFenceInfo,
7801 VkExternalFenceProperties *pExternalFenceProperties)
7802 {
7803 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
7804
7805 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
7806 (pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT ||
7807 pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT)) {
7808 pExternalFenceProperties->exportFromImportedHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
7809 pExternalFenceProperties->compatibleHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
7810 pExternalFenceProperties->externalFenceFeatures = VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT |
7811 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7812 } else {
7813 pExternalFenceProperties->exportFromImportedHandleTypes = 0;
7814 pExternalFenceProperties->compatibleHandleTypes = 0;
7815 pExternalFenceProperties->externalFenceFeatures = 0;
7816 }
7817 }
7818
7819 VkResult
7820 radv_CreateDebugReportCallbackEXT(VkInstance _instance,
7821 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
7822 const VkAllocationCallbacks* pAllocator,
7823 VkDebugReportCallbackEXT* pCallback)
7824 {
7825 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7826 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
7827 pCreateInfo, pAllocator, &instance->alloc,
7828 pCallback);
7829 }
7830
7831 void
7832 radv_DestroyDebugReportCallbackEXT(VkInstance _instance,
7833 VkDebugReportCallbackEXT _callback,
7834 const VkAllocationCallbacks* pAllocator)
7835 {
7836 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7837 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
7838 _callback, pAllocator, &instance->alloc);
7839 }
7840
7841 void
7842 radv_DebugReportMessageEXT(VkInstance _instance,
7843 VkDebugReportFlagsEXT flags,
7844 VkDebugReportObjectTypeEXT objectType,
7845 uint64_t object,
7846 size_t location,
7847 int32_t messageCode,
7848 const char* pLayerPrefix,
7849 const char* pMessage)
7850 {
7851 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7852 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
7853 object, location, messageCode, pLayerPrefix, pMessage);
7854 }
7855
7856 void
7857 radv_GetDeviceGroupPeerMemoryFeatures(
7858 VkDevice device,
7859 uint32_t heapIndex,
7860 uint32_t localDeviceIndex,
7861 uint32_t remoteDeviceIndex,
7862 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
7863 {
7864 assert(localDeviceIndex == remoteDeviceIndex);
7865
7866 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
7867 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
7868 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
7869 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
7870 }
7871
7872 static const VkTimeDomainEXT radv_time_domains[] = {
7873 VK_TIME_DOMAIN_DEVICE_EXT,
7874 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
7875 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
7876 };
7877
7878 VkResult radv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
7879 VkPhysicalDevice physicalDevice,
7880 uint32_t *pTimeDomainCount,
7881 VkTimeDomainEXT *pTimeDomains)
7882 {
7883 int d;
7884 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
7885
7886 for (d = 0; d < ARRAY_SIZE(radv_time_domains); d++) {
7887 vk_outarray_append(&out, i) {
7888 *i = radv_time_domains[d];
7889 }
7890 }
7891
7892 return vk_outarray_status(&out);
7893 }
7894
7895 static uint64_t
7896 radv_clock_gettime(clockid_t clock_id)
7897 {
7898 struct timespec current;
7899 int ret;
7900
7901 ret = clock_gettime(clock_id, &current);
7902 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
7903 ret = clock_gettime(CLOCK_MONOTONIC, &current);
7904 if (ret < 0)
7905 return 0;
7906
7907 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
7908 }
7909
7910 VkResult radv_GetCalibratedTimestampsEXT(
7911 VkDevice _device,
7912 uint32_t timestampCount,
7913 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
7914 uint64_t *pTimestamps,
7915 uint64_t *pMaxDeviation)
7916 {
7917 RADV_FROM_HANDLE(radv_device, device, _device);
7918 uint32_t clock_crystal_freq = device->physical_device->rad_info.clock_crystal_freq;
7919 int d;
7920 uint64_t begin, end;
7921 uint64_t max_clock_period = 0;
7922
7923 begin = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
7924
7925 for (d = 0; d < timestampCount; d++) {
7926 switch (pTimestampInfos[d].timeDomain) {
7927 case VK_TIME_DOMAIN_DEVICE_EXT:
7928 pTimestamps[d] = device->ws->query_value(device->ws,
7929 RADEON_TIMESTAMP);
7930 uint64_t device_period = DIV_ROUND_UP(1000000, clock_crystal_freq);
7931 max_clock_period = MAX2(max_clock_period, device_period);
7932 break;
7933 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
7934 pTimestamps[d] = radv_clock_gettime(CLOCK_MONOTONIC);
7935 max_clock_period = MAX2(max_clock_period, 1);
7936 break;
7937
7938 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
7939 pTimestamps[d] = begin;
7940 break;
7941 default:
7942 pTimestamps[d] = 0;
7943 break;
7944 }
7945 }
7946
7947 end = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
7948
7949 /*
7950 * The maximum deviation is the sum of the interval over which we
7951 * perform the sampling and the maximum period of any sampled
7952 * clock. That's because the maximum skew between any two sampled
7953 * clock edges is when the sampled clock with the largest period is
7954 * sampled at the end of that period but right at the beginning of the
7955 * sampling interval and some other clock is sampled right at the
7956 * begining of its sampling period and right at the end of the
7957 * sampling interval. Let's assume the GPU has the longest clock
7958 * period and that the application is sampling GPU and monotonic:
7959 *
7960 * s e
7961 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
7962 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
7963 *
7964 * g
7965 * 0 1 2 3
7966 * GPU -----_____-----_____-----_____-----_____
7967 *
7968 * m
7969 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
7970 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
7971 *
7972 * Interval <----------------->
7973 * Deviation <-------------------------->
7974 *
7975 * s = read(raw) 2
7976 * g = read(GPU) 1
7977 * m = read(monotonic) 2
7978 * e = read(raw) b
7979 *
7980 * We round the sample interval up by one tick to cover sampling error
7981 * in the interval clock
7982 */
7983
7984 uint64_t sample_interval = end - begin + 1;
7985
7986 *pMaxDeviation = sample_interval + max_clock_period;
7987
7988 return VK_SUCCESS;
7989 }
7990
7991 void radv_GetPhysicalDeviceMultisamplePropertiesEXT(
7992 VkPhysicalDevice physicalDevice,
7993 VkSampleCountFlagBits samples,
7994 VkMultisamplePropertiesEXT* pMultisampleProperties)
7995 {
7996 if (samples & (VK_SAMPLE_COUNT_2_BIT |
7997 VK_SAMPLE_COUNT_4_BIT |
7998 VK_SAMPLE_COUNT_8_BIT)) {
7999 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 2, 2 };
8000 } else {
8001 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 0, 0 };
8002 }
8003 }
8004
8005 VkResult radv_CreatePrivateDataSlotEXT(
8006 VkDevice _device,
8007 const VkPrivateDataSlotCreateInfoEXT* pCreateInfo,
8008 const VkAllocationCallbacks* pAllocator,
8009 VkPrivateDataSlotEXT* pPrivateDataSlot)
8010 {
8011 RADV_FROM_HANDLE(radv_device, device, _device);
8012 return vk_private_data_slot_create(&device->vk, pCreateInfo, pAllocator,
8013 pPrivateDataSlot);
8014 }
8015
8016 void radv_DestroyPrivateDataSlotEXT(
8017 VkDevice _device,
8018 VkPrivateDataSlotEXT privateDataSlot,
8019 const VkAllocationCallbacks* pAllocator)
8020 {
8021 RADV_FROM_HANDLE(radv_device, device, _device);
8022 vk_private_data_slot_destroy(&device->vk, privateDataSlot, pAllocator);
8023 }
8024
8025 VkResult radv_SetPrivateDataEXT(
8026 VkDevice _device,
8027 VkObjectType objectType,
8028 uint64_t objectHandle,
8029 VkPrivateDataSlotEXT privateDataSlot,
8030 uint64_t data)
8031 {
8032 RADV_FROM_HANDLE(radv_device, device, _device);
8033 return vk_object_base_set_private_data(&device->vk, objectType,
8034 objectHandle, privateDataSlot,
8035 data);
8036 }
8037
8038 void radv_GetPrivateDataEXT(
8039 VkDevice _device,
8040 VkObjectType objectType,
8041 uint64_t objectHandle,
8042 VkPrivateDataSlotEXT privateDataSlot,
8043 uint64_t* pData)
8044 {
8045 RADV_FROM_HANDLE(radv_device, device, _device);
8046 vk_object_base_get_private_data(&device->vk, objectType, objectHandle,
8047 privateDataSlot, pData);
8048 }