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