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