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