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