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