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