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