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